Skip to content

Document using zini-pthash from build.zig #4

Description

@malcolmstill

I was playing around yesterday with getting a *.pth file generated as part of a build.zig rather than invoking zini-pthash manually. Now, that was using a custom binary for my particular application, however, if zini-pthash suffices then it is straightforward to use zini-pthash directly without a separate implementation.

Let's say you are building a program that will consume (i.e. call .get()) a *.pth file, so it depends on zini (now via build.zig.zon as per #2). Your build.zig will look something like:

    const zini = b.dependency("zini", .{ .target = target, .optimize = optimize });

    const exe = b.addExecutable(.{
        .name = "myPthConsumer",
        .root_source_file = .{ .path = "src/main.zig" },
        .target = target,
        .optimize = optimize,
    });

    exe.root_module.addImport("zini", zini.module("zini"));

Now to run zini-pthash to generate and make available the .pth at build time you can do:

    const zini = b.dependency("zini", .{ .target = target, .optimize = optimize });

    // Build our .pth file
    const zini_build_exe = zini.artifact("zini-pthash"); // Get a reference to the `b.addExecutable` for `zini-pthash`
    const builder_step = b.addRunArtifact(zini_build_exe); // Run `zini-pthash` during build
    builder_step.addArg("build");
    builder_step.addArg("-i");
    builder_step.addFileArg(.{ .path = "input.txt" });
    builder_step.addArg("-o");
    // zig will generate a path somewhere in `zig-cache` for this output:
    const pth_output = builder_step.addOutputFileArg("out.pth"); 

    const exe = b.addExecutable(.{
        .name = "myPthConsumer",
        .root_source_file = .{ .path = "src/main.zig" },
        .target = target,
        .optimize = optimize,
    });

    exe.root_module.addImport("zini", zini.module("zini"));
    // Make the building of `myPthConsumer` depend on `builder_step` and make `out.pth`
    // available to `myPthConsumer` via `@embedFile("pth")`:
    exe.root_module.addAnonymousImport("pth", .{ .root_source_file = pth_output }); 

It might be worth documenting this alongside the rest of the information under Usage in README.md, as I think this would be typical of any use of zini as a library?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions