From 3d47786735c7ecfb7e129d9c364cfccd7fb684fb Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Wed, 18 Nov 2026 12:13:42 +0000 Subject: [PATCH 1/7] test(atomic): cover atomicWrite failure paths Add openat, write and renameat hooks to atomic.Ops so tests can inject failures. Cover atomicWrite when the disk is full (`ENOSPC`), the file system is read-only (`EROFS`) and the rename crosses devices (`EXDEV`), plus the makedirs and fsyncDir error paths. --- changelog.d/+atomic-write-error-tests.misc.md | 1 + src/atomic.zig | 41 ++++++++++++++++-- src/atomic_test.zig | 43 +++++++++++++++++++ 3 files changed, 82 insertions(+), 3 deletions(-) create mode 100644 changelog.d/+atomic-write-error-tests.misc.md diff --git a/changelog.d/+atomic-write-error-tests.misc.md b/changelog.d/+atomic-write-error-tests.misc.md new file mode 100644 index 0000000..a163b29 --- /dev/null +++ b/changelog.d/+atomic-write-error-tests.misc.md @@ -0,0 +1 @@ +Add `atomic.Ops` fault hooks and unit tests covering `atomicWrite` failures on `ENOSPC`, `EROFS`, and `EXDEV`, as well as `makedirs` and `fsyncDir` error paths. diff --git a/src/atomic.zig b/src/atomic.zig index 2618440..3f56ece 100644 --- a/src/atomic.zig +++ b/src/atomic.zig @@ -30,6 +30,9 @@ pub const Ops = struct { fchmod: *const fn (fd: sys.fd_t, mode: u32) usize = realChmod, fchown: *const fn (fd: sys.fd_t, uid: linux.uid_t, gid: linux.gid_t) usize = realChown, fsync: *const fn (fd: sys.fd_t) usize = realFsync, + openat: *const fn (dir: sys.fd_t, path: [*:0]const u8, flags: sys.O, mode: linux.mode_t) usize = realOpenat, + write: *const fn (fd: sys.fd_t, bytes: []const u8) usize = realWrite, + renameat: *const fn (old_dir: sys.fd_t, old_path: [*:0]const u8, new_dir: sys.fd_t, new_path: [*:0]const u8) usize = realRenameat, geteuid: *const fn () linux.uid_t = realGeteuid, created: *const fn (fd: sys.fd_t) void = realCreated, }; @@ -66,6 +69,15 @@ fn realChown(fd: sys.fd_t, uid: linux.uid_t, gid: linux.gid_t) usize { fn realFsync(fd: sys.fd_t) usize { return linux.fsync(fd); } +fn realOpenat(dir: sys.fd_t, path: [*:0]const u8, flags: sys.O, mode: linux.mode_t) usize { + return linux.openat(dir, path, flags, mode); +} +fn realWrite(fd: sys.fd_t, bytes: []const u8) usize { + return linux.write(fd, bytes.ptr, bytes.len); +} +fn realRenameat(old_dir: sys.fd_t, old_path: [*:0]const u8, new_dir: sys.fd_t, new_path: [*:0]const u8) usize { + return linux.renameat(old_dir, old_path, new_dir, new_path); +} fn realGeteuid() linux.uid_t { return linux.geteuid(); } @@ -78,6 +90,29 @@ fn op(f: anytype, args: anytype) sys.Error!usize { } } +fn openTemp(path: []const u8, flags: sys.O, mode: linux.mode_t) sys.Error!sys.fd_t { + var zb: [sys.path_max:0]u8 = undefined; + var f = flags; + f.CLOEXEC = true; + const rc = try op(ops.openat, .{ fsx.cwd, (try sys.z(&zb, path)).ptr, f, mode }); + return @intCast(rc); +} + +fn writeTemp(fd: sys.fd_t, bytes: []const u8) sys.Error!void { + var off: usize = 0; + while (off < bytes.len) { + const n = try op(ops.write, .{ fd, bytes[off..] }); + if (n == 0) return error.NoSpace; + off += n; + } +} + +fn renameTemp(old_path: []const u8, new_path: []const u8) sys.Error!void { + var za: [sys.path_max:0]u8 = undefined; + var zb: [sys.path_max:0]u8 = undefined; + _ = try op(ops.renameat, .{ fsx.cwd, (try sys.z(&za, old_path)).ptr, fsx.cwd, (try sys.z(&zb, new_path)).ptr }); +} + /// Python's OSError text for an error from one of the calls, so a message /// reads "[Errno 13] Permission denied" as the Python tool prints it; the /// errno comes from `sys.last_errno` (see `sys.describe`). @@ -445,7 +480,7 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write defer a.free(step); if (opts.faults.fails(step)) return injected(a, why, step); } - const fd = try sys.openat(fsx.cwd, tmp, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true, .NOFOLLOW = true }, 0o600); + const fd = try openTemp(tmp, .{ .ACCMODE = .WRONLY, .CREAT = true, .EXCL = true, .NOFOLLOW = true }, 0o600); const created = fsx.fstat(fd) catch |err| { sys.close(fd); // Created above with O_EXCL, so it is this call's file. @@ -456,7 +491,7 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write errdefer discard(tmp, created); { defer sys.close(fd); - try sys.writeAll(fd, data); + try writeTemp(fd, data); var inner: Why = .{}; defer inner.deinit(a); restoreMetadata(a, fd, metadata, mode, &inner) catch |err| return refuse(a, why, "cannot preserve access metadata for {s}: {s}", .{ path, if (err == error.Refused) inner.msg else describe(err) }); @@ -479,7 +514,7 @@ pub fn atomicWrite(a: Allocator, path: []const u8, data: []const u8, opts: Write defer a.free(step); if (opts.faults.fails(step)) return injected(a, why, step); } - try sys.renameat(fsx.cwd, tmp, fsx.cwd, path); + try renameTemp(tmp, path); try fsyncDir(parent); } diff --git a/src/atomic_test.zig b/src/atomic_test.zig index 7978eb2..ab233f7 100644 --- a/src/atomic_test.zig +++ b/src/atomic_test.zig @@ -1731,3 +1731,46 @@ test "atomicWrite frees what it allocates but a refusal's message" { try expectAttrs(s.expected, m.getPath(s.path)); } } + +fn enospcWrite(_: sys.fd_t, _: []const u8) usize { + return err(.NOSPC); +} + +fn erofsOpenat(_: sys.fd_t, _: [*:0]const u8, _: sys.O, _: linux.mode_t) usize { + return err(.ROFS); +} + +fn exdevRenameat(_: sys.fd_t, _: [*:0]const u8, _: sys.fd_t, _: [*:0]const u8) usize { + return err(.XDEV); +} + +test "atomicWrite returns NoSpace, ReadOnly, and CrossDevice without touching the live file" { + begin(); + defer end(); + const dir = tmpdir(); + defer cleanup(dir); + const pt = staleModule(dir); + + atomic.ops.write = enospcWrite; + try testing.expectError(error.NoSpace, write(pt[0], "new", replace)); + try testing.expectEqualStrings("[Errno 28] No space left on device", atomic.describe(error.NoSpace)); + try testing.expect(!exists(pt[1])); + try testing.expectEqualStrings("old", readFile(pt[0])); + + atomic.ops.* = .{}; + atomic.ops.openat = erofsOpenat; + try testing.expectError(error.ReadOnly, write(pt[0], "new", replace)); + try testing.expectEqualStrings("[Errno 30] Read-only file system", atomic.describe(error.ReadOnly)); + try testing.expect(!exists(pt[1])); + try testing.expectEqualStrings("old", readFile(pt[0])); + + atomic.ops.* = .{}; + atomic.ops.renameat = exdevRenameat; + try testing.expectError(error.CrossDevice, write(pt[0], "new", replace)); + try testing.expectEqualStrings("[Errno 18] Invalid cross-device link", atomic.describe(error.CrossDevice)); + try testing.expect(!exists(pt[1])); + try testing.expectEqualStrings("old", readFile(pt[0])); + + try testing.expectError(error.NotDir, atomic.makedirs(join(pt[0], "child"))); + try testing.expectError(error.NotFound, atomic.fsyncDir(join(dir, "absent"))); +} From 91f1381fa58b5e304e487cdc13dfcfb944683229 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Wed, 18 Nov 2026 12:14:08 +0000 Subject: [PATCH 2/7] test(fsx): cover error paths for public file and directory helpers Exercise the error returns of fstat, statAt, realpathFd, realpath, openRegular, openDir, copyTo, appendLine, readAll, moveAcross, replaceContents and deleteTree. openRegular on a directory now expects error.IsDir, matching the landed type diagnostics. --- changelog.d/+fsx-error-paths-test.misc.md | 1 + src/fsx.zig | 55 +++++++++++++++++++++++ 2 files changed, 56 insertions(+) create mode 100644 changelog.d/+fsx-error-paths-test.misc.md diff --git a/changelog.d/+fsx-error-paths-test.misc.md b/changelog.d/+fsx-error-paths-test.misc.md new file mode 100644 index 0000000..2a927cf --- /dev/null +++ b/changelog.d/+fsx-error-paths-test.misc.md @@ -0,0 +1 @@ +Add unit tests covering error paths for public file and directory helpers in `src/fsx.zig`. diff --git a/src/fsx.zig b/src/fsx.zig index 99ec5b5..c4aada0 100644 --- a/src/fsx.zig +++ b/src/fsx.zig @@ -1142,6 +1142,61 @@ test "moveAcross keeps the source when publish fails before rename" { try std.testing.expectError(error.NotFound, statAt(d, "dst", false)); } +test "fsx public helpers return expected errors on bad paths and descriptors" { + const gpa = std.testing.allocator; + var cwd_buf: [sys.path_max]u8 = undefined; + const here = try realpath(cwd, ".", &cwd_buf); + var pb: [sys.path_max]u8 = undefined; + const base = try std.mem.print(&pb, "{s}/.zig-cache/zig-common-fsx-err-{d}", .{ here, linux.getpid() }); + var zb: [sys.path_max:0]u8 = undefined; + _ = linux.mkdirat(cwd, (try sys.z(&zb, base)).ptr, 0o700); + const d = try openDir(cwd, base, false); + defer { + deleteTree(gpa, cwd, base) catch {}; + sys.close(d); + } + + const reg_fd = try sys.openat(d, "reg", .{ .ACCMODE = .WRONLY, .CREAT = true }, 0o644); + try sys.writeAll(reg_fd, "0123456789"); + sys.close(reg_fd); + var dir_z: [sys.path_max:0]u8 = undefined; + _ = linux.mkdirat(d, (try sys.z(&dir_z, "sub")).ptr, 0o700); + var lnk_z: [sys.path_max:0]u8 = undefined; + _ = linux.symlinkat("reg", d, (try sys.z(&lnk_z, "lnk")).ptr); + var dlnk_z: [sys.path_max:0]u8 = undefined; + _ = linux.symlinkat("sub", d, (try sys.z(&dlnk_z, "dlnk")).ptr); + + try std.testing.expectError(error.InvalidArgument, fstat(-1)); + try std.testing.expectError(error.NotFound, statAt(d, "missing", false)); + var out: [sys.path_max]u8 = undefined; + try std.testing.expectError(error.NotFound, realpathFd(-1, &out)); + try std.testing.expectError(error.NotFound, realpath(d, "missing", &out)); + + try std.testing.expectError(error.NotFound, openRegular(d, "missing", false)); + try std.testing.expectError(error.SymLink, openRegular(d, "lnk", false)); + try std.testing.expectError(error.IsDir, openRegular(d, "sub", false)); + + try std.testing.expectError(error.NotFound, openDir(d, "missing", false)); + try std.testing.expectError(error.NotDir, openDir(d, "reg", false)); + try std.testing.expectError(error.NotDir, openDir(d, "dlnk", false)); + + const opened = try openRegular(d, "reg", false); + defer sys.close(opened.fd); + try std.testing.expectError(error.SymLink, copyTo(opened.fd, opened.stat, d, "lnk")); + try std.testing.expectError(error.IsDir, copyTo(opened.fd, opened.stat, d, "sub")); + try std.testing.expectError(error.SymLink, appendLine(gpa, d, "lnk", "x")); + try std.testing.expectError(error.IsDir, appendLine(gpa, d, "sub", "x")); + try std.testing.expectError(error.StreamTooLong, readAll(gpa, opened.fd, 4)); + try std.testing.expectError(error.NotFound, moveAcross(gpa, d, "missing", d, "dst", .{})); + try std.testing.expectError(error.NotFound, replaceContents(gpa, d, "missing", "x")); + try std.testing.expectError(error.SymLink, replaceContents(gpa, d, "lnk", "x")); + try std.testing.expectError(error.NotFound, entryType(d, .{ .name = "missing", .type = DT.UNKNOWN })); + var bad_it = try DirIter.init(gpa, -1); + defer bad_it.deinit(gpa); + try std.testing.expectError(error.InvalidArgument, bad_it.next()); + try std.testing.expectError(error.NotFound, deleteTree(gpa, d, "missing")); +} + test "moveAcross reports not a regular file for a FIFO source on EXDEV fallback" { const gpa = std.testing.allocator; var cwd_buf: [sys.path_max]u8 = undefined; From 50c86b0102c195ec1af261d869273001cf268440 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Wed, 18 Nov 2026 12:14:37 +0000 Subject: [PATCH 3/7] test(proc): cover which, groupAlive, and run error paths Cover the cases which rejects, groupAlive with an absent process group, the signal helpers with a zero pgid, and run with invalid arguments, an argument overflow and an exec error. The executable fixtures reuse makeExecFixture. --- changelog.d/+proc-error-tests.misc.md | 1 + src/proc.zig | 28 +++++++++++++++++++++++++++ 2 files changed, 29 insertions(+) create mode 100644 changelog.d/+proc-error-tests.misc.md diff --git a/changelog.d/+proc-error-tests.misc.md b/changelog.d/+proc-error-tests.misc.md new file mode 100644 index 0000000..67ad9a9 --- /dev/null +++ b/changelog.d/+proc-error-tests.misc.md @@ -0,0 +1 @@ +Add unit tests covering error and boundary paths for `which`, `groupAlive`, `killGroup`, `stopGroup`, and `run` in `src/proc.zig`. diff --git a/src/proc.zig b/src/proc.zig index c02f84c..13dd328 100644 --- a/src/proc.zig +++ b/src/proc.zig @@ -861,3 +861,31 @@ test "which resolves executable candidates directly" { try std.testing.expectEqual(@as(?[]u8, null), try which(gpa, "plain.txt", fixture.base)); try std.testing.expectEqual(@as(?[]u8, null), try which(gpa, "not-present-tool", fixture.base)); } + +test "which, groupAlive, and run cover error and boundary paths" { + const gpa = std.testing.allocator; + try std.testing.expectEqual(@as(?[]u8, null), try which(gpa, "", "/bin:/usr/bin")); + try std.testing.expectEqual(@as(?[]u8, null), try which(gpa, "a/b", "/bin:/usr/bin")); + try std.testing.expectEqual(@as(?[]u8, null), try which(gpa, "no-such-zig-common-tool", "/bin:/usr/bin")); + + const fixture = try makeExecFixture(gpa, "which-err"); + defer fixture.deinit(gpa); + const dir = try fsx.openDir(fsx.cwd, fixture.base, false); + defer sys.close(dir); + _ = linux.mkdirat(dir, "sub", 0o755); + + try std.testing.expectEqual(@as(?[]u8, null), try which(gpa, "sub", fixture.base)); + try std.testing.expectEqual(@as(?[]u8, null), try which(gpa, "plain.txt", fixture.base)); + const found = (try which(gpa, "tool.sh", fixture.base)).?; + defer gpa.free(found); + try std.testing.expectEqualStrings(fixture.exe_path, found); + + try std.testing.expect(!groupAlive(2_000_000_000)); + killGroup(0, .TERM); + stopGroup(0); + + try std.testing.expectError(error.InvalidArgument, run(gpa, "/bin/\x00sh", &.{"sh"}, no_env, .{})); + try std.testing.expectError(error.InvalidArgument, run(gpa, "/bin/sh", &.{ "sh", "bad\x00arg" }, no_env, .{})); + try std.testing.expectError(error.StreamTooLong, run(gpa, "/bin/sh", &.{ "sh", "-c", "printf 12345678" }, no_env, .{ .stdout_limit = 4 })); + try std.testing.expectError(error.NotFound, run(gpa, "/no/such/zig-common-exe", &.{"x"}, no_env, .{ .exec_error = true })); +} From 8196f90399ee2fb63a1a4502d8454f5c5206d886 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Wed, 18 Nov 2026 12:14:53 +0000 Subject: [PATCH 4/7] test(logs): cover gzipInPlace error paths Check that gzipInPlace returns NotFound for a missing file, InvalidArgument for a directory, SymLink for a symlink, TooManyLinks for a hard-linked file and Exists when the .gz archive is already there. --- changelog.d/+logs-error-tests.misc.md | 1 + src/logs.zig | 40 +++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 changelog.d/+logs-error-tests.misc.md diff --git a/changelog.d/+logs-error-tests.misc.md b/changelog.d/+logs-error-tests.misc.md new file mode 100644 index 0000000..eb25516 --- /dev/null +++ b/changelog.d/+logs-error-tests.misc.md @@ -0,0 +1 @@ +Add unit tests covering `gzipInPlace` error paths (missing file, directory, symlink, hard link, and existing `.gz` archive) in `src/logs.zig`. diff --git a/src/logs.zig b/src/logs.zig index abce3f1..ed13c23 100644 --- a/src/logs.zig +++ b/src/logs.zig @@ -215,3 +215,43 @@ test "renameInList" { try std.testing.expectEqualStrings("/r/a.log.gz\n/r/b.log\n", got); try std.testing.expect((try renameInList(gpa, "/r/b.log\n", &m)) == null); } + +test "gzipInPlace refuses missing files, symlinks, directories, hard links, and existing archives" { + const gpa = std.testing.allocator; + var cwd_buf: [sys.path_max]u8 = undefined; + const here = try fsx.realpath(fsx.cwd, ".", &cwd_buf); + var pb: [sys.path_max]u8 = undefined; + const base = try std.mem.print(&pb, "{s}/.zig-cache/zig-common-logs-err-{d}", .{ here, linux.getpid() }); + var zb: [sys.path_max:0]u8 = undefined; + _ = linux.mkdirat(fsx.cwd, (try sys.z(&zb, base)).ptr, 0o700); + const dir = try fsx.openDir(fsx.cwd, base, false); + defer { + fsx.deleteTree(gpa, fsx.cwd, base) catch {}; + sys.close(dir); + } + + const io = std.Io.Threaded.global_single_threaded.io(); + try std.testing.expectError(error.NotFound, gzipInPlace(gpa, io, dir, "missing.log")); + + var sub_z: [sys.path_max:0]u8 = undefined; + _ = linux.mkdirat(dir, (try sys.z(&sub_z, "sub")).ptr, 0o700); + try std.testing.expectError(error.IsDir, gzipInPlace(gpa, io, dir, "sub")); + + const orig = try sys.openat(dir, "orig.log", .{ .ACCMODE = .WRONLY, .CREAT = true }, 0o644); + try sys.writeAll(orig, "hello"); + sys.close(orig); + + var lnk_z: [sys.path_max:0]u8 = undefined; + _ = linux.symlinkat("orig.log", dir, (try sys.z(&lnk_z, "lnk.log")).ptr); + try std.testing.expectError(error.SymLink, gzipInPlace(gpa, io, dir, "lnk.log")); + + var hl_z: [sys.path_max:0]u8 = undefined; + var orig_z: [sys.path_max:0]u8 = undefined; + _ = linux.linkat(dir, (try sys.z(&orig_z, "orig.log")).ptr, dir, (try sys.z(&hl_z, "hard.log")).ptr, 0); + try std.testing.expectError(error.TooManyLinks, gzipInPlace(gpa, io, dir, "orig.log")); + sys.unlinkat(dir, "hard.log", 0) catch {}; + + const gz = try sys.openat(dir, "orig.log.gz", .{ .ACCMODE = .WRONLY, .CREAT = true }, 0o644); + sys.close(gz); + try std.testing.expectError(error.Exists, gzipInPlace(gpa, io, dir, "orig.log")); +} From 0c7997b641f0600401f74ae18059d31886a2c3d3 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Wed, 18 Nov 2026 12:15:08 +0000 Subject: [PATCH 5/7] test(cli): cover write-error handling in put, print and versionLine Check that cli.put and cli.print ignore a bad file descriptor (`EBADF`) for both stack and heap-formatted messages, and pin the cli.versionLine format. --- changelog.d/+cli-write-errors-test.misc.md | 1 + src/cli.zig | 13 +++++++++++++ 2 files changed, 14 insertions(+) create mode 100644 changelog.d/+cli-write-errors-test.misc.md diff --git a/changelog.d/+cli-write-errors-test.misc.md b/changelog.d/+cli-write-errors-test.misc.md new file mode 100644 index 0000000..7759594 --- /dev/null +++ b/changelog.d/+cli-write-errors-test.misc.md @@ -0,0 +1 @@ +Add unit tests verifying `cli.put` and `cli.print` ignore descriptor write errors and checking `cli.versionLine` formatting. diff --git a/src/cli.zig b/src/cli.zig index bb7106a..43a517b 100644 --- a/src/cli.zig +++ b/src/cli.zig @@ -50,3 +50,16 @@ pub fn versionLine(comptime tool: []const u8, comptime version: []const u8, comp return tool ++ " " ++ version ++ " (" ++ @tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag) ++ "-" ++ @tagName(builtin.abi) ++ ", " ++ @tagName(builtin.mode) ++ ", zig " ++ builtin.zig_version_string ++ ", " ++ commit ++ ")\n"; } + +test "put and print ignore write errors and versionLine formats tool and version" { + put(-1, "ignored\n"); + print(-1, "ignored {d}\n", .{42}); + + var big: [9000]u8 = undefined; + @memset(&big, 'x'); + print(-1, "{s}", .{big[0..]}); + + const line = versionLine("demo", "1.2.3", "abc1234"); + try std.testing.expect(std.mem.startsWith(u8, line, "demo 1.2.3 (")); + try std.testing.expect(std.mem.endsWith(u8, line, ", abc1234)\n")); +} From 318f9c909ca3eccd955987c5a3757422e8d90569 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Thu, 19 Nov 2026 03:46:06 +0000 Subject: [PATCH 6/7] refactor(proc): share one executable search loop Move the PATH walk in which into one search entry that takes a directory handle and a set of lookup options, and resolves relative and absolute candidates the same way. The shutil-compatible lookup in the next commit reuses it instead of copying the split, join, access and stat loop. proc.which behaves as before, and its existing tests pass unmodified. --- .../+proc-which-search-options.misc.md | 1 + src/proc.zig | 105 +++++++++++++++--- 2 files changed, 90 insertions(+), 16 deletions(-) create mode 100644 changelog.d/+proc-which-search-options.misc.md diff --git a/changelog.d/+proc-which-search-options.misc.md b/changelog.d/+proc-which-search-options.misc.md new file mode 100644 index 0000000..87540fc --- /dev/null +++ b/changelog.d/+proc-which-search-options.misc.md @@ -0,0 +1 @@ +`proc.which` uses one internal options-driven search loop for executable path matching. diff --git a/src/proc.zig b/src/proc.zig index 13dd328..0a08aef 100644 --- a/src/proc.zig +++ b/src/proc.zig @@ -114,31 +114,104 @@ pub const Result = struct { /// exits 127. pub const Error = sys.Error || Allocator.Error || error{ StreamTooLong, TimedOut, Canceled, NotAbsolute }; +const PathUnset = enum { + none, + use_default, +}; + +const EmptyPath = enum { + return_none, + search_cwd, +}; + +const ResultPath = enum { + absolute, + candidate, +}; + +const ExecutableCheck = enum { + regular_file, + not_directory, +}; + +const SlashName = enum { + reject, + check_direct, +}; + +const WhichOptions = struct { + unset_path: PathUnset = .none, + default_path: []const u8 = "", + empty_path: EmptyPath = .return_none, + result_path: ResultPath = .absolute, + executable_check: ExecutableCheck = .regular_file, + slash_name: SlashName = .reject, +}; + /// Search `path_env` (colon-separated, an empty entry meaning the current /// directory, as execvp does) for an executable regular file `name`. /// Returns an absolute path to it, without resolving symbolic links, or /// null. A name containing '/' is not looked up. pub fn which(gpa: Allocator, name: []const u8, path_env: []const u8) Allocator.Error!?[]u8 { - if (std.mem.findScalar(u8, name, '/') != null or name.len == 0) return null; - var it = std.mem.splitScalar(u8, path_env, ':'); - while (it.next()) |dir_raw| { - const cand = try std.fs.path.join(gpa, &.{ if (dir_raw.len == 0) "." else dir_raw, name }); - defer gpa.free(cand); - if (!isExecutableFile(cand)) continue; - if (cand[0] == '/') return try gpa.dupe(u8, cand); - var rb: [sys.path_max]u8 = undefined; - const dir_abs = fsx.realpath(fsx.cwd, if (dir_raw.len == 0) "." else dir_raw, &rb) catch continue; - return try std.fs.path.join(gpa, &.{ dir_abs, name }); - } - return null; + return whichWithOptions(gpa, std.Io.Dir.cwd().handle, name, path_env, .{ .empty_path = .search_cwd }); } -fn isExecutableFile(path: []const u8) bool { +fn isExecutableAt(cwd_dir: fsx.fd_t, path: []const u8, check: ExecutableCheck) bool { var zb: [sys.path_max:0]u8 = undefined; const z = sys.z(&zb, path) catch return false; - if (linux.errno(linux.faccessat(linux.AT.FDCWD, z.ptr, linux.X_OK, 0)) != .SUCCESS) return false; - const st = fsx.statAt(fsx.cwd, path, true) catch return false; - return st.isReg(); + if (linux.errno(linux.faccessat(cwd_dir, z.ptr, linux.X_OK, 0)) != .SUCCESS) return false; + const st = fsx.statAt(cwd_dir, path, true) catch return false; + return switch (check) { + .regular_file => st.isReg(), + .not_directory => !st.isDir(), + }; +} + +fn isExecutableFile(path: []const u8) bool { + return isExecutableAt(fsx.cwd, path, .regular_file); +} + +fn resolveSearchPath(path_env: ?[]const u8, opts: WhichOptions) ?[]const u8 { + if (path_env) |path| return path; + return switch (opts.unset_path) { + .none => null, + .use_default => opts.default_path, + }; +} + +fn candidatePath(gpa: Allocator, dir_raw: []const u8, name: []const u8, opts: WhichOptions) Allocator.Error![]u8 { + if (dir_raw.len == 0 and opts.empty_path == .search_cwd) return std.fs.path.join(gpa, &.{ ".", name }); + return std.fs.path.join(gpa, &.{ dir_raw, name }); +} + +fn toAbsoluteAt(gpa: Allocator, cwd_dir: fsx.fd_t, candidate: []const u8, dir_raw: []const u8, opts: WhichOptions) Allocator.Error!?[]u8 { + if (candidate[0] == '/') return try gpa.dupe(u8, candidate); + const base_dir = if (dir_raw.len == 0 and opts.empty_path == .search_cwd) "." else dir_raw; + var rb: [sys.path_max]u8 = undefined; + const dir_abs = fsx.realpath(cwd_dir, base_dir, &rb) catch return null; + return try std.fs.path.join(gpa, &.{ dir_abs, std.fs.path.basename(candidate) }); +} + +fn whichWithOptions(gpa: Allocator, cwd_dir: fsx.fd_t, name: []const u8, path_env: ?[]const u8, opts: WhichOptions) Allocator.Error!?[]u8 { + if (name.len == 0) return null; + if (std.mem.findScalar(u8, name, '/') != null) return switch (opts.slash_name) { + .reject => null, + .check_direct => if (isExecutableAt(cwd_dir, name, opts.executable_check)) try gpa.dupe(u8, name) else null, + }; + + const path = resolveSearchPath(path_env, opts) orelse return null; + if (path.len == 0 and opts.empty_path == .return_none) return null; + var it = std.mem.splitScalar(u8, path, ':'); + while (it.next()) |dir_raw| { + const cand = try candidatePath(gpa, dir_raw, name, opts); + defer gpa.free(cand); + if (!isExecutableAt(cwd_dir, cand, opts.executable_check)) continue; + return switch (opts.result_path) { + .candidate => try gpa.dupe(u8, cand), + .absolute => (try toAbsoluteAt(gpa, cwd_dir, cand, dir_raw, opts)) orelse continue, + }; + } + return null; } /// Resolve an executable name to an absolute path. A name with '/' is treated From 1ca0611ee70eb514ca117b999b5f731ead603299 Mon Sep 17 00:00:00 2001 From: Rohit Goswami Date: Thu, 19 Nov 2026 03:51:16 +0000 Subject: [PATCH 7/7] feat(proc): add whichShutil with Python shutil.which semantics Callers that must match Python's shutil.which on POSIX can opt in to proc.whichShutil, and proc.which keeps its current behavior. whichShutil searches /bin:/usr/bin when PATH is unset and finds nothing when PATH is empty. An empty PATH entry resolves against the caller's working-directory handle and returns a relative candidate. Names that contain a slash are normalized the way os.path.split and join do before the direct check, so a//x matches a/x, while a/x/ still does not match a regular file. --- changelog.d/+proc-which-shutil.feature.md | 1 + src/proc.zig | 123 +++++++++++++++++++++- 2 files changed, 122 insertions(+), 2 deletions(-) create mode 100644 changelog.d/+proc-which-shutil.feature.md diff --git a/changelog.d/+proc-which-shutil.feature.md b/changelog.d/+proc-which-shutil.feature.md new file mode 100644 index 0000000..f4f6977 --- /dev/null +++ b/changelog.d/+proc-which-shutil.feature.md @@ -0,0 +1 @@ +`proc.whichShutil` adds an opt-in executable lookup mode that matches POSIX `shutil.which` behavior. diff --git a/src/proc.zig b/src/proc.zig index 0a08aef..0ff0cd2 100644 --- a/src/proc.zig +++ b/src/proc.zig @@ -146,6 +146,7 @@ const WhichOptions = struct { result_path: ResultPath = .absolute, executable_check: ExecutableCheck = .regular_file, slash_name: SlashName = .reject, + slash_split_join: bool = false, }; /// Search `path_env` (colon-separated, an empty entry meaning the current @@ -180,7 +181,7 @@ fn resolveSearchPath(path_env: ?[]const u8, opts: WhichOptions) ?[]const u8 { } fn candidatePath(gpa: Allocator, dir_raw: []const u8, name: []const u8, opts: WhichOptions) Allocator.Error![]u8 { - if (dir_raw.len == 0 and opts.empty_path == .search_cwd) return std.fs.path.join(gpa, &.{ ".", name }); + if (dir_raw.len == 0 and opts.empty_path == .search_cwd) return std.fs.path.join(gpa, &.{ "", name }); return std.fs.path.join(gpa, &.{ dir_raw, name }); } @@ -196,7 +197,17 @@ fn whichWithOptions(gpa: Allocator, cwd_dir: fsx.fd_t, name: []const u8, path_en if (name.len == 0) return null; if (std.mem.findScalar(u8, name, '/') != null) return switch (opts.slash_name) { .reject => null, - .check_direct => if (isExecutableAt(cwd_dir, name, opts.executable_check)) try gpa.dupe(u8, name) else null, + .check_direct => blk: { + const candidate = if (opts.slash_split_join) + try shutilSplitJoinPosix(gpa, name) + else + try gpa.dupe(u8, name); + if (!isExecutableAt(cwd_dir, candidate, opts.executable_check)) { + gpa.free(candidate); + break :blk null; + } + break :blk candidate; + }, }; const path = resolveSearchPath(path_env, opts) orelse return null; @@ -214,6 +225,48 @@ fn whichWithOptions(gpa: Allocator, cwd_dir: fsx.fd_t, name: []const u8, path_en return null; } +fn shutilSplitPosix(path: []const u8) struct { head: []const u8, tail: []const u8 } { + const cut = (std.mem.lastIndexOfScalar(u8, path, '/') orelse return .{ .head = "", .tail = path }) + 1; + var head = path[0..cut]; + const tail = path[cut..]; + if (head.len > 0) { + var all_slash = true; + for (head) |c| if (c != '/') { + all_slash = false; + break; + }; + if (!all_slash) head = std.mem.trimEnd(u8, head, "/"); + } + return .{ .head = head, .tail = tail }; +} + +fn shutilJoinPosix(gpa: Allocator, head: []const u8, tail: []const u8) Allocator.Error![]u8 { + if (head.len == 0 or tail.len > 0 and tail[0] == '/') return gpa.dupe(u8, tail); + if (head[head.len - 1] == '/') return std.fmt.allocPrint(gpa, "{s}{s}", .{ head, tail }); + return std.fmt.allocPrint(gpa, "{s}/{s}", .{ head, tail }); +} + +fn shutilSplitJoinPosix(gpa: Allocator, path: []const u8) Allocator.Error![]u8 { + const parts = shutilSplitPosix(path); + return shutilJoinPosix(gpa, parts.head, parts.tail); +} + +/// Search an executable path with POSIX `shutil.which` behavior: +/// an unset PATH uses "/bin:/usr/bin", an empty PATH returns null, empty +/// PATH entries search the current directory and keep relative hits, and a +/// name containing '/' is checked directly after split/join normalization. +pub fn whichShutil(gpa: Allocator, name: []const u8, path_env: ?[]const u8) Allocator.Error!?[]u8 { + return whichWithOptions(gpa, std.Io.Dir.cwd().handle, name, path_env, .{ + .unset_path = .use_default, + .default_path = "/bin:/usr/bin", + .empty_path = .return_none, + .result_path = .candidate, + .executable_check = .not_directory, + .slash_name = .check_direct, + .slash_split_join = true, + }); +} + /// Resolve an executable name to an absolute path. A name with '/' is treated /// as a path and returned as an absolute path when it names an executable /// regular file; other names are looked up in `path_env`, or in @@ -935,6 +988,72 @@ test "which resolves executable candidates directly" { try std.testing.expectEqual(@as(?[]u8, null), try which(gpa, "not-present-tool", fixture.base)); } +test "whichShutil uses os.defpath when PATH is unset" { + const gpa = std.testing.allocator; + const found = (try whichShutil(gpa, "sh", null)).?; + defer gpa.free(found); + try std.testing.expect(found.len > 0 and found[0] == '/'); + try std.testing.expectEqualStrings("sh", std.fs.path.basename(found)); +} + +test "whichShutil returns null for an empty PATH" { + const gpa = std.testing.allocator; + const fixture = try makeExecFixture(gpa, "which-shutil-empty"); + defer fixture.deinit(gpa); + try std.testing.expectEqual(@as(?[]u8, null), try whichShutil(gpa, "tool.sh", "")); +} + +test "whichShutil empty entry search uses provided cwd handle" { + const gpa = std.testing.allocator; + const fixture = try makeExecFixture(gpa, "which-shutil-cwd-handle"); + defer fixture.deinit(gpa); + const dir = try fsx.openDir(fsx.cwd, fixture.base, false); + defer sys.close(dir); + + const found = (try whichWithOptions(gpa, dir, "tool.sh", ":", .{ + .unset_path = .use_default, + .default_path = "/bin:/usr/bin", + .empty_path = .search_cwd, + .result_path = .candidate, + .executable_check = .not_directory, + .slash_name = .check_direct, + .slash_split_join = true, + })).?; + defer gpa.free(found); + try std.testing.expectEqualStrings("tool.sh", found); +} + +test "whichShutil slash normalization keeps //x and collapses a//x" { + const gpa = std.testing.allocator; + const collapsed = try shutilSplitJoinPosix(gpa, "a//x"); + defer gpa.free(collapsed); + try std.testing.expectEqualStrings("a/x", collapsed); + + const double = try shutilSplitJoinPosix(gpa, "//x"); + defer gpa.free(double); + try std.testing.expectEqualStrings("//x", double); + + const dotted = try shutilSplitJoinPosix(gpa, ".//a/x"); + defer gpa.free(dotted); + try std.testing.expectEqualStrings(".//a/x", dotted); +} + +test "whichShutil slash paths ending in slash do not match regular files" { + const gpa = std.testing.allocator; + const fixture = try makeExecFixture(gpa, "which-shutil-slash-tail"); + defer fixture.deinit(gpa); + + const slash = try std.fmt.allocPrint(gpa, "{s}//tool.sh", .{fixture.base}); + defer gpa.free(slash); + const found = (try whichShutil(gpa, slash, "")).?; + defer gpa.free(found); + try std.testing.expectEqualStrings(fixture.exe_path, found); + + const trailing = try std.fmt.allocPrint(gpa, "{s}/tool.sh/", .{fixture.base}); + defer gpa.free(trailing); + try std.testing.expectEqual(@as(?[]u8, null), try whichShutil(gpa, trailing, "")); +} + test "which, groupAlive, and run cover error and boundary paths" { const gpa = std.testing.allocator; try std.testing.expectEqual(@as(?[]u8, null), try which(gpa, "", "/bin:/usr/bin"));