pedropark99 / zig-book

An open, technical and introductory book for the Zig programming language
https://pedropark99.github.io/zig-book/
Other
618 stars 24 forks source link

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

Open pedropark99 opened 1 month ago

pedropark99 commented 1 month ago

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 commented 1 month ago

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;
}