summaryrefslogtreecommitdiff
path: root/dev
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-18 22:34:26 -0300
committerGabriel Schneider <[email protected]>2026-11-18 22:57:27 -0300
commit250d34c1b942cd6e3726e96f6d80a9cf98d6e20e (patch)
tree30d0d8bb7cd769adf3174d215d4be7e21d754fc2 /dev
parent99f5b10eccd95aa0066ea6fe6bb75f367ab56a47 (diff)
downloadpardes-250d34c1b942cd6e3726e96f6d80a9cf98d6e20e.tar.gz
pardes-250d34c1b942cd6e3726e96f6d80a9cf98d6e20e.zip
dev: host_io.zig into its type files (the reorganisation's tree, step 2e): Host, KindJob, Inbox, Lsp and Shell each a file of its own beside it, their declarations moved as they were (a struct's body is the file's, one indent less), each file importing what it names and host_io.zig naming each (`pub const Shell = @import("Shell.zig")`), so every caller reads as before; Shell's `setenv` is pub, host_io.zig's own code calling it; the tests inside the structs move with them (host_io.Shell.test.* now Shell.test.*); nothing else changes: the ledger, frames byte-identical, replicas and process-test the base's
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'dev')
-rw-r--r--dev/Host.zig66
-rw-r--r--dev/Inbox.zig375
-rw-r--r--dev/KindJob.zig95
-rw-r--r--dev/Lsp.zig400
-rw-r--r--dev/Shell.zig731
-rw-r--r--dev/host_io.zig1650
6 files changed, 1672 insertions, 1645 deletions
diff --git a/dev/Host.zig b/dev/Host.zig
new file mode 100644
index 00000000..0dc2ae6c
--- /dev/null
+++ b/dev/Host.zig
@@ -0,0 +1,66 @@
+const pardes = @import("core");
+const host_io = @import("host_io.zig");
+const Lsp = host_io.Lsp;
+
+ctx: ?*anyopaque = null,
+vtable: *const VTable = &.{},
+
+pub const VTable = struct {
+ wait_input: ?*const fn (ctx: ?*anyopaque, timeout_ms: u32) void = null,
+ /// The shell's monotonic clock in ns: the only time the core sees.
+ /// Without one, core animation moves only by `.tick` events.
+ now: ?*const fn (ctx: ?*anyopaque) u64 = null,
+ present: ?*const fn (ctx: ?*anyopaque, surface: *const pardes.Surface) void = null,
+ post_present: ?*const fn (ctx: ?*anyopaque) void = null,
+ poll_frame: ?*const fn (ctx: ?*anyopaque) void = null,
+ /// Whether anyone sees a frame drawn now. A detached session with no
+ /// client attached draws none (a /screen read draws its own), and
+ /// the frame owed is drawn when one attaches. Absent: always.
+ watched: ?*const fn (ctx: ?*anyopaque) bool = null,
+ /// Detach: the terminal or window let go, the session left running
+ /// for the daemon to attach again (daemon.zig).
+ detach: ?*const fn (ctx: ?*anyopaque) void = null,
+ /// Adopt: the shells a dead session left, asked of the daemon.
+ adopt: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null,
+ /// Upgrade: this process exec'd as the pardes installed since, at
+ /// the step's end (upgrade.zig); `pane` hears why if it cannot be.
+ upgrade: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null,
+ /// Whether a newer pardes is installed at the path this process
+ /// started from, to be said once (upgrade.zig): asked at a focus-in.
+ newer_build: ?*const fn (ctx: ?*anyopaque) bool = null,
+ spawn: ?*const fn (ctx: ?*anyopaque, pane: u8, cwd: []const u8) void = null,
+ pty_write: ?*const fn (ctx: ?*anyopaque, pane: u8, bytes: []const u8) void = null,
+ pty_resize: ?*const fn (ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void = null,
+ pty_signal: ?*const fn (ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void = null,
+ close_pty: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null,
+ tty_taken: ?*const fn (ctx: ?*anyopaque, pane: u8) bool = null,
+ /// The name of the program holding the tty, when it is not the
+ /// shell (host_io.foregroundName), in `buf`.
+ fg_name: ?*const fn (ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 = null,
+ /// Answered at once, not queued as an effect: Kill asks while the
+ /// job it saw running is still the one in the tty (host_io.killJob).
+ kill_job: ?*const fn (ctx: ?*anyopaque, pane: u8) bool = null,
+ write_file: ?*const fn (ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void = null,
+ write_dump: ?*const fn (ctx: ?*anyopaque, bytes: []const u8) void = null,
+ watch_file: ?*const fn (ctx: ?*anyopaque, pane: u8, path: []const u8, on: bool, mode: pardes.WatchMode) void = null,
+ watch_theme: ?*const fn (ctx: ?*anyopaque, generation: u32, on: bool) void = null,
+ dump_themes: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null,
+ set_clipboard: ?*const fn (ctx: ?*anyopaque, text: []const u8) void = null,
+ read_clipboard: ?*const fn (ctx: ?*anyopaque) void = null,
+ open_link: ?*const fn (ctx: ?*anyopaque, url: []const u8) void = null,
+ /// A plumbing rule's program (Effect.start): every host's is
+ /// startDetached. Null once it runs, else why not.
+ start: ?*const fn (ctx: ?*anyopaque, line: []const u8, why: []u8) ?[]const u8 = null,
+ lsp: ?*const fn (ctx: ?*anyopaque, req: Lsp.Request) void = null,
+ pipe: ?*const fn (ctx: ?*anyopaque, id: u32) void = null,
+ /// Start the streaming search of this generation on a worker
+ /// (pardes.Stream.start); absent, it runs on the loop.
+ search: ?*const fn (ctx: ?*anyopaque, gen: u32) void = null,
+ /// Carry the dump of handover `seq` to another window on a worker
+ /// (Handover.start), which answers through the inbox's `handed`.
+ hand_over: ?*const fn (ctx: ?*anyopaque, seq: u32, bytes: []const u8) void = null,
+ /// Run job `token` of the pane in slot `pane` (whose serial is
+ /// `serial`) on a worker (`KindJob`), answering with the `job` event;
+ /// absent, it runs on the loop.
+ job: ?*const fn (ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void = null,
+};
diff --git a/dev/Inbox.zig b/dev/Inbox.zig
new file mode 100644
index 00000000..d8b14221
--- /dev/null
+++ b/dev/Inbox.zig
@@ -0,0 +1,375 @@
+const std = @import("std");
+const libc = std.c;
+const pardes = @import("core");
+const selection_pipe = @import("core").selection_pipe;
+const host_io = @import("host_io.zig");
+const KindJob = host_io.KindJob;
+const Lsp = host_io.Lsp;
+const Inbox = @This();
+
+pub const Msg = union(enum) {
+ output: struct { pane: u8, gen: u32, bytes: []u8 },
+ eof: struct { pane: u8, gen: u32, failure: ?anyerror = null },
+ lsp: struct { id: u32, rows: ?[]u8 },
+ lsp_status: []u8,
+ pipe: selection_pipe.Response,
+ /// A streaming search's rows (pardes.Stream), of whatever generation:
+ /// the core drops a stale one.
+ search: pardes.Stream.Batch,
+ /// How a handover went (Handover.zig): `words` is where it went, or
+ /// why it did not; gpa-owned.
+ handed: struct { seq: u32, ok: bool, words: []u8 },
+ /// A kind's job done on a worker (KindJob), never dropped.
+ kind_job: *KindJob,
+ files_changed,
+ fs_ready,
+ /// The daemon asks for the window again (`pardes-gui --attach`).
+ window,
+ /// A shell a dead session left, its pty's master (Adopt); pid 0 is
+ /// the last of them told.
+ adopted: struct { pid: libc.pid_t, fd: c_int },
+
+ pub fn deinit(m: Msg, gpa: std.mem.Allocator, lsp_allocator: std.mem.Allocator) void {
+ switch (m) {
+ .output => |o| gpa.free(o.bytes),
+ .lsp => |l| if (l.rows) |rows| lsp_allocator.free(rows),
+ .lsp_status => |t| lsp_allocator.free(t),
+ .pipe => |response_value| {
+ var response = response_value;
+ response.deinit(gpa);
+ },
+ .search => |b| b.deinit(gpa),
+ .handed => |h| gpa.free(h.words),
+ .kind_job => |j| j.drop(),
+ .adopted => |a| if (a.fd >= 0) {
+ _ = libc.close(a.fd);
+ },
+ .eof, .files_changed, .fs_ready, .window => {},
+ }
+ }
+};
+
+pub const capacity = 512;
+pub const output_capacity = capacity - pardes.MAX_PANES;
+
+pub const Batch = struct {
+ items: [capacity + 2 * selection_pipe.Tasks.capacity + 2]Msg = undefined,
+ len: usize = 0,
+
+ pub fn slice(batch: *Batch) []Msg {
+ return batch.items[0..batch.len];
+ }
+};
+
+gpa: std.mem.Allocator,
+lsp_allocator: std.mem.Allocator,
+/// The query in flight; the UI thread's alone (spawnLsp, teardown).
+lsp_task: ?Lsp.Task = null,
+/// Wakes the host's loop after a push from another thread: an SDL
+/// event, a macOS runtime callback. Null: nobody to wake (tests).
+wake_fn: ?*const fn (?*anyopaque) void = null,
+wake_ctx: ?*anyopaque = null,
+/// The process's Io: its terminal readers wait for space on `space`.
+io: std.Io,
+mutex: std.Io.Mutex = .init,
+space: std.Io.Condition = .init,
+items: [capacity]Msg = undefined,
+head: usize = 0,
+len: usize = 0,
+closed: bool = false,
+files_changed: bool = false,
+readers: [pardes.MAX_PANES]?u32 = @splat(null),
+waiting: usize = 0,
+lsp_id: ?u32 = null,
+completions: [2 * selection_pipe.Tasks.capacity + 1]Msg = undefined,
+completion_len: usize = 0,
+
+pub fn lock(q: *Inbox) void {
+ q.mutex.lockUncancelable(q.io);
+}
+
+pub fn unlock(q: *Inbox) void {
+ q.mutex.unlock(q.io);
+}
+
+pub fn wake(q: *Inbox) void {
+ if (q.wake_fn) |f| f(q.wake_ctx);
+}
+
+pub fn acceptReader(q: *Inbox, pane: u8, gen: u32) void {
+ q.lock();
+ defer q.unlock();
+ std.debug.assert(q.readers[pane] == null);
+ q.readers[pane] = gen;
+}
+
+pub fn cancelReader(q: *Inbox, pane: u8, gen: u32) void {
+ q.lock();
+ defer q.unlock();
+ if (q.readers[pane] != gen) return;
+ q.readers[pane] = null;
+ var i: usize = 0;
+ while (i < q.len) {
+ const msg = q.items[(q.head + i) % q.items.len];
+ const matches = switch (msg) {
+ .output => |o| o.pane == pane and o.gen == gen,
+ .eof => |e| e.pane == pane and e.gen == gen,
+ else => false,
+ };
+ if (matches) q.removeAt(i).deinit(q.gpa, q.lsp_allocator) else i += 1;
+ }
+ q.space.broadcast(q.io);
+}
+
+pub fn pushOutput(q: *Inbox, pane: u8, gen: u32, bytes: []u8) bool {
+ q.lock();
+ while (!q.closed and q.readers[pane] == gen and q.len >= output_capacity) {
+ q.waiting += 1;
+ q.space.waitUncancelable(q.io, &q.mutex);
+ q.waiting -= 1;
+ }
+ if (q.closed or q.readers[pane] != gen) {
+ q.unlock();
+ q.gpa.free(bytes);
+ return false;
+ }
+ q.items[(q.head + q.len) % q.items.len] = .{ .output = .{ .pane = pane, .gen = gen, .bytes = bytes } };
+ q.len += 1;
+ q.unlock();
+ q.wake();
+ return true;
+}
+
+fn removeAt(q: *Inbox, offset: usize) Msg {
+ const removed = q.items[(q.head + offset) % q.items.len];
+ var i = offset;
+ while (i + 1 < q.len) : (i += 1)
+ q.items[(q.head + i) % q.items.len] = q.items[(q.head + i + 1) % q.items.len];
+ q.len -= 1;
+ return removed;
+}
+
+pub fn discardLsp(q: *Inbox) void {
+ for (q.completions[0..q.completion_len], 0..) |msg, i| if (msg == .lsp) {
+ msg.deinit(q.gpa, q.lsp_allocator);
+ q.completion_len -= 1;
+ std.mem.copyForwards(Msg, q.completions[i..q.completion_len], q.completions[i + 1 .. q.completion_len + 1]);
+ return;
+ };
+}
+
+pub fn push(q: *Inbox, m: Msg) void {
+ if (m == .output) {
+ _ = q.pushOutput(m.output.pane, m.output.gen, m.output.bytes);
+ return;
+ }
+ q.lock();
+ if (q.closed) {
+ q.unlock();
+ m.deinit(q.gpa, q.lsp_allocator);
+ return;
+ }
+ switch (m) {
+ .files_changed => q.files_changed = true,
+ .lsp, .pipe, .kind_job => {
+ if (m == .lsp) {
+ if (q.lsp_id != m.lsp.id) {
+ q.unlock();
+ m.deinit(q.gpa, q.lsp_allocator);
+ return;
+ }
+ q.discardLsp();
+ }
+ std.debug.assert(q.completion_len < q.completions.len);
+ q.completions[q.completion_len] = m;
+ q.completion_len += 1;
+ },
+ else => {
+ if (m == .eof) {
+ if (q.readers[m.eof.pane] != m.eof.gen) {
+ q.unlock();
+ return;
+ }
+ std.debug.assert(q.len < q.items.len);
+ } else if (q.len >= output_capacity) {
+ q.unlock();
+ m.deinit(q.gpa, q.lsp_allocator);
+ return;
+ }
+ q.items[(q.head + q.len) % q.items.len] = m;
+ q.len += 1;
+ },
+ }
+ q.unlock();
+ q.wake();
+}
+
+pub fn take(q: *Inbox) Batch {
+ var batch: Batch = .{};
+ q.takeInto(&batch);
+ return batch;
+}
+
+/// `take` into a batch the caller keeps: an idle wakeup copies nothing
+/// (the batch is some 20 KB, and was built and returned by value each
+/// time).
+pub fn takeInto(q: *Inbox, batch: *Batch) void {
+ batch.len = 0;
+ q.lock();
+ defer q.unlock();
+ if (q.len == 0 and !q.files_changed and q.completion_len == 0) return;
+ while (q.len > 0) {
+ batch.items[batch.len] = q.items[q.head];
+ batch.len += 1;
+ q.head = (q.head + 1) % q.items.len;
+ q.len -= 1;
+ }
+ q.head = 0;
+ if (q.files_changed) {
+ batch.items[batch.len] = .files_changed;
+ batch.len += 1;
+ q.files_changed = false;
+ }
+ @memcpy(batch.items[batch.len..][0..q.completion_len], q.completions[0..q.completion_len]);
+ batch.len += q.completion_len;
+ q.completion_len = 0;
+ q.space.broadcast(q.io);
+}
+
+pub fn discardCompletions(q: *Inbox) void {
+ q.lock();
+ defer q.unlock();
+ q.lsp_id = null;
+ for (q.completions[0..q.completion_len]) |msg| msg.deinit(q.gpa, q.lsp_allocator);
+ q.completion_len = 0;
+}
+
+pub fn close(q: *Inbox) void {
+ q.lock();
+ q.closed = true;
+ q.files_changed = false;
+ q.readers = @splat(null);
+ q.space.broadcast(q.io);
+ q.unlock();
+ q.discardCompletions();
+ q.lock();
+ defer q.unlock();
+ while (q.len > 0) {
+ const m = q.items[q.head];
+ m.deinit(q.gpa, q.lsp_allocator);
+ q.head = (q.head + 1) % q.items.len;
+ q.len -= 1;
+ }
+ q.head = 0;
+}
+
+pub fn deinit(q: *Inbox) void {
+ q.close();
+ std.debug.assert(q.waiting == 0);
+}
+
+/// A pane's reader: its pty's output pushed as it comes, then its end
+/// of file; canceled (closePty), it pushes nothing more.
+pub fn startReader(q: *Inbox, pty: std.Io.File, pane: u8, gen: u32) !std.Io.Future(void) {
+ q.acceptReader(pane, gen);
+ errdefer q.cancelReader(pane, gen);
+ return q.io.concurrent(readPty, .{ q, pty, pane, gen });
+}
+
+fn readPty(q: *Inbox, pty: std.Io.File, pane: u8, gen: u32) void {
+ var buf: [0x10000]u8 = undefined;
+ var failure: ?anyerror = null;
+ while (true) {
+ const n = pty.readStreaming(q.io, &.{&buf}) catch |err| switch (err) {
+ // A pty whose child has gone answers EIO: its end of file.
+ error.EndOfStream, error.InputOutput => break,
+ error.Canceled => return,
+ else => {
+ failure = err;
+ break;
+ },
+ };
+ if (n == 0) continue;
+ const bytes = q.gpa.dupe(u8, buf[0..n]) catch |err| {
+ failure = err;
+ break;
+ };
+ if (!q.pushOutput(pane, gen, bytes)) return;
+ }
+ q.push(.{ .eof = .{ .pane = pane, .gen = gen, .failure = failure } });
+}
+
+/// Starts `e`, its answer let in and every older one's turned away.
+pub fn startLsp(q: *Inbox, core: *pardes.Pardes, e: Lsp.Request) void {
+ q.lock();
+ q.lsp_id = e.id;
+ q.discardLsp();
+ q.unlock();
+ // The old query's waits are cancelation points: its join is short, and
+ // what it still delivers carries an id the queue now rejects.
+ Lsp.start(q.io, q.lsp_allocator, core, &q.lsp_task, e, q, pushLspRows);
+}
+
+fn pushLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void {
+ const q: *Inbox = @ptrCast(@alignCast(ctx orelse return));
+ q.push(.{ .lsp = .{ .id = id, .rows = rows } });
+}
+
+/// The language client's status line (lsp.setStatusSink).
+pub fn lspStatus(ctx: ?*anyopaque, text: []const u8) void {
+ const q: *Inbox = @ptrCast(@alignCast(ctx orelse return));
+ const copy = q.lsp_allocator.dupe(u8, text) catch return;
+ q.push(.{ .lsp_status = copy });
+}
+
+/// A `|` job's answer (selection_pipe.start's sink).
+pub fn pushJob(ctx: ?*anyopaque, j: *KindJob) void {
+ const q: *Inbox = @ptrCast(@alignCast(ctx.?));
+ q.push(.{ .kind_job = j });
+}
+
+pub fn pushPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void {
+ const q: *Inbox = @ptrCast(@alignCast(ctx.?));
+ q.push(.{ .pipe = response });
+}
+
+/// A handover's end (Handover.Job.post).
+pub fn pushHanded(ctx: ?*anyopaque, seq: u32, ok: bool, words: []const u8) void {
+ const q: *Inbox = @ptrCast(@alignCast(ctx.?));
+ const copy = q.gpa.dupe(u8, words) catch return;
+ q.push(.{ .handed = .{ .seq = seq, .ok = ok, .words = copy } });
+}
+
+/// A streaming search's batch (pardes.Stream.start's sink). Never
+/// dropped for want of room, as output is not: the worker waits for
+/// room, a wait its cancel ends (false: it stops).
+pub fn pushSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool {
+ const q: *Inbox = @ptrCast(@alignCast(ctx.?));
+ q.lock();
+ while (!q.closed and q.len >= output_capacity) {
+ q.waiting += 1;
+ q.space.wait(q.io, &q.mutex) catch {
+ q.waiting -= 1;
+ q.unlock();
+ batch.deinit(q.gpa);
+ return false;
+ };
+ q.waiting -= 1;
+ }
+ if (q.closed) {
+ q.unlock();
+ batch.deinit(q.gpa);
+ return false;
+ }
+ q.items[(q.head + q.len) % q.items.len] = .{ .search = batch };
+ q.len += 1;
+ q.unlock();
+ q.wake();
+ return true;
+}
+
+/// A watched child exited (setExitWake): wake the loop, which takes it.
+pub fn wakeForExit(ctx: ?*anyopaque) void {
+ const q: *Inbox = @ptrCast(@alignCast(ctx.?));
+ q.wake();
+}
diff --git a/dev/KindJob.zig b/dev/KindJob.zig
new file mode 100644
index 00000000..c24ad88d
--- /dev/null
+++ b/dev/KindJob.zig
@@ -0,0 +1,95 @@
+const std = @import("std");
+const pardes = @import("core");
+const selection_pipe = @import("core").selection_pipe;
+const KindJob = @This();
+
+gpa: std.mem.Allocator,
+pane: u8,
+serial: u32,
+token: u32,
+gen: u32,
+ops: *const pardes.Kind.Ops,
+in: []u8,
+/// What the job allocates (`pa_out`), freed with it; `out` the last.
+arena: std.heap.ArenaAllocator,
+out: []u8 = &.{},
+id: u32 = 0,
+/// A draw's: the core it was asked in.
+draw: ?*const pardes.Pardes = null,
+
+pub fn take(p: *pardes.Pardes, pane: u8, serial: u32, token: u32) ?*KindJob {
+ const pn = p.panes[pane] orelse return null;
+ const slot = pn.addon orelse return null;
+ const ops = slot.ops orelse return null;
+ if (pn.serial != serial or ops.job_run == null) return null;
+ const at = for (&slot.jobs) |*j| {
+ if (j.*) |job| if (job.token == token) break j;
+ } else return null;
+ const j = slot.gpa.create(KindJob) catch return null;
+ j.* = .{ .gpa = slot.gpa, .pane = pane, .serial = serial, .token = token, .gen = slot.gen, .ops = ops, .in = at.*.?.in, .arena = .init(slot.gpa) };
+ at.* = null;
+ pardes.Addon.holdJob(ops, true);
+ return j;
+}
+
+pub fn run(j: *KindJob) void {
+ const Out = struct {
+ fn alloc(out: [*c]pardes.Kind.c.pa_out, n: usize) callconv(.c) ?*anyopaque {
+ const job: *KindJob = @ptrCast(@alignCast(out.*.ctx));
+ job.out = job.arena.allocator().alignedAlloc(u8, .@"16", n) catch &.{};
+ return if (job.out.len == n) job.out.ptr else null;
+ }
+ };
+ var out: pardes.Kind.c.pa_out = .{ .alloc = Out.alloc, .ctx = j };
+ const n = j.ops.job_run.?(j.in.ptr, @intCast(j.in.len), &out);
+ j.out = j.out[0..@min(n, j.out.len)];
+}
+
+/// Its answer to the core, and it gone.
+pub fn land(j: *KindJob, p: *pardes.Pardes) void {
+ if (j.draw != null) return pardes.Kind.landDraw(p, j);
+ p.update(.{ .job = .{ .pane = j.pane, .serial = j.serial, .token = j.token, .gen = j.gen, .bytes = j.out } });
+ j.drop();
+}
+
+pub fn drop(j: *KindJob) void {
+ pardes.Addon.holdJob(j.ops, false);
+ j.gpa.free(j.in);
+ j.arena.deinit();
+ j.gpa.destroy(j);
+}
+
+/// On a worker of `io`, posting itself to `sink` done: a host's `job`.
+pub fn start(io: std.Io, p: *pardes.Pardes, tasks: *selection_pipe.Tasks, pane: u8, serial: u32, token: u32, ctx: ?*anyopaque, sink: *const fn (?*anyopaque, *KindJob) void) void {
+ const j = take(p, pane, serial, token) orelse return;
+ if (!go(io, tasks, j, ctx, sink)) here(j, p);
+}
+
+/// `j` on a worker of `io`, posting itself to `sink` done; false when
+/// none could take it.
+pub fn go(io: std.Io, tasks: *selection_pipe.Tasks, j: *KindJob, ctx: ?*anyopaque, sink: *const fn (?*anyopaque, *KindJob) void) bool {
+ next_id +%= 1;
+ j.id = next_id | 0x8000_0000;
+ const work = struct {
+ fn work(job: *KindJob, c: ?*anyopaque, s: *const fn (?*anyopaque, *KindJob) void) void {
+ job.run();
+ s(c, job);
+ }
+ }.work;
+ if (tasks.full()) return false;
+ const future = io.concurrent(work, .{ j, ctx, sink }) catch return false;
+ _ = tasks.add(.{ .id = j.id, .future = future });
+ return true;
+}
+
+var next_id: u32 = 0;
+
+fn here(j: *KindJob, p: *pardes.Pardes) void {
+ j.run();
+ j.land(p);
+}
+
+/// No workers (a test, the fallback): it runs on the loop, at once.
+pub fn runHere(p: *pardes.Pardes, pane: u8, serial: u32, token: u32) void {
+ here(take(p, pane, serial, token) orelse return, p);
+}
diff --git a/dev/Lsp.zig b/dev/Lsp.zig
new file mode 100644
index 00000000..edc99eeb
--- /dev/null
+++ b/dev/Lsp.zig
@@ -0,0 +1,400 @@
+const std = @import("std");
+const pardes = @import("core");
+const filesystem = @import("core").filesystem;
+
+pub const Request = struct {
+ id: u32,
+ kind: pardes.lsp.Kind,
+ pane: u8,
+ offset: u32,
+ arg: []const u8,
+};
+
+pub const Task = struct {
+ id: u32,
+ future: std.Io.Future(void),
+};
+
+/// One language query, owned by the worker that runs it.
+pub const Job = struct {
+ callstack_depth: u8 = pardes.lsp.callstack_default_depth,
+ dirty: bool = false,
+ id: u32,
+ kind: pardes.lsp.Kind,
+ offset: u32,
+ path: []u8,
+ source: [:0]u8,
+ arg: []u8,
+ root: []u8,
+ /// The other open files, for a query that can reach them.
+ others: []pardes.lsp.Doc = &.{},
+
+ pub fn free(job: *Job, gpa: std.mem.Allocator) void {
+ gpa.free(job.path);
+ gpa.free(job.source);
+ gpa.free(job.arg);
+ gpa.free(job.root);
+ for (job.others) |doc| {
+ gpa.free(doc.path);
+ gpa.free(doc.source);
+ }
+ gpa.free(job.others);
+ gpa.destroy(job);
+ }
+};
+
+// Copy before starting a worker; the editor may replace any source slice afterward.
+pub fn snapshot(gpa: std.mem.Allocator, core: *const pardes.Pardes, req: Request) !*Job {
+ if (req.pane >= core.panes.len) return error.NoPane;
+ const pane = core.panes[req.pane] orelse return error.NoPane;
+ const file = pane.file;
+ const job = try gpa.create(Job);
+ errdefer gpa.destroy(job);
+ const declared_path = if (file) |f| f.path else "";
+ const path = try gpa.dupe(u8, filesystem.localPath(declared_path) orelse declared_path);
+ errdefer gpa.free(path);
+ const source = try gpa.dupeSentinel(u8, if (file) |f| f.content else "", 0);
+ errdefer gpa.free(source);
+ const arg = try gpa.dupe(u8, req.arg);
+ errdefer gpa.free(arg);
+ const declared_root = if (file) |f| pardes.panes.Dir.ofName(f.path) else pane.cwdSlice();
+ const root = try gpa.dupe(u8, filesystem.localPath(declared_root) orelse declared_root);
+ errdefer gpa.free(root);
+ job.* = .{
+ .callstack_depth = core.settings.callstack_depth,
+ .dirty = pardes.tagline.dirty(pane),
+ .id = req.id,
+ .kind = req.kind,
+ .offset = req.offset,
+ .path = path,
+ .source = source,
+ .arg = arg,
+ .root = root,
+ };
+ // ponytail: a copy of every open file per such query; a server
+ // already told of one is sent nothing more (syncDoc).
+ // Lspwhy too: the query it explains may be one of those, and its
+ // trace shows each file synced first.
+ if (pardes.lsp.reachesOtherFiles(req.kind) or req.kind == .explain) {
+ var others: std.ArrayList(pardes.lsp.Doc) = .empty;
+ errdefer {
+ for (others.items) |doc| {
+ gpa.free(doc.path);
+ gpa.free(doc.source);
+ }
+ others.deinit(gpa);
+ }
+ var copied: usize = 0;
+ for (core.panes, 0..) |slot, i| {
+ const other = slot orelse continue;
+ if (i == req.pane) continue;
+ const f = other.file orelse continue;
+ if (f.output != null) continue;
+ if (copied + f.content.len > pardes.memory.limits.lsp_snapshot_bytes) continue;
+ copied += f.content.len;
+ const local = filesystem.localPath(f.path) orelse continue;
+ const other_path = try gpa.dupe(u8, local);
+ const other_source = gpa.dupeSentinel(u8, f.content, 0) catch |err| {
+ gpa.free(other_path);
+ return err;
+ };
+ try others.append(gpa, .{ .path = other_path, .source = other_source });
+ }
+ job.others = try others.toOwnedSlice(gpa);
+ }
+ return job;
+}
+
+// Null is failure; the receiver frees non-null rows with the job's allocator.
+pub const Deliver = *const fn (ctx: ?*anyopaque, id: u32, rows: ?[]u8) void;
+
+/// Start `req` on a worker that hands its rows to `deliver`, the query
+/// in `task` canceled first. One that cannot start is answered (no rows)
+/// and reported here.
+pub fn start(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, task: *?Task, req: Request, ctx: ?*anyopaque, deliver: Deliver) void {
+ if (task.*) |*old| {
+ old.future.cancel(io);
+ task.* = null;
+ }
+ const job = snapshot(gpa, core, req) catch |err| {
+ core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } });
+ return core.reportError(req.pane, "lsp", err);
+ };
+ const future = io.concurrent(work, .{ io, gpa, job, ctx, deliver }) catch |err| {
+ job.free(gpa);
+ core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } });
+ return core.reportError(req.pane, "lsp", err);
+ };
+ task.* = .{ .id = req.id, .future = future };
+}
+
+pub fn work(io: std.Io, gpa: std.mem.Allocator, job: *Job, ctx: ?*anyopaque, deliver: Deliver) void {
+ defer job.free(gpa);
+ // The query's memory is the fixed region memory.zig reserved at
+ // startup: a hard bound, reused by each query in turn.
+ const region = pardes.memory.takeLspQuery() orelse {
+ deliver(ctx, job.id, null);
+ return;
+ };
+ var arena: std.heap.FixedBufferAllocator = .init(region);
+ defer pardes.memory.giveLspQuery(arena.end_index);
+ var out: std.Io.Writer.Allocating = .init(gpa);
+ defer out.deinit();
+ pardes.lsp.query(io, arena.allocator(), .{
+ .kind = job.kind,
+ .path = job.path,
+ .source = job.source,
+ .offset = job.offset,
+ .arg = job.arg,
+ .root = job.root,
+ .others = job.others,
+ .callstack_depth = job.callstack_depth,
+ .dirty = job.dirty,
+ .budget = &arena,
+ }, &out.writer) catch {
+ deliver(ctx, job.id, null);
+ return;
+ };
+ const rows = out.toOwnedSlice() catch {
+ deliver(ctx, job.id, null);
+ return;
+ };
+ deliver(ctx, job.id, rows);
+}
+
+test "a snapshot owns every byte the backend will read" {
+ if (pardes.Term.ops == null) return error.SkipZigTest; // a terminal pane's snapshot
+ const gpa = std.testing.allocator;
+ const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
+ defer core.deinit();
+
+ core.settings.callstack_depth = 16;
+ var needle: [6]u8 = "needle".*;
+ const job = try snapshot(gpa, core, .{
+ .id = 7,
+ .kind = .status,
+ .pane = @intCast(core.view().active),
+ .offset = 0,
+ .arg = &needle,
+ });
+ defer job.free(gpa);
+
+ core.settings.callstack_depth = 2;
+ try std.testing.expectEqual(@as(u8, 16), job.callstack_depth);
+ try std.testing.expectEqual(@as(u32, 7), job.id);
+ try std.testing.expectEqual(pardes.lsp.Kind.status, job.kind);
+ try std.testing.expectEqualStrings("needle", job.arg);
+ try std.testing.expect(job.arg.ptr != &needle);
+ try std.testing.expectEqualStrings("", job.path);
+ try std.testing.expectEqual(@as(usize, 0), job.source.len);
+ try std.testing.expectEqual(@as(u8, 0), job.source[0]);
+ const pane = core.panes[core.view().active].?;
+ try std.testing.expectEqualStrings(pane.cwdSlice(), job.root);
+ if (job.root.len > 0) try std.testing.expect(job.root.ptr != pane.cwdSlice().ptr);
+}
+
+test "LSP snapshot frees every partially copied field on allocation failure" {
+ const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true });
+ defer core.deinit();
+ _ = try core.setTestFile("const copied = true;\n");
+ const Snapshot = struct {
+ fn check(gpa: std.mem.Allocator, p: *const pardes.Pardes) !void {
+ const job = try snapshot(gpa, p, .{
+ .id = 7,
+ .kind = .hover,
+ .pane = @intCast(p.view().active),
+ .offset = 6,
+ .arg = "query",
+ });
+ defer job.free(gpa);
+ try std.testing.expectEqualStrings("const copied = true;\n", job.source);
+ }
+ };
+ try std.testing.checkAllAllocationFailures(std.testing.allocator, Snapshot.check, .{core});
+}
+
+test "LSP snapshots translate explicit OS paths once and retain virtual names" {
+ const gpa = std.testing.allocator;
+ const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
+ defer core.deinit();
+ const pane = try core.setTestFile("const value = true;\n");
+ for ([_]struct { path: []const u8, native: []const u8 }{
+ .{ .path = "/n/os/project/file.zig", .native = "/project/file.zig" },
+ .{ .path = "/n/os/n/os/project/file.zig", .native = "/n/os/project/file.zig" },
+ .{ .path = "/virtual/src/file.zig", .native = "/virtual/src/file.zig" },
+ }) |case| {
+ const replacement = try gpa.dupe(u8, case.path);
+ gpa.free(pane.file.?.path);
+ pane.file.?.path = replacement;
+ const job = try snapshot(gpa, core, .{ .id = 1, .kind = .hover, .pane = @intCast(core.view().active), .offset = 0, .arg = "" });
+ defer job.free(gpa);
+ try std.testing.expectEqualStrings(case.native, job.path);
+ try std.testing.expectEqualStrings(std.Io.Dir.path.dirname(case.native).?, job.root);
+ try std.testing.expectEqualStrings(case.path, pane.file.?.path);
+ }
+}
+
+test "a pane that is gone yields no job rather than a null deref" {
+ const gpa = std.testing.allocator;
+ const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
+ defer core.deinit();
+
+ // The effect is drained after the core has moved on, so the pane it names
+ // may already have been deleted. Every shell open-coded this check.
+ const empty = for (core.panes, 0..) |slot, id| {
+ if (slot == null) break @as(u8, @intCast(id));
+ } else return error.NoEmptyPane;
+ try std.testing.expectError(error.NoPane, snapshot(gpa, core, .{
+ .id = 1,
+ .kind = .definition,
+ .pane = empty,
+ .offset = 0,
+ .arg = "",
+ }));
+}
+
+test "work consumes the job and hands its rows to the sink" {
+ const gpa = std.testing.allocator;
+ const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
+ defer core.deinit();
+
+ const Sink = struct {
+ var seen_id: u32 = 0;
+ var seen_rows: ?[]u8 = null;
+ fn take(_: ?*anyopaque, id: u32, rows: ?[]u8) void {
+ seen_id = id;
+ seen_rows = rows;
+ }
+ };
+ Sink.seen_id = 0;
+ Sink.seen_rows = null;
+
+ const job = try snapshot(gpa, core, .{
+ .id = 42,
+ .kind = .status,
+ .pane = @intCast(core.view().active),
+ .offset = 0,
+ .arg = "",
+ });
+ work(std.testing.io, gpa, job, null, Sink.take);
+
+ // `status` is the one kind that answers with no file and no cursor, which
+ // is what makes it assertable here without a language server on the box.
+ try std.testing.expectEqual(@as(u32, 42), Sink.seen_id);
+ const rows = Sink.seen_rows orelse return error.SinkNeverCalled;
+ defer gpa.free(rows);
+}
+
+test "LSP edit query failure leaves text and undo untouched before a successful retry" {
+ if (!pardes.lsp.supports.contains(.format)) return;
+ const Sink = struct {
+ core: *pardes.Pardes,
+ gpa: std.mem.Allocator,
+ calls: usize = 0,
+ failed: bool = false,
+
+ fn take(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void {
+ const self: *@This() = @ptrCast(@alignCast(ctx.?));
+ defer if (rows) |text| self.gpa.free(text);
+ self.calls += 1;
+ self.failed = rows == null;
+ self.core.update(.{ .lsp_resp = .{ .id = id, .rows = rows } });
+ }
+ };
+ const gpa = std.testing.allocator;
+ for ([_]pardes.lsp.Kind{ .format, .rename }) |kind| {
+ const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
+ defer core.deinit();
+ const pane = try core.setTestFile("const value=1;\n");
+ const path = try gpa.dupe(u8, "/file.zig");
+ gpa.free(pane.file.?.path);
+ pane.file.?.path = path;
+ pane.body.cur_col = 6;
+ const revision = pane.file.?.revision;
+ const undo_len = pane.file.?.history.journal.done;
+ var failing = std.testing.FailingAllocator.init(gpa, .{});
+ var sink: Sink = .{ .core = core, .gpa = failing.allocator() };
+ for ([_]bool{ true, false }) |fail| {
+ failing.fail_index = std.math.maxInt(usize);
+ core.lspRequest(core.view().active, kind, "renamed");
+ const job = try snapshot(failing.allocator(), core, .{
+ .id = core.lsp_ask.wait.?.id,
+ .kind = kind,
+ .pane = @intCast(core.view().active),
+ .offset = 6,
+ .arg = "renamed",
+ });
+ if (fail) failing.fail_index = failing.alloc_index;
+ work(std.testing.io, failing.allocator(), job, &sink, Sink.take);
+ try std.testing.expectEqual(fail, sink.failed);
+ try std.testing.expect(core.lsp_ask.wait == null);
+ if (fail) {
+ try std.testing.expectEqualStrings("const value=1;\n", pane.file.?.content);
+ try std.testing.expectEqual(revision, pane.file.?.revision);
+ try std.testing.expectEqual(undo_len, pane.file.?.history.journal.done);
+ } else {
+ try std.testing.expectEqualStrings(if (kind == .format) "const value = 1;\n" else "const renamed=1;\n", pane.file.?.content);
+ try std.testing.expectEqual(undo_len + 1, pane.file.?.history.journal.done);
+ }
+ }
+ try std.testing.expectEqual(@as(usize, 2), sink.calls);
+ }
+}
+
+test "LSP work delivers failure when transferring result ownership cannot allocate" {
+ if (!pardes.lsp.supports.contains(.status)) return;
+ const TransferAllocator = struct {
+ failed: bool = false,
+ fail_copy: bool = false,
+ fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 {
+ const self: *@This() = @ptrCast(@alignCast(ctx));
+ if (self.fail_copy) {
+ self.failed = true;
+ return null;
+ }
+ return std.testing.allocator.rawAlloc(len, alignment, ra);
+ }
+ fn resize(_: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) bool {
+ return std.testing.allocator.rawResize(bytes, alignment, len, ra);
+ }
+ fn remap(ctx: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) ?[*]u8 {
+ const self: *@This() = @ptrCast(@alignCast(ctx));
+ if (len < bytes.len) {
+ self.fail_copy = true;
+ return null;
+ }
+ return std.testing.allocator.rawRemap(bytes, alignment, len, ra);
+ }
+ fn free(_: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, ra: usize) void {
+ std.testing.allocator.rawFree(bytes, alignment, ra);
+ }
+ };
+ const Sink = struct {
+ calls: usize = 0,
+ id: u32 = 0,
+ rows: ?[]u8 = null,
+ fn take(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void {
+ const self: *@This() = @ptrCast(@alignCast(ctx.?));
+ self.calls += 1;
+ self.id = id;
+ self.rows = rows;
+ }
+ };
+ var allocator: TransferAllocator = .{};
+ const gpa: std.mem.Allocator = .{ .ptr = &allocator, .vtable = &.{
+ .alloc = TransferAllocator.alloc,
+ .resize = TransferAllocator.resize,
+ .remap = TransferAllocator.remap,
+ .free = TransferAllocator.free,
+ } };
+ const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true });
+ defer core.deinit();
+ const job = try snapshot(gpa, core, .{ .id = 37, .kind = .status, .pane = @intCast(core.view().active), .offset = 0, .arg = "" });
+ var sink: Sink = .{};
+ work(std.testing.io, gpa, job, &sink, Sink.take);
+ if (sink.rows) |rows| gpa.free(rows);
+ try std.testing.expect(allocator.failed);
+ try std.testing.expectEqual(@as(usize, 1), sink.calls);
+ try std.testing.expectEqual(@as(u32, 37), sink.id);
+ try std.testing.expect(sink.rows == null);
+}
diff --git a/dev/Shell.zig b/dev/Shell.zig
new file mode 100644
index 00000000..f7c0caff
--- /dev/null
+++ b/dev/Shell.zig
@@ -0,0 +1,731 @@
+const builtin = @import("builtin");
+const std = @import("std");
+const libc = std.c;
+const pardes = @import("core");
+const ninep_io = @import("runtime").ninep_io;
+const host_io = @import("host_io.zig");
+const testUnsetenv = host_io.testUnsetenv;
+const writeFd = host_io.writeFd;
+const Shell = @This();
+
+const X_OK: c_int = 1;
+
+extern "c" fn mkstemp(template: [*:0]u8) c_int;
+pub extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
+
+const path_capacity = 4096;
+const max_path_files = 64;
+
+// Repair only the system-only PATH inherited from a macOS GUI launch.
+fn adoptSystemPath() void {
+ if (comptime builtin.os.tag != .macos) return;
+ var buf: [path_capacity]u8 = undefined;
+ var len: usize = 0;
+ collectSystemPath("/etc/paths", "/etc/paths.d", &buf, &len);
+ if (len == 0) return;
+ const system = buf[0..len];
+
+ const current: []const u8 = if (libc.getenv("PATH")) |p| std.mem.span(p) else "";
+ if (!allEntriesWithin(current, system)) return;
+ if (std.mem.eql(u8, current, system)) return;
+
+ var out: [path_capacity:0]u8 = undefined;
+ if (len >= out.len) return;
+ @memcpy(out[0..len], system);
+ out[len] = 0;
+ _ = setenv("PATH", out[0..len :0].ptr, 1);
+}
+
+// Run in the parent before forking; children borrow the completed prompt files.
+pub fn prepare() PromptFiles {
+ adoptSystemPath();
+ if (comptime builtin.os.tag.isDarwin())
+ _ = setenv("BASH_SILENCE_DEPRECATION_WARNING", "1", 1);
+ sweepDeadRcs();
+ const rcs = PromptFiles.init();
+ // A private file goes at a fatal signal too, not only at Exit.
+ for ([_]?[:0]const u8{ if (rcs.bash_owned) rcs.bashPath() else null, if (rcs.fish_owned) rcs.fishPath() else null }, 0..) |owned, i| {
+ const path = owned orelse continue;
+ @memcpy(fatal_rcs[i][0..path.len], path);
+ fatal_rcs[i][path.len] = 0;
+ fatal_rc_len[i] = path.len;
+ }
+ ninep_io.fatal_cleanup = unlinkOwnedRcs;
+ return rcs;
+}
+
+/// This process's private prompt files, where a fatal signal's handler
+/// can reach them (unlinkOwnedRcs).
+var fatal_rcs: [2][rc_path_capacity:0]u8 = undefined;
+var fatal_rc_len: [2]usize = .{ 0, 0 };
+
+/// Removes this process's private prompt files. Async-signal-safe (two
+/// unlinks): SIGTERM and SIGHUP call it before the signal's death.
+pub fn unlinkOwnedRcs() void {
+ for (&fatal_rc_len, 0..) |*len, i| {
+ const n = len.*;
+ if (n == 0) continue;
+ len.* = 0;
+ _ = libc.unlink(fatal_rcs[i][0..n :0].ptr);
+ }
+}
+
+/// Removes /tmp's `pardes-osc133-<shell>-<pid>-XXXXXX` files whose pid
+/// is gone (kill(pid, 0) answers ESRCH): what a killed or crashed
+/// editor left. A live pid's, one of another user's, or a name of
+/// another shape is left alone.
+fn sweepDeadRcs() void {
+ const dir = std.c.opendir("/tmp") orelse return;
+ defer _ = std.c.closedir(dir);
+ var dead: [64][64]u8 = undefined;
+ var dead_len: [64]usize = undefined;
+ var n: usize = 0;
+ while (std.c.readdir(dir)) |ent| {
+ const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&ent.name)), 0);
+ const pid = rcPid(name) orelse continue;
+ // This pid's are this process's, but in an upgraded one: those
+ // were its old image's (upgrade.zig), and its own come after.
+ if (pid == std.c.getpid() and @import("runtime").upgrade.resumed == null) continue;
+ if (pid != std.c.getpid() and std.posix.errno(std.c.kill(pid, @fromBackingInt(@intCast(0)))) != .SRCH) continue;
+ if (name.len >= 64 or n == dead.len) continue;
+ @memcpy(dead[n][0..name.len], name);
+ dead_len[n] = name.len;
+ n += 1;
+ }
+ for (dead[0..n], dead_len[0..n]) |*entry, len| {
+ var path_buf: [80:0]u8 = undefined;
+ const path = std.fmt.bufPrintSentinel(&path_buf, "/tmp/{s}", .{entry[0..len]}, 0) catch continue;
+ const facts = ninep_io.statNoFollow(path) orelse continue;
+ if (facts.mode & 0o170000 != 0o100000 or facts.uid != libc.getuid()) continue;
+ _ = libc.unlink(path.ptr);
+ }
+}
+
+/// The pid in `pardes-osc133-<shell>-<pid>-XXXXXX`, or null.
+fn rcPid(name: []const u8) ?std.c.pid_t {
+ const head = "pardes-osc133-";
+ if (!std.mem.startsWith(u8, name, head)) return null;
+ var fields = std.mem.splitScalar(u8, name[head.len..], '-');
+ _ = fields.next() orelse return null; // the shell
+ const digits = fields.next() orelse return null;
+ const rest = fields.next() orelse return null;
+ if (fields.next() != null or rest.len != 6 or digits.len == 0 or digits.len > 10) return null;
+ for (digits) |c| if (!std.ascii.isDigit(c)) return null;
+ const pid = std.fmt.parseInt(std.c.pid_t, digits, 10) catch return null;
+ return if (pid > 0) pid else null;
+}
+
+fn collectSystemPath(paths_file: [:0]const u8, paths_dir: []const u8, buf: []u8, len: *usize) void {
+ var file_buf: [path_capacity]u8 = undefined;
+ if (readSmall(paths_file, &file_buf)) |body| appendLines(buf, len, body);
+
+ const io = std.Io.Threaded.global_single_threaded.io();
+ var dir = std.Io.Dir.cwd().openDir(io, paths_dir, .{ .iterate = true }) catch return;
+ defer dir.close(io);
+
+ var names: [max_path_files][256]u8 = undefined;
+ var name_lens: [max_path_files]usize = undefined;
+ var count: usize = 0;
+ var it = dir.iterate();
+ while (count < names.len) {
+ const entry = (it.next(io) catch break) orelse break;
+ if (entry.kind == .directory) continue;
+ if (entry.name.len == 0 or entry.name.len > names[count].len) continue;
+ @memcpy(names[count][0..entry.name.len], entry.name);
+ name_lens[count] = entry.name.len;
+ count += 1;
+ }
+ var order: [max_path_files]usize = undefined;
+ for (0..count) |i| order[i] = i;
+ std.mem.sort(usize, order[0..count], Names{ .names = &names, .lens = &name_lens }, Names.lessThan);
+
+ var path_buf: [512]u8 = undefined;
+ for (order[0..count]) |i| {
+ const name = names[i][0..name_lens[i]];
+ const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ paths_dir, name }, 0) catch continue;
+ if (readSmall(path, &file_buf)) |body| appendLines(buf, len, body);
+ }
+}
+
+const Names = struct {
+ names: *const [max_path_files][256]u8,
+ lens: *const [max_path_files]usize,
+
+ fn lessThan(self: Names, a: usize, b: usize) bool {
+ return std.mem.order(u8, self.names[a][0..self.lens[a]], self.names[b][0..self.lens[b]]) == .lt;
+ }
+};
+
+fn appendLines(buf: []u8, len: *usize, body: []const u8) void {
+ var lines = std.mem.splitScalar(u8, body, '\n');
+ while (lines.next()) |raw| appendEntry(buf, len, std.mem.trim(u8, raw, " \t\r"));
+}
+
+fn appendEntry(buf: []u8, len: *usize, entry: []const u8) void {
+ if (entry.len == 0) return;
+ if (hasEntry(buf[0..len.*], entry)) return;
+ const separator: usize = if (len.* == 0) 0 else 1;
+ if (len.* + separator + entry.len > buf.len) return;
+ if (separator == 1) {
+ buf[len.*] = ':';
+ len.* += 1;
+ }
+ @memcpy(buf[len.*..][0..entry.len], entry);
+ len.* += entry.len;
+}
+
+fn hasEntry(list: []const u8, entry: []const u8) bool {
+ var it = std.mem.tokenizeScalar(u8, list, ':');
+ while (it.next()) |have| if (std.mem.eql(u8, have, entry)) return true;
+ return false;
+}
+
+fn allEntriesWithin(candidate: []const u8, list: []const u8) bool {
+ var it = std.mem.tokenizeScalar(u8, candidate, ':');
+ while (it.next()) |entry| if (!hasEntry(list, entry)) return false;
+ return true;
+}
+
+fn readSmall(path: [:0]const u8, buf: []u8) ?[]const u8 {
+ const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0));
+ if (fd < 0) return null;
+ defer _ = libc.close(fd);
+ var off: usize = 0;
+ while (off < buf.len) {
+ const n = libc.read(fd, buf[off..].ptr, buf.len - off);
+ if (n < 0) {
+ if (libc.errno(n) == .INTR) continue;
+ return null;
+ }
+ if (n == 0) break;
+ off += @intCast(n);
+ }
+ return buf[0..off];
+}
+
+test "the launchd PATH is replaced and a configured one is left alone" {
+ var buf: [256]u8 = undefined;
+ var len: usize = 0;
+ appendEntry(&buf, &len, "/usr/bin");
+ appendEntry(&buf, &len, "/bin");
+ appendEntry(&buf, &len, "/usr/bin"); // already there: dedup keeps the first
+ appendEntry(&buf, &len, "");
+ try std.testing.expectEqualStrings("/usr/bin:/bin", buf[0..len]);
+
+ try std.testing.expect(allEntriesWithin("/usr/bin:/bin", "/usr/bin:/bin:/sbin"));
+ try std.testing.expect(allEntriesWithin("", "/usr/bin"));
+ try std.testing.expect(!allEntriesWithin("/Users/x/.cargo/bin:/usr/bin", "/usr/bin:/bin"));
+ try std.testing.expect(!allEntriesWithin("/opt/homebrew/bin", "/usr/bin:/bin"));
+}
+
+test "system path files are sorted and duplicate directories keep their first position" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths", .data = " /usr/bin \n/bin\n\n/usr/bin\n" });
+ try tmp.dir.createDirPath(std.testing.io, "paths.d");
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths.d/20-last", .data = "/opt/local/bin\n/usr/bin\n" });
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths.d/10-first", .data = "/opt/homebrew/bin\n/bin\n" });
+ var root_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
+ const root = root_buf[0..try tmp.dir.realPath(std.testing.io, &root_buf)];
+ var file_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
+ const paths_file = try std.fmt.bufPrintSentinel(&file_buf, "{s}/paths", .{root}, 0);
+ var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
+ const paths_dir = try std.fmt.bufPrint(&dir_buf, "{s}/paths.d", .{root});
+ var buf: [path_capacity]u8 = undefined;
+ var len: usize = 0;
+ collectSystemPath(paths_file, paths_dir, &buf, &len);
+ try std.testing.expectEqualStrings("/usr/bin:/bin:/opt/homebrew/bin:/opt/local/bin", buf[0..len]);
+}
+
+const Family = enum { bash, fish, none };
+
+fn family(bin: []const u8) Family {
+ const slash = std.mem.lastIndexOfScalar(u8, bin, '/');
+ const base = if (slash) |s| bin[s + 1 ..] else bin;
+ if (std.mem.startsWith(u8, base, "bash")) return .bash;
+ if (std.mem.startsWith(u8, base, "fish")) return .fish;
+ return .none;
+}
+
+/// `family`, for a shell whose name does not say it (a renamed copy, a
+/// link named otherwise): what it really is, by the name its links end
+/// at, else by the program itself -- bash's carries BASH_VERSINFO, fish's
+/// fish_prompt. ponytail: a string scan of at most 16 MiB, once a spawn
+/// and only for a name that says nothing; a --version probe would fork.
+fn familyOf(path: [*:0]const u8) Family {
+ const named = family(std.mem.span(path));
+ if (named != .none) return named;
+ // A name a POSIX shell answers to is that shell, whatever the file:
+ // bash run as `sh` is sh, and reads no --rcfile.
+ const bin = std.mem.span(path);
+ const base = if (std.mem.lastIndexOfScalar(u8, bin, '/')) |s| bin[s + 1 ..] else bin;
+ for ([_][]const u8{ "sh", "dash", "zsh", "ksh", "mksh", "yash", "nu", "elvish", "xonsh", "tcsh", "csh" }) |known|
+ if (std.mem.eql(u8, base, known)) return .none;
+ var real: [std.Io.Dir.max_path_bytes]u8 = undefined;
+ if (libc.realpath(path, &real)) |r| {
+ const by_link = family(std.mem.span(@as([*:0]const u8, @ptrCast(r))));
+ if (by_link != .none) return by_link;
+ }
+ const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0));
+ if (fd < 0) return .none;
+ defer _ = libc.close(fd);
+ var chunk: [64 * 1024]u8 = undefined;
+ var carry: usize = 0;
+ var total: usize = 0;
+ while (total < 16 << 20) {
+ const n = libc.read(fd, chunk[carry..].ptr, chunk.len - carry);
+ if (n <= 0) break;
+ const have = carry + @as(usize, @intCast(n));
+ total += @intCast(n);
+ // A script is no binary: its interpreter is what runs.
+ if (total == have and std.mem.startsWith(u8, chunk[0..have], "#!")) return .none;
+ if (std.mem.indexOf(u8, chunk[0..have], "BASH_VERSINFO") != null) return .bash;
+ if (std.mem.indexOf(u8, chunk[0..have], "fish_prompt") != null) return .fish;
+ // Keep the tail, so a marker cut by the chunk is still seen.
+ carry = @min(have, 16);
+ std.mem.copyForwards(u8, chunk[0..carry], chunk[have - carry .. have]);
+ }
+ return .none;
+}
+
+test "a bash under another name is still told as bash" {
+ const bash: [:0]const u8 = "/usr/bin/bash";
+ if (libc.access(bash, X_OK) != 0) return;
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ const bytes = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, bash, std.testing.allocator, .limited(16 << 20));
+ defer std.testing.allocator.free(bytes);
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "mysh", .data = bytes, .flags = .{ .permissions = .executable_file } });
+ var dir_buf: [4096]u8 = undefined;
+ const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)];
+ var path: [4200:0]u8 = undefined;
+ const p = try std.fmt.bufPrintSentinel(&path, "{s}/mysh", .{dir}, 0);
+ try std.testing.expectEqual(Family.bash, familyOf(p.ptr));
+ try std.testing.expectEqual(Family.none, familyOf("/bin/sh"));
+}
+
+const bash_rc =
+ \\[ -f "$HOME/.bashrc" ] && source "$HOME/.bashrc"
+ \\PS1='\[\e]133;A;cl=line;aid=pardes\a\]'"$PS1"'\[\e]133;B;aid=pardes\a\]'
+ \\PS2='\[\e]133;A;k=c;aid=pardes\a\]'"$PS2"'\[\e]133;B;aid=pardes\a\]'
+ \\PROMPT_COMMAND='printf "\e]133;D;%s;aid=pardes\a" "$?"'"${PROMPT_COMMAND:+;$PROMPT_COMMAND}"
+ \\if ((BASH_VERSINFO[0] * 100 + BASH_VERSINFO[1] >= 404)); then
+ \\ PS0='\e]133;C;aid=pardes\a'"$PS0"
+ \\else
+ \\ trap 'printf "\e]133;C;aid=pardes\a"' DEBUG
+ \\fi
+ \\
+;
+
+// fish -C runs after config.fish; bash --rcfile must source .bashrc itself.
+const fish_rc =
+ \\functions -c fish_prompt __pardes_user_prompt
+ \\function fish_prompt
+ \\ printf '\e]133;A;cl=line;aid=pardes\a'
+ \\ __pardes_user_prompt
+ \\ printf '\e]133;B;aid=pardes\a'
+ \\end
+ \\function __pardes_preexec --on-event fish_preexec
+ \\ printf '\e]133;C;aid=pardes\a'
+ \\end
+ \\function __pardes_postexec --on-event fish_postexec
+ \\ printf '\e]133;D;%s;aid=pardes\a' $status
+ \\end
+ \\
+;
+
+const rc_path_capacity = 256;
+
+/// The prompt files a shell sources at start. Under $XDG_RUNTIME_DIR
+/// (private to the user) there is one file per content, named by its
+/// hash and shared by every pardes, so none is left behind by a pardes
+/// that was killed: 72K of them piled up in /tmp when each host wrote
+/// its own. Without that directory each host writes private mkstemp
+/// files in /tmp and removes them at teardown, as before.
+pub const PromptFiles = struct {
+ bash_path: [rc_path_capacity:0]u8 = @splat(0),
+ bash_len: u16 = 0,
+ bash_owned: bool = false,
+ fish_path: [rc_path_capacity:0]u8 = @splat(0),
+ fish_len: u16 = 0,
+ fish_owned: bool = false,
+ fish_command: [rc_path_capacity + "source ''".len:0]u8 = @splat(0),
+ fish_command_len: u16 = 0,
+
+ pub fn init() PromptFiles {
+ var rcs: PromptFiles = .{};
+ const bash = place(&rcs.bash_path, "bash", bash_rc);
+ rcs.bash_len = bash.len;
+ rcs.bash_owned = bash.owned;
+ const fish = place(&rcs.fish_path, "fish", fish_rc);
+ rcs.fish_len = fish.len;
+ rcs.fish_owned = fish.owned;
+ if (rcs.fishPath()) |path| {
+ // Quoted for fish; a path a quote would break is not used.
+ const command = if (std.mem.indexOfAny(u8, path, "'\\") != null)
+ error.NoSpaceLeft
+ else
+ std.fmt.bufPrintSentinel(&rcs.fish_command, "source '{s}'", .{path}, 0);
+ const ok = command catch {
+ if (rcs.fish_owned) _ = libc.unlink(path.ptr);
+ rcs.fish_len = 0;
+ return rcs;
+ };
+ rcs.fish_command_len = @intCast(ok.len);
+ }
+ return rcs;
+ }
+
+ pub fn deinit(rcs: *PromptFiles) void {
+ // Removed here, not again by a signal's handler.
+ for (&fatal_rc_len, 0..) |*len, i| for ([_]?[:0]const u8{ rcs.bashPath(), rcs.fishPath() }) |mine| {
+ if (mine) |path| if (len.* == path.len and std.mem.eql(u8, fatal_rcs[i][0..len.*], path)) {
+ len.* = 0;
+ };
+ };
+ if (rcs.bashPath()) |path| if (rcs.bash_owned) {
+ _ = libc.unlink(path.ptr);
+ };
+ if (rcs.fishPath()) |path| if (rcs.fish_owned) {
+ _ = libc.unlink(path.ptr);
+ };
+ rcs.bash_len = 0;
+ rcs.fish_len = 0;
+ rcs.fish_command_len = 0;
+ }
+
+ fn bashPath(rcs: *const PromptFiles) ?[:0]const u8 {
+ if (rcs.bash_len == 0) return null;
+ return rcs.bash_path[0..rcs.bash_len :0];
+ }
+
+ fn fishPath(rcs: *const PromptFiles) ?[:0]const u8 {
+ if (rcs.fish_len == 0) return null;
+ return rcs.fish_path[0..rcs.fish_len :0];
+ }
+
+ fn fishCommand(rcs: *const PromptFiles) ?[:0]const u8 {
+ if (rcs.fish_command_len == 0) return null;
+ return rcs.fish_command[0..rcs.fish_command_len :0];
+ }
+};
+
+/// The shared file for `contents` under $XDG_RUNTIME_DIR, written
+/// beside it and renamed into place when missing or different, so a
+/// shell never reads half of one; failing that, a private /tmp file.
+fn place(path_buf: *[rc_path_capacity:0]u8, name: []const u8, contents: []const u8) struct { len: u16, owned: bool } {
+ shared: {
+ const dir = std.mem.span(std.c.getenv("XDG_RUNTIME_DIR") orelse break :shared);
+ if (dir.len == 0 or dir[0] != '/') break :shared;
+ const final = std.fmt.bufPrintSentinel(path_buf, "{s}/pardes-osc133-{s}-{x:0>16}", .{ dir, name, std.hash.Wyhash.hash(0, contents) }, 0) catch break :shared;
+ var have: [2048]u8 = undefined;
+ if (readSmall(final, &have)) |got| if (std.mem.eql(u8, got, contents)) return .{ .len = @intCast(final.len), .owned = false };
+ var tmp_buf: [rc_path_capacity:0]u8 = @splat(0);
+ var template_buf: [rc_path_capacity]u8 = undefined;
+ const tmp_template = std.fmt.bufPrint(&template_buf, "{s}.XXXXXX", .{final}) catch break :shared;
+ const n = stage(&tmp_buf, tmp_template, contents);
+ if (n == 0) break :shared;
+ if (libc.rename(tmp_buf[0..n :0].ptr, final.ptr) != 0) {
+ _ = libc.unlink(tmp_buf[0..n :0].ptr);
+ break :shared;
+ }
+ return .{ .len = @intCast(final.len), .owned = false };
+ }
+ var tmp_template: [64]u8 = undefined;
+ // Its pid in the name: one a killed editor left is swept by the
+ // next (sweepDeadRcs).
+ const template = std.fmt.bufPrint(&tmp_template, "/tmp/pardes-osc133-{s}-{d}-XXXXXX", .{ name, @as(u32, @intCast(std.c.getpid())) }) catch return .{ .len = 0, .owned = false };
+ return .{ .len = stage(path_buf, template, contents), .owned = true };
+}
+
+// Publish a path only after its private 0600 file is fully written and closed.
+fn stage(path_buf: *[rc_path_capacity:0]u8, template: []const u8, contents: []const u8) u16 {
+ const path = std.fmt.bufPrintSentinel(path_buf, "{s}", .{template}, 0) catch return 0;
+ const fd = mkstemp(path.ptr);
+ if (fd < 0) return 0;
+ if (!writeFd(fd, contents)) {
+ _ = libc.close(fd);
+ _ = libc.unlink(path.ptr);
+ return 0;
+ }
+ if (libc.close(fd) != 0) {
+ _ = libc.unlink(path.ptr);
+ return 0;
+ }
+ return @intCast(path.len);
+}
+
+test "shell family is the basename's prefix, and anything else runs unadorned" {
+ try std.testing.expectEqual(Family.fish, family("fish"));
+ try std.testing.expectEqual(Family.fish, family("/usr/bin/fish"));
+ try std.testing.expectEqual(Family.fish, family("/opt/homebrew/bin/fish"));
+ try std.testing.expectEqual(Family.bash, family("bash"));
+ try std.testing.expectEqual(Family.bash, family("/bin/bash"));
+ try std.testing.expectEqual(Family.bash, family("/usr/bin/bash-5.2"));
+ try std.testing.expectEqual(Family.fish, family("/usr/local/bin/fish-3.7"));
+ try std.testing.expectEqual(Family.none, family("/opt/fish/bin/nu"));
+ try std.testing.expectEqual(Family.none, family("/usr/bin/zsh"));
+ try std.testing.expectEqual(Family.none, family("/bin/sh"));
+ try std.testing.expectEqual(Family.none, family("nu"));
+ try std.testing.expectEqual(Family.none, family(""));
+}
+
+const bin_dirs = [_][]const u8{
+ "/usr/bin/",
+ "/bin/",
+ "/usr/local/bin/",
+ "/opt/homebrew/bin/",
+ "/opt/local/bin/",
+ "/usr/sbin/",
+};
+
+const fallbacks = [_][]const u8{
+ if (builtin.os.tag == .linux) "/usr/bin/bash" else "/bin/bash",
+ "/bin/sh",
+};
+
+pub const Spawn = struct {
+ path: [*:0]const u8,
+ argv: [6:null]?[*:0]const u8,
+};
+
+// Resolve in the parent. The path buffer and prompt files must survive through exec.
+pub fn resolve(bin: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8, prompt_rcs: *const PromptFiles) Spawn {
+ const path = find(bin, buf) orelse fallback(buf);
+ const marks: [2]?[*:0]const u8 = switch (familyOf(path)) {
+ .bash => if (prompt_rcs.bashPath()) |rc| .{ "--rcfile", rc.ptr } else .{ null, null },
+ .fish => if (prompt_rcs.fishCommand()) |command| .{ "-C", command.ptr } else .{ null, null },
+ .none => .{ null, null },
+ };
+ return .{ .path = path, .argv = .{ path, marks[0], marks[1], null, null, null } };
+}
+
+/// A command pane's shell runs its one line with job control on, so a
+/// job the line puts in the background has a process group of its own.
+/// The shell leads the terminal's session, and when it exits the kernel
+/// hangs up the terminal's foreground group: with job control off that
+/// is the shell's own, the job's too, and the job died with the command
+/// (nohup'd or not; only setsid got out, and not always in time). A
+/// shell pardes does not know runs the line as it is.
+pub fn commandArgv(path: [*:0]const u8, line: [*:0]const u8) [6:null]?[*:0]const u8 {
+ const bin = std.mem.span(path);
+ const base = if (std.mem.lastIndexOfScalar(u8, bin, '/')) |s| bin[s + 1 ..] else bin;
+ const posix_shells = [_][]const u8{ "bash", "sh", "dash", "zsh", "ksh", "mksh", "yash" };
+ for (posix_shells) |name| if (std.mem.eql(u8, base, name))
+ return .{ path, "-m", "-c", line, null, null };
+ if (family(bin) == .fish) return .{ path, "-C", "status job-control full", "-c", line, null };
+ return .{ path, "-c", line, null, null, null };
+}
+
+/// A shell by its path or its name in the usual directories, or null.
+/// A path may be under a mount this editor serves: the turn goes out
+/// with the lookups (pardes.Turn.yield).
+pub fn find(bin: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8) ?[*:0]const u8 {
+ if (bin.len == 0 or bin.len + 1 > buf.len) return null;
+ pardes.turn.yield();
+ defer pardes.turn.back();
+ if (std.mem.indexOfScalar(u8, bin, '/') != null) {
+ @memcpy(buf[0..bin.len], bin);
+ buf[bin.len] = 0;
+ const p: [*:0]const u8 = @ptrCast(buf);
+ return if (libc.access(p, X_OK) == 0 and !isDirectory(p)) p else null;
+ }
+ for (bin_dirs) |dir| {
+ if (dir.len + bin.len + 1 > buf.len) continue;
+ @memcpy(buf[0..dir.len], dir);
+ @memcpy(buf[dir.len..][0..bin.len], bin);
+ buf[dir.len + bin.len] = 0;
+ const p: [*:0]const u8 = @ptrCast(buf);
+ if (libc.access(p, X_OK) == 0) return p;
+ }
+ return null;
+}
+
+/// A directory passes access(X_OK) (it can be searched): no shell.
+pub fn isDirectory(path: [*:0]const u8) bool {
+ const d = libc.opendir(path) orelse return false;
+ _ = libc.closedir(d);
+ return true;
+}
+
+/// Why `bin` is no shell, for the words that name one (Term, Shell);
+/// null when it is one.
+pub fn refusal(bin: []const u8, said: []u8) ?[]const u8 {
+ var buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
+ if (find(bin, &buf)) |found| {
+ // A script whose `#!` names a program that is not there: its
+ // exec fails ENOENT as a missing shell's does, so told apart.
+ var interp: [256]u8 = undefined;
+ const missing = missingInterpreter(found, &interp) orelse return null;
+ return std.fmt.bufPrint(said, "interpreter {s} not found", .{missing}) catch "interpreter not found";
+ }
+ if (std.mem.indexOfScalar(u8, bin, '/') != null and bin.len < buf.len) {
+ @memcpy(buf[0..bin.len], bin);
+ buf[bin.len] = 0;
+ if (isDirectory(@ptrCast(&buf))) return std.fmt.bufPrint(said, "not a shell: {s} is a directory", .{bin}) catch "not a shell: a directory";
+ // There, but no program: said so, not "not found".
+ if (libc.access(@ptrCast(&buf), 0) == 0) return std.fmt.bufPrint(said, "not a shell: {s} is not executable", .{bin}) catch "not a shell: not executable";
+ }
+ // "not found": the words a mount reads as ENOENT.
+ return std.fmt.bufPrint(said, "shell \"{s}\" not found (a name on the usual paths, or a path to one)", .{bin}) catch "no such shell";
+}
+
+/// The program a script's `#!` line names, when it is not there to
+/// run; null for a script whose interpreter is there, or no script.
+pub fn missingInterpreter(path: [*:0]const u8, out: []u8) ?[]const u8 {
+ pardes.turn.yield();
+ defer pardes.turn.back();
+ const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0));
+ if (fd < 0) return null;
+ defer _ = libc.close(fd);
+ var head: [256]u8 = undefined;
+ const n = libc.read(fd, &head, head.len);
+ if (n < 2) return null;
+ const got = head[0..@intCast(n)];
+ if (!std.mem.startsWith(u8, got, "#!")) return null;
+ const line = got[2 .. std.mem.indexOfScalar(u8, got, '\n') orelse got.len];
+ var words = std.mem.tokenizeAny(u8, line, " \t\r");
+ const interp = words.next() orelse return null;
+ if (interp.len + 1 > out.len) return null;
+ @memcpy(out[0..interp.len], interp);
+ out[interp.len] = 0;
+ if (libc.access(@ptrCast(out.ptr), X_OK) == 0) return null;
+ return out[0..interp.len];
+}
+
+test "a script whose #! names a program not there is told apart from a missing shell" {
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "bad", .data = "#!/no/such/interp -x\n", .flags = .{ .permissions = .executable_file } });
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "good", .data = "#!/bin/sh\n", .flags = .{ .permissions = .executable_file } });
+ var dir_buf: [4096]u8 = undefined;
+ const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)];
+ var path: [4200]u8 = undefined;
+ var said: [320]u8 = undefined;
+ try std.testing.expectEqualStrings("interpreter /no/such/interp not found", refusal(try std.fmt.bufPrint(&path, "{s}/bad", .{dir}), &said).?);
+ try std.testing.expect(refusal(try std.fmt.bufPrint(&path, "{s}/good", .{dir}), &said) == null);
+ try std.testing.expect(std.mem.startsWith(u8, refusal(try std.fmt.bufPrint(&path, "{s}/none", .{dir}), &said).?, "shell \""));
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "plain", .data = "echo\n" });
+ const plain = try std.fmt.bufPrint(&path, "{s}/plain", .{dir});
+ try std.testing.expect(std.mem.endsWith(u8, refusal(plain, &said).?, "plain is not executable"));
+}
+
+fn fallback(buf: *[std.Io.Dir.max_path_bytes]u8) [*:0]const u8 {
+ for (fallbacks) |f| {
+ @memcpy(buf[0..f.len], f);
+ buf[f.len] = 0;
+ const p: [*:0]const u8 = @ptrCast(buf);
+ if (libc.access(p, X_OK) == 0) return p;
+ }
+ return @ptrCast(buf);
+}
+
+test "a command pane's line runs with job control on in the shells that have it" {
+ const want = struct {
+ fn check(path: [*:0]const u8, words: []const []const u8) !void {
+ const argv = commandArgv(path, "sleep 9 &");
+ for (words, 0..) |w, i| try std.testing.expectEqualStrings(w, std.mem.span(argv[i].?));
+ try std.testing.expect(argv[words.len] == null);
+ }
+ };
+ try want.check("/usr/bin/bash", &.{ "/usr/bin/bash", "-m", "-c", "sleep 9 &" });
+ try want.check("/bin/sh", &.{ "/bin/sh", "-m", "-c", "sleep 9 &" });
+ try want.check("/usr/bin/fish", &.{ "/usr/bin/fish", "-C", "status job-control full", "-c", "sleep 9 &" });
+ try want.check("/usr/bin/nu", &.{ "/usr/bin/nu", "-c", "sleep 9 &" });
+}
+
+test "a path is taken at its word, a name is looked up, and both pick their own marks" {
+ if (builtin.os.tag == .windows) return;
+ var buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
+ var prompt_rcs = PromptFiles.init();
+ defer prompt_rcs.deinit();
+
+ const sh = resolve("/bin/sh", &buf, &prompt_rcs);
+ try std.testing.expectEqualStrings("/bin/sh", std.mem.span(sh.path));
+ try std.testing.expect(sh.argv[1] == null);
+
+ const bash = resolve("bash", &buf, &prompt_rcs);
+ try std.testing.expect(family(std.mem.span(bash.path)) == .bash);
+ try std.testing.expectEqualStrings("--rcfile", std.mem.span(bash.argv[1].?));
+ try std.testing.expectEqualStrings(prompt_rcs.bashPath().?, std.mem.span(bash.argv[2].?));
+
+ const missing = resolve("zznosuchshell", &buf, &prompt_rcs);
+ try std.testing.expect(!std.mem.eql(u8, "zznosuchshell", std.mem.span(missing.path)));
+ try std.testing.expect(libc.access(missing.path, X_OK) == 0);
+
+ const gone = resolve("/zz/no/such/shell", &buf, &prompt_rcs);
+ try std.testing.expect(libc.access(gone.path, X_OK) == 0);
+}
+
+test "a private prompt file names its pid, and a dead pid's is swept while a live one's stays" {
+ if (builtin.os.tag == .windows) return;
+ const dead = "/tmp/pardes-osc133-bash-2147483647-AbCdEf";
+ var live_buf: [80:0]u8 = undefined;
+ const live = try std.fmt.bufPrintSentinel(&live_buf, "/tmp/pardes-osc133-bash-{d}-AbCdEf", .{@as(u32, @intCast(std.c.getppid()))}, 0);
+ defer for ([_][:0]const u8{ dead, live }) |path| {
+ _ = libc.unlink(path.ptr);
+ };
+ for ([_][:0]const u8{ dead, live }) |path| {
+ const fd = libc.open(path, .{ .CREAT = true, .ACCMODE = .WRONLY }, @as(libc.mode_t, 0o600));
+ if (fd < 0) return error.SkipZigTest;
+ _ = libc.close(fd);
+ }
+ sweepDeadRcs();
+ try std.testing.expect(libc.access(dead, 0) < 0);
+ try std.testing.expect(libc.access(live, 0) == 0);
+ // The pid is read only from that shape: an older name has none.
+ try std.testing.expectEqual(@as(?std.c.pid_t, 42), rcPid("pardes-osc133-fish-42-Xy12Zq"));
+ try std.testing.expectEqual(@as(?std.c.pid_t, null), rcPid("pardes-osc133-bash-01z3XK"));
+}
+
+test "prompt files are one per content under the runtime dir, or private and cleaned up without it" {
+ if (builtin.os.tag == .windows) return;
+ var saved_buf: [std.Io.Dir.max_path_bytes:0]u8 = @splat(0);
+ const saved: ?[:0]const u8 = if (std.c.getenv("XDG_RUNTIME_DIR")) |v| std.fmt.bufPrintSentinel(&saved_buf, "{s}", .{std.mem.span(v)}, 0) catch null else null;
+ defer _ = if (saved) |v| setenv("XDG_RUNTIME_DIR", v.ptr, 1) else testUnsetenv("XDG_RUNTIME_DIR");
+
+ var tmp = std.testing.tmpDir(.{});
+ defer tmp.cleanup();
+ var dir_buf: [std.Io.Dir.max_path_bytes:0]u8 = @splat(0);
+ const dir_len = try tmp.dir.realPath(std.testing.io, &dir_buf);
+ _ = setenv("XDG_RUNTIME_DIR", dir_buf[0..dir_len :0].ptr, 1);
+
+ // Shared: the same file for every owner, left in place, rewritten
+ // whole when what is there is not its content.
+ var a = PromptFiles.init();
+ var b = PromptFiles.init();
+ const a_bash = a.bashPath() orelse return error.TempCreateFailed;
+ try std.testing.expectEqualStrings(a_bash, b.bashPath().?);
+ try std.testing.expect(std.mem.startsWith(u8, a_bash, dir_buf[0..dir_len]));
+ const fish_command = a.fishCommand() orelse return error.MissingFishCommand;
+ var want: [rc_path_capacity + 16]u8 = undefined;
+ try std.testing.expectEqualStrings(try std.fmt.bufPrint(&want, "source '{s}'", .{a.fishPath().?}), fish_command);
+ var buf: [2048]u8 = undefined;
+ try std.testing.expectEqualStrings(bash_rc, readSmall(a_bash, &buf) orelse return error.ReadFailed);
+ try std.testing.expectEqualStrings(fish_rc, readSmall(a.fishPath().?, &buf) orelse return error.ReadFailed);
+ const stat = try @import("core").filesystem.statPath(std.testing.io, a_bash, .{});
+ try std.testing.expectEqual(0, stat.permissions.toMode() & 0o077);
+ var kept: [rc_path_capacity:0]u8 = @splat(0);
+ @memcpy(kept[0..a_bash.len], a_bash);
+ a.deinit();
+ b.deinit();
+ try std.testing.expect(libc.access(&kept, 0) == 0);
+ try tmp.dir.writeFile(std.testing.io, .{ .sub_path = std.Io.Dir.path.basename(kept[0..a_bash.len]), .data = "half" });
+ var c = PromptFiles.init();
+ defer c.deinit();
+ try std.testing.expectEqualStrings(bash_rc, readSmall(c.bashPath().?, &buf) orelse return error.ReadFailed);
+
+ // No runtime dir: private files, one per owner, gone at teardown.
+ _ = testUnsetenv("XDG_RUNTIME_DIR");
+ var d = PromptFiles.init();
+ var e = PromptFiles.init();
+ defer e.deinit();
+ const d_bash = d.bashPath() orelse return error.TempCreateFailed;
+ try std.testing.expect(!std.mem.eql(u8, d_bash, e.bashPath().?));
+ try std.testing.expect(std.mem.startsWith(u8, d_bash, "/tmp/pardes-osc133-bash-"));
+ try std.testing.expectEqual(@as(?std.c.pid_t, std.c.getpid()), rcPid(std.Io.Dir.path.basename(d_bash)));
+ @memcpy(kept[0..d_bash.len], d_bash);
+ kept[d_bash.len] = 0;
+ d.deinit();
+ try std.testing.expect(libc.access(&kept, 0) < 0);
+}
diff --git a/dev/host_io.zig b/dev/host_io.zig
index d8b8bbb3..1e03cdaf 100644
--- a/dev/host_io.zig
+++ b/dev/host_io.zig
@@ -12,168 +12,14 @@ const replica = @import("core").replica;
const daemon = @import("runtime").daemon;
const panes = @import("core").panes;
-pub const Host = struct {
- ctx: ?*anyopaque = null,
- vtable: *const VTable = &.{},
-
- pub const VTable = struct {
- wait_input: ?*const fn (ctx: ?*anyopaque, timeout_ms: u32) void = null,
- /// The shell's monotonic clock in ns: the only time the core sees.
- /// Without one, core animation moves only by `.tick` events.
- now: ?*const fn (ctx: ?*anyopaque) u64 = null,
- present: ?*const fn (ctx: ?*anyopaque, surface: *const pardes.Surface) void = null,
- post_present: ?*const fn (ctx: ?*anyopaque) void = null,
- poll_frame: ?*const fn (ctx: ?*anyopaque) void = null,
- /// Whether anyone sees a frame drawn now. A detached session with no
- /// client attached draws none (a /screen read draws its own), and
- /// the frame owed is drawn when one attaches. Absent: always.
- watched: ?*const fn (ctx: ?*anyopaque) bool = null,
- /// Detach: the terminal or window let go, the session left running
- /// for the daemon to attach again (daemon.zig).
- detach: ?*const fn (ctx: ?*anyopaque) void = null,
- /// Adopt: the shells a dead session left, asked of the daemon.
- adopt: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null,
- /// Upgrade: this process exec'd as the pardes installed since, at
- /// the step's end (upgrade.zig); `pane` hears why if it cannot be.
- upgrade: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null,
- /// Whether a newer pardes is installed at the path this process
- /// started from, to be said once (upgrade.zig): asked at a focus-in.
- newer_build: ?*const fn (ctx: ?*anyopaque) bool = null,
- spawn: ?*const fn (ctx: ?*anyopaque, pane: u8, cwd: []const u8) void = null,
- pty_write: ?*const fn (ctx: ?*anyopaque, pane: u8, bytes: []const u8) void = null,
- pty_resize: ?*const fn (ctx: ?*anyopaque, pane: u8, cols: u16, rows: u16) void = null,
- pty_signal: ?*const fn (ctx: ?*anyopaque, pane: u8, sig: pardes.PtySignal) void = null,
- close_pty: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null,
- tty_taken: ?*const fn (ctx: ?*anyopaque, pane: u8) bool = null,
- /// The name of the program holding the tty, when it is not the
- /// shell (host_io.foregroundName), in `buf`.
- fg_name: ?*const fn (ctx: ?*anyopaque, pane: u8, buf: []u8) ?[]const u8 = null,
- /// Answered at once, not queued as an effect: Kill asks while the
- /// job it saw running is still the one in the tty (host_io.killJob).
- kill_job: ?*const fn (ctx: ?*anyopaque, pane: u8) bool = null,
- write_file: ?*const fn (ctx: ?*anyopaque, pane: u8, path: []const u8, bytes: []const u8) void = null,
- write_dump: ?*const fn (ctx: ?*anyopaque, bytes: []const u8) void = null,
- watch_file: ?*const fn (ctx: ?*anyopaque, pane: u8, path: []const u8, on: bool, mode: pardes.WatchMode) void = null,
- watch_theme: ?*const fn (ctx: ?*anyopaque, generation: u32, on: bool) void = null,
- dump_themes: ?*const fn (ctx: ?*anyopaque, pane: u8) void = null,
- set_clipboard: ?*const fn (ctx: ?*anyopaque, text: []const u8) void = null,
- read_clipboard: ?*const fn (ctx: ?*anyopaque) void = null,
- open_link: ?*const fn (ctx: ?*anyopaque, url: []const u8) void = null,
- /// A plumbing rule's program (Effect.start): every host's is
- /// startDetached. Null once it runs, else why not.
- start: ?*const fn (ctx: ?*anyopaque, line: []const u8, why: []u8) ?[]const u8 = null,
- lsp: ?*const fn (ctx: ?*anyopaque, req: Lsp.Request) void = null,
- pipe: ?*const fn (ctx: ?*anyopaque, id: u32) void = null,
- /// Start the streaming search of this generation on a worker
- /// (pardes.Stream.start); absent, it runs on the loop.
- search: ?*const fn (ctx: ?*anyopaque, gen: u32) void = null,
- /// Carry the dump of handover `seq` to another window on a worker
- /// (Handover.start), which answers through the inbox's `handed`.
- hand_over: ?*const fn (ctx: ?*anyopaque, seq: u32, bytes: []const u8) void = null,
- /// Run job `token` of the pane in slot `pane` (whose serial is
- /// `serial`) on a worker (`KindJob`), answering with the `job` event;
- /// absent, it runs on the loop.
- job: ?*const fn (ctx: ?*anyopaque, pane: u8, serial: u32, token: u32) void = null,
- };
-};
+pub const Host = @import("Host.zig");
/// A kind's job (Effect.job), taken off its pane: its input, its kind's
/// `job_run` and generation; run on a worker (or here), its answer the
/// core's `job` event. Its library is held until it lands (Addon.holdJob).
/// A draw (api.draw, `draw`) is one of this process's alone: never an
/// event, its answer kept for the pane's next paint (Kind.landDraw).
-pub const KindJob = struct {
- gpa: std.mem.Allocator,
- pane: u8,
- serial: u32,
- token: u32,
- gen: u32,
- ops: *const pardes.Kind.Ops,
- in: []u8,
- /// What the job allocates (`pa_out`), freed with it; `out` the last.
- arena: std.heap.ArenaAllocator,
- out: []u8 = &.{},
- id: u32 = 0,
- /// A draw's: the core it was asked in.
- draw: ?*const pardes.Pardes = null,
-
- pub fn take(p: *pardes.Pardes, pane: u8, serial: u32, token: u32) ?*KindJob {
- const pn = p.panes[pane] orelse return null;
- const slot = pn.addon orelse return null;
- const ops = slot.ops orelse return null;
- if (pn.serial != serial or ops.job_run == null) return null;
- const at = for (&slot.jobs) |*j| {
- if (j.*) |job| if (job.token == token) break j;
- } else return null;
- const j = slot.gpa.create(KindJob) catch return null;
- j.* = .{ .gpa = slot.gpa, .pane = pane, .serial = serial, .token = token, .gen = slot.gen, .ops = ops, .in = at.*.?.in, .arena = .init(slot.gpa) };
- at.* = null;
- pardes.Addon.holdJob(ops, true);
- return j;
- }
-
- pub fn run(j: *KindJob) void {
- const Out = struct {
- fn alloc(out: [*c]pardes.Kind.c.pa_out, n: usize) callconv(.c) ?*anyopaque {
- const job: *KindJob = @ptrCast(@alignCast(out.*.ctx));
- job.out = job.arena.allocator().alignedAlloc(u8, .@"16", n) catch &.{};
- return if (job.out.len == n) job.out.ptr else null;
- }
- };
- var out: pardes.Kind.c.pa_out = .{ .alloc = Out.alloc, .ctx = j };
- const n = j.ops.job_run.?(j.in.ptr, @intCast(j.in.len), &out);
- j.out = j.out[0..@min(n, j.out.len)];
- }
-
- /// Its answer to the core, and it gone.
- pub fn land(j: *KindJob, p: *pardes.Pardes) void {
- if (j.draw != null) return pardes.Kind.landDraw(p, j);
- p.update(.{ .job = .{ .pane = j.pane, .serial = j.serial, .token = j.token, .gen = j.gen, .bytes = j.out } });
- j.drop();
- }
-
- pub fn drop(j: *KindJob) void {
- pardes.Addon.holdJob(j.ops, false);
- j.gpa.free(j.in);
- j.arena.deinit();
- j.gpa.destroy(j);
- }
-
- /// On a worker of `io`, posting itself to `sink` done: a host's `job`.
- pub fn start(io: std.Io, p: *pardes.Pardes, tasks: *selection_pipe.Tasks, pane: u8, serial: u32, token: u32, ctx: ?*anyopaque, sink: *const fn (?*anyopaque, *KindJob) void) void {
- const j = take(p, pane, serial, token) orelse return;
- if (!go(io, tasks, j, ctx, sink)) here(j, p);
- }
-
- /// `j` on a worker of `io`, posting itself to `sink` done; false when
- /// none could take it.
- pub fn go(io: std.Io, tasks: *selection_pipe.Tasks, j: *KindJob, ctx: ?*anyopaque, sink: *const fn (?*anyopaque, *KindJob) void) bool {
- next_id +%= 1;
- j.id = next_id | 0x8000_0000;
- const work = struct {
- fn work(job: *KindJob, c: ?*anyopaque, s: *const fn (?*anyopaque, *KindJob) void) void {
- job.run();
- s(c, job);
- }
- }.work;
- if (tasks.full()) return false;
- const future = io.concurrent(work, .{ j, ctx, sink }) catch return false;
- _ = tasks.add(.{ .id = j.id, .future = future });
- return true;
- }
-
- var next_id: u32 = 0;
-
- fn here(j: *KindJob, p: *pardes.Pardes) void {
- j.run();
- j.land(p);
- }
-
- /// No workers (a test, the fallback): it runs on the loop, at once.
- pub fn runHere(p: *pardes.Pardes, pane: u8, serial: u32, token: u32) void {
- here(take(p, pane, serial, token) orelse return, p);
- }
-};
+pub const KindJob = @import("KindJob.zig");
/// PARDES_TEST_CLOCK makes a shell's `Host.now` answer a virtual clock
/// instead of `std.Io.Clock.awake`, moved only when a timed wait runs out --
@@ -349,1497 +195,11 @@ pub const Fallback = struct {
/// full output queue never holds them up), and file-watch news. Output and
/// end of file of a reader that was canceled or replaced, and an answer to
/// a language query since superseded, are dropped here.
-pub const Inbox = struct {
- pub const Msg = union(enum) {
- output: struct { pane: u8, gen: u32, bytes: []u8 },
- eof: struct { pane: u8, gen: u32, failure: ?anyerror = null },
- lsp: struct { id: u32, rows: ?[]u8 },
- lsp_status: []u8,
- pipe: selection_pipe.Response,
- /// A streaming search's rows (pardes.Stream), of whatever generation:
- /// the core drops a stale one.
- search: pardes.Stream.Batch,
- /// How a handover went (Handover.zig): `words` is where it went, or
- /// why it did not; gpa-owned.
- handed: struct { seq: u32, ok: bool, words: []u8 },
- /// A kind's job done on a worker (KindJob), never dropped.
- kind_job: *KindJob,
- files_changed,
- fs_ready,
- /// The daemon asks for the window again (`pardes-gui --attach`).
- window,
- /// A shell a dead session left, its pty's master (Adopt); pid 0 is
- /// the last of them told.
- adopted: struct { pid: libc.pid_t, fd: c_int },
-
- pub fn deinit(m: Msg, gpa: std.mem.Allocator, lsp_allocator: std.mem.Allocator) void {
- switch (m) {
- .output => |o| gpa.free(o.bytes),
- .lsp => |l| if (l.rows) |rows| lsp_allocator.free(rows),
- .lsp_status => |t| lsp_allocator.free(t),
- .pipe => |response_value| {
- var response = response_value;
- response.deinit(gpa);
- },
- .search => |b| b.deinit(gpa),
- .handed => |h| gpa.free(h.words),
- .kind_job => |j| j.drop(),
- .adopted => |a| if (a.fd >= 0) {
- _ = libc.close(a.fd);
- },
- .eof, .files_changed, .fs_ready, .window => {},
- }
- }
- };
-
- pub const capacity = 512;
- pub const output_capacity = capacity - pardes.MAX_PANES;
-
- pub const Batch = struct {
- items: [capacity + 2 * selection_pipe.Tasks.capacity + 2]Msg = undefined,
- len: usize = 0,
-
- pub fn slice(batch: *Batch) []Msg {
- return batch.items[0..batch.len];
- }
- };
-
- gpa: std.mem.Allocator,
- lsp_allocator: std.mem.Allocator,
- /// The query in flight; the UI thread's alone (spawnLsp, teardown).
- lsp_task: ?Lsp.Task = null,
- /// Wakes the host's loop after a push from another thread: an SDL
- /// event, a macOS runtime callback. Null: nobody to wake (tests).
- wake_fn: ?*const fn (?*anyopaque) void = null,
- wake_ctx: ?*anyopaque = null,
- /// The process's Io: its terminal readers wait for space on `space`.
- io: std.Io,
- mutex: std.Io.Mutex = .init,
- space: std.Io.Condition = .init,
- items: [capacity]Msg = undefined,
- head: usize = 0,
- len: usize = 0,
- closed: bool = false,
- files_changed: bool = false,
- readers: [pardes.MAX_PANES]?u32 = @splat(null),
- waiting: usize = 0,
- lsp_id: ?u32 = null,
- completions: [2 * selection_pipe.Tasks.capacity + 1]Msg = undefined,
- completion_len: usize = 0,
-
- pub fn lock(q: *Inbox) void {
- q.mutex.lockUncancelable(q.io);
- }
-
- pub fn unlock(q: *Inbox) void {
- q.mutex.unlock(q.io);
- }
-
- pub fn wake(q: *Inbox) void {
- if (q.wake_fn) |f| f(q.wake_ctx);
- }
-
- pub fn acceptReader(q: *Inbox, pane: u8, gen: u32) void {
- q.lock();
- defer q.unlock();
- std.debug.assert(q.readers[pane] == null);
- q.readers[pane] = gen;
- }
-
- pub fn cancelReader(q: *Inbox, pane: u8, gen: u32) void {
- q.lock();
- defer q.unlock();
- if (q.readers[pane] != gen) return;
- q.readers[pane] = null;
- var i: usize = 0;
- while (i < q.len) {
- const msg = q.items[(q.head + i) % q.items.len];
- const matches = switch (msg) {
- .output => |o| o.pane == pane and o.gen == gen,
- .eof => |e| e.pane == pane and e.gen == gen,
- else => false,
- };
- if (matches) q.removeAt(i).deinit(q.gpa, q.lsp_allocator) else i += 1;
- }
- q.space.broadcast(q.io);
- }
-
- pub fn pushOutput(q: *Inbox, pane: u8, gen: u32, bytes: []u8) bool {
- q.lock();
- while (!q.closed and q.readers[pane] == gen and q.len >= output_capacity) {
- q.waiting += 1;
- q.space.waitUncancelable(q.io, &q.mutex);
- q.waiting -= 1;
- }
- if (q.closed or q.readers[pane] != gen) {
- q.unlock();
- q.gpa.free(bytes);
- return false;
- }
- q.items[(q.head + q.len) % q.items.len] = .{ .output = .{ .pane = pane, .gen = gen, .bytes = bytes } };
- q.len += 1;
- q.unlock();
- q.wake();
- return true;
- }
-
- fn removeAt(q: *Inbox, offset: usize) Msg {
- const removed = q.items[(q.head + offset) % q.items.len];
- var i = offset;
- while (i + 1 < q.len) : (i += 1)
- q.items[(q.head + i) % q.items.len] = q.items[(q.head + i + 1) % q.items.len];
- q.len -= 1;
- return removed;
- }
-
- pub fn discardLsp(q: *Inbox) void {
- for (q.completions[0..q.completion_len], 0..) |msg, i| if (msg == .lsp) {
- msg.deinit(q.gpa, q.lsp_allocator);
- q.completion_len -= 1;
- std.mem.copyForwards(Msg, q.completions[i..q.completion_len], q.completions[i + 1 .. q.completion_len + 1]);
- return;
- };
- }
-
- pub fn push(q: *Inbox, m: Msg) void {
- if (m == .output) {
- _ = q.pushOutput(m.output.pane, m.output.gen, m.output.bytes);
- return;
- }
- q.lock();
- if (q.closed) {
- q.unlock();
- m.deinit(q.gpa, q.lsp_allocator);
- return;
- }
- switch (m) {
- .files_changed => q.files_changed = true,
- .lsp, .pipe, .kind_job => {
- if (m == .lsp) {
- if (q.lsp_id != m.lsp.id) {
- q.unlock();
- m.deinit(q.gpa, q.lsp_allocator);
- return;
- }
- q.discardLsp();
- }
- std.debug.assert(q.completion_len < q.completions.len);
- q.completions[q.completion_len] = m;
- q.completion_len += 1;
- },
- else => {
- if (m == .eof) {
- if (q.readers[m.eof.pane] != m.eof.gen) {
- q.unlock();
- return;
- }
- std.debug.assert(q.len < q.items.len);
- } else if (q.len >= output_capacity) {
- q.unlock();
- m.deinit(q.gpa, q.lsp_allocator);
- return;
- }
- q.items[(q.head + q.len) % q.items.len] = m;
- q.len += 1;
- },
- }
- q.unlock();
- q.wake();
- }
-
- pub fn take(q: *Inbox) Batch {
- var batch: Batch = .{};
- q.takeInto(&batch);
- return batch;
- }
-
- /// `take` into a batch the caller keeps: an idle wakeup copies nothing
- /// (the batch is some 20 KB, and was built and returned by value each
- /// time).
- pub fn takeInto(q: *Inbox, batch: *Batch) void {
- batch.len = 0;
- q.lock();
- defer q.unlock();
- if (q.len == 0 and !q.files_changed and q.completion_len == 0) return;
- while (q.len > 0) {
- batch.items[batch.len] = q.items[q.head];
- batch.len += 1;
- q.head = (q.head + 1) % q.items.len;
- q.len -= 1;
- }
- q.head = 0;
- if (q.files_changed) {
- batch.items[batch.len] = .files_changed;
- batch.len += 1;
- q.files_changed = false;
- }
- @memcpy(batch.items[batch.len..][0..q.completion_len], q.completions[0..q.completion_len]);
- batch.len += q.completion_len;
- q.completion_len = 0;
- q.space.broadcast(q.io);
- }
-
- pub fn discardCompletions(q: *Inbox) void {
- q.lock();
- defer q.unlock();
- q.lsp_id = null;
- for (q.completions[0..q.completion_len]) |msg| msg.deinit(q.gpa, q.lsp_allocator);
- q.completion_len = 0;
- }
-
- pub fn close(q: *Inbox) void {
- q.lock();
- q.closed = true;
- q.files_changed = false;
- q.readers = @splat(null);
- q.space.broadcast(q.io);
- q.unlock();
- q.discardCompletions();
- q.lock();
- defer q.unlock();
- while (q.len > 0) {
- const m = q.items[q.head];
- m.deinit(q.gpa, q.lsp_allocator);
- q.head = (q.head + 1) % q.items.len;
- q.len -= 1;
- }
- q.head = 0;
- }
-
- pub fn deinit(q: *Inbox) void {
- q.close();
- std.debug.assert(q.waiting == 0);
- }
-
- /// A pane's reader: its pty's output pushed as it comes, then its end
- /// of file; canceled (closePty), it pushes nothing more.
- pub fn startReader(q: *Inbox, pty: std.Io.File, pane: u8, gen: u32) !std.Io.Future(void) {
- q.acceptReader(pane, gen);
- errdefer q.cancelReader(pane, gen);
- return q.io.concurrent(readPty, .{ q, pty, pane, gen });
- }
-
- fn readPty(q: *Inbox, pty: std.Io.File, pane: u8, gen: u32) void {
- var buf: [0x10000]u8 = undefined;
- var failure: ?anyerror = null;
- while (true) {
- const n = pty.readStreaming(q.io, &.{&buf}) catch |err| switch (err) {
- // A pty whose child has gone answers EIO: its end of file.
- error.EndOfStream, error.InputOutput => break,
- error.Canceled => return,
- else => {
- failure = err;
- break;
- },
- };
- if (n == 0) continue;
- const bytes = q.gpa.dupe(u8, buf[0..n]) catch |err| {
- failure = err;
- break;
- };
- if (!q.pushOutput(pane, gen, bytes)) return;
- }
- q.push(.{ .eof = .{ .pane = pane, .gen = gen, .failure = failure } });
- }
-
- /// Starts `e`, its answer let in and every older one's turned away.
- pub fn startLsp(q: *Inbox, core: *pardes.Pardes, e: Lsp.Request) void {
- q.lock();
- q.lsp_id = e.id;
- q.discardLsp();
- q.unlock();
- // The old query's waits are cancelation points: its join is short, and
- // what it still delivers carries an id the queue now rejects.
- Lsp.start(q.io, q.lsp_allocator, core, &q.lsp_task, e, q, pushLspRows);
- }
-
- fn pushLspRows(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void {
- const q: *Inbox = @ptrCast(@alignCast(ctx orelse return));
- q.push(.{ .lsp = .{ .id = id, .rows = rows } });
- }
-
- /// The language client's status line (lsp.setStatusSink).
- pub fn lspStatus(ctx: ?*anyopaque, text: []const u8) void {
- const q: *Inbox = @ptrCast(@alignCast(ctx orelse return));
- const copy = q.lsp_allocator.dupe(u8, text) catch return;
- q.push(.{ .lsp_status = copy });
- }
-
- /// A `|` job's answer (selection_pipe.start's sink).
- pub fn pushJob(ctx: ?*anyopaque, j: *KindJob) void {
- const q: *Inbox = @ptrCast(@alignCast(ctx.?));
- q.push(.{ .kind_job = j });
- }
-
- pub fn pushPipe(ctx: ?*anyopaque, response: selection_pipe.Response) void {
- const q: *Inbox = @ptrCast(@alignCast(ctx.?));
- q.push(.{ .pipe = response });
- }
-
- /// A handover's end (Handover.Job.post).
- pub fn pushHanded(ctx: ?*anyopaque, seq: u32, ok: bool, words: []const u8) void {
- const q: *Inbox = @ptrCast(@alignCast(ctx.?));
- const copy = q.gpa.dupe(u8, words) catch return;
- q.push(.{ .handed = .{ .seq = seq, .ok = ok, .words = copy } });
- }
-
- /// A streaming search's batch (pardes.Stream.start's sink). Never
- /// dropped for want of room, as output is not: the worker waits for
- /// room, a wait its cancel ends (false: it stops).
- pub fn pushSearch(ctx: ?*anyopaque, batch: pardes.Stream.Batch) bool {
- const q: *Inbox = @ptrCast(@alignCast(ctx.?));
- q.lock();
- while (!q.closed and q.len >= output_capacity) {
- q.waiting += 1;
- q.space.wait(q.io, &q.mutex) catch {
- q.waiting -= 1;
- q.unlock();
- batch.deinit(q.gpa);
- return false;
- };
- q.waiting -= 1;
- }
- if (q.closed) {
- q.unlock();
- batch.deinit(q.gpa);
- return false;
- }
- q.items[(q.head + q.len) % q.items.len] = .{ .search = batch };
- q.len += 1;
- q.unlock();
- q.wake();
- return true;
- }
-
- /// A watched child exited (setExitWake): wake the loop, which takes it.
- pub fn wakeForExit(ctx: ?*anyopaque) void {
- const q: *Inbox = @ptrCast(@alignCast(ctx.?));
- q.wake();
- }
-};
-
-pub const Lsp = struct {
- pub const Request = struct {
- id: u32,
- kind: pardes.lsp.Kind,
- pane: u8,
- offset: u32,
- arg: []const u8,
- };
-
- pub const Task = struct {
- id: u32,
- future: std.Io.Future(void),
- };
-
- /// One language query, owned by the worker that runs it.
- pub const Job = struct {
- callstack_depth: u8 = pardes.lsp.callstack_default_depth,
- dirty: bool = false,
- id: u32,
- kind: pardes.lsp.Kind,
- offset: u32,
- path: []u8,
- source: [:0]u8,
- arg: []u8,
- root: []u8,
- /// The other open files, for a query that can reach them.
- others: []pardes.lsp.Doc = &.{},
-
- pub fn free(job: *Job, gpa: std.mem.Allocator) void {
- gpa.free(job.path);
- gpa.free(job.source);
- gpa.free(job.arg);
- gpa.free(job.root);
- for (job.others) |doc| {
- gpa.free(doc.path);
- gpa.free(doc.source);
- }
- gpa.free(job.others);
- gpa.destroy(job);
- }
- };
-
- // Copy before starting a worker; the editor may replace any source slice afterward.
- pub fn snapshot(gpa: std.mem.Allocator, core: *const pardes.Pardes, req: Request) !*Job {
- if (req.pane >= core.panes.len) return error.NoPane;
- const pane = core.panes[req.pane] orelse return error.NoPane;
- const file = pane.file;
- const job = try gpa.create(Job);
- errdefer gpa.destroy(job);
- const declared_path = if (file) |f| f.path else "";
- const path = try gpa.dupe(u8, filesystem.localPath(declared_path) orelse declared_path);
- errdefer gpa.free(path);
- const source = try gpa.dupeSentinel(u8, if (file) |f| f.content else "", 0);
- errdefer gpa.free(source);
- const arg = try gpa.dupe(u8, req.arg);
- errdefer gpa.free(arg);
- const declared_root = if (file) |f| pardes.panes.Dir.ofName(f.path) else pane.cwdSlice();
- const root = try gpa.dupe(u8, filesystem.localPath(declared_root) orelse declared_root);
- errdefer gpa.free(root);
- job.* = .{
- .callstack_depth = core.settings.callstack_depth,
- .dirty = pardes.tagline.dirty(pane),
- .id = req.id,
- .kind = req.kind,
- .offset = req.offset,
- .path = path,
- .source = source,
- .arg = arg,
- .root = root,
- };
- // ponytail: a copy of every open file per such query; a server
- // already told of one is sent nothing more (syncDoc).
- // Lspwhy too: the query it explains may be one of those, and its
- // trace shows each file synced first.
- if (pardes.lsp.reachesOtherFiles(req.kind) or req.kind == .explain) {
- var others: std.ArrayList(pardes.lsp.Doc) = .empty;
- errdefer {
- for (others.items) |doc| {
- gpa.free(doc.path);
- gpa.free(doc.source);
- }
- others.deinit(gpa);
- }
- var copied: usize = 0;
- for (core.panes, 0..) |slot, i| {
- const other = slot orelse continue;
- if (i == req.pane) continue;
- const f = other.file orelse continue;
- if (f.output != null) continue;
- if (copied + f.content.len > pardes.memory.limits.lsp_snapshot_bytes) continue;
- copied += f.content.len;
- const local = filesystem.localPath(f.path) orelse continue;
- const other_path = try gpa.dupe(u8, local);
- const other_source = gpa.dupeSentinel(u8, f.content, 0) catch |err| {
- gpa.free(other_path);
- return err;
- };
- try others.append(gpa, .{ .path = other_path, .source = other_source });
- }
- job.others = try others.toOwnedSlice(gpa);
- }
- return job;
- }
-
- // Null is failure; the receiver frees non-null rows with the job's allocator.
- pub const Deliver = *const fn (ctx: ?*anyopaque, id: u32, rows: ?[]u8) void;
-
- /// Start `req` on a worker that hands its rows to `deliver`, the query
- /// in `task` canceled first. One that cannot start is answered (no rows)
- /// and reported here.
- pub fn start(io: std.Io, gpa: std.mem.Allocator, core: *pardes.Pardes, task: *?Task, req: Request, ctx: ?*anyopaque, deliver: Deliver) void {
- if (task.*) |*old| {
- old.future.cancel(io);
- task.* = null;
- }
- const job = snapshot(gpa, core, req) catch |err| {
- core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } });
- return core.reportError(req.pane, "lsp", err);
- };
- const future = io.concurrent(work, .{ io, gpa, job, ctx, deliver }) catch |err| {
- job.free(gpa);
- core.update(.{ .lsp_resp = .{ .id = req.id, .rows = null } });
- return core.reportError(req.pane, "lsp", err);
- };
- task.* = .{ .id = req.id, .future = future };
- }
-
- pub fn work(io: std.Io, gpa: std.mem.Allocator, job: *Job, ctx: ?*anyopaque, deliver: Deliver) void {
- defer job.free(gpa);
- // The query's memory is the fixed region memory.zig reserved at
- // startup: a hard bound, reused by each query in turn.
- const region = pardes.memory.takeLspQuery() orelse {
- deliver(ctx, job.id, null);
- return;
- };
- var arena: std.heap.FixedBufferAllocator = .init(region);
- defer pardes.memory.giveLspQuery(arena.end_index);
- var out: std.Io.Writer.Allocating = .init(gpa);
- defer out.deinit();
- pardes.lsp.query(io, arena.allocator(), .{
- .kind = job.kind,
- .path = job.path,
- .source = job.source,
- .offset = job.offset,
- .arg = job.arg,
- .root = job.root,
- .others = job.others,
- .callstack_depth = job.callstack_depth,
- .dirty = job.dirty,
- .budget = &arena,
- }, &out.writer) catch {
- deliver(ctx, job.id, null);
- return;
- };
- const rows = out.toOwnedSlice() catch {
- deliver(ctx, job.id, null);
- return;
- };
- deliver(ctx, job.id, rows);
- }
-
- test "a snapshot owns every byte the backend will read" {
- if (pardes.Term.ops == null) return error.SkipZigTest; // a terminal pane's snapshot
- const gpa = std.testing.allocator;
- const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
- defer core.deinit();
-
- core.settings.callstack_depth = 16;
- var needle: [6]u8 = "needle".*;
- const job = try snapshot(gpa, core, .{
- .id = 7,
- .kind = .status,
- .pane = @intCast(core.view().active),
- .offset = 0,
- .arg = &needle,
- });
- defer job.free(gpa);
-
- core.settings.callstack_depth = 2;
- try std.testing.expectEqual(@as(u8, 16), job.callstack_depth);
- try std.testing.expectEqual(@as(u32, 7), job.id);
- try std.testing.expectEqual(pardes.lsp.Kind.status, job.kind);
- try std.testing.expectEqualStrings("needle", job.arg);
- try std.testing.expect(job.arg.ptr != &needle);
- try std.testing.expectEqualStrings("", job.path);
- try std.testing.expectEqual(@as(usize, 0), job.source.len);
- try std.testing.expectEqual(@as(u8, 0), job.source[0]);
- const pane = core.panes[core.view().active].?;
- try std.testing.expectEqualStrings(pane.cwdSlice(), job.root);
- if (job.root.len > 0) try std.testing.expect(job.root.ptr != pane.cwdSlice().ptr);
- }
-
- test "LSP snapshot frees every partially copied field on allocation failure" {
- const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true });
- defer core.deinit();
- _ = try core.setTestFile("const copied = true;\n");
- const Snapshot = struct {
- fn check(gpa: std.mem.Allocator, p: *const pardes.Pardes) !void {
- const job = try snapshot(gpa, p, .{
- .id = 7,
- .kind = .hover,
- .pane = @intCast(p.view().active),
- .offset = 6,
- .arg = "query",
- });
- defer job.free(gpa);
- try std.testing.expectEqualStrings("const copied = true;\n", job.source);
- }
- };
- try std.testing.checkAllAllocationFailures(std.testing.allocator, Snapshot.check, .{core});
- }
-
- test "LSP snapshots translate explicit OS paths once and retain virtual names" {
- const gpa = std.testing.allocator;
- const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
- defer core.deinit();
- const pane = try core.setTestFile("const value = true;\n");
- for ([_]struct { path: []const u8, native: []const u8 }{
- .{ .path = "/n/os/project/file.zig", .native = "/project/file.zig" },
- .{ .path = "/n/os/n/os/project/file.zig", .native = "/n/os/project/file.zig" },
- .{ .path = "/virtual/src/file.zig", .native = "/virtual/src/file.zig" },
- }) |case| {
- const replacement = try gpa.dupe(u8, case.path);
- gpa.free(pane.file.?.path);
- pane.file.?.path = replacement;
- const job = try snapshot(gpa, core, .{ .id = 1, .kind = .hover, .pane = @intCast(core.view().active), .offset = 0, .arg = "" });
- defer job.free(gpa);
- try std.testing.expectEqualStrings(case.native, job.path);
- try std.testing.expectEqualStrings(std.Io.Dir.path.dirname(case.native).?, job.root);
- try std.testing.expectEqualStrings(case.path, pane.file.?.path);
- }
- }
-
- test "a pane that is gone yields no job rather than a null deref" {
- const gpa = std.testing.allocator;
- const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
- defer core.deinit();
-
- // The effect is drained after the core has moved on, so the pane it names
- // may already have been deleted. Every shell open-coded this check.
- const empty = for (core.panes, 0..) |slot, id| {
- if (slot == null) break @as(u8, @intCast(id));
- } else return error.NoEmptyPane;
- try std.testing.expectError(error.NoPane, snapshot(gpa, core, .{
- .id = 1,
- .kind = .definition,
- .pane = empty,
- .offset = 0,
- .arg = "",
- }));
- }
-
- test "work consumes the job and hands its rows to the sink" {
- const gpa = std.testing.allocator;
- const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
- defer core.deinit();
-
- const Sink = struct {
- var seen_id: u32 = 0;
- var seen_rows: ?[]u8 = null;
- fn take(_: ?*anyopaque, id: u32, rows: ?[]u8) void {
- seen_id = id;
- seen_rows = rows;
- }
- };
- Sink.seen_id = 0;
- Sink.seen_rows = null;
-
- const job = try snapshot(gpa, core, .{
- .id = 42,
- .kind = .status,
- .pane = @intCast(core.view().active),
- .offset = 0,
- .arg = "",
- });
- work(std.testing.io, gpa, job, null, Sink.take);
-
- // `status` is the one kind that answers with no file and no cursor, which
- // is what makes it assertable here without a language server on the box.
- try std.testing.expectEqual(@as(u32, 42), Sink.seen_id);
- const rows = Sink.seen_rows orelse return error.SinkNeverCalled;
- defer gpa.free(rows);
- }
+pub const Inbox = @import("Inbox.zig");
- test "LSP edit query failure leaves text and undo untouched before a successful retry" {
- if (!pardes.lsp.supports.contains(.format)) return;
- const Sink = struct {
- core: *pardes.Pardes,
- gpa: std.mem.Allocator,
- calls: usize = 0,
- failed: bool = false,
+pub const Lsp = @import("Lsp.zig");
- fn take(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void {
- const self: *@This() = @ptrCast(@alignCast(ctx.?));
- defer if (rows) |text| self.gpa.free(text);
- self.calls += 1;
- self.failed = rows == null;
- self.core.update(.{ .lsp_resp = .{ .id = id, .rows = rows } });
- }
- };
- const gpa = std.testing.allocator;
- for ([_]pardes.lsp.Kind{ .format, .rename }) |kind| {
- const core = try pardes.Pardes.init(gpa, .{ .tty_only = true });
- defer core.deinit();
- const pane = try core.setTestFile("const value=1;\n");
- const path = try gpa.dupe(u8, "/file.zig");
- gpa.free(pane.file.?.path);
- pane.file.?.path = path;
- pane.body.cur_col = 6;
- const revision = pane.file.?.revision;
- const undo_len = pane.file.?.history.journal.done;
- var failing = std.testing.FailingAllocator.init(gpa, .{});
- var sink: Sink = .{ .core = core, .gpa = failing.allocator() };
- for ([_]bool{ true, false }) |fail| {
- failing.fail_index = std.math.maxInt(usize);
- core.lspRequest(core.view().active, kind, "renamed");
- const job = try snapshot(failing.allocator(), core, .{
- .id = core.lsp_ask.wait.?.id,
- .kind = kind,
- .pane = @intCast(core.view().active),
- .offset = 6,
- .arg = "renamed",
- });
- if (fail) failing.fail_index = failing.alloc_index;
- work(std.testing.io, failing.allocator(), job, &sink, Sink.take);
- try std.testing.expectEqual(fail, sink.failed);
- try std.testing.expect(core.lsp_ask.wait == null);
- if (fail) {
- try std.testing.expectEqualStrings("const value=1;\n", pane.file.?.content);
- try std.testing.expectEqual(revision, pane.file.?.revision);
- try std.testing.expectEqual(undo_len, pane.file.?.history.journal.done);
- } else {
- try std.testing.expectEqualStrings(if (kind == .format) "const value = 1;\n" else "const renamed=1;\n", pane.file.?.content);
- try std.testing.expectEqual(undo_len + 1, pane.file.?.history.journal.done);
- }
- }
- try std.testing.expectEqual(@as(usize, 2), sink.calls);
- }
- }
-
- test "LSP work delivers failure when transferring result ownership cannot allocate" {
- if (!pardes.lsp.supports.contains(.status)) return;
- const TransferAllocator = struct {
- failed: bool = false,
- fail_copy: bool = false,
- fn alloc(ctx: *anyopaque, len: usize, alignment: std.mem.Alignment, ra: usize) ?[*]u8 {
- const self: *@This() = @ptrCast(@alignCast(ctx));
- if (self.fail_copy) {
- self.failed = true;
- return null;
- }
- return std.testing.allocator.rawAlloc(len, alignment, ra);
- }
- fn resize(_: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) bool {
- return std.testing.allocator.rawResize(bytes, alignment, len, ra);
- }
- fn remap(ctx: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, len: usize, ra: usize) ?[*]u8 {
- const self: *@This() = @ptrCast(@alignCast(ctx));
- if (len < bytes.len) {
- self.fail_copy = true;
- return null;
- }
- return std.testing.allocator.rawRemap(bytes, alignment, len, ra);
- }
- fn free(_: *anyopaque, bytes: []u8, alignment: std.mem.Alignment, ra: usize) void {
- std.testing.allocator.rawFree(bytes, alignment, ra);
- }
- };
- const Sink = struct {
- calls: usize = 0,
- id: u32 = 0,
- rows: ?[]u8 = null,
- fn take(ctx: ?*anyopaque, id: u32, rows: ?[]u8) void {
- const self: *@This() = @ptrCast(@alignCast(ctx.?));
- self.calls += 1;
- self.id = id;
- self.rows = rows;
- }
- };
- var allocator: TransferAllocator = .{};
- const gpa: std.mem.Allocator = .{ .ptr = &allocator, .vtable = &.{
- .alloc = TransferAllocator.alloc,
- .resize = TransferAllocator.resize,
- .remap = TransferAllocator.remap,
- .free = TransferAllocator.free,
- } };
- const core = try pardes.Pardes.init(std.testing.allocator, .{ .tty_only = true });
- defer core.deinit();
- const job = try snapshot(gpa, core, .{ .id = 37, .kind = .status, .pane = @intCast(core.view().active), .offset = 0, .arg = "" });
- var sink: Sink = .{};
- work(std.testing.io, gpa, job, &sink, Sink.take);
- if (sink.rows) |rows| gpa.free(rows);
- try std.testing.expect(allocator.failed);
- try std.testing.expectEqual(@as(usize, 1), sink.calls);
- try std.testing.expectEqual(@as(u32, 37), sink.id);
- try std.testing.expect(sink.rows == null);
- }
-};
-
-pub const Shell = struct {
- const X_OK: c_int = 1;
-
- extern "c" fn mkstemp(template: [*:0]u8) c_int;
- extern "c" fn setenv(name: [*:0]const u8, value: [*:0]const u8, overwrite: c_int) c_int;
-
- const path_capacity = 4096;
- const max_path_files = 64;
-
- // Repair only the system-only PATH inherited from a macOS GUI launch.
- fn adoptSystemPath() void {
- if (comptime builtin.os.tag != .macos) return;
- var buf: [path_capacity]u8 = undefined;
- var len: usize = 0;
- collectSystemPath("/etc/paths", "/etc/paths.d", &buf, &len);
- if (len == 0) return;
- const system = buf[0..len];
-
- const current: []const u8 = if (libc.getenv("PATH")) |p| std.mem.span(p) else "";
- if (!allEntriesWithin(current, system)) return;
- if (std.mem.eql(u8, current, system)) return;
-
- var out: [path_capacity:0]u8 = undefined;
- if (len >= out.len) return;
- @memcpy(out[0..len], system);
- out[len] = 0;
- _ = setenv("PATH", out[0..len :0].ptr, 1);
- }
-
- // Run in the parent before forking; children borrow the completed prompt files.
- pub fn prepare() PromptFiles {
- adoptSystemPath();
- if (comptime builtin.os.tag.isDarwin())
- _ = setenv("BASH_SILENCE_DEPRECATION_WARNING", "1", 1);
- sweepDeadRcs();
- const rcs = PromptFiles.init();
- // A private file goes at a fatal signal too, not only at Exit.
- for ([_]?[:0]const u8{ if (rcs.bash_owned) rcs.bashPath() else null, if (rcs.fish_owned) rcs.fishPath() else null }, 0..) |owned, i| {
- const path = owned orelse continue;
- @memcpy(fatal_rcs[i][0..path.len], path);
- fatal_rcs[i][path.len] = 0;
- fatal_rc_len[i] = path.len;
- }
- ninep_io.fatal_cleanup = unlinkOwnedRcs;
- return rcs;
- }
-
- /// This process's private prompt files, where a fatal signal's handler
- /// can reach them (unlinkOwnedRcs).
- var fatal_rcs: [2][rc_path_capacity:0]u8 = undefined;
- var fatal_rc_len: [2]usize = .{ 0, 0 };
-
- /// Removes this process's private prompt files. Async-signal-safe (two
- /// unlinks): SIGTERM and SIGHUP call it before the signal's death.
- pub fn unlinkOwnedRcs() void {
- for (&fatal_rc_len, 0..) |*len, i| {
- const n = len.*;
- if (n == 0) continue;
- len.* = 0;
- _ = libc.unlink(fatal_rcs[i][0..n :0].ptr);
- }
- }
-
- /// Removes /tmp's `pardes-osc133-<shell>-<pid>-XXXXXX` files whose pid
- /// is gone (kill(pid, 0) answers ESRCH): what a killed or crashed
- /// editor left. A live pid's, one of another user's, or a name of
- /// another shape is left alone.
- fn sweepDeadRcs() void {
- const dir = std.c.opendir("/tmp") orelse return;
- defer _ = std.c.closedir(dir);
- var dead: [64][64]u8 = undefined;
- var dead_len: [64]usize = undefined;
- var n: usize = 0;
- while (std.c.readdir(dir)) |ent| {
- const name = std.mem.sliceTo(@as([*:0]const u8, @ptrCast(&ent.name)), 0);
- const pid = rcPid(name) orelse continue;
- // This pid's are this process's, but in an upgraded one: those
- // were its old image's (upgrade.zig), and its own come after.
- if (pid == std.c.getpid() and @import("runtime").upgrade.resumed == null) continue;
- if (pid != std.c.getpid() and std.posix.errno(std.c.kill(pid, @fromBackingInt(@intCast(0)))) != .SRCH) continue;
- if (name.len >= 64 or n == dead.len) continue;
- @memcpy(dead[n][0..name.len], name);
- dead_len[n] = name.len;
- n += 1;
- }
- for (dead[0..n], dead_len[0..n]) |*entry, len| {
- var path_buf: [80:0]u8 = undefined;
- const path = std.fmt.bufPrintSentinel(&path_buf, "/tmp/{s}", .{entry[0..len]}, 0) catch continue;
- const facts = ninep_io.statNoFollow(path) orelse continue;
- if (facts.mode & 0o170000 != 0o100000 or facts.uid != libc.getuid()) continue;
- _ = libc.unlink(path.ptr);
- }
- }
-
- /// The pid in `pardes-osc133-<shell>-<pid>-XXXXXX`, or null.
- fn rcPid(name: []const u8) ?std.c.pid_t {
- const head = "pardes-osc133-";
- if (!std.mem.startsWith(u8, name, head)) return null;
- var fields = std.mem.splitScalar(u8, name[head.len..], '-');
- _ = fields.next() orelse return null; // the shell
- const digits = fields.next() orelse return null;
- const rest = fields.next() orelse return null;
- if (fields.next() != null or rest.len != 6 or digits.len == 0 or digits.len > 10) return null;
- for (digits) |c| if (!std.ascii.isDigit(c)) return null;
- const pid = std.fmt.parseInt(std.c.pid_t, digits, 10) catch return null;
- return if (pid > 0) pid else null;
- }
-
- fn collectSystemPath(paths_file: [:0]const u8, paths_dir: []const u8, buf: []u8, len: *usize) void {
- var file_buf: [path_capacity]u8 = undefined;
- if (readSmall(paths_file, &file_buf)) |body| appendLines(buf, len, body);
-
- const io = std.Io.Threaded.global_single_threaded.io();
- var dir = std.Io.Dir.cwd().openDir(io, paths_dir, .{ .iterate = true }) catch return;
- defer dir.close(io);
-
- var names: [max_path_files][256]u8 = undefined;
- var name_lens: [max_path_files]usize = undefined;
- var count: usize = 0;
- var it = dir.iterate();
- while (count < names.len) {
- const entry = (it.next(io) catch break) orelse break;
- if (entry.kind == .directory) continue;
- if (entry.name.len == 0 or entry.name.len > names[count].len) continue;
- @memcpy(names[count][0..entry.name.len], entry.name);
- name_lens[count] = entry.name.len;
- count += 1;
- }
- var order: [max_path_files]usize = undefined;
- for (0..count) |i| order[i] = i;
- std.mem.sort(usize, order[0..count], Names{ .names = &names, .lens = &name_lens }, Names.lessThan);
-
- var path_buf: [512]u8 = undefined;
- for (order[0..count]) |i| {
- const name = names[i][0..name_lens[i]];
- const path = std.fmt.bufPrintSentinel(&path_buf, "{s}/{s}", .{ paths_dir, name }, 0) catch continue;
- if (readSmall(path, &file_buf)) |body| appendLines(buf, len, body);
- }
- }
-
- const Names = struct {
- names: *const [max_path_files][256]u8,
- lens: *const [max_path_files]usize,
-
- fn lessThan(self: Names, a: usize, b: usize) bool {
- return std.mem.order(u8, self.names[a][0..self.lens[a]], self.names[b][0..self.lens[b]]) == .lt;
- }
- };
-
- fn appendLines(buf: []u8, len: *usize, body: []const u8) void {
- var lines = std.mem.splitScalar(u8, body, '\n');
- while (lines.next()) |raw| appendEntry(buf, len, std.mem.trim(u8, raw, " \t\r"));
- }
-
- fn appendEntry(buf: []u8, len: *usize, entry: []const u8) void {
- if (entry.len == 0) return;
- if (hasEntry(buf[0..len.*], entry)) return;
- const separator: usize = if (len.* == 0) 0 else 1;
- if (len.* + separator + entry.len > buf.len) return;
- if (separator == 1) {
- buf[len.*] = ':';
- len.* += 1;
- }
- @memcpy(buf[len.*..][0..entry.len], entry);
- len.* += entry.len;
- }
-
- fn hasEntry(list: []const u8, entry: []const u8) bool {
- var it = std.mem.tokenizeScalar(u8, list, ':');
- while (it.next()) |have| if (std.mem.eql(u8, have, entry)) return true;
- return false;
- }
-
- fn allEntriesWithin(candidate: []const u8, list: []const u8) bool {
- var it = std.mem.tokenizeScalar(u8, candidate, ':');
- while (it.next()) |entry| if (!hasEntry(list, entry)) return false;
- return true;
- }
-
- fn readSmall(path: [:0]const u8, buf: []u8) ?[]const u8 {
- const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0));
- if (fd < 0) return null;
- defer _ = libc.close(fd);
- var off: usize = 0;
- while (off < buf.len) {
- const n = libc.read(fd, buf[off..].ptr, buf.len - off);
- if (n < 0) {
- if (libc.errno(n) == .INTR) continue;
- return null;
- }
- if (n == 0) break;
- off += @intCast(n);
- }
- return buf[0..off];
- }
-
- test "the launchd PATH is replaced and a configured one is left alone" {
- var buf: [256]u8 = undefined;
- var len: usize = 0;
- appendEntry(&buf, &len, "/usr/bin");
- appendEntry(&buf, &len, "/bin");
- appendEntry(&buf, &len, "/usr/bin"); // already there: dedup keeps the first
- appendEntry(&buf, &len, "");
- try std.testing.expectEqualStrings("/usr/bin:/bin", buf[0..len]);
-
- try std.testing.expect(allEntriesWithin("/usr/bin:/bin", "/usr/bin:/bin:/sbin"));
- try std.testing.expect(allEntriesWithin("", "/usr/bin"));
- try std.testing.expect(!allEntriesWithin("/Users/x/.cargo/bin:/usr/bin", "/usr/bin:/bin"));
- try std.testing.expect(!allEntriesWithin("/opt/homebrew/bin", "/usr/bin:/bin"));
- }
-
- test "system path files are sorted and duplicate directories keep their first position" {
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths", .data = " /usr/bin \n/bin\n\n/usr/bin\n" });
- try tmp.dir.createDirPath(std.testing.io, "paths.d");
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths.d/20-last", .data = "/opt/local/bin\n/usr/bin\n" });
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "paths.d/10-first", .data = "/opt/homebrew/bin\n/bin\n" });
- var root_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
- const root = root_buf[0..try tmp.dir.realPath(std.testing.io, &root_buf)];
- var file_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
- const paths_file = try std.fmt.bufPrintSentinel(&file_buf, "{s}/paths", .{root}, 0);
- var dir_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
- const paths_dir = try std.fmt.bufPrint(&dir_buf, "{s}/paths.d", .{root});
- var buf: [path_capacity]u8 = undefined;
- var len: usize = 0;
- collectSystemPath(paths_file, paths_dir, &buf, &len);
- try std.testing.expectEqualStrings("/usr/bin:/bin:/opt/homebrew/bin:/opt/local/bin", buf[0..len]);
- }
-
- const Family = enum { bash, fish, none };
-
- fn family(bin: []const u8) Family {
- const slash = std.mem.lastIndexOfScalar(u8, bin, '/');
- const base = if (slash) |s| bin[s + 1 ..] else bin;
- if (std.mem.startsWith(u8, base, "bash")) return .bash;
- if (std.mem.startsWith(u8, base, "fish")) return .fish;
- return .none;
- }
-
- /// `family`, for a shell whose name does not say it (a renamed copy, a
- /// link named otherwise): what it really is, by the name its links end
- /// at, else by the program itself -- bash's carries BASH_VERSINFO, fish's
- /// fish_prompt. ponytail: a string scan of at most 16 MiB, once a spawn
- /// and only for a name that says nothing; a --version probe would fork.
- fn familyOf(path: [*:0]const u8) Family {
- const named = family(std.mem.span(path));
- if (named != .none) return named;
- // A name a POSIX shell answers to is that shell, whatever the file:
- // bash run as `sh` is sh, and reads no --rcfile.
- const bin = std.mem.span(path);
- const base = if (std.mem.lastIndexOfScalar(u8, bin, '/')) |s| bin[s + 1 ..] else bin;
- for ([_][]const u8{ "sh", "dash", "zsh", "ksh", "mksh", "yash", "nu", "elvish", "xonsh", "tcsh", "csh" }) |known|
- if (std.mem.eql(u8, base, known)) return .none;
- var real: [std.Io.Dir.max_path_bytes]u8 = undefined;
- if (libc.realpath(path, &real)) |r| {
- const by_link = family(std.mem.span(@as([*:0]const u8, @ptrCast(r))));
- if (by_link != .none) return by_link;
- }
- const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0));
- if (fd < 0) return .none;
- defer _ = libc.close(fd);
- var chunk: [64 * 1024]u8 = undefined;
- var carry: usize = 0;
- var total: usize = 0;
- while (total < 16 << 20) {
- const n = libc.read(fd, chunk[carry..].ptr, chunk.len - carry);
- if (n <= 0) break;
- const have = carry + @as(usize, @intCast(n));
- total += @intCast(n);
- // A script is no binary: its interpreter is what runs.
- if (total == have and std.mem.startsWith(u8, chunk[0..have], "#!")) return .none;
- if (std.mem.indexOf(u8, chunk[0..have], "BASH_VERSINFO") != null) return .bash;
- if (std.mem.indexOf(u8, chunk[0..have], "fish_prompt") != null) return .fish;
- // Keep the tail, so a marker cut by the chunk is still seen.
- carry = @min(have, 16);
- std.mem.copyForwards(u8, chunk[0..carry], chunk[have - carry .. have]);
- }
- return .none;
- }
-
- test "a bash under another name is still told as bash" {
- const bash: [:0]const u8 = "/usr/bin/bash";
- if (libc.access(bash, X_OK) != 0) return;
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- const bytes = try std.Io.Dir.cwd().readFileAlloc(std.testing.io, bash, std.testing.allocator, .limited(16 << 20));
- defer std.testing.allocator.free(bytes);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "mysh", .data = bytes, .flags = .{ .permissions = .executable_file } });
- var dir_buf: [4096]u8 = undefined;
- const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)];
- var path: [4200:0]u8 = undefined;
- const p = try std.fmt.bufPrintSentinel(&path, "{s}/mysh", .{dir}, 0);
- try std.testing.expectEqual(Family.bash, familyOf(p.ptr));
- try std.testing.expectEqual(Family.none, familyOf("/bin/sh"));
- }
-
- const bash_rc =
- \\[ -f "$HOME/.bashrc" ] && source "$HOME/.bashrc"
- \\PS1='\[\e]133;A;cl=line;aid=pardes\a\]'"$PS1"'\[\e]133;B;aid=pardes\a\]'
- \\PS2='\[\e]133;A;k=c;aid=pardes\a\]'"$PS2"'\[\e]133;B;aid=pardes\a\]'
- \\PROMPT_COMMAND='printf "\e]133;D;%s;aid=pardes\a" "$?"'"${PROMPT_COMMAND:+;$PROMPT_COMMAND}"
- \\if ((BASH_VERSINFO[0] * 100 + BASH_VERSINFO[1] >= 404)); then
- \\ PS0='\e]133;C;aid=pardes\a'"$PS0"
- \\else
- \\ trap 'printf "\e]133;C;aid=pardes\a"' DEBUG
- \\fi
- \\
- ;
-
- // fish -C runs after config.fish; bash --rcfile must source .bashrc itself.
- const fish_rc =
- \\functions -c fish_prompt __pardes_user_prompt
- \\function fish_prompt
- \\ printf '\e]133;A;cl=line;aid=pardes\a'
- \\ __pardes_user_prompt
- \\ printf '\e]133;B;aid=pardes\a'
- \\end
- \\function __pardes_preexec --on-event fish_preexec
- \\ printf '\e]133;C;aid=pardes\a'
- \\end
- \\function __pardes_postexec --on-event fish_postexec
- \\ printf '\e]133;D;%s;aid=pardes\a' $status
- \\end
- \\
- ;
-
- const rc_path_capacity = 256;
-
- /// The prompt files a shell sources at start. Under $XDG_RUNTIME_DIR
- /// (private to the user) there is one file per content, named by its
- /// hash and shared by every pardes, so none is left behind by a pardes
- /// that was killed: 72K of them piled up in /tmp when each host wrote
- /// its own. Without that directory each host writes private mkstemp
- /// files in /tmp and removes them at teardown, as before.
- pub const PromptFiles = struct {
- bash_path: [rc_path_capacity:0]u8 = @splat(0),
- bash_len: u16 = 0,
- bash_owned: bool = false,
- fish_path: [rc_path_capacity:0]u8 = @splat(0),
- fish_len: u16 = 0,
- fish_owned: bool = false,
- fish_command: [rc_path_capacity + "source ''".len:0]u8 = @splat(0),
- fish_command_len: u16 = 0,
-
- pub fn init() PromptFiles {
- var rcs: PromptFiles = .{};
- const bash = place(&rcs.bash_path, "bash", bash_rc);
- rcs.bash_len = bash.len;
- rcs.bash_owned = bash.owned;
- const fish = place(&rcs.fish_path, "fish", fish_rc);
- rcs.fish_len = fish.len;
- rcs.fish_owned = fish.owned;
- if (rcs.fishPath()) |path| {
- // Quoted for fish; a path a quote would break is not used.
- const command = if (std.mem.indexOfAny(u8, path, "'\\") != null)
- error.NoSpaceLeft
- else
- std.fmt.bufPrintSentinel(&rcs.fish_command, "source '{s}'", .{path}, 0);
- const ok = command catch {
- if (rcs.fish_owned) _ = libc.unlink(path.ptr);
- rcs.fish_len = 0;
- return rcs;
- };
- rcs.fish_command_len = @intCast(ok.len);
- }
- return rcs;
- }
-
- pub fn deinit(rcs: *PromptFiles) void {
- // Removed here, not again by a signal's handler.
- for (&fatal_rc_len, 0..) |*len, i| for ([_]?[:0]const u8{ rcs.bashPath(), rcs.fishPath() }) |mine| {
- if (mine) |path| if (len.* == path.len and std.mem.eql(u8, fatal_rcs[i][0..len.*], path)) {
- len.* = 0;
- };
- };
- if (rcs.bashPath()) |path| if (rcs.bash_owned) {
- _ = libc.unlink(path.ptr);
- };
- if (rcs.fishPath()) |path| if (rcs.fish_owned) {
- _ = libc.unlink(path.ptr);
- };
- rcs.bash_len = 0;
- rcs.fish_len = 0;
- rcs.fish_command_len = 0;
- }
-
- fn bashPath(rcs: *const PromptFiles) ?[:0]const u8 {
- if (rcs.bash_len == 0) return null;
- return rcs.bash_path[0..rcs.bash_len :0];
- }
-
- fn fishPath(rcs: *const PromptFiles) ?[:0]const u8 {
- if (rcs.fish_len == 0) return null;
- return rcs.fish_path[0..rcs.fish_len :0];
- }
-
- fn fishCommand(rcs: *const PromptFiles) ?[:0]const u8 {
- if (rcs.fish_command_len == 0) return null;
- return rcs.fish_command[0..rcs.fish_command_len :0];
- }
- };
-
- /// The shared file for `contents` under $XDG_RUNTIME_DIR, written
- /// beside it and renamed into place when missing or different, so a
- /// shell never reads half of one; failing that, a private /tmp file.
- fn place(path_buf: *[rc_path_capacity:0]u8, name: []const u8, contents: []const u8) struct { len: u16, owned: bool } {
- shared: {
- const dir = std.mem.span(std.c.getenv("XDG_RUNTIME_DIR") orelse break :shared);
- if (dir.len == 0 or dir[0] != '/') break :shared;
- const final = std.fmt.bufPrintSentinel(path_buf, "{s}/pardes-osc133-{s}-{x:0>16}", .{ dir, name, std.hash.Wyhash.hash(0, contents) }, 0) catch break :shared;
- var have: [2048]u8 = undefined;
- if (readSmall(final, &have)) |got| if (std.mem.eql(u8, got, contents)) return .{ .len = @intCast(final.len), .owned = false };
- var tmp_buf: [rc_path_capacity:0]u8 = @splat(0);
- var template_buf: [rc_path_capacity]u8 = undefined;
- const tmp_template = std.fmt.bufPrint(&template_buf, "{s}.XXXXXX", .{final}) catch break :shared;
- const n = stage(&tmp_buf, tmp_template, contents);
- if (n == 0) break :shared;
- if (libc.rename(tmp_buf[0..n :0].ptr, final.ptr) != 0) {
- _ = libc.unlink(tmp_buf[0..n :0].ptr);
- break :shared;
- }
- return .{ .len = @intCast(final.len), .owned = false };
- }
- var tmp_template: [64]u8 = undefined;
- // Its pid in the name: one a killed editor left is swept by the
- // next (sweepDeadRcs).
- const template = std.fmt.bufPrint(&tmp_template, "/tmp/pardes-osc133-{s}-{d}-XXXXXX", .{ name, @as(u32, @intCast(std.c.getpid())) }) catch return .{ .len = 0, .owned = false };
- return .{ .len = stage(path_buf, template, contents), .owned = true };
- }
-
- // Publish a path only after its private 0600 file is fully written and closed.
- fn stage(path_buf: *[rc_path_capacity:0]u8, template: []const u8, contents: []const u8) u16 {
- const path = std.fmt.bufPrintSentinel(path_buf, "{s}", .{template}, 0) catch return 0;
- const fd = mkstemp(path.ptr);
- if (fd < 0) return 0;
- if (!writeFd(fd, contents)) {
- _ = libc.close(fd);
- _ = libc.unlink(path.ptr);
- return 0;
- }
- if (libc.close(fd) != 0) {
- _ = libc.unlink(path.ptr);
- return 0;
- }
- return @intCast(path.len);
- }
-
- test "shell family is the basename's prefix, and anything else runs unadorned" {
- try std.testing.expectEqual(Family.fish, family("fish"));
- try std.testing.expectEqual(Family.fish, family("/usr/bin/fish"));
- try std.testing.expectEqual(Family.fish, family("/opt/homebrew/bin/fish"));
- try std.testing.expectEqual(Family.bash, family("bash"));
- try std.testing.expectEqual(Family.bash, family("/bin/bash"));
- try std.testing.expectEqual(Family.bash, family("/usr/bin/bash-5.2"));
- try std.testing.expectEqual(Family.fish, family("/usr/local/bin/fish-3.7"));
- try std.testing.expectEqual(Family.none, family("/opt/fish/bin/nu"));
- try std.testing.expectEqual(Family.none, family("/usr/bin/zsh"));
- try std.testing.expectEqual(Family.none, family("/bin/sh"));
- try std.testing.expectEqual(Family.none, family("nu"));
- try std.testing.expectEqual(Family.none, family(""));
- }
-
- const bin_dirs = [_][]const u8{
- "/usr/bin/",
- "/bin/",
- "/usr/local/bin/",
- "/opt/homebrew/bin/",
- "/opt/local/bin/",
- "/usr/sbin/",
- };
-
- const fallbacks = [_][]const u8{
- if (builtin.os.tag == .linux) "/usr/bin/bash" else "/bin/bash",
- "/bin/sh",
- };
-
- pub const Spawn = struct {
- path: [*:0]const u8,
- argv: [6:null]?[*:0]const u8,
- };
-
- // Resolve in the parent. The path buffer and prompt files must survive through exec.
- pub fn resolve(bin: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8, prompt_rcs: *const PromptFiles) Spawn {
- const path = find(bin, buf) orelse fallback(buf);
- const marks: [2]?[*:0]const u8 = switch (familyOf(path)) {
- .bash => if (prompt_rcs.bashPath()) |rc| .{ "--rcfile", rc.ptr } else .{ null, null },
- .fish => if (prompt_rcs.fishCommand()) |command| .{ "-C", command.ptr } else .{ null, null },
- .none => .{ null, null },
- };
- return .{ .path = path, .argv = .{ path, marks[0], marks[1], null, null, null } };
- }
-
- /// A command pane's shell runs its one line with job control on, so a
- /// job the line puts in the background has a process group of its own.
- /// The shell leads the terminal's session, and when it exits the kernel
- /// hangs up the terminal's foreground group: with job control off that
- /// is the shell's own, the job's too, and the job died with the command
- /// (nohup'd or not; only setsid got out, and not always in time). A
- /// shell pardes does not know runs the line as it is.
- pub fn commandArgv(path: [*:0]const u8, line: [*:0]const u8) [6:null]?[*:0]const u8 {
- const bin = std.mem.span(path);
- const base = if (std.mem.lastIndexOfScalar(u8, bin, '/')) |s| bin[s + 1 ..] else bin;
- const posix_shells = [_][]const u8{ "bash", "sh", "dash", "zsh", "ksh", "mksh", "yash" };
- for (posix_shells) |name| if (std.mem.eql(u8, base, name))
- return .{ path, "-m", "-c", line, null, null };
- if (family(bin) == .fish) return .{ path, "-C", "status job-control full", "-c", line, null };
- return .{ path, "-c", line, null, null, null };
- }
-
- /// A shell by its path or its name in the usual directories, or null.
- /// A path may be under a mount this editor serves: the turn goes out
- /// with the lookups (pardes.Turn.yield).
- pub fn find(bin: []const u8, buf: *[std.Io.Dir.max_path_bytes]u8) ?[*:0]const u8 {
- if (bin.len == 0 or bin.len + 1 > buf.len) return null;
- pardes.turn.yield();
- defer pardes.turn.back();
- if (std.mem.indexOfScalar(u8, bin, '/') != null) {
- @memcpy(buf[0..bin.len], bin);
- buf[bin.len] = 0;
- const p: [*:0]const u8 = @ptrCast(buf);
- return if (libc.access(p, X_OK) == 0 and !isDirectory(p)) p else null;
- }
- for (bin_dirs) |dir| {
- if (dir.len + bin.len + 1 > buf.len) continue;
- @memcpy(buf[0..dir.len], dir);
- @memcpy(buf[dir.len..][0..bin.len], bin);
- buf[dir.len + bin.len] = 0;
- const p: [*:0]const u8 = @ptrCast(buf);
- if (libc.access(p, X_OK) == 0) return p;
- }
- return null;
- }
-
- /// A directory passes access(X_OK) (it can be searched): no shell.
- pub fn isDirectory(path: [*:0]const u8) bool {
- const d = libc.opendir(path) orelse return false;
- _ = libc.closedir(d);
- return true;
- }
-
- /// Why `bin` is no shell, for the words that name one (Term, Shell);
- /// null when it is one.
- pub fn refusal(bin: []const u8, said: []u8) ?[]const u8 {
- var buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
- if (find(bin, &buf)) |found| {
- // A script whose `#!` names a program that is not there: its
- // exec fails ENOENT as a missing shell's does, so told apart.
- var interp: [256]u8 = undefined;
- const missing = missingInterpreter(found, &interp) orelse return null;
- return std.fmt.bufPrint(said, "interpreter {s} not found", .{missing}) catch "interpreter not found";
- }
- if (std.mem.indexOfScalar(u8, bin, '/') != null and bin.len < buf.len) {
- @memcpy(buf[0..bin.len], bin);
- buf[bin.len] = 0;
- if (isDirectory(@ptrCast(&buf))) return std.fmt.bufPrint(said, "not a shell: {s} is a directory", .{bin}) catch "not a shell: a directory";
- // There, but no program: said so, not "not found".
- if (libc.access(@ptrCast(&buf), 0) == 0) return std.fmt.bufPrint(said, "not a shell: {s} is not executable", .{bin}) catch "not a shell: not executable";
- }
- // "not found": the words a mount reads as ENOENT.
- return std.fmt.bufPrint(said, "shell \"{s}\" not found (a name on the usual paths, or a path to one)", .{bin}) catch "no such shell";
- }
-
- /// The program a script's `#!` line names, when it is not there to
- /// run; null for a script whose interpreter is there, or no script.
- pub fn missingInterpreter(path: [*:0]const u8, out: []u8) ?[]const u8 {
- pardes.turn.yield();
- defer pardes.turn.back();
- const fd = libc.open(path, .{ .ACCMODE = .RDONLY }, @as(libc.mode_t, 0));
- if (fd < 0) return null;
- defer _ = libc.close(fd);
- var head: [256]u8 = undefined;
- const n = libc.read(fd, &head, head.len);
- if (n < 2) return null;
- const got = head[0..@intCast(n)];
- if (!std.mem.startsWith(u8, got, "#!")) return null;
- const line = got[2 .. std.mem.indexOfScalar(u8, got, '\n') orelse got.len];
- var words = std.mem.tokenizeAny(u8, line, " \t\r");
- const interp = words.next() orelse return null;
- if (interp.len + 1 > out.len) return null;
- @memcpy(out[0..interp.len], interp);
- out[interp.len] = 0;
- if (libc.access(@ptrCast(out.ptr), X_OK) == 0) return null;
- return out[0..interp.len];
- }
-
- test "a script whose #! names a program not there is told apart from a missing shell" {
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "bad", .data = "#!/no/such/interp -x\n", .flags = .{ .permissions = .executable_file } });
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "good", .data = "#!/bin/sh\n", .flags = .{ .permissions = .executable_file } });
- var dir_buf: [4096]u8 = undefined;
- const dir = dir_buf[0..try tmp.dir.realPath(std.testing.io, &dir_buf)];
- var path: [4200]u8 = undefined;
- var said: [320]u8 = undefined;
- try std.testing.expectEqualStrings("interpreter /no/such/interp not found", refusal(try std.fmt.bufPrint(&path, "{s}/bad", .{dir}), &said).?);
- try std.testing.expect(refusal(try std.fmt.bufPrint(&path, "{s}/good", .{dir}), &said) == null);
- try std.testing.expect(std.mem.startsWith(u8, refusal(try std.fmt.bufPrint(&path, "{s}/none", .{dir}), &said).?, "shell \""));
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = "plain", .data = "echo\n" });
- const plain = try std.fmt.bufPrint(&path, "{s}/plain", .{dir});
- try std.testing.expect(std.mem.endsWith(u8, refusal(plain, &said).?, "plain is not executable"));
- }
-
- fn fallback(buf: *[std.Io.Dir.max_path_bytes]u8) [*:0]const u8 {
- for (fallbacks) |f| {
- @memcpy(buf[0..f.len], f);
- buf[f.len] = 0;
- const p: [*:0]const u8 = @ptrCast(buf);
- if (libc.access(p, X_OK) == 0) return p;
- }
- return @ptrCast(buf);
- }
-
- test "a command pane's line runs with job control on in the shells that have it" {
- const want = struct {
- fn check(path: [*:0]const u8, words: []const []const u8) !void {
- const argv = commandArgv(path, "sleep 9 &");
- for (words, 0..) |w, i| try std.testing.expectEqualStrings(w, std.mem.span(argv[i].?));
- try std.testing.expect(argv[words.len] == null);
- }
- };
- try want.check("/usr/bin/bash", &.{ "/usr/bin/bash", "-m", "-c", "sleep 9 &" });
- try want.check("/bin/sh", &.{ "/bin/sh", "-m", "-c", "sleep 9 &" });
- try want.check("/usr/bin/fish", &.{ "/usr/bin/fish", "-C", "status job-control full", "-c", "sleep 9 &" });
- try want.check("/usr/bin/nu", &.{ "/usr/bin/nu", "-c", "sleep 9 &" });
- }
-
- test "a path is taken at its word, a name is looked up, and both pick their own marks" {
- if (builtin.os.tag == .windows) return;
- var buf: [std.Io.Dir.max_path_bytes]u8 = undefined;
- var prompt_rcs = PromptFiles.init();
- defer prompt_rcs.deinit();
-
- const sh = resolve("/bin/sh", &buf, &prompt_rcs);
- try std.testing.expectEqualStrings("/bin/sh", std.mem.span(sh.path));
- try std.testing.expect(sh.argv[1] == null);
-
- const bash = resolve("bash", &buf, &prompt_rcs);
- try std.testing.expect(family(std.mem.span(bash.path)) == .bash);
- try std.testing.expectEqualStrings("--rcfile", std.mem.span(bash.argv[1].?));
- try std.testing.expectEqualStrings(prompt_rcs.bashPath().?, std.mem.span(bash.argv[2].?));
-
- const missing = resolve("zznosuchshell", &buf, &prompt_rcs);
- try std.testing.expect(!std.mem.eql(u8, "zznosuchshell", std.mem.span(missing.path)));
- try std.testing.expect(libc.access(missing.path, X_OK) == 0);
-
- const gone = resolve("/zz/no/such/shell", &buf, &prompt_rcs);
- try std.testing.expect(libc.access(gone.path, X_OK) == 0);
- }
-
- test "a private prompt file names its pid, and a dead pid's is swept while a live one's stays" {
- if (builtin.os.tag == .windows) return;
- const dead = "/tmp/pardes-osc133-bash-2147483647-AbCdEf";
- var live_buf: [80:0]u8 = undefined;
- const live = try std.fmt.bufPrintSentinel(&live_buf, "/tmp/pardes-osc133-bash-{d}-AbCdEf", .{@as(u32, @intCast(std.c.getppid()))}, 0);
- defer for ([_][:0]const u8{ dead, live }) |path| {
- _ = libc.unlink(path.ptr);
- };
- for ([_][:0]const u8{ dead, live }) |path| {
- const fd = libc.open(path, .{ .CREAT = true, .ACCMODE = .WRONLY }, @as(libc.mode_t, 0o600));
- if (fd < 0) return error.SkipZigTest;
- _ = libc.close(fd);
- }
- sweepDeadRcs();
- try std.testing.expect(libc.access(dead, 0) < 0);
- try std.testing.expect(libc.access(live, 0) == 0);
- // The pid is read only from that shape: an older name has none.
- try std.testing.expectEqual(@as(?std.c.pid_t, 42), rcPid("pardes-osc133-fish-42-Xy12Zq"));
- try std.testing.expectEqual(@as(?std.c.pid_t, null), rcPid("pardes-osc133-bash-01z3XK"));
- }
-
- test "prompt files are one per content under the runtime dir, or private and cleaned up without it" {
- if (builtin.os.tag == .windows) return;
- var saved_buf: [std.Io.Dir.max_path_bytes:0]u8 = @splat(0);
- const saved: ?[:0]const u8 = if (std.c.getenv("XDG_RUNTIME_DIR")) |v| std.fmt.bufPrintSentinel(&saved_buf, "{s}", .{std.mem.span(v)}, 0) catch null else null;
- defer _ = if (saved) |v| setenv("XDG_RUNTIME_DIR", v.ptr, 1) else testUnsetenv("XDG_RUNTIME_DIR");
-
- var tmp = std.testing.tmpDir(.{});
- defer tmp.cleanup();
- var dir_buf: [std.Io.Dir.max_path_bytes:0]u8 = @splat(0);
- const dir_len = try tmp.dir.realPath(std.testing.io, &dir_buf);
- _ = setenv("XDG_RUNTIME_DIR", dir_buf[0..dir_len :0].ptr, 1);
-
- // Shared: the same file for every owner, left in place, rewritten
- // whole when what is there is not its content.
- var a = PromptFiles.init();
- var b = PromptFiles.init();
- const a_bash = a.bashPath() orelse return error.TempCreateFailed;
- try std.testing.expectEqualStrings(a_bash, b.bashPath().?);
- try std.testing.expect(std.mem.startsWith(u8, a_bash, dir_buf[0..dir_len]));
- const fish_command = a.fishCommand() orelse return error.MissingFishCommand;
- var want: [rc_path_capacity + 16]u8 = undefined;
- try std.testing.expectEqualStrings(try std.fmt.bufPrint(&want, "source '{s}'", .{a.fishPath().?}), fish_command);
- var buf: [2048]u8 = undefined;
- try std.testing.expectEqualStrings(bash_rc, readSmall(a_bash, &buf) orelse return error.ReadFailed);
- try std.testing.expectEqualStrings(fish_rc, readSmall(a.fishPath().?, &buf) orelse return error.ReadFailed);
- const stat = try @import("core").filesystem.statPath(std.testing.io, a_bash, .{});
- try std.testing.expectEqual(0, stat.permissions.toMode() & 0o077);
- var kept: [rc_path_capacity:0]u8 = @splat(0);
- @memcpy(kept[0..a_bash.len], a_bash);
- a.deinit();
- b.deinit();
- try std.testing.expect(libc.access(&kept, 0) == 0);
- try tmp.dir.writeFile(std.testing.io, .{ .sub_path = std.Io.Dir.path.basename(kept[0..a_bash.len]), .data = "half" });
- var c = PromptFiles.init();
- defer c.deinit();
- try std.testing.expectEqualStrings(bash_rc, readSmall(c.bashPath().?, &buf) orelse return error.ReadFailed);
-
- // No runtime dir: private files, one per owner, gone at teardown.
- _ = testUnsetenv("XDG_RUNTIME_DIR");
- var d = PromptFiles.init();
- var e = PromptFiles.init();
- defer e.deinit();
- const d_bash = d.bashPath() orelse return error.TempCreateFailed;
- try std.testing.expect(!std.mem.eql(u8, d_bash, e.bashPath().?));
- try std.testing.expect(std.mem.startsWith(u8, d_bash, "/tmp/pardes-osc133-bash-"));
- try std.testing.expectEqual(@as(?std.c.pid_t, std.c.getpid()), rcPid(std.Io.Dir.path.basename(d_bash)));
- @memcpy(kept[0..d_bash.len], d_bash);
- kept[d_bash.len] = 0;
- d.deinit();
- try std.testing.expect(libc.access(&kept, 0) < 0);
- }
-};
+pub const Shell = @import("Shell.zig");
/// In a child between fork and exec: every signal back to its default and
/// none blocked, whatever this process ignores or blocks (the tty's SIGWINCH,