summaryrefslogtreecommitdiff
path: root/test/process
diff options
context:
space:
mode:
Diffstat (limited to 'test/process')
-rw-r--r--test/process/edit.zig139
-rw-r--r--test/process/other_files.zig119
-rw-r--r--test/process/root_ctl.zig107
-rw-r--r--test/process/terminals.zig241
-rw-r--r--test/process/tree.zig484
5 files changed, 1090 insertions, 0 deletions
diff --git a/test/process/edit.zig b/test/process/edit.zig
new file mode 100644
index 00000000..8cccfdd1
--- /dev/null
+++ b/test/process/edit.zig
@@ -0,0 +1,139 @@
+//! docs/typ/reference.typ, Edit <edit>, through a real session's socket:
+//! its commands run in the session's shell, and its w writes.
+const std = @import("std");
+const process = @import("../process.zig");
+const eh = @import("../e2e_harness.zig");
+const expect = std.testing.expect;
+const expectEqual = std.testing.expectEqual;
+const expectEqualStrings = std.testing.expectEqualStrings;
+
+pub const cases = .{
+ .{ "edit: < | > run off the loop and answer their write once applied, a failing one changing nothing; a held Edit write is flushed; X edits every open file it matches, w writes", editCommands },
+};
+
+fn has(hay: []const u8, needle: []const u8) bool {
+ return std.mem.indexOf(u8, hay, needle) != null;
+}
+
+fn refusedSaying(c: *process.Conn, path: []const u8, data: []const u8, why: []const u8) !void {
+ try std.testing.expectError(error.Refused, c.write(path, data));
+ if (!has(c.said, why)) {
+ std.debug.print("{s} refused saying {s}, not {s}\n", .{ path, c.said, why });
+ return error.WrongWords;
+ }
+}
+
+/// An Edit written on another connection, in a thread.
+const Slow = struct {
+ conn: *process.Conn,
+ path: []const u8,
+ done: std.atomic.Value(bool) = .init(false),
+
+ fn go(s: *Slow) void {
+ s.conn.write(s.path, "Edit , | sleep 1; cat\n") catch {};
+ s.done.store(true, .release);
+ }
+};
+
+fn editCommands(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var d = try process.Detached.start(gpa, exe, "edit", .{});
+ defer d.deinit();
+ const f = &d.files;
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const ar = arena.allocator();
+ const c = try process.Conn.dial(gpa, d.socket());
+ defer c.deinit(gpa);
+ const root = d.root();
+ try d.put("a.txt", "pear\napple\nfig\n");
+ try d.put("b.txt", "apple pie\n");
+ const a = try c.look(ar, f.at("{s}/a.txt", .{root}));
+ const b = try c.look(ar, f.at("{s}/b.txt", .{root}));
+ const actl = f.at("/pane/{d}/ctl", .{a});
+ const abody = f.at("/pane/{d}/body", .{a});
+ // The write returns with the text sorted, through the session's shell
+ // in the file's directory.
+ try c.write(actl, "Edit , | sort\n");
+ try expectEqualStrings("apple\nfig\npear\n", try c.read(ar, abody));
+ try c.write(actl, "Edit $ < pwd\n");
+ try expectEqualStrings(f.at("apple\nfig\npear\n{s}\n", .{root}), try c.read(ar, abody));
+ try c.write(actl, "Undo\n");
+ try expectEqualStrings("apple\nfig\npear\n", try c.read(ar, abody));
+ // A per-match command, one undo step.
+ try c.write(actl, "Edit ,x/[a-z]+/ | tr a-z A-Z\n");
+ try expectEqualStrings("APPLE\nFIG\nPEAR\n", try c.read(ar, abody));
+ // A failing command: nothing changed, the write fails in words, its
+ // stderr in +Errors.
+ try refusedSaying(c, actl, "Edit , | echo nope >&2; exit 4\n", "exit status 4");
+ try expectEqualStrings("APPLE\nFIG\nPEAR\n", try c.read(ar, abody));
+ var said = false;
+ var rows = std.mem.tokenizeScalar(u8, try c.read(ar, "/index"), '\n');
+ while (rows.next()) |row| {
+ if (!has(row, "+Errors")) continue;
+ said = said or has(try c.read(ar, f.at("/pane/{s}/body", .{row[0..std.mem.indexOfScalar(u8, row, ' ').?]})), "nope");
+ }
+ try expect(said);
+ // While a slow command runs, the editor answers.
+ {
+ const other = try process.Conn.dial(gpa, d.socket());
+ defer other.deinit(gpa);
+ var slow: Slow = .{ .conn = other, .path = f.at("/pane/{d}/ctl", .{b}) };
+ const worker = try std.Thread.spawn(.{}, Slow.go, .{&slow});
+ process.sleep(200);
+ const began = eh.nowMs();
+ _ = try c.read(ar, "/index");
+ const quick = eh.nowMs() - began < 500 and !slow.done.load(.acquire);
+ worker.join();
+ try expect(quick); // the editor did not wait on the command
+ try expect(slow.done.load(.acquire));
+ }
+ // On the same connection: the Edit's write is held, and a read sent
+ // after it is answered first; a Tflush of it stops it, changes nothing,
+ // and frees the way for the next Edit.
+ const ctl = try c.hold(actl, 1);
+ const status = try c.hold("/status", 0);
+ const began = eh.nowMs();
+ const held = try c.send(.{ .write = .{ .fid = ctl, .offset = 0, .data = "Edit , | sleep 1; cat\n" } });
+ const read = try c.send(.{ .read = .{ .fid = status, .offset = 0, .count = 4096 } });
+ const first = try c.answer();
+ try expect(first.tag == read and first.result == .read and eh.nowMs() - began < 500);
+ const second = try c.answer();
+ try expect(second.tag == held and second.result == .write);
+ const flushed = try c.send(.{ .write = .{ .fid = ctl, .offset = 0, .data = "Edit , | sleep 5; tr a-z A-Z\n" } });
+ process.sleep(300);
+ const flush = try c.send(.{ .flush = .{ .oldtag = flushed } });
+ const one = (try c.answer()).tag;
+ const two = (try c.answer()).tag;
+ try expect((one == flushed and two == flush) or (one == flush and two == flushed));
+ c.clunk(ctl);
+ c.clunk(status);
+ process.sleep(1000);
+ try c.write(actl, "Edit , | cat\n");
+ process.sleep(4500);
+ try expectEqualStrings("APPLE\nFIG\nPEAR\n", try c.read(ar, abody));
+ // X: each open file whose line matches; w writes it.
+ try c.write(actl, "Edit X/b\\.txt$/ ,s/apple/APPLE/\n");
+ try expectEqualStrings("APPLE pie\n", try c.read(ar, f.at("/pane/{d}/body", .{b})));
+ try c.write(f.at("/pane/{d}/ctl", .{b}), "Edit w\n");
+ try expectEqualStrings("APPLE pie\n", try d.get(ar, "b.txt"));
+ try c.write(actl, "Edit 1 w first.txt\n");
+ try expectEqualStrings("APPLE\n", try d.get(ar, "first.txt"));
+ // A file changed on disk under unsaved edits: Edit's w refuses once, as
+ // Save does, and the next w overwrites it.
+ try d.put("w1.txt", "one\n");
+ const w = try c.look(ar, f.at("{s}/w1.txt", .{root}));
+ const wctl = f.at("/pane/{d}/ctl", .{w});
+ try c.write(wctl, "Edit $a/two/\n");
+ const changed = f.at("\nchanged {d}", .{w});
+ const seen = std.mem.count(u8, try c.read(ar, "/log"), changed);
+ try eh.appendFile(try std.fmt.allocPrintSentinel(ar, "{s}/w1.txt", .{root}, 0), "external\n");
+ const deadline = eh.nowMs() + 10_000;
+ while (std.mem.count(u8, try c.read(ar, "/log"), changed) == seen) {
+ if (eh.nowMs() > deadline) return error.NeverHeard;
+ process.sleep(50);
+ }
+ try refusedSaying(c, wctl, "Edit w\n", "modified on disk since read (w again to overwrite)");
+ try expectEqualStrings("one\nexternal\n", try d.get(ar, "w1.txt"));
+ try c.write(wctl, "Edit w\n");
+ try expectEqualStrings("one\ntwo", try d.get(ar, "w1.txt"));
+}
diff --git a/test/process/other_files.zig b/test/process/other_files.zig
index d03d6b36..f682bb18 100644
--- a/test/process/other_files.zig
+++ b/test/process/other_files.zig
@@ -6,8 +6,33 @@ const process = @import("../process.zig");
pub const cases = .{
.{ "other-files: kbdin and mousein drive a detached session as the user would, each write done before it is answered", keysAndMouse },
.{ "other-files: a held connection lists a directory, stats a file, writes and reads, is refused in words and removes a pane", heldConnection },
+ .{ "other-files: a file opened and closed is in /recent closed, and still is in the next session; Recent's row opens it again", recentSurvivesRestart },
+ .{ "other-files: two sessions share one store: a file opened in one is in the other's /recent, a Del'd pane comes back from @p only where it was", storeShared },
};
+extern "c" fn system(cmd: [*:0]const u8) c_int;
+
+fn has(hay: []const u8, needle: []const u8) bool {
+ return std.mem.indexOf(u8, hay, needle) != null;
+}
+
+/// A session's root kept past it, removed at the test's end.
+fn keepRoot(d: *process.Detached, buf: *[4096]u8) []const u8 {
+ d.owns_root = false;
+ @memcpy(buf[0..d.root().len], d.root());
+ return buf[0..d.root().len];
+}
+
+fn removeRoot(root: []const u8) void {
+ var cmd: [4200]u8 = undefined;
+ _ = system(std.fmt.bufPrintSentinel(&cmd, "rm -rf -- '{s}'", .{root}, 0) catch return);
+}
+
+fn storeExists(root: []const u8) bool {
+ var buf: [4200]u8 = undefined;
+ return std.c.access(std.fmt.bufPrintSentinel(&buf, "{s}/.local/state/pardes/store", .{root}, 0) catch return false, 0) == 0;
+}
+
/// A script types and clicks as the user does: no sleep or poll between a
/// write and the read that checks it; where to click is read off /screen.
/// (test/fs.py's keys_and_mouse, the first case written through the files
@@ -64,3 +89,97 @@ fn heldConnection(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
try c.remove(try std.fmt.bufPrint(&path, "/pane/{d}", .{serial}));
try std.testing.expectError(error.NotFound, c.walk(body));
}
+
+/// The list is kept under $XDG_STATE_HOME (here HOME's .local/state) across
+/// restarts.
+fn recentSurvivesRestart(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var root_buf: [4096]u8 = undefined;
+ var one = try process.Detached.start(gpa, exe, "recent1", .{});
+ const root = keepRoot(&one, &root_buf);
+ defer removeRoot(root);
+ const kept = try std.fmt.allocPrint(a, "{s}/kept.txt", .{root});
+ {
+ defer one.deinit();
+ try one.put("kept.txt", "one\ntwo\n");
+ const c = try process.Conn.dial(gpa, one.socket());
+ defer c.deinit(gpa);
+ const serial = try c.look(a, try std.fmt.allocPrint(a, "{s}:2", .{kept}));
+ try std.testing.expect(has(try c.read(a, "/recent"), try std.fmt.allocPrint(a, "open {s}\n", .{kept})));
+ try c.write(try std.fmt.allocPrint(a, "/pane/{d}/ctl", .{serial}), "Del\n");
+ try std.testing.expect(has(try c.read(a, "/recent"), try std.fmt.allocPrint(a, "closed {s}\n", .{kept})));
+ }
+ try std.testing.expect(storeExists(root));
+ var two = try process.Detached.start(gpa, exe, "recent2", .{ .root = root });
+ defer two.deinit();
+ const c = try process.Conn.dial(gpa, two.socket());
+ defer c.deinit(gpa);
+ try std.testing.expect(has(try c.read(a, "/recent"), try std.fmt.allocPrint(a, "closed {s}\n", .{kept})));
+ // Recent fills a query pane with it, its row relative to the pane's
+ // directory, and a look at the row opens it again.
+ try c.write("/pane/1/exec", "Recent\n");
+ var answer = std.mem.tokenizeAny(u8, try c.read(a, "/pane/1/exec"), " \n");
+ var last: []const u8 = "";
+ while (answer.next()) |w| last = w;
+ const rows = try std.fmt.parseInt(u32, last, 10);
+ const body = try c.read(a, try std.fmt.allocPrint(a, "/pane/{d}/body", .{rows}));
+ try std.testing.expect(std.mem.startsWith(u8, body, "Recent "));
+ var lines = std.mem.tokenizeScalar(u8, body, '\n');
+ const row = while (lines.next()) |l| {
+ if (std.mem.startsWith(u8, l, "kept.txt:")) break l;
+ } else return error.NoRow;
+ try c.write(try std.fmt.allocPrint(a, "/pane/{d}/look", .{rows}), try std.fmt.allocPrint(a, "{s}\n", .{row[0 .. std.mem.indexOfScalar(u8, row, ' ') orelse row.len]}));
+ try std.testing.expect(has(try c.read(a, "/recent"), try std.fmt.allocPrint(a, "open {s}\n", .{kept})));
+}
+
+/// Del, and again when the first refused over unsaved text.
+fn delTwice(c: *process.Conn, ctl: []const u8) !void {
+ c.write(ctl, "Del\n") catch try c.write(ctl, "Del\n");
+}
+
+/// The store (Store.zig) shared with no restart; a pane Del'd in one
+/// comes back where it was from a look at its @p serial there, its text
+/// with it, and only there.
+fn storeShared(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ var root_buf: [4096]u8 = undefined;
+ var one = try process.Detached.start(gpa, exe, "store1", .{});
+ const root = keepRoot(&one, &root_buf);
+ defer removeRoot(root);
+ {
+ defer one.deinit();
+ var two = try process.Detached.start(gpa, exe, "store2", .{ .root = root });
+ defer two.deinit();
+ const c1 = try process.Conn.dial(gpa, one.socket());
+ defer c1.deinit(gpa);
+ const c2 = try process.Conn.dial(gpa, two.socket());
+ defer c2.deinit(gpa);
+ try one.put("shared.txt", "one\ntwo\nthree\n");
+ const shared = try std.fmt.allocPrint(a, "{s}/shared.txt", .{root});
+ const serial = try c1.look(a, try std.fmt.allocPrint(a, "{s}:3", .{shared}));
+ try std.testing.expect(has(try c1.read(a, "/recent"), try std.fmt.allocPrint(a, "open {s}\n", .{shared})));
+ try std.testing.expect(has(try c2.read(a, "/recent"), try std.fmt.allocPrint(a, "closed {s}\n", .{shared})));
+ try c1.write(try std.fmt.allocPrint(a, "/pane/{d}/ctl", .{serial}), "Del\n");
+ try std.testing.expect(has(try c1.read(a, "/recent"), try std.fmt.allocPrint(a, "closed {s}\n", .{shared})));
+ const scratch = try c1.newPane();
+ try c1.write(try std.fmt.allocPrint(a, "/pane/{d}/body", .{scratch}), "kept across a Del\n");
+ try delTwice(c1, try std.fmt.allocPrint(a, "/pane/{d}/ctl", .{scratch}));
+ var rows = std.mem.tokenizeScalar(u8, try c1.read(a, "/index"), '\n');
+ while (rows.next()) |r| try std.testing.expect(!std.mem.startsWith(u8, r, try std.fmt.allocPrint(a, "{d} ", .{scratch})));
+ const back = try c1.look(a, try std.fmt.allocPrint(a, "@p{d}", .{scratch}));
+ try std.testing.expectEqualStrings("kept across a Del\n", try c1.read(a, try std.fmt.allocPrint(a, "/pane/{d}/body", .{back})));
+ // The other window's session closed no such pane.
+ const source = try c2.newPane();
+ c2.write(try std.fmt.allocPrint(a, "/pane/{d}/look", .{source}), try std.fmt.allocPrint(a, "@p{d}\n", .{scratch})) catch {};
+ var others = std.mem.tokenizeScalar(u8, try c2.read(a, "/index"), '\n');
+ while (others.next()) |r| {
+ const body = try c2.read(a, try std.fmt.allocPrint(a, "/pane/{s}/body", .{r[0..std.mem.indexOfScalar(u8, r, ' ').?]}));
+ try std.testing.expect(!has(body, "kept across a Del"));
+ }
+ }
+ try std.testing.expect(storeExists(root));
+}
diff --git a/test/process/root_ctl.zig b/test/process/root_ctl.zig
new file mode 100644
index 00000000..6c32d499
--- /dev/null
+++ b/test/process/root_ctl.zig
@@ -0,0 +1,107 @@
+//! docs/typ/reference.typ, The root ctl <root-ctl>, through a real
+//! session's socket: it exits, keeps its own clock and saves.
+const std = @import("std");
+const libc = std.c;
+const process = @import("../process.zig");
+const eh = @import("../e2e_harness.zig");
+const expect = std.testing.expect;
+const expectEqualStrings = std.testing.expectEqualStrings;
+
+pub const cases = .{
+ .{ "root-ctl: Exit is answered before the editor quits", exitAnswers },
+ .{ "root-ctl: with nothing attached a message leaves after MessageLinger on its own clock", messagesExpire },
+ .{ "root-ctl: Putall with one pane's file changed on disk fails, answered once the other panes' saves have landed", putallAfterSaves },
+ .{ "root-ctl: long and odd paths where a path goes (name, look, DumpDir, Dump, Save) are refused or said, never a crash; a bad ThemeFile fails the write", oddPaths },
+};
+
+fn has(hay: []const u8, needle: []const u8) bool {
+ return std.mem.indexOf(u8, hay, needle) != null;
+}
+
+fn exitAnswers(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var d = try process.Detached.start(gpa, exe, "exit", .{});
+ defer d.deinit();
+ try d.files.write("/ctl", "Exit\n");
+ if (d.exited(5_000) == null) return error.StillRunning;
+}
+
+/// Nothing attached, no key, no click, no other request comes to move it along.
+fn messagesExpire(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var d = try process.Detached.start(gpa, exe, "msg", .{});
+ defer d.deinit();
+ try d.files.write("/pane/1/ctl", "Msg lingering-words\n");
+ try expect(has(try d.files.screen(), "lingering-words"));
+ // Reading /screen is itself a request, so wait without asking.
+ process.sleep(2500);
+ try expect(!has(try d.files.screen(), "lingering-words"));
+}
+
+fn putallAfterSaves(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var d = try process.Detached.start(gpa, exe, "putall", .{});
+ defer d.deinit();
+ const f = &d.files;
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const ar = arena.allocator();
+ const c = try process.Conn.dial(gpa, d.socket());
+ defer c.deinit(gpa);
+ try d.put("a.txt", "a\n");
+ try d.put("b.txt", "b\n");
+ const a = try c.look(ar, f.at("{s}/a.txt", .{d.root()}));
+ const b = try c.look(ar, f.at("{s}/b.txt", .{d.root()}));
+ for ([_]u32{ a, b }) |serial| try c.write(f.at("/pane/{d}/body", .{serial}), "edited\n");
+ try d.put("b.txt", "changed on disk\n");
+ const deadline = eh.nowMs() + 10_000;
+ while (!has(try c.read(ar, "/log"), f.at("changed {d}", .{b}))) {
+ if (eh.nowMs() > deadline) return error.NeverHeard;
+ process.sleep(50);
+ }
+ try std.testing.expectError(error.Refused, c.write("/ctl", "Putall\n"));
+ try expect(has(c.said, "modified on disk"));
+ try expectEqualStrings("a\nedited\n", try d.get(ar, "a.txt"));
+ try expectEqualStrings("changed on disk\n", try d.get(ar, "b.txt"));
+}
+
+/// A part over 255 bytes (ENAMETOOLONG), a loop of links (ELOOP), a file
+/// taken for a directory (ENOTDIR), one not ours (EACCES).
+fn oddPaths(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var d = try process.Detached.start(gpa, exe, "odd", .{});
+ defer d.deinit();
+ const f = &d.files;
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const c = try process.Conn.dial(gpa, d.socket());
+ defer c.deinit(gpa);
+ const root = d.root();
+ const loop = try std.fmt.allocPrintSentinel(a, "{s}/loop", .{root}, 0);
+ try expect(libc.symlink(loop, loop) == 0);
+ try d.put("plain", "x\n");
+ const long: [300]u8 = @splat('x');
+ const odd = [_][]const u8{
+ f.at("/tmp/{s}/f.txt", .{&long}), f.at("{s}/{s}", .{ root, &long }), f.at("{s}/loop/f", .{root}),
+ f.at("{s}/plain/f", .{root}), "/root/nope/f", f.at("{s}/a/../b.txt", .{root}),
+ };
+ const serial = try c.newPane();
+ try c.write(f.at("/pane/{d}/body", .{serial}), "text\n");
+ for (odd) |path| {
+ for ([_][2][]const u8{
+ .{ f.at("/pane/{d}/name", .{serial}), path }, .{ "/look", path }, .{ "/ctl", f.at("DumpDir {s}", .{path}) },
+ .{ "/ctl", "Dump" }, .{ f.at("/pane/{d}/ctl", .{serial}), "Save" },
+ }) |w| {
+ c.write(w[0], f.at("{s}\n", .{w[1]})) catch {};
+ try expect((try c.read(a, "/index")).len > 0);
+ }
+ }
+ try c.write("/ctl", "DumpDir\n");
+ // A theme file that is not there, or no theme, fails the write.
+ try d.put("bad.zon", ".{ .nonsense = 1 }");
+ for ([_][2][]const u8{
+ .{ f.at("ThemeFile {s}/missing.zon\n", .{root}), "theme file" },
+ .{ f.at("ThemeFile {s}/bad.zon\n", .{root}), "theme file" },
+ .{ "ThemeFile notes.txt\n", "a theme file is a .zon" },
+ }) |t| {
+ try std.testing.expectError(error.Refused, c.write("/ctl", t[0]));
+ try expect(has(c.said, t[1]));
+ }
+}
diff --git a/test/process/terminals.zig b/test/process/terminals.zig
new file mode 100644
index 00000000..e84b48e9
--- /dev/null
+++ b/test/process/terminals.zig
@@ -0,0 +1,241 @@
+//! docs/typ/guide.typ, Terminals <terminals>, through a real session's
+//! socket: its shells run.
+const std = @import("std");
+const libc = std.c;
+const process = @import("../process.zig");
+const eh = @import("../e2e_harness.zig");
+const expect = std.testing.expect;
+const expectEqual = std.testing.expectEqual;
+const expectEqualStrings = std.testing.expectEqualStrings;
+
+extern "c" fn system(cmd: [*:0]const u8) c_int;
+
+pub const cases = .{
+ .{ "terminals: pty/run takes a line and answers how it ended, then what it printed, on the same open; busy while a job holds the tty, gone with its shell", runFile },
+ .{ "terminals: a terminal started outside the session's directory is named by it from its new on, and a shell that cannot start leaves no pane", namedOnce },
+};
+
+fn has(hay: []const u8, needle: []const u8) bool {
+ return std.mem.indexOf(u8, hay, needle) != null;
+}
+
+fn refusedSaying(c: *process.Conn, path: []const u8, data: []const u8, why: []const u8) !void {
+ try std.testing.expectError(error.Refused, c.write(path, data));
+ if (!has(c.said, why)) {
+ std.debug.print("{s} refused saying {s}, not {s}\n", .{ path, c.said, why });
+ return error.WrongWords;
+ }
+}
+
+/// A line written to a terminal's pty/run and the answer read on the same open.
+fn run(a: std.mem.Allocator, c: *process.Conn, serial: u32, line: []const u8) ![]const u8 {
+ var buf: [64]u8 = undefined;
+ const fid = try c.hold(try std.fmt.bufPrint(&buf, "/pane/{d}/pty/run", .{serial}), 2);
+ defer c.clunk(fid);
+ _ = try c.writeFid(fid, 0, line);
+ return a.dupe(u8, try c.readFid(fid, 0, 1 << 16));
+}
+
+/// The serials of /index's rows whose fourth word, the path, is `path`.
+fn panesAt(a: std.mem.Allocator, c: *process.Conn, path: []const u8) ![]const []const u8 {
+ var out: std.ArrayList([]const u8) = .empty;
+ var rows = std.mem.tokenizeScalar(u8, try c.read(a, "/index"), '\n');
+ while (rows.next()) |row| {
+ var w = std.mem.tokenizeScalar(u8, row, ' ');
+ const serial = w.next().?;
+ _ = w.next();
+ _ = w.next();
+ if (std.mem.eql(u8, w.next() orelse "", path)) try out.append(a, serial);
+ }
+ return out.items;
+}
+
+/// The serials /index lists.
+fn serials(a: std.mem.Allocator, c: *process.Conn) ![]const u32 {
+ var out: std.ArrayList(u32) = .empty;
+ var rows = std.mem.tokenizeScalar(u8, try c.read(a, "/index"), '\n');
+ while (rows.next()) |row| try out.append(a, try std.fmt.parseInt(u32, row[0..std.mem.indexOfScalar(u8, row, ' ').?], 10));
+ return out.items;
+}
+
+fn shell(a: std.mem.Allocator, comptime fmt: []const u8, args: anytype) c_int {
+ return system(std.fmt.allocPrintSentinel(a, fmt, args, 0) catch @panic("out of memory"));
+}
+
+/// A run on another connection, as another client's, in a thread.
+const Other = struct {
+ a: std.mem.Allocator,
+ conn: *process.Conn,
+ serial: u32,
+ line: []const u8,
+ got: []const u8 = "",
+
+ fn go(o: *Other) void {
+ o.got = run(o.a, o.conn, o.serial, o.line) catch "";
+ }
+};
+
+fn runFile(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var d = try process.Detached.start(gpa, exe, "run", .{});
+ defer d.deinit();
+ const f = &d.files;
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const c = try process.Conn.dial(gpa, d.socket());
+ defer c.deinit(gpa);
+ const root = d.root();
+ // From a pane on a peer's path no command or terminal starts: refused
+ // before any pane is made, no `exit 127` pane left.
+ const peer = try c.newPane();
+ try c.write(f.at("/pane/{d}/name", .{peer}), "/n/nosuchpeer/d/f.txt\n");
+ const count = std.mem.count(u8, try c.read(a, "/index"), "\n");
+ try refusedSaying(c, f.at("/pane/{d}/exec", .{peer}), "ls\n", "no such directory");
+ try refusedSaying(c, f.at("/pane/{d}/exec", .{peer}), "Tty\n", "no such directory");
+ try expectEqual(count, std.mem.count(u8, try c.read(a, "/index"), "\n"));
+ try expect(!has(try c.read(a, "/log"), "exit 127"));
+ try c.remove(f.at("/pane/{d}", .{peer}));
+ try c.write("/exec", "Shell bash\n");
+ try c.write("/exec", "Tty\n");
+ var term: u32 = 0;
+ var rows = std.mem.tokenizeScalar(u8, try c.read(a, "/index"), '\n');
+ while (rows.next()) |r| {
+ var w = std.mem.tokenizeScalar(u8, r, ' ');
+ const serial = try std.fmt.parseInt(u32, w.next().?, 10);
+ if (std.mem.eql(u8, w.next().?, "term")) term = @max(term, serial);
+ }
+ const deadline = eh.nowMs() + 10_000;
+ while (std.mem.eql(u8, try run(a, c, term, "true\n"), "busy\n")) { // until its first prompt
+ if (eh.nowMs() > deadline) return error.NoPrompt;
+ process.sleep(50);
+ }
+ try expectEqualStrings("exit 1\n", try run(a, c, term, "false\n"));
+ try expectEqualStrings("exit 0\none\ntwo\n", try run(a, c, term, "printf \"one\\ntwo\\n\"\n")); // then what it printed
+ try expectEqualStrings("exit 7\n", try run(a, c, term, "sh -c \"exit 7\"\n"));
+ try expectEqualStrings("error not run\n", try run(a, c, term, "fi\n")); // a syntax error runs nothing
+ try expectEqualStrings("error not run\n", try run(a, c, term, "echo 'open\n")); // nor does an open quote
+ try expectEqualStrings("exit 0\n", try run(a, c, term, "true\n")); // ...and the shell is clear after
+ // With no frontend attached the pty's size is in pixels too, at a
+ // nominal 8x16 cell: a program sizes its kitty graphics by it.
+ const said = try run(a, c, term, "python3 -c 'import fcntl,termios,struct;print(*struct.unpack(\"4H\",fcntl.ioctl(0,termios.TIOCGWINSZ,bytes(8))))'\n");
+ var lines = std.mem.splitScalar(u8, said, '\n');
+ _ = lines.next();
+ var size = std.mem.tokenizeScalar(u8, lines.next() orelse "", ' ');
+ var n: [4]u32 = undefined;
+ for (&n) |*v| v.* = try std.fmt.parseInt(u32, size.next() orelse return error.NoSize, 10);
+ try expect(n[2] == n[1] * 8 and n[3] == n[0] * 16 and n[2] > 0);
+ // A paging command run through pty/run does not wait in less: the
+ // terminal's PAGER is `pardes -`, and its text is a +Pager pane.
+ if (shell(a, "command -v git >/dev/null", .{}) == 0) {
+ const git = f.at("HOME='{s}' git -C '{s}/pagedrepo' -c user.name=p -c user.email=p@x", .{ root, root });
+ try expectEqual(@as(c_int, 0), shell(a, "mkdir '{s}/pagedrepo' && {s} init -q && echo x > '{s}/pagedrepo/f' && {s} add f && {s} commit -qm paged-commit-subject", .{ root, git, root, git, git }));
+ try expect(std.mem.startsWith(u8, try run(a, c, term, "git -C pagedrepo log\n"), "exit 0\n"));
+ const pager = try panesAt(a, c, f.at("{s}/pagedrepo/+Pager", .{root})); // git -C runs it in the repo
+ try expectEqual(@as(usize, 1), pager.len);
+ const body = try c.read(a, f.at("/pane/{s}/body", .{pager[0]}));
+ try expect(has(body, "paged-commit-subject") and !has(body, "\x1b"));
+ try c.remove(f.at("/pane/{s}", .{pager[0]}));
+ }
+ // systemd's tools page through their own variable: set too, its secure
+ // mode off, the path unquoted where it needs none. Read by the shell:
+ // coreutils 9.12's printenv quotes a value with a blank on a terminal.
+ const systemd = try run(a, c, term, "printf \"%s\\n\" \"$SYSTEMD_PAGER\" \"$SYSTEMD_PAGERSECURE\"\n");
+ try expect(std.mem.startsWith(u8, systemd, "exit 0\n") and std.mem.endsWith(u8, std.mem.trimEnd(u8, systemd, " \n"), " -\n0"));
+ if (shell(a, "command -v journalctl >/dev/null", .{}) == 0) {
+ try expect(std.mem.startsWith(u8, try run(a, c, term, "journalctl -n 3 --no-hostname\n"), "exit "));
+ for (try panesAt(a, c, f.at("{s}/+Pager", .{root}))) |p| try c.remove(f.at("/pane/{s}", .{p}));
+ }
+ // A pty is not given one row (it loses the prompt's input mark, and the
+ // shell would read busy for ever): refused, and said.
+ const ptyctl = f.at("/pane/{d}/pty/ctl", .{term});
+ try refusedSaying(c, ptyctl, "winsize 20 1\n", "at least 2 rows");
+ try c.write(ptyctl, "winsize 20 2\n");
+ process.sleep(500);
+ try expectEqualStrings("exit 0\n", try run(a, c, term, "true\n"));
+ var words = std.mem.tokenizeAny(u8, try c.read(a, ptyctl), " \n");
+ _ = words.next();
+ _ = words.next();
+ try expectEqualStrings("2", words.next().?);
+ try c.write(ptyctl, "winsize 80 24\n");
+ // A shell started again that cannot start (its directory is there but
+ // cannot be entered) fails the write and leaves the running shell be:
+ // runs still work.
+ const locked = try std.fmt.allocPrintSentinel(a, "{s}/locked", .{root}, 0);
+ try expectEqual(@as(c_int, 0), libc.mkdir(locked, 0o755));
+ try expectEqualStrings("exit 0\n", try run(a, c, term, f.at("cd {s}\n", .{locked})));
+ const until = eh.nowMs() + 5_000;
+ while (!has(try c.read(a, "/index"), locked)) {
+ if (eh.nowMs() > until) return error.NeverMoved;
+ process.sleep(50);
+ }
+ _ = libc.chmod(locked, 0o600);
+ const refused = if (libc.geteuid() != 0) refusedSaying(c, ptyctl, "exec\n", "shell") else {}; // root enters any directory
+ _ = libc.chmod(locked, 0o755);
+ try refused;
+ try expectEqualStrings("exit 0\n", try run(a, c, term, "true\n"));
+ try expectEqualStrings("exit 0\n", try run(a, c, term, f.at("cd {s}\n", .{root})));
+ const other = try process.Conn.dial(gpa, d.socket());
+ defer other.deinit(gpa);
+ const tv: libc.timeval = .{ .sec = 10, .usec = 0 };
+ _ = libc.setsockopt(other.fd, libc.SOL.SOCKET, libc.SO.RCVTIMEO, &tv, @sizeOf(libc.timeval));
+ var slow: Other = .{ .a = a, .conn = other, .serial = term, .line = "sleep 1\n" };
+ var waiter = try std.Thread.spawn(.{}, Other.go, .{&slow});
+ process.sleep(300);
+ // The job the other client ran holds the tty, and says so.
+ const busy = run(a, c, term, "true\n");
+ waiter.join();
+ try expectEqualStrings("busy: sleep is running\n", try busy);
+ try expectEqualStrings("exit 0\n", slow.got);
+ var closing: Other = .{ .a = a, .conn = other, .serial = term, .line = "sleep 30\n" };
+ waiter = try std.Thread.spawn(.{}, Other.go, .{&closing});
+ process.sleep(300);
+ const del = c.write(f.at("/pane/{d}/exec", .{term}), "Del\n");
+ waiter.join();
+ try del;
+ try expectEqualStrings("error shell gone\n", closing.got);
+}
+
+fn namedOnce(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var d = try process.Detached.start(gpa, exe, "names", .{});
+ defer d.deinit();
+ const f = &d.files;
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const c = try process.Conn.dial(gpa, d.socket());
+ defer c.deinit(gpa);
+ const root = d.root();
+ try expectEqual(@as(c_int, 0), libc.mkdir(try std.fmt.allocPrintSentinel(a, "{s}/sub", .{root}, 0), 0o755));
+ // A look at a directory starts a terminal there (DirLook terminal);
+ // DirLook pane, the default, lists it in a pane.
+ try c.write("/ctl", "DirLook terminal\n");
+ var made: std.ArrayList(u32) = .empty;
+ try made.append(a, try c.look(a, f.at("{s}/sub", .{root})));
+ const before = try serials(a, c);
+ try c.write("/pane/1/ctl", "Tty\n");
+ if (shell(a, "command -v fish >/dev/null", .{}) == 0) try c.write("/pane/1/ctl", "Tty fish\n");
+ for (try serials(a, c)) |s| if (std.mem.indexOfScalar(u32, before, s) == null) try made.append(a, s);
+ try expect(made.items.len >= 2);
+ process.sleep(1500); // their shells start and say where they are
+ // A shell started again by pty/ctl exec: named as it was.
+ try c.write(f.at("/pane/{d}/pty/ctl", .{made.items[0]}), "exec\n");
+ process.sleep(1500);
+ const log = f.at("\n{s}", .{try c.read(a, "/log")});
+ for (made.items) |s| {
+ try expect(!has(log, f.at("\nrename {d} ", .{s})));
+ try expect(has(log, f.at("\nnew {d} {s}", .{ s, root })));
+ }
+ // A shell that cannot start (its interpreter is not there): Tty fails
+ // the write with why and leaves no pane; pty/ctl exec fails with why
+ // and keeps its terminal.
+ try d.put("badsh", "#!/nonexistent/interp\n");
+ const bad = f.at("{s}/badsh", .{root});
+ _ = libc.chmod(try std.fmt.allocPrintSentinel(a, "{s}", .{bad}, 0), 0o755);
+ const panes = std.mem.count(u8, try c.read(a, "/index"), "\n");
+ try refusedSaying(c, "/pane/1/ctl", f.at("Tty {s}\n", .{bad}), "interpreter /nonexistent/interp not found");
+ try refusedSaying(c, "/ctl", f.at("Shell {s}\n", .{bad}), "interpreter /nonexistent/interp not found");
+ process.sleep(300);
+ try expectEqual(panes, std.mem.count(u8, try c.read(a, "/index"), "\n"));
+ try expect(!has(try c.read(a, "/log"), "shell: shell not found"));
+ try expect(std.mem.indexOfScalar(u32, try serials(a, c), made.items[0]) != null);
+}
diff --git a/test/process/tree.zig b/test/process/tree.zig
new file mode 100644
index 00000000..4d1b2915
--- /dev/null
+++ b/test/process/tree.zig
@@ -0,0 +1,484 @@
+//! docs/typ/reference.typ, The tree <tree>, through a real session's socket.
+const std = @import("std");
+const libc = std.c;
+const process = @import("../process.zig");
+const c9 = @import("cloud9");
+const eh = @import("../e2e_harness.zig");
+const expect = std.testing.expect;
+const expectEqual = std.testing.expectEqual;
+const expectEqualStrings = std.testing.expectEqualStrings;
+
+pub const cases = .{
+ .{ "tree: listing, stat and find are inert; new, remove, look, exec, name, sel, log, ctl lock, focus, the ctl split, commands, Save and the slots behave", discovery },
+ .{ "tree: a write bigger than a 9P message runs each line once, whole, an Edit block once it ends; a detached session is 160x50 until told", cutWrites },
+};
+
+fn has(hay: []const u8, needle: []const u8) bool {
+ return std.mem.indexOf(u8, hay, needle) != null;
+}
+
+fn contains(names: []const []const u8, name: []const u8) bool {
+ for (names) |n| if (std.mem.eql(u8, n, name)) return true;
+ return false;
+}
+
+/// A write refused, its words holding `why`.
+fn refusedSaying(c: *process.Conn, path: []const u8, data: []const u8, why: []const u8) !void {
+ try std.testing.expectError(error.Refused, c.write(path, data));
+ if (!has(c.said, why)) {
+ std.debug.print("{s} refused saying {s}, not {s}\n", .{ path, c.said, why });
+ return error.WrongWords;
+ }
+}
+
+/// A read on `c` given up after `sec` seconds, so a wait that never ends fails.
+fn timeout(c: *process.Conn, sec: i64) void {
+ const tv: libc.timeval = .{ .sec = sec, .usec = 0 };
+ _ = libc.setsockopt(c.fd, libc.SOL.SOCKET, libc.SO.RCVTIMEO, &tv, @sizeOf(libc.timeval));
+}
+
+/// /index's row for `serial`.
+fn indexRow(index: []const u8, serial: u32) ![]const u8 {
+ var rows = std.mem.tokenizeScalar(u8, index, '\n');
+ while (rows.next()) |row| {
+ const sp = std.mem.indexOfScalar(u8, row, ' ') orelse continue;
+ if ((std.fmt.parseInt(u32, row[0..sp], 10) catch continue) == serial) return row;
+ }
+ return error.NoRow;
+}
+
+/// The serials of /index's rows whose fourth word, the path, is `path`.
+fn panesAt(a: std.mem.Allocator, c: *process.Conn, path: []const u8) ![]const []const u8 {
+ var out: std.ArrayList([]const u8) = .empty;
+ var rows = std.mem.tokenizeScalar(u8, try c.read(a, "/index"), '\n');
+ while (rows.next()) |row| {
+ var w = std.mem.tokenizeScalar(u8, row, ' ');
+ const serial = w.next().?;
+ _ = w.next();
+ _ = w.next();
+ if (std.mem.eql(u8, w.next() orelse "", path)) try out.append(a, serial);
+ }
+ return out.items;
+}
+
+const Seen = struct { path: []const u8, mode: u32, mtime: u32 };
+
+/// Every entry below `path` stated, as `find` does, without opening one.
+fn walkTree(a: std.mem.Allocator, c: *process.Conn, path: []const u8, seen: *std.ArrayList(Seen)) !void {
+ for (try c.list(a, path)) |name| {
+ const child = try std.fmt.allocPrint(a, "{s}/{s}", .{ std.mem.trimEnd(u8, path, "/"), name });
+ const st = try c.stat(child);
+ try seen.append(a, .{ .path = child, .mode = st.mode, .mtime = st.mtime });
+ if (st.mode & c9.dmdir != 0 and !contains(&.{ "/log", "/os", "/screen" }, child)) try walkTree(a, c, child, seen);
+ }
+}
+
+/// A follower's read on a held /log, which waits for a new record.
+const Follower = struct {
+ conn: *process.Conn,
+ fid: u32,
+ off: u64,
+ buf: [256]u8 = undefined,
+ len: usize = 0,
+
+ fn run(w: *Follower) void {
+ const got = w.conn.readFid(w.fid, w.off, 4096) catch return;
+ w.len = @min(got.len, w.buf.len);
+ @memcpy(w.buf[0..w.len], got[0..w.len]);
+ }
+};
+
+fn discovery(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var d = try process.Detached.start(gpa, exe, "discovery", .{});
+ defer d.deinit();
+ const f = &d.files;
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const c = try process.Conn.dial(gpa, d.socket());
+ defer c.deinit(gpa);
+ const root = d.root();
+
+ const top = try c.list(a, "/");
+ // A set: which files the root holds, not the order a listing gives.
+ const want = [_][]const u8{ "README", "index", "status", "focus", "ctl", "commands", "recent", "look", "exec", "pager", "log", "screen", "listeners", "sessions", "layout", "tag", "tagexec", "kbdin", "mousein", "pane", "col", "os" };
+ var others: usize = 0;
+ for (top) |n| {
+ if (contains(&.{ "src", "shaders" }, n)) continue;
+ others += 1;
+ try expect(contains(&want, n));
+ }
+ try expectEqual(want.len, others);
+ for (want) |n| try expect(contains(top, n));
+ const embedded = contains(top, "src");
+ const before = try c.read(a, "/index");
+ const guide = try c.read(a, "/README");
+ try expect(std.mem.count(u8, guide, "\n") <= 45 and has(guide, "Msg hello") and has(guide, "pane/new"));
+ try expectEqual(guide.len, (try c.stat("/README")).length);
+ // ls/stat/find over the whole tree, without opening, creates nothing.
+ var seen: std.ArrayList(Seen) = .empty;
+ try walkTree(a, c, "/", &seen);
+ var names: std.ArrayList([]const u8) = .empty;
+ for (seen.items) |s| try names.append(a, s.path);
+ for ([_][]const u8{ "/index", "/status", "/look", "/exec", "/log", "/pane/1", "/pane/1/body", "/pane/1/name", "/pane/1/sel", "/pane/1/ctl", "/pane/1/tag", "/pane/1/event", "/pane/1/dot", "/pane/1/limit", "/pane/1/dirty", "/pane/1/mark", "/pane/1/scroll", "/pane/1/look", "/pane/1/exec" }) |n| try expect(contains(names.items, n));
+ try expect(!contains(names.items, "/pane/1/pty")); // the fixture file pane grew no pty/
+ for (seen.items) |s| {
+ try expect(!std.mem.startsWith(u8, s.path, "/self") and !std.mem.endsWith(u8, s.path, "/rdsel") and !std.mem.endsWith(u8, s.path, "/wrsel"));
+ const mode = s.mode & 0o777;
+ try expect(mode == 0o755 or mode == 0o644 or mode == 0o666 or mode == 0o444 or mode == 0o222 or mode == 0o555);
+ try expect(s.mtime > 0);
+ }
+ try expectEqualStrings(before, try c.read(a, "/index")); // browsing created no pane
+ try expect(before.len > 0);
+ try expectEqual(@as(u64, 0), (try c.stat("/index")).length); // a view made by each read stats 0 (reference.typ, Stats)
+ try expectEqual(@as(u32, 0o444), (try c.stat("/index")).mode & 0o777);
+ try expectEqual(@as(u32, 0o444), (try c.stat("/status")).mode & 0o777);
+ try expectEqual(@as(u32, 0o666), (try c.stat("/exec")).mode & 0o777);
+ try expectEqual(@as(u32, 0o666), (try c.stat("/pane/1/body")).mode & 0o777);
+ try expectEqual(@as(u32, 0o755), (try c.stat("/pane")).mode & 0o777);
+ // A range file reads the pair it takes; a flag file reads 0 or 1.
+ try expectEqual(@as(u64, 24), (try c.stat("/pane/1/addr")).length);
+ try expectEqual(@as(u64, 0), (try c.stat("/pane/1/limit")).length);
+ try expectEqualStrings("0\n", try c.read(a, "/pane/1/dirty"));
+ try expectEqualStrings("1\n", try c.read(a, "/pane/1/scroll"));
+ const fixture = try std.fmt.parseInt(u32, before[0..std.mem.indexOfScalar(u8, before, ' ').?], 10);
+ try expect(std.mem.startsWith(u8, before, f.at("{d} text 0 ", .{fixture})));
+ try expect(std.mem.endsWith(u8, before[0..std.mem.lastIndexOfScalar(u8, std.mem.trimEnd(u8, before, "\n"), ' ').?], "/discovery.txt"));
+ // /status reports the editor; /exec has nothing to report yet.
+ var pid: i64 = 0;
+ var version = false;
+ var panes: i64 = 0;
+ var lines = std.mem.tokenizeScalar(u8, try c.read(a, "/status"), '\n');
+ while (lines.next()) |line| {
+ const sp = std.mem.indexOfScalar(u8, line, ' ') orelse continue;
+ const key, const value = .{ line[0..sp], std.mem.trim(u8, line[sp..], " ") };
+ if (std.mem.eql(u8, key, "pid")) pid = try std.fmt.parseInt(i64, value, 10);
+ if (std.mem.eql(u8, key, "version")) version = value.len > 0;
+ if (std.mem.eql(u8, key, "panes")) panes = try std.fmt.parseInt(i64, value, 10);
+ }
+ try expect(pid > 0 and version and panes >= 1);
+ try expectEqualStrings("", try c.read(a, "/exec"));
+ // An open of /pane/new makes a pane and the read names it; each open
+ // makes another. A stat makes none, which is why new can be listed at
+ // all: ls -l stats every name a listing gave it. /log answers the
+ // recent past and ends; `follow` written to the same open makes its
+ // reads past that wait for new records.
+ const log = try c.hold("/log", 2);
+ const frozen = (try c.readFid(log, 0, 1 << 16)).len;
+ _ = try c.writeFid(log, 0, "follow\n");
+ const first = try c.newPane();
+ try expectEqual(first, try c.newest(a));
+ const second = try c.newPane();
+ try expect(first != second and first != fixture);
+ try expect(contains(try c.list(a, "/pane"), "new"));
+ _ = try c.stat("/pane/new");
+ try expectEqual(second, try c.newest(a)); // a stat of new made no pane
+ // What the editor said is in the stream too.
+ const paneEvent = struct {
+ fn next(conn: *process.Conn, al: std.mem.Allocator, fid: u32, off: u64) ![]const u8 {
+ while (true) {
+ const record = try conn.readFid(fid, off, 1 << 16);
+ if (!std.mem.startsWith(u8, record, "msg ") and !std.mem.startsWith(u8, record, "err ")) return al.dupe(u8, record);
+ }
+ }
+ }.next;
+ try expectEqualStrings(f.at("new {d} {s}/+New\n", .{ first, root }), try paneEvent(c, a, log, frozen));
+ try expectEqualStrings(f.at("new {d} {s}/+New\n", .{ second, root }), try paneEvent(c, a, log, frozen));
+ // A follower that is waiting wakes when the editor logs, not when some
+ // unrelated request next happens to wait.
+ {
+ const follower = try process.Conn.dial(gpa, d.socket());
+ defer follower.deinit(gpa);
+ timeout(follower, 5);
+ const waiting = try follower.hold("/log", 2);
+ const start = (try follower.readFid(waiting, 0, 1 << 16)).len;
+ _ = try follower.writeFid(waiting, 0, "follow\n");
+ var w: Follower = .{ .conn = follower, .fid = waiting, .off = start };
+ const reader = try std.Thread.spawn(.{}, Follower.run, .{&w});
+ process.sleep(200);
+ try c.write("/exec", "Msg woken\n");
+ reader.join();
+ try expect(std.mem.endsWith(u8, w.buf[0..w.len], " woken\n"));
+ }
+ // A pane's ctl takes acme's lock: a second open's lock fails at once
+ // with "file in use" until the holder unlocks, and nothing else waits
+ // on it meanwhile.
+ {
+ const other = try process.Conn.dial(gpa, d.socket());
+ defer other.deinit(gpa);
+ const ctl = f.at("/pane/{d}/ctl", .{first});
+ const mine = try c.hold(ctl, 2);
+ _ = try c.writeFid(mine, 0, "lock\n");
+ const theirs = try other.hold(ctl, 1);
+ try std.testing.expectError(error.Refused, other.writeFid(theirs, 0, "lock\n"));
+ try expect(has(other.said, "file in use"));
+ try c.write(f.at("/pane/{d}/addr", .{first}), "#0");
+ _ = try c.writeFid(mine, 0, "unlock\n");
+ _ = try other.writeFid(theirs, 0, "lock\n");
+ c.clunk(mine);
+ other.clunk(theirs);
+ }
+ // /focus names the pane with the keyboard and moves it, as rio's wctl
+ // `current` does; a pane's ctl line ends saying which it is.
+ try c.write("/focus", f.at("{d}\n", .{first}));
+ try expectEqualStrings(f.at("{d}\n", .{first}), try c.read(a, "/focus"));
+ try expect(has(try c.read(a, f.at("/pane/{d}/ctl", .{first})), " current "));
+ try expect(has(try c.read(a, f.at("/pane/{d}/ctl", .{second})), " notcurrent "));
+ try refusedSaying(c, "/focus", "99999\n", "no such pane");
+ // /ctl reads the settings as a write takes them and takes the session's
+ // builtins; a pane's ctl takes the pane's.
+ const settings = try c.read(a, "/ctl");
+ try expect(has(settings, "Verbose ") and !has(settings, "Platform"));
+ try c.write("/ctl", settings);
+ try expectEqualStrings(settings, try c.read(a, "/ctl"));
+ try c.write("/ctl", "Verbose off\n");
+ try expect(has(try c.read(a, "/ctl"), "Verbose off\n"));
+ try refusedSaying(c, "/ctl", "Del\n", "not a session control message \"Del\"");
+ try refusedSaying(c, "/ctl", "Nope 3\n", "unknown control message \"Nope\"");
+ try refusedSaying(c, f.at("/pane/{d}/ctl", .{first}), "Newcol\n", "not a window control message \"Newcol\"");
+ const commands = try c.read(a, "/commands");
+ const row = struct {
+ fn row(text: []const u8, start: []const u8) bool {
+ var rows = std.mem.tokenizeScalar(u8, text, '\n');
+ while (rows.next()) |r| if (std.mem.eql(u8, r, start) or (std.mem.startsWith(u8, r, start) and r.len > start.len and r[start.len] == ' ')) return true;
+ return false;
+ }
+ }.row;
+ try expect(row(commands, "Newcol root") and row(commands, "Save arg pane") and row(commands, "Edit arg both"));
+ // word, `arg` if it takes one, its ctl, a setting's values, then `-- ` what it does
+ var crows = std.mem.tokenizeScalar(u8, commands, '\n');
+ while (crows.next()) |r| {
+ var w = std.mem.tokenizeScalar(u8, r, ' ');
+ _ = w.next();
+ var which = w.next().?;
+ if (std.mem.eql(u8, which, "arg")) which = w.next().?;
+ try expect(contains(&.{ "root", "pane", "both" }, which));
+ }
+ try expect(row(commands, "Placement arg root acme,pardes"));
+ try expect(std.mem.endsWith(u8, commands, "\n"));
+ try expectEqual(commands.len, (try c.stat("/commands")).length);
+ try c.write(f.at("/pane/{d}/ctl", .{first}), "Msg said through ctl\n");
+ try expect(has(try f.screen(), "said through ctl"));
+ const listed = try c.list(a, "/pane");
+ try expectEqual(@as(usize, 4), listed.len);
+ for ([_]u32{ fixture, first, second }) |n| try expect(contains(listed, f.at("{d}", .{n})));
+ try expect(contains(listed, "new"));
+ try c.replace(f.at("/pane/{d}/body", .{first}), "first pane");
+ try expectEqualStrings("first pane", try c.read(a, f.at("/pane/{d}/body", .{first})));
+ try expectEqualStrings("", try c.read(a, f.at("/pane/{d}/body", .{second})));
+ try expectEqual(@as(u64, "first pane".len), (try c.stat(f.at("/pane/{d}/body", .{first}))).length);
+ const index = try c.read(a, "/index");
+ try expect(std.mem.startsWith(u8, try indexRow(index, first), f.at("{d} text 1 ", .{first})));
+ try expect(std.mem.startsWith(u8, try indexRow(index, second), f.at("{d} text 0 ", .{second})));
+ // name: read the file name, write to rename; sel: the selection.
+ const name = f.at("/pane/{d}/name", .{first});
+ try expectEqualStrings(f.at("{s}/+New\n", .{root}), try c.read(a, name));
+ try c.write(name, "notes.txt\n");
+ try expectEqualStrings(f.at("{s}/notes.txt\n", .{root}), try c.read(a, name));
+ try expectEqualStrings(f.at("rename {d} {s}/notes.txt\n", .{ first, root }), try paneEvent(c, a, log, frozen));
+ try expectEqual(@as(u64, f.at("{s}/notes.txt\n", .{root}).len), (try c.stat(name)).length);
+ // Copying addr onto dot selects that range; sel reads and replaces it.
+ const addr = f.at("/pane/{d}/addr", .{first});
+ const dot = f.at("/pane/{d}/dot", .{first});
+ const sel = f.at("/pane/{d}/sel", .{first});
+ try c.write(addr, "#0,#5");
+ try c.write(dot, try c.read(a, addr));
+ try expectEqualStrings(try c.read(a, addr), try c.read(a, dot));
+ try expectEqualStrings("first", try c.read(a, sel));
+ try expectEqual(@as(u64, 5), (try c.stat(sel)).length);
+ try c.write(sel, "FIRST");
+ try expectEqualStrings("FIRST pane", try c.read(a, f.at("/pane/{d}/body", .{first})));
+ try expectEqualStrings("FIRST", try c.read(a, sel)); // what a write to sel put there is selected
+ // exec Msg shows text; exec Save writes the named file; rmdir closes.
+ try c.write(f.at("/pane/{d}/exec", .{first}), "Msg hello from 9P\n");
+ try expect(has(try f.screen(), "hello from 9P"));
+ try expectEqualStrings("1\n", try c.read(a, f.at("/pane/{d}/dirty", .{first})));
+ try c.write(f.at("/pane/{d}/exec", .{first}), "Save\n");
+ try expectEqualStrings("FIRST pane", try d.get(a, "notes.txt"));
+ try expectEqualStrings(f.at("save {d} {s}/notes.txt\n", .{ first, root }), try paneEvent(c, a, log, frozen));
+ try expectEqualStrings(f.at("{d}\n", .{first}), try c.read(a, "/exec"));
+ try expectEqualStrings("0\n", try c.read(a, f.at("/pane/{d}/dirty", .{first})));
+ try c.remove(f.at("/pane/{d}", .{second}));
+ try expectEqualStrings(f.at("del {d} {s}/+New\n", .{ second, root }), try paneEvent(c, a, log, frozen));
+ try expect(!contains(try c.list(a, "/pane"), f.at("{d}", .{second})));
+ // look opens a file; the serial reads back.
+ try d.put("opened.txt", "one\ntwo\nthree\n");
+ try c.write("/look", f.at("{s}/opened.txt:2\n", .{root}));
+ const opened = try std.fmt.parseInt(u32, std.mem.trim(u8, try c.read(a, "/look"), "\n"), 10);
+ try expect(opened != fixture and opened != first and opened != second);
+ try expectEqualStrings("one\ntwo\nthree\n", try c.read(a, f.at("/pane/{d}/body", .{opened})));
+ try expectEqualStrings(f.at("{s}/opened.txt\n", .{root}), try c.read(a, f.at("/pane/{d}/name", .{opened})));
+ try expectEqualStrings(f.at("new {d} {s}/opened.txt\n", .{ opened, root }), try paneEvent(c, a, log, frozen));
+ try c.write(f.at("/pane/{d}/look", .{first}), f.at("{s}/opened.txt:3\n", .{root}));
+ try expectEqualStrings(f.at("{d}\n", .{opened}), try c.read(a, "/look")); // a repeated look targets the open pane
+ for ([_]u32{ fixture, first, opened }) |n| try expect(contains(try c.list(a, "/pane"), f.at("{d}", .{n})));
+ // Writing an event record back still performs the action it names.
+ try c.replace(f.at("/pane/{d}/body", .{first}), "Msg via event");
+ try c.write(f.at("/pane/{d}/event", .{first}), "FX0 13\n");
+ try expect(has(try f.screen(), "via event"));
+ // A command line may not carry control characters, and nothing else in
+ // the tree may be created or removed.
+ if (c.write("/exec", "Msg a\x00b")) |_| return error.Taken else |_| {}
+ if (c.write("/status", "anything\n")) |_| return error.Taken else |_| {}
+ if (c.create("/", "x", c9.dmdir | 0o755)) |_| return error.Taken else |_| {}
+ if (c.create("/pane", "one", c9.dmdir | 0o755)) |_| return error.Taken else |_| {}
+ if (c.create("/pane", "plain-file", 0o644)) |_| return error.Taken else |_| {}
+ if (c.remove("/pane/1/body")) |_| return error.Taken else |_| {}
+ if (c.remove("/index")) |_| return error.Taken else |_| {}
+ c.clunk(log);
+ if (embedded) {
+ try expect(std.mem.startsWith(u8, try c.read(a, "/src/pardes.zig"), "const std"));
+ try expectEqual(@as(u32, 0o444), (try c.stat("/src/pardes.zig")).mode & 0o777);
+ try expect(has(try c.read(a, f.at("/pane/{d}/body", .{try c.look(a, "/virtual/src/pardes.zig")})), "pub const Pardes"));
+ }
+ // An open of data with OTRUNC (a shell's >) deletes the addressed range
+ // only, so the write after it replaces that range.
+ const scratch = try c.newPane();
+ try c.write(f.at("/pane/{d}/body", .{scratch}), "hello world\nsecond line\n");
+ try c.write(f.at("/pane/{d}/addr", .{scratch}), "#0,#5");
+ try c.replace(f.at("/pane/{d}/data", .{scratch}), "HOWDY");
+ try expectEqualStrings("HOWDY world\nsecond line\n", try c.read(a, f.at("/pane/{d}/body", .{scratch})));
+ // sam's regexps: ^ at any line; a miss says so and leaves no address,
+ // so the data write after it refuses.
+ try c.write(f.at("/pane/{d}/addr", .{scratch}), "/^second/");
+ try expectEqualStrings(" 12 18 ", try c.read(a, f.at("/pane/{d}/addr", .{scratch})));
+ try refusedSaying(c, f.at("/pane/{d}/addr", .{scratch}), "/nowhere/", "no match for regexp");
+ try refusedSaying(c, f.at("/pane/{d}/data", .{scratch}), "LOST", "no address");
+ try expectEqualStrings("HOWDY world\nsecond line\n", try c.read(a, f.at("/pane/{d}/body", .{scratch})));
+ // Through a mount both read as EINVAL; the log says which and why.
+ try expect(has(try c.read(a, "/log"), f.at("err {d} addr: no match for regexp\n", .{scratch})));
+ try c.remove(f.at("/pane/{d}", .{scratch}));
+ // Real `diff -u` in a command pane: the terminal turns the tab before
+ // each timestamp into blanks, and a look at a changed line still opens
+ // the new file at it.
+ try d.put("diff-old.txt", "one\ntwo\nthree\n");
+ try d.put("diff-new.txt", "one\nTWO\nthree\n");
+ const exits = std.mem.count(u8, try c.read(a, "/log"), "\nexit ");
+ try c.write("/exec", "diff -u diff-old.txt diff-new.txt\n");
+ const deadline = eh.nowMs() + 10_000;
+ while (std.mem.count(u8, try c.read(a, "/log"), "\nexit ") <= exits) {
+ if (eh.nowMs() > deadline) return error.DiffNeverEnded;
+ process.sleep(50);
+ }
+ // A command's pane is kind cmd, not term: no shell to type into.
+ var ran: u32 = 0;
+ var irows = std.mem.tokenizeScalar(u8, try c.read(a, "/index"), '\n');
+ while (irows.next()) |r| {
+ var w = std.mem.tokenizeScalar(u8, r, ' ');
+ const serial = w.next().?;
+ if (std.mem.eql(u8, w.next() orelse "", "cmd")) ran = try std.fmt.parseInt(u32, serial, 10);
+ }
+ const shown = try c.read(a, f.at("/pane/{d}/body", .{ran}));
+ try expect(has(shown, "+++ diff-new.txt") and !has(shown, "\t"));
+ try c.write(f.at("/pane/{d}/look", .{ran}), "+TWO\n");
+ const diffed = try panesAt(a, c, f.at("{s}/diff-new.txt", .{root}));
+ try expectEqual(@as(usize, 1), diffed.len);
+ try c.remove(f.at("/pane/{s}", .{diffed[0]}));
+ try c.remove(f.at("/pane/{d}", .{ran}));
+ // A Save makes the directories its file goes in, whatever names it: the
+ // pane's own name or Save's path. `~` is home (this session's HOME, the
+ // test's root) wherever a path is typed: Save, name, a look, with an
+ // address or not.
+ const tilde = try c.newPane();
+ try c.write(f.at("/pane/{d}/body", .{tilde}), "one\ntwo\nthree\n");
+ try c.write(f.at("/pane/{d}/ctl", .{tilde}), "Save ~/tilde-made/sub/x.txt\n");
+ try expectEqualStrings("one\ntwo\nthree\n", try d.get(a, "tilde-made/sub/x.txt"));
+ try c.write(f.at("/pane/{d}/name", .{tilde}), "~/tilde-named.txt\n");
+ try expectEqualStrings(f.at("{s}/tilde-named.txt\n", .{root}), try c.read(a, f.at("/pane/{d}/name", .{tilde})));
+ try c.remove(f.at("/pane/{d}", .{tilde}));
+ try c.write("/look", "~/tilde-made/sub/x.txt:3\n");
+ const looked = try panesAt(a, c, f.at("{s}/tilde-made/sub/x.txt", .{root}));
+ try expectEqual(@as(usize, 1), looked.len);
+ // At line 3: dot, offset 8, where the look put it (addr is a 9P client's own register).
+ try expect(std.mem.startsWith(u8, std.mem.trimStart(u8, try c.read(a, f.at("/pane/{s}/dot", .{looked[0]})), " "), "8 "));
+ try c.remove(f.at("/pane/{s}", .{looked[0]}));
+ const made_dirs = try c.newPane();
+ try c.write(f.at("/pane/{d}/body", .{made_dirs}), "deep\n");
+ try c.write(f.at("/pane/{d}/ctl", .{made_dirs}), f.at("Save {s}/save-made/a/b/x.txt\n", .{root}));
+ try expectEqualStrings("deep\n", try d.get(a, "save-made/a/b/x.txt"));
+ try c.write(f.at("/pane/{d}/name", .{made_dirs}), f.at("{s}/save-named/c/y.txt\n", .{root}));
+ try c.write(f.at("/pane/{d}/ctl", .{made_dirs}), "Save\n");
+ try expectEqualStrings("deep\n", try d.get(a, "save-named/c/y.txt"));
+ try c.remove(f.at("/pane/{d}", .{made_dirs}));
+ // A save the host cannot do (a directory it may not make) fails the
+ // write that asked for it, and the log's err record names the path and
+ // why.
+ const unsaved = try c.newPane();
+ try c.write(f.at("/pane/{d}/body", .{unsaved}), "unsaved\n");
+ try refusedSaying(c, f.at("/pane/{d}/ctl", .{unsaved}), "Save /nonexistent-pardes-dir/x.txt\n", "Save /nonexistent-pardes-dir/x.txt: permission denied"); // a directory it may not make
+ try expect(has(try c.read(a, "/log"), f.at("err {d} ctl: Save /nonexistent-pardes-dir/x.txt: ", .{unsaved})));
+ try c.remove(f.at("/pane/{d}", .{unsaved}));
+ // Sixteen connections fill the slots; the next is told why.
+ {
+ var extra: [15]*process.Conn = undefined;
+ var n: usize = 0;
+ defer for (extra[0..n]) |e| e.deinit(gpa);
+ while (n < extra.len) : (n += 1) extra[n] = try process.Conn.dial(gpa, d.socket());
+ var words: [256]u8 = undefined;
+ try expect(has(try process.Conn.dialRefusal(gpa, d.socket(), &words), "too many connections"));
+ }
+ const until = eh.nowMs() + 5_000;
+ while (!has(try c.read(a, "/log"), "err - 9p: too many connections")) {
+ if (eh.nowMs() > until) return error.NotLogged;
+ process.sleep(10);
+ }
+}
+
+fn screenSize(f: *process.Files) !struct { i64, i64 } {
+ const json = try std.json.parseFromSliceLeaky(std.json.Value, f.arena.allocator(), try f.read("/screen"), .{});
+ return .{ json.object.get("cols").?.integer, json.object.get("rows").?.integer };
+}
+
+/// A write bigger than a 9P message comes as several, cut anywhere: each
+/// command line runs once, whole, an Edit block once it ends, and a last
+/// line with no newline when the open closes. Never a fragment.
+fn cutWrites(gpa: std.mem.Allocator, exe: [:0]const u8) !void {
+ var d = try process.Detached.start(gpa, exe, "cut", .{});
+ defer d.deinit();
+ const f = &d.files;
+ var arena = std.heap.ArenaAllocator.init(gpa);
+ defer arena.deinit();
+ const a = arena.allocator();
+ const c = try process.Conn.dial(gpa, d.socket());
+ defer c.deinit(gpa);
+ // As test/fs.py's client cut them: an 8192-byte msize's writes.
+ const cut = 8192 - 23;
+ var burst: std.ArrayList(u8) = .empty;
+ for (0..1000) |i| try burst.print(a, "Msg burst-{d:0>4}\n", .{i});
+ try expect(burst.items.len > 8192);
+ try c.writeCut("/exec", 1, burst.items, cut);
+ const log = try c.read(a, "/log");
+ var i: usize = 0;
+ var lines = std.mem.tokenizeScalar(u8, log, '\n');
+ while (lines.next()) |line| {
+ if (!std.mem.startsWith(u8, line, "msg ") or !has(line, "burst-")) continue;
+ var w = std.mem.splitScalar(u8, line, ' ');
+ _ = w.next();
+ _ = w.next();
+ try expectEqualStrings(f.at("burst-{d:0>4}", .{i}), w.rest());
+ i += 1;
+ }
+ try expectEqual(@as(usize, 1000), i);
+ try expect(!has(log, "\nrun ") and !has(log, "exit 127"));
+ try c.write("/exec", "Msg no-newline-at-end");
+ const said = try c.read(a, "/log");
+ const upto = said[0..std.mem.indexOf(u8, said, "no-newline-at-end").?];
+ try expect(has(upto[upto.len -| 40..], "msg "));
+ const serial = try c.newPane();
+ var block: std.ArrayList(u8) = .empty;
+ try block.appendSlice(a, "Edit ,a\n");
+ for (0..2500) |k| try block.print(a, "line {d:0>5} of the block\n", .{k});
+ try block.appendSlice(a, ".\n");
+ try expect(block.items.len > 50000);
+ try c.writeCut(f.at("/pane/{d}/ctl", .{serial}), 1, block.items, cut);
+ var body = std.mem.splitScalar(u8, std.mem.trimEnd(u8, try c.read(a, f.at("/pane/{d}/body", .{serial})), "\n"), '\n');
+ var k: usize = 0;
+ while (body.next()) |line| : (k += 1) try expectEqualStrings(f.at("line {d:0>5} of the block", .{k}), line);
+ try expectEqual(@as(usize, 2500), k);
+ // A detached session with no frontend is 160x50 until told.
+ const cols, const rows = try screenSize(f);
+ try expect(cols == 160 and rows == 50);
+ try c.write("/ctl", "size 132 40\n");
+ const cols2, const rows2 = try screenSize(f);
+ try expect(cols2 == 132 and rows2 == 40);
+}