Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Demonstrate how to execute system (or terminal) commands in Zig #79

Open
pedropark99 opened this issue Oct 19, 2024 · 1 comment
Open

Comments

@pedropark99
Copy link
Owner

Demonstrate how to execute system (or terminal) commands in Zig

Link to Zig module: https://github.com/ziglang/zig/blob/master/lib/std/process/Child.zig

    const argv: []const []const u8 = &.{ "echo", "Hello World!" };
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();
    var v = std.process.Child.init(argv, allocator);
    const p = try v.spawnAndWait();
@pedropark99
Copy link
Owner Author

pedropark99 commented Oct 23, 2024

Ok, this is complete sacrilege, but fun nevertheless. We are using the Zig Build system to run a Cmake script. How messed up is that?

const std = @import("std");
const Allocator = std.mem.Allocator;
const Child = std.process.Child;
const Dir = std.fs.Dir;

pub fn build(b: *std.Build) !void {
    try clear_build_folder();
    try start_cmake_build();
    _ = b;
}

fn clear_build_folder() !void {
    const cwd = std.fs.cwd();
    const build_path = "./dependencies/libraw/build/";
    cwd.deleteTree(build_path) catch {
        // do nothing
    };

    try cwd.makePath(build_path);
}

fn start_cmake_build() !void {
    const cwd = std.fs.cwd();
    const build_path: ?[]const u8 = "./dependencies/libraw/build/";
    const build_dir = try cwd.openDir(build_path.?, .{});

    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    const allocator = gpa.allocator();

    var p_cmake = try create_cmake_process(allocator, build_path, build_dir);
    const cmake_result = try p_cmake.spawnAndWait();
    _ = cmake_result;
}

fn create_cmake_process(allocator: Allocator, build_path: ?[]const u8, build_dir: Dir) !Child {
    const argv_cmake: []const []const u8 = &.{ "cmake", ".." };
    var p_cmake = std.process.Child.init(argv_cmake, allocator);
    p_cmake.cwd = build_path;
    p_cmake.cwd_dir = build_dir;
    p_cmake.stdout_behavior = .Inherit;
    p_cmake.stderr_behavior = .Inherit;
    return p_cmake;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant