diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d8fe908e..a4302b99 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -53,7 +53,7 @@ jobs: - name: Setup Zig uses: mlugg/setup-zig@v2 with: - version: 0.16.0 + version: 0.17.1 - name: Build CLI run: zig build diff --git a/.github/workflows/e2e.yml b/.github/workflows/e2e.yml index 182c53f5..e79d7294 100644 --- a/.github/workflows/e2e.yml +++ b/.github/workflows/e2e.yml @@ -66,7 +66,7 @@ jobs: - name: Setup Zig uses: mlugg/setup-zig@v2 with: - version: 0.16.0 + version: 0.17.1 - name: Build CLI run: zig build @@ -233,7 +233,7 @@ jobs: - name: Setup Zig uses: mlugg/setup-zig@v2 with: - version: 0.16.0 + version: 0.17.1 - name: Build CLI run: cd labelle-cli && zig build @@ -359,7 +359,7 @@ jobs: - name: Setup Zig uses: mlugg/setup-zig@v2 with: - version: 0.16.0 + version: 0.17.1 - name: Install system dependencies run: | @@ -693,7 +693,7 @@ jobs: - name: Setup Zig uses: mlugg/setup-zig@v2 with: - version: 0.16.0 + version: 0.17.1 # Native libs the generated raylib desktop game compiles against # (same set as the versions-integration job). diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index cfc5ccee..908c3ad1 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -39,7 +39,7 @@ jobs: path: labelle-gui - uses: mlugg/setup-zig@v2 with: - version: 0.16.0 + version: 0.17.1 - run: zig build -Doptimize=ReleaseSafe -Dcpu=baseline -Dversion=${GITHUB_REF#refs/tags/v} - uses: actions/upload-artifact@v4 with: @@ -72,7 +72,7 @@ jobs: path: labelle-gui - uses: mlugg/setup-zig@v2 with: - version: 0.16.0 + version: 0.17.1 - run: zig build -Doptimize=ReleaseSafe -Dtarget=aarch64-linux -Dversion=${GITHUB_REF#refs/tags/v} - uses: actions/upload-artifact@v4 with: @@ -105,7 +105,7 @@ jobs: path: labelle-gui - uses: mlugg/setup-zig@v2 with: - version: 0.16.0 + version: 0.17.1 - run: zig build -Doptimize=ReleaseSafe -Dtarget=x86_64-macos -Dversion=${GITHUB_REF#refs/tags/v} - uses: actions/upload-artifact@v4 with: @@ -138,7 +138,7 @@ jobs: path: labelle-gui - uses: mlugg/setup-zig@v2 with: - version: 0.16.0 + version: 0.17.1 - run: zig build -Doptimize=ReleaseSafe -Dtarget=aarch64-macos -Dversion=${GITHUB_REF#refs/tags/v} - uses: actions/upload-artifact@v4 with: @@ -171,7 +171,7 @@ jobs: path: labelle-gui - uses: mlugg/setup-zig@v2 with: - version: 0.16.0 + version: 0.17.1 - run: zig build -Doptimize=ReleaseSafe -Dcpu=baseline "-Dversion=$($env:GITHUB_REF -replace 'refs/tags/v','')" - uses: actions/upload-artifact@v4 with: diff --git a/.github/workflows/toolchain.yml b/.github/workflows/toolchain.yml index 400bf726..4cdd92a5 100644 --- a/.github/workflows/toolchain.yml +++ b/.github/workflows/toolchain.yml @@ -50,7 +50,7 @@ jobs: # provisioning below is exercised through that CLI, not this install. - uses: mlugg/setup-zig@v2 with: - version: 0.16.0 + version: 0.17.1 - name: Build CLI shell: bash diff --git a/build.zig b/build.zig index d085bcaf..fc18022e 100644 --- a/build.zig +++ b/build.zig @@ -39,9 +39,7 @@ pub fn build(b: *std.Build) void { b.installArtifact(gen_exe); const gen_run = b.addRunArtifact(gen_exe); - if (b.args) |args| { - gen_run.addArgs(args); - } + gen_run.addPassthruArgs(); const gen_step = b.step("generate", "Generate assembler from project.labelle"); gen_step.dependOn(&gen_run.step); @@ -74,12 +72,15 @@ pub fn build(b: *std.Build) void { .link_libc = true, }), }); - const child_fixture_install = b.addInstallArtifact(child_fixture, .{}); const test_fixtures = b.addOptions(); - test_fixtures.addOption([]const u8, "child_exe", b.getInstallPath(.bin, child_fixture.out_filename)); + // Zig 0.17: install paths are not known while build.zig runs (the + // configurer is a separate process from the maker), so the fixture is + // handed over as the compile step's emitted binary rather than its + // `zig-out/bin` copy. That also makes the test depend on it directly. + test_fixtures.addOptionPath("child_exe", child_fixture.getEmittedBin()); // The source tree, for the reserved-environment-name guard // (`config.zig`), which checks every `LABELLE_*` name the CLI spells. - test_fixtures.addOption([]const u8, "src_dir", b.pathFromRoot("src")); + test_fixtures.addOptionPathDirectory("src_dir", b.path("src")); cli_tests.root_module.addOptions("test_fixtures", test_fixtures); // `docs/shader-materials.md` quotes material_toolchain.zig's diagnostics // and its Windows extension lists verbatim. The toolchain tests embed the @@ -87,7 +88,6 @@ pub fn build(b: *std.Build) void { // hand (cli#389 follow-up: two stale quotes shipped in one PR). cli_tests.root_module.addAnonymousImport("shader_materials_doc", .{ .root_source_file = b.path("docs/shader-materials.md") }); const run_cli_tests = b.addRunArtifact(cli_tests); - run_cli_tests.step.dependOn(&child_fixture_install.step); const test_step = b.step("test", "Run CLI unit tests"); test_step.dependOn(&run_cli_tests.step); @@ -192,7 +192,7 @@ pub fn build(b: *std.Build) void { /// the shrinking migration allowlist (RFC #406, docs/rfc-package-commands.md /// "Enforcement"). The test walks src/, so it always runs on the HOST, from /// the repo root. Part of `zig build test`; `zig build test-guard` runs it alone. -fn addAgnosticGuard(b: *std.Build, test_step: *std.Build.Step, optimize: std.builtin.OptimizeMode) void { +fn addAgnosticGuard(b: *std.Build, test_step: *std.Build.Step, optimize: std.lang.Optimize) void { const guard_tests = b.addTest(.{ .root_module = b.createModule(.{ .root_source_file = b.path("src/agnostic_guard_test.zig"), @@ -215,7 +215,7 @@ fn addAgnosticGuard(b: *std.Build, test_step: *std.Build.Step, optimize: std.bui /// third-party code lives outside `src/`, so the agnostic guard does not /// scan upstream comments — cli#471 X2): PNG/TGA/BMP decode and /// PNG/BMP/TGA/JPEG encode, with its headers on the include path. -/// Three consumers `@cImport` those headers: `src/cli/bake.zig` (decode, +/// Three consumers call into it through `src/stb.zig`: `src/cli/bake.zig` (decode, /// for the PNG→LRGBA prebake), `src/texpack/` (decode + encode, for /// `labelle pack`), and `src/cli/screenshot_format.zig` (decode + encode, /// to re-encode a `--screenshot` capture into the requested format — diff --git a/build.zig.zon b/build.zig.zon index 48030053..0046bea7 100644 --- a/build.zig.zon +++ b/build.zig.zon @@ -1,8 +1,8 @@ .{ .fingerprint = 0xa3d95bf7b905a401, .name = .labelle_cli, - .version = "4.1.3", - .minimum_zig_version = "0.16.0", + .version = "5.0.0", + .minimum_zig_version = "0.17.1", .dependencies = .{ // Issue #217: labelle-cli is a thin driver over the standalone // labelle-assembler binary — it no longer compiles in the @@ -12,8 +12,8 @@ // schema (src/cli/project_config.zig) and its own self-contained // assembler-binary bootstrap (src/cli/asm_cache.zig). .zspec = .{ - .url = "https://github.com/apotema/zspec/archive/v0.9.1.tar.gz", - .hash = "zspec-0.9.1-jaKLbbX4AwBKANdetxzzWc3UTO0UY0lcJJzTagQHlt5K", + .url = "https://github.com/apotema/zspec/archive/v0.10.0.tar.gz", + .hash = "zspec-0.10.0-jaKLbbQlBABK3_qQJn5tDMF0wbJmepYdXFQug35tOur4", }, // `labelle pack` (#214) decodes/encodes PNG via the vendored stb // C sources in src/cli/ (stb_image*.h + stb_image_impl.c), wired diff --git a/docs/provider-local-dispatch.md b/docs/provider-local-dispatch.md index 3e797e70..fd8cfe43 100644 --- a/docs/provider-local-dispatch.md +++ b/docs/provider-local-dispatch.md @@ -83,6 +83,13 @@ system integrations; providers must support this mode. Dependencies must be prepared beforehand in the Labelle Zig package cache. Build scripts are trusted executable package code, not sandboxed processes. +The tool is built with a global compiler cache of its own +(`/zig-provider-tool-cache`), not the one game builds share: +Zig 0.17.1 panics under `--system` when a lazy dependency is absent from the +package directory while its tarball sits in the global cache, and the shared +cache holds every game's tarballs. The tool itself still runs with the shared +`ZIG_GLOBAL_CACHE_DIR`. + Zig owns caching of source, imported modules, compiler, host and options. The runner always evaluates the named install step; it does not use a shallow timestamp check to skip dependency validation. Unchanged compiled objects are diff --git a/src/agnostic_guard_test.zig b/src/agnostic_guard_test.zig index ce01f769..a39f0995 100644 --- a/src/agnostic_guard_test.zig +++ b/src/agnostic_guard_test.zig @@ -353,7 +353,7 @@ const Scan = struct { self.dirty[i] = true; return; // a platform in the name keeps the entry on its own } - const msg = try std.fmt.allocPrint(self.gpa, "src/{s}: '{s}' in path {s}", .{ path, word, finding_note }); + const msg = try self.gpa.print("src/{s}: '{s}' in path {s}", .{ path, word, finding_note }); try self.offenders.append(self.gpa, msg); } var line_no: usize = 0; @@ -366,7 +366,7 @@ const Scan = struct { self.dirty[i] = true; return; // one hit keeps the entry; no need to read on } - const msg = try std.fmt.allocPrint(self.gpa, "src/{s}:{d}: '{s}' {s}", .{ path, line_no, word, finding_note }); + const msg = try self.gpa.print("src/{s}:{d}: '{s}' {s}", .{ path, line_no, word, finding_note }); try self.offenders.append(self.gpa, msg); } } @@ -374,9 +374,9 @@ const Scan = struct { /// A symlink the guard cannot scan: always a finding, allowlist or not. fn linkFinding(self: *Scan, path: []const u8, comptime fmt: []const u8, args: anytype) !void { - const what = try std.fmt.allocPrint(self.gpa, fmt, args); + const what = try self.gpa.print(fmt, args); defer self.gpa.free(what); - const msg = try std.fmt.allocPrint(self.gpa, "src/{s}: {s} {s}", .{ path, what, finding_note }); + const msg = try self.gpa.print("src/{s}: {s} {s}", .{ path, what, finding_note }); try self.offenders.append(self.gpa, msg); } diff --git a/src/astc/astcenc_bin.zig b/src/astc/astcenc_bin.zig index 66476573..1f81346f 100644 --- a/src/astc/astcenc_bin.zig +++ b/src/astc/astcenc_bin.zig @@ -65,7 +65,7 @@ pub fn candidateNames(os: std.Target.Os.Tag, arch: std.Target.Cpu.Arch) []const /// `https://...//astcenc--.zip`. Caller owns the slice. pub fn releaseUrl(allocator: std.mem.Allocator, version: []const u8, suffix: []const u8) ![]u8 { - return std.fmt.allocPrint(allocator, "{s}/{s}/astcenc-{s}-{s}.zip", .{ release_base_override orelse RELEASE_BASE, version, version, suffix }); + return allocator.print("{s}/{s}/astcenc-{s}-{s}.zip", .{ release_base_override orelse RELEASE_BASE, version, version, suffix }); } /// `/astcenc/` — the archive extracts its own `bin/...` @@ -77,7 +77,7 @@ pub fn versionDir(allocator: std.mem.Allocator, cache_root: []const u8, version: /// First candidate binary that exists under `/bin/`, or null. Caller /// owns the returned slice. fn resolveExisting(allocator: std.mem.Allocator, ver_dir: []const u8) !?[]u8 { - for (candidateNames(builtin.os.tag, builtin.cpu.arch)) |name| { + for (candidateNames(builtin.target.os.tag, builtin.target.cpu.arch)) |name| { const p = try std.fs.path.join(allocator, &.{ ver_dir, "bin", name }); if (util.fileExists(p)) return p; allocator.free(p); @@ -104,7 +104,7 @@ pub fn ensure(allocator: std.mem.Allocator, cache_root: []const u8, version: []c if (try resolveExisting(allocator, ver_dir)) |p| return p; - const suffix = assetSuffix(builtin.os.tag, builtin.cpu.arch) catch { + const suffix = assetSuffix(builtin.target.os.tag, builtin.target.cpu.arch) catch { std.debug.print("labelle: no prebuilt astcenc for this platform; install astcenc {s} under {s}/bin/\n", .{ version, ver_dir }); return error.AstcencUnavailable; }; @@ -144,7 +144,7 @@ pub fn ensure(allocator: std.mem.Allocator, cache_root: []const u8, version: []c // extract would fail only for those users. The absolute path always hits the // libarchive-backed system tar. If SystemRoot is unset it tries the stock // C:\Windows\System32\tar.exe, then bare `tar` (`unsetRootTar`). - const extracted = if (builtin.os.tag == .windows) blk: { + const extracted = if (builtin.target.os.tag == .windows) blk: { const tar_exe = windowsTarPath(allocator) catch |err| switch (err) { // The bare-`tar` fallback exists ONLY for an unset/invalid // SystemRoot+windir (the same cases `envVarOwnedOptional` collapses @@ -172,7 +172,7 @@ pub fn ensure(allocator: std.mem.Allocator, cache_root: []const u8, version: []c defer allocator.free(staged_bin); // Executable BEFORE publishing: once the version dir exists another // labelle may run the binary straight away. - if (builtin.os.tag != .windows) { + if (builtin.target.os.tag != .windows) { if (cwd.openFile(io, staged_bin, .{})) |f| { defer f.close(io); f.setPermissions(io, .fromMode(0o755)) catch {}; @@ -224,7 +224,7 @@ fn windowsTarPath(allocator: std.mem.Allocator) ![]u8 { else => return err, }; defer allocator.free(root); - return std.fmt.allocPrint(allocator, "{s}\\System32\\tar.exe", .{root}); + return allocator.print("{s}\\System32\\tar.exe", .{root}); } /// The tar to use when SystemRoot/windir are unset: the stock @@ -291,22 +291,22 @@ const ConcurrentEnsure = struct { defer a.free(fwd); std.mem.replaceScalar(u8, fwd, '\\', '/'); return if (fwd.len > 0 and fwd[0] == '/') - std.fmt.allocPrint(a, "file://{s}", .{fwd}) + a.print("file://{s}", .{fwd}) else - std.fmt.allocPrint(a, "file:///{s}", .{fwd}); + a.print("file:///{s}", .{fwd}); } /// Zip `/bin` into `zip_path`: bsdtar on Windows/macOS, `zip` on /// Linux (GNU tar cannot write zips). Null if no tool is available. fn makeZip(a: std.mem.Allocator, src: []const u8, zip_path: []const u8) !bool { - if (builtin.os.tag == .windows) { + if (builtin.target.os.tag == .windows) { const tar_exe = windowsTarPath(a) catch try unsetRootTar(a); defer a.free(tar_exe); return runOk(a, &.{ tar_exe, "-a", "-cf", zip_path, "-C", src, "bin" }); } - if (builtin.os.tag == .macos) return runOk(a, &.{ "tar", "-a", "-cf", zip_path, "-C", src, "bin" }); + if (builtin.target.os.tag == .macos) return runOk(a, &.{ "tar", "-a", "-cf", zip_path, "-C", src, "bin" }); // `zip` stores paths relative to its cwd; -j would flatten, so cd via sh. - const script = try std.fmt.allocPrint(a, "cd '{s}' && zip -q -r '{s}' bin", .{ src, zip_path }); + const script = try a.print("cd '{s}' && zip -q -r '{s}' bin", .{ src, zip_path }); defer a.free(script); return runOk(a, &.{ "sh", "-c", script }); } @@ -330,9 +330,9 @@ test "astcenc ensure: parallel installs into one labelle home all succeed with a const io = util_io(); const cwd = std.Io.Dir.cwd(); const version = ConcurrentEnsure.version; - const suffix = assetSuffix(builtin.os.tag, builtin.cpu.arch) catch return error.SkipZigTest; + const suffix = assetSuffix(builtin.target.os.tag, builtin.target.cpu.arch) catch return error.SkipZigTest; if (!runOk(a, &.{ "curl", "--version" })) return error.SkipZigTest; - if (builtin.os.tag == .linux and !runOk(a, &.{ "unzip", "-v" })) return error.SkipZigTest; + if (builtin.target.os.tag == .linux and !runOk(a, &.{ "unzip", "-v" })) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); @@ -349,7 +349,7 @@ test "astcenc ensure: parallel installs into one labelle home all succeed with a const payload = try a.alloc(u8, 2 << 20); defer a.free(payload); for (payload, 0..) |*b, i| b.* = @truncate(i *% 2654435761 >> 5); - for (candidateNames(builtin.os.tag, builtin.cpu.arch)) |name| { + for (candidateNames(builtin.target.os.tag, builtin.target.cpu.arch)) |name| { const p = try std.fs.path.join(a, &.{ src_bin, name }); defer a.free(p); try cwd.writeFile(io, .{ .sub_path = p, .data = payload }); @@ -357,7 +357,7 @@ test "astcenc ensure: parallel installs into one labelle home all succeed with a const rel_ver = try std.fs.path.join(a, &.{ root, "rel", version }); defer a.free(rel_ver); try cwd.createDirPath(io, rel_ver); - const zip_name = try std.fmt.allocPrint(a, "astcenc-{s}-{s}.zip", .{ version, suffix }); + const zip_name = try a.print("astcenc-{s}-{s}.zip", .{ version, suffix }); defer a.free(zip_name); const zip_path = try std.fs.path.join(a, &.{ rel_ver, zip_name }); defer a.free(zip_path); @@ -381,7 +381,7 @@ test "astcenc ensure: parallel installs into one labelle home all succeed with a // Every candidate is complete (no truncated binary from a racing extract). const ver_dir = try versionDir(a, home, version); defer a.free(ver_dir); - for (candidateNames(builtin.os.tag, builtin.cpu.arch)) |name| { + for (candidateNames(builtin.target.os.tag, builtin.target.cpu.arch)) |name| { const p = try std.fs.path.join(a, &.{ ver_dir, "bin", name }); defer a.free(p); const got = try cwd.readFileAlloc(io, p, a, .limited(8 << 20)); diff --git a/src/astc/capabilities.zig b/src/astc/capabilities.zig index f5e082a1..cd754834 100644 --- a/src/astc/capabilities.zig +++ b/src/astc/capabilities.zig @@ -26,15 +26,15 @@ pub fn parse(gpa: std.mem.Allocator, bytes: []const u8, target: []const u8) !Sel var arena = std.heap.ArenaAllocator.init(gpa); defer arena.deinit(); const a = arena.allocator(); - const source = try a.dupeZ(u8, bytes); + const source = try a.dupeSentinel(u8, bytes, 0); defer a.free(source); - var ast = try std.zig.Ast.parse(a, source, .zon); + var ast = try std.zig.Ast.parse(a, source, .{ .mode = .zon }); defer ast.deinit(a); if (ast.errors.len != 0) return error.InvalidTextureCapabilities; var zoir = try std.zig.ZonGen.generate(a, ast, .{ .parse_str_lits = false }); defer zoir.deinit(a); if (zoir.hasCompileErrors()) return error.InvalidTextureCapabilities; - const root = switch (std.zig.Zoir.Node.Index.root.get(zoir)) { + const root = switch (std.zig.Zoir.Node.Index.root.get(&zoir)) { .struct_literal => |fields| fields, .empty_literal => return .{}, else => return error.InvalidTextureCapabilities, @@ -42,25 +42,31 @@ pub fn parse(gpa: std.mem.Allocator, bytes: []const u8, target: []const u8) !Sel var result: Selection = .{}; var seen = false; for (root.names, 0..) |name, i| { - if (!std.mem.eql(u8, name.get(zoir), "texture_caps")) continue; + if (!std.mem.eql(u8, name.get(&zoir), "texture_caps")) continue; if (seen) return error.InvalidTextureCapabilities; seen = true; - const targets = switch (root.vals.at(@intCast(i)).get(zoir)) { + const targets = switch (root.vals.at(@intCast(i)).get(&zoir)) { .struct_literal => |fields| fields, .empty_literal => return result, else => return error.InvalidTextureCapabilities, }; for (targets.names, 0..) |key, j| { - const target_name = key.get(zoir); + const target_name = key.get(&zoir); for (targets.names[0..j]) |previous| { - if (std.mem.eql(u8, previous.get(zoir), target_name)) return error.InvalidTextureCapabilities; + if (std.mem.eql(u8, previous.get(&zoir), target_name)) return error.InvalidTextureCapabilities; } - const value = std.zon.parse.fromZoirNodeAlloc(Target, a, ast, zoir, targets.vals.at(@intCast(j)), null, .{}) catch |err| { + var diagnostics: std.zon.parse.Diagnostics = undefined; + const value = std.zon.parse.fromZoir(Target, .{ + .arena = a, + .ast = &ast, + .zoir = &zoir, + .node = targets.vals.at(@intCast(j)), + .diagnostics = &diagnostics, + }) catch |err| { if (err == error.OutOfMemory) return err; return error.InvalidTextureCapabilities; }; - defer std.zon.parse.free(a, value); - var caps: convert.BackendCaps = .{ .blocks = .initEmpty(), .default_block = value.astc.default_block }; + var caps: convert.BackendCaps = .{ .blocks = .empty, .default_block = value.astc.default_block }; for (value.astc.blocks) |block| { if (caps.blocks.contains(block)) return error.InvalidTextureCapabilities; caps.blocks.insert(block); diff --git a/src/astc/cmd.zig b/src/astc/cmd.zig index 034f74d1..d7d445b2 100644 --- a/src/astc/cmd.zig +++ b/src/astc/cmd.zig @@ -430,10 +430,8 @@ fn readDeclaredResources( defer allocator.free(path); const raw = std.Io.Dir.cwd().readFileAlloc(config.globalIo(), path, allocator, .limited(1024 * 1024)) catch return null; defer allocator.free(raw); - const source = allocator.dupeZ(u8, raw) catch return null; - const parsed = std.zon.parse.fromSliceAlloc(ManifestResources, allocator, source, null, .{ - .ignore_unknown_fields = true, - }) catch { + const source = allocator.dupeSentinel(u8, raw, 0) catch return null; + const parsed = util.parseZon(ManifestResources, allocator, source, .{ .ignore_unknown_fields = true }) catch { std.debug.print("labelle astc: could not parse {s} — skipping its resources\n", .{path}); return null; }; @@ -625,9 +623,9 @@ fn existingOutputInodeKey(allocator: std.mem.Allocator, io: std.Io, path: []cons const cwd = std.Io.Dir.cwd(); const file = cwd.openFile(io, path, .{}) catch return null; defer file.close(io); - const identity = if (builtin.os.tag == .windows) + const identity = if (builtin.target.os.tag == .windows) windowsFileIdentity(file.handle) catch return null - else if (comptime usesPosixFileIdentity(builtin.os.tag)) + else if (comptime usesPosixFileIdentity(builtin.target.os.tag)) posixFileIdentity(file.handle) catch return null else return null; @@ -639,11 +637,11 @@ fn existingOutputInodeKey(allocator: std.mem.Allocator, io: std.Io, path: []cons /// still get deterministic collision behavior. fn sourceIdentityKey(allocator: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 { if (existingOutputInodeKey(allocator, io, path)) |key| return key; - return std.fmt.allocPrint(allocator, "@path:{s}", .{path}); + return allocator.print("@path:{s}", .{path}); } fn fileIdentityKey(allocator: std.mem.Allocator, identity: FileIdentity) ?[]u8 { - return std.fmt.allocPrint(allocator, "@file:{d}:{d}", .{ identity.volume, identity.inode }) catch null; + return allocator.print("@file:{d}:{d}", .{ identity.volume, identity.inode }) catch null; } /// Hosts whose file identity comes from `posixFileIdentity`: every Darwin @@ -685,7 +683,7 @@ test "usesPosixFileIdentity keeps the historical host set" { } fn posixFileIdentity(handle: std.posix.fd_t) !FileIdentity { - if (builtin.os.tag == .linux) { + if (builtin.target.os.tag == .linux) { var stat: std.os.linux.Statx = undefined; const result = std.c.statx( handle, @@ -862,9 +860,9 @@ fn measureDirCaseInsensitive(io: std.Io, dir: *const std.Io.Dir, tag: []const u8 io.random(&random_buf); const suffix = std.mem.readInt(u64, &random_buf, .little) ^ case_probe_serial.fetchAdd(1, .monotonic); var upper_buf: [std.fs.max_name_bytes]u8 = undefined; - const upper = std.fmt.bufPrint(&upper_buf, "{s}-{x}-UPPER", .{ tag, suffix }) catch return false; + const upper = std.mem.print(&upper_buf, "{s}-{x}-UPPER", .{ tag, suffix }) catch return false; var lower_buf: [std.fs.max_name_bytes]u8 = undefined; - const lower = std.fmt.bufPrint(&lower_buf, "{s}-{x}-upper", .{ tag, suffix }) catch return false; + const lower = std.mem.print(&lower_buf, "{s}-{x}-upper", .{ tag, suffix }) catch return false; const upper_file = dir.createFile(io, upper, .{ .exclusive = true }) catch |err| switch (err) { error.PathAlreadyExists => continue, @@ -1018,7 +1016,7 @@ test "file identity key distinguishes devices with reused inode numbers" { } test "linux file identity rejects statx results without an inode bit" { - if (builtin.os.tag != .linux) return error.SkipZigTest; + if (builtin.target.os.tag != .linux) return error.SkipZigTest; var stat: std.os.linux.Statx = undefined; stat.mask = .{}; stat.dev_major = 1; @@ -1033,7 +1031,7 @@ test "linux file identity rejects statx results without an inode bit" { } test "conflictingBlockPin: symlinked texture dirs share one output" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var tmp = std.testing.tmpDir(.{}); @@ -1054,7 +1052,7 @@ test "conflictingBlockPin: symlinked texture dirs share one output" { } test "conflictingBlockPin: source symlink keeps its declared output name" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var tmp = std.testing.tmpDir(.{}); @@ -1073,7 +1071,7 @@ test "conflictingBlockPin: source symlink keeps its declared output name" { } test "conflictingBlockPin: existing .astc reached through a symlink alias clashes" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var tmp = std.testing.tmpDir(.{}); @@ -1095,7 +1093,7 @@ test "conflictingBlockPin: existing .astc reached through a symlink alias clashe } test "conflictingBlockPin: hardlinked existing outputs share one inode key" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var tmp = std.testing.tmpDir(.{}); @@ -1119,7 +1117,7 @@ test "conflictingBlockPin: hardlinked existing outputs share one inode key" { } test "conflictingBlockPin: distinct sources sharing an output clash at the same block" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var tmp = std.testing.tmpDir(.{}); @@ -1144,7 +1142,7 @@ test "conflictingBlockPin: distinct sources sharing an output clash at the same } test "conflictingBlockPin: not-yet-created outputs through symlink aliases clash" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var tmp = std.testing.tmpDir(.{}); @@ -1165,7 +1163,7 @@ test "conflictingBlockPin: not-yet-created outputs through symlink aliases clash } test "conflictingBlockPin: matching blocks through symlink aliases are fine" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var tmp = std.testing.tmpDir(.{}); @@ -1316,7 +1314,7 @@ test "conflictingBlockPin: case aliases with matching blocks are fine on case-in } test "conflictingBlockPin: multi-level missing outputs through symlink aliases clash" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var tmp = std.testing.tmpDir(.{}); @@ -1337,7 +1335,7 @@ test "conflictingBlockPin: multi-level missing outputs through symlink aliases c } test "nearestExistingRealPath: walks past missing dirs and resolves symlink aliases" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var tmp = std.testing.tmpDir(.{}); @@ -1384,7 +1382,7 @@ test "conflictingBlockPin: injected case-insensitive probe clashes case aliases" } test "conflictingBlockPin: dangling output symlink aliases share one key" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var tmp = std.testing.tmpDir(.{}); @@ -1407,7 +1405,7 @@ test "conflictingBlockPin: dangling output symlink aliases share one key" { } test "conflictingBlockPin: existing output symlink aliases share one inode key" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var tmp = std.testing.tmpDir(.{}); @@ -1588,7 +1586,7 @@ test "a current sibling survives a failed-encoder run; a stale one does not" { test "an undeletable stale sibling is a fatal error, not a silent PNG fallback" { // POSIX-only: a read-only directory is how we make the unlink fail. Root // ignores directory permissions, so the premise can't be staged there. - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; if (std.c.getuid() == 0) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); @@ -1622,4 +1620,4 @@ test "an undeletable stale sibling is a fatal error, not a silent PNG fallback" const test_narrow_caps: convert.BackendCaps = .{}; const test_wide_caps: convert.BackendCaps = .{ .blocks = .initMany(&.{ .@"4x4", .@"8x8" }), .default_block = .@"8x8" }; -const test_full_caps: convert.BackendCaps = .{ .blocks = .initFull(), .default_block = .@"8x8" }; +const test_full_caps: convert.BackendCaps = .{ .blocks = .full, .default_block = .@"8x8" }; diff --git a/src/astc/convert.zig b/src/astc/convert.zig index 3ddfe908..f81991d6 100644 --- a/src/astc/convert.zig +++ b/src/astc/convert.zig @@ -115,7 +115,7 @@ pub fn outputPath(allocator: std.mem.Allocator, src: []const u8) ![]u8 { src[0 .. src.len - ".png".len] else src; - return std.fmt.allocPrint(allocator, "{s}.astc", .{stem}); + return allocator.print("{s}.astc", .{stem}); } /// Build the astcenc argv: `astcenc -cs 8x8 -fast`. diff --git a/src/cli.zig b/src/cli.zig index f11b54f1..34556792 100644 --- a/src/cli.zig +++ b/src/cli.zig @@ -151,7 +151,7 @@ fn handleToolchainCmd(allocator: std.mem.Allocator, cmd_args: []const []const u8 const usage_error: u8 = 2; pub fn main(proc_init: std.process.Init) !u8 { - var gpa = std.heap.DebugAllocator(.{}){}; + var gpa: std.heap.SafeAllocator = .init(std.heap.page_allocator, .{}); defer _ = gpa.deinit(); const allocator = gpa.allocator(); diff --git a/src/cli/app_icon.zig b/src/cli/app_icon.zig index 9368c1dd..4b2886a5 100644 --- a/src/cli/app_icon.zig +++ b/src/cli/app_icon.zig @@ -41,10 +41,7 @@ const std = @import("std"); const config = @import("config.zig"); -const c = @cImport({ - @cInclude("stb_image.h"); - @cInclude("stb_image_write.h"); -}); +const c = @import("../stb.zig"); /// Filename the assembler writes its bundled default icon to, relative /// to the generated target dir. Contract with labelle-assembler diff --git a/src/cli/args.zig b/src/cli/args.zig index 5b949f9b..49795667 100644 --- a/src/cli/args.zig +++ b/src/cli/args.zig @@ -407,7 +407,7 @@ fn dockerBuildRefused(docker_build: bool, target: ?[]const u8, host_os: std.Targ } fn refuseDockerBuild(cmd_name: []const u8, docker_build: bool, target: ?[]const u8) bool { - if (!dockerBuildRefused(docker_build, target, builtin.os.tag)) return false; + if (!dockerBuildRefused(docker_build, target, builtin.target.os.tag)) return false; std.debug.print("labelle {s}: --docker does not cross-compile for macOS (target {s}); pick a Linux or Windows --target, or build natively on a Mac\n", .{ cmd_name, target orelse "defaults to this Mac" }); return true; } diff --git a/src/cli/asm_cache.zig b/src/cli/asm_cache.zig index 2555e131..d0d22ef4 100644 --- a/src/cli/asm_cache.zig +++ b/src/cli/asm_cache.zig @@ -77,7 +77,7 @@ pub fn getCacheRoot(allocator: std.mem.Allocator) ![]const u8 { return std.fs.path.resolve(allocator, &.{ cwd, home }); } - const home_env = if (builtin.os.tag == .windows) "USERPROFILE" else "HOME"; + const home_env = if (builtin.target.os.tag == .windows) "USERPROFILE" else "HOME"; const home_dir = envLookup(allocator, home_env) orelse { std.debug.print("labelle: could not determine home directory ({s})\n", .{home_env}); return error.NoHomeDirectory; diff --git a/src/cli/assembler.zig b/src/cli/assembler.zig index 1f894bbc..96fe86fa 100644 --- a/src/cli/assembler.zig +++ b/src/cli/assembler.zig @@ -25,7 +25,10 @@ const std = @import("std"); /// project the current assembler line refuses to build). The /// released-path smoke test in ci.yml (init with NO local overrides → /// generate → build) fails if this constant rots again. -pub const DEFAULT_ASSEMBLER_VERSION = "0.120.0"; +/// +/// 0.128.0 is the first assembler release built with, and generating for, +/// Zig 0.17.1 (core 3 / engine 5 / gfx 3); it pairs with `versions.zon`. +pub const DEFAULT_ASSEMBLER_VERSION = "0.128.0"; const builtin = @import("builtin"); const asm_cache = @import("asm_cache.zig"); const compatibility = @import("compatibility.zig"); @@ -139,29 +142,29 @@ fn resolveLocalAssembler(allocator: std.mem.Allocator, rel_path: []const u8, pro /// Platform/arch names used in the release URL. fn osName() error{UnsupportedPlatform}![]const u8 { - return switch (builtin.os.tag) { + return switch (builtin.target.os.tag) { .macos => "macos", .linux => "linux", .windows => "windows", else => { - std.debug.print("labelle: unsupported OS for assembler download: {s}\n", .{@tagName(builtin.os.tag)}); + std.debug.print("labelle: unsupported OS for assembler download: {s}\n", .{@tagName(builtin.target.os.tag)}); return error.UnsupportedPlatform; }, }; } fn archName() error{UnsupportedPlatform}![]const u8 { - return switch (builtin.cpu.arch) { + return switch (builtin.target.cpu.arch) { .aarch64 => "aarch64", .x86_64 => "x86_64", else => { - std.debug.print("labelle: unsupported architecture for assembler download: {s}\n", .{@tagName(builtin.cpu.arch)}); + std.debug.print("labelle: unsupported architecture for assembler download: {s}\n", .{@tagName(builtin.target.cpu.arch)}); return error.UnsupportedPlatform; }, }; } -const exe_suffix = if (builtin.os.tag == .windows) ".exe" else ""; +const exe_suffix = if (builtin.target.os.tag == .windows) ".exe" else ""; const exe_name = "labelle-assembler" ++ exe_suffix; /// Look up `asset`'s expected digest in a `SHA256SUMS` body. @@ -224,13 +227,13 @@ fn verifyAgainstManifest( path: []const u8, ) !?[64]u8 { const io = config.globalIo(); - const manifest_url = try std.fmt.allocPrint(allocator, "{s}/v{s}/SHA256SUMS", .{ + const manifest_url = try allocator.print("{s}/v{s}/SHA256SUMS", .{ releaseBase(), version, }); defer allocator.free(manifest_url); - const manifest_path = try std.fmt.allocPrint(allocator, "{s}.sha256sums", .{path}); + const manifest_path = try allocator.print("{s}.sha256sums", .{path}); defer allocator.free(manifest_path); defer std.Io.Dir.cwd().deleteFile(io, manifest_path) catch {}; @@ -324,12 +327,12 @@ fn verifyAgainstManifest( pub fn downloadAssembler(allocator: std.mem.Allocator, version: []const u8, dest_path: []const u8) !void { const io = config.globalIo(); const cwd = std.Io.Dir.cwd(); - const asset = try std.fmt.allocPrint(allocator, "labelle-assembler-{s}-{s}", .{ + const asset = try allocator.print("labelle-assembler-{s}-{s}", .{ try osName(), try archName(), }); defer allocator.free(asset); - const url = try std.fmt.allocPrint(allocator, "{s}/v{s}/{s}", .{ + const url = try allocator.print("{s}/v{s}/{s}", .{ releaseBase(), version, asset, @@ -401,7 +404,7 @@ pub fn downloadAssembler(allocator: std.mem.Allocator, version: []const u8, dest // Executable BEFORE it is published: the moment `dest_path` exists a // concurrent labelle may run it, so it must never appear without +x. - if (builtin.os.tag != .windows) { + if (builtin.target.os.tag != .windows) { if (cwd.openFile(io, part_path, .{})) |file| { defer file.close(io); file.setPermissions(io, .fromMode(0o755)) catch |err| { @@ -613,10 +616,9 @@ fn missingLocalAssemblerMessage( const anchored_elsewhere = !std.fs.path.isAbsolute(written) and if (project_root) |r| !std.mem.eql(u8, r, project_dir) else false; if (!anchored_elsewhere) { - return std.fmt.allocPrint(allocator, "labelle: local assembler path '{s}' does not exist: {any}", .{ resolved, err }); + return allocator.print("labelle: local assembler path '{s}' does not exist: {any}", .{ resolved, err }); } - return std.fmt.allocPrint( - allocator, + return allocator.print( "labelle: local assembler path '{s}' does not exist (resolved to '{s}'): {any}\n" ++ " Relative local: paths resolve from the main checkout\n" ++ " ('{s}'), not this worktree ('{s}').\n" ++ @@ -767,7 +769,7 @@ pub const MissingLocalAssemblerMessage = struct { defer alloc.free(main_abs); const wt_abs = try tmp.dir.realPathFileAlloc(io, "wt", alloc); defer alloc.free(wt_abs); - const linkfile = try std.fmt.allocPrint(alloc, "gitdir: {s}/.git/worktrees/wt\n", .{main_abs}); + const linkfile = try alloc.print("gitdir: {s}/.git/worktrees/wt\n", .{main_abs}); defer alloc.free(linkfile); try tmp.dir.writeFile(io, .{ .sub_path = "wt/.git", .data = linkfile }); @@ -775,7 +777,7 @@ pub const MissingLocalAssemblerMessage = struct { defer alloc.free(root); const msg = try missingLocalAssemblerMessage(alloc, "../missing", "x", wt_abs, root, error.FileNotFound); defer alloc.free(msg); - const expected = try std.fmt.allocPrint(alloc, "('{s}'), not this worktree ('{s}')", .{ main_abs, wt_abs }); + const expected = try alloc.print("('{s}'), not this worktree ('{s}')", .{ main_abs, wt_abs }); defer alloc.free(expected); try std.testing.expect(std.mem.indexOf(u8, msg, expected) != null); } @@ -814,7 +816,7 @@ pub const ResolveProjectRoot = struct { const wt_abs = try tmp.dir.realPathFileAlloc(io, "wt", alloc); defer alloc.free(wt_abs); - const linkfile = try std.fmt.allocPrint(alloc, "gitdir: {s}/.git/worktrees/wt\n", .{main_abs}); + const linkfile = try alloc.print("gitdir: {s}/.git/worktrees/wt\n", .{main_abs}); defer alloc.free(linkfile); try tmp.dir.writeFile(io, .{ .sub_path = "wt/.git", .data = linkfile }); @@ -875,7 +877,7 @@ pub const ResolveProjectRoot = struct { const sub_abs = try tmp.dir.realPathFileAlloc(io, "super/sub", alloc); defer alloc.free(sub_abs); - const linkfile = try std.fmt.allocPrint(alloc, "gitdir: {s}/.git/modules/sub\n", .{super_abs}); + const linkfile = try alloc.print("gitdir: {s}/.git/modules/sub\n", .{super_abs}); defer alloc.free(linkfile); try tmp.dir.writeFile(io, .{ .sub_path = "super/sub/.git", .data = linkfile }); @@ -923,8 +925,7 @@ pub const ResolveProjectRoot = struct { const wt_abs = try tmp.dir.realPathFileAlloc(io, "wt", alloc); defer alloc.free(wt_abs); - const linkfile = try std.fmt.allocPrint( - alloc, + const linkfile = try alloc.print( "gitdir: {s}/.git/worktrees/wt\ncommondir: {s}/.git\n", .{ main_abs, main_abs }, ); @@ -1042,9 +1043,9 @@ pub const ConcurrentDownload = struct { std.mem.replaceScalar(u8, fwd, '\\', '/'); // `file:///C:/x` on Windows, `file:///tmp/x` elsewhere. return if (fwd.len > 0 and fwd[0] == '/') - std.fmt.allocPrint(a, "file://{s}", .{fwd}) + a.print("file://{s}", .{fwd}) else - std.fmt.allocPrint(a, "file:///{s}", .{fwd}); + a.print("file:///{s}", .{fwd}); } fn haveCurl() bool { @@ -1075,7 +1076,7 @@ pub const ConcurrentDownload = struct { defer a.free(root); // Release fixture: /rel/v9.9.9/{, SHA256SUMS}. - const asset = try std.fmt.allocPrint(a, "labelle-assembler-{s}-{s}", .{ try osName(), try archName() }); + const asset = try a.print("labelle-assembler-{s}-{s}", .{ try osName(), try archName() }); defer a.free(asset); const rel_dir = try std.fs.path.join(a, &.{ root, "rel", "v" ++ fixture_version }); defer a.free(rel_dir); @@ -1089,7 +1090,7 @@ pub const ConcurrentDownload = struct { try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = asset_path, .data = payload }); const sha = try @import("provider_github/files.zig").sha256Hex(a, payload); defer a.free(sha); - const sums = try std.fmt.allocPrint(a, "{s} {s}\n", .{ sha, asset }); + const sums = try a.print("{s} {s}\n", .{ sha, asset }); defer a.free(sums); const sums_path = try std.fs.path.join(a, &.{ rel_dir, "SHA256SUMS" }); defer a.free(sums_path); @@ -1136,7 +1137,7 @@ pub const ConcurrentDownload = struct { defer tmp.cleanup(); const root = try tmp.dir.realPathFileAlloc(io, ".", a); defer a.free(root); - const asset = try std.fmt.allocPrint(a, "labelle-assembler-{s}-{s}", .{ try osName(), try archName() }); + const asset = try a.print("labelle-assembler-{s}-{s}", .{ try osName(), try archName() }); defer a.free(asset); const rel_dir = try std.fs.path.join(a, &.{ root, "rel", "v" ++ fixture_version }); defer a.free(rel_dir); @@ -1144,7 +1145,7 @@ pub const ConcurrentDownload = struct { const asset_path = try std.fs.path.join(a, &.{ rel_dir, asset }); defer a.free(asset_path); try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = asset_path, .data = "tampered" }); - const sums = try std.fmt.allocPrint(a, "{s} {s}\n", .{ "0" ** 64, asset }); + const sums = try a.print("{s} {s}\n", .{ &@as([64]u8, @splat('0')), asset }); defer a.free(sums); const sums_path = try std.fs.path.join(a, &.{ rel_dir, "SHA256SUMS" }); defer a.free(sums_path); @@ -1161,7 +1162,7 @@ pub const ConcurrentDownload = struct { const dest = try std.fs.path.join(a, &.{ ver_dir, exe_name }); defer a.free(dest); try std.Io.Dir.cwd().createDirPath(io, ver_dir); - const lock_path = try std.fmt.allocPrint(a, "{s}.lock", .{dest}); + const lock_path = try a.print("{s}.lock", .{dest}); defer a.free(lock_path); try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = lock_path, .data = "" }); diff --git a/src/cli/assembler_proc.zig b/src/cli/assembler_proc.zig index 68b8c82d..5951194e 100644 --- a/src/cli/assembler_proc.zig +++ b/src/cli/assembler_proc.zig @@ -462,7 +462,7 @@ fn spawnAndWait( // inherited (not captured), so the child's own diagnostic line // is not available here without log scraping. var detail_buf: [progress.max_detail_len]u8 = undefined; - const detail = std.fmt.bufPrint( + const detail = std.mem.print( &detail_buf, "assembler {s} failed", .{subcommand}, diff --git a/src/cli/audit.zig b/src/cli/audit.zig index 7a5b0805..eb52acf8 100644 --- a/src/cli/audit.zig +++ b/src/cli/audit.zig @@ -62,7 +62,6 @@ /// 2 — IO error (could not open project / files / dirs) /// /// Read-only. The audit never modifies project files. - const std = @import("std"); const config = @import("config.zig"); @@ -839,7 +838,7 @@ fn walkB2( const saved = path_buf.items.len; defer path_buf.shrinkRetainingCapacity(saved); var buf: [32]u8 = undefined; - const idx = std.fmt.bufPrint(&buf, "/{d}", .{i}) catch unreachable; + const idx = std.mem.print(&buf, "/{d}", .{i}) catch unreachable; try path_buf.appendSlice(arena, idx); try walkB2(arena, item, file, path_buf, report); } @@ -902,7 +901,7 @@ fn walkLegacyComponentsOnRef( const saved = path_buf.items.len; defer path_buf.shrinkRetainingCapacity(saved); var buf: [32]u8 = undefined; - const idx = std.fmt.bufPrint(&buf, "/{d}", .{i}) catch unreachable; + const idx = std.mem.print(&buf, "/{d}", .{i}) catch unreachable; try path_buf.appendSlice(arena, idx); try walkLegacyComponentsOnRef(arena, item, file, path_buf, report); } @@ -976,7 +975,7 @@ fn walkLegacyOverridesWrapper( const saved = path_buf.items.len; defer path_buf.shrinkRetainingCapacity(saved); var buf: [32]u8 = undefined; - const idx = std.fmt.bufPrint(&buf, "/{d}", .{i}) catch unreachable; + const idx = std.mem.print(&buf, "/{d}", .{i}) catch unreachable; try path_buf.appendSlice(arena, idx); try walkLegacyOverridesWrapper(arena, item, file, path_buf, report); } diff --git a/src/cli/bake.zig b/src/cli/bake.zig index f1b7c636..e708e7f0 100644 --- a/src/cli/bake.zig +++ b/src/cli/bake.zig @@ -11,9 +11,7 @@ const std = @import("std"); const project_config = @import("project_config.zig"); const config = @import("config.zig"); -const stbi = @cImport({ - @cInclude("stb_image.h"); -}); +const stbi = @import("../stb.zig"); /// Container: /// 0..7 magic "LRGBA\0\0\0" diff --git a/src/cli/bundle.zig b/src/cli/bundle.zig index ac82d749..1f9fcfc7 100644 --- a/src/cli/bundle.zig +++ b/src/cli/bundle.zig @@ -146,7 +146,7 @@ pub const iconset_max_px: u32 = iconset_entries[iconset_entries.len - 1].size; /// time (cli.zig) so a Linux/Windows user gets the refusal BEFORE the /// multi-minute generate+build, not after. pub fn hostSupported() bool { - return builtin.os.tag == .macos; + return builtin.target.os.tag == .macos; } /// One line, exit non-zero. Windows/Linux icon paths are tracked on the @@ -361,7 +361,7 @@ fn incrementDecimal(allocator: std.mem.Allocator, digits: []const u8) ![]u8 { fn clampComponent(component: []const u8, comptime max_digits: usize, clamped: *bool) []const u8 { if (std.mem.trimStart(u8, component, "0").len <= max_digits) return component; clamped.* = true; - return "9" ** max_digits; + return &@as([max_digits]u8, @splat('9')); } /// Digit-length check of a validated component (`digits` is a non-empty @@ -886,7 +886,7 @@ pub fn checkAssetsOverlap( /// Name of the real Mach-O beside the launcher: `-bin`. Caller owns. pub fn binName(allocator: std.mem.Allocator, exe_name: []const u8) ![]u8 { - return std.fmt.allocPrint(allocator, "{s}{s}", .{ exe_name, bin_suffix }); + return allocator.print("{s}{s}", .{ exe_name, bin_suffix }); } /// Render the `Contents/MacOS/` launcher script (cli#364). @@ -1240,7 +1240,7 @@ pub fn layoutBundle( // bundle is never launched there, only laid out by tests. const launcher_dst = try std.fs.path.join(allocator, &.{ macos_dir, exe_name }); defer allocator.free(launcher_dst); - const launcher_flags: std.Io.Dir.CreateFileOptions = if (builtin.os.tag == .windows) .{} else .{ .permissions = .fromMode(0o755) }; + const launcher_flags: std.Io.Dir.CreateFileOptions = if (builtin.target.os.tag == .windows) .{} else .{ .permissions = .fromMode(0o755) }; try cwd.writeFile(io, .{ .sub_path = launcher_dst, .data = launcher, .flags = launcher_flags }); const plist_path = try std.fs.path.join(allocator, &.{ bundle_dir, "Contents", "Info.plist" }); @@ -1283,7 +1283,7 @@ pub fn makeScratchIconset(allocator: std.mem.Allocator) ![]u8 { var prng = std.Random.DefaultPrng.init(@intFromPtr(&tmp_root) ^ std.hash.Wyhash.hash(0, tmp_root)); var attempt: u8 = 0; while (attempt < 8) : (attempt += 1) { - const name = try std.fmt.allocPrint(allocator, "{s}-{x}.iconset", .{ icon_file_key, prng.random().int(u64) }); + const name = try allocator.print("{s}-{x}.iconset", .{ icon_file_key, prng.random().int(u64) }); defer allocator.free(name); const path = try std.fs.path.join(allocator, &.{ tmp_root, name }); errdefer allocator.free(path); @@ -1687,7 +1687,7 @@ test "buildVersion never goes DOWN along a release history that crosses 1.0 (the const got = try buildVersion(a, v); defer a.free(got); // `""` → `1.0` has two components; pad so SemanticVersion can order it. - const padded = if (std.mem.count(u8, got, ".") == 1) try std.fmt.allocPrint(a, "{s}.0", .{got}) else try a.dupe(u8, got); + const padded = if (std.mem.count(u8, got, ".") == 1) try a.print("{s}.0", .{got}) else try a.dupe(u8, got); defer a.free(padded); const cur = try std.SemanticVersion.parse(padded); if (prev) |p| try testing.expect(p.order(cur) == .lt); @@ -1944,7 +1944,7 @@ test "writeIconset emits all ten PNGs at their sizes, upscaling a small master" test "resolveOutputDir: absolute passes through, relative anchors to the project, default is target zig-out/bundle/desktop" { const a = testing.allocator; - const abs_in = if (builtin.os.tag == .windows) "C:\\dist" else "/dist"; + const abs_in = if (builtin.target.os.tag == .windows) "C:\\dist" else "/dist"; const abs = try resolveOutputDir(a, "/proj", "/proj/.labelle/fixture_desktop", abs_in); defer a.free(abs); try testing.expectEqualStrings(abs_in, abs); @@ -1997,7 +1997,7 @@ test "layoutBundle writes Contents/{MacOS/,Info.plist,PkgInfo,Resources/} a const launcher = try cwd.readFileAlloc(io, launcher_dst, a, .unlimited); defer a.free(launcher); try testing.expectEqualStrings("#!/bin/sh\nexec launcher\n", launcher); - if (builtin.os.tag != .windows) { + if (builtin.target.os.tag != .windows) { const st = try cwd.statFile(io, launcher_dst, .{}); try testing.expect(st.permissions.toMode() & 0o111 == 0o111); } @@ -2069,7 +2069,7 @@ fn assetsFixture(a: std.mem.Allocator, work: []const u8) !void { const deep = try std.fs.path.join(a, &.{ nested, "outro.mp4" }); defer a.free(deep); try cwd.writeFile(io, .{ .sub_path = deep, .data = "outro-bytes" }); - if (builtin.os.tag != .windows) { + if (builtin.target.os.tag != .windows) { const link = try std.fs.path.join(a, &.{ assets, "alias.mp4" }); defer a.free(link); try cwd.symLink(io, "intro.mp4", link, .{}); @@ -2159,7 +2159,7 @@ test "stageAssets copies assets/ into Contents/Resources byte for byte, followin defer a.free(bundle); const report = (try stageAssets(a, work, bundle)) orelse return error.TestUnexpectedResult; - const posix = builtin.os.tag != .windows; + const posix = builtin.target.os.tag != .windows; // intro + nested outro (+ the alias, dereferenced, on POSIX); the // dangling link is skipped, never reproduced. try testing.expectEqual(@as(usize, if (posix) 3 else 2), report.files); @@ -2231,7 +2231,7 @@ test "resolveProbedKind: only a missing target is a skippable dangling link; oth } test "stageAssets fails (does not skip) on a symlink whose target is unreadable (#366)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; // root ignores mode bits, so the probe would succeed and prove nothing. if (std.c.getuid() == 0) return error.SkipZigTest; const a = testing.allocator; @@ -2351,7 +2351,7 @@ test "linkVerdict: into the output root → skip, back onto the active stack → } test "stageAssets cuts a sibling-directory link cycle (a/to-b -> ../b, b/to-a -> ../a) instead of ping-ponging to the depth cap (#366)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = testing.allocator; const io = config.globalIo(); const cwd = std.Io.Dir.cwd(); @@ -2413,7 +2413,7 @@ test "stageAssets cuts a sibling-directory link cycle (a/to-b -> ../b, b/to-a -> } test "stageAssets skips reached by ordinary descent through a link to an ANCESTOR of (#366)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = testing.allocator; const io = config.globalIo(); const cwd = std.Io.Dir.cwd(); @@ -2455,7 +2455,7 @@ test "stageAssets skips reached by ordinary descent through a link to an A } test "createFromBuild skips a directory link that resolves into and still replaces the stale bundle (#366)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = testing.allocator; const io = config.globalIo(); const cwd = std.Io.Dir.cwd(); @@ -2493,7 +2493,7 @@ test "createFromBuild skips a directory link that resolves into and still } test "stageAssets follows a directory link to a sibling outside , also when is the project root (#366)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = testing.allocator; const io = config.globalIo(); const cwd = std.Io.Dir.cwd(); @@ -2535,7 +2535,7 @@ test "stageAssets follows a directory link to a sibling outside , also when } test "stageAssets skips a symlink cycle inside assets/ with the link named, instead of hitting the depth cap (#366)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = testing.allocator; const io = config.globalIo(); const cwd = std.Io.Dir.cwd(); diff --git a/src/cli/cache_publish.zig b/src/cli/cache_publish.zig index 819cd636..cf6e7b2b 100644 --- a/src/cli/cache_publish.zig +++ b/src/cli/cache_publish.zig @@ -36,7 +36,7 @@ const util = @import("util.zig"); /// make staging names readable and unique across processes; the random part /// keeps them unique across threads of one process. pub fn processId() u64 { - return switch (builtin.os.tag) { + return switch (builtin.target.os.tag) { .windows => std.os.windows.GetCurrentProcessId(), .linux => @intCast(std.os.linux.getpid()), else => if (builtin.link_libc) @intCast(std.c.getpid()) else 0, @@ -49,7 +49,7 @@ pub fn processId() u64 { pub fn tempSibling(a: std.mem.Allocator, dest: []const u8, tag: []const u8) ![]u8 { var random: [8]u8 = undefined; config.globalIo().random(&random); - return std.fmt.allocPrint(a, "{s}.{s}-{d}-{s}", .{ + return a.print("{s}.{s}-{d}-{s}", .{ std.mem.trimEnd(u8, dest, "/\\"), tag, processId(), @@ -76,7 +76,7 @@ pub const InstallLock = struct { pub fn acquire(a: std.mem.Allocator, dest: []const u8) !InstallLock { const io = config.globalIo(); const cwd = std.Io.Dir.cwd(); - const lock_path = try std.fmt.allocPrint(a, "{s}.lock", .{std.mem.trimEnd(u8, dest, "/\\")}); + const lock_path = try a.print("{s}.lock", .{std.mem.trimEnd(u8, dest, "/\\")}); defer a.free(lock_path); if (std.fs.path.dirname(lock_path)) |dir| try cwd.createDirPath(io, dir); const file = cwd.createFile(io, lock_path, .{ .truncate = false, .lock = .exclusive }) catch |err| { @@ -206,7 +206,7 @@ test "tempSibling: same directory, tagged, pid-stamped and unique per call" { try testing.expect(!std.mem.eql(u8, one, two)); try testing.expectEqualStrings(std.fs.path.dirname(dest).?, std.fs.path.dirname(one).?); try testing.expect(std.mem.startsWith(u8, one, dest)); - const pid = try std.fmt.allocPrint(a, ".tmp-{d}-", .{processId()}); + const pid = try a.print(".tmp-{d}-", .{processId()}); defer a.free(pid); try testing.expect(std.mem.indexOf(u8, one, pid) != null); try testing.expect(isSiblingName(std.fs.path.basename(one), "labelle-assembler")); @@ -214,7 +214,7 @@ test "tempSibling: same directory, tagged, pid-stamped and unique per call" { try testing.expect(!isSiblingName("labelle-assembler.lock", "labelle-assembler")); // A trailing separator on a directory destination does not leak in. - const dir_dest = try std.fmt.allocPrint(a, "{s}{c}", .{ std.fs.path.dirname(dest).?, std.fs.path.sep }); + const dir_dest = try a.print("{s}{c}", .{ std.fs.path.dirname(dest).?, std.fs.path.sep }); defer a.free(dir_dest); const staged_dir = try tempSibling(a, dir_dest, "stale"); defer a.free(staged_dir); @@ -274,7 +274,7 @@ test "publishDir: publishes, keeps a valid tree, replaces a partial leftover" { const HasTool = struct { pub fn valid(_: @This(), dir: []const u8) bool { var buf: [1024]u8 = undefined; - const p = std.fmt.bufPrint(&buf, "{s}{c}bin{c}tool", .{ dir, std.fs.path.sep, std.fs.path.sep }) catch return false; + const p = std.mem.print(&buf, "{s}{c}bin{c}tool", .{ dir, std.fs.path.sep, std.fs.path.sep }) catch return false; return util.fileExists(p); } }; diff --git a/src/cli/compatibility.zig b/src/cli/compatibility.zig index eee03fa8..2c71f426 100644 --- a/src/cli/compatibility.zig +++ b/src/cli/compatibility.zig @@ -324,11 +324,13 @@ test "the pin set `labelle init` scaffolds passes the CLI's own check (#357)" { // 1.x set is asserted separately below as the case that SHOULD warn. // The CLI pin is this CLI's own version, so the case keeps meaning "on // the current line" across CLI major bumps (3.0.0 broke a hard-coded 2.0.0). + // The package pins are the curated set itself for the same reason (the + // Zig 0.17 set, core 3 / engine 5 / gfx 3, broke a hard-coded 2/3/2). const reported = project_config.ProjectConfig{ .name = "my_game", - .core_version = "2.0.0", - .engine_version = "3.0.0", - .gfx_version = "2.0.0", + .core_version = project_config.CORE_VERSION, + .engine_version = project_config.ENGINE_VERSION, + .gfx_version = project_config.GFX_VERSION, .labelle_version = project_config.CLI_VERSION, }; try std.testing.expectEqual(@as(u8, 0), compatWarnings(reported, false)); @@ -337,9 +339,9 @@ test "the pin set `labelle init` scaffolds passes the CLI's own check (#357)" { if (parseVersion(project_config.CLI_VERSION).major >= 3) { const cli_behind = project_config.ProjectConfig{ .name = "my_game", - .core_version = "2.0.0", - .engine_version = "3.0.0", - .gfx_version = "2.0.0", + .core_version = project_config.CORE_VERSION, + .engine_version = project_config.ENGINE_VERSION, + .gfx_version = project_config.GFX_VERSION, .labelle_version = "2.1.1", }; try std.testing.expectEqual(@as(u8, 1), compatWarnings(cli_behind, false)); @@ -361,9 +363,9 @@ test "the pin set `labelle init` scaffolds passes the CLI's own check (#357)" { // …as does the flagship game's set (core 1.28.0 + engine 2.13.0). const flagship = project_config.ProjectConfig{ .name = "flying_platform", - .core_version = "2.0.0", - .engine_version = "3.0.0", - .gfx_version = "2.0.0", + .core_version = project_config.CORE_VERSION, + .engine_version = project_config.ENGINE_VERSION, + .gfx_version = project_config.GFX_VERSION, .labelle_version = project_config.CLI_VERSION, }; try std.testing.expectEqual(@as(u8, 0), compatWarnings(flagship, false)); diff --git a/src/cli/config.zig b/src/cli/config.zig index 220726a9..dfbaebc7 100644 --- a/src/cli/config.zig +++ b/src/cli/config.zig @@ -86,7 +86,7 @@ fn readProjectConfigImpl(allocator: std.mem.Allocator, project_dir: []const u8, }; defer allocator.free(source_raw); - const source = try allocator.dupeZ(u8, source_raw); + const source = try allocator.dupeSentinel(u8, source_raw, 0); defer allocator.free(source); // `ignore_unknown_fields`: the CLI's `project_config.ProjectConfig` @@ -95,9 +95,7 @@ fn readProjectConfigImpl(allocator: std.mem.Allocator, project_dir: []const u8, // mirror — without this, a newer project.labelle would fail to parse // and break the CLI for no good reason. try @import("provider_settings.zig").validateProject(allocator, source, if (verbose) labelle_path else null); - var cfg = std.zon.parse.fromSliceAlloc(project_config.ProjectConfig, allocator, source, null, .{ - .ignore_unknown_fields = true, - }) catch |err| { + var cfg = @import("util.zig").parseZon(project_config.ProjectConfig, allocator, source, .{ .ignore_unknown_fields = true }) catch |err| { if (verbose) std.debug.print("labelle: could not parse '{s}': {any}\n", .{ labelle_path, err }); return error.ParseError; }; diff --git a/src/cli/docker.zig b/src/cli/docker.zig index f4e53c22..ba3ca4e7 100644 --- a/src/cli/docker.zig +++ b/src/cli/docker.zig @@ -7,21 +7,47 @@ const std = @import("std"); const builtin = @import("builtin"); const config = @import("config.zig"); -const ZIG_VERSION = "0.16.0"; +const zig_toolchain = @import("zig_toolchain.zig"); -const host_arch = switch (builtin.cpu.arch) { +const host_arch = switch (builtin.target.cpu.arch) { .aarch64 => "aarch64", .x86_64 => "x86_64", else => @compileError("unsupported architecture for docker builds"), }; -const host_target = host_arch ++ "-" ++ @tagName(builtin.os.tag); +const host_target = host_arch ++ "-" ++ @tagName(builtin.target.os.tag); + +/// The shell that downloads Zig `version` from ziglang.org into the +/// container. `version` is the one the PROJECT requires (its `zig_version` +/// pin, else the one its engine builds with, else the CLI default): the same +/// resolution a native build uses, so a project on an engine of the Zig 0.16 +/// era is not handed the CLI's newer default. It reaches a shell, so anything +/// but a plain version string is refused. Caller owns the slice. +fn installZigScript(allocator: std.mem.Allocator, version: []const u8) ![]u8 { + if (version.len == 0) return error.InvalidZigVersion; + for (version) |c| switch (c) { + '0'...'9', 'a'...'z', 'A'...'Z', '.', '-', '+' => {}, + else => return error.InvalidZigVersion, + }; + return allocator.print("apt-get update -qq > /dev/null && " ++ + "apt-get install -y -qq curl xz-utils ca-certificates > /dev/null && " ++ + "curl -fsSL https://ziglang.org/download/{0s}/zig-x86_64-linux-{0s}.tar.xz | tar -xJ -C /opt > /dev/null && " ++ + "ln -sf /opt/zig-x86_64-linux-{0s}/zig /usr/local/bin/zig", .{version}); +} -// Download Zig from ziglang.org directly into the container. -const install_zig = "apt-get update -qq > /dev/null && " ++ - "apt-get install -y -qq curl xz-utils ca-certificates > /dev/null && " ++ - "curl -fsSL https://ziglang.org/download/" ++ ZIG_VERSION ++ "/zig-x86_64-linux-" ++ ZIG_VERSION ++ ".tar.xz | tar -xJ -C /opt > /dev/null && " ++ - "ln -sf /opt/zig-x86_64-linux-" ++ ZIG_VERSION ++ "/zig /usr/local/bin/zig"; +test "docker: the container installs the Zig version it is given, and refuses shell text" { + const a = std.testing.allocator; + const old = try installZigScript(a, "0.16.0"); + defer a.free(old); + try std.testing.expect(std.mem.indexOf(u8, old, "/download/0.16.0/zig-x86_64-linux-0.16.0.tar.xz") != null); + try std.testing.expect(std.mem.indexOf(u8, old, zig_toolchain.DEFAULT_ZIG_VERSION) == null); + const new = try installZigScript(a, "0.17.1"); + defer a.free(new); + try std.testing.expect(std.mem.indexOf(u8, new, "/opt/zig-x86_64-linux-0.17.1/zig") != null); + for ([_][]const u8{ "", "0.16.0; rm -rf /", "$(id)", "0.16.0 ", "a/b" }) |bad| { + try std.testing.expectError(error.InvalidZigVersion, installZigScript(a, bad)); + } +} /// Recursively copy a directory tree. `src` and `dst` are absolute paths. /// @@ -180,7 +206,11 @@ fn sanitizeTarget(allocator: std.mem.Allocator, target: []const u8) ![]u8 { /// Run `zig build` inside a Docker container with inherited stdio, sharing /// the host Zig cache. macOS targets never get here: argument parsing refuses /// them (cli#471 X3). Returns the exit code of the docker process. -pub fn runBuild(allocator: std.mem.Allocator, target_dir: []const u8, target_override: ?[]const u8, optimize: ?[]const u8) !u8 { +pub fn runBuild(allocator: std.mem.Allocator, project_dir: []const u8, target_dir: []const u8, target_override: ?[]const u8, optimize: ?[]const u8) !u8 { + const required = try zig_toolchain.resolveRequiredVersion(allocator, project_dir); + defer allocator.free(required.version); + const install_zig = try installZigScript(allocator, required.version); + defer allocator.free(install_zig); const abs_target = try std.Io.Dir.cwd().realPathFileAlloc(config.globalIo(), target_dir, allocator); defer allocator.free(abs_target); @@ -195,7 +225,7 @@ pub fn runBuild(allocator: std.mem.Allocator, target_dir: []const u8, target_ove const parent = std.fs.path.dirname(abs_target) orelse return error.InvalidPath; const subdir = std.fs.path.basename(abs_target); - const labelle_vol = try std.fmt.allocPrint(allocator, "{s}:/labelle", .{parent}); + const labelle_vol = try allocator.print("{s}:/labelle", .{parent}); defer allocator.free(labelle_vol); // Build the zig command with -Dtarget and optional -Doptimize flags. @@ -205,18 +235,17 @@ pub fn runBuild(allocator: std.mem.Allocator, target_dir: []const u8, target_ove const effective_target: []const u8 = sanitized_target orelse host_target; const optimize_part = if (optimize) |opt| - try std.fmt.allocPrint(allocator, " -Doptimize={s}", .{opt}) + try allocator.print(" -Doptimize={s}", .{opt}) else null; defer if (optimize_part) |o| allocator.free(o); - const effective_cmd = try std.fmt.allocPrint(allocator, "zig build -Dtarget={s}{s}", .{ effective_target, optimize_part orelse "" }); + const effective_cmd = try allocator.print("zig build -Dtarget={s}{s}", .{ effective_target, optimize_part orelse "" }); defer allocator.free(effective_cmd); // Fix fingerprint: run build once to get the error, patch if needed, then build for real. // Only re-runs the build if a fingerprint was actually found and patched. - const script = try std.fmt.allocPrint( - allocator, + const script = try allocator.print( "{s} && cd /labelle/{s} && " ++ "BUILD_OUT=$({s} 2>&1 || true) && " ++ "FP=$(echo \"$BUILD_OUT\" | grep 'use this value:' | head -1 | sed 's/.*use this value: //') && " ++ @@ -229,7 +258,7 @@ pub fn runBuild(allocator: std.mem.Allocator, target_dir: []const u8, target_ove // Share the host Zig cache for pre-fetched packages. if (zigCacheDir(allocator)) |cache_dir| { defer allocator.free(cache_dir); - const cache_vol = try std.fmt.allocPrint(allocator, "{s}:/root/.cache/zig", .{cache_dir}); + const cache_vol = try allocator.print("{s}:/root/.cache/zig", .{cache_dir}); defer allocator.free(cache_vol); return spawnAndWait(allocator, &.{ "docker", "run", "--rm", "-v", labelle_vol, "-v", cache_vol, "ubuntu:24.04", "bash", "-c", script }); @@ -252,11 +281,11 @@ fn spawnAndWait(allocator: std.mem.Allocator, argv: []const []const u8) !u8 { return switch (term) { .exited => |code| code, .signal => |sig| { - std.debug.print("labelle: docker killed by signal {d}\n", .{@intFromEnum(sig)}); + std.debug.print("labelle: docker killed by signal {d}\n", .{@backingInt(sig)}); return 1; }, .stopped => |sig| { - std.debug.print("labelle: docker stopped by signal {d}\n", .{@intFromEnum(sig)}); + std.debug.print("labelle: docker stopped by signal {d}\n", .{@backingInt(sig)}); return 1; }, .unknown => |val| { diff --git a/src/cli/doctor.zig b/src/cli/doctor.zig index d87f9fbb..e3f20932 100644 --- a/src/cli/doctor.zig +++ b/src/cli/doctor.zig @@ -374,12 +374,12 @@ fn checkZig(arena: std.mem.Allocator, project_dir: []const u8) Check { break :blk true; }; if (installed) { - return .{ .name = "Zig toolchain", .ok = true, .detail = std.fmt.allocPrint(arena, "managed zig {s} ({s})", .{ resolved.version, resolved.source.label() }) catch "managed zig" }; + return .{ .name = "Zig toolchain", .ok = true, .detail = arena.print("managed zig {s} ({s})", .{ resolved.version, resolved.source.label() }) catch "managed zig" }; } return .{ .name = "Zig toolchain", .ok = true, - .detail = std.fmt.allocPrint(arena, "managed zig {s} — will download + verify on first build", .{resolved.version}) catch "managed zig (not yet installed)", + .detail = arena.print("managed zig {s} — will download + verify on first build", .{resolved.version}) catch "managed zig (not yet installed)", }; } @@ -389,13 +389,12 @@ fn checkOverride(arena: std.mem.Allocator, source: []const u8, path: []const u8, const name = "Zig toolchain"; const verified = zig_toolchain.verifyBinary(arena, path, required) catch return .{ .name = name, .ok = false, .hint = "could not check the Zig override (out of memory)" }; - const fmt = std.fmt.allocPrint; return switch (verified) { - .ok => .{ .name = name, .ok = true, .detail = fmt(arena, "{s} override: {s} (zig {s}, verified)", .{ source, path, required }) catch "override verified" }, - .missing => .{ .name = name, .ok = false, .hint = fmt(arena, "{s} override '{s}' does not exist", .{ source, path }) catch "override does not exist" }, - .not_executable => .{ .name = name, .ok = false, .hint = fmt(arena, "{s} override '{s}' is not an executable file", .{ source, path }) catch "override is not executable" }, - .failed => .{ .name = name, .ok = false, .hint = fmt(arena, "{s} override '{s}' did not run `zig version`", .{ source, path }) catch "override did not run" }, - .version => |reported| .{ .name = name, .ok = false, .hint = fmt(arena, "{s} override '{s}' is Zig {s}; this project requires {s}", .{ source, path, reported, required }) catch "override has the wrong version" }, + .ok => .{ .name = name, .ok = true, .detail = arena.print("{s} override: {s} (zig {s}, verified)", .{ source, path, required }) catch "override verified" }, + .missing => .{ .name = name, .ok = false, .hint = arena.print("{s} override '{s}' does not exist", .{ source, path }) catch "override does not exist" }, + .not_executable => .{ .name = name, .ok = false, .hint = arena.print("{s} override '{s}' is not an executable file", .{ source, path }) catch "override is not executable" }, + .failed => .{ .name = name, .ok = false, .hint = arena.print("{s} override '{s}' did not run `zig version`", .{ source, path }) catch "override did not run" }, + .version => |reported| .{ .name = name, .ok = false, .hint = arena.print("{s} override '{s}' is Zig {s}; this project requires {s}", .{ source, path, reported, required }) catch "override has the wrong version" }, }; } @@ -412,7 +411,7 @@ fn checkPython(arena: std.mem.Allocator) Check { // install reports not-ok instead of faking readiness (PR #291 review). if (python_provision.managedPythonOk(arena)) { const exe = python_provision.findPythonExe(arena) orelse unreachable; - return .{ .name = python_check_name, .ok = true, .required = false, .detail = std.fmt.allocPrint(arena, "managed: {s}", .{exe}) catch "managed" }; + return .{ .name = python_check_name, .ok = true, .required = false, .detail = arena.print("managed: {s}", .{exe}) catch "managed" }; } if (python_provision.systemPythonOk(arena)) { return .{ .name = python_check_name, .ok = true, .required = false, .detail = "system python3 on PATH" }; @@ -459,11 +458,11 @@ test "doctor: a Zig override is verified, not assumed: missing, wrong version, r try std.testing.expect(!checkOverride(a, "--zig", dir, "0.16.0").ok); // Scripts that answer `zig version`: POSIX shells only. - if (builtin.os.tag == .windows) return; + if (builtin.target.os.tag == .windows) return; const Fake = struct { fn write(d: std.Io.Dir, name: []const u8, version: []const u8) !void { var buf: [128]u8 = undefined; - const text = try std.fmt.bufPrint(&buf, "#!/bin/sh\necho {s}\n", .{version}); + const text = try std.mem.print(&buf, "#!/bin/sh\necho {s}\n", .{version}); try d.writeFile(config.globalIo(), .{ .sub_path = name, .data = text, .flags = .{ .permissions = .executable_file } }); } }; diff --git a/src/cli/init.zig b/src/cli/init.zig index 7a361bf9..e26215b7 100644 --- a/src/cli/init.zig +++ b/src/cli/init.zig @@ -49,7 +49,7 @@ fn withCliVersion(allocator: std.mem.Allocator, cmd_args: []const []const u8, cl const out = try allocator.alloc([]const u8, cmd_args.len + 1); errdefer allocator.free(out); @memcpy(out[0..cmd_args.len], cmd_args); - out[cmd_args.len] = try std.fmt.allocPrint(allocator, labelle_version_flag ++ "={s}", .{cli_version}); + out[cmd_args.len] = try allocator.print(labelle_version_flag ++ "={s}", .{cli_version}); return out; } diff --git a/src/cli/launcher_manifest.zig b/src/cli/launcher_manifest.zig index 548f9d3b..b09ac7bb 100644 --- a/src/cli/launcher_manifest.zig +++ b/src/cli/launcher_manifest.zig @@ -32,12 +32,10 @@ pub fn readLauncherManifest(allocator: std.mem.Allocator, project_dir: []const u }; defer allocator.free(source_raw); - const source = try allocator.dupeZ(u8, source_raw); + const source = try allocator.dupeSentinel(u8, source_raw, 0); defer allocator.free(source); - return std.zon.parse.fromSliceAlloc(LauncherManifest, allocator, source, null, .{ - .ignore_unknown_fields = true, - }) catch |err| { + return @import("util.zig").parseZon(LauncherManifest, allocator, source, .{ .ignore_unknown_fields = true }) catch |err| { std.debug.print("labelle: could not parse launcher manifest from project.labelle: {any}\n", .{err}); return error.ParseError; }; diff --git a/src/cli/linux_desktop.zig b/src/cli/linux_desktop.zig index f21b29ce..870a6911 100644 --- a/src/cli/linux_desktop.zig +++ b/src/cli/linux_desktop.zig @@ -52,7 +52,7 @@ pub const icon_px: u32 = 256; /// Whether to emit the entry for this build: the explicit `--linux-desktop` /// opt-in anywhere, else automatically on a Linux host. pub fn shouldEmit(opt_in: bool) bool { - return opt_in or builtin.os.tag == .linux; + return opt_in or builtin.target.os.tag == .linux; } /// Characters the spec reserves in `Exec` arguments — their presence means @@ -219,7 +219,7 @@ pub fn createFromBuild( var icon_abs: ?[]u8 = null; defer if (icon_abs) |p| allocator.free(p); if (maybe_img) |img| { - const icon_name = try std.fmt.allocPrint(allocator, "{s}.png", .{exe.name}); + const icon_name = try allocator.print("{s}.png", .{exe.name}); defer allocator.free(icon_name); const icon_path = try std.fs.path.join(allocator, &.{ out_dir, icon_name }); errdefer allocator.free(icon_path); @@ -238,7 +238,7 @@ pub fn createFromBuild( .icon_path = icon_abs, }); defer allocator.free(text); - const entry_name = try std.fmt.allocPrint(allocator, "{s}.desktop", .{exe.name}); + const entry_name = try allocator.print("{s}.desktop", .{exe.name}); defer allocator.free(entry_name); const entry_path = try std.fs.path.join(allocator, &.{ out_dir, entry_name }); errdefer allocator.free(entry_path); @@ -445,10 +445,10 @@ pub const CreateFromBuildSpec = struct { // and escapes — so compare against the escaper, not the raw path. const exe_escaped = try escapeExecArg(allocator, exe_real); defer allocator.free(exe_escaped); - const want_exec = try std.fmt.allocPrint(allocator, "Exec={s}\n", .{exe_escaped}); + const want_exec = try allocator.print("Exec={s}\n", .{exe_escaped}); defer allocator.free(want_exec); try std.testing.expect(std.mem.indexOf(u8, text, want_exec) != null); - const want_path = try std.fmt.allocPrint(allocator, "Path={s}\n", .{target_real}); + const want_path = try allocator.print("Path={s}\n", .{target_real}); defer allocator.free(want_path); try std.testing.expect(std.mem.indexOf(u8, text, want_path) != null); try std.testing.expect(std.mem.indexOf(u8, text, "Name=Colony Ship\n") != null); @@ -456,7 +456,7 @@ pub const CreateFromBuildSpec = struct { const icon_path = try std.fs.path.join(allocator, &.{ target_real, "zig-out", "game.png" }); defer allocator.free(icon_path); - const want_icon = try std.fmt.allocPrint(allocator, "Icon={s}\n", .{icon_path}); + const want_icon = try allocator.print("Icon={s}\n", .{icon_path}); defer allocator.free(want_icon); try std.testing.expect(std.mem.indexOf(u8, text, want_icon) != null); const icon_bytes = try cwd.readFileAlloc(io, icon_path, allocator, .limited(4 << 20)); @@ -508,6 +508,6 @@ pub const CreateFromBuildSpec = struct { pub const ShouldEmitSpec = struct { test "the opt-in always wins; otherwise only a Linux host emits" { try std.testing.expect(shouldEmit(true)); - try expect.equal(shouldEmit(false), builtin.os.tag == .linux); + try expect.equal(shouldEmit(false), builtin.target.os.tag == .linux); } }; diff --git a/src/cli/lock_open.zig b/src/cli/lock_open.zig index bc17151d..ac05f005 100644 --- a/src/cli/lock_open.zig +++ b/src/cli/lock_open.zig @@ -10,7 +10,7 @@ const std = @import("std"); const builtin = @import("builtin"); const config = @import("config.zig"); -const is_windows = builtin.os.tag == .windows; +const is_windows = builtin.target.os.tag == .windows; /// Open (or create) `lock_path` for reading and writing, never through a /// symbolic link: an existing entry is opened without following links and diff --git a/src/cli/lockfile.zig b/src/cli/lockfile.zig index d77db7bd..7a26ba08 100644 --- a/src/cli/lockfile.zig +++ b/src/cli/lockfile.zig @@ -241,16 +241,14 @@ fn readGuiManifestName(allocator: std.mem.Allocator, plugin_dir: []const u8) ?[] }; defer allocator.free(raw); - const raw_z = allocator.dupeZ(u8, raw) catch return null; + const raw_z = allocator.dupeSentinel(u8, raw, 0) catch return null; defer allocator.free(raw_z); - const manifest = std.zon.parse.fromSliceAlloc( - GuiManifestName, - allocator, - raw_z, - null, - .{ .ignore_unknown_fields = true }, - ) catch |err| { + // Zig 0.17's ZON parser allocates the value in an arena and has no + // per-value free, so the parse gets a scratch arena of its own. + var zon_arena = std.heap.ArenaAllocator.init(allocator); + defer zon_arena.deinit(); + const manifest = @import("util.zig").parseZon(GuiManifestName, zon_arena.allocator(), raw_z, .{ .ignore_unknown_fields = true }) catch |err| { // The manifest file exists but won't parse — warn so the // fallback name in labelle.lock is not silently misleading. std.debug.print( @@ -259,7 +257,6 @@ fn readGuiManifestName(allocator: std.mem.Allocator, plugin_dir: []const u8) ?[] ); return null; }; - defer std.zon.parse.free(allocator, manifest); if (manifest.name.len == 0) { std.debug.print( @@ -625,8 +622,7 @@ test "lockCliVersion: only the top-level field counts" { /// return the dir path the gate should be pointed at (cwd-relative, the /// same shape the other tmp-dir tests here use). Caller frees. fn stampedLockDir(alloc: std.mem.Allocator, tmp: *std.testing.TmpDir, version: []const u8) ![]u8 { - const body = try std.fmt.allocPrint( - alloc, + const body = try alloc.print( "// labelle.lock — resolved dependency versions\n.{{\n .cli_version = \"{s}\",\n .resolved = .{{}},\n}}\n", .{version}, ); diff --git a/src/cli/material_toolchain.zig b/src/cli/material_toolchain.zig index 760aab7e..0b161628 100644 --- a/src/cli/material_toolchain.zig +++ b/src/cli/material_toolchain.zig @@ -165,7 +165,7 @@ pub fn validateOverride(path: []const u8) !void { // A regular file is not yet a runnable one. Without this the preflight // waves through a `-rw-r--r--` path and the build dies at exec time with // exactly the opaque failure the gate exists to replace. - if (builtin.os.tag == .windows) { + if (builtin.target.os.tag == .windows) { switch (classifyWindowsPath(path)) { .directly_executable => {}, .interpreter_required => { diff --git a/src/cli/migrate.zig b/src/cli/migrate.zig index b27d81d3..97e24216 100644 --- a/src/cli/migrate.zig +++ b/src/cli/migrate.zig @@ -90,7 +90,6 @@ /// migrate/pipeline.zig — transform dispatcher + Summary/FileCounts /// migrate/walk.zig — directory traversal + xref pre-scan /// migrate/tests*.zig — zspec spec namespaces - const std = @import("std"); const pipeline = @import("migrate/pipeline.zig"); diff --git a/src/cli/migrate/tests_rfc596.zig b/src/cli/migrate/tests_rfc596.zig index c77a2d8e..2d2dd1fc 100644 --- a/src/cli/migrate/tests_rfc596.zig +++ b/src/cli/migrate/tests_rfc596.zig @@ -20,7 +20,6 @@ const applyAllArenaFull = helpers.applyAllArenaFull; const applyAllFullCounts = helpers.applyAllFullCounts; const FileCounts = pipeline.FileCounts; - // ───────────────────────────────────────────────────────────────────── // RFC #596 — Transform 5: lift `overrides` block on prefab refs // ───────────────────────────────────────────────────────────────────── diff --git a/src/cli/migrate/transforms_meta.zig b/src/cli/migrate/transforms_meta.zig index 7ff7efc0..62d1e940 100644 --- a/src/cli/migrate/transforms_meta.zig +++ b/src/cli/migrate/transforms_meta.zig @@ -163,7 +163,7 @@ pub fn insertNewMeta( if (file_start >= src.len or src[file_start] != '{') return null; // Probe the object's first key (if any) to determine the indent // we should match. Default to four spaces if the object is empty. - var indent_buf: [16]u8 = [_]u8{' '} ** 16; + var indent_buf: [16]u8 = @splat(' '); var indent_len: usize = 4; { var i: usize = file_start + 1; diff --git a/src/cli/pack.zig b/src/cli/pack.zig index c850303e..2f36a723 100644 --- a/src/cli/pack.zig +++ b/src/cli/pack.zig @@ -432,7 +432,7 @@ const Capture = struct { buf: *std.ArrayList(u8), gpa: std.mem.Allocator, fn print(self: @This(), comptime fmt: []const u8, args: anytype) !void { - const s = try std.fmt.allocPrint(self.gpa, fmt, args); + const s = try self.gpa.print(fmt, args); defer self.gpa.free(s); try self.buf.appendSlice(self.gpa, s); } diff --git a/src/cli/pipeline.zig b/src/cli/pipeline.zig index cefa9a11..3657f080 100644 --- a/src/cli/pipeline.zig +++ b/src/cli/pipeline.zig @@ -422,7 +422,7 @@ pub fn run(allocator: std.mem.Allocator, parsed_args: ParsedArgs) !u8 { // Build with the effective optimize mode computed above. const optimize_flag: ?[]const u8 = if (effective_optimize) |opt| - try std.fmt.allocPrint(allocator, "-Doptimize={s}", .{opt}) + try allocator.print("-Doptimize={s}", .{opt}) else null; defer if (optimize_flag) |f| allocator.free(f); diff --git a/src/cli/pipeline/build.zig b/src/cli/pipeline/build.zig index d6b800e1..a550b8ee 100644 --- a/src/cli/pipeline/build.zig +++ b/src/cli/pipeline/build.zig @@ -63,7 +63,7 @@ pub fn run( // its progress pipe) lives inside the container. if (reporter) |r| r.beginPhaseOrStep(.compile, "docker build"); std.debug.print("labelle: building via docker...\n", .{}); - const docker_exit = try docker.runBuild(allocator, target_dir, parsed_args.docker_target, effective_optimize); + const docker_exit = try docker.runBuild(allocator, project_dir, target_dir, parsed_args.docker_target, effective_optimize); if (reporter) |r| r.clearSpinner(); if (docker_exit != 0) { if (reporter) |r| r.finishFailed(docker_exit, "docker build failed"); diff --git a/src/cli/pipeline/rebuild_commit_tests.zig b/src/cli/pipeline/rebuild_commit_tests.zig index a0b1f9c4..33bd930a 100644 --- a/src/cli/pipeline/rebuild_commit_tests.zig +++ b/src/cli/pipeline/rebuild_commit_tests.zig @@ -94,7 +94,7 @@ const Published = struct { const g = try std.Io.Dir.cwd().readFileAlloc(config.globalIo(), self.publisher.generation_file, a, .limited(64)); defer a.free(g); var buf: [24]u8 = undefined; - try std.testing.expectEqualStrings(try std.fmt.bufPrint(&buf, "{d}\n", .{generation}), g); + try std.testing.expectEqualStrings(try std.mem.print(&buf, "{d}\n", .{generation}), g); } }; @@ -103,7 +103,7 @@ pub fn contains(haystack: []const u8, needle: []const u8) bool { } test "rebuild commit: labelle.lock is committed before the generation advances, and rolled back after (cli#474)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; var fx: Fixture = undefined; try fx.init(a); @@ -171,7 +171,7 @@ test "rebuild commit: labelle.lock is committed before the generation advances, } test "rebuild commit: a staged lock that cannot be committed fails the rebuild, which rolls back (cli#474)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; var fx: Fixture = undefined; try fx.init(a); @@ -226,7 +226,7 @@ test "rebuild commit: a staged lock that cannot be committed fails the rebuild, } test "rebuild commit: a cancel during the publication is honoured before the switch and before the commit (cli#474)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); for ([_]bool{ false, true }) |at_switch| { @@ -278,7 +278,7 @@ test "rebuild commit: a cancel during the publication is honoured before the swi } test "rebuild commit: a local provider's source edit is a session change; its build output is not (cli#474)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var fx: Fixture = undefined; @@ -321,7 +321,7 @@ test "rebuild commit: a local provider's source edit is a session change; its bu } test "rebuild commit: the local providers outside the project are watched with it (cli#474)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var fx: Fixture = undefined; @@ -407,7 +407,7 @@ fn freeRoots(a: std.mem.Allocator, roots: *std.ArrayList([]const u8)) void { } test "rebuild commit: nested local providers are walked once, so an inner edit rebuilds (cli#474)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var tmp = std.testing.tmpDir(.{}); @@ -454,7 +454,7 @@ test "rebuild commit: nested local providers are walked once, so an inner edit r } test "rebuild commit: a local provider containing the project is watched without the project (cli#474)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var tmp = std.testing.tmpDir(.{}); @@ -491,7 +491,7 @@ test "rebuild commit: a local provider containing the project is watched without } test "rebuild commit: a rollback restores an absent labelle.lock as absent (cli#474)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var fx: Fixture = undefined; @@ -534,7 +534,7 @@ test "rebuild commit: a rollback restores an absent labelle.lock as absent (cli# } test "rebuild commit: a prebuild output inside an external local provider is ignored by its canonical walk (cli#476)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var tmp = std.testing.tmpDir(.{}); @@ -567,7 +567,7 @@ test "rebuild commit: a prebuild output inside an external local provider is ign } test "rebuild commit: a project reached through a link watches the providers beside its real path (cli#476)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; // links need a privilege there + if (builtin.target.os.tag == .windows) return error.SkipZigTest; // links need a privilege there const a = std.testing.allocator; const io = config.globalIo(); var tmp = std.testing.tmpDir(.{}); @@ -594,7 +594,7 @@ test "rebuild commit: a project reached through a link watches the providers bes } test "rebuild commit: a newly declared provider whose manifest fails the replan is still watched (cli#476)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var fx: Fixture = undefined; @@ -643,7 +643,7 @@ test "rebuild commit: a newly declared provider whose manifest fails the replan } test "rebuild commit: a rollback leaves a labelle.lock another command rewrote meanwhile (cli#478)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; var fx: Fixture = undefined; try fx.init(a); @@ -707,7 +707,7 @@ test "rebuild commit: a rollback leaves a labelle.lock another command rewrote m } test "rebuild commit: a local provider whose manifest is deleted stays watched, so recreating it rebuilds (cli#478)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var fx: Fixture = undefined; diff --git a/src/cli/pipeline/rebuild_lock_tests.zig b/src/cli/pipeline/rebuild_lock_tests.zig index 797d2c3c..259c496f 100644 --- a/src/cli/pipeline/rebuild_lock_tests.zig +++ b/src/cli/pipeline/rebuild_lock_tests.zig @@ -147,13 +147,13 @@ fn overlap(first_publishes: bool, second_publishes: bool, second_first: bool) !v } test "rebuild lock: overlapping sessions are serialized; both failing, in either order, leaves the original lock (cli#481)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; try overlap(false, false, false); // one fails, then two fails try overlap(false, false, true); // two fails, then one fails } test "rebuild lock: overlapping sessions end on the last published lock (cli#481)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; try overlap(true, false, false); // one publishes, two fails: one's lock try overlap(true, false, true); // two publishes, one fails: two's lock try overlap(false, true, false); // one fails, two publishes: two's lock @@ -161,7 +161,7 @@ test "rebuild lock: overlapping sessions end on the last published lock (cli#481 } test "rebuild lock: Ctrl+C while a rebuild waits for another session's transaction stops it cleanly (cli#481)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; var s: Sessions = .{}; try s.init(a); @@ -203,7 +203,7 @@ test "rebuild lock: Ctrl+C while a rebuild waits for another session's transacti } test "rebuild lock: the commit keeps a newer CLI's stamp written after the lock was staged (cli#481)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var s: Sessions = .{}; diff --git a/src/cli/pipeline/rebuild_replan.zig b/src/cli/pipeline/rebuild_replan.zig index ade0e875..2baed605 100644 --- a/src/cli/pipeline/rebuild_replan.zig +++ b/src/cli/pipeline/rebuild_replan.zig @@ -520,7 +520,7 @@ pub const Replanner = struct { for (args) |arg| { if (!std.mem.startsWith(u8, arg, "-Doptimize=")) try out.append(a, arg); } - if (mode) |m| try out.append(a, try std.fmt.allocPrint(a, "-Doptimize={s}", .{m})); + if (mode) |m| try out.append(a, try a.print("-Doptimize={s}", .{m})); return out.items; } diff --git a/src/cli/pipeline/rebuild_replan_tests.zig b/src/cli/pipeline/rebuild_replan_tests.zig index f67cdd4a..407a2ea0 100644 --- a/src/cli/pipeline/rebuild_replan_tests.zig +++ b/src/cli/pipeline/rebuild_replan_tests.zig @@ -46,7 +46,7 @@ test "watch replan re-reads the project and provider manifests on every call" { const Manifest = struct { fn writeAt(dir: std.Io.Dir, sub_path: []const u8, targets: []const u8, hooks: []const u8) !void { var buf: [1024]u8 = undefined; - const text = try std.fmt.bufPrint(&buf, ".{{ .name = \"pkg\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .targets = .{{ {s} }}, .hooks = .{{ {s} }} }}", .{ targets, hooks }); + const text = try std.mem.print(&buf, ".{{ .name = \"pkg\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .targets = .{{ {s} }}, .hooks = .{{ {s} }} }}", .{ targets, hooks }); try dir.writeFile(config.globalIo(), .{ .sub_path = sub_path, .data = text }); } fn write(dir: std.Io.Dir, hooks: []const u8) !void { @@ -152,7 +152,7 @@ const TwoStage = struct { const local_project = ".{ .name = \"game\", .plugins = .{ .{ .name = \"pkg\", .repo = \"local:../pkg\", .version = \"1.0.0\" } } }"; fn manifest(buf: []u8, targets: []const u8, hooks: []const u8) ![]const u8 { - return std.fmt.bufPrint(buf, ".{{ .name = \"pkg\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .targets = .{{ {s} }}, .hooks = .{{ {s} }} }}", .{ targets, hooks }); + return std.mem.print(buf, ".{{ .name = \"pkg\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .targets = .{{ {s} }}, .hooks = .{{ {s} }} }}", .{ targets, hooks }); } const Spy = struct { @@ -464,12 +464,12 @@ test "watch replan extracts a pinned provider once per changed pin" { std.crypto.hash.sha2.Sha256.hash(data, &digest, .{}); const hex = std.fmt.bytesToHex(digest, .lower); var name_buf: [128]u8 = undefined; - const name = try std.fmt.bufPrint(&name_buf, "home/provider-archives/{s}.tar.gz", .{&hex}); + const name = try std.mem.print(&name_buf, "home/provider-archives/{s}.tar.gz", .{&hex}); try dir.writeFile(config.globalIo(), .{ .sub_path = name, .data = data }); var commit_hex: [40]u8 = undefined; @memset(&commit_hex, commit); var lock_buf: [512]u8 = undefined; - const lock = try std.fmt.bufPrint(&lock_buf, "{{\"schema_version\":1,\"providers\":[{{\"package\":\"pkg\",\"repo\":\"example/pkg\",\"version\":\"1.0.0\",\"commit\":\"{s}\",\"sha256\":\"{s}\"}}]}}", .{ &commit_hex, &hex }); + const lock = try std.mem.print(&lock_buf, "{{\"schema_version\":1,\"providers\":[{{\"package\":\"pkg\",\"repo\":\"example/pkg\",\"version\":\"1.0.0\",\"commit\":\"{s}\",\"sha256\":\"{s}\"}}]}}", .{ &commit_hex, &hex }); try dir.writeFile(config.globalIo(), .{ .sub_path = "project/" ++ provider_github.lock_name, .data = lock }); } }; @@ -674,10 +674,10 @@ test "watched serve shutdown runs the replanned after-run hooks" { const Files = struct { fn write(dir: std.Io.Dir, version: []const u8, hook_id: []const u8) !void { var buf: [1024]u8 = undefined; - const manifest = try std.fmt.bufPrint(&buf, ".{{ .name = \"pkg\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .targets = .{{ \"probe-target\" }}, .hooks = .{{ .{{ .id = \"{s}\", .step = .run, .target = \"probe-target\", .when = .after, .build_step = \"tool\", .executable = \"bin/tool\" }} }} }}", .{hook_id}); + const manifest = try std.mem.print(&buf, ".{{ .name = \"pkg\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .targets = .{{ \"probe-target\" }}, .hooks = .{{ .{{ .id = \"{s}\", .step = .run, .target = \"probe-target\", .when = .after, .build_step = \"tool\", .executable = \"bin/tool\" }} }} }}", .{hook_id}); try dir.writeFile(config.globalIo(), .{ .sub_path = "pkg/plugin.labelle", .data = manifest }); var pbuf: [512]u8 = undefined; - const proj = try std.fmt.bufPrint(&pbuf, ".{{ .name = \"game\", .plugins = .{{ .{{ .name = \"pkg\", .repo = \"local:../pkg\", .version = \"{s}\" }} }} }}", .{version}); + const proj = try std.mem.print(&pbuf, ".{{ .name = \"game\", .plugins = .{{ .{{ .name = \"pkg\", .repo = \"local:../pkg\", .version = \"{s}\" }} }} }}", .{version}); try dir.writeFile(config.globalIo(), .{ .sub_path = "project/project.labelle", .data = proj }); } }; @@ -918,7 +918,7 @@ test "watch replan recomputes the effective optimize mode from the owner's defau const Manifest = struct { fn write(dir: std.Io.Dir, defaults: []const u8) !void { var buf: [512]u8 = undefined; - const text = try std.fmt.bufPrint(&buf, ".{{ .name = \"pkg\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .targets = .{{ \"probe-target\" }}, .target_defaults = .{{ {s} }} }}", .{defaults}); + const text = try std.mem.print(&buf, ".{{ .name = \"pkg\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .targets = .{{ \"probe-target\" }}, .target_defaults = .{{ {s} }} }}", .{defaults}); try dir.writeFile(config.globalIo(), .{ .sub_path = "pkg/plugin.labelle", .data = text }); } fn flags(args: []const []const u8) usize { diff --git a/src/cli/pipeline/rebuild_tests.zig b/src/cli/pipeline/rebuild_tests.zig index 65f674f2..94bb8695 100644 --- a/src/cli/pipeline/rebuild_tests.zig +++ b/src/cli/pipeline/rebuild_tests.zig @@ -25,7 +25,7 @@ test "watched rebuild gates the shader override after the before-generate hooks // Production wiring: the default IS the cold pipeline's preflight, // not a copy of it. - const default_gate = std.meta.fieldInfo(RebuildCtx, .shader_preflight).defaultValue() orelse return error.TestUnexpectedResult; + const default_gate = @import("../util.zig").fieldDefault(RebuildCtx, "shader_preflight") orelse return error.TestUnexpectedResult; try std.testing.expect(default_gate == material_toolchain.preflight); const Fixture = struct { @@ -114,7 +114,7 @@ test "watched rebuild runs the generate and build hook phases in order" { defer a.free(project); // Production wiring: the default runner IS the cold pipeline's. - const default_runner = std.meta.fieldInfo(RebuildCtx, .run_hook_phase).defaultValue() orelse return error.TestUnexpectedResult; + const default_runner = @import("../util.zig").fieldDefault(RebuildCtx, "run_hook_phase") orelse return error.TestUnexpectedResult; try std.testing.expect(default_runner == provider_hooks.runPhase); const Spy = struct { @@ -352,7 +352,7 @@ test "watched rebuild replans the hook phases on every rebuild" { }; defer ctx.deinit(); // Production wiring: the default prebuild runner IS the cold one. - const default_prebuild = std.meta.fieldInfo(RebuildCtx, .run_prebuild).defaultValue() orelse return error.TestUnexpectedResult; + const default_prebuild = @import("../util.zig").fieldDefault(RebuildCtx, "run_prebuild") orelse return error.TestUnexpectedResult; try std.testing.expect(default_prebuild == prebuild.runAll); // Rebuild 1: replanned once; the FRESH plans ran, the startup plans diff --git a/src/cli/pipeline/rebuild_transaction_tests.zig b/src/cli/pipeline/rebuild_transaction_tests.zig index 465c52b6..948dafdc 100644 --- a/src/cli/pipeline/rebuild_transaction_tests.zig +++ b/src/cli/pipeline/rebuild_transaction_tests.zig @@ -84,10 +84,10 @@ pub const Fixture = struct { pub fn write(fx: *Fixture, spec: Spec) !void { const io = config.globalIo(); var buf: [4096]u8 = undefined; - const manifest = try std.fmt.bufPrint(&buf, ".{{ .name = \"pkg\", .manifest_version = 2, .command_contract = \"{s}\", .targets = .{{ \"{s}\" }}, .target_defaults = .{{ {s} }}, .hooks = .{{ .{{ .id = \"serve\", .step = .run, .target = \"{s}\", .when = .replace, .build_step = \"tool\", .executable = \"bin/tool\", .watch = true }}, {s} }} }}", .{ spec.contract, target, spec.defaults, target, spec.hooks }); + const manifest = try std.mem.print(&buf, ".{{ .name = \"pkg\", .manifest_version = 2, .command_contract = \"{s}\", .targets = .{{ \"{s}\" }}, .target_defaults = .{{ {s} }}, .hooks = .{{ .{{ .id = \"serve\", .step = .run, .target = \"{s}\", .when = .replace, .build_step = \"tool\", .executable = \"bin/tool\", .watch = true }}, {s} }} }}", .{ spec.contract, target, spec.defaults, target, spec.hooks }); try fx.tmp.dir.writeFile(io, .{ .sub_path = "pkg/plugin.labelle", .data = manifest }); var pbuf: [2048]u8 = undefined; - const proj = try std.fmt.bufPrint(&pbuf, ".{{ .name = \"game\", .plugins = .{{ .{{ .name = \"pkg\", .repo = \"local:../pkg\", .version = \"{s}\" }} }}{s} }}", .{ spec.version, spec.project_extra }); + const proj = try std.mem.print(&pbuf, ".{{ .name = \"game\", .plugins = .{{ .{{ .name = \"pkg\", .repo = \"local:../pkg\", .version = \"{s}\" }} }}{s} }}", .{ spec.version, spec.project_extra }); try fx.tmp.dir.writeFile(io, .{ .sub_path = "project/project.labelle", .data = proj }); } @@ -199,7 +199,7 @@ pub fn rebuildCtx(fx: *Fixture, site: *provider_hooks.Site, replan: *Replanner, } test "rebuild transaction: a failure after the replan restores every replanned piece of state (cli#469)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; var fx: Fixture = undefined; try fx.init(a); @@ -266,7 +266,7 @@ test "rebuild transaction: a failure after the replan restores every replanned p } test "rebuild transaction: publication happens only after the after-build hooks, never after a failure" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; var fx: Fixture = undefined; try fx.init(a); @@ -306,7 +306,7 @@ test "rebuild transaction: publication happens only after the after-build hooks, } test "rebuild transaction: an edited prebuild step runs in the rebuild that sees it, and swaps the ignore set (cli#463)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; var fx: Fixture = undefined; try fx.init(a); @@ -353,7 +353,7 @@ test "rebuild transaction: an edited prebuild step runs in the rebuild that sees } test "rebuild transaction: a change the running replacement depends on publishes nothing" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; var fx: Fixture = undefined; try fx.init(a); @@ -403,7 +403,7 @@ test "rebuild transaction: a change the running replacement depends on publishes if (i == 3) { // Rewrite the manifest's replacement without `.watch`. var buf: [1024]u8 = undefined; - const manifest = try std.fmt.bufPrint(&buf, ".{{ .name = \"pkg\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .targets = .{{ \"{s}\" }}, .hooks = .{{ .{{ .id = \"serve\", .step = .run, .target = \"{s}\", .when = .replace, .build_step = \"tool\", .executable = \"bin/tool\" }} }} }}", .{ target, target }); + const manifest = try std.mem.print(&buf, ".{{ .name = \"pkg\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .targets = .{{ \"{s}\" }}, .hooks = .{{ .{{ .id = \"serve\", .step = .run, .target = \"{s}\", .when = .replace, .build_step = \"tool\", .executable = \"bin/tool\" }} }} }}", .{ target, target }); try fx.tmp.dir.writeFile(config.globalIo(), .{ .sub_path = "pkg/plugin.labelle", .data = manifest }); } Steps.runs = 0; @@ -440,7 +440,7 @@ fn rebuildOnThread(ctx: *RebuildCtx, ok: *bool) void { } test "rebuild transaction: cancelling reaps the in-flight child — provisioning, compile, after-build — and publishes nothing" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); const exe = @import("test_fixtures").child_exe; @@ -487,7 +487,7 @@ test "rebuild transaction: cancelling reaps the in-flight child — provisioning } test "rebuild transaction: an edited project's lock is staged privately and committed only with the rebuild" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; var fx: Fixture = undefined; try fx.init(a); @@ -559,13 +559,13 @@ test "rebuild transaction: an edited project's lock is staged privately and comm } test "rebuild transaction: a rebuild runs the cold pipeline's pre-passes and prebuild Python wiring on the re-read project" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); // Production wiring: the defaults ARE the cold pipeline's functions. - const default_prepass = std.meta.fieldInfo(RebuildCtx, .run_prepasses).defaultValue() orelse return error.TestUnexpectedResult; + const default_prepass = @import("../util.zig").fieldDefault(RebuildCtx, "run_prepasses") orelse return error.TestUnexpectedResult; try std.testing.expect(default_prepass == @import("generate.zig").corePrepasses); - const default_wire = std.meta.fieldInfo(RebuildCtx, .wire_prebuild_env).defaultValue() orelse return error.TestUnexpectedResult; + const default_wire = @import("../util.zig").fieldDefault(RebuildCtx, "wire_prebuild_env") orelse return error.TestUnexpectedResult; try std.testing.expect(default_wire == @import("install.zig").wirePrebuildPython); var fx: Fixture = undefined; @@ -586,7 +586,7 @@ test "rebuild transaction: a rebuild runs the cold pipeline's pre-passes and pre defer a.free(log); { var buf: [512]u8 = undefined; - const script = try std.fmt.bufPrint(&buf, "#!/bin/sh\necho assembler >> '{s}'\n", .{log}); + const script = try std.mem.print(&buf, "#!/bin/sh\necho assembler >> '{s}'\n", .{log}); try fx.tmp.dir.writeFile(io, .{ .sub_path = "asm-log", .data = script, .flags = .{ .permissions = .executable_file } }); } const asm_path = try fx.tmp.dir.realPathFileAlloc(io, "asm-log", a); @@ -643,7 +643,7 @@ test "rebuild transaction: a rebuild runs the cold pipeline's pre-passes and pre } test "rebuild transaction: a before-run hook's OWNING provider changing is a session change" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const a = std.testing.allocator; const io = config.globalIo(); var fx: Fixture = undefined; @@ -656,7 +656,7 @@ test "rebuild transaction: a before-run hook's OWNING provider changing is a ses const Project = struct { fn write(dir: std.Io.Dir, aux_version: []const u8) !void { var buf: [1024]u8 = undefined; - const text = try std.fmt.bufPrint(&buf, ".{{ .name = \"game\", .plugins = .{{ .{{ .name = \"pkg\", .repo = \"local:../pkg\", .version = \"1.0.0\" }}, .{{ .name = \"aux\", .repo = \"local:../aux\", .version = \"{s}\" }} }} }}", .{aux_version}); + const text = try std.mem.print(&buf, ".{{ .name = \"game\", .plugins = .{{ .{{ .name = \"pkg\", .repo = \"local:../pkg\", .version = \"1.0.0\" }}, .{{ .name = \"aux\", .repo = \"local:../aux\", .version = \"{s}\" }} }} }}", .{aux_version}); try dir.writeFile(config.globalIo(), .{ .sub_path = "project/project.labelle", .data = text }); } }; diff --git a/src/cli/pipeline/run.zig b/src/cli/pipeline/run.zig index 5a530d99..54c41a3e 100644 --- a/src/cli/pipeline/run.zig +++ b/src/cli/pipeline/run.zig @@ -133,7 +133,7 @@ pub fn launch( try extras.append(allocator, .{ .key = "LABELLE_HEADLESS_UNCAPPED", .value = "1" }); } if (parsed_args.headless_ticks) |n| { - const ticks_str = try std.fmt.bufPrint(&ticks_buf, "{d}", .{n}); + const ticks_str = try std.mem.print(&ticks_buf, "{d}", .{n}); try extras.append(allocator, .{ .key = "LABELLE_HEADLESS_TICKS", .value = ticks_str }); } } @@ -220,10 +220,10 @@ pub fn launch( // assembler emits `.exe`, so a suffix-less probe never // matches and would wrongly fall back to the legacy `game` name, // then fail to launch with FileNotFound (cli#309). - const exe_suffix = if (builtin.os.tag == .windows) ".exe" else ""; + const exe_suffix = if (builtin.target.os.tag == .windows) ".exe" else ""; const sanitized = try util.sanitizeExeName(allocator, parsed.name); defer allocator.free(sanitized); - const sanitized_exe = try std.fmt.allocPrint(allocator, "{s}{s}", .{ sanitized, exe_suffix }); + const sanitized_exe = try allocator.print("{s}{s}", .{ sanitized, exe_suffix }); defer allocator.free(sanitized_exe); const sanitized_full = try std.fs.path.join(allocator, &.{ target_dir, "zig-out", "bin", sanitized_exe }); defer allocator.free(sanitized_full); @@ -282,13 +282,13 @@ fn formatDuration(buf: []u8, ns: u64) []const u8 { const mins = secs / 60; const rem = secs % 60; return (if (secs == 0) - std.fmt.bufPrint(buf, "{d}ms", .{ns / std.time.ns_per_ms}) + std.mem.print(buf, "{d}ms", .{ns / std.time.ns_per_ms}) else if (mins > 0 and rem > 0) - std.fmt.bufPrint(buf, "{d}m{d}s", .{ mins, rem }) + std.mem.print(buf, "{d}m{d}s", .{ mins, rem }) else if (mins > 0) - std.fmt.bufPrint(buf, "{d}m", .{mins}) + std.mem.print(buf, "{d}m", .{mins}) else - std.fmt.bufPrint(buf, "{d}s", .{secs})) catch "?"; + std.mem.print(buf, "{d}s", .{secs})) catch "?"; } test "pipeline: run durations format as the notices print them" { diff --git a/src/cli/pipeline/screenshot.zig b/src/cli/pipeline/screenshot.zig index a4ec3d85..175e8462 100644 --- a/src/cli/pipeline/screenshot.zig +++ b/src/cli/pipeline/screenshot.zig @@ -81,7 +81,7 @@ pub const ScreenshotProbe = struct { /// Candidate `i`: 0 is the resolved path itself, then one per suffix. fn candidatePath(self: ScreenshotProbe, allocator: std.mem.Allocator, i: usize) ?[]u8 { if (i == 0) return allocator.dupe(u8, self.resolved) catch null; - return std.fmt.allocPrint(allocator, "{s}{s}", .{ self.resolved, screenshot_suffixes[i - 1] }) catch null; + return allocator.print("{s}{s}", .{ self.resolved, screenshot_suffixes[i - 1] }) catch null; } /// Report where the screenshot ACTUALLY landed, after the game has exited. @@ -163,7 +163,7 @@ pub const ScreenshotProbeSpec = struct { /// directory under a cwd-relative `.zig-cache/tmp/`, so a cwd-relative /// `run_cwd` addresses exactly the files the tmp dir holds. fn runCwd(allocator: std.mem.Allocator, tmp: std.testing.TmpDir) ![]u8 { - return std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}", .{tmp.sub_path}); + return allocator.print(".zig-cache/tmp/{s}", .{tmp.sub_path}); } test "a .png request the backend answered with .png.tga lands as a PNG" { diff --git a/src/cli/pipeline/session_key.zig b/src/cli/pipeline/session_key.zig index 3122e18a..a81c4a8c 100644 --- a/src/cli/pipeline/session_key.zig +++ b/src/cli/pipeline/session_key.zig @@ -153,14 +153,14 @@ pub const SessionKey = struct { }; const doc = try provider_github.parse(a, bytes, true); for (doc.providers) |pin| { - if (pin.matches(dep)) return std.fmt.allocPrint(a, "{s}@{s}#{s}", .{ pin.repo, pin.commit, pin.sha256 }); + if (pin.matches(dep)) return a.print("{s}@{s}#{s}", .{ pin.repo, pin.commit, pin.sha256 }); } return dep.repo; } /// `.labelle/_`: the output location a key names. pub fn outputOf(a: std.mem.Allocator, backend: []const u8, target: []const u8) ![]const u8 { - const name = try std.fmt.allocPrint(a, "{s}_{s}", .{ backend, target }); + const name = try a.print("{s}_{s}", .{ backend, target }); return std.fs.path.join(a, &.{ ".labelle", name }); } @@ -341,7 +341,7 @@ fn settingsDigest(a: std.mem.Allocator, root: []const u8, cfg: project_config.Pr defer a.free(path); const bytes = std.Io.Dir.cwd().readFileAlloc(config.globalIo(), path, a, .limited(16 * 1024 * 1024)) catch |err| switch (err) { // A missing file is its own state: creating it is a change. - error.FileNotFound => return [_]u8{0} ** 32, + error.FileNotFound => return @splat(0), else => return err, }; defer a.free(bytes); @@ -394,7 +394,7 @@ test "session key: every field the replacement depends on is reported, the first }.f }, .{ .what = "the provider source", .edit = struct { fn f(k: *SessionKey) void { - k.source = [_]u8{2} ** 32; + k.source = @splat(2); } }.f }, .{ .what = "the provider contract version", .edit = struct { @@ -444,7 +444,7 @@ test "session key: every field the replacement depends on is reported, the first }.f }, .{ .what = "the replacement's settings", .edit = struct { fn f(k: *SessionKey) void { - k.settings = [_]u8{1} ** 32; + k.settings = @splat(1); } }.f }, .{ @@ -529,7 +529,7 @@ test "session key: a remote provider's pin is the accepted lock entry, so a re-p var sha: [64]u8 = undefined; @memset(&sha, sha_digit); var buf: [512]u8 = undefined; - const text = try std.fmt.bufPrint(&buf, "{{\"schema_version\":1,\"providers\":[{{\"package\":\"pkg\",\"repo\":\"example/pkg\",\"version\":\"1.0.0\",\"commit\":\"1111111111111111111111111111111111111111\",\"sha256\":\"{s}\"}}]}}", .{&sha}); + const text = try std.mem.print(&buf, "{{\"schema_version\":1,\"providers\":[{{\"package\":\"pkg\",\"repo\":\"example/pkg\",\"version\":\"1.0.0\",\"commit\":\"1111111111111111111111111111111111111111\",\"sha256\":\"{s}\"}}]}}", .{&sha}); try dir.writeFile(config.globalIo(), .{ .sub_path = provider_github.lock_name, .data = text }); } }; diff --git a/src/cli/pipeline/testing.zig b/src/cli/pipeline/testing.zig index 26bdf019..b53edba9 100644 --- a/src/cli/pipeline/testing.zig +++ b/src/cli/pipeline/testing.zig @@ -35,7 +35,7 @@ pub fn okTool(a: std.mem.Allocator, dir: std.Io.Dir) ![:0]u8 { pub fn exitTool(a: std.mem.Allocator, dir: std.Io.Dir, name: []const u8, code: u8) ![:0]u8 { const io = @import("../config.zig").globalIo(); var buf: [64]u8 = undefined; - const script = try std.fmt.bufPrint(&buf, "#!/bin/sh\nexit {d}\n", .{code}); + const script = try std.mem.print(&buf, "#!/bin/sh\nexit {d}\n", .{code}); try dir.writeFile(io, .{ .sub_path = name, .data = script, .flags = .{ .permissions = .executable_file } }); return dir.realPathFileAlloc(io, name, a); } @@ -53,7 +53,7 @@ fn fakeDescribe(arena: std.mem.Allocator, argv: []const []const u8) ?[]const u8 const path = std.fs.path.join(arena, &.{ argv[3], "project.labelle" }) catch return null; const text = std.Io.Dir.cwd().readFileAlloc(config.globalIo(), path, arena, .limited(1 << 20)) catch return null; const backend: []const u8 = if (std.mem.indexOf(u8, text, ".backend = .null") != null) "null" else "probe"; - return std.fmt.allocPrint(arena, + return arena.print( \\{{"schema":"labelle.describe/v1","target":"{s}","target_dir":".labelle/{s}_{s}","backend":{{"name":"{s}","id":null,"repo":null,"version":null,"local_path":null}},"asset_format":"png","supported":true}} , .{ argv[5], backend, argv[5], backend }) catch null; } diff --git a/src/cli/plugin_path_key.zig b/src/cli/plugin_path_key.zig index 0c3c27f7..0f48f7e8 100644 --- a/src/cli/plugin_path_key.zig +++ b/src/cli/plugin_path_key.zig @@ -60,7 +60,7 @@ pub fn pluginCachePath( repo: []const u8, version: []const u8, ) (Error || std.mem.Allocator.Error)![]const u8 { - return pluginCachePathFor(allocator, builtin.os.tag, packages_dir, repo, version); + return pluginCachePathFor(allocator, builtin.target.os.tag, packages_dir, repo, version); } /// The fetcher's identity for a remote — a mirror of the assembler's @@ -95,9 +95,9 @@ pub fn problem(allocator: std.mem.Allocator, os: std.Target.Os.Tag, repo: []cons return null; const what = if (bad < 0x20 or bad == 0x7f) - try std.fmt.allocPrint(allocator, "contains control byte 0x{x:0>2}", .{bad}) + try allocator.print("contains control byte 0x{x:0>2}", .{bad}) else - try std.fmt.allocPrint(allocator, "contains '{c}', which {s} does not allow in a file name", .{ bad, @tagName(os) }); + try allocator.print("contains '{c}', which {s} does not allow in a file name", .{ bad, @tagName(os) }); defer allocator.free(what); // For the repo, the fetcher's own identity names the same remote without @@ -105,9 +105,9 @@ pub fn problem(allocator: std.mem.Allocator, os: std.Target.Os.Tag, repo: []cons // one copy-paste. const canonical = if (std.mem.eql(u8, which, "repo")) normalizeRemote(repo) else ""; if (canonical.len > 0 and firstBadByte(canonical, os) == null and !std.mem.eql(u8, canonical, repo)) { - return try std.fmt.allocPrint(allocator, "package {s} '{s}' cannot be used as a cache path: it {s}. Spell it '{s}' — the same remote", .{ which, value, what, canonical }); + return try allocator.print("package {s} '{s}' cannot be used as a cache path: it {s}. Spell it '{s}' — the same remote", .{ which, value, what, canonical }); } - return try std.fmt.allocPrint(allocator, "package {s} '{s}' cannot be used as a cache path: it {s}", .{ which, value, what }); + return try allocator.print("package {s} '{s}' cannot be used as a cache path: it {s}", .{ which, value, what }); } /// Print `problem` for the host (stderr). A no-op when the pair is usable. @@ -118,7 +118,7 @@ pub fn problem(allocator: std.mem.Allocator, os: std.Target.Os.Tag, repo: []cons pub fn report(repo: []const u8, version: []const u8) void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); - const msg = problem(arena.allocator(), builtin.os.tag, repo, version) catch { + const msg = problem(arena.allocator(), builtin.target.os.tag, repo, version) catch { std.debug.print("labelle: package repo '{s}' / version '{s}' cannot be used as a cache path on this OS\n", .{ repo, version }); return; } orelse return; @@ -201,7 +201,7 @@ test "plugin_path_key: problem names the field and byte, and suggests the canoni // A declaration longer than any small fixed buffer still gets its full // line; `report` builds it in an unbounded arena (PR #505 review). - const long_repo = "git+https://github.com/labelle-toolkit/" ++ "x" ** 1200; + const long_repo = "git+https://github.com/labelle-toolkit/" ++ &@as([1200]u8, @splat('x')); const long = (try problem(a, .windows, long_repo, "1.0.0")).?; - try testing.expect(std.mem.indexOf(u8, long, "Spell it 'github.com/labelle-toolkit/" ++ "x" ** 1200 ++ "'") != null); + try testing.expect(std.mem.indexOf(u8, long, "Spell it 'github.com/labelle-toolkit/" ++ &@as([1200]u8, @splat('x')) ++ "'") != null); } diff --git a/src/cli/plugin_slot.zig b/src/cli/plugin_slot.zig index 729f3529..34e272ca 100644 --- a/src/cli/plugin_slot.zig +++ b/src/cli/plugin_slot.zig @@ -40,7 +40,7 @@ const path_key = @import("plugin_path_key.zig"); /// failing. The archive slot comes from `plugin_path_key`, the mirror of the /// assembler's builder, so the two still agree on every usable spelling. pub fn resolveRemotePlugin(allocator: std.mem.Allocator, dep: project_config.PluginDep) ![]const u8 { - return resolveRemotePluginFor(allocator, builtin.os.tag, dep); + return resolveRemotePluginFor(allocator, builtin.target.os.tag, dep); } /// `resolveRemotePlugin` judged by `os`'s file-name rules (tests pin it). @@ -99,7 +99,7 @@ pub fn slotKey(allocator: std.mem.Allocator, repo: []const u8, name: []const u8) } } const readable = if (label.items.len == 0) "plugin" else label.items; - return std.fmt.allocPrint(allocator, "{s}-{x:0>16}", .{ readable, hasher.final() }); + return allocator.print("{s}-{x:0>16}", .{ readable, hasher.final() }); } /// The checkout an EXPLICIT override names for `dep`, when its slot and @@ -219,7 +219,7 @@ test "plugin slot: an EXPLICIT override wins, a discovered one or a dead source defer a.free(checkout); const marker_rel = "packages/local.origins/plugins/debug-ce1b0657dc37ae68"; - const explicit = try std.fmt.allocPrint(a, "# labelle local cache slot\nsource = {s}\nrevision = unknown\npinned = 0.1.0\nmode = explicit\n", .{checkout}); + const explicit = try a.print("# labelle local cache slot\nsource = {s}\nrevision = unknown\npinned = 0.1.0\nmode = explicit\n", .{checkout}); defer a.free(explicit); try tmp.dir.writeFile(io, .{ .sub_path = marker_rel, .data = explicit }); // Folded in at load time: the dep becomes LOCAL to its checkout for @@ -247,7 +247,7 @@ test "plugin slot: an EXPLICIT override wins, a discovered one or a dead source try testing.expect(!deps[0].isLocal()); // A discovered slot is the assembler's monorepo business, not ours. - const discovered = try std.fmt.allocPrint(a, "source = {s}\nmode = discovered\n", .{checkout}); + const discovered = try a.print("source = {s}\nmode = discovered\n", .{checkout}); defer a.free(discovered); try tmp.dir.writeFile(io, .{ .sub_path = marker_rel, .data = discovered }); try testing.expect(try explicitOverrideSource(a, debug_dep) == null); @@ -300,7 +300,7 @@ test "plugin slot: an unnameable repo/version/subdir is refused before any path } // The host entry point applies the host's rule. - if (builtin.os.tag == .windows) { + if (builtin.target.os.tag == .windows) { try testing.expectError(error.UnusableCachePath, resolveRemotePlugin(a, git)); } else { const host = try resolveRemotePlugin(a, git); diff --git a/src/cli/plugins.zig b/src/cli/plugins.zig index b731731a..5067e0d4 100644 --- a/src/cli/plugins.zig +++ b/src/cli/plugins.zig @@ -99,20 +99,20 @@ pub fn readPluginMeta(allocator: std.mem.Allocator, plugin_dir: []const u8) erro }; defer allocator.free(raw); - const raw_z = try allocator.dupeZ(u8, raw); + const raw_z = try allocator.dupeSentinel(u8, raw, 0); defer allocator.free(raw_z); - const parsed = std.zon.parse.fromSliceAlloc(ZonPluginMeta, allocator, raw_z, null, .{ - .ignore_unknown_fields = true, - }) catch |err| { + // Zig 0.17's ZON parser allocates the value in an arena and has no + // per-value free, so the parse gets a scratch arena of its own. + var zon_arena = std.heap.ArenaAllocator.init(allocator); + defer zon_arena.deinit(); + const parsed = @import("util.zig").parseZon(ZonPluginMeta, zon_arena.allocator(), raw_z, .{ .ignore_unknown_fields = true }) catch |err| { if (err == error.OutOfMemory) return error.OutOfMemory; std.debug.print("labelle: warning: could not parse '{s}': {s} — listing it without license/author\n", .{ manifest_path, @errorName(err) }); return null; }; - // The parser deep-copies strings; free the whole parsed value after - // re-duping the fields we keep so ownership is a single, simple - // `PluginMeta.deinit`. - defer std.zon.parse.free(allocator, parsed); + // The parser deep-copies strings into `zon_arena`; the fields we keep + // are re-duped so ownership is a single, simple `PluginMeta.deinit`. const name = try allocator.dupe(u8, parsed.name); errdefer allocator.free(name); diff --git a/src/cli/prebuild.zig b/src/cli/prebuild.zig index 271540ac..fe67e8fb 100644 --- a/src/cli/prebuild.zig +++ b/src/cli/prebuild.zig @@ -484,7 +484,7 @@ pub fn renderArgv(allocator: std.mem.Allocator, argv: []const []const u8) ![]u8 /// per-call-site label a feed consumer can render). Pure; writes into /// `buf`, which must be `progress.max_detail_len` bytes. pub fn failureDetail(buf: []u8, index: usize, total: usize) []const u8 { - return std.fmt.bufPrint(buf, "prebuild step {d}/{d} failed", .{ index + 1, total }) catch + return std.mem.print(buf, "prebuild step {d}/{d} failed", .{ index + 1, total }) catch "prebuild step failed"; } @@ -526,7 +526,7 @@ pub fn runStep( else prebuild_relay.stdoutRoute( opts.route_stdout_to_stderr, - builtin.os.tag, + builtin.target.os.tag, std.Io.File.stderr().isTty(io) catch false, ); @@ -1049,7 +1049,7 @@ pub const RecipeFingerprintSpec = struct { /// `.run` edited. POSIX only. pub const end_to_end = struct { test "changing .run alone forces a re-run" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const io = config.globalIo(); @@ -1097,7 +1097,7 @@ pub const RecipeFingerprintSpec = struct { } test "the fingerprint is persisted under .labelle/" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const io = config.globalIo(); @@ -1118,7 +1118,7 @@ pub const RecipeFingerprintSpec = struct { } test "an untracked step writes no state file" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const io = config.globalIo(); @@ -1211,7 +1211,7 @@ pub const NoPrebuildIsInertSpec = struct { pub const RunStepSpec = struct { pub const exit_codes = struct { test "a successful step returns 0" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; @@ -1224,7 +1224,7 @@ pub const RunStepSpec = struct { } test "a failing step's exact exit code is returned, not collapsed to 1" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; @@ -1245,7 +1245,7 @@ pub const RunStepSpec = struct { /// still failing a relay that waits for the descendant. pub const relay_is_bounded = struct { fn elapsedNs(relay_test: RelayTest) !u64 { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const io = config.globalIo(); @@ -1270,7 +1270,7 @@ pub const RunStepSpec = struct { pub const cwd_is_project_root = struct { test "the step runs with the project root as cwd" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const io = config.globalIo(); @@ -1292,7 +1292,7 @@ pub const RunStepSpec = struct { pub const no_shell_interpretation = struct { test "argv is passed verbatim — no shell metacharacter expansion" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const io = config.globalIo(); @@ -1319,7 +1319,7 @@ pub const RunStepSpec = struct { pub const spawn_failure = struct { test "a missing program reports PrebuildSpawnFailed, not a crash" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; @@ -1340,7 +1340,7 @@ pub const RunStepSpec = struct { pub const RunAllSpec = struct { pub const ordering = struct { test "steps run in declared order" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const io = config.globalIo(); @@ -1363,7 +1363,7 @@ pub const RunAllSpec = struct { // first has recorded what produced `gen.txt`. Run 1 proves the // conservative default (no record = run), run 2 the skip. test "a step whose outputs are current is skipped on the next run" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const io = config.globalIo(); @@ -1392,7 +1392,7 @@ pub const RunAllSpec = struct { } test "a step with no inputs/outputs runs unconditionally" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const io = config.globalIo(); @@ -1428,7 +1428,7 @@ pub const RunAllSpec = struct { // validating inside the execution loop let step 1 mutate the // project before step 2 was found to be malformed. test "a malformed LATER step stops the valid first step from running" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const io = config.globalIo(); @@ -1453,7 +1453,7 @@ pub const RunAllSpec = struct { } test "an empty argv[0] in a later step is caught the same way" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const io = config.globalIo(); @@ -1481,7 +1481,7 @@ pub const RunAllSpec = struct { /// not reloaded onto a stale bundle. pub const non_fatal_mode = struct { test "a failing step returns an error instead of exiting the process" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; @@ -1496,7 +1496,7 @@ pub const RunAllSpec = struct { } test "a succeeding step still runs normally in non-fatal mode" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var tmp = std.testing.tmpDir(.{}); defer tmp.cleanup(); const io = config.globalIo(); @@ -1540,13 +1540,7 @@ pub const ParsePrebuildSpec = struct { ; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); - const cfg = try std.zon.parse.fromSliceAlloc( - project_config.ProjectConfig, - arena.allocator(), - src, - null, - .{ .ignore_unknown_fields = true }, - ); + const cfg = try @import("util.zig").parseZon(project_config.ProjectConfig, arena.allocator(), src, .{ .ignore_unknown_fields = true }); try std.testing.expectEqual(@as(usize, 1), cfg.prebuild.len); try std.testing.expectEqualStrings("python3", cfg.prebuild[0].run[0]); @@ -1566,13 +1560,7 @@ pub const ParsePrebuildSpec = struct { ; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); - const cfg = try std.zon.parse.fromSliceAlloc( - project_config.ProjectConfig, - arena.allocator(), - src, - null, - .{ .ignore_unknown_fields = true }, - ); + const cfg = try @import("util.zig").parseZon(project_config.ProjectConfig, arena.allocator(), src, .{ .ignore_unknown_fields = true }); try std.testing.expectEqual(@as(usize, 0), cfg.prebuild[0].inputs.len); try std.testing.expectEqual(@as(usize, 0), cfg.prebuild[0].outputs.len); @@ -1582,13 +1570,7 @@ pub const ParsePrebuildSpec = struct { @setEvalBranchQuota(10000); var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); - const cfg = try std.zon.parse.fromSliceAlloc( - project_config.ProjectConfig, - arena.allocator(), - ".{ .name = \"demo\" }", - null, - .{ .ignore_unknown_fields = true }, - ); + const cfg = try @import("util.zig").parseZon(project_config.ProjectConfig, arena.allocator(), ".{ .name = \"demo\" }", .{ .ignore_unknown_fields = true }); try std.testing.expectEqual(@as(usize, 0), cfg.prebuild.len); } }; diff --git a/src/cli/prebuild_relay.zig b/src/cli/prebuild_relay.zig index f565c39b..6e161579 100644 --- a/src/cli/prebuild_relay.zig +++ b/src/cli/prebuild_relay.zig @@ -285,7 +285,7 @@ pub const RelayOwnershipSpec = struct { sink: ?std.Io.File = null, fn begin(f: *Fixture) !void { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const fds = try std.Io.Threaded.pipe2(.{ .CLOEXEC = true }); const read_end: std.Io.File = .{ .handle = fds[0], .flags = .{ .nonblocking = false } }; f.hooks.write_end = .{ .handle = fds[1], .flags = .{ .nonblocking = false } }; @@ -343,7 +343,7 @@ pub const RelayOwnershipSpec = struct { } test "a partial line is written out at finish, before the handover" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const io = std.testing.io; const sink_fds = try std.Io.Threaded.pipe2(.{ .CLOEXEC = true }); const sink_read: std.Io.File = .{ .handle = sink_fds[0], .flags = .{ .nonblocking = false } }; diff --git a/src/cli/progress.zig b/src/cli/progress.zig index f9c4745b..d2cc88fc 100644 --- a/src/cli/progress.zig +++ b/src/cli/progress.zig @@ -500,7 +500,7 @@ pub const Reporter = struct { self.mutex.unlock(self.io); if (terminal) return; var buf: [max_detail_len]u8 = undefined; - const detail = std.fmt.bufPrint(&buf, "{s} failed", .{stage}) catch "build failed"; + const detail = std.mem.print(&buf, "{s} failed", .{stage}) catch "build failed"; self.finishFailed(exit_code, detail); } diff --git a/src/cli/project_config.zig b/src/cli/project_config.zig index acdb7d0f..87d298c6 100644 --- a/src/cli/project_config.zig +++ b/src/cli/project_config.zig @@ -468,20 +468,20 @@ pub const ProjectConfig = struct { /// generate it). `error.InvalidDeclaredTarget` when `.platform` is not an /// enum literal. Pure: parses `source`, reads nothing else. pub fn declaredTarget(a: std.mem.Allocator, source: [:0]const u8) !?[]const u8 { - var ast = try std.zig.Ast.parse(a, source, .zon); + var ast = try std.zig.Ast.parse(a, source, .{ .mode = .zon }); defer ast.deinit(a); if (ast.errors.len != 0) return null; // The owning project parser diagnoses it. var zoir = try std.zig.ZonGen.generate(a, ast, .{ .parse_str_lits = false }); defer zoir.deinit(a); if (zoir.hasCompileErrors()) return null; - const fields = switch (std.zig.Zoir.Node.Index.root.get(zoir)) { + const fields = switch (std.zig.Zoir.Node.Index.root.get(&zoir)) { .struct_literal => |fields| fields, else => return null, }; for (fields.names, 0..) |name, i| { - if (!std.mem.eql(u8, name.get(zoir), "platform")) continue; - return switch (fields.vals.at(@intCast(i)).get(zoir)) { - .enum_literal => |literal| try a.dupe(u8, literal.get(zoir)), + if (!std.mem.eql(u8, name.get(&zoir), "platform")) continue; + return switch (fields.vals.at(@intCast(i)).get(&zoir)) { + .enum_literal => |literal| try a.dupe(u8, literal.get(&zoir)), else => error.InvalidDeclaredTarget, }; } @@ -506,7 +506,7 @@ test "declaredTarget: `.platform` is read as a name, any name" { var arena = std.heap.ArenaAllocator.init(a); defer arena.deinit(); const src: [:0]const u8 = ".{ .name = \"x\", .platform = .probe, .asset_compression = .{ .probe = .astc, .desktop = .png } }"; - const cfg = try std.zon.parse.fromSliceAlloc(ProjectConfig, arena.allocator(), src, null, .{ .ignore_unknown_fields = true }); + const cfg = try @import("util.zig").parseZon(ProjectConfig, arena.allocator(), src, .{ .ignore_unknown_fields = true }); try std.testing.expectEqualStrings(default_target, cfg.declared_target); } @@ -522,6 +522,6 @@ test "a target block the CLI does not model still parses (the assembler owns its \\.{ .name = "legacy", .probe_target = .{ .package_name = "com.x.y", .orientation = .landscape, .immersive_mode = true }, \\ .other_target = .{ .app_name = "Legacy", .bundle_id = "com.x.y", .minimum = "15.0", .orientation = .sensor_landscape } } ; - const cfg = try std.zon.parse.fromSliceAlloc(ProjectConfig, arena.allocator(), src, null, .{ .ignore_unknown_fields = true }); + const cfg = try @import("util.zig").parseZon(ProjectConfig, arena.allocator(), src, .{ .ignore_unknown_fields = true }); try std.testing.expectEqualStrings("legacy", cfg.name); } diff --git a/src/cli/project_lock.zig b/src/cli/project_lock.zig index e7b2173d..3d659a4a 100644 --- a/src/cli/project_lock.zig +++ b/src/cli/project_lock.zig @@ -341,7 +341,7 @@ test "project lock: Ctrl+C or a cancellation ends the wait, and nothing is held } test "project lock: a symbolic link at the lock path is refused and never written through (cli#481)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; // links need a privilege there + if (builtin.target.os.tag == .windows) return error.SkipZigTest; // links need a privilege there const a = std.testing.allocator; const io = config.globalIo(); var t = try Tmp.init(a); diff --git a/src/cli/provider_cache.zig b/src/cli/provider_cache.zig index 96c689ce..431663a3 100644 --- a/src/cli/provider_cache.zig +++ b/src/cli/provider_cache.zig @@ -41,11 +41,11 @@ pub fn canonicalId(a: std.mem.Allocator, dep: project.PluginDep, real_dir: []con var digest: [32]u8 = undefined; std.crypto.hash.sha2.Sha256.hash(key, &digest, .{}); const hex = std.fmt.bytesToHex(digest[0..16].*, .lower); - return std.fmt.allocPrint(a, "local/{s}-{s}", .{ try readableName(a, basename(real_dir)), &hex }); + return a.print("local/{s}-{s}", .{ try readableName(a, basename(real_dir)), &hex }); } const repo = try github.projectRepo(dep.repo); const slash = std.mem.indexOfScalar(u8, repo, '/').?; - return std.fmt.allocPrint(a, "{s}/{s}/{s}", .{ + return a.print("{s}/{s}/{s}", .{ github_host, try segment(a, repo[0..slash]), try segment(a, repo[slash + 1 ..]), @@ -79,16 +79,16 @@ fn segment(a: std.mem.Allocator, raw: []const u8) ![]const u8 { var out = try std.ascii.allocLowerString(a, raw); if (contract.windowsReservedDeviceName(out)) { const dot = std.mem.indexOfScalar(u8, out, '.') orelse out.len; - out = try std.fmt.allocPrint(a, "{s}~{s}", .{ out[0..dot], out[dot..] }); + out = try a.print("{s}~{s}", .{ out[0..dot], out[dot..] }); } - if (std.mem.endsWith(u8, out, ".")) out = try std.fmt.allocPrint(a, "{s}~", .{out}); + if (std.mem.endsWith(u8, out, ".")) out = try a.print("{s}~", .{out}); return out; } /// `/providers//`, with the host's separators. /// Pure: the caller creates it. pub fn dirPath(a: std.mem.Allocator, cache_root: []const u8, dep: project.PluginDep, real_dir: []const u8) ![]const u8 { - const id = try canonicalId(a, dep, real_dir, builtin.os.tag == .windows); + const id = try canonicalId(a, dep, real_dir, builtin.target.os.tag == .windows); var parts: std.ArrayList([]const u8) = .empty; try parts.appendSlice(a, &.{ cache_root, providers_dir }); var it = std.mem.splitScalar(u8, id, '/'); @@ -129,13 +129,13 @@ test "provider cache: a pinned provider is keyed by its normalised repository" { var names: std.ArrayList([]const u8) = .empty; try names.appendSlice(a, &.{ "con", "prn", "aux", "nul", "conin$", "conout$" }); for (1..10) |n| { - try names.append(a, try std.fmt.allocPrint(a, "com{d}", .{n})); - try names.append(a, try std.fmt.allocPrint(a, "lpt{d}", .{n})); + try names.append(a, try a.print("com{d}", .{n})); + try names.append(a, try a.print("lpt{d}", .{n})); } for (names.items) |name| { for ([_][]const u8{ "", ".tools", ".tar.gz", "." }) |suffix| { for ([_]bool{ false, true }) |upper| { - const raw = try std.fmt.allocPrint(a, "{s}{s}", .{ name, suffix }); + const raw = try a.print("{s}{s}", .{ name, suffix }); if (upper) _ = std.ascii.upperString(raw, raw); const escaped = try segment(a, raw); try std.testing.expect(!contract.windowsReservedDeviceName(escaped)); @@ -178,7 +178,7 @@ test "provider cache: the directory sits under the cache root's providers/" { var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); - const root = if (builtin.os.tag == .windows) "C:\\home" else "/home"; + const root = if (builtin.target.os.tag == .windows) "C:\\home" else "/home"; const got = try dirPath(a, root, .{ .name = "probe", .repo = "github.com/o/n", .version = "1.0.0" }, "/unused"); try std.testing.expectEqualStrings(try std.fs.path.join(a, &.{ root, "providers", "github.com", "o", "n" }), got); } diff --git a/src/cli/provider_contract.zig b/src/cli/provider_contract.zig index a838a7fa..74cdc9af 100644 --- a/src/cli/provider_contract.zig +++ b/src/cli/provider_contract.zig @@ -394,12 +394,12 @@ pub const Context = struct { /// rather than written as null. pub fn jsonStringify(self: Context, jws: anytype) !void { try jws.beginObject(); - inline for (std.meta.fields(Context)) |field| { - const value = @field(self, field.name); - const optional = comptime std.mem.eql(u8, field.name, "build_number") or std.mem.eql(u8, field.name, "run"); - const run_gated = comptime std.mem.eql(u8, field.name, "target_dir"); - const toolchain_gated = comptime std.mem.eql(u8, field.name, "cache_dir") or std.mem.eql(u8, field.name, "env_file"); - const final_step_gated = comptime std.mem.eql(u8, field.name, "final_step"); + inline for (@typeInfo(Context).@"struct".field_names) |field_name| { + const value = @field(self, field_name); + const optional = comptime std.mem.eql(u8, field_name, "build_number") or std.mem.eql(u8, field_name, "run"); + const run_gated = comptime std.mem.eql(u8, field_name, "target_dir"); + const toolchain_gated = comptime std.mem.eql(u8, field_name, "cache_dir") or std.mem.eql(u8, field_name, "env_file"); + const final_step_gated = comptime std.mem.eql(u8, field_name, "final_step"); const write = if (optional) value != null else if (run_gated) @@ -411,8 +411,8 @@ pub const Context = struct { else true; if (write) { - try jws.objectField(field.name); - if (comptime std.mem.eql(u8, field.name, "run")) { + try jws.objectField(field_name); + if (comptime std.mem.eql(u8, field_name, "run")) { try value.?.write(jws, self.contract_version); } else try jws.write(value); } diff --git a/src/cli/provider_dispatch.zig b/src/cli/provider_dispatch.zig index f200f1a3..d3eacad2 100644 --- a/src/cli/provider_dispatch.zig +++ b/src/cli/provider_dispatch.zig @@ -359,7 +359,7 @@ pub fn requirePinnedAt(a: std.mem.Allocator, lock_path: []const u8, provider: Pr return error.MissingProjectLock; }; const Lock = struct { plugins: []const project.PluginDep = &.{} }; - const lock = try std.zon.parse.fromSliceAlloc(Lock, a, try a.dupeZ(u8, lock_bytes), null, .{ .ignore_unknown_fields = true }); + const lock = try @import("util.zig").parseZon(Lock, a, try a.dupeSentinel(u8, lock_bytes, 0), .{ .ignore_unknown_fields = true }); try validatePin(provider.dep, lock.plugins); if (!provider.verified) { std.debug.print("labelle: remote provider '{s}' is unpinned. Run labelle providers resolve, review the pins, then repeat with --accept.\n", .{provider.dep.name}); @@ -375,7 +375,7 @@ fn isHelp(arg: []const u8) bool { /// A canonical child must be strictly beneath its canonical parent. pub fn contained(parent: []const u8, child: []const u8) bool { if (parent.len == 0) return false; - const prefix = if (builtin.os.tag == .windows) + const prefix = if (builtin.target.os.tag == .windows) child.len > parent.len and std.ascii.eqlIgnoreCase(parent, child[0..parent.len]) else std.mem.startsWith(u8, child, parent) and child.len > parent.len; @@ -384,8 +384,8 @@ pub fn contained(parent: []const u8, child: []const u8) bool { } fn executable(a: std.mem.Allocator, prefix: []const u8, relative: []const u8) ![]const u8 { - const suffix = if (builtin.os.tag == .windows) ".exe" else ""; - const path = try std.fs.path.join(a, &.{ prefix, try std.fmt.allocPrint(a, "{s}{s}", .{ relative, suffix }) }); + const suffix = if (builtin.target.os.tag == .windows) ".exe" else ""; + const path = try std.fs.path.join(a, &.{ prefix, try a.print("{s}{s}", .{ relative, suffix }) }); const resolved = try real(a, path); if (!contained(try real(a, prefix), resolved)) return error.EscapingProviderExecutable; const stat = try std.Io.Dir.cwd().statFile(config.globalIo(), resolved, .{}); @@ -682,6 +682,27 @@ pub fn ensureCacheDir(a: std.mem.Allocator, host: Host, provider: Provider) ![]c return canonicalDir(a, try provider_cache.dirPath(a, host.cache_root, provider.dep, provider.dir)); } +/// The global compiler cache a provider tool is BUILT with: a sibling of the +/// shared one under LABELLE_HOME, never holding package tarballs. +fn toolBuildGlobalCache(a: std.mem.Allocator, host: Host) ![]const u8 { + return std.fs.path.join(a, &.{ host.cache_root, zig_cache.PROVIDER_TOOL_GLOBAL_CACHE_SUBDIR }); +} + +test "a provider tool is built with a global cache that is not the shared package cache" { + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); + const home = try std.fs.path.join(a, &.{ "home", "labelle" }); + const shared = try std.fs.path.join(a, &.{ home, zig_cache.GLOBAL_CACHE_SUBDIR }); + const host: Host = .{ .zig = "zig", .cache_root = home, .global_cache = shared, .packages = try std.fs.path.join(a, &.{ shared, "p" }) }; + const private = try toolBuildGlobalCache(a, host); + try std.testing.expect(!std.mem.eql(u8, private, host.global_cache)); + // Under LABELLE_HOME, and neither inside the shared cache nor around it. + try std.testing.expect(std.mem.startsWith(u8, private, home)); + try std.testing.expect(!std.mem.startsWith(u8, private, shared)); + try std.testing.expect(!std.mem.startsWith(u8, host.packages, private)); +} + /// Build the tool in a fresh isolated prefix, verify the declared executable, /// write the context file and run it. Returns the tool's exit status; the /// workspace is removed whatever happens. @@ -710,7 +731,11 @@ pub fn runTool(a: std.mem.Allocator, host: Host, root: []const u8, provider: Pro var env = try runner.buildZigEnv(a, &.{}); defer env.deinit(); // Keep relative LABELLE_HOME stable when child cwd changes to the package. - try env.put("ZIG_GLOBAL_CACHE_DIR", host.global_cache); + // The tool's BUILD gets a global cache of its own, whose `p/` holds no + // package tarball (`zig_cache.PROVIDER_TOOL_GLOBAL_CACHE_SUBDIR`: Zig + // 0.17.1 panics under `--system` on a lazy dependency whose tarball is + // in the global cache). The tool itself runs with the shared one. + try env.put("ZIG_GLOBAL_CACHE_DIR", try toolBuildGlobalCache(a, host)); try env.put("ZIG_LOCAL_CACHE_DIR", try std.fs.path.join(a, &.{ host.cache_root, zig_cache.LOCAL_CACHE_SUBDIR })); try env.put("LABELLE_HOME", host.cache_root); // Zig owns the complete source/dependency/compiler/options cache identity. @@ -723,6 +748,7 @@ pub fn runTool(a: std.mem.Allocator, host: Host, root: []const u8, provider: Pro else try runner.runZigInheritWithEnv(a, provider.dir, build_argv, null, &env); if (build_code != 0) return build_code; + try env.put("ZIG_GLOBAL_CACHE_DIR", host.global_cache); if (!contained(run_dir, try real(a, prefix))) return error.EscapingProviderInstall; const exe = try executable(a, prefix, tool.executable); const wire = try manifest.negotiate(provider.meta.command_contract orelse return error.MissingCommandContract); @@ -773,8 +799,8 @@ fn runStdoutToStderr(cwd: []const u8, argv: []const []const u8, env: *const std. fn exitStatus(term: std.process.Child.Term) u8 { return switch (term) { .exited => |code| code, - .signal => |sig| 128 +% @as(u8, @truncate(@intFromEnum(sig))), - .stopped => |sig| 128 +% @as(u8, @truncate(@intFromEnum(sig))), + .signal => |sig| 128 +% @as(u8, @truncate(@backingInt(sig))), + .stopped => |sig| 128 +% @as(u8, @truncate(@backingInt(sig))), .unknown => 1, }; } @@ -841,8 +867,7 @@ test "provider dispatch: only a built-in command's name is reserved" { for (reserved) |name| { if (std.mem.eql(u8, name, "providers")) continue; var found = false; - inline for (@typeInfo(Command).@"enum".fields) |field| { - const tag = field.name; + inline for (@typeInfo(Command).@"enum".field_names) |tag| { const bare = if (comptime std.mem.endsWith(u8, tag, "_cmd")) tag[0 .. tag.len - "_cmd".len] else tag; found = found or std.mem.eql(u8, name, bare); } diff --git a/src/cli/provider_dispatch_test.zig b/src/cli/provider_dispatch_test.zig index ce70140e..4951f021 100644 --- a/src/cli/provider_dispatch_test.zig +++ b/src/cli/provider_dispatch_test.zig @@ -35,7 +35,7 @@ test "provider dispatch: a hook ToolRun yields a valid hook context, and none wi var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); - const abs = if (builtin.os.tag == .windows) "C:\\proj" else "/proj"; + const abs = if (builtin.target.os.tag == .windows) "C:\\proj" else "/proj"; const run: ToolRun = .{ .invocation = .{ .kind = .hook, .id = "stamp", .step = .build, .phase = .after }, .needs_project = true, @@ -70,7 +70,7 @@ test "provider dispatch: build_number reaches only a provider whose range admits var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); - const abs = if (builtin.os.tag == .windows) "C:\\proj" else "/proj"; + const abs = if (builtin.target.os.tag == .windows) "C:\\proj" else "/proj"; const run: ToolRun = .{ .invocation = .{ .kind = .hook, .id = "pack", .step = .bundle, .phase = .replace }, .needs_project = true, @@ -128,7 +128,7 @@ test "provider dispatch: target_dir and run options reach only a provider whose var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); - const abs = if (builtin.os.tag == .windows) "C:\\proj" else "/proj"; + const abs = if (builtin.target.os.tag == .windows) "C:\\proj" else "/proj"; const env = [_]contract.RunEnv{ .{ .name = "LABELLE_SCENE", .value = "x" }, .{ .name = "LABELLE_SCREENSHOT_PATH", .value = "s" }, @@ -194,7 +194,7 @@ test "provider dispatch: cache_dir and env_file reach only a provider whose rang var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); - const abs = if (builtin.os.tag == .windows) "C:\\proj" else "/proj"; + const abs = if (builtin.target.os.tag == .windows) "C:\\proj" else "/proj"; const run: ToolRun = .{ .invocation = .{ .kind = .hook, .id = "toolchain", .step = .generate, .phase = .before }, .needs_project = true, @@ -300,7 +300,7 @@ test "provider dispatch: an unread remote package defers its references under .u const Manifests = struct { fn write(dir: std.Io.Dir, sub_path: []const u8, name: []const u8, hook: []const u8) !void { var buf: [512]u8 = undefined; - const text = try std.fmt.bufPrint(&buf, ".{{ .name = \"{s}\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .hooks = .{{ {s} }} }}", .{ name, hook }); + const text = try std.mem.print(&buf, ".{{ .name = \"{s}\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .hooks = .{{ {s} }} }}", .{ name, hook }); try dir.writeFile(config.globalIo(), .{ .sub_path = sub_path, .data = text }); } }; @@ -413,7 +413,7 @@ test "provider dispatch: a remote repo the host cannot name is reported, never p try std.testing.expectEqual(@as(usize, 1), found.providers.len); try std.testing.expectEqualStrings("pkg-a", found.providers[0].meta.name); try std.testing.expectEqualStrings("rem", found.unresolved[0]); - if (builtin.os.tag == .windows) { + if (builtin.target.os.tag == .windows) { // Refused by the path builder: an unavailable package, with the cause. try std.testing.expectEqual(@as(usize, 1), found.unavailable.len); try std.testing.expectEqualStrings("rem", found.unavailable[0].package); diff --git a/src/cli/provider_doctor.zig b/src/cli/provider_doctor.zig index d51708b3..d44ac001 100644 --- a/src/cli/provider_doctor.zig +++ b/src/cli/provider_doctor.zig @@ -471,7 +471,7 @@ const Recorder = struct { for (self.stdouts) |entry| if (std.mem.eql(u8, entry[0], step.label)) { stdout.* = entry[1]; }; - try self.calls.append(self.a, try std.fmt.allocPrint(self.a, "{s}:{s}", .{ step.label, command.executable })); + try self.calls.append(self.a, try self.a.print("{s}:{s}", .{ step.label, command.executable })); for (self.errors) |label| if (std.mem.eql(u8, label, step.label)) return error.ProviderCompilerMissing; for (self.exit_codes) |entry| if (std.mem.eql(u8, entry[0], step.label)) return entry[1]; return 0; @@ -730,7 +730,7 @@ test "provider doctor: one host resolution per doctor, failure included, and eve for ([_][]const u8{ "project", "pkg-a", "pkg-b" }) |dir| try tmp.dir.createDirPath(io, dir); const root = try tmp.dir.realPathFileAlloc(io, "project", a); for ([_][2][]const u8{ .{ "pkg-a", "a" }, .{ "pkg-b", "b" } }) |pkg| { - const text = try std.fmt.allocPrint(a, ".{{ .name = \"{s}\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .namespace = \"{s}\", .commands = .{{ .{{ .name = \"doctor\", .build_step = \"t\", .executable = \"bin/t\", .help = \"h\" }} }} }}", .{ pkg[0], pkg[1] }); + const text = try a.print(".{{ .name = \"{s}\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .namespace = \"{s}\", .commands = .{{ .{{ .name = \"doctor\", .build_step = \"t\", .executable = \"bin/t\", .help = \"h\" }} }} }}", .{ pkg[0], pkg[1] }); try tmp.dir.writeFile(io, .{ .sub_path = try std.fs.path.join(a, &.{ pkg[0], "plugin.labelle" }), .data = text }); } const deps = ".{ .name = \"pkg-a\", .repo = \"local:../pkg-a\", .version = \"1.0.0\" }, .{ .name = \"pkg-b\", .repo = \"local:../pkg-b\", .version = \"1.0.0\" }"; diff --git a/src/cli/provider_doctor_json.zig b/src/cli/provider_doctor_json.zig index d48e9ea9..805f3d9a 100644 --- a/src/cli/provider_doctor_json.zig +++ b/src/cli/provider_doctor_json.zig @@ -71,10 +71,10 @@ pub fn validate(a: std.mem.Allocator, stdout: []const u8) !Validated { const cap = std.json.parseFromSliceLeaky(Capability, a, trimmed, .{ .ignore_unknown_fields = true, .allocate = .alloc_always, - }) catch |err| return .{ .invalid = try std.fmt.allocPrint(a, "its stdout is not one capability object ({s})", .{@errorName(err)}) }; + }) catch |err| return .{ .invalid = try a.print("its stdout is not one capability object ({s})", .{@errorName(err)}) }; if (cap.id.len == 0) return .{ .invalid = "its capability id is empty" }; for (cap.items, 0..) |item, i| { - if (item.id.len == 0) return .{ .invalid = try std.fmt.allocPrint(a, "item {d} of capability '{s}' has an empty id", .{ i, cap.id }) }; + if (item.id.len == 0) return .{ .invalid = try a.print("item {d} of capability '{s}' has an empty id", .{ i, cap.id }) }; } return .{ .capability = cap }; } @@ -87,7 +87,7 @@ fn owner(outcome: provider_doctor.Outcome) []const u8 { fn subject(a: std.mem.Allocator, outcome: provider_doctor.Outcome) ![]const u8 { if (outcome.package.len == 0) return outcome.label; - return std.fmt.allocPrint(a, "labelle {s} {s} (provider '{s}')", .{ outcome.label, provider_doctor.command_name, outcome.package }); + return a.print("labelle {s} {s} (provider '{s}')", .{ outcome.label, provider_doctor.command_name, outcome.package }); } fn errorItem(name: []const u8, detail: []const u8, hint: ?[]const u8) Item { @@ -114,7 +114,7 @@ pub const Contribution = struct { capability: Capability, reported: bool }; fn synthetic(a: std.mem.Allocator, outcome: provider_doctor.Outcome, required: bool, item: Item) !Contribution { return .{ .reported = false, .capability = .{ - .id = try std.fmt.allocPrint(a, "{s}{s}", .{ synthetic_prefix, owner(outcome) }), + .id = try a.print("{s}{s}", .{ synthetic_prefix, owner(outcome) }), .required = required, .ok = false, .items = try a.dupe(Item, &.{item}), @@ -131,19 +131,19 @@ pub fn fromOutcome(a: std.mem.Allocator, outcome: provider_doctor.Outcome) !Cont var failed = cap; failed.ok = false; if (cap.ok) { - const note = errorItem(name, try std.fmt.allocPrint(a, "exited {d} although its report says ok", .{code}), null); + const note = errorItem(name, try a.print("exited {d} although its report says ok", .{code}), null); failed.items = try std.mem.concat(a, Item, &.{ cap.items, &.{note} }); } return .{ .capability = failed, .reported = true }; }, .invalid => |why| { - const detail = try std.fmt.allocPrint(a, "exited {d}, and {s}", .{ code, why }); + const detail = try a.print("exited {d}, and {s}", .{ code, why }); return synthetic(a, outcome, true, errorItem(name, detail, null)); }, } } const err = outcome.err orelse error.ProviderDoctorDidNotRun; - const detail = try std.fmt.allocPrint(a, "did not run: {s}", .{@errorName(err)}); + const detail = try a.print("did not run: {s}", .{@errorName(err)}); return synthetic(a, outcome, !outcome.warning, errorItem(name, detail, hintFor(err))); } @@ -201,7 +201,7 @@ pub fn aggregate(a: std.mem.Allocator, core: []const Capability, report: ?provid try out.append(a, cap); continue; } - const detail = try std.fmt.allocPrint(a, "capability '{s}' is reported by providers {s}; a capability id must have one owner", .{ cap.id, names.items }); + const detail = try a.print("capability '{s}' is reported by providers {s}; a capability id must have one owner", .{ cap.id, names.items }); try out.append(a, .{ .id = cap.id, .required = true, diff --git a/src/cli/provider_env.zig b/src/cli/provider_env.zig index 834725d7..71b52af2 100644 --- a/src/cli/provider_env.zig +++ b/src/cli/provider_env.zig @@ -24,7 +24,7 @@ const builtin = @import("builtin"); const contract = @import("provider_contract.zig"); const config = @import("config.zig"); -pub const native_windows = builtin.os.tag == .windows; +pub const native_windows = builtin.target.os.tag == .windows; pub const Var = struct { name: []const u8, value: []const u8 }; @@ -66,7 +66,7 @@ pub const Diagnostic = struct { }; fn fail(a: std.mem.Allocator, diag: *Diagnostic, comptime fmt: []const u8, args: anytype) error{ InvalidEnvFile, OutOfMemory } { - diag.message = try std.fmt.allocPrint(a, fmt, args); + diag.message = try a.print(fmt, args); return error.InvalidEnvFile; } @@ -282,13 +282,13 @@ pub const Accumulator = struct { for (self.options.items) |option| { for (base) |arg| { if (!setsBuildOption(arg, option.name)) continue; - diag.message = try std.fmt.allocPrint(a, "build option '-D{s}={s}' from hook '{s}' conflicts with the CLI's '{s}'", .{ option.name, option.value, option.hook, arg }); + diag.message = try a.print("build option '-D{s}={s}' from hook '{s}' conflicts with the CLI's '{s}'", .{ option.name, option.value, option.hook, arg }); return error.BuildOptionConflict; } } const out = try a.alloc([]const u8, base.len + self.options.items.len); @memcpy(out[0..base.len], base); - for (self.options.items, out[base.len..]) |option, *arg| arg.* = try std.fmt.allocPrint(a, "-D{s}={s}", .{ option.name, option.value }); + for (self.options.items, out[base.len..]) |option, *arg| arg.* = try a.print("-D{s}={s}", .{ option.name, option.value }); return out; } @@ -402,13 +402,13 @@ test "provider env: names, reserved names and PATH entries" { defer arena.deinit(); const a = arena.allocator(); for ([_][]const u8{ "", "1ABC", "HAS SPACE", "A=B", "A-B", "É" }) |name| { - const doc = try std.fmt.allocPrint(a, "{{\"set\":[{{\"name\":\"{s}\",\"value\":\"x\"}}]}}", .{name}); + const doc = try a.print("{{\"set\":[{{\"name\":\"{s}\",\"value\":\"x\"}}]}}", .{name}); try parseFails(a, doc, false, "invalid variable name"); } // Reserved: the fixed CLI-owned table; PATH is pointed at path_prepend. try parseFails(a, "{\"set\":[{\"name\":\"PATH\",\"value\":\"/x\"}]}", false, "path_prepend"); for ([_][]const u8{ "ZIG_GLOBAL_CACHE_DIR", "ZIG_LOCAL_CACHE_DIR", "LABELLE_HOME", "LABELLE_CONTEXT", "LABELLE_OFFLINE", "LABELLE_ZIG", "LABELLE_ASSEMBLER" }) |name| { - const doc = try std.fmt.allocPrint(a, "{{\"set\":[{{\"name\":\"{s}\",\"value\":\"x\"}}]}}", .{name}); + const doc = try a.print("{{\"set\":[{{\"name\":\"{s}\",\"value\":\"x\"}}]}}", .{name}); try parseFails(a, doc, false, "reserved"); } // Not a prefix ban: a LABELLE_* name the CLI does not own stays settable. @@ -424,7 +424,7 @@ test "provider env: names, reserved names and PATH entries" { _ = try parseOk(a, "{\"set\":[{\"name\":\"A\",\"value\":\"1\"},{\"name\":\"a\",\"value\":\"1\"}]}", false); // PATH entries: absolute for the host, no separator inside. for ([_][]const u8{ "relative/bin", "./bin", "" }) |dir| { - const doc = try std.fmt.allocPrint(a, "{{\"path_prepend\":[\"{s}\"]}}", .{dir}); + const doc = try a.print("{{\"path_prepend\":[\"{s}\"]}}", .{dir}); try parseFails(a, doc, false, "not an absolute path"); try parseFails(a, doc, true, "not an absolute path"); } @@ -513,7 +513,7 @@ test "provider env: apply and compose make the merge on a real environment map" var composed = try acc.compose(std.testing.allocator, &base); defer composed.deinit(); try std.testing.expectEqualStrings("v", composed.get("PROBE_VAR").?); - const expected_path = try std.fmt.allocPrint(a, "{s}{c}/usr/bin", .{ abs, pathSeparator(native_windows) }); + const expected_path = try a.print("{s}{c}/usr/bin", .{ abs, pathSeparator(native_windows) }); try std.testing.expectEqualStrings(expected_path, composed.get("PATH").?); // The base is untouched: the next build composes from it again. try std.testing.expectEqualStrings("old", base.get("PROBE_VAR").?); @@ -616,11 +616,11 @@ test "provider env: build_options are parsed and validated (wire 1.6.0)" { } try std.testing.expectEqual(@as(usize, 0), (try parseOk(a, "{\"build_options\":[]}", false)).build_options.?.len); for ([_][]const u8{ "", "1abc", "-dash", "has space", "a=b", "a.b" }) |name| { - const doc = try std.fmt.allocPrint(a, "{{\"build_options\":[{{\"name\":\"{s}\",\"value\":\"x\"}}]}}", .{name}); + const doc = try a.print("{{\"build_options\":[{{\"name\":\"{s}\",\"value\":\"x\"}}]}}", .{name}); try parseFails(a, doc, false, "invalid build option name"); } for (cli_owned_build_options) |name| { - const doc = try std.fmt.allocPrint(a, "{{\"build_options\":[{{\"name\":\"{s}\",\"value\":\"x\"}}]}}", .{name}); + const doc = try a.print("{{\"build_options\":[{{\"name\":\"{s}\",\"value\":\"x\"}}]}}", .{name}); try parseFails(a, doc, false, "owned by the CLI"); } try parseFails(a, "{\"build_options\":[{\"name\":\"a\",\"value\":\"x\\ny\"}]}", false, "line break"); diff --git a/src/cli/provider_github/archive.zig b/src/cli/provider_github/archive.zig index cdc291d0..2897ed16 100644 --- a/src/cli/provider_github/archive.zig +++ b/src/cli/provider_github/archive.zig @@ -13,7 +13,7 @@ const uniqueName = files_mod.uniqueName; pub fn archivePath(a: std.mem.Allocator, pin: Pin) ![]const u8 { try pin.validate(); - return std.fs.path.join(a, &.{ try cacheRoot(a), "provider-archives", try std.fmt.allocPrint(a, "{s}.tar.gz", .{pin.sha256}) }); + return std.fs.path.join(a, &.{ try cacheRoot(a), "provider-archives", try a.print("{s}.tar.gz", .{pin.sha256}) }); } /// The compressed size bound of every provider archive read or download. @@ -23,7 +23,7 @@ pub fn download(a: std.mem.Allocator, url: []const u8, dest: []const u8, max_siz const result = try util.runCmd(a, &.{ "curl", "--fail", "--silent", "--show-error", "--location", "--proto", "=https", "--proto-redir", "=https", "--connect-timeout", - "30", "--max-time", "180", "--max-filesize", try std.fmt.allocPrint(a, "{d}", .{max_size}), + "30", "--max-time", "180", "--max-filesize", try a.print("{d}", .{max_size}), "--output", dest, url, }); if (result.term != .exited or result.term.exited != 0) { diff --git a/src/cli/provider_github/fetch.zig b/src/cli/provider_github/fetch.zig index acd16a6a..9c145c68 100644 --- a/src/cli/provider_github/fetch.zig +++ b/src/cli/provider_github/fetch.zig @@ -231,7 +231,7 @@ const Fixture = struct { /// A pin over `bytes`, served by the fake codeload at its archive URL. fn pin(a: std.mem.Allocator, package: []const u8, commit_digit: u8, bytes: []const u8) !Pin { - return .{ .package = package, .repo = try std.fmt.allocPrint(a, "example/{s}", .{package}), .version = "1.0.0", .commit = try a.dupe(u8, &([_]u8{commit_digit} ** 40)), .sha256 = try files.sha256Hex(a, bytes) }; + return .{ .package = package, .repo = try a.print("example/{s}", .{package}), .version = "1.0.0", .commit = try a.dupe(u8, &@as([40]u8, @splat(commit_digit))), .sha256 = try files.sha256Hex(a, bytes) }; } fn serve(a: std.mem.Allocator, p: Pin, bytes: []const u8) !void { diff --git a/src/cli/provider_github/files.zig b/src/cli/provider_github/files.zig index b6275297..f0e42789 100644 --- a/src/cli/provider_github/files.zig +++ b/src/cli/provider_github/files.zig @@ -16,7 +16,7 @@ pub fn cacheRoot(a: std.mem.Allocator) ![]const u8 { pub fn uniqueName(a: std.mem.Allocator, prefix: []const u8) ![]const u8 { var random: [16]u8 = undefined; config.globalIo().random(&random); - return std.fmt.allocPrint(a, "{s}-{s}", .{ prefix, std.fmt.bytesToHex(random, .lower) }); + return a.print("{s}-{s}", .{ prefix, std.fmt.bytesToHex(random, .lower) }); } pub fn sha256Hex(a: std.mem.Allocator, data: []const u8) ![]const u8 { diff --git a/src/cli/provider_github/pin.zig b/src/cli/provider_github/pin.zig index 1fcd07ba..4f15c4ad 100644 --- a/src/cli/provider_github/pin.zig +++ b/src/cli/provider_github/pin.zig @@ -41,7 +41,7 @@ pub const Pin = struct { pub fn archiveUrl(self: Pin, a: std.mem.Allocator) ![]const u8 { try self.validate(); - return std.fmt.allocPrint(a, "https://codeload.github.com/{s}/tar.gz/{s}", .{ self.repo, self.commit }); + return a.print("https://codeload.github.com/{s}/tar.gz/{s}", .{ self.repo, self.commit }); } }; @@ -235,7 +235,7 @@ test "provider github: immutable GitHub identity and strict document" { } test "provider github: a project repo matches its pin in the GitHub forms the assembler fetches" { - const pin: Pin = .{ .package = "fixture", .repo = "owner/repo", .version = "1.0.0", .commit = "1" ** 40, .sha256 = "a" ** 64 }; + const pin: Pin = .{ .package = "fixture", .repo = "owner/repo", .version = "1.0.0", .commit = &@as([40]u8, @splat('1')), .sha256 = &@as([64]u8, @splat('a')) }; const Case = struct { repo: []const u8, matches: bool }; for ([_]Case{ // The assembler's form and the bare registry form. @@ -296,7 +296,7 @@ test "provider github: lock schema 2 records the registry source; schema 1 stays var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); - const pin = "{\"package\":\"fixture\",\"repo\":\"owner/fixture\",\"version\":\"1.0.0\",\"commit\":\"" ++ "1" ** 40 ++ "\",\"sha256\":\"" ++ "a" ** 64 ++ "\"}"; + const pin = "{\"package\":\"fixture\",\"repo\":\"owner/fixture\",\"version\":\"1.0.0\",\"commit\":\"" ++ &@as([40]u8, @splat('1')) ++ "\",\"sha256\":\"" ++ &@as([64]u8, @splat('a')) ++ "\"}"; const one = try parseLock(a, "{\"schema_version\":1,\"providers\":[" ++ pin ++ "]}"); try std.testing.expect(one.registry == null); try std.testing.expectEqual(@as(usize, 1), one.document.providers.len); diff --git a/src/cli/provider_github/preview.zig b/src/cli/provider_github/preview.zig index 76561ec0..a9e5bd56 100644 --- a/src/cli/provider_github/preview.zig +++ b/src/cli/provider_github/preview.zig @@ -259,12 +259,12 @@ test "provider github: accept is bound to the recorded preview" { // field is rejected by name, the lock is never written, and the stale // preview stays so the diagnostic can be compared against it. var repointed = fx.pin; - repointed.commit = "2" ** 40; + repointed.commit = &@as([40]u8, @splat('2')); try fx.publish(a, repointed); try std.testing.expectError(error.ProviderPreviewMismatch, fx.run(a, true)); try std.testing.expect(!try fx.exists(a, lock_name)); var rehashed = fx.pin; - rehashed.sha256 = "0" ** 64; + rehashed.sha256 = &@as([64]u8, @splat('0')); try fx.publish(a, rehashed); try std.testing.expectError(error.ProviderPreviewMismatch, fx.run(a, true)); try std.testing.expect(!try fx.exists(a, lock_name)); @@ -318,7 +318,7 @@ test "provider github: an edited preview file fails its digest and is not accept const path = try std.fs.path.join(a, &.{ fx.root, preview_name }); const original = try read(a, path, 1024 * 1024); // Same shape, one hex digit of the reviewed commit changed: the digest no longer verifies. - const edited = try std.mem.replaceOwned(u8, a, original, fx.pin.commit, "2" ** 40); + const edited = try std.mem.replaceOwned(u8, a, original, fx.pin.commit, &@as([40]u8, @splat('2'))); try std.testing.expect(!std.mem.eql(u8, original, edited)); try std.Io.Dir.cwd().writeFile(config.globalIo(), .{ .sub_path = path, .data = edited }); try std.testing.expectError(error.ProviderPreviewCorrupt, loadPreview(a, fx.root)); diff --git a/src/cli/provider_github/registry_lookup.zig b/src/cli/provider_github/registry_lookup.zig index 82d23d61..cd6a2862 100644 --- a/src/cli/provider_github/registry_lookup.zig +++ b/src/cli/provider_github/registry_lookup.zig @@ -119,7 +119,7 @@ pub fn canonicalSource(a: std.mem.Allocator, source: []const u8) ![]const u8 { pub fn projectSource(a: std.mem.Allocator, root: []const u8, canonical: []const u8) ![]const u8 { if (isUrl(canonical)) return canonical; const relative = try std.fs.path.relative(a, root, null, root, canonical); - if (builtin.os.tag == .windows) std.mem.replaceScalar(u8, relative, '\\', '/'); + if (builtin.target.os.tag == .windows) std.mem.replaceScalar(u8, relative, '\\', '/'); return relative; } @@ -313,8 +313,8 @@ pub fn offlineRequested(a: std.mem.Allocator) bool { const AcceptFixture = @import("test_fixtures.zig").AcceptFixture; -const commit_a = "1" ** 40; -const hash_a = "a" ** 64; +const commit_a = &@as([40]u8, @splat('1')); +const hash_a = &@as([64]u8, @splat('a')); fn testRecord(comptime package: []const u8, comptime version: []const u8, comptime targets: []const u8) []const u8 { return "{\"package\":\"" ++ package ++ "\",\"repo\":\"owner/" ++ package ++ "\",\"version\":\"" ++ version ++ @@ -427,7 +427,7 @@ test "provider registry lookup: offline never fetches; a failed, unparseable or } test "provider registry lookup: the download capture is capped in the CLI, not only by curl" { - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); @@ -505,7 +505,7 @@ test "provider registry lookup: a record that does not verify is a generic miss // Another snapshot's document under this digest. try std.json.Stringify.valueAlloc(a, Accepted{ .source = fork, .document_sha256 = digest, .document = other_doc }, .{}), // A CLI 2.0.0 record: no digest binds its source to its document. - try std.fmt.allocPrint(a, "{{\"schema_version\":1,\"source\":\"{s}\",\"document\":{s}}}", .{ fork, other_json }), + try a.print("{{\"schema_version\":1,\"source\":\"{s}\",\"document\":{s}}}", .{ fork, other_json }), // A source that is not one printable line. try std.json.Stringify.valueAlloc(a, Accepted{ .source = "https://example.test/\x1b[2Jx", .document_sha256 = digest, .document = custom_doc }, .{}), // Not a record at all. @@ -667,7 +667,7 @@ test "provider registry lookup: a local source is compared in the lock's project } test "provider registry lookup: a local source on another Windows drive is kept absolute" { - if (builtin.os.tag != .windows) return error.SkipZigTest; + if (builtin.target.os.tag != .windows) return error.SkipZigTest; var arena = std.heap.ArenaAllocator.init(std.testing.allocator); defer arena.deinit(); const a = arena.allocator(); diff --git a/src/cli/provider_github/resolve.zig b/src/cli/provider_github/resolve.zig index 1311ada0..73df10fc 100644 --- a/src/cli/provider_github/resolve.zig +++ b/src/cli/provider_github/resolve.zig @@ -194,12 +194,12 @@ test "provider github: accept is bound to the whole registry document, not only const a = arena.allocator(); var fx = try AcceptFixture.init(a); defer fx.deinit(); - const fixture_record = try std.fmt.allocPrint(a, "{{\"package\":\"fixture\",\"repo\":\"{s}\",\"version\":\"{s}\",\"commit\":\"{s}\",\"sha256\":\"{s}\",\"namespace\":\"probe\",\"targets\":[]}}", .{ fx.pin.repo, fx.pin.version, fx.pin.commit, fx.pin.sha256 }); - const other_record = "{\"package\":\"other\",\"repo\":\"example/other\",\"version\":\"1.0.0\",\"commit\":\"" ++ "3" ** 40 ++ "\",\"sha256\":\"" ++ "0" ** 64 ++ "\",\"namespace\":null,\"targets\":[\"TARGET\"]}"; + const fixture_record = try a.print("{{\"package\":\"fixture\",\"repo\":\"{s}\",\"version\":\"{s}\",\"commit\":\"{s}\",\"sha256\":\"{s}\",\"namespace\":\"probe\",\"targets\":[]}}", .{ fx.pin.repo, fx.pin.version, fx.pin.commit, fx.pin.sha256 }); + const other_record = "{\"package\":\"other\",\"repo\":\"example/other\",\"version\":\"1.0.0\",\"commit\":\"" ++ &@as([40]u8, @splat('3')) ++ "\",\"sha256\":\"" ++ &@as([64]u8, @splat('0')) ++ "\",\"namespace\":null,\"targets\":[\"TARGET\"]}"; const Doc = struct { fn of(al: std.mem.Allocator, fixture: []const u8, other_target: []const u8, defaults: []const u8, sep: []const u8) ![]const u8 { const other = try std.mem.replaceOwned(u8, al, other_record, "TARGET", other_target); - return std.fmt.allocPrint(al, "{{\"schema_version\":2,{s}\"defaults\":[{s}],{s}\"providers\":[{s},{s}{s}]}}", .{ sep, defaults, sep, fixture, sep, other }); + return al.print("{{\"schema_version\":2,{s}\"defaults\":[{s}],{s}\"providers\":[{s},{s}{s}]}}", .{ sep, defaults, sep, fixture, sep, other }); } }; // (1) Schema 2 swapped for an otherwise identical schema 1: same pins, diff --git a/src/cli/provider_github/test_fixtures.zig b/src/cli/provider_github/test_fixtures.zig index 5eba57a1..cbf2192e 100644 --- a/src/cli/provider_github/test_fixtures.zig +++ b/src/cli/provider_github/test_fixtures.zig @@ -63,8 +63,8 @@ pub const AcceptFixture = struct { try tmp.dir.createDirPath(io, "project"); try tmp.dir.createDirPath(io, "home/provider-archives"); const data = try gzipArchive(a); - const pin: Pin = .{ .package = "fixture", .repo = "example/fixture", .version = "1.0.0", .commit = "1" ** 40, .sha256 = try sha256Hex(a, data) }; - try tmp.dir.writeFile(io, .{ .sub_path = try std.fmt.allocPrint(a, "home/provider-archives/{s}.tar.gz", .{pin.sha256}), .data = data }); + const pin: Pin = .{ .package = "fixture", .repo = "example/fixture", .version = "1.0.0", .commit = &@as([40]u8, @splat('1')), .sha256 = try sha256Hex(a, data) }; + try tmp.dir.writeFile(io, .{ .sub_path = try a.print("home/provider-archives/{s}.tar.gz", .{pin.sha256}), .data = data }); try tmp.dir.writeFile(io, .{ .sub_path = "project/project.labelle", .data = ".{ .name = \"game\", .plugins = .{ .{ .name = \"fixture\", .repo = \"example/fixture\", .version = \"1.0.0\" } } }" }); var self: AcceptFixture = .{ .tmp = tmp, .root = root, .home = home, .registry = try std.fs.path.join(a, &.{ base, "providers.json" }), .pin = pin }; try self.publish(a, pin); @@ -74,7 +74,7 @@ pub const AcceptFixture = struct { /// Rewrite the project's declaration of the fixture with `repo` as its `.repo`. pub fn declare(self: *AcceptFixture, a: std.mem.Allocator, repo: []const u8) !void { - const text = try std.fmt.allocPrint(a, ".{{ .name = \"game\", .plugins = .{{ .{{ .name = \"fixture\", .repo = \"{s}\", .version = \"1.0.0\" }} }} }}", .{repo}); + const text = try a.print(".{{ .name = \"game\", .plugins = .{{ .{{ .name = \"fixture\", .repo = \"{s}\", .version = \"1.0.0\" }} }} }}", .{repo}); try std.Io.Dir.cwd().writeFile(config.globalIo(), .{ .sub_path = try std.fs.path.join(a, &.{ self.root, "project.labelle" }), .data = text }); } @@ -91,7 +91,7 @@ pub const AcceptFixture = struct { /// A schema-2 registry (#411) listing `pin` with the given ownership /// claims, as JSON fragments (`"probe"` or `null`; `"t1","t2"`). pub fn schemaTwo(a: std.mem.Allocator, pin: Pin, namespace: []const u8, targets: []const u8) ![]const u8 { - return std.fmt.allocPrint(a, "{{\"schema_version\":2,\"defaults\":[],\"providers\":[{{\"package\":\"{s}\",\"repo\":\"{s}\",\"version\":\"{s}\",\"commit\":\"{s}\",\"sha256\":\"{s}\",\"namespace\":{s},\"targets\":[{s}]}}]}}", .{ pin.package, pin.repo, pin.version, pin.commit, pin.sha256, namespace, targets }); + return a.print("{{\"schema_version\":2,\"defaults\":[],\"providers\":[{{\"package\":\"{s}\",\"repo\":\"{s}\",\"version\":\"{s}\",\"commit\":\"{s}\",\"sha256\":\"{s}\",\"namespace\":{s},\"targets\":[{s}]}}]}}", .{ pin.package, pin.repo, pin.version, pin.commit, pin.sha256, namespace, targets }); } pub fn publishSchemaTwo(self: *AcceptFixture, a: std.mem.Allocator, namespace: []const u8, targets: []const u8) !void { diff --git a/src/cli/provider_hooks.zig b/src/cli/provider_hooks.zig index 3fde2ae1..c628f992 100644 --- a/src/cli/provider_hooks.zig +++ b/src/cli/provider_hooks.zig @@ -392,7 +392,7 @@ pub fn runPhaseReporting(site: *Site, list: []const Planned, step: contract.Step const outcome_file: ?[]const u8 = if (outcome_dir) |dir| try std.fs.path.join(a, &.{ dir, run_outcome.file_name }) else null; var hook_run_options = run_options; if (hook_run_options) |*options| options.outcome_file = outcome_file; - if (site.reporter) |r| r.beginPhaseOrStep(progressPhase(step), try std.fmt.allocPrint(a, "hook {s}", .{planned.qualified})); + if (site.reporter) |r| r.beginPhaseOrStep(progressPhase(step), try a.print("hook {s}", .{planned.qualified})); std.debug.print("labelle: running {s} hook '{s}' for {s} ({s})\n", .{ @tagName(phase), planned.qualified, @tagName(step), site.target }); const code = try site.run_tool(a, site.host.?, site.root, provider, .{ .build_step = planned.hook.build_step, .executable = planned.hook.executable }, .{ .invocation = invocation, @@ -457,7 +457,7 @@ fn privateDir(a: std.mem.Allocator, host: dispatch.Host, kind: []const u8) ![]co fn absorbEnvFile(site: *Site, a: std.mem.Allocator, planned: Planned, invocation: contract.Invocation, path: []const u8) !void { const qualified = planned.qualified; const read = provider_env.readFile(a, path, site.env_file_cap) catch |err| switch (err) { - error.StreamTooLong => return rejectEnvFile(site, qualified, try std.fmt.allocPrint(a, "the file is larger than the {d}-byte cap", .{site.env_file_cap})), + error.StreamTooLong => return rejectEnvFile(site, qualified, try a.print("the file is larger than the {d}-byte cap", .{site.env_file_cap})), else => return err, }; const bytes = read orelse return; @@ -469,12 +469,12 @@ fn absorbEnvFile(site: *Site, a: std.mem.Allocator, planned: Planned, invocation if (file.build_options != null) { const provider = planned.provider; if (!provider.meta.ownsTarget(site.target)) - return rejectEnvFile(site, qualified, try std.fmt.allocPrint(a, "build_options may only come from the owner of target '{s}', not package '{s}'", .{ site.target, provider.meta.name })); + return rejectEnvFile(site, qualified, try a.print("build_options may only come from the owner of target '{s}', not package '{s}'", .{ site.target, provider.meta.name })); if (!contract.buildOptionsSlot(invocation)) - return rejectEnvFile(site, qualified, try std.fmt.allocPrint(a, "build_options may only come from a 'before generate' or 'before build' hook, not '{s} {s}'", .{ @tagName(invocation.phase.?), @tagName(invocation.step.?) })); + return rejectEnvFile(site, qualified, try a.print("build_options may only come from a 'before generate' or 'before build' hook, not '{s} {s}'", .{ @tagName(invocation.phase.?), @tagName(invocation.step.?) })); const wire = manifest.negotiate(provider.meta.command_contract orelse "") catch "none"; if (!contract.carriesBuildOptions(wire)) - return rejectEnvFile(site, qualified, try std.fmt.allocPrint(a, "build_options need provider contract >= {s}; package '{s}' speaks {s}", .{ contract.build_options_since, provider.meta.name, wire })); + return rejectEnvFile(site, qualified, try a.print("build_options need provider contract >= {s}; package '{s}' speaks {s}", .{ contract.build_options_since, provider.meta.name, wire })); } site.env.add(site.backing, a, qualified, file, &diag) catch |err| switch (err) { error.InvalidEnvFile => { @@ -763,7 +763,7 @@ test "provider hooks: an unpinned provider is refused before the host compiler i } }; // Production wiring: the default resolver IS the real one. - try std.testing.expect((std.meta.fieldInfo(Site, .resolve_host).defaultValue() orelse return error.TestUnexpectedResult) == dispatch.resolveHost); + try std.testing.expect((@import("util.zig").fieldDefault(Site, "resolve_host") orelse return error.TestUnexpectedResult) == dispatch.resolveHost); var unpinned = Fixture.provider("pkg", &.{}, &.{Fixture.hook("h", .build, "desktop", .after, &.{})}); unpinned.dep.repo = "example/pkg"; unpinned.verified = false; diff --git a/src/cli/provider_hooks_env_test.zig b/src/cli/provider_hooks_env_test.zig index ac98af01..16565474 100644 --- a/src/cli/provider_hooks_env_test.zig +++ b/src/cli/provider_hooks_env_test.zig @@ -105,7 +105,7 @@ const Harness = struct { fn planned(self: *Harness, i: usize) hooks.Planned { const entry = self.provider.meta.hooks[i]; - return .{ .provider = &self.provider, .hook = entry, .qualified = std.fmt.allocPrint(self.arena.allocator(), "pkg/{s}", .{entry.id}) catch unreachable }; + return .{ .provider = &self.provider, .hook = entry, .qualified = self.arena.allocator().print("pkg/{s}", .{entry.id}) catch unreachable }; } fn out(self: *Harness) []const u8 { diff --git a/src/cli/provider_hooks_run_test.zig b/src/cli/provider_hooks_run_test.zig index 8c0f26d1..af9a0456 100644 --- a/src/cli/provider_hooks_run_test.zig +++ b/src/cli/provider_hooks_run_test.zig @@ -115,7 +115,7 @@ test "provider hooks: each phase runs on a scratch arena that is freed on return }; const out = try std.fs.path.join(a, &.{ root, "zig-out" }); // Production wiring: the default launcher IS the real one. - try std.testing.expect((std.meta.fieldInfo(Site, .run_tool).defaultValue() orelse return error.TestUnexpectedResult) == dispatch.runTool); + try std.testing.expect((@import("util.zig").fieldDefault(Site, "run_tool") orelse return error.TestUnexpectedResult) == dispatch.runTool); try std.testing.expectEqual(@as(u8, 0), try runPhase(&site, &.{planned}, .build, .after, out)); try std.testing.expectEqual(@as(usize, 1), Spy.calls); diff --git a/src/cli/provider_manifest.zig b/src/cli/provider_manifest.zig index f700ccd9..b7695513 100644 --- a/src/cli/provider_manifest.zig +++ b/src/cli/provider_manifest.zig @@ -142,38 +142,38 @@ pub fn splitHookRef(ref: []const u8) ?HookRef { /// The stable hook identity of contract §6. pub fn qualifiedId(a: std.mem.Allocator, package: []const u8, id: []const u8) ![]const u8 { - return std.fmt.allocPrint(a, "{s}/{s}", .{ package, id }); + return a.print("{s}/{s}", .{ package, id }); } /// Arena-owned result. Unknown top-level runtime fields are ignored, but every /// selected field is parsed with ignore_unknown_fields=false (including children). pub fn parse(allocator: std.mem.Allocator, bytes: []const u8) !Manifest { - const source = try allocator.dupeZ(u8, bytes); + const source = try allocator.dupeSentinel(u8, bytes, 0); defer allocator.free(source); - var ast = try std.zig.Ast.parse(allocator, source, .zon); + var ast = try std.zig.Ast.parse(allocator, source, .{ .mode = .zon }); defer ast.deinit(allocator); if (ast.errors.len != 0) return error.InvalidManifest; try rejectRepeatedFields(ast); var zoir = try std.zig.ZonGen.generate(allocator, ast, .{ .parse_str_lits = false }); defer zoir.deinit(allocator); if (zoir.hasCompileErrors()) return error.InvalidManifest; - const fields = switch (std.zig.Zoir.Node.Index.root.get(zoir)) { + const fields = switch (std.zig.Zoir.Node.Index.root.get(&zoir)) { .struct_literal => |fields| fields, else => return error.InvalidManifest, }; var result: Manifest = .{}; for (fields.names, 0..) |name, i| { - inline for (std.meta.fields(Manifest)) |field| { - if (std.mem.eql(u8, name.get(zoir), field.name)) { - @field(result, field.name) = try std.zon.parse.fromZoirNodeAlloc( - field.type, - allocator, - ast, - zoir, - fields.vals.at(@intCast(i)), - null, - .{}, - ); + const manifest_info = @typeInfo(Manifest).@"struct"; + inline for (manifest_info.field_names, manifest_info.field_types) |field_name, field_type| { + if (std.mem.eql(u8, name.get(&zoir), field_name)) { + var diagnostics: std.zon.parse.Diagnostics = undefined; + @field(result, field_name) = try std.zon.parse.fromZoir(field_type, .{ + .arena = allocator, + .ast = &ast, + .zoir = &zoir, + .node = fields.vals.at(@intCast(i)), + .diagnostics = &diagnostics, + }); } } } @@ -220,7 +220,7 @@ test "provider manifest: strict records, negotiation, defaults and runtime exten } fn hookManifest(a: std.mem.Allocator, targets: []const u8, hooks: []const u8) ![]const u8 { - return std.fmt.allocPrint(a, ".{{ .name = \"fixture\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .targets = .{{ {s} }}, .hooks = .{{ {s} }} }}", .{ targets, hooks }); + return a.print(".{{ .name = \"fixture\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .targets = .{{ {s} }}, .hooks = .{{ {s} }} }}", .{ targets, hooks }); } test "provider manifest: replace hooks need an owned target; before/after attach anywhere" { @@ -254,12 +254,12 @@ test "provider manifest: a declared or hooked target is never a Windows reserved // Identifier-shaped, so only the device rule can refuse them. for ([_][]const u8{ "con", "nul", "prn", "aux", "com1", "lpt9" }) |device| { try std.testing.expect(contract.identifier(device)); - const declared = try std.fmt.allocPrint(a, "\"{s}\"", .{device}); + const declared = try a.print("\"{s}\"", .{device}); try std.testing.expectError(error.ReservedDeviceTarget, parse(a, try hookManifest(a, declared, ""))); // Alongside a legitimate target, and as a hook target (any phase). - const mixed = try std.fmt.allocPrint(a, "\"probe-target\", \"{s}\"", .{device}); + const mixed = try a.print("\"probe-target\", \"{s}\"", .{device}); try std.testing.expectError(error.ReservedDeviceTarget, parse(a, try hookManifest(a, mixed, ""))); - const hook = try std.fmt.allocPrint(a, ".{{ .id = \"pack\", .step = .bundle, .target = \"{s}\", .when = .before, .build_step = \"tool\", .executable = \"bin/tool\" }}", .{device}); + const hook = try a.print(".{{ .id = \"pack\", .step = .bundle, .target = \"{s}\", .when = .before, .build_step = \"tool\", .executable = \"bin/tool\" }}", .{device}); try std.testing.expectError(error.ReservedDeviceTarget, parse(a, try hookManifest(a, "", hook))); } // Near misses stay valid targets. @@ -297,8 +297,8 @@ test "provider manifest: hook steps are limited to the four contract steps" { defer arena.deinit(); const a = arena.allocator(); const hook = ".{ .id = \"pack\", .step = .{s}, .target = \"desktop\", .when = .before, .build_step = \"tool\", .executable = \"bin/tool\" }"; - inline for (std.meta.fields(contract.Step)) |step| { - const ok = try std.mem.replaceOwned(u8, a, hook, "{s}", step.name); + inline for (@typeInfo(contract.Step).@"enum".field_names) |step_name| { + const ok = try std.mem.replaceOwned(u8, a, hook, "{s}", step_name); _ = try parse(a, try hookManifest(a, "", ok)); } // There is no separate package lifecycle step (contract §1). @@ -320,7 +320,7 @@ test "provider manifest: a repeated top-level field is rejected, never last-wins ".manifest_version = 2", ".commands = .{ .{ .name = \"doctor\", .build_step = \"tool\", .executable = \"bin/doctor\", .help = \"Inspect\" } }", }) |decl| { - const repeated = try std.mem.replaceOwned(u8, a, good, decl, try std.fmt.allocPrint(a, "{s}, {s}", .{ decl, decl })); + const repeated = try std.mem.replaceOwned(u8, a, good, decl, try a.print("{s}, {s}", .{ decl, decl })); try std.testing.expect(!std.mem.eql(u8, good, repeated)); try std.testing.expectError(error.DuplicateManifestField, parse(a, repeated)); } @@ -367,19 +367,19 @@ test "provider manifest: target defaults belong to the target's owner, once per defer arena.deinit(); const a = arena.allocator(); const base = ".{{ .name = \"fixture\", .manifest_version = 2, .command_contract = \">=1.0.0 <2.0.0\", .targets = .{{ {s} }}, .target_defaults = .{{ {s} }} }}"; - const owned = try parse(a, try std.fmt.allocPrint(a, base, .{ "\"probe-target\"", ".{ .target = \"probe-target\", .optimize = .ReleaseSafe }" })); + const owned = try parse(a, try a.print(base, .{ "\"probe-target\"", ".{ .target = \"probe-target\", .optimize = .ReleaseSafe }" })); try std.testing.expectEqual(contract.Optimize.ReleaseSafe, owned.defaultOptimize("probe-target").?); try std.testing.expect(owned.defaultOptimize("desktop") == null); // A defaults-only manifest is still a provider manifest. try std.testing.expect(owned.isProvider()); // Someone else's target, including core's `desktop`: refused. - try std.testing.expectError(error.TargetDefaultRequiresOwnedTarget, parse(a, try std.fmt.allocPrint(a, base, .{ "\"probe-target\"", ".{ .target = \"other\", .optimize = .ReleaseSafe }" }))); - try std.testing.expectError(error.TargetDefaultRequiresOwnedTarget, parse(a, try std.fmt.allocPrint(a, base, .{ "", ".{ .target = \"desktop\", .optimize = .ReleaseFast }" }))); + try std.testing.expectError(error.TargetDefaultRequiresOwnedTarget, parse(a, try a.print(base, .{ "\"probe-target\"", ".{ .target = \"other\", .optimize = .ReleaseSafe }" }))); + try std.testing.expectError(error.TargetDefaultRequiresOwnedTarget, parse(a, try a.print(base, .{ "", ".{ .target = \"desktop\", .optimize = .ReleaseFast }" }))); // Two defaults for one target, even agreeing: refused. - try std.testing.expectError(error.DuplicateTargetDefault, parse(a, try std.fmt.allocPrint(a, base, .{ "\"probe-target\"", ".{ .target = \"probe-target\", .optimize = .ReleaseSafe }, .{ .target = \"probe-target\", .optimize = .ReleaseSafe }" }))); + try std.testing.expectError(error.DuplicateTargetDefault, parse(a, try a.print(base, .{ "\"probe-target\"", ".{ .target = \"probe-target\", .optimize = .ReleaseSafe }, .{ .target = \"probe-target\", .optimize = .ReleaseSafe }" }))); // Strict records: an unknown field or mode is a parse error. - try std.testing.expectError(error.ParseZon, parse(a, try std.fmt.allocPrint(a, base, .{ "\"probe-target\"", ".{ .target = \"probe-target\", .optimize = .ReleaseSafe, .typo = 1 }" }))); - try std.testing.expectError(error.ParseZon, parse(a, try std.fmt.allocPrint(a, base, .{ "\"probe-target\"", ".{ .target = \"probe-target\", .optimize = .Fastest }" }))); + try std.testing.expectError(error.ParseZon, parse(a, try a.print(base, .{ "\"probe-target\"", ".{ .target = \"probe-target\", .optimize = .ReleaseSafe, .typo = 1 }" }))); + try std.testing.expectError(error.ParseZon, parse(a, try a.print(base, .{ "\"probe-target\"", ".{ .target = \"probe-target\", .optimize = .Fastest }" }))); } test "provider manifest: .watch is declared only on a run replacement" { diff --git a/src/cli/provider_registry.zig b/src/cli/provider_registry.zig index ff70322f..998b3110 100644 --- a/src/cli/provider_registry.zig +++ b/src/cli/provider_registry.zig @@ -350,8 +350,8 @@ fn addUnique(a: std.mem.Allocator, list: *std.ArrayList([]const u8), name: []con try list.append(a, name); } -const commit_a = "1" ** 40; -const hash_a = "a" ** 64; +const commit_a = &@as([40]u8, @splat('1')); +const hash_a = &@as([64]u8, @splat('a')); inline fn testRecord(comptime package: []const u8, comptime version: []const u8, comptime namespace: []const u8, comptime targets: []const u8) []const u8 { return "{\"package\":\"" ++ package ++ "\",\"repo\":\"owner/" ++ package ++ "\",\"version\":\"" ++ version ++ diff --git a/src/cli/provider_settings.zig b/src/cli/provider_settings.zig index 6493e3f1..1e50904d 100644 --- a/src/cli/provider_settings.zig +++ b/src/cli/provider_settings.zig @@ -8,20 +8,27 @@ pub const Entry = struct { package: []const u8, file: []const u8 }; /// the offending mapping before returning the error (the verbose /// `config.readProjectConfig` path, codex #460): without it a bad mapping /// made `build`/`generate`/`run` exit 1 with no message. -pub fn validateProject(a: std.mem.Allocator, source: [:0]const u8, labelle_path: ?[]const u8) !void { +pub fn validateProject(gpa: std.mem.Allocator, source: [:0]const u8, labelle_path: ?[]const u8) !void { + // Zig 0.17's ZON parser allocates values and diagnostics in an arena + // (no per-value free); everything parsed here is scratch. + var arena_state = std.heap.ArenaAllocator.init(gpa); + defer arena_state.deinit(); + const a = arena_state.allocator(); const entries = try parseReporting(a, source, labelle_path); - defer std.zon.parse.free(a, entries); if (entries.len == 0) return; - // Validate before parsing the full ProjectConfig, whose static defaults - // cannot be safely released with zon.parse.free on a later rejection. + // Validate before parsing the full ProjectConfig. const References = struct { plugins: []const struct { name: []const u8 } = &.{} }; - var diag: std.zon.parse.Diagnostics = .{}; - defer diag.deinit(a); - const refs = std.zon.parse.fromSliceAlloc(References, a, source, &diag, .{ .ignore_unknown_fields = true }) catch |err| { - if (labelle_path) |path| std.debug.print("labelle: could not parse '{s}': {any}\n{f}", .{ path, err, &diag }); + var diag: std.zon.parse.Diagnostics = undefined; + const refs = std.zon.parse.fromSlice(References, .{ + .gpa = gpa, + .arena = a, + .source = source, + .diagnostics = &diag, + .ignore_unknown_fields = true, + }) catch |err| { + if (labelle_path) |path| std.debug.print("labelle: could not parse '{s}': {any}\n{f}\n", .{ path, err, diag.fmt(path) }); return err; }; - defer std.zon.parse.free(a, refs); var bad: usize = 0; validateAt(entries, refs.plugins, &bad) catch |err| { if (labelle_path) |path| report(path, err, bad, entries[bad]); @@ -76,35 +83,37 @@ fn validateAt(entries: []const Entry, plugins: anytype, bad: *usize) !void { } /// Strictly parse this subtree even when a caller ignores other project fields. -/// Caller frees the returned entries with std.zon.parse.free. -pub fn parse(a: std.mem.Allocator, source: [:0]const u8) ![]const Entry { - return parseReporting(a, source, null); +/// The returned entries live in `arena`, which must be one (Zig 0.17's ZON +/// parser has no per-value free); it also serves the scratch allocations. +pub fn parse(arena: std.mem.Allocator, source: [:0]const u8) ![]const Entry { + return parseReporting(arena, source, null); } /// `parse`; a non-null `labelle_path` prints why the subtree was rejected. fn parseReporting(a: std.mem.Allocator, source: [:0]const u8, labelle_path: ?[]const u8) ![]const Entry { - var transferred = false; - var ast = try std.zig.Ast.parse(a, source, .zon); - defer if (!transferred) ast.deinit(a); + var ast = try std.zig.Ast.parse(a, source, .{ .mode = .zon }); + defer ast.deinit(a); if (ast.errors.len != 0) return syntaxError(labelle_path); var zoir = try std.zig.ZonGen.generate(a, ast, .{ .parse_str_lits = false }); - defer if (!transferred) zoir.deinit(a); + defer zoir.deinit(a); if (zoir.hasCompileErrors()) return syntaxError(labelle_path); - const fields = switch (std.zig.Zoir.Node.Index.root.get(zoir)) { + const fields = switch (std.zig.Zoir.Node.Index.root.get(&zoir)) { .struct_literal => |fields| fields, else => return &.{}, // The owning project parser diagnoses the root. }; for (fields.names, 0..) |name, i| { - if (std.mem.eql(u8, name.get(zoir), "provider_config")) { - // Diagnostics takes ownership of the AST/ZOIR and any error text. - // Passing null leaks unexpected-field diagnostics in Zig 0.16. - var diag: std.zon.parse.Diagnostics = .{}; - transferred = true; - defer diag.deinit(a); - return std.zon.parse.fromZoirNodeAlloc([]const Entry, a, ast, zoir, fields.vals.at(@intCast(i)), &diag, .{}) catch |err| { + if (std.mem.eql(u8, name.get(&zoir), "provider_config")) { + var diag: std.zon.parse.Diagnostics = undefined; + return std.zon.parse.fromZoir([]const Entry, .{ + .arena = a, + .ast = &ast, + .zoir = &zoir, + .node = fields.vals.at(@intCast(i)), + .diagnostics = &diag, + }) catch |err| { if (labelle_path) |path| std.debug.print( - "labelle: invalid .provider_config in '{s}': malformed mapping record; each entry must be .{{ .package = \"\", .file = \"\" }} ({s})\n{f}", - .{ path, @errorName(err), &diag }, + "labelle: invalid .provider_config in '{s}': malformed mapping record; each entry must be .{{ .package = \"\", .file = \"\" }} ({s})\n{f}\n", + .{ path, @errorName(err), diag.fmt(path) }, ); return err; }; @@ -114,9 +123,10 @@ fn parseReporting(a: std.mem.Allocator, source: [:0]const u8, labelle_path: ?[]c } test "provider settings: strict mapping, declarations and portable paths" { - const a = std.testing.allocator; + var arena = std.heap.ArenaAllocator.init(std.testing.allocator); + defer arena.deinit(); + const a = arena.allocator(); const entries = try parse(a, ".{ .unrelated = true, .provider_config = .{ .{ .package = \"fixture\", .file = \"providers/settings.json\" } } }"); - defer std.zon.parse.free(a, entries); const plugins = [_]struct { name: []const u8 }{.{ .name = "fixture" }}; try validate(entries, &plugins); try std.testing.expectError(error.ParseZon, parse(a, ".{ .provider_config = .{ .{ .package = \"fixture\", .file = \"x\", .typo = true } } }")); diff --git a/src/cli/provider_targets.zig b/src/cli/provider_targets.zig index 98f08c40..3dd81a83 100644 --- a/src/cli/provider_targets.zig +++ b/src/cli/provider_targets.zig @@ -79,7 +79,7 @@ pub fn resolve(providers: []const dispatch.Provider, requested: []const u8) !Res /// The diagnostic for `UnverifiedTargetOwner`: names the package, and the /// way to pin it. pub fn unverifiedOwnerDiagnostic(a: std.mem.Allocator, target: []const u8, package: []const u8) ![]const u8 { - return std.fmt.allocPrint(a, "labelle: target '{s}' is declared by remote package '{s}', which is unpinned; a target's provider must be pinned. Run labelle providers resolve, review the pins, then repeat with --accept.\n", .{ target, package }); + return a.print("labelle: target '{s}' is declared by remote package '{s}', which is unpinned; a target's provider must be pinned. Run labelle providers resolve, review the pins, then repeat with --accept.\n", .{ target, package }); } /// Print the unverified-owner diagnostic for `target` (which `resolve` just @@ -351,7 +351,7 @@ test "provider targets: the no-provider diagnostic names a candidate on a hit an try std.testing.expect(std.mem.startsWith(u8, custom, head)); try std.testing.expect(has(custom, "The registry this project last accepted from lists package 'fixture' as the provider")); try std.testing.expect(has(custom, "2.0.0, is a candidate: `labelle providers resolve --accept`")); - try std.testing.expect(has(custom, try std.fmt.allocPrint(a, "(quote or escape it for your shell, since it may contain spaces or special characters):\n {s}\n", .{source}))); + try std.testing.expect(has(custom, try a.print("(quote or escape it for your shell, since it may contain spaces or special characters):\n {s}\n", .{source}))); try std.testing.expectEqual(@as(usize, 1), std.mem.count(u8, custom, source)); try std.testing.expect(has(custom, "run `labelle providers resolve` with the source above as its argument")); try std.testing.expect(!has(custom, "labelle providers resolve --accept #") and !has(custom, "labelle providers resolve #")); diff --git a/src/cli/python_provision.zig b/src/cli/python_provision.zig index 7830cced..2cd6d8a6 100644 --- a/src/cli/python_provision.zig +++ b/src/cli/python_provision.zig @@ -23,7 +23,7 @@ const util = @import("util.zig"); const asm_cache = @import("asm_cache.zig"); const cache_publish = @import("cache_publish.zig"); -const is_windows = builtin.os.tag == .windows; +const is_windows = builtin.target.os.tag == .windows; const path_sep: u8 = if (is_windows) ';' else ':'; // Pinned python-build-standalone release (install_only = relocatable, includes @@ -38,9 +38,9 @@ const PY_RELEASE = "20240814"; const PyDist = struct { triple: []const u8, sha256: []const u8 }; fn pyDist() ?PyDist { - return switch (builtin.os.tag) { + return switch (builtin.target.os.tag) { .windows => .{ .triple = "x86_64-pc-windows-msvc", .sha256 = "4c71d25731214b8a960d1d87510f24179d819249c5b434aaf7135818421b6215" }, - .macos => switch (builtin.cpu.arch) { + .macos => switch (builtin.target.cpu.arch) { .aarch64 => .{ .triple = "aarch64-apple-darwin", .sha256 = "8760e908f25fdc8a01f4d1b101854ac047b4eacb723fb2593a168fb989c86eef" }, .x86_64 => .{ .triple = "x86_64-apple-darwin", .sha256 = "76073305812c093ce840df9c4c17068aa69da8d951e7376ef48f43376986a13e" }, else => null, @@ -185,8 +185,7 @@ fn provisionInto(gpa: std.mem.Allocator) Result { defer cwd.deleteTree(io, staging) catch {}; cwd.createDirPath(io, staging) catch return .failed; - const url = std.fmt.allocPrint( - a, + const url = a.print( "https://github.com/astral-sh/python-build-standalone/releases/download/" ++ PY_RELEASE ++ "/cpython-" ++ PY_VERSION ++ "+" ++ PY_RELEASE ++ "-{s}-install_only.tar.gz", .{dist.triple}, @@ -287,7 +286,7 @@ pub fn autoWireEnv(gpa: std.mem.Allocator) void { const present = if (is_windows) util.windowsPathEql(seg, bin_dir) else std.mem.eql(u8, seg, bin_dir); if (present) return; // already present } - const new_path = std.fmt.allocPrint(a, "{s}{c}{s}", .{ bin_dir, path_sep, old_path }) catch return; + const new_path = a.print("{s}{c}{s}", .{ bin_dir, path_sep, old_path }) catch return; setPathEnv(a, new_path); std.debug.print("labelle: using provisioned Python ({s})\n", .{bin_dir}); } @@ -345,8 +344,8 @@ fn setEnvVar(a: std.mem.Allocator, name: []const u8, value: []const u8) void { const value_w = std.unicode.utf8ToUtf16LeAllocZ(a, value) catch return; _ = SetEnvironmentVariableW(name_w.ptr, value_w.ptr); } else { - const name_z = a.dupeZ(u8, name) catch return; - const value_z = a.dupeZ(u8, value) catch return; + const name_z = a.dupeSentinel(u8, name, 0) catch return; + const value_z = a.dupeSentinel(u8, value, 0) catch return; _ = setenv(name_z.ptr, value_z.ptr, 1); } } diff --git a/src/cli/runner.zig b/src/cli/runner.zig index 4df90ef0..96a3bcea 100644 --- a/src/cli/runner.zig +++ b/src/cli/runner.zig @@ -8,7 +8,7 @@ const zig_cache = @import("zig_cache.zig"); const progress = @import("progress.zig"); const zig_progress = @import("zig_progress.zig"); const provider_env = @import("provider_env.zig"); -const is_windows = builtin.os.tag == .windows; +const is_windows = builtin.target.os.tag == .windows; /// Resolve the managed `zig` binary for `project_dir` (labelle-cli#279). /// This is the ONE place spawns get a `zig` path — never PATH. Downloads + @@ -203,12 +203,12 @@ fn exitStatus(term: std.process.Child.Term) u8 { return switch (term) { .exited => |code| code, .signal => |sig| blk: { - std.debug.print("labelle: killed by signal {d}\n", .{@intFromEnum(sig)}); - break :blk 128 +% @as(u8, @truncate(@intFromEnum(sig))); + std.debug.print("labelle: killed by signal {d}\n", .{@backingInt(sig)}); + break :blk 128 +% @as(u8, @truncate(@backingInt(sig))); }, .stopped => |sig| blk: { - std.debug.print("labelle: stopped by signal {d}\n", .{@intFromEnum(sig)}); - break :blk 128 +% @as(u8, @truncate(@intFromEnum(sig))); + std.debug.print("labelle: stopped by signal {d}\n", .{@backingInt(sig)}); + break :blk 128 +% @as(u8, @truncate(@backingInt(sig))); }, .unknown => |val| blk: { std.debug.print("labelle: unknown termination {d}\n", .{val}); @@ -257,6 +257,17 @@ fn exitStatus(term: std.process.Child.Term) u8 { // "steps" node — unit-tested against synthesized packets), so richer // data lights up without code changes once a fixed Zig lands. // +// Zig 0.17.1 (re-measured the same way): the wire format is unchanged +// (`Node.Storage`, 120-byte names, the 0xFFFFFFFF IPC marker), and the +// maker's "steps" tree still does not reach the fd, so `step`/`total` +// stay null. What changed is the frontend's own subtree: 0.17 no longer +// compiles a build runner per project. Its root node is "Compiling maker +// (first time setup)" and it appears once per toolchain + global cache +// (966 kB of packets on a cold global cache); every later `zig build`, +// including a cold project build, writes 0 bytes. So under 0.17 the feed +// is heartbeats only in practice, where 0.16 at least named the build +// script compile whenever build.zig changed. +// // Why the `/usr/bin/env ZIG_PROGRESS=` argv wrapper instead of putting // the var in `environ_map`: `std.process.spawn` actively *strips* a // `ZIG_PROGRESS` key from any user-supplied env block unless it manages @@ -346,11 +357,11 @@ fn termToExitCode(term: anytype) u8 { return switch (term) { .exited => |code| code, .signal => |sig| blk: { - std.debug.print("labelle: killed by signal {d}\n", .{@intFromEnum(sig)}); + std.debug.print("labelle: killed by signal {d}\n", .{@backingInt(sig)}); break :blk 1; }, .stopped => |sig| blk: { - std.debug.print("labelle: stopped by signal {d}\n", .{@intFromEnum(sig)}); + std.debug.print("labelle: stopped by signal {d}\n", .{@backingInt(sig)}); break :blk 1; }, .unknown => |val| blk: { @@ -381,7 +392,7 @@ pub fn runZigInheritProgress( return runZigInheritHeartbeat(allocator, cwd, argv, environ_map, reporter); var fd_env_buf: [32]u8 = undefined; - const fd_env = std.fmt.bufPrint(&fd_env_buf, "ZIG_PROGRESS={d}", .{fds[1]}) catch unreachable; + const fd_env = std.mem.print(&fd_env_buf, "ZIG_PROGRESS={d}", .{fds[1]}) catch unreachable; var wrapped: std.ArrayList([]const u8) = .empty; defer wrapped.deinit(allocator); @@ -509,7 +520,7 @@ pub fn appendRunOptionEnv( try extras.append(allocator, .{ .key = "LABELLE_SCREENSHOT_PATH", .value = path }); if (opts.screenshot_after_ns) |ns| { const sec_f64 = @as(f64, @floatFromInt(ns)) / @as(f64, std.time.ns_per_s); - const sec_str = try std.fmt.bufPrint(sec_buf, "{d:.3}", .{sec_f64}); + const sec_str = try std.mem.print(sec_buf, "{d:.3}", .{sec_f64}); try extras.append(allocator, .{ .key = "LABELLE_SCREENSHOT_AFTER_SEC", .value = sec_str }); } } @@ -699,7 +710,7 @@ fn msFromNs(ns: u64) u32 { fn taskkillTree(allocator: std.mem.Allocator, pid: std.os.windows.DWORD) void { _ = allocator; var pid_buf: [16]u8 = undefined; - const pid_str = std.fmt.bufPrint(&pid_buf, "{d}", .{pid}) catch return; + const pid_str = std.mem.print(&pid_buf, "{d}", .{pid}) catch return; const argv = [_][]const u8{ "taskkill", "/F", "/T", "/PID", pid_str }; const io = config.globalIo(); var kill_child = std.process.spawn(io, .{ @@ -765,6 +776,15 @@ pub fn fixFingerprint(allocator: std.mem.Allocator, project_dir: []const u8, out // fingerprint — swallowing the real build into this probe (~0.15s vs // minutes; found while wiring the cli#284 progress feed, which showed // the cold compile landing inside the "generate" phase). + // Checked against Zig 0.17.1, where `zig build` moved into the build + // system and build.zig runs in a separate configurer: the manifest is + // still validated before configuration, the message still reads + // `invalid fingerprint: 0x…; if this is a new or forked package, use + // this value: 0x…` on stderr (now with a cwd-relative `build.zig.zon` + // path instead of an absolute one), and the exit status is still 1. + // A manifest with NO fingerprint reports `suggested value: 0x…` + // instead, in 0.16 and 0.17 alike; this probe does not handle that + // case (the assembler always emits one). // The target owner's `build_options` (wire 1.6.0+) reach the probe too: // it configures the generated build, as the compile will. var args_arena = std.heap.ArenaAllocator.init(allocator); diff --git a/src/cli/screenshot_format.zig b/src/cli/screenshot_format.zig index 47c04696..806f82ba 100644 --- a/src/cli/screenshot_format.zig +++ b/src/cli/screenshot_format.zig @@ -22,10 +22,7 @@ const std = @import("std"); const config = @import("config.zig"); -const c = @cImport({ - @cInclude("stb_image.h"); - @cInclude("stb_image_write.h"); -}); +const c = @import("../stb.zig"); /// An image format the CLI can both read (stb_image, see /// `stb_image_impl.c`'s `STBI_ONLY_*` set) and write (stb_image_write). @@ -356,7 +353,7 @@ pub const ApplySpec = struct { /// directory under a cwd-relative `.zig-cache/tmp/`, so cwd-relative /// paths built from `sub_path` address exactly the same files. fn tmpPath(allocator: std.mem.Allocator, tmp: std.testing.TmpDir, name: []const u8) ![]u8 { - return std.fmt.allocPrint(allocator, ".zig-cache/tmp/{s}/{s}", .{ tmp.sub_path, name }); + return allocator.print(".zig-cache/tmp/{s}/{s}", .{ tmp.sub_path, name }); } const writeFixture = writeTestFixture; diff --git a/src/cli/supervise.zig b/src/cli/supervise.zig index 77cb1164..39c6d70c 100644 --- a/src/cli/supervise.zig +++ b/src/cli/supervise.zig @@ -28,7 +28,7 @@ const builtin = @import("builtin"); const config = @import("config.zig"); const project_lock = @import("project_lock.zig"); -const is_windows = builtin.os.tag == .windows; +const is_windows = builtin.target.os.tag == .windows; /// The most children one group tracks at once. A rebuild runs one child at /// a time; the headroom covers helpers such as a relay. @@ -40,17 +40,17 @@ pub threadlocal var current: ?*Group = null; /// Groups a stop signal reaches (`forwardAll`, `killAll`): attached for /// the life of a session. Read lock-free from a signal handler. -var attached: [4]std.atomic.Value(usize) = [_]std.atomic.Value(usize){.init(0)} ** 4; +var attached: [4]std.atomic.Value(usize) = @splat(.init(0)); pub const Group = struct { /// POSIX: the pid of each registered child (it leads its own process /// group, so `-pid` is the group). Windows: its job object handle. /// Zero is a free slot. - slots: [max_children]std.atomic.Value(usize) = [_]std.atomic.Value(usize){.init(0)} ** max_children, + slots: [max_children]std.atomic.Value(usize) = @splat(.init(0)), /// Bumped each time a slot is taken: a `Handle` names one registration, /// so a kill aimed at a child already reaped never reaches the child /// registered in its slot since (cli#478). Guarded by `mutex`. - generations: [max_children]u64 = [_]u64{0} ** max_children, + generations: [max_children]u64 = @splat(0), cancelled: std.atomic.Value(bool) = .init(false), /// A stop forwarded to the group (`forward`), latched: `Stop` + 1, or /// 0. A child registered AFTER the stop arrived — while the session was @@ -132,7 +132,7 @@ pub const Group = struct { /// Signal-handler safe: latch `sig`, then forward it to every /// registered tree. fn forward(self: *Group, sig: Stop) usize { - self.pending.store(@as(u8, @intFromEnum(sig)) + 1, .seq_cst); + self.pending.store(@as(u8, @backingInt(sig)) + 1, .seq_cst); var n: usize = 0; for (&self.slots) |*slot| { const id = slot.load(.seq_cst); @@ -308,7 +308,7 @@ pub fn spawnIn(group_opt: ?*Group, io: std.Io, given: std.process.SpawnOptions) if (latched != 0) { // On Windows an interrupt is the console event, which a child that // was not running then never saw: terminate its job instead. - const stop: Stop = @enumFromInt(latched - 1); + const stop: Stop = @fromBackingInt(@intCast(latched - 1)); signalTree(id, if (is_windows and stop == .interrupt) .terminate else stop); } return .{ .child = child, .group = group, .slot = slot }; @@ -573,7 +573,7 @@ fn processGone(pid: u32) bool { defer _ = win.CloseHandle(h); return K.WaitForSingleObject(h, 0) == 0; } - return std.posix.system.kill(@intCast(pid), @enumFromInt(0)) != 0; + return std.posix.system.kill(@intCast(pid), @fromBackingInt(0)) != 0; } test "supervise: an unsupervised thread spawns exactly as before" { diff --git a/src/cli/update.zig b/src/cli/update.zig index 8cd34baf..c29064b6 100644 --- a/src/cli/update.zig +++ b/src/cli/update.zig @@ -191,7 +191,7 @@ fn windowsUpdateScript( const bin_path = try escapeBatchPercent(allocator, bin_path_raw); defer allocator.free(bin_path); - return std.fmt.allocPrint(allocator, + return allocator.print( \\@echo off \\setlocal \\if not defined SystemRoot set "SystemRoot=C:\Windows" @@ -266,7 +266,7 @@ pub fn cmdUpdate(allocator: std.mem.Allocator, cmd_args: []const []const u8) !vo std.debug.print(" new version available: {s}\n\n", .{target_version}); const builtin = @import("builtin"); - const os_name: []const u8 = switch (builtin.os.tag) { + const os_name: []const u8 = switch (builtin.target.os.tag) { .macos => "darwin", .linux => "linux", .windows => "windows", @@ -276,7 +276,7 @@ pub fn cmdUpdate(allocator: std.mem.Allocator, cmd_args: []const []const u8) !vo return; }, }; - const arch_name: []const u8 = switch (builtin.cpu.arch) { + const arch_name: []const u8 = switch (builtin.target.cpu.arch) { .aarch64 => "arm64", .x86_64 => "x86_64", else => { @@ -286,7 +286,7 @@ pub fn cmdUpdate(allocator: std.mem.Allocator, cmd_args: []const []const u8) !vo }, }; - const download_url = try std.fmt.allocPrint(allocator, "{s}/v{s}/labelle-{s}-{s}", .{ + const download_url = try allocator.print("{s}/v{s}/labelle-{s}-{s}", .{ r2_base_url, target_version, os_name, arch_name, }); defer allocator.free(download_url); @@ -300,7 +300,7 @@ pub fn cmdUpdate(allocator: std.mem.Allocator, cmd_args: []const []const u8) !vo const bin_dir = try std.fs.path.join(allocator, &.{ cache_root, "bin" }); defer allocator.free(bin_dir); - const bin_name: []const u8 = if (builtin.os.tag == .windows) "labelle.exe" else "labelle"; + const bin_name: []const u8 = if (builtin.target.os.tag == .windows) "labelle.exe" else "labelle"; const bin_path = try std.fs.path.join(allocator, &.{ bin_dir, bin_name }); defer allocator.free(bin_path); @@ -341,11 +341,11 @@ pub fn cmdUpdate(allocator: std.mem.Allocator, cmd_args: []const []const u8) !vo }, } - if (builtin.os.tag != .windows) { + if (builtin.target.os.tag != .windows) { _ = util.runCmd(allocator, &.{ "chmod", "+x", tmp_path }) catch {}; } - if (builtin.os.tag == .windows) { + if (builtin.target.os.tag == .windows) { const bat_path = try std.fs.path.join(allocator, &.{ bin_dir, "labelle-update.bat" }); defer allocator.free(bat_path); @@ -420,7 +420,7 @@ pub fn cmdUpdate(allocator: std.mem.Allocator, cmd_args: []const []const u8) !vo fn setupPath(allocator: std.mem.Allocator, bin_dir: []const u8) void { const builtin = @import("builtin"); - if (builtin.os.tag == .windows) { + if (builtin.target.os.tag == .windows) { setupPathWindows(allocator, bin_dir); return; } @@ -442,7 +442,7 @@ fn setupPath(allocator: std.mem.Allocator, bin_dir: []const u8) void { }; defer allocator.free(home_dir); - const path_line = std.fmt.allocPrint(allocator, "export PATH=\"{s}:$PATH\"", .{bin_dir}) catch return; + const path_line = allocator.print("export PATH=\"{s}:$PATH\"", .{bin_dir}) catch return; defer allocator.free(path_line); if (std.mem.endsWith(u8, shell_env, "zsh")) { @@ -458,7 +458,7 @@ fn setupPath(allocator: std.mem.Allocator, bin_dir: []const u8) void { const bash_profile = std.fs.path.join(allocator, &.{ home_dir, ".bash_profile" }) catch return; defer allocator.free(bash_profile); - const target_rc = if (builtin.os.tag == .macos and !util.fileExists(bashrc)) + const target_rc = if (builtin.target.os.tag == .macos and !util.fileExists(bashrc)) bash_profile else bashrc; @@ -469,7 +469,7 @@ fn setupPath(allocator: std.mem.Allocator, bin_dir: []const u8) void { std.debug.print(" run `source ~/{s}` or restart your terminal\n\n", .{rc_name}); } } else if (std.mem.endsWith(u8, shell_env, "fish")) { - const fish_cmd = std.fmt.allocPrint(allocator, "fish_add_path {s}", .{bin_dir}) catch return; + const fish_cmd = allocator.print("fish_add_path {s}", .{bin_dir}) catch return; defer allocator.free(fish_cmd); if (util.runCmd(allocator, &.{ "fish", "-c", fish_cmd })) |result| { defer allocator.free(result.stdout); @@ -511,7 +511,7 @@ fn setupPathWindows(allocator: std.mem.Allocator, bin_dir: []const u8) void { const escaped_dir = util.escapePowerShellString(allocator, bin_dir) catch return; defer allocator.free(escaped_dir); - const set_cmd = std.fmt.allocPrint(allocator, "[Environment]::SetEnvironmentVariable('Path', '{s};' + [Environment]::GetEnvironmentVariable('Path', 'User'), 'User')", .{escaped_dir}) catch return; + const set_cmd = allocator.print("[Environment]::SetEnvironmentVariable('Path', '{s};' + [Environment]::GetEnvironmentVariable('Path', 'User'), 'User')", .{escaped_dir}) catch return; defer allocator.free(set_cmd); if (util.runCmd(allocator, &.{ "powershell", "-NoProfile", "-Command", set_cmd })) |set_result| { @@ -535,7 +535,7 @@ fn setupPathWindows(allocator: std.mem.Allocator, bin_dir: []const u8) void { fn checkOldBinary(new_path: []const u8) void { const builtin = @import("builtin"); - if (builtin.os.tag == .windows) return; + if (builtin.target.os.tag == .windows) return; const system_paths = [_][]const u8{ "/usr/local/bin/labelle", "/usr/bin/labelle" }; for (system_paths) |sys_path| { diff --git a/src/cli/upgrade.zig b/src/cli/upgrade.zig index f88c12ac..b3d47fd0 100644 --- a/src/cli/upgrade.zig +++ b/src/cli/upgrade.zig @@ -425,7 +425,7 @@ fn skipTrivia(content: []const u8, start: usize) usize { fn insertBeforeClosingBrace(allocator: std.mem.Allocator, old_content: []u8, field_name: []const u8, value: []const u8) ![]u8 { errdefer allocator.free(old_content); - const line = try std.fmt.allocPrint(allocator, " .{s} = \"{s}\",\n", .{ field_name, value }); + const line = try allocator.print(" .{s} = \"{s}\",\n", .{ field_name, value }); defer allocator.free(line); // Find the last `}` in the content. diff --git a/src/cli/util.zig b/src/cli/util.zig index 1fe1da6c..a3288653 100644 --- a/src/cli/util.zig +++ b/src/cli/util.zig @@ -11,6 +11,41 @@ pub fn dirExists(path: []const u8) bool { return stat.kind == .directory; } +/// `std.zon.parse.fromSlice` for callers that do not report ZON diagnostics. +/// +/// Zig 0.17 made the diagnostics out-parameter mandatory and allocates the +/// result in an arena with no per-value `free` (0.16's `fromSliceAlloc` + +/// `std.zon.parse.free` pair is gone). So `arena` must really be one, or an +/// allocator whose owner releases everything at once: nothing returned here +/// can be freed on its own. It also serves the parser's scratch allocations. +pub fn parseZon( + comptime T: type, + arena: std.mem.Allocator, + source: [:0]const u8, + options: struct { ignore_unknown_fields: bool = false }, +) error{ OutOfMemory, ParseZon }!T { + var diagnostics: std.zon.parse.Diagnostics = undefined; + return std.zon.parse.fromSlice(T, .{ + .gpa = arena, + .arena = arena, + .source = source, + .diagnostics = &diagnostics, + .ignore_unknown_fields = options.ignore_unknown_fields, + }); +} + +/// The declared default of struct field `name`, or null when it has none. +/// Tests use it to assert that a seam's default IS the production function. +/// (Zig 0.17: `@typeInfo` struct info is struct-of-arrays and +/// `std.meta.fieldInfo` is deprecated.) +pub fn fieldDefault(comptime T: type, comptime name: []const u8) ?@FieldType(T, name) { + const info = @typeInfo(T).@"struct"; + inline for (info.field_names, info.field_attrs) |field_name, attrs| { + if (comptime std.mem.eql(u8, field_name, name)) return attrs.defaultValue(@FieldType(T, name)); + } + @compileError("no field '" ++ name ++ "' in " ++ @typeName(T)); +} + /// True if `data`'s SHA-256 equals the lowercase-hex `expected` (64 chars). /// Pure — verifies provisioned-toolchain downloads before use. pub fn sha256Matches(data: []const u8, expected_hex: []const u8) bool { @@ -39,7 +74,7 @@ test "sha256Matches verifies known vectors" { pub fn getTempFilePath(allocator: std.mem.Allocator, name: []const u8) ![]const u8 { const builtin = @import("builtin"); const env = config.globalEnviron(); - const tmp_base: []const u8 = if (builtin.os.tag == .windows) + const tmp_base: []const u8 = if (builtin.target.os.tag == .windows) env.getAlloc(allocator, "TEMP") catch env.getAlloc(allocator, "TMP") catch try allocator.dupe(u8, "C:\\Windows\\Temp") diff --git a/src/cli/watch/cancel.zig b/src/cli/watch/cancel.zig index aa26b72f..8f502024 100644 --- a/src/cli/watch/cancel.zig +++ b/src/cli/watch/cancel.zig @@ -22,7 +22,7 @@ pub var cancel_requested: std.atomic.Value(bool) = .init(false); /// Register the stop handler for this process. Idempotent. pub fn installCancelHandler() void { - if (builtin.os.tag == .windows) { + if (builtin.target.os.tag == .windows) { _ = SetConsoleCtrlHandler(consoleCtrl, .TRUE); } else { var act: std.posix.Sigaction = .{ @@ -73,7 +73,7 @@ test "handleStop: the first stop is latched on every attached group, on every ho defer group.detach(); // The console handler and the signal handler both go through this. try std.testing.expectEqual(.handled, handleStop(.interrupt)); - try std.testing.expect(group.pending.load(.seq_cst) == @as(u8, @intFromEnum(supervise.Stop.interrupt)) + 1); + try std.testing.expect(group.pending.load(.seq_cst) == @as(u8, @backingInt(supervise.Stop.interrupt)) + 1); // A repeat with no tree registered asks the caller to end the process. try std.testing.expectEqual(.exit, handleStop(.interrupt)); } diff --git a/src/cli/watch/publish.zig b/src/cli/watch/publish.zig index faf0a92e..f80a1748 100644 --- a/src/cli/watch/publish.zig +++ b/src/cli/watch/publish.zig @@ -31,7 +31,7 @@ const builtin = @import("builtin"); const config = @import("../config.zig"); const tree = @import("tree.zig"); -const is_windows = builtin.os.tag == .windows; +const is_windows = builtin.target.os.tag == .windows; /// Checks a rebuild runs inside the publication (`Publisher.publish`), so /// the publication is part of the rebuild's transaction (cli#474): @@ -178,9 +178,9 @@ pub const Publisher = struct { var k: u32 = 0; while (k < 1000) : (k += 1) { const name = if (k == 0) - try std.fmt.allocPrint(a, "published-{d}", .{n}) + try a.print("published-{d}", .{n}) else - try std.fmt.allocPrint(a, "published-{d}-{d}", .{ n, k }); + try a.print("published-{d}-{d}", .{ n, k }); errdefer a.free(name); const path = try std.fs.path.join(a, &.{ self.root, name }); defer a.free(path); @@ -218,7 +218,7 @@ pub const Publisher = struct { fn switchTo(self: *Publisher, name: []const u8, dest: []const u8, restore: ?[]const u8) !void { if (is_windows) return self.retargetJunction(dest, restore); const io = config.globalIo(); - const tmp = try std.fmt.allocPrint(self.allocator, "{s}.tmp-{s}", .{ self.output_dir, name }); + const tmp = try self.allocator.print("{s}.tmp-{s}", .{ self.output_dir, name }); defer self.allocator.free(tmp); std.Io.Dir.cwd().deleteFile(io, tmp) catch {}; try std.Io.Dir.cwd().symLink(io, name, tmp, .{ .is_directory = true }); @@ -228,10 +228,10 @@ pub const Publisher = struct { pub fn writeGeneration(self: *Publisher, n: u64) anyerror!void { const io = config.globalIo(); - const tmp = try std.fmt.allocPrint(self.allocator, "{s}.tmp", .{self.generation_file}); + const tmp = try self.allocator.print("{s}.tmp", .{self.generation_file}); defer self.allocator.free(tmp); var buf: [24]u8 = undefined; - try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = tmp, .data = try std.fmt.bufPrint(&buf, "{d}\n", .{n}) }); + try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = tmp, .data = try std.mem.print(&buf, "{d}\n", .{n}) }); // Windows refuses to replace a file another process holds open // without delete sharing (a consumer mid-read): retry briefly. var attempt: u32 = 0; diff --git a/src/cli/watch/session_lock.zig b/src/cli/watch/session_lock.zig index f2921405..1b7e00d7 100644 --- a/src/cli/watch/session_lock.zig +++ b/src/cli/watch/session_lock.zig @@ -21,7 +21,7 @@ const builtin = @import("builtin"); const config = @import("../config.zig"); const lock_open = @import("../lock_open.zig"); -const is_windows = builtin.os.tag == .windows; +const is_windows = builtin.target.os.tag == .windows; /// Byte 0 of the file is a marker: Windows locks that byte (the range /// `std.Io` locks), and a locked range cannot be read through another @@ -40,7 +40,7 @@ pub const SessionLock = struct { took_over: ?u64 = null, pub fn acquire(allocator: std.mem.Allocator, root: []const u8) !SessionLock { - const path = try std.fmt.allocPrint(allocator, "{s}.lock", .{root}); + const path = try allocator.print("{s}.lock", .{root}); errdefer allocator.free(path); if (std.fs.path.dirname(root)) |parent| try std.Io.Dir.cwd().createDirPath(config.globalIo(), parent); const claimed = try claim(path); @@ -105,7 +105,7 @@ fn rewritePid(file: std.Io.File) !void { const io = config.globalIo(); try file.setLength(io, 0); var buf: [32]u8 = undefined; - const text = try std.fmt.bufPrint(&buf, "#{d}\n", .{ownPid()}); + const text = try std.mem.print(&buf, "#{d}\n", .{ownPid()}); try file.writePositionalAll(io, text, 0); } @@ -149,7 +149,7 @@ fn parseOwner(bytes: []const u8) ?u64 { fn ownPid() u64 { if (is_windows) return GetCurrentProcessId(); - if (builtin.os.tag == .linux) return @intCast(std.os.linux.getpid()); + if (builtin.target.os.tag == .linux) return @intCast(std.os.linux.getpid()); return @intCast(std.c.getpid()); } diff --git a/src/cli/watch/tree.zig b/src/cli/watch/tree.zig index 6f57c715..def790bf 100644 --- a/src/cli/watch/tree.zig +++ b/src/cli/watch/tree.zig @@ -555,7 +555,7 @@ test "watchIgnorePath: roots a declared output the way the walk builds paths" { // under test (a leading `./` must still match the walked path) is // separator-agnostic, and the tree-level test above covers it on // every platform. - if (builtin.os.tag == .windows) return error.SkipZigTest; + if (builtin.target.os.tag == .windows) return error.SkipZigTest; const alloc = std.testing.allocator; const plain = try watchIgnorePath(alloc, "/proj", "assets/out.png"); @@ -658,7 +658,7 @@ test "entryKind: a kind the listing reports as .unknown is resolved without foll defer tmp.cleanup(); try tmp.dir.createDirPath(io, "sub"); try tmp.dir.writeFile(io, .{ .sub_path = "file.txt", .data = "x" }); - const links = builtin.os.tag != .windows; // links need a privilege there + const links = builtin.target.os.tag != .windows; // links need a privilege there if (links) try tmp.dir.symLink(io, "sub", "link", .{ .is_directory = true }); // Reported kinds pass through untouched. try std.testing.expectEqual(std.Io.File.Kind.file, try entryKind(io, tmp.dir, .{ .name = "sub", .kind = .file, .inode = 0 })); @@ -669,7 +669,7 @@ test "entryKind: a kind the listing reports as .unknown is resolved without foll } test "computeSignature: a directory swapped for a link mid-walk is not followed (cli#476)" { - if (builtin.os.tag == .windows) return error.SkipZigTest; // links need a privilege there + if (builtin.target.os.tag == .windows) return error.SkipZigTest; // links need a privilege there const io = config.globalIo(); const alloc = std.testing.allocator; var tmp = std.testing.tmpDir(.{}); diff --git a/src/cli/zig_cache.zig b/src/cli/zig_cache.zig index e59fab8e..08717510 100644 --- a/src/cli/zig_cache.zig +++ b/src/cli/zig_cache.zig @@ -28,7 +28,7 @@ const std = @import("std"); const builtin = @import("builtin"); const asm_cache = @import("asm_cache.zig"); -const is_windows = builtin.os.tag == .windows; +const is_windows = builtin.target.os.tag == .windows; /// Subdirectory of the cache root that holds managed Zig toolchains. /// @@ -43,6 +43,19 @@ pub const ZIG_SUBDIR = if (is_windows) "tc" else "zig"; /// user-writable space, never next to a read-only install (epic gotcha). pub const GLOBAL_CACHE_SUBDIR = "zig-global-cache"; +/// Global-compiler-cache subdir used ONLY to build provider tools +/// (`provider_dispatch.runTool`: `zig build --system `). +/// +/// Zig 0.17.1 panics (`reached unreachable code`, `assert(!job_queue.read_only)` +/// in `Maker/Fetch.zig`) when a build run with `--system` has a LAZY +/// dependency that is absent from the system directory while its tarball is +/// in the global cache's `p/`. The shared global cache holds the tarballs of +/// every game build, so a provider declaring a lazy dependency a game also +/// uses (a C-translation package, say) crashed its own tool build. A `--system` +/// build never fetches, so this cache's `p/` stays empty and the lazy +/// dependency is simply reported unavailable, as the provider expects. +pub const PROVIDER_TOOL_GLOBAL_CACHE_SUBDIR = "zig-provider-tool-cache"; + /// Local-compiler-cache subdir under the cache root. Passed as /// `ZIG_LOCAL_CACHE_DIR`. Kept under the labelle tree (rather than the /// project's `.zig-cache/`) so studio-launched builds against a read-only diff --git a/src/cli/zig_toolchain.zig b/src/cli/zig_toolchain.zig index cc68ca91..3f7ebb7d 100644 --- a/src/cli/zig_toolchain.zig +++ b/src/cli/zig_toolchain.zig @@ -24,14 +24,13 @@ //! 3. `zig_version` pin in `project.labelle` (`launcher_manifest`). //! 4. Engine-derived: map the pinned engine version (`project.labelle` //! `engine_version`, else `labelle.lock`) to its required Zig via -//! `zigVersionForEngine`. Today the whole toolkit rides ONE Zig train -//! (0.16.x), so the map returns `DEFAULT_ZIG_VERSION` for the current -//! engine major — but the *source* is attributed to the engine so -//! `toolchain which` reports it honestly, and the map is the seam where -//! future engine-train divergence lands. NOTE: there is no first-class -//! engine→Zig table in the toolkit yet (the engine's +//! `zigVersionForEngine`: engine 1.x-4.x build with Zig 0.16.0, engine +//! 5.x with Zig 0.17.1. An engine major the table does not know falls +//! through to the default — the *source* is attributed to the engine +//! so `toolchain which` reports it honestly. NOTE: there is no +//! first-class engine→Zig table in the toolkit yet (the engine's //! `minimum_zig_version` is not surfaced to the CLI at runtime); this -//! map is the most-defensible stand-in. See PR notes. +//! map is the most-defensible stand-in. //! 5. `DEFAULT_ZIG_VERSION` constant — kept in lockstep with the CLI's own //! build Zig and the SUB2/#280 bundled seed. @@ -43,12 +42,12 @@ const launcher_manifest = @import("launcher_manifest.zig"); const util = @import("util.zig"); const cache_publish = @import("cache_publish.zig"); -const is_windows = builtin.os.tag == .windows; +const is_windows = builtin.target.os.tag == .windows; /// Default Zig version resolved/downloaded when a project pins none and no /// engine mapping applies. Keep in lockstep with the CLI's own build Zig /// (the toolkit rides one Zig train) and with the SUB2/#280 bundled seed. -pub const DEFAULT_ZIG_VERSION = "0.16.0"; +pub const DEFAULT_ZIG_VERSION = "0.17.1"; // ── First-run seed (SUB2 / labelle-cli#280) ──────────────────────────── // @@ -83,7 +82,7 @@ fn seedAllowedFor(version: []const u8) bool { /// download path uses (`zig---.`). This is what a /// CLI-only distribution places under its `seeds/` dir. Caller owns the slice. pub fn seedArchiveName(allocator: std.mem.Allocator, version: []const u8) ![]u8 { - return std.fmt.allocPrint(allocator, "zig-{s}-{s}-{s}.{s}", .{ + return allocator.print("zig-{s}-{s}-{s}.{s}", .{ try archName(), try osName(), version, archive_ext, }); } @@ -191,25 +190,25 @@ pub fn lookupEnvOverride(allocator: std.mem.Allocator) !?[]u8 { /// Zig's os name in the release triple. Zig switched the archive naming from /// `zig---` (≤0.14.0) to `zig---` (0.14.1+); the -/// toolkit rides 0.16.x, so we build the modern arch-first form. +/// toolkit rides 0.16+, so we build the modern arch-first form. fn osName() error{UnsupportedPlatform}![]const u8 { - return switch (builtin.os.tag) { + return switch (builtin.target.os.tag) { .macos => "macos", .linux => "linux", .windows => "windows", else => { - std.debug.print("labelle: unsupported OS for Zig download: {s}\n", .{@tagName(builtin.os.tag)}); + std.debug.print("labelle: unsupported OS for Zig download: {s}\n", .{@tagName(builtin.target.os.tag)}); return error.UnsupportedPlatform; }, }; } fn archName() error{UnsupportedPlatform}![]const u8 { - return switch (builtin.cpu.arch) { + return switch (builtin.target.cpu.arch) { .aarch64 => "aarch64", .x86_64 => "x86_64", else => { - std.debug.print("labelle: unsupported architecture for Zig download: {s}\n", .{@tagName(builtin.cpu.arch)}); + std.debug.print("labelle: unsupported architecture for Zig download: {s}\n", .{@tagName(builtin.target.cpu.arch)}); return error.UnsupportedPlatform; }, }; @@ -222,29 +221,36 @@ const archive_ext = if (is_windows) "zip" else "tar.xz"; /// `https://ziglang.org/download/0.16.0/zig-x86_64-linux-0.16.0.tar.xz`. /// Caller owns the returned slice. pub fn archiveUrl(allocator: std.mem.Allocator, version: []const u8) ![]u8 { - return std.fmt.allocPrint(allocator, "{s}/{s}/zig-{s}-{s}-{s}.{s}", .{ + return allocator.print("{s}/{s}/zig-{s}-{s}-{s}.{s}", .{ ZIG_DOWNLOAD_BASE, version, try archName(), try osName(), version, archive_ext, }); } // ── Version resolution ─────────────────────────────────────────────── -/// Map a pinned engine version to its required Zig version. The toolkit -/// currently ships every package (engine included) on a single Zig train, so -/// any engine on the 1.x major maps to `DEFAULT_ZIG_VERSION`. Returns null for -/// an unrecognized engine so the caller falls through to the default. +/// Map a pinned engine version to the Zig version that engine major builds +/// with. Complete and explicit for every released engine major: /// -/// This is the seam where future divergence lands: when an engine 2.x train -/// requires a different Zig, add an arm here. Kept intentionally small rather -/// than fabricating a speculative table. +/// - engine 1.x-4.x → Zig 0.16.0 +/// - engine 5.x → Zig 0.17.1 +/// +/// These are constants of their own, NOT `DEFAULT_ZIG_VERSION`: a released +/// engine never changes compiler, so a project pinned to engine 2.x-4.x keeps +/// building with Zig 0.16.0 after the CLI default moves on. Returns null only +/// for a major this CLI does not know (0, or one released after it), where +/// the caller falls through to the default. Add an arm per new engine major. pub fn zigVersionForEngine(engine_version: []const u8) ?[]const u8 { const major = util.parseVersion(engine_version) / 1_000_000; return switch (major) { - 1 => DEFAULT_ZIG_VERSION, + 1...4 => zig_for_engine_1_to_4, + 5 => zig_for_engine_5, else => null, }; } +const zig_for_engine_1_to_4 = "0.16.0"; +const zig_for_engine_5 = "0.17.1"; + /// Resolve the Zig VERSION the project requires and where it came from. /// Does not consult the path overrides (those short-circuit in `resolveZig`); /// this is the version-only chain: project pin → engine-derived → default. @@ -285,16 +291,14 @@ fn readLockEngineVersion(allocator: std.mem.Allocator, project_dir: []const u8) @setEvalBranchQuota(10000); const lock_path = std.fs.path.join(allocator, &.{ project_dir, "labelle.lock" }) catch return null; const raw = std.Io.Dir.cwd().readFileAlloc(config.globalIo(), lock_path, allocator, .limited(1024 * 1024)) catch return null; - const raw_z = allocator.dupeZ(u8, raw) catch return null; + const raw_z = allocator.dupeSentinel(u8, raw, 0) catch return null; const LockShape = struct { resolved: ?struct { engine: ?struct { version: []const u8 = "" } = null, } = null, }; - const parsed = std.zon.parse.fromSliceAlloc(LockShape, allocator, raw_z, null, .{ - .ignore_unknown_fields = true, - }) catch return null; + const parsed = util.parseZon(LockShape, allocator, raw_z, .{ .ignore_unknown_fields = true }) catch return null; const resolved = parsed.resolved orelse return null; const engine = resolved.engine orelse return null; if (engine.version.len == 0) return null; @@ -447,7 +451,7 @@ fn resolveSeedSig(allocator: std.mem.Allocator, seed_path: []const u8, env_sig: } } - const adjacent = try std.fmt.allocPrint(allocator, "{s}.minisig", .{seed_path}); + const adjacent = try allocator.print("{s}.minisig", .{seed_path}); if (cwd.access(io, adjacent, .{})) |_| { return adjacent; } else |_| allocator.free(adjacent); @@ -500,7 +504,7 @@ fn ensureInstalledWithSeed(allocator: std.mem.Allocator, version: []const u8, se const zroot = try zig_cache.zigRoot(allocator); defer allocator.free(zroot); cwd.createDirPath(io, zroot) catch {}; - const lock_path = try std.fmt.allocPrint(allocator, "{s}{c}{s}.lock", .{ zroot, std.fs.path.sep, version }); + const lock_path = try allocator.print("{s}{c}{s}.lock", .{ zroot, std.fs.path.sep, version }); defer allocator.free(lock_path); const lock_file = cwd.createFile(io, lock_path, .{ .truncate = false, .lock = .exclusive }) catch |err| { std.debug.print("labelle: could not acquire install lock {s}: {any}\n", .{ lock_path, err }); @@ -551,13 +555,13 @@ fn ensureInstalledWithSeed(allocator: std.mem.Allocator, version: []const u8, se // ── Network download + verify path (#279) ───────────────────── const url = try archiveUrl(allocator, version); defer allocator.free(url); - const archive_name = try std.fmt.allocPrint(allocator, "zig-{s}.{s}", .{ version, archive_ext }); + const archive_name = try allocator.print("zig-{s}.{s}", .{ version, archive_ext }); defer allocator.free(archive_name); const archive_path = try std.fs.path.join(allocator, &.{ staging, archive_name }); defer allocator.free(archive_path); - const sig_path = try std.fmt.allocPrint(allocator, "{s}.minisig", .{archive_path}); + const sig_path = try allocator.print("{s}.minisig", .{archive_path}); defer allocator.free(sig_path); - const sig_url = try std.fmt.allocPrint(allocator, "{s}.minisig", .{url}); + const sig_url = try allocator.print("{s}.minisig", .{url}); defer allocator.free(sig_url); std.debug.print("labelle: downloading Zig {s}...\n", .{version}); @@ -759,7 +763,7 @@ fn extractArchive(allocator: std.mem.Allocator, archive_path: []const u8, dest_d if (!is_windows) { std.debug.print( "labelle: cannot extract a .zip archive on {s} (Zig releases are .tar.xz here); provide a .tar.xz seed\n archive: {s}\n", - .{ @tagName(builtin.os.tag), archive_path }, + .{ @tagName(builtin.target.os.tag), archive_path }, ); return error.ZigSeedFormatUnsupported; } @@ -803,7 +807,7 @@ fn extractZipWindows(allocator: std.mem.Allocator, archive_path: []const u8, des defer allocator.free(archive_q); const scratch_q = try util.escapePowerShellString(allocator, scratch); defer allocator.free(scratch_q); - const ps = try std.fmt.allocPrint(allocator, + const ps = try allocator.print( \\Expand-Archive -LiteralPath '{s}' -DestinationPath '{s}' -Force , .{ archive_q, scratch_q }); defer allocator.free(ps); @@ -937,9 +941,57 @@ test "archiveUrl builds the modern arch-os triple on ziglang.org" { try testing.expect(arch_idx < os_idx); } -test "zigVersionForEngine maps the 1.x train to the default; unknown -> null" { - try testing.expectEqualStrings(DEFAULT_ZIG_VERSION, zigVersionForEngine("1.65.0").?); - try testing.expect(zigVersionForEngine("2.0.0") == null); +test "zigVersionForEngine: engine 1-4 -> Zig 0.16.0, engine 5 -> Zig 0.17.1, unknown -> null" { + for ([_][]const u8{ "1.0.0", "1.65.0", "2.0.0", "2.22.0", "3.4.1", "4.0.0", "4.1.4", "4.99.99" }) |ev| { + try testing.expectEqualStrings("0.16.0", zigVersionForEngine(ev).?); + } + for ([_][]const u8{ "5.0.0", "5.0.1", "5.12.3" }) |ev| { + try testing.expectEqualStrings("0.17.1", zigVersionForEngine(ev).?); + } + // Majors this CLI does not know fall through to the default. + for ([_][]const u8{ "0.9.0", "6.0.0", "not-a-version", "" }) |ev| { + try testing.expect(zigVersionForEngine(ev) == null); + } +} + +// The reason the table exists: the CLI default is Zig 0.17.1, and a project +// pinned to an engine of the Zig 0.16 era must NOT fall through to it. +test "resolveRequiredVersion: engines 2.x-4.x stay on Zig 0.16.0, not the CLI default; engine 5.x gets 0.17.1" { + const alloc = testing.allocator; + const cases = [_]struct { engine: []const u8, zig: []const u8 }{ + .{ .engine = "2.22.0", .zig = "0.16.0" }, + .{ .engine = "3.4.1", .zig = "0.16.0" }, + .{ .engine = "4.1.4", .zig = "0.16.0" }, + .{ .engine = "5.0.0", .zig = "0.17.1" }, + }; + for (cases) |case| { + // Once from project.labelle, once from labelle.lock alone. + for ([_]bool{ true, false }) |in_project| { + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + const project = try std.fmt.allocPrint(alloc, ".{{ .name = \"t\"{s}{s}{s} }}", .{ + if (in_project) ", .engine_version = \"" else "", + if (in_project) case.engine else "", + if (in_project) "\"" else "", + }); + defer alloc.free(project); + try tmp.dir.writeFile(config.globalIo(), .{ .sub_path = "project.labelle", .data = project }); + if (!in_project) { + const lock = try std.fmt.allocPrint(alloc, ".{{ .resolved = .{{ .engine = .{{ .version = \"{s}\" }} }} }}", .{case.engine}); + defer alloc.free(lock); + try tmp.dir.writeFile(config.globalIo(), .{ .sub_path = "labelle.lock", .data = lock }); + } + var buf: [std.Io.Dir.max_path_bytes]u8 = undefined; + const n = try tmp.dir.realPath(config.globalIo(), &buf); + + const r = try resolveRequiredVersion(alloc, buf[0..n]); + defer alloc.free(r.version); + try testing.expectEqualStrings(case.zig, r.version); + try testing.expectEqual(VersionSource.engine_derived, r.source); + } + } + // The premise: were these to fall through, they would get the default. + try testing.expect(!std.mem.eql(u8, "0.16.0", DEFAULT_ZIG_VERSION)); } test "resolveRequiredVersion: no project -> default" { @@ -985,7 +1037,7 @@ test "resolveRequiredVersion: engine_version derives when no explicit pin" { const r = try resolveRequiredVersion(alloc, buf[0..n]); defer alloc.free(r.version); - try testing.expectEqualStrings(DEFAULT_ZIG_VERSION, r.version); + try testing.expectEqualStrings("0.16.0", r.version); try testing.expectEqual(VersionSource.engine_derived, r.source); } @@ -1007,7 +1059,7 @@ test "resolveRequiredVersion: falls back to labelle.lock engine version" { const r = try resolveRequiredVersion(alloc, buf[0..n]); defer alloc.free(r.version); try testing.expectEqual(VersionSource.engine_derived, r.source); - try testing.expectEqualStrings(DEFAULT_ZIG_VERSION, r.version); + try testing.expectEqualStrings("0.16.0", r.version); } test "resolveZig: --zig flag override returns the path verbatim; env wins over flag" { @@ -1068,8 +1120,7 @@ const MiniFixture = struct { var gsig_b64: [100]u8 = undefined; const gsig_b64_s = Enc.encode(&gsig_b64, &gsig.toBytes()); - const sig_text = try std.fmt.allocPrint( - alloc, + const sig_text = try alloc.print( "untrusted comment: x\n{s}\ntrusted comment: {s}\n{s}\n", .{ sig_b64_s, trusted_comment, gsig_b64_s }, ); @@ -1084,7 +1135,7 @@ const MiniFixture = struct { test "verifyMinisign: accepts a valid signature, rejects a tampered file" { const alloc = testing.allocator; - const kp = try std.crypto.sign.Ed25519.KeyPair.generateDeterministic([_]u8{7} ** 32); + const kp = try std.crypto.sign.Ed25519.KeyPair.generateDeterministic(@splat(7)); const file_data = "the labelle managed zig archive bytes"; var fx = try MiniFixture.make(alloc, file_data, kp); @@ -1099,8 +1150,8 @@ test "verifyMinisign: accepts a valid signature, rejects a tampered file" { test "verifyMinisign: rejects a signature from the wrong key" { const alloc = testing.allocator; - const kp = try std.crypto.sign.Ed25519.KeyPair.generateDeterministic([_]u8{11} ** 32); - const other = try std.crypto.sign.Ed25519.KeyPair.generateDeterministic([_]u8{22} ** 32); + const kp = try std.crypto.sign.Ed25519.KeyPair.generateDeterministic(@splat(11)); + const other = try std.crypto.sign.Ed25519.KeyPair.generateDeterministic(@splat(22)); const file_data = "payload"; var fx = try MiniFixture.make(alloc, file_data, kp); @@ -1121,7 +1172,7 @@ test "verifyMinisign: rejects a signature from the wrong key" { test "verifyMinisign: key_id mismatch is caught before crypto" { const alloc = testing.allocator; - const kp = try std.crypto.sign.Ed25519.KeyPair.generateDeterministic([_]u8{33} ** 32); + const kp = try std.crypto.sign.Ed25519.KeyPair.generateDeterministic(@splat(33)); var fx = try MiniFixture.make(alloc, "x", kp); defer fx.deinit(alloc); // Zig's real key has a different key_id than our fixture's {1..8}. @@ -1145,7 +1196,7 @@ fn touch(path: []const u8) !void { test "seedAllowedFor: only the DEFAULT version is ever seeded" { try testing.expect(seedAllowedFor(DEFAULT_ZIG_VERSION)); try testing.expect(!seedAllowedFor("0.15.2")); - try testing.expect(!seedAllowedFor("0.17.0")); + try testing.expect(!seedAllowedFor("0.16.0")); } test "seedArchiveName matches the downloaded archive's basename" { @@ -1258,7 +1309,7 @@ test "resolveSeedSig: env sig wins; else adjacent .minisig; else null" { try testing.expect((try resolveSeedSig(alloc, seed, null)) == null); // Adjacent `.minisig` → picked up. - const adjacent = try std.fmt.allocPrint(alloc, "{s}.minisig", .{seed}); + const adjacent = try alloc.print("{s}.minisig", .{seed}); defer alloc.free(adjacent); try touch(adjacent); { @@ -1292,7 +1343,7 @@ test "resolveSeedSig: LABELLE_ZIG_SEED_SIG set-but-missing FAILS CLOSED (no sile // An ADJACENT `.minisig` exists — so a silent downgrade would happily use // it — but the explicit env opt-in points at a typo path. Must hard-error, // never fall back to the adjacent sig or to no-sig. - const adjacent = try std.fmt.allocPrint(alloc, "{s}.minisig", .{seed}); + const adjacent = try alloc.print("{s}.minisig", .{seed}); defer alloc.free(adjacent); try touch(adjacent); @@ -1375,7 +1426,7 @@ test "ensureInstalledWithSeed: DEFAULT seed extracts to the downloaded layout, n // binary sits directly in the flat version dir, with lib/ beside it. const bin = try zig_cache.binaryPath(alloc, DEFAULT_ZIG_VERSION); defer alloc.free(bin); - try cwd.access(io, bin, .{}); // /zig/0.16.0/zig + try cwd.access(io, bin, .{}); // /zig//zig const vdir = try zig_cache.versionDir(alloc, DEFAULT_ZIG_VERSION); defer alloc.free(vdir); diff --git a/src/stb.zig b/src/stb.zig new file mode 100644 index 00000000..f48a6518 --- /dev/null +++ b/src/stb.zig @@ -0,0 +1,67 @@ +//! Zig declarations for the handful of stb entry points the CLI calls +//! (`vendor/stb/stb_image.h`, `vendor/stb/stb_image_write.h`; the +//! implementation is compiled by build.zig's `wireStb`). +//! +//! Zig 0.17 removed `@cImport`. The replacement for translating a whole +//! header is the external translate-c package, which would add a network +//! dependency and a C-translator build to a CLI that needs seven functions +//! from a vendored, pinned header. They are declared by hand instead, with +//! the exact types `@cImport` produced, so call sites are unchanged. +//! +//! `vendor/stb/stb_image_impl.c` restates each prototype below as a C +//! assignment, so a vendored-header bump that changes one of them fails the +//! build there; keep the two in step. + +pub const stbi_uc = u8; + +/// `typedef void stbi_write_func(void *context, void *data, int size);` +pub const stbi_write_func = fn (context: ?*anyopaque, data: ?*anyopaque, size: c_int) callconv(.c) void; + +pub extern fn stbi_load_from_memory( + buffer: [*c]const stbi_uc, + len: c_int, + x: [*c]c_int, + y: [*c]c_int, + channels_in_file: [*c]c_int, + desired_channels: c_int, +) [*c]stbi_uc; + +pub extern fn stbi_image_free(retval_from_stbi_load: ?*anyopaque) void; + +pub extern fn stbi_write_png_to_func( + func: ?*const stbi_write_func, + context: ?*anyopaque, + w: c_int, + h: c_int, + comp: c_int, + data: ?*const anyopaque, + stride_in_bytes: c_int, +) c_int; + +pub extern fn stbi_write_bmp_to_func( + func: ?*const stbi_write_func, + context: ?*anyopaque, + w: c_int, + h: c_int, + comp: c_int, + data: ?*const anyopaque, +) c_int; + +pub extern fn stbi_write_tga_to_func( + func: ?*const stbi_write_func, + context: ?*anyopaque, + w: c_int, + h: c_int, + comp: c_int, + data: ?*const anyopaque, +) c_int; + +pub extern fn stbi_write_jpg_to_func( + func: ?*const stbi_write_func, + context: ?*anyopaque, + w: c_int, + h: c_int, + comp: c_int, + data: ?*const anyopaque, + quality: c_int, +) c_int; diff --git a/src/texpack/texpack.zig b/src/texpack/texpack.zig index fd195e22..e6e9eec9 100644 --- a/src/texpack/texpack.zig +++ b/src/texpack/texpack.zig @@ -10,10 +10,7 @@ const std = @import("std"); const maxrects = @import("maxrects.zig"); const atlas_json = @import("atlas_json.zig"); -const c = @cImport({ - @cInclude("stb_image.h"); - @cInclude("stb_image_write.h"); -}); +const c = @import("../stb.zig"); pub const Options = struct { /// Transparent gap reserved to the right/bottom of each sprite, px. @@ -146,9 +143,9 @@ pub fn packDir( const png_bytes = try renderSheetPng(allocator, sprites.items, sheet.w, sheet.h); defer allocator.free(png_bytes); - const png_name = try std.fmt.allocPrint(allocator, "{s}.atlas.png", .{name}); + const png_name = try allocator.print("{s}.atlas.png", .{name}); defer allocator.free(png_name); - const json_name = try std.fmt.allocPrint(allocator, "{s}.atlas.json", .{name}); + const json_name = try allocator.print("{s}.atlas.json", .{name}); defer allocator.free(json_name); // Stable JSON frame order regardless of the size-sorted placement. @@ -254,7 +251,7 @@ fn scanInto( const rel_key = if (rel.len == 0) try allocator.dupe(u8, entry.name) else - try std.fmt.allocPrint(allocator, "{s}/{s}", .{ rel, entry.name }); + try allocator.print("{s}/{s}", .{ rel, entry.name }); errdefer allocator.free(rel_key); if (entry.kind == .directory) { @@ -783,7 +780,7 @@ pub const NonSquareSheets = struct { for (0..4) |i| { const png = try encodeSolidPng(allocator, 64, 8, .{ 255, 0, 0, 255 }); defer allocator.free(png); - const name = try std.fmt.allocPrint(allocator, "strip{d}.png", .{i}); + const name = try allocator.print("strip{d}.png", .{i}); defer allocator.free(name); const path = try std.fs.path.join(allocator, &.{ work, name }); defer allocator.free(path); diff --git a/test/fixtures/child.zig b/test/fixtures/child.zig index 88010448..f336f17b 100644 --- a/test/fixtures/child.zig +++ b/test/fixtures/child.zig @@ -37,7 +37,7 @@ pub fn main(init: std.process.Init) !u8 { const grandchild = try std.process.spawn(init.io, .{ .argv = &.{ exe, "sleep:60000" }, .stdin = .ignore, .stdout = .ignore, .stderr = .ignore }); const pid: u64 = if (@import("builtin").os.tag == .windows) GetProcessId(grandchild.id.?) else @intCast(grandchild.id.?); var buf: [32]u8 = undefined; - try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = pid_file, .data = try std.fmt.bufPrint(&buf, "{d}\n", .{pid}) }); + try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = pid_file, .data = try std.mem.print(&buf, "{d}\n", .{pid}) }); sleepMs(60_000); return 0; } @@ -52,7 +52,7 @@ pub fn main(init: std.process.Init) !u8 { const grandchild = try std.process.spawn(init.io, options); const pid: u64 = if (@import("builtin").os.tag == .windows) GetProcessId(grandchild.id.?) else @intCast(grandchild.id.?); var buf: [32]u8 = undefined; - try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = pid_file, .data = try std.fmt.bufPrint(&buf, "{d}\n", .{pid}) }); + try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = pid_file, .data = try std.mem.print(&buf, "{d}\n", .{pid}) }); try std.Io.File.stdout().writeStreamingAll(init.io, "child-output\n"); return 0; } diff --git a/test/fixtures/provider/build.zig b/test/fixtures/provider/build.zig index aeacb6d0..5a5ebea1 100644 --- a/test/fixtures/provider/build.zig +++ b/test/fixtures/provider/build.zig @@ -1,18 +1,12 @@ const std = @import("std"); pub fn build(b: *std.Build) void { + // Zig 0.17 caches the configure phase and does not track the environment + // reads below: without this, a cached configuration skips both checks. + b.graph.poisonCache(); // A hook's environment contribution (contract §2 `env_file`) reaches the // hooks' own processes and the project's zig invocations, never the // build of a provider's host tool: this build refuses to run with one. if (b.graph.environ_map.get("PROBE_TOOLCHAIN") != null) @panic("a hook environment contribution reached the provider tool build"); - // `PROVIDER_PROBE_BUILD_STDOUT=`: the tool's build prints `` - // on stdout, the way a chatty provider build might, so a suite can check - // it never reaches a stdout the CLI owns (`labelle doctor --json`). - if (b.graph.environ_map.get("PROVIDER_PROBE_BUILD_STDOUT")) |text| { - var buf: [256]u8 = undefined; - var out = std.Io.File.stdout().writerStreaming(b.graph.io, &buf); - out.interface.print("{s}\n", .{text}) catch {}; - out.interface.flush() catch {}; - } const exe = b.addExecutable(.{ .name = "provider-probe", .root_module = b.createModule(.{ @@ -21,6 +15,17 @@ pub fn build(b: *std.Build) void { }), }); const install = b.addInstallArtifact(exe, .{}); + // `PROVIDER_PROBE_BUILD_STDOUT=`: the tool's build prints `` + // on stdout, the way a chatty provider build might, so a suite can check + // it never reaches a stdout the CLI owns (`labelle doctor --json`). A + // build step prints it: in Zig 0.17 the stdout of `build.zig` itself + // carries the configuration to the build runner. + if (b.graph.environ_map.get("PROVIDER_PROBE_BUILD_STDOUT")) |text| { + const noise = b.addRunArtifact(exe); + noise.addArgs(&.{ "build-noise", text }); + noise.stdio = .inherit; + install.step.dependOn(&noise.step); + } b.step("probe-tool", "Install the host probe").dependOn(&install.step); _ = b.step("missing-tool", "Succeed without installing the declared artifact"); } diff --git a/test/fixtures/provider/main.zig b/test/fixtures/provider/main.zig index 59c957c7..b92cfb51 100644 --- a/test/fixtures/provider/main.zig +++ b/test/fixtures/provider/main.zig @@ -6,10 +6,21 @@ pub fn main(init: std.process.Init) !u8 { { var probe_args = try std.process.Args.Iterator.initAllocator(init.minimal.args, a); _ = probe_args.skip(); - if (probe_args.next()) |first| if (std.mem.eql(u8, first, "linger")) { - init.io.sleep(std.Io.Duration.fromSeconds(120), .awake) catch {}; - return 0; - }; + if (probe_args.next()) |first| { + if (std.mem.eql(u8, first, "linger")) { + init.io.sleep(std.Io.Duration.fromSeconds(120), .awake) catch {}; + return 0; + } + // `provider-probe build-noise `: run by this package's own + // build (`PROVIDER_PROBE_BUILD_STDOUT`) to print on its stdout. + if (std.mem.eql(u8, first, "build-noise")) { + var buf: [256]u8 = undefined; + var out = std.Io.File.stdout().writerStreaming(init.io, &buf); + try out.interface.print("{s}\n", .{probe_args.next() orelse ""}); + try out.interface.flush(); + return 0; + } + } } const context = try init.minimal.environ.getAlloc(a, "LABELLE_CONTEXT"); const bytes = try std.Io.Dir.cwd().readFileAlloc(init.io, context, a, .limited(1024 * 1024)); @@ -114,7 +125,7 @@ pub fn main(init: std.process.Init) !u8 { const id = parts.next() orelse return error.BadProbeNestedSpec; const result = parts.next() orelse return error.BadProbeNestedSpec; const labelle = parts.next() orelse return error.BadProbeNestedSpec; - const armed = if (std.Io.Dir.cwd().access(init.io, try std.fmt.allocPrint(a, "{s}.arm", .{result}), .{})) |_| true else |_| false; + const armed = if (std.Io.Dir.cwd().access(init.io, try a.print("{s}.arm", .{result}), .{})) |_| true else |_| false; const done = if (std.Io.Dir.cwd().access(init.io, result, .{})) |_| true else |_| false; if (armed and !done and invocation == .object and std.mem.eql(u8, invocation.object.get("id").?.string, id)) { try nested(init, a, result, labelle, ctx.value.object.get("project_dir").?.string, ctx.value.object.get("target").?.string); @@ -127,7 +138,7 @@ pub fn main(init: std.process.Init) !u8 { // survives it. if (init.minimal.environ.getAlloc(a, "PROVIDER_PROBE_SLOW")) |spec| { const bar = std.mem.indexOfScalar(u8, spec, '|') orelse return error.BadProbeSlowSpec; - const armed = if (std.Io.Dir.cwd().access(init.io, try std.fmt.allocPrint(a, "{s}.arm", .{spec[bar + 1 ..]}), .{})) |_| true else |_| false; + const armed = if (std.Io.Dir.cwd().access(init.io, try a.print("{s}.arm", .{spec[bar + 1 ..]}), .{})) |_| true else |_| false; if (armed and invocation == .object and std.mem.eql(u8, invocation.object.get("id").?.string, spec[0..bar])) { try linger(init, a, spec[bar + 1 ..]); init.io.sleep(std.Io.Duration.fromSeconds(120), .awake) catch {}; @@ -186,7 +197,7 @@ pub fn main(init: std.process.Init) !u8 { if (invocation == .object and std.mem.eql(u8, invocation.object.get("id").?.string, patch_id)) { try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = try std.fs.path.join(a, &.{ output, "bin", "data.txt" }), - .data = try std.fmt.allocPrint(a, "patched:{s}", .{patch_id}), + .data = try a.print("patched:{s}", .{patch_id}), }); } } else |_| {} @@ -247,7 +258,7 @@ pub fn main(init: std.process.Init) !u8 { // `--json` report. Printed before the failure knobs below, so a failing // doctor can still report. if (init.minimal.environ.getAlloc(a, "PROVIDER_PROBE_STDOUT")) |dir| { - const file = try std.fs.path.join(a, &.{ dir, try std.fmt.allocPrint(a, "{s}.out", .{std.fs.path.basename(output)}) }); + const file = try std.fs.path.join(a, &.{ dir, try a.print("{s}.out", .{std.fs.path.basename(output)}) }); if (std.Io.Dir.cwd().readFileAlloc(init.io, file, a, .limited(4 * 1024 * 1024))) |report| { var out_buf: [4096]u8 = undefined; var out = std.Io.File.stdout().writerStreaming(init.io, &out_buf); @@ -275,7 +286,7 @@ pub fn main(init: std.process.Init) !u8 { fn findOnPath(init: std.process.Init, a: std.mem.Allocator, name: []const u8) !?[]const u8 { const is_windows = @import("builtin").os.tag == .windows; - const file = if (is_windows) try std.fmt.allocPrint(a, "{s}.exe", .{name}) else name; + const file = if (is_windows) try a.print("{s}.exe", .{name}) else name; const path_value = init.minimal.environ.getAlloc(a, "PATH") catch return null; var dirs = std.mem.splitScalar(u8, path_value, std.fs.path.delimiter); while (dirs.next()) |dir| { @@ -295,8 +306,8 @@ fn linger(init: std.process.Init, a: std.mem.Allocator, marker: []const u8) !voi const is_windows = @import("builtin").os.tag == .windows; const own: u64 = if (is_windows) GetCurrentProcessId() else if (@import("builtin").os.tag == .linux) @intCast(std.os.linux.getpid()) else @intCast(std.c.getpid()); const theirs: u64 = if (is_windows) GetProcessId(child.id.?) else @intCast(child.id.?); - const tmp = try std.fmt.allocPrint(a, "{s}.tmp", .{marker}); - try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = tmp, .data = try std.fmt.allocPrint(a, "{d} {d}\n", .{ own, theirs }) }); + const tmp = try a.print("{s}.tmp", .{marker}); + try std.Io.Dir.cwd().writeFile(init.io, .{ .sub_path = tmp, .data = try a.print("{d} {d}\n", .{ own, theirs }) }); try std.Io.Dir.cwd().rename(tmp, std.Io.Dir.cwd(), marker, init.io); } @@ -320,7 +331,7 @@ fn watchServer(init: std.process.Init, a: std.mem.Allocator, output: []const u8, const data_path = try std.fs.path.join(a, &.{ output_dir, "bin", "data.txt" }); const data = std.Io.Dir.cwd().readFileAlloc(io, data_path, a, .limited(1024)) catch "missing"; const previous = std.Io.Dir.cwd().readFileAlloc(io, log_path, a, .limited(1 << 20)) catch ""; - const line = try std.fmt.allocPrint(a, "{s}gen={s} data={s}\n", .{ previous, gen, std.mem.trim(u8, data, " \r\n") }); + const line = try a.print("{s}gen={s} data={s}\n", .{ previous, gen, std.mem.trim(u8, data, " \r\n") }); try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = log_path, .data = line }); } } else |_| {} @@ -358,17 +369,17 @@ fn nested(init: std.process.Init, a: std.mem.Allocator, result: []const u8, labe const owner: ?[]const u8 = std.Io.Dir.cwd().readFileAlloc(io, owner_path, a, .limited(256)) catch null; const started = std.Io.Timestamp.now(io, .awake); const run = std.process.run(a, io, .{ - .argv = &.{ labelle, "generate", try std.fmt.allocPrint(a, "--platform={s}", .{target}), "--progress=off" }, + .argv = &.{ labelle, "generate", try a.print("--platform={s}", .{target}), "--progress=off" }, .cwd = .{ .path = project }, .environ_map = &env, }); const elapsed_ms = @divTrunc(std.Io.Timestamp.now(io, .awake).nanoseconds - started.nanoseconds, std.time.ns_per_ms); const code: []const u8, const stderr: []const u8 = if (run) |r| .{ switch (r.term) { - .exited => |c| try std.fmt.allocPrint(a, "{d}", .{c}), + .exited => |c| try a.print("{d}", .{c}), else => "signal", }, r.stderr } else |err| .{ @errorName(err), "" }; const report = try std.json.Stringify.valueAlloc(a, .{ .code = code, .elapsed_ms = elapsed_ms, .marker = marker, .owner = owner, .stderr = stderr }, .{}); - const tmp = try std.fmt.allocPrint(a, "{s}.tmp", .{result}); + const tmp = try a.print("{s}.tmp", .{result}); try std.Io.Dir.cwd().writeFile(io, .{ .sub_path = tmp, .data = report }); try std.Io.Dir.cwd().rename(tmp, std.Io.Dir.cwd(), result, io); } diff --git a/test/gui-plugin-test/scripts/gui.zig b/test/gui-plugin-test/scripts/gui.zig index 1751e7af..3ec09ae4 100644 --- a/test/gui-plugin-test/scripts/gui.zig +++ b/test/gui-plugin-test/scripts/gui.zig @@ -4,7 +4,7 @@ var show_demo: bool = true; var counter: i32 = 0; var slider_val: f32 = 0.5; var checkbox_val: bool = false; -var input_buf: [128]u8 = [_]u8{0} ** 128; +var input_buf: [128]u8 = @splat(0); var combo_current: i32 = 0; var color: [3]f32 = .{ 0.4, 0.7, 1.0 }; var progress: f32 = 0.0; diff --git a/test/nuklear-plugin-test/.labelle/raylib_desktop/scripts/gui.zig b/test/nuklear-plugin-test/.labelle/raylib_desktop/scripts/gui.zig index c1bf8ce0..f09d68b5 100644 --- a/test/nuklear-plugin-test/.labelle/raylib_desktop/scripts/gui.zig +++ b/test/nuklear-plugin-test/.labelle/raylib_desktop/scripts/gui.zig @@ -5,7 +5,7 @@ const c = nk.c; var slider_val: f32 = 0.5; var checkbox_val: bool = false; var counter: i32 = 0; -var text_buf: [128]u8 = [_]u8{0} ** 128; +var text_buf: [128]u8 = @splat(0); var text_len: c_int = 0; var spawned: bool = false; @@ -54,7 +54,7 @@ pub fn drawGui(g: anytype) void { } c.nk_layout_row_dynamic(ctx, 25, 1); var buf: [64]u8 = undefined; - const label = std.fmt.bufPrintZ(&buf, "Counter: {d}", .{counter}) catch "?"; + const label = std.mem.printSentinel(&buf, "Counter: {d}", .{counter}, 0) catch "?"; c.nk_label(ctx, label.ptr, c.NK_TEXT_LEFT); c.nk_layout_row_dynamic(ctx, 5, 1); @@ -66,7 +66,7 @@ pub fn drawGui(g: anytype) void { c.nk_layout_row_dynamic(ctx, 25, 1); _ = c.nk_slider_float(ctx, 0.0, &slider_val, 1.0, 0.01); var sbuf: [32]u8 = undefined; - const slabel = std.fmt.bufPrintZ(&sbuf, "Value: {d:.2}", .{slider_val}) catch "?"; + const slabel = std.mem.printSentinel(&sbuf, "Value: {d:.2}", .{slider_val}, 0) catch "?"; c.nk_label(ctx, slabel.ptr, c.NK_TEXT_LEFT); c.nk_layout_row_dynamic(ctx, 5, 1); diff --git a/test/nuklear-plugin-test/scripts/gui.zig b/test/nuklear-plugin-test/scripts/gui.zig index c1bf8ce0..f09d68b5 100644 --- a/test/nuklear-plugin-test/scripts/gui.zig +++ b/test/nuklear-plugin-test/scripts/gui.zig @@ -5,7 +5,7 @@ const c = nk.c; var slider_val: f32 = 0.5; var checkbox_val: bool = false; var counter: i32 = 0; -var text_buf: [128]u8 = [_]u8{0} ** 128; +var text_buf: [128]u8 = @splat(0); var text_len: c_int = 0; var spawned: bool = false; @@ -54,7 +54,7 @@ pub fn drawGui(g: anytype) void { } c.nk_layout_row_dynamic(ctx, 25, 1); var buf: [64]u8 = undefined; - const label = std.fmt.bufPrintZ(&buf, "Counter: {d}", .{counter}) catch "?"; + const label = std.mem.printSentinel(&buf, "Counter: {d}", .{counter}, 0) catch "?"; c.nk_label(ctx, label.ptr, c.NK_TEXT_LEFT); c.nk_layout_row_dynamic(ctx, 5, 1); @@ -66,7 +66,7 @@ pub fn drawGui(g: anytype) void { c.nk_layout_row_dynamic(ctx, 25, 1); _ = c.nk_slider_float(ctx, 0.0, &slider_val, 1.0, 0.01); var sbuf: [32]u8 = undefined; - const slabel = std.fmt.bufPrintZ(&sbuf, "Value: {d:.2}", .{slider_val}) catch "?"; + const slabel = std.mem.printSentinel(&sbuf, "Value: {d:.2}", .{slider_val}, 0) catch "?"; c.nk_label(ctx, slabel.ptr, c.NK_TEXT_LEFT); c.nk_layout_row_dynamic(ctx, 5, 1); diff --git a/test/progress_e2e.zig b/test/progress_e2e.zig index 378600f3..eebf989f 100644 --- a/test/progress_e2e.zig +++ b/test/progress_e2e.zig @@ -328,7 +328,7 @@ test "progress feed e2e: real build --progress=json, concurrent status file, fai const assembler_bin = (try envOpt(a, "LABELLE_ASSEMBLER")) orelse return error.SkipZigTest; if (assembler_bin.len == 0 or deps_dir.len == 0) return error.SkipZigTest; - const exe_suffix = if (builtin.os.tag == .windows) ".exe" else ""; + const exe_suffix = if (builtin.target.os.tag == .windows) ".exe" else ""; const cli_bin_raw = (try envOpt(a, "LABELLE_E2E_CLI_BIN")) orelse try std.fs.path.join(a, &.{ "zig-out", "bin", "labelle" ++ exe_suffix }); const cli_src = (try envOpt(a, "LABELLE_E2E_CLI_SRC")) orelse @@ -366,7 +366,7 @@ test "progress feed e2e: real build --progress=json, concurrent status file, fai const base_len = try tmp.dir.realPath(io, &base_buf); const project_dir = try std.fs.path.join(a, &.{ base_buf[0..base_len], "progress_e2e" }); - const project_labelle = try std.fmt.allocPrint(a, + const project_labelle = try a.print( \\.{{ \\ .name = "progress_e2e", .title = "progress_e2e", .width = 800, .height = 600, .target_fps = 60, \\ .y_axis = .up, diff --git a/test/provider_dispatch_e2e.py b/test/provider_dispatch_e2e.py index e7aa5d1b..42c1f8ad 100644 --- a/test/provider_dispatch_e2e.py +++ b/test/provider_dispatch_e2e.py @@ -85,10 +85,15 @@ def run(*args, code=0, cwd=nested): assert Path(ctx["lock_file"]) == lock_file assert not Path(first["context_path"]).exists(), "context not cleaned after success" assert not list((home / "provider-runs").iterdir()), "run workspace not cleaned" - cache_before = {p: (p.stat().st_size, p.stat().st_mtime_ns) for p in (home / "zig-local-cache" / "o").rglob("*") if p.is_file()} - assert cache_before, "cache reuse assertion needs actual compiled artifacts" + # Zig 0.17 rewrites the generated `o//dependencies.zig` (same bytes, + # new mtime) on every `zig build`; it is a build-runner input, not a + # compiled artifact, so it is compared by size only. + def compiled(): + return {p: (p.stat().st_size, None if p.name == "dependencies.zig" else p.stat().st_mtime_ns) for p in (home / "zig-local-cache" / "o").rglob("*") if p.is_file()} + cache_before = compiled() + assert any(stamp for _, stamp in cache_before.values()), "cache reuse assertion needs actual compiled artifacts" run("probe", "inspect") - cache_after = {p: (p.stat().st_size, p.stat().st_mtime_ns) for p in (home / "zig-local-cache" / "o").rglob("*") if p.is_file()} + cache_after = compiled() assert cache_after == cache_before, "unchanged invocation did not reuse compiled artifacts" (provider / "revision.zig").write_text('pub const value = "edited";\n') run("probe", "inspect") diff --git a/test/provider_hooks_e2e.py b/test/provider_hooks_e2e.py index c313f2c2..271d5372 100644 --- a/test/provider_hooks_e2e.py +++ b/test/provider_hooks_e2e.py @@ -86,13 +86,19 @@ def backend_of(root): 'pub fn build(b: *std.Build) void {\\n' ' const optimize = b.standardOptimizeOption(.{});\\n' ' const probe_opt = b.option([]const u8, "probe_opt", "an e2e build option") orelse "-";\\n' + # Zig 0.17 caches the configure phase; the log below is a side + # effect it does not track, so every invocation must configure. + ' b.graph.poisonCache();\\n' ' if (b.graph.environ_map.get("PROBE_CONFIGURE_LOG") != null) {\\n' - ' const log_path = b.pathFromRoot("configure.log");\\n' + ' const log_path = b.root.joinString(b.allocator, "configure.log") catch @panic("OOM");\\n' ' const previous = std.Io.Dir.cwd().readFileAlloc(b.graph.io, log_path, b.allocator, .limited(65536)) catch "";\\n' + # The mode as the CLI spells it (`-Doptimize=ReleaseSafe`): Zig + # 0.17 renamed the enum tags to debug / safe / fast / small. + ' const mode = switch (optimize) { .debug => "Debug", .safe => "ReleaseSafe", .fast => "ReleaseFast", .small => "ReleaseSmall" };\\n' ' const value = b.graph.environ_map.get("PROBE_TOOLCHAIN") orelse "-";\\n' ' const path_env = b.graph.environ_map.get("PATH") orelse "";\\n' ' const head = path_env[0 .. std.mem.indexOfScalar(u8, path_env, std.fs.path.delimiter) orelse path_env.len];\\n' - ' const line = b.fmt("{s}{s}|{s}|{s}|{s}\\\\n", .{ previous, @tagName(optimize), value, head, probe_opt });\\n' + ' const line = b.fmt("{s}{s}|{s}|{s}|{s}\\\\n", .{ previous, mode, value, head, probe_opt });\\n' ' std.Io.Dir.cwd().writeFile(b.graph.io, .{ .sub_path = log_path, .data = line }) catch @panic("configure.log");\\n' ' }\\n' ' const exe = b.addExecutable(.{ .name = "game", .root_module = b.createModule(.{\\n' diff --git a/test/run_exit_e2e.zig b/test/run_exit_e2e.zig index 9664222b..5fd3bd0a 100644 --- a/test/run_exit_e2e.zig +++ b/test/run_exit_e2e.zig @@ -45,7 +45,7 @@ const Fixture = struct { var env = try std.testing.environ.createMap(self.a); defer env.deinit(); if (spec) |s| try env.put("E390_EXIT", s); - const timeout_arg = try std.fmt.allocPrint(self.a, "--timeout={s}", .{timeout}); + const timeout_arg = try self.a.print("--timeout={s}", .{timeout}); var argv: std.ArrayList([]const u8) = .empty; try argv.appendSlice(self.a, &.{ self.cli_bin, "run", self.project_dir, timeout_arg }); if (stdout_path != null) try argv.append(self.a, "--progress=json"); @@ -78,7 +78,7 @@ test "run exit e2e: the CLI's exit status is the game's — crash, abort, clean, const deps_dir = (try envOpt(a, "LABELLE_E2E_DEPS")) orelse return error.SkipZigTest; const assembler_bin = (try envOpt(a, "LABELLE_ASSEMBLER")) orelse return error.SkipZigTest; if (assembler_bin.len == 0 or deps_dir.len == 0) return error.SkipZigTest; - const exe_suffix = if (builtin.os.tag == .windows) ".exe" else ""; + const exe_suffix = if (builtin.target.os.tag == .windows) ".exe" else ""; const cli_bin_raw = (try envOpt(a, "LABELLE_E2E_CLI_BIN")) orelse try std.fs.path.join(a, &.{ "zig-out", "bin", "labelle" ++ exe_suffix }); const cli_src = (try envOpt(a, "LABELLE_E2E_CLI_SRC")) orelse @@ -105,7 +105,7 @@ test "run exit e2e: the CLI's exit status is the game's — crash, abort, clean, const base_len = try tmp.dir.realPath(io, &base_buf); const project_dir = try std.fs.path.join(a, &.{ base_buf[0..base_len], "exit_e2e" }); - const project_labelle = try std.fmt.allocPrint(a, + const project_labelle = try a.print( \\.{{ \\ .name = "exit_e2e", .title = "exit_e2e", .width = 320, .height = 200, .target_fps = 60, \\ .backend = .null, .y_axis = .up, .ecs = .zig_ecs, .plugins = .{{}}, @@ -184,7 +184,7 @@ test "run exit e2e: the CLI's exit status is the game's — crash, abort, clean, // ── 3. abnormal termination ──────────────────────────────────────── const abort_code = code(try fx.run("abort", "120s", null)) orelse return error.TestUnexpectedResult; try std.testing.expect(abort_code != 0); - if (builtin.os.tag != .windows) try std.testing.expectEqual(@as(u8, 128 + 6), abort_code); + if (builtin.target.os.tag != .windows) try std.testing.expectEqual(@as(u8, 128 + 6), abort_code); // ── 4. a normal run: the headless main plays its frames and returns ─ try std.testing.expectEqual(@as(?u8, 0), code(try fx.run(null, "120s", null))); diff --git a/test/test_freshness_e2e.zig b/test/test_freshness_e2e.zig index c4c808e0..5f81de87 100644 --- a/test/test_freshness_e2e.zig +++ b/test/test_freshness_e2e.zig @@ -77,7 +77,7 @@ const Fixture = struct { /// `labelle test --no-libs`, stderr+stdout captured. fn labelleTest(self: *Fixture) !Result { self.runs += 1; - const log_path = try std.fmt.allocPrint(self.a, "{s}/labelle-test-{d}.log", .{ self.project_dir, self.runs }); + const log_path = try self.a.print("{s}/labelle-test-{d}.log", .{ self.project_dir, self.runs }); const log_file = try std.Io.Dir.cwd().createFile(io, log_path, .{}); var child = try std.process.spawn(io, .{ .argv = &.{ self.cli_bin, "test", self.project_dir, "--no-libs" }, @@ -152,7 +152,7 @@ test "test freshness e2e: only `labelle test` between edits — edit, add, delet const deps_dir = (try envOpt(a, "LABELLE_E2E_DEPS")) orelse return error.SkipZigTest; const assembler_bin = (try envOpt(a, "LABELLE_ASSEMBLER")) orelse return error.SkipZigTest; if (assembler_bin.len == 0 or deps_dir.len == 0) return error.SkipZigTest; - const exe_suffix = if (builtin.os.tag == .windows) ".exe" else ""; + const exe_suffix = if (builtin.target.os.tag == .windows) ".exe" else ""; const cli_bin_raw = (try envOpt(a, "LABELLE_E2E_CLI_BIN")) orelse try std.fs.path.join(a, &.{ "zig-out", "bin", "labelle" ++ exe_suffix }); const cli_src = (try envOpt(a, "LABELLE_E2E_CLI_SRC")) orelse @@ -179,7 +179,7 @@ test "test freshness e2e: only `labelle test` between edits — edit, add, delet const base_len = try tmp.dir.realPath(io, &base_buf); const project_dir = try std.fs.path.join(a, &.{ base_buf[0..base_len], "fresh_e2e" }); - const project_labelle = try std.fmt.allocPrint(a, + const project_labelle = try a.print( \\.{{ \\ .name = "fresh_e2e", .title = "fresh_e2e", .width = 320, .height = 200, .target_fps = 60, \\ .backend = .null, .y_axis = .up, .ecs = .zig_ecs, .plugins = .{{}}, diff --git a/vendor/stb/stb_image_impl.c b/vendor/stb/stb_image_impl.c index 307bca58..19144672 100644 --- a/vendor/stb/stb_image_impl.c +++ b/vendor/stb/stb_image_impl.c @@ -19,3 +19,24 @@ #define STB_IMAGE_WRITE_IMPLEMENTATION #define STBI_WRITE_NO_STDIO #include "stb_image_write.h" + +/* Prototype guard for `src/stb.zig`. Zig 0.17 removed `@cImport`, so the + CLI declares the stb entry points it calls by hand. Each assignment + below restates one of those declarations in C: if a vendored-header + bump changes a signature, this file stops compiling instead of the Zig + side calling through a stale prototype. Keep in step with src/stb.zig. */ +typedef void labelle_stb_write_fn(void *context, void *data, int size); +static unsigned char *(*const labelle_stb_check_load)(unsigned char const *, int, int *, int *, int *, int) = stbi_load_from_memory; +static void (*const labelle_stb_check_free)(void *) = stbi_image_free; +static int (*const labelle_stb_check_png)(labelle_stb_write_fn *, void *, int, int, int, const void *, int) = stbi_write_png_to_func; +static int (*const labelle_stb_check_bmp)(labelle_stb_write_fn *, void *, int, int, int, const void *) = stbi_write_bmp_to_func; +static int (*const labelle_stb_check_tga)(labelle_stb_write_fn *, void *, int, int, int, const void *) = stbi_write_tga_to_func; +static int (*const labelle_stb_check_jpg)(labelle_stb_write_fn *, void *, int, int, int, const void *, int) = stbi_write_jpg_to_func; +void labelle_stb_prototype_guard(void) { + (void)labelle_stb_check_load; + (void)labelle_stb_check_free; + (void)labelle_stb_check_png; + (void)labelle_stb_check_bmp; + (void)labelle_stb_check_tga; + (void)labelle_stb_check_jpg; +} diff --git a/versions.zon b/versions.zon index 117a4f42..4bc7737f 100644 --- a/versions.zon +++ b/versions.zon @@ -3,9 +3,11 @@ // packages version on INDEPENDENT minor trains (the assembler unifies them // onto the project's core at build time), so these minors differ by design. // Bump to the latest releases as they're cut + CI-verified together. - .core = "2.1.0", - .engine = "3.4.1", - .gfx = "2.2.0", + // This set is the first one for Zig 0.17.1 (core 3 / engine 5 / gfx 3); + // the Zig 0.16 lines were core 2.x, engine 2.x-4.x and gfx 2.x. + .core = "3.0.0", + .engine = "5.0.0", + .gfx = "3.0.0", // No backend package pin (RFC cli#471 D4): `upgrade all` delegates the // backend bump to `labelle-assembler upgrade backend`, which pairs it // with gfx through its own version floors.