zig fetch

zig fetch can downloads Zig libraries that we can use as dependencies in our code.

We’ll use the zopt library as an example. It provides a simple way to parse command-line arguments. Our main.zig uses it to check for a -f or --foo flag:

const std = @import("std");
const print = std.debug.print;
const Zopt = @import("zopt");

pub fn main(init: std.process.Init) !void {
    const arena = init.arena.allocator();
    var z: Zopt = try .init(arena, init.minimal.args);
    if (z.flag('f', "foo")) {
        print("flag set!\n", .{});
    } else {
        print("flat not set.\n", .{});
    }
}

Using zig fetch requires a build.zig file. We’ll use one similar to the one in Build System, changed make the library available to our code:

const std = @import("std");

pub fn build(b: *std.Build) void {
    const root_source_file = b.path("main.zig");

    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    // We’ll declare a dependency on zopt...
    const zopt_dep = b.dependency(
        "zopt",
        .{ .target = target, .optimize = optimize },
    );

    const exe = b.addExecutable(.{
        .name = "flags",
        .root_module = b.createModule(.{
            .root_source_file = root_source_file,
            .target = target,
            .optimize = optimize,
            // and make it available to import in Zig.
            .imports = &.{
                .{
                    .name = "zopt",
                    .module = zopt_dep.module("zopt"),
                },
            },
        }),
    });
    b.installArtifact(exe);

    const run_step = b.step("run", "Run the program");
    const run_exe = b.addRunArtifact(exe);
    run_step.dependOn(&run_exe.step);
}

Now we can use zig fetch to download the library. It stores the library under zig-pkg and creates a build.zig.zon file with metadata:

$ zig fetch --save git+https://codeberg.org/hgrsd/zopt/#v0.0.18
info: resolved ref "v0.0.18" to commit 4e55d605062cea684ea61cc03b377589b58c77a1
$ ls
build.zig  build.zig.zon  main.zig  zig-pkg

Now we’re ready to compile and run the program:

$ zig build
$ zig-out/bin/flags -f
got flag

Next example: Using C.