From 5157579ff7f9ae0cfc3c7629e953da05bce340fc Mon Sep 17 00:00:00 2001 From: Gabriel Schneider Date: Mon, 9 Nov 2026 00:52:52 -0300 Subject: tests: at the end of their files: every top-level test block of the 46 files that had one mid-file (the locality analysis's 45 and test/hxdiff.zig; gui.zig, macos.zig, look, host_io, 9p_io, terminal, tui, mouse, fs, replica, layout among them, 11,429 test lines), with the functions only tests call, moved after the file's code in their order, a mechanical move (.scratch/suites/tests_to_end.py), zig fmt'd; the unit suites pass as before (tui 1486/1487, gui 1536/1537, core 956/956 on both), macos.zig only parse-checked here Co-Authored-By: Claude Fable 5.1 Claude-Session: https://claude.ai/code/session_016Y9MNAtZenFv4weoMD3cge --- src/host_io.zig | 990 ++++++++++++++++++++++++++++---------------------------- 1 file changed, 495 insertions(+), 495 deletions(-) (limited to 'src/host_io.zig') diff --git a/src/host_io.zig b/src/host_io.zig index 9e0292b3..be741020 100644 --- a/src/host_io.zig +++ b/src/host_io.zig @@ -1091,10 +1091,6 @@ pub const Lsp = struct { } }; -test { - _ = Lsp; -} - pub const Shell = struct { const X_OK: c_int = 1; @@ -1834,30 +1830,6 @@ pub fn resetChildSignals() void { posix.sigprocmask(posix.SIG.SETMASK, &none, null); } -test "a child starts with every signal at its default and none blocked" { - var blocked = posix.sigemptyset(); - posix.sigaddset(&blocked, posix.SIG.WINCH); - posix.sigprocmask(posix.SIG.BLOCK, &blocked, null); - defer posix.sigprocmask(posix.SIG.UNBLOCK, &blocked, null); - const ignore: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.IGN }, .mask = posix.sigemptyset(), .flags = 0 }; - var was: posix.Sigaction = undefined; - posix.sigaction(posix.SIG.HUP, &ignore, &was); - defer posix.sigaction(posix.SIG.HUP, &was, null); - const pid = libc.fork(); - if (pid == 0) { - resetChildSignals(); - var now: posix.Sigaction = undefined; - posix.sigaction(posix.SIG.HUP, null, &now); - var mask = posix.sigemptyset(); - posix.sigprocmask(posix.SIG.BLOCK, null, &mask); - const ok = now.handler.handler == posix.SIG.DFL and !posix.sigismember(&mask, posix.SIG.WINCH); - libc._exit(if (ok) 0 else 1); - } - var status: c_int = 0; - _ = libc.waitpid(pid, &status, 0); - try std.testing.expectEqual(@as(c_int, 0), status); -} - extern "c" fn forkpty(amaster: *c_int, name: ?[*:0]u8, termp: ?*const anyopaque, winp: ?*const posix.winsize) c_int; extern "c" fn execv(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8) c_int; extern "c" fn execve(path: [*:0]const u8, argv: [*:null]const ?[*:0]const u8, envp: [*:null]const ?[*:0]const u8) c_int; @@ -2024,91 +1996,6 @@ pub const ChildEnv = struct { } }; -test "the pager's path is quoted only when it needs it" { - var buf: [64]u8 = undefined; - try std.testing.expectEqualStrings("/usr/bin/pardes", ChildEnv.pagerCommand("/usr/bin/pardes", &buf)); - try std.testing.expectEqualStrings("'/opt/my apps/pardes'", ChildEnv.pagerCommand("/opt/my apps/pardes", &buf)); - try std.testing.expectEqualStrings("pardes", ChildEnv.pagerCommand("/odd'dir/pardes", &buf)); -} - -test "the child environment replaces the launcher's terminal identity exactly once" { - const saved: ?[]const u8 = if (libc.getenv("TERM")) |t| std.mem.span(t) else null; - var saved_buf: [256]u8 = undefined; - const restore: ?[:0]const u8 = if (saved) |t| blk: { - if (t.len >= saved_buf.len) break :blk null; - @memcpy(saved_buf[0..t.len], t); - saved_buf[t.len] = 0; - break :blk saved_buf[0..t.len :0]; - } else null; - defer if (restore) |t| { - _ = Shell.setenv("TERM", t.ptr, 1); - } else { - _ = testUnsetenv("TERM"); - }; - - // A launcher TERM must be shadowed rather than duplicated, and the rest of - // the environment must arrive untouched. - try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("TERM", "dumb", 1)); - try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("PARDES_CHILD_ENV_PROBE", "1", 1)); - defer _ = testUnsetenv("PARDES_CHILD_ENV_PROBE"); - - var slots: ChildEnv.Slots = undefined; - // Where the user named no pager: a terminal's shell pages into a - // +Pager pane (`pardes -`); a command pane's through cat. A pager the - // user named is kept. - var shell_slots: ChildEnv.Slots = undefined; - const shell_envp = ChildEnv.build(&shell_slots, .terminal) orelse return error.EnvironmentTooLarge; - var said: usize = 0; - var systemd: usize = 0; - var j: usize = 0; - while (shell_envp[j]) |entry| : (j += 1) { - const line = std.mem.span(entry); - if (std.c.getenv("SYSTEMD_PAGER") == null and std.mem.startsWith(u8, line, "SYSTEMD_PAGER=")) systemd += 1; - if (std.c.getenv("SYSTEMD_PAGERSECURE") == null and std.mem.eql(u8, line, "SYSTEMD_PAGERSECURE=0")) systemd += 1; - if (std.mem.startsWith(u8, line, "PAGER=") and std.c.getenv("PAGER") == null) { - try std.testing.expect(std.mem.endsWith(u8, line, " -")); - said += 1; - } - } - if (std.c.getenv("PAGER") == null) try std.testing.expectEqual(@as(usize, 1), said); - // systemd's pager and its secure mode off, with ours only. - if (std.c.getenv("SYSTEMD_PAGER") == null and std.c.getenv("SYSTEMD_PAGERSECURE") == null) - try std.testing.expectEqual(@as(usize, 2), systemd); - const envp = ChildEnv.build(&slots, .command) orelse return error.EnvironmentTooLarge; - var terms: usize = 0; - var colorterms: usize = 0; - var probes: usize = 0; - var dumb = false; - var pagers: usize = 0; - var git_pagers: usize = 0; - var pager_cat = false; - var git_pager_cat = false; - var i: usize = 0; - while (envp[i]) |entry| : (i += 1) { - const line = std.mem.span(entry); - if (std.mem.startsWith(u8, line, "TERM=")) terms += 1; - if (std.mem.startsWith(u8, line, "COLORTERM=")) colorterms += 1; - if (std.mem.eql(u8, line, "TERM=dumb")) dumb = true; - if (std.mem.eql(u8, line, "PARDES_CHILD_ENV_PROBE=1")) probes += 1; - if (std.mem.startsWith(u8, line, "PAGER=")) pagers += 1; - if (std.mem.startsWith(u8, line, "GIT_PAGER=")) git_pagers += 1; - if (std.mem.eql(u8, line, "PAGER=cat")) pager_cat = true; - if (std.mem.eql(u8, line, "GIT_PAGER=cat")) git_pager_cat = true; - } - // A pager only where the user named none: cat, so nothing waits in less. - try std.testing.expectEqual(@as(usize, 1), pagers); - try std.testing.expectEqual(@as(usize, 1), git_pagers); - if (std.c.getenv("PAGER") == null) try std.testing.expect(pager_cat); - if (std.c.getenv("GIT_PAGER") == null) try std.testing.expect(git_pager_cat); - try std.testing.expectEqual(@as(usize, 1), terms); - try std.testing.expectEqual(@as(usize, 1), colorterms); - try std.testing.expectEqual(@as(usize, 1), probes); - try std.testing.expect(!dumb); - // TERM_PROGRAM shares the prefix "TERM"; the match is on the name, so it - // is a separate entry and never a second TERM. - try std.testing.expectEqualStrings("TERM=" ++ pardes.config.child_term, std.mem.span(envp[i - ChildEnv.own.len].?)); -} - extern "c" fn unsetenv(name: [*:0]const u8) c_int; /// For tests: unset `name` without compacting the environment block std @@ -2280,88 +2167,6 @@ pub fn forkShell( return .{ .file = .{ .handle = master, .flags = .{ .nonblocking = false } }, .pid = pid }; } -test "shell spawn rejects invalid directories before creating a child" { - const rcs: Shell.PromptFiles = .{}; - try std.testing.expectError(error.InvalidPath, forkShell(null, 0, &rcs, "/bin/sh", "/tmp\x00/ignored", 24, 80)); - const too_long = @as([4096]u8, @splat('x')); - try std.testing.expectError(error.NameTooLong, forkShell(null, 0, &rcs, "/bin/sh", &too_long, 24, 80)); - - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "file", .data = "not a directory\n" }); - var directory_buf: [4096]u8 = undefined; - const directory = directory_buf[0..try tmp.dir.realPath(std.testing.io, &directory_buf)]; - var path_buf: [4096]u8 = undefined; - const file = try std.fmt.bufPrint(&path_buf, "{s}/file", .{directory}); - try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", file, 24, 80)); - const explicit_file = try std.fmt.bufPrint(&path_buf, "/n/os{s}/file", .{directory}); - try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", explicit_file, 24, 80)); - const missing = try std.fmt.bufPrint(&path_buf, "{s}/missing/" ++ (std.mem.asBytes(&@as([50][6]u8, @splat("child/".*)))), .{directory}); - try std.testing.expect(missing.len > 256); - try std.testing.expectError(error.FileNotFound, forkShell(null, 0, &rcs, "/bin/sh", missing, 24, 80)); -} - -test "a forked shell is told which terminal it is talking to" { - if (!haveFile("/bin/sh")) return error.SkipZigTest; - // Whatever launched the test is the wrong answer, so make it a loud one. - const saved = libc.getenv("TERM"); - var saved_buf: [256]u8 = undefined; - const restore: ?[:0]const u8 = if (saved) |t| blk: { - const span = std.mem.span(t); - if (span.len >= saved_buf.len) break :blk null; - @memcpy(saved_buf[0..span.len], span); - saved_buf[span.len] = 0; - break :blk saved_buf[0..span.len :0]; - } else null; - defer if (restore) |t| { - _ = Shell.setenv("TERM", t.ptr, 1); - } else { - _ = testUnsetenv("TERM"); - }; - _ = Shell.setenv("TERM", "dumb", 1); - - const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - // The echoed command carries the unexpanded `$TERM`, so only the shell's - // own expansion can match this. - try std.testing.expect(writeFd(child.file.handle, "printf '\nPARDES-TERM:%s:%s\n' \"$TERM\" \"$COLORTERM\"; exit\n")); - try std.testing.expect(sh.waitText( - "PARDES-TERM:" ++ pardes.config.child_term ++ ":" ++ pardes.config.child_colorterm, - 5_000, - )); -} - -test "shell spawn uses an explicit OS directory longer than 256 bytes" { - if (!haveFile("/bin/sh")) return error.SkipZigTest; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const sub_path = std.mem.asBytes(&@as([7][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); - try tmp.dir.createDirPath(std.testing.io, sub_path); - var directory_buf: [4096]u8 = undefined; - const directory = directory_buf[0..try tmp.dir.realPathFile(std.testing.io, sub_path, &directory_buf)]; - try std.testing.expect(directory.len > 256); - var explicit_buf: [4096]u8 = undefined; - const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{directory}); - const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", explicit, 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - try std.testing.expect(writeFd(child.file.handle, "printf '\\nPARDES-CWD:'; pwd; exit\n")); - var expected_buf: [4096]u8 = undefined; - const expected = try std.fmt.bufPrint(&expected_buf, "PARDES-CWD:{s}", .{directory}); - try std.testing.expect(sh.waitText(expected, 5_000)); -} - pub fn writeFd(fd: c_int, data: []const u8) bool { var off: usize = 0; while (off < data.len) { @@ -2485,109 +2290,7 @@ fn realShell(shell_exe: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8) ?[]cons return std.mem.span(@as([*:0]const u8, @ptrCast(r))); } -test "a terminal is where its shell is: under a wrapper the foreground shell, never a job's directory" { - if (comptime builtin.os.tag != .linux) return error.SkipZigTest; - if (!haveFile("/bin/sh") or !haveFile("/usr/bin/timeout")) return error.SkipZigTest; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.createDirPath(io, "start/a/b"); - var path_buf: [4096]u8 = undefined; - const start = path_buf[0..try tmp.dir.realPathFile(io, "start", &path_buf)]; - var inner_buf: [4096]u8 = undefined; - const inner = inner_buf[0..try tmp.dir.realPathFile(io, "start/a/b", &inner_buf)]; - const rcs: Shell.PromptFiles = .{}; - var result: [4096]u8 = undefined; - // A wrapper exec'd over the shell (timeout standing in for 9ns) runs - // another, two directories down, in the foreground. - { - const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - try std.testing.expect(writeFd(child.file.handle, "exec timeout --foreground 30 /bin/sh -c 'cd a/b && printf \"\\160ardes-in-\\n\" && exec /bin/sh -i'\n")); - try std.testing.expect(sh.waitText("pardes-in-", 5_000)); - // printf runs before the inner shell takes the foreground. - var tries: usize = 0; - while (ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) == null and tries < 50) : (tries += 1) - try std.testing.io.sleep(.fromMilliseconds(20), .awake); - try std.testing.expectEqualStrings(start, shellCwd(child.pid, &result) orelse return error.MissingCwd); - try std.testing.expectEqualStrings(inner, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); - } - // A job of the shell's own, gone into a/b, leaves the pane where the - // shell is. - { - const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - try std.testing.expect(writeFd(child.file.handle, "set -m; (cd a/b && printf '\\160ardes-job\\n' && exec sleep 30)\n")); - try std.testing.expect(sh.waitText("pardes-job", 5_000)); - try std.testing.expectEqualStrings(start, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); - } -} - -test "shell cwd rejects truncation and preserves an owned child path longer than 1024 bytes" { - if (comptime builtin.os.tag != .linux) return error.SkipZigTest; - if (!haveFile("/bin/sh")) return error.SkipZigTest; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - const nested = std.mem.asBytes(&@as([24][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); - try tmp.dir.createDirPath(io, nested); - var path_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - const directory = path_buf[0..try tmp.dir.realPathFile(io, nested, &path_buf)]; - try std.testing.expect(directory.len > 1024); - const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - try std.testing.expect(writeFd(child.file.handle, "printf '\\160ardes-cwd-ready\\n'\n")); - try std.testing.expect(sh.waitText("pardes-cwd-ready", 5_000)); - var result: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; - try std.testing.expect(shellCwd(child.pid, result[0..0]) == null); - try std.testing.expect(shellCwd(child.pid, result[0..1024]) == null); - try std.testing.expect(shellCwd(child.pid, result[0..directory.len]) == null); - try std.testing.expectEqualStrings(directory, shellCwd(child.pid, result[0 .. directory.len + 1]) orelse return error.MissingCwd); - try std.testing.expectEqualStrings(directory, shellCwd(child.pid, &result) orelse return error.MissingCwd); -} - -test "a shell whose directory was removed is not named `... (deleted)`" { - if (comptime builtin.os.tag != .linux) return error.SkipZigTest; - if (!haveFile("/bin/sh")) return error.SkipZigTest; - const io = std.testing.io; - var tmp = std.testing.tmpDir(.{}); - defer tmp.cleanup(); - try tmp.dir.createDirPath(io, "gone"); - var path_buf: [4096]u8 = undefined; - const directory = path_buf[0..try tmp.dir.realPathFile(io, "gone", &path_buf)]; - const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); - defer { - _ = libc.kill(child.pid, libc.SIG.KILL); - _ = libc.waitpid(child.pid, null, 0); - _ = libc.close(child.file.handle); - } - var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; - try std.testing.expect(writeFd(child.file.handle, "printf '\\160ardes-cwd-ready\\n'\n")); - try std.testing.expect(sh.waitText("pardes-cwd-ready", 5_000)); - var result: [4096]u8 = undefined; - try std.testing.expectEqualStrings(directory, shellCwd(child.pid, &result) orelse return error.MissingCwd); - try tmp.dir.deleteDir(io, "gone"); - try std.testing.expect(shellCwd(child.pid, &result) == null); -} - -extern "c" fn tcgetpgrp(fd: c_int) libc.pid_t; +extern "c" fn tcgetpgrp(fd: c_int) libc.pid_t; const occ_max_depth: u8 = 8; const occ_max_visited: usize = 32; @@ -3135,46 +2838,6 @@ fn parseChildren(text: []const u8, out: []libc.pid_t) usize { return total; } -test "the children blob parses to pids, and a garbage token never becomes one" { - var out: [8]libc.pid_t = undefined; - try std.testing.expectEqual(@as(usize, 0), parseChildren("", &out)); - try std.testing.expectEqual(@as(usize, 0), parseChildren(" ", &out)); - try std.testing.expectEqual(@as(usize, 1), parseChildren("991 ", &out)); - try std.testing.expectEqual(@as(libc.pid_t, 991), out[0]); - try std.testing.expectEqual(@as(usize, 3), parseChildren("7 8 9 ", &out)); - try std.testing.expectEqualSlices(libc.pid_t, &.{ 7, 8, 9 }, out[0..3]); - try std.testing.expectEqual(@as(usize, 2), parseChildren("11 12", &out)); - try std.testing.expectEqual(@as(usize, 2), parseChildren("11 12\n", &out)); - try std.testing.expectEqual(@as(usize, 2), parseChildren("5 -1 +7 0x3 abc 6 ", &out)); - try std.testing.expectEqualSlices(libc.pid_t, &.{ 5, 6 }, out[0..2]); - var two: [2]libc.pid_t = undefined; - try std.testing.expectEqual(@as(usize, 4), parseChildren("1 2 3 4 ", &two)); - try std.testing.expectEqualSlices(libc.pid_t, &.{ 1, 2 }, two[0..2]); -} - -test "the process group comes off the last ')', not a comm-shifted stat field" { - const shifted = "1234 (sh (a b)) S 991 992 993 34816 992 4194560 " ++ - "1729 0 0 0 1 0 0 0 20 0 1 0 8244630 9887744 1131"; - try std.testing.expectEqual(@as(libc.pid_t, 992), parseGroupSession(shifted).?.pgrp); - try std.testing.expectEqual(@as(libc.pid_t, 7), parseGroupSession("42 (bash) S 1 7 7 34816 7 4194304").?.pgrp); - try std.testing.expectEqual(@as(libc.pid_t, 42), parseGroupSession("42 (sleep) S 7 42 7 0 -1").?.pgrp); - try std.testing.expect(parseGroupSession("") == null); - try std.testing.expect(parseGroupSession("1234 (bash) S 991") == null); - try std.testing.expect(parseGroupSession("1234 (bash) S 991 notanumber") == null); - try std.testing.expect(parseGroupSession("no parens here at all") == null); -} - -test "the zombie state comes off its own status line" { - try std.testing.expect(parseZombie("Name:\tsh (a b)\nUmask:\t0022\nState:\tZ (zombie)\nTgid:\t1234\n")); - try std.testing.expect(parseZombie("State:\tZ (zombie)\n")); - try std.testing.expect(!parseZombie("Name:\tsh\nState:\tS (sleeping)\n")); - try std.testing.expect(!parseZombie("Name:\tvim\nState:\tR (running)\n")); - try std.testing.expect(!parseZombie("Name:\tvim\nState:\tT (stopped)\n")); - try std.testing.expect(!parseZombie("Name:\tsh (State: Z)\nState:\tS (sleeping)\n")); - try std.testing.expect(!parseZombie("Name:\tsh\nSta")); - try std.testing.expect(!parseZombie("State:\t")); -} - const test_shell = "/bin/bash"; const test_prompt = "PZX> "; @@ -3323,98 +2986,512 @@ fn sleepMs(ms: i64) void { std.testing.io.sleep(.fromMilliseconds(ms), .awake) catch {}; } -test "an idle prompt is free, a foreground job takes the tty, and Ctrl-C hands it back" { - if (comptime !tty_probe_platform) return error.SkipZigTest; - var sh = TestShell.start() orelse return error.SkipZigTest; - defer sh.stop(); - - try std.testing.expect(sh.holdsTaken(false, 200)); +// ---- what every host's vtable does alike ---- - sh.send("sleep 30\n"); - try std.testing.expect(sh.waitTaken(true, 10_000)); +/// A Save's write: the file written through the core's filesystem, the +/// pane's watch told the new text is the editor's own (so it is no outside +/// change), and "saved" said on the pane. +pub fn writeFile(core: *pardes.Pardes, watches: *file_watch.Table, pane: u8, path: []const u8, bytes: []const u8) void { + filesystem.write(core, path, bytes) catch |err| + return core.saveFailed(pane, path, err); + if (core.panes[pane]) |pn| if (pn.file) |f| if (std.mem.eql(u8, f.path, path)) { + if (watches[pane]) |*w| if (w.serial == pn.serial) switch (w.generation) { + .text => w.generation = .{ .text = std.hash.Wyhash.hash(0, bytes) }, + .kind => {}, + }; + }; + var mbuf: [256]u8 = undefined; + core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "saved", path)); + // The init file, saved here (Config): its settings take effect now. + pardes.exec.reapplyInitFile(core, path, bytes); +} - sh.forget(); - sh.send("\x03"); - try std.testing.expect(sh.waitTaken(false, 10_000)); - try std.testing.expect(sh.waitText(test_prompt, 10_000)); +/// A Dump's write: into the state file under a label of its own +/// (Db.putDump), or as a file of its own where `Dump export` names one or +/// $PARDES_DUMP does (verbatim: the snapshot harness pins it for its +/// goldens). +pub fn writeDump(core: *pardes.Pardes, bytes: []const u8) void { + const to: ?[]const u8 = core.dump_export orelse if (std.c.getenv("PARDES_DUMP")) |p| std.mem.span(p) else null; + if (to) |path| { + filesystem.write(core, path, bytes) catch |err| return core.dumpFailed(path, err); + return core.setLastDump(path); + } + var stamp: [64]u8 = undefined; + var buf: [128]u8 = undefined; + const label = core.db.putDump(core, bytes, pardes.dump.label(&stamp), &buf) catch |err| { + var path: [4200]u8 = undefined; + // In the words a host reports failures in (tape.Failure). + const said: pardes.tape.Failure = switch (err) { + error.NoStateFile => error.NoDumpDirectory, + error.OutOfMemory => error.OutOfMemory, + error.NoSpaceLeft => error.NoSpaceLeft, + error.AccessDenied => error.AccessDenied, + else => error.InputOutput, + }; + return core.dumpFailed(pardes.Db.statePath(&path, core.settings.dump_dir.get()) orelse core.settings.dump_dir.get(), said); + }; + core.setLastDump(label); } -test "Kill stops the foreground job, never the shell, and finds none with job control off" { - if (comptime !tty_probe_platform) return error.SkipZigTest; - var sh = TestShell.start() orelse return error.SkipZigTest; - defer sh.stop(); +/// DumpThemes: the built-in themes written below the config directory. +pub fn dumpThemes(core: *pardes.Pardes, io: std.Io, gpa: std.mem.Allocator, pane: u8) void { + const config_dir = core.opts.config_dir orelse return; + const out_dir = pardes.config.User.dumpThemes(io, gpa, config_dir, pardes.themes) catch |err| { + core.reportError(pane, "dump themes", err); + return; + }; + defer gpa.free(out_dir); + var mbuf: [256]u8 = undefined; + core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "dumped themes", out_dir)); +} - // At the prompt the shell is the foreground: there is nothing to stop. - try std.testing.expect(!killJob(sh.pid, sh.master)); - sleepMs(100); - try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); +pub const PtyTests = struct { + pub fn waitBlocked(queue: *Inbox) !void { + const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; + while (std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) { + queue.lock(); + const waiting = queue.waiting; + queue.unlock(); + if (waiting != 0) return; + try std.testing.io.sleep(.fromMilliseconds(1), .awake); + } + return error.ReaderDidNotBlock; + } - sh.send("sleep 30\n"); - try std.testing.expect(sh.waitTaken(true, 10_000)); - sh.forget(); - try std.testing.expect(killJob(sh.pid, sh.master)); - try std.testing.expect(sh.waitTaken(false, 10_000)); - try std.testing.expect(sh.waitText(test_prompt, 10_000)); - try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); + fn tail(queue: *Inbox, bytes: []u8) void { + if (queue.pushOutput(0, 1, bytes)) queue.push(.{ .eof = .{ .pane = 0, .gen = 1 } }); + } +}; - // Job control off: the job runs in the shell's own group. - sh.forget(); - sh.send("set +m; sleep 30\n"); - sleepMs(300); - try std.testing.expect(!killJob(sh.pid, sh.master)); - sh.forget(); - sh.send("\x03"); - try std.testing.expect(sh.waitText(test_prompt, 10_000)); - try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); +test { + _ = Lsp; } -test "a command pane's child is its shell running the one line, and its exit status is read at the end" { - if (comptime !tty_probe_platform) return error.SkipZigTest; - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - while (core.nextEffect()) |_| {} - const id = core.freeSlot().?; - _ = try panes.newCommand(core, id, "", "printf 'said '; exit 7"); - while (core.nextEffect()) |_| {} - const rcs: Shell.PromptFiles = .{}; - const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); - defer _ = libc.close(child.file.handle); - var got: [256]u8 = undefined; - var n: usize = 0; - while (n < got.len) { - const r = libc.read(child.file.handle, got[n..].ptr, got.len - n); - if (r <= 0) break; // EIO once the child is gone: the pty's end - n += @intCast(r); +test "a child starts with every signal at its default and none blocked" { + var blocked = posix.sigemptyset(); + posix.sigaddset(&blocked, posix.SIG.WINCH); + posix.sigprocmask(posix.SIG.BLOCK, &blocked, null); + defer posix.sigprocmask(posix.SIG.UNBLOCK, &blocked, null); + const ignore: posix.Sigaction = .{ .handler = .{ .handler = posix.SIG.IGN }, .mask = posix.sigemptyset(), .flags = 0 }; + var was: posix.Sigaction = undefined; + posix.sigaction(posix.SIG.HUP, &ignore, &was); + defer posix.sigaction(posix.SIG.HUP, &was, null); + const pid = libc.fork(); + if (pid == 0) { + resetChildSignals(); + var now: posix.Sigaction = undefined; + posix.sigaction(posix.SIG.HUP, null, &now); + var mask = posix.sigemptyset(); + posix.sigprocmask(posix.SIG.BLOCK, null, &mask); + const ok = now.handler.handler == posix.SIG.DFL and !posix.sigismember(&mask, posix.SIG.WINCH); + libc._exit(if (ok) 0 else 1); } - try std.testing.expect(std.mem.indexOf(u8, got[0..n], "said") != null); - try std.testing.expectEqual(@as(?u8, 7), exitStatus(child.pid, 2000)); + var status: c_int = 0; + _ = libc.waitpid(pid, &status, 0); + try std.testing.expectEqual(@as(c_int, 0), status); } -test "a command's exit is its process's, told by its watcher, whether or not its pty has ended" { - if (comptime !tty_probe_platform) return error.SkipZigTest; - const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); - defer core.deinit(); - while (core.nextEffect()) |_| {} - const rcs: Shell.PromptFiles = .{}; - const Case = struct { line: []const u8, status: u8 }; - // A job left in the background holds the pty open past the command's - // exit; a command that lets go of its terminal runs on past its end of - // file. Either way the exit is the process's. - for ([_]Case{ - .{ .line = "sleep 3 & exit 4", .status = 4 }, - .{ .line = "exec /dev/null 2>&1; sleep 0.3; exit 5", .status = 5 }, - }) |c| { - const id = core.freeSlot().?; - _ = try panes.newCommand(core, id, "", c.line); - while (core.nextEffect()) |_| {} - const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); - defer _ = libc.close(child.file.handle); - try std.testing.expect(watchExit(child.pid)); - var got: ?libc.pid_t = null; - var waited: i64 = 0; - while (got == null and waited < 5000) : (waited += 10) { - got = takeExited(); - if (got == null) sleepMs(10); +test "the pager's path is quoted only when it needs it" { + var buf: [64]u8 = undefined; + try std.testing.expectEqualStrings("/usr/bin/pardes", ChildEnv.pagerCommand("/usr/bin/pardes", &buf)); + try std.testing.expectEqualStrings("'/opt/my apps/pardes'", ChildEnv.pagerCommand("/opt/my apps/pardes", &buf)); + try std.testing.expectEqualStrings("pardes", ChildEnv.pagerCommand("/odd'dir/pardes", &buf)); +} + +test "the child environment replaces the launcher's terminal identity exactly once" { + const saved: ?[]const u8 = if (libc.getenv("TERM")) |t| std.mem.span(t) else null; + var saved_buf: [256]u8 = undefined; + const restore: ?[:0]const u8 = if (saved) |t| blk: { + if (t.len >= saved_buf.len) break :blk null; + @memcpy(saved_buf[0..t.len], t); + saved_buf[t.len] = 0; + break :blk saved_buf[0..t.len :0]; + } else null; + defer if (restore) |t| { + _ = Shell.setenv("TERM", t.ptr, 1); + } else { + _ = testUnsetenv("TERM"); + }; + + // A launcher TERM must be shadowed rather than duplicated, and the rest of + // the environment must arrive untouched. + try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("TERM", "dumb", 1)); + try std.testing.expectEqual(@as(c_int, 0), Shell.setenv("PARDES_CHILD_ENV_PROBE", "1", 1)); + defer _ = testUnsetenv("PARDES_CHILD_ENV_PROBE"); + + var slots: ChildEnv.Slots = undefined; + // Where the user named no pager: a terminal's shell pages into a + // +Pager pane (`pardes -`); a command pane's through cat. A pager the + // user named is kept. + var shell_slots: ChildEnv.Slots = undefined; + const shell_envp = ChildEnv.build(&shell_slots, .terminal) orelse return error.EnvironmentTooLarge; + var said: usize = 0; + var systemd: usize = 0; + var j: usize = 0; + while (shell_envp[j]) |entry| : (j += 1) { + const line = std.mem.span(entry); + if (std.c.getenv("SYSTEMD_PAGER") == null and std.mem.startsWith(u8, line, "SYSTEMD_PAGER=")) systemd += 1; + if (std.c.getenv("SYSTEMD_PAGERSECURE") == null and std.mem.eql(u8, line, "SYSTEMD_PAGERSECURE=0")) systemd += 1; + if (std.mem.startsWith(u8, line, "PAGER=") and std.c.getenv("PAGER") == null) { + try std.testing.expect(std.mem.endsWith(u8, line, " -")); + said += 1; + } + } + if (std.c.getenv("PAGER") == null) try std.testing.expectEqual(@as(usize, 1), said); + // systemd's pager and its secure mode off, with ours only. + if (std.c.getenv("SYSTEMD_PAGER") == null and std.c.getenv("SYSTEMD_PAGERSECURE") == null) + try std.testing.expectEqual(@as(usize, 2), systemd); + const envp = ChildEnv.build(&slots, .command) orelse return error.EnvironmentTooLarge; + var terms: usize = 0; + var colorterms: usize = 0; + var probes: usize = 0; + var dumb = false; + var pagers: usize = 0; + var git_pagers: usize = 0; + var pager_cat = false; + var git_pager_cat = false; + var i: usize = 0; + while (envp[i]) |entry| : (i += 1) { + const line = std.mem.span(entry); + if (std.mem.startsWith(u8, line, "TERM=")) terms += 1; + if (std.mem.startsWith(u8, line, "COLORTERM=")) colorterms += 1; + if (std.mem.eql(u8, line, "TERM=dumb")) dumb = true; + if (std.mem.eql(u8, line, "PARDES_CHILD_ENV_PROBE=1")) probes += 1; + if (std.mem.startsWith(u8, line, "PAGER=")) pagers += 1; + if (std.mem.startsWith(u8, line, "GIT_PAGER=")) git_pagers += 1; + if (std.mem.eql(u8, line, "PAGER=cat")) pager_cat = true; + if (std.mem.eql(u8, line, "GIT_PAGER=cat")) git_pager_cat = true; + } + // A pager only where the user named none: cat, so nothing waits in less. + try std.testing.expectEqual(@as(usize, 1), pagers); + try std.testing.expectEqual(@as(usize, 1), git_pagers); + if (std.c.getenv("PAGER") == null) try std.testing.expect(pager_cat); + if (std.c.getenv("GIT_PAGER") == null) try std.testing.expect(git_pager_cat); + try std.testing.expectEqual(@as(usize, 1), terms); + try std.testing.expectEqual(@as(usize, 1), colorterms); + try std.testing.expectEqual(@as(usize, 1), probes); + try std.testing.expect(!dumb); + // TERM_PROGRAM shares the prefix "TERM"; the match is on the name, so it + // is a separate entry and never a second TERM. + try std.testing.expectEqualStrings("TERM=" ++ pardes.config.child_term, std.mem.span(envp[i - ChildEnv.own.len].?)); +} + +test "shell spawn rejects invalid directories before creating a child" { + const rcs: Shell.PromptFiles = .{}; + try std.testing.expectError(error.InvalidPath, forkShell(null, 0, &rcs, "/bin/sh", "/tmp\x00/ignored", 24, 80)); + const too_long = @as([4096]u8, @splat('x')); + try std.testing.expectError(error.NameTooLong, forkShell(null, 0, &rcs, "/bin/sh", &too_long, 24, 80)); + + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "file", .data = "not a directory\n" }); + var directory_buf: [4096]u8 = undefined; + const directory = directory_buf[0..try tmp.dir.realPath(std.testing.io, &directory_buf)]; + var path_buf: [4096]u8 = undefined; + const file = try std.fmt.bufPrint(&path_buf, "{s}/file", .{directory}); + try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", file, 24, 80)); + const explicit_file = try std.fmt.bufPrint(&path_buf, "/n/os{s}/file", .{directory}); + try std.testing.expectError(error.NotDir, forkShell(null, 0, &rcs, "/bin/sh", explicit_file, 24, 80)); + const missing = try std.fmt.bufPrint(&path_buf, "{s}/missing/" ++ (std.mem.asBytes(&@as([50][6]u8, @splat("child/".*)))), .{directory}); + try std.testing.expect(missing.len > 256); + try std.testing.expectError(error.FileNotFound, forkShell(null, 0, &rcs, "/bin/sh", missing, 24, 80)); +} + +test "a forked shell is told which terminal it is talking to" { + if (!haveFile("/bin/sh")) return error.SkipZigTest; + // Whatever launched the test is the wrong answer, so make it a loud one. + const saved = libc.getenv("TERM"); + var saved_buf: [256]u8 = undefined; + const restore: ?[:0]const u8 = if (saved) |t| blk: { + const span = std.mem.span(t); + if (span.len >= saved_buf.len) break :blk null; + @memcpy(saved_buf[0..span.len], span); + saved_buf[span.len] = 0; + break :blk saved_buf[0..span.len :0]; + } else null; + defer if (restore) |t| { + _ = Shell.setenv("TERM", t.ptr, 1); + } else { + _ = testUnsetenv("TERM"); + }; + _ = Shell.setenv("TERM", "dumb", 1); + + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", "", 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + // The echoed command carries the unexpanded `$TERM`, so only the shell's + // own expansion can match this. + try std.testing.expect(writeFd(child.file.handle, "printf '\nPARDES-TERM:%s:%s\n' \"$TERM\" \"$COLORTERM\"; exit\n")); + try std.testing.expect(sh.waitText( + "PARDES-TERM:" ++ pardes.config.child_term ++ ":" ++ pardes.config.child_colorterm, + 5_000, + )); +} + +test "shell spawn uses an explicit OS directory longer than 256 bytes" { + if (!haveFile("/bin/sh")) return error.SkipZigTest; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const sub_path = std.mem.asBytes(&@as([7][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); + try tmp.dir.createDirPath(std.testing.io, sub_path); + var directory_buf: [4096]u8 = undefined; + const directory = directory_buf[0..try tmp.dir.realPathFile(std.testing.io, sub_path, &directory_buf)]; + try std.testing.expect(directory.len > 256); + var explicit_buf: [4096]u8 = undefined; + const explicit = try std.fmt.bufPrint(&explicit_buf, "/n/os{s}", .{directory}); + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", explicit, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "printf '\\nPARDES-CWD:'; pwd; exit\n")); + var expected_buf: [4096]u8 = undefined; + const expected = try std.fmt.bufPrint(&expected_buf, "PARDES-CWD:{s}", .{directory}); + try std.testing.expect(sh.waitText(expected, 5_000)); +} + +test "a terminal is where its shell is: under a wrapper the foreground shell, never a job's directory" { + if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (!haveFile("/bin/sh") or !haveFile("/usr/bin/timeout")) return error.SkipZigTest; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(io, "start/a/b"); + var path_buf: [4096]u8 = undefined; + const start = path_buf[0..try tmp.dir.realPathFile(io, "start", &path_buf)]; + var inner_buf: [4096]u8 = undefined; + const inner = inner_buf[0..try tmp.dir.realPathFile(io, "start/a/b", &inner_buf)]; + const rcs: Shell.PromptFiles = .{}; + var result: [4096]u8 = undefined; + // A wrapper exec'd over the shell (timeout standing in for 9ns) runs + // another, two directories down, in the foreground. + { + const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "exec timeout --foreground 30 /bin/sh -c 'cd a/b && printf \"\\160ardes-in-\\n\" && exec /bin/sh -i'\n")); + try std.testing.expect(sh.waitText("pardes-in-", 5_000)); + // printf runs before the inner shell takes the foreground. + var tries: usize = 0; + while (ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) == null and tries < 50) : (tries += 1) + try std.testing.io.sleep(.fromMilliseconds(20), .awake); + try std.testing.expectEqualStrings(start, shellCwd(child.pid, &result) orelse return error.MissingCwd); + try std.testing.expectEqualStrings(inner, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); + } + // A job of the shell's own, gone into a/b, leaves the pane where the + // shell is. + { + const child = try forkShell(null, 0, &rcs, "/bin/sh", start, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "set -m; (cd a/b && printf '\\160ardes-job\\n' && exec sleep 30)\n")); + try std.testing.expect(sh.waitText("pardes-job", 5_000)); + try std.testing.expectEqualStrings(start, ttyCwd(child.pid, child.file.handle, "/bin/sh", &result) orelse return error.MissingCwd); + } +} + +test "shell cwd rejects truncation and preserves an owned child path longer than 1024 bytes" { + if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (!haveFile("/bin/sh")) return error.SkipZigTest; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + const nested = std.mem.asBytes(&@as([24][49]u8, @splat("nested-directory-with-more-than-forty-characters/".*))); + try tmp.dir.createDirPath(io, nested); + var path_buf: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + const directory = path_buf[0..try tmp.dir.realPathFile(io, nested, &path_buf)]; + try std.testing.expect(directory.len > 1024); + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "printf '\\160ardes-cwd-ready\\n'\n")); + try std.testing.expect(sh.waitText("pardes-cwd-ready", 5_000)); + var result: [pardes.memory.limits.host_path_cap + 1]u8 = undefined; + try std.testing.expect(shellCwd(child.pid, result[0..0]) == null); + try std.testing.expect(shellCwd(child.pid, result[0..1024]) == null); + try std.testing.expect(shellCwd(child.pid, result[0..directory.len]) == null); + try std.testing.expectEqualStrings(directory, shellCwd(child.pid, result[0 .. directory.len + 1]) orelse return error.MissingCwd); + try std.testing.expectEqualStrings(directory, shellCwd(child.pid, &result) orelse return error.MissingCwd); +} + +test "a shell whose directory was removed is not named `... (deleted)`" { + if (comptime builtin.os.tag != .linux) return error.SkipZigTest; + if (!haveFile("/bin/sh")) return error.SkipZigTest; + const io = std.testing.io; + var tmp = std.testing.tmpDir(.{}); + defer tmp.cleanup(); + try tmp.dir.createDirPath(io, "gone"); + var path_buf: [4096]u8 = undefined; + const directory = path_buf[0..try tmp.dir.realPathFile(io, "gone", &path_buf)]; + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(null, 0, &rcs, "/bin/sh", directory, 24, 80); + defer { + _ = libc.kill(child.pid, libc.SIG.KILL); + _ = libc.waitpid(child.pid, null, 0); + _ = libc.close(child.file.handle); + } + var sh: TestShell = .{ .master = child.file.handle, .pid = child.pid }; + try std.testing.expect(writeFd(child.file.handle, "printf '\\160ardes-cwd-ready\\n'\n")); + try std.testing.expect(sh.waitText("pardes-cwd-ready", 5_000)); + var result: [4096]u8 = undefined; + try std.testing.expectEqualStrings(directory, shellCwd(child.pid, &result) orelse return error.MissingCwd); + try tmp.dir.deleteDir(io, "gone"); + try std.testing.expect(shellCwd(child.pid, &result) == null); +} + +test "the children blob parses to pids, and a garbage token never becomes one" { + var out: [8]libc.pid_t = undefined; + try std.testing.expectEqual(@as(usize, 0), parseChildren("", &out)); + try std.testing.expectEqual(@as(usize, 0), parseChildren(" ", &out)); + try std.testing.expectEqual(@as(usize, 1), parseChildren("991 ", &out)); + try std.testing.expectEqual(@as(libc.pid_t, 991), out[0]); + try std.testing.expectEqual(@as(usize, 3), parseChildren("7 8 9 ", &out)); + try std.testing.expectEqualSlices(libc.pid_t, &.{ 7, 8, 9 }, out[0..3]); + try std.testing.expectEqual(@as(usize, 2), parseChildren("11 12", &out)); + try std.testing.expectEqual(@as(usize, 2), parseChildren("11 12\n", &out)); + try std.testing.expectEqual(@as(usize, 2), parseChildren("5 -1 +7 0x3 abc 6 ", &out)); + try std.testing.expectEqualSlices(libc.pid_t, &.{ 5, 6 }, out[0..2]); + var two: [2]libc.pid_t = undefined; + try std.testing.expectEqual(@as(usize, 4), parseChildren("1 2 3 4 ", &two)); + try std.testing.expectEqualSlices(libc.pid_t, &.{ 1, 2 }, two[0..2]); +} + +test "the process group comes off the last ')', not a comm-shifted stat field" { + const shifted = "1234 (sh (a b)) S 991 992 993 34816 992 4194560 " ++ + "1729 0 0 0 1 0 0 0 20 0 1 0 8244630 9887744 1131"; + try std.testing.expectEqual(@as(libc.pid_t, 992), parseGroupSession(shifted).?.pgrp); + try std.testing.expectEqual(@as(libc.pid_t, 7), parseGroupSession("42 (bash) S 1 7 7 34816 7 4194304").?.pgrp); + try std.testing.expectEqual(@as(libc.pid_t, 42), parseGroupSession("42 (sleep) S 7 42 7 0 -1").?.pgrp); + try std.testing.expect(parseGroupSession("") == null); + try std.testing.expect(parseGroupSession("1234 (bash) S 991") == null); + try std.testing.expect(parseGroupSession("1234 (bash) S 991 notanumber") == null); + try std.testing.expect(parseGroupSession("no parens here at all") == null); +} + +test "the zombie state comes off its own status line" { + try std.testing.expect(parseZombie("Name:\tsh (a b)\nUmask:\t0022\nState:\tZ (zombie)\nTgid:\t1234\n")); + try std.testing.expect(parseZombie("State:\tZ (zombie)\n")); + try std.testing.expect(!parseZombie("Name:\tsh\nState:\tS (sleeping)\n")); + try std.testing.expect(!parseZombie("Name:\tvim\nState:\tR (running)\n")); + try std.testing.expect(!parseZombie("Name:\tvim\nState:\tT (stopped)\n")); + try std.testing.expect(!parseZombie("Name:\tsh (State: Z)\nState:\tS (sleeping)\n")); + try std.testing.expect(!parseZombie("Name:\tsh\nSta")); + try std.testing.expect(!parseZombie("State:\t")); +} + +test "an idle prompt is free, a foreground job takes the tty, and Ctrl-C hands it back" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + + try std.testing.expect(sh.holdsTaken(false, 200)); + + sh.send("sleep 30\n"); + try std.testing.expect(sh.waitTaken(true, 10_000)); + + sh.forget(); + sh.send("\x03"); + try std.testing.expect(sh.waitTaken(false, 10_000)); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); +} + +test "Kill stops the foreground job, never the shell, and finds none with job control off" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + var sh = TestShell.start() orelse return error.SkipZigTest; + defer sh.stop(); + + // At the prompt the shell is the foreground: there is nothing to stop. + try std.testing.expect(!killJob(sh.pid, sh.master)); + sleepMs(100); + try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); + + sh.send("sleep 30\n"); + try std.testing.expect(sh.waitTaken(true, 10_000)); + sh.forget(); + try std.testing.expect(killJob(sh.pid, sh.master)); + try std.testing.expect(sh.waitTaken(false, 10_000)); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); + try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); + + // Job control off: the job runs in the shell's own group. + sh.forget(); + sh.send("set +m; sleep 30\n"); + sleepMs(300); + try std.testing.expect(!killJob(sh.pid, sh.master)); + sh.forget(); + sh.send("\x03"); + try std.testing.expect(sh.waitText(test_prompt, 10_000)); + try std.testing.expectEqual(@as(libc.pid_t, 0), libc.waitpid(sh.pid, null, libc.W.NOHANG)); +} + +test "a command pane's child is its shell running the one line, and its exit status is read at the end" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + while (core.nextEffect()) |_| {} + const id = core.freeSlot().?; + _ = try panes.newCommand(core, id, "", "printf 'said '; exit 7"); + while (core.nextEffect()) |_| {} + const rcs: Shell.PromptFiles = .{}; + const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); + defer _ = libc.close(child.file.handle); + var got: [256]u8 = undefined; + var n: usize = 0; + while (n < got.len) { + const r = libc.read(child.file.handle, got[n..].ptr, got.len - n); + if (r <= 0) break; // EIO once the child is gone: the pty's end + n += @intCast(r); + } + try std.testing.expect(std.mem.indexOf(u8, got[0..n], "said") != null); + try std.testing.expectEqual(@as(?u8, 7), exitStatus(child.pid, 2000)); +} + +test "a command's exit is its process's, told by its watcher, whether or not its pty has ended" { + if (comptime !tty_probe_platform) return error.SkipZigTest; + const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true }); + defer core.deinit(); + while (core.nextEffect()) |_| {} + const rcs: Shell.PromptFiles = .{}; + const Case = struct { line: []const u8, status: u8 }; + // A job left in the background holds the pty open past the command's + // exit; a command that lets go of its terminal runs on past its end of + // file. Either way the exit is the process's. + for ([_]Case{ + .{ .line = "sleep 3 & exit 4", .status = 4 }, + .{ .line = "exec /dev/null 2>&1; sleep 0.3; exit 5", .status = 5 }, + }) |c| { + const id = core.freeSlot().?; + _ = try panes.newCommand(core, id, "", c.line); + while (core.nextEffect()) |_| {} + const child = try forkShell(core, id, &rcs, "/bin/sh", "", 24, 80); + defer _ = libc.close(child.file.handle); + try std.testing.expect(watchExit(child.pid)); + var got: ?libc.pid_t = null; + var waited: i64 = 0; + while (got == null and waited < 5000) : (waited += 10) { + got = takeExited(); + if (got == null) sleepMs(10); } try std.testing.expectEqual(@as(?libc.pid_t, child.pid), got); // Told before it is reaped: the pid is still the child's. @@ -3581,65 +3658,6 @@ test "a full-screen program takes the tty until it quits" { if (ran == 0) return error.SkipZigTest; } -// ---- what every host's vtable does alike ---- - -/// A Save's write: the file written through the core's filesystem, the -/// pane's watch told the new text is the editor's own (so it is no outside -/// change), and "saved" said on the pane. -pub fn writeFile(core: *pardes.Pardes, watches: *file_watch.Table, pane: u8, path: []const u8, bytes: []const u8) void { - filesystem.write(core, path, bytes) catch |err| - return core.saveFailed(pane, path, err); - if (core.panes[pane]) |pn| if (pn.file) |f| if (std.mem.eql(u8, f.path, path)) { - if (watches[pane]) |*w| if (w.serial == pn.serial) switch (w.generation) { - .text => w.generation = .{ .text = std.hash.Wyhash.hash(0, bytes) }, - .kind => {}, - }; - }; - var mbuf: [256]u8 = undefined; - core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "saved", path)); - // The init file, saved here (Config): its settings take effect now. - pardes.exec.reapplyInitFile(core, path, bytes); -} - -/// A Dump's write: into the state file under a label of its own -/// (Db.putDump), or as a file of its own where `Dump export` names one or -/// $PARDES_DUMP does (verbatim: the snapshot harness pins it for its -/// goldens). -pub fn writeDump(core: *pardes.Pardes, bytes: []const u8) void { - const to: ?[]const u8 = core.dump_export orelse if (std.c.getenv("PARDES_DUMP")) |p| std.mem.span(p) else null; - if (to) |path| { - filesystem.write(core, path, bytes) catch |err| return core.dumpFailed(path, err); - return core.setLastDump(path); - } - var stamp: [64]u8 = undefined; - var buf: [128]u8 = undefined; - const label = core.db.putDump(core, bytes, pardes.dump.label(&stamp), &buf) catch |err| { - var path: [4200]u8 = undefined; - // In the words a host reports failures in (tape.Failure). - const said: pardes.tape.Failure = switch (err) { - error.NoStateFile => error.NoDumpDirectory, - error.OutOfMemory => error.OutOfMemory, - error.NoSpaceLeft => error.NoSpaceLeft, - error.AccessDenied => error.AccessDenied, - else => error.InputOutput, - }; - return core.dumpFailed(pardes.Db.statePath(&path, core.settings.dump_dir.get()) orelse core.settings.dump_dir.get(), said); - }; - core.setLastDump(label); -} - -/// DumpThemes: the built-in themes written below the config directory. -pub fn dumpThemes(core: *pardes.Pardes, io: std.Io, gpa: std.mem.Allocator, pane: u8) void { - const config_dir = core.opts.config_dir orelse return; - const out_dir = pardes.config.User.dumpThemes(io, gpa, config_dir, pardes.themes) catch |err| { - core.reportError(pane, "dump themes", err); - return; - }; - defer gpa.free(out_dir); - var mbuf: [256]u8 = undefined; - core.setMessage(pane, pardes.Messages.Message.stamp(&mbuf, "dumped themes", out_dir)); -} - test "completion survives a full output queue" { const gpa = std.testing.allocator; var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa, .lsp_id = 7 }; @@ -3678,24 +3696,6 @@ test "completion survives a full output queue" { try std.testing.expectEqual(@as(usize, 0), queue.take().len); } -pub const PtyTests = struct { - pub fn waitBlocked(queue: *Inbox) !void { - const until = std.Io.Clock.awake.now(std.testing.io).toMilliseconds() + 2_000; - while (std.Io.Clock.awake.now(std.testing.io).toMilliseconds() < until) { - queue.lock(); - const waiting = queue.waiting; - queue.unlock(); - if (waiting != 0) return; - try std.testing.io.sleep(.fromMilliseconds(1), .awake); - } - return error.ReaderDidNotBlock; - } - - fn tail(queue: *Inbox, bytes: []u8) void { - if (queue.pushOutput(0, 1, bytes)) queue.push(.{ .eof = .{ .pane = 0, .gen = 1 } }); - } -}; - test "PTY backpressure retains byte order and tail before EOF" { const gpa = std.testing.allocator; var queue: Inbox = .{ .io = std.testing.io, .gpa = gpa, .lsp_allocator = gpa }; -- cgit v1.3