Put .version field of build.zig.zon in my executable

Because I want my executable to feel professional AF, I would like to print “my-executable v0.1.2” at the beginning of execution, where “0.1.2” comes from the .version field of my build.zig.zon.

How can I accomplish this?

ATM, importing ZON files requires providing the result type.

It’ll be possible to simply import them after this PR is merged (the example code their demonstrates accomplishing exactly what you’re asking):

1 Like

Even today you can embedFile and find the version substring.

4 Likes

while we wait for the next release, here is one way of doing it that can give you at least major, minor, and patch:

fn getVersionFromZon() std.SemanticVersion {
    const build_zig_zon = @embedFile("build.zig.zon");
    var buffer: [10 * build_zig_zon.len]u8 = undefined;
    var fba = std.heap.FixedBufferAllocator.init(&buffer);
    const version = std.zon.parse.fromSlice(
        struct { version: []const u8 },
        fba.allocator(),
        build_zig_zon,
        null,
        .{ .ignore_unknown_fields = true },
    ) catch @panic("Invalid build.zig.zon!");
    const semantic_version = std.SemanticVersion.parse(version.version) catch @panic("Invalid version!");
    return std.SemanticVersion{
        .major = semantic_version.major,
        .minor = semantic_version.minor,
        .patch = semantic_version.patch,
        .build = null, // dont return pointers to stack memory
        .pre = null, // dont return pointers to stack memory
    };
}

2 Likes

Just as an example, here’s what the result type of @import("build.zig.zon") can look like:

3 Likes

Just to add on to the previous comments (until the next release when this becomes easier):

Put this in your build.zig:

    const zon_module = b.createModule(.{
        .root_source_file = b.path("build.zig.zon"),
    });
    exe_mod.addImport("zon_mod", zon_module);

Then the import in your code will look like this:

const zon: struct {
    name: enum { <your project name> },
    version: []const u8,
    fingerprint: u64,
    minimum_zig_version: []const u8,
    dependencies: struct {
//   zq: Dependency,
//   list all your dependencies from your build.zig.zon
    },
    paths: []const []const u8,
    const Dependency = struct { url: []const u8, hash: []const u8, lazy: bool = false };
} = @import("zon_mod");

Then you can use zon.version in your code.