External program output into build

I want to embed the git version into my program. What I tried to do is:

    const get_command_output = b.addSystemCommand(&.{ "git", "rev-parse", "--short", "HEAD" });
    const git_version = get_command_output.captureStdOut();
    options.addOption([]const u8, "git_version", git_version);

but I get the following error:

build.zig:172:50: error: expected type '[]const u8', found 'Build.LazyPath'
    options.addOption([]const u8, "git_version", git_version);

There is another way to do it, get the git command to output to a file and then @embedFile to get the string value, but I think my current approach is cleaner.

Thanks

We do std.mem.trimRight(u8, b.run(&.{ "git", "rev-parse", "--verify", "HEAD" }), "\n") which means git rev-parse is run on every configure, which is not great in theory, but ok in practice.

The neat way to do this is to depend on ./git/logs/HEAD:

Otherwise, I don’t think there’s an automatic way to do what you want to do here, but it is possible by writing your own Options step.

Yeah, Zig itself also does that at configure time, so it’s officially fine :stuck_out_tongue:

Yes, that is neat, but probably more than I need right now, unless you have an easy way to add it to a build.zig file.

Thanks also for the pointer to b.run() - it works.

I finally settled on:

    const git_version = b.run(&.{ "git", "log",
                  "--pretty=format:%cI-%h", "-1" });

Which has the commit time as well as the uid, which makes it easier to find, and reason about ordering.

1 Like