diff options
Diffstat (limited to 'src/Plumb.zig')
| -rw-r--r-- | src/Plumb.zig | 503 |
1 files changed, 414 insertions, 89 deletions
diff --git a/src/Plumb.zig b/src/Plumb.zig index 57a19b14..5299a8c3 100644 --- a/src/Plumb.zig +++ b/src/Plumb.zig @@ -10,9 +10,10 @@ const std = @import("std"); const pardes = @import("pardes.zig"); const fs = @import("fs.zig"); const look = @import("look.zig"); -const exec = @import("exec.zig"); const layout = @import("layout.zig"); const Kind = @import("Kind.zig"); +const tape = @import("tape.zig"); +const events = @import("ninep/events.zig"); const Regex = @import("regexp.zig").Regex; const Pardes = pardes.Pardes; @@ -24,6 +25,17 @@ text: std.ArrayList(u8) = .empty, /// are `include basic`'s, so a session starts with the defaults, and so /// does a dump made before the plumber. written: bool = false, +/// Every port a rule has named this session, in the order they were +/// named, never dropped (plumber(4)'s directory): plumb/<port>'s files, +/// a port's index its node. +ports: std.ArrayList([]u8) = .empty, +/// The rules in force read, kept until their text changes (by its hash): +/// a send parses nothing (29k instructions a send in a fast build, half +/// of what a URL's costs). Each process's own. +parsed: ?struct { hash: u64, rules: Rules } = null, +parsed_arena: ?std.heap.ArenaAllocator = null, + +pub const replica = .{ .derived = .{ "parsed", "parsed_arena" } }; /// The default rules, which `include basic` names, as Plan 9's names /// /lib/plumb/basic. @@ -45,7 +57,10 @@ pub const e_client = "no port for \"client\" rule"; pub const e_empty = "empty argument list"; pub fn deinit(pl: *Plumb, gpa: std.mem.Allocator) void { + if (pl.parsed_arena) |*a| a.deinit(); pl.text.deinit(gpa); + for (pl.ports.items) |name| gpa.free(name); + pl.ports.deinit(gpa); } // ---- the message ---- @@ -496,6 +511,22 @@ fn rulesOf(p: *Pardes, arena: std.mem.Allocator) Parser.Error!Rules { return ps.rules; } +/// The rules in force, read once for every send until they change. A +/// send made while a rule's word runs (a look it makes) reads them into +/// the step's scratch: the send it runs in holds the kept ones. +fn inForceRules(p: *Pardes) Parser.Error!Rules { + const pl = &p.plumber; + const hash = std.hash.Wyhash.hash(0, source(p)); + if (pl.parsed) |c| if (c.hash == hash) return c.rules; + if (p.plumb_declined != null) return rulesOf(p, p.scratch.allocator()); + pl.parsed = null; + if (pl.parsed_arena) |*a| a.deinit(); + pl.parsed_arena = .init(p.gpa); + const rules = try rulesOf(p, pl.parsed_arena.?.allocator()); + pl.parsed = .{ .hash = hash, .rules = rules }; + return rules; +} + /// The rules in force as plumb/rules reads them, the defaults printed /// (in the step's scratch) while none were written. pub fn inForce(p: *Pardes) []const u8 { @@ -507,17 +538,115 @@ pub fn inForce(p: *Pardes) []const u8 { return out.written(); } +/// What the `Plumb` word says to a rule written after it. +pub const e_word = "Plumb takes no rule now: rules are plumb(6) rule sets, in <config>/plumbing (Plumb opens it) or written to plumb/rules"; + +/// The plumbing file, the user's rules beside init (plumber(4)'s +/// $home/lib/plumbing), in `buf`; null with no configuration directory. +pub fn filePath(p: *Pardes, buf: *[4096]u8) ?[]const u8 { + const dir = p.configDir() orelse return null; + return std.fmt.bufPrint(buf, "{s}/plumbing", .{std.mem.trimEnd(u8, dir, "/")}) catch null; +} + +/// At boot, the plumbing file's rules in force, if it is there (the +/// plumber reading $home/lib/plumbing); a refusal is said, as an init +/// line that fails is, and the defaults stay. Either way the ports the +/// rules in force name have their files. +pub fn boot(p: *Pardes) void { + if (rulesOf(p, p.scratch.allocator())) |rules| notePorts(p, rules.ports.items) catch {} else |_| {} + var buf: [4096]u8 = undefined; + const path = filePath(p, &buf) orelse return; + const text = fs.read(p, path) catch return; + defer p.gpa.free(text); + if (apply(p, false, "plumbing", text)) |why| p.reportFailure(p.view().active, why); +} + +/// A file saved from pane `pane`: when it is the plumbing file, its rules +/// in force now, or the save says why not and the rules stay as they were +/// (plumb.ms's `cp lib/plumbing /mnt/plumb/rules`, done for you). +pub fn saved(p: *Pardes, pane: usize, path: []const u8, text: []const u8) void { + var buf: [4096]u8 = undefined; + const mine = filePath(p, &buf) orelse return; + if (!std.mem.eql(u8, mine, path)) return; + if (apply(p, false, "plumbing", text)) |why| p.reportFailure(pane, why); +} + +/// `names` added to the session's ports, those it has not yet, in order; +/// none when they would be more than max_ports. +fn notePorts(p: *Pardes, names: []const []const u8) error{ TooMany, OutOfMemory }!void { + var new: usize = 0; + for (names) |n| new += @intFromBool(portIndex(p, n) == null); + if (p.plumber.ports.items.len + new > max_ports) return error.TooMany; + try p.plumber.ports.ensureUnusedCapacity(p.gpa, new); + for (names) |n| if (portIndex(p, n) == null) p.plumber.ports.appendAssumeCapacity(try p.gpa.dupe(u8, n)); +} + +/// The port named `name`'s index, its file's node. +pub fn portIndex(p: *const Pardes, name: []const u8) ?u8 { + for (p.plumber.ports.items, 0..) |n, i| if (std.mem.eql(u8, n, name)) return @intCast(i); + return null; +} + +pub fn portName(p: *const Pardes, index: u8) ?[]const u8 { + return if (index < p.plumber.ports.items.len) p.plumber.ports.items[index] else null; +} + +/// Whether a program reads port `index` (an open of its file): the +/// authority's 9P state, asked through the tape. +fn portRead(p: *Pardes, index: u8) bool { + for (&p.fs.opens) |*o| if (o.node != 0 and o.what == .port and o.what.port.index == index) return true; + return false; +} + +/// `m` packed onto `q` (a reader's, the held ones'), after `lead` (a +/// held message's port); false when it is over what a queue holds. +fn enqueue(p: *Pardes, q: *events.Queue, lead: []const u8, m: *const Msg) bool { + var out: std.Io.Writer.Allocating = .init(p.scratch.allocator()); + out.writer.writeAll(lead) catch return false; + m.pack(&out.writer) catch return false; + if (out.written().len + 4 > q.cap) return false; + q.push(p.gpa, out.written()); + return true; +} + +/// A copy of `m` to every reader of port `index` (plumber(4)'s queuesend: +/// every fid open when it was sent), each read held for one answered. +fn fanOut(p: *Pardes, index: u8, m: *const Msg) void { + for (&p.fs.opens) |*o| if (o.node != 0 and o.what == .port and o.what.port.index == index) { + if (!enqueue(p, &o.what.port.queue, "", m)) { + var said: Kind.Buf(160) = .{}; + events.notePath(p, "err -", said.print("plumb/{s}: a message of {d} bytes is over a reader's {d} KiB, not sent to it", .{ portName(p, index).?, m.data.len, events.queue_cap / 1024 })); + } + }; + p.fs.news = true; +} + +/// A port's file opened (tree.zig): what `client` rules held for it, the +/// opener's (plumber(4)'s queueheld). +pub fn opened(p: *Pardes, index: u8, q: *events.Queue) void { + const held = &p.fs.plumb_held; + var kept: events.Queue = .{}; + while (held.peek()) |record| { + if (record[0] == index) { + q.push(p.gpa, record[1..]); + } else kept.push(p.gpa, record); + held.pop(); + } + held.deinit(p.gpa); + held.* = kept; +} + /// No rules at all: a `>` to plumb/rules, before what it writes. pub fn clear(p: *Pardes) void { p.plumber.text.clearRetainingCapacity(); p.plumber.written = true; } -/// `more` read after the rules in force (`keep`) or in their place, and -/// what that makes kept as the rules: plumb/rules' write and its close's -/// rest. Null when taken, else why not, in the step's scratch, the rules -/// as they were. -pub fn apply(p: *Pardes, keep: bool, more: []const u8) ?[]const u8 { +/// `more` (read from `name`) read after the rules in force (`keep`) or in +/// their place, and what that makes kept as the rules: plumb/rules' write +/// and its close's rest, the plumbing file saved or read at boot. Null +/// when taken, else why not, in the step's scratch, the rules as they were. +pub fn apply(p: *Pardes, keep: bool, name: []const u8, more: []const u8) ?[]const u8 { const arena = p.scratch.allocator(); var ps: Parser = .{ .arena = arena, .p = p, .check = true }; const said = said: { @@ -525,11 +654,15 @@ pub fn apply(p: *Pardes, keep: bool, more: []const u8) ?[]const u8 { ps.feed("plumb/rules", source(p)) catch break :said ps.why; ps.finish() catch break :said ps.why; } - ps.feed("plumb/rules", more) catch break :said ps.why; + ps.feed(name, more) catch break :said ps.why; ps.finish() catch break :said ps.why; var out: std.Io.Writer.Allocating = .init(arena); ps.rules.print(&out.writer) catch break :said "out of memory"; if (out.written().len > max_text) break :said std.fmt.comptimePrint("rules too long; max {d} KiB", .{max_text / 1024}); + notePorts(p, ps.rules.ports.items) catch |err| break :said switch (err) { + error.TooMany => std.fmt.comptimePrint("too many ports; max {d}", .{max_ports}), + error.OutOfMemory => "out of memory", + }; p.plumber.text.clearRetainingCapacity(); p.plumber.text.appendSlice(p.gpa, out.written()) catch break :said "out of memory"; p.plumber.written = true; @@ -550,6 +683,9 @@ const Send = struct { from: ?usize, arena: std.mem.Allocator, rules: Rules, + /// The data as a look sent it (`Seen`): a message to `edit` that still + /// holds it is Look's to open. + looked: ?[]const u8 = null, memo_name: ?[]const u8 = null, memo_wdir: []const u8 = "", memo: ?fs.Resolved = null, @@ -571,23 +707,10 @@ const Send = struct { fn search(s: *Send, wdir: []const u8, name: []const u8) ?fs.Resolved { if (name.len == 0) return null; - if (fs.resolve(s.p, name, wdir, &s.memo_buf)) |found| return found; - if (name[0] == '/' or fs.dotRelative(name)) return null; - if (s.from) |id| { - const v = s.p.view(); - var seen: [pardes.MAX_PANES][]const u8 = undefined; - var nseen: usize = 0; - var n: usize = 1; - cand: while (n <= v.jumps.n) : (n += 1) { - const k = v.jumps.list[v.jumps.n - n].pane; - if (k == id) continue; - const dir = Pardes.paneDir(s.p.panes[k] orelse continue); - if (std.mem.eql(u8, dir, wdir)) continue; - for (seen[0..nseen]) |d| if (std.mem.eql(u8, d, dir)) continue :cand; - seen[nseen] = dir; - nseen += 1; - if (fs.resolve(s.p, name, dir, &s.memo_buf)) |found| return found; - } + var dirs: look.Dirs = .init(s.p, s.from, wdir); + while (dirs.next()) |dir| { + if (fs.resolve(s.p, name, dir, &s.memo_buf)) |found| return found; + if (name[0] == '/' or fs.dotRelative(name)) return null; } for (s.p.incl.items) |dir| if (fs.resolve(s.p, name, dir, &s.memo_buf)) |found| return found; return null; @@ -711,14 +834,42 @@ const Port = enum { web, }; +/// What a look found of the name it sends (look.zig's resolveLookTarget: +/// in its pane's directory, the jump list's, Incl's), which `isfile` and +/// `isdir` take as found rather than ask the disk again: the same answer, +/// and Look's own readings of a name kept (a URL, `//`: no file). +pub const Seen = struct { name: []const u8, found: ?fs.Resolved }; + +/// Where a send went. +pub const Sent = union(enum) { + /// Taken: started, or given to the port that reads it. + done, + /// To `edit` as the look sent it (`Seen`): Look opens what it found, + /// as acme's own look opens a file. + look, + /// Taken by nothing, in Plan 9's words; or what a rule started + /// declined it (`declined`). + refused: []const u8, +}; + +/// What a send a rule's started word declined says (Pardes.plumb_declined): +/// fsys.c's words for a message nothing takes. +pub const e_declined = "no matching plumb rule"; + /// A message matched against the rules and sent where they say (fsys.c's /// write of `send`, then dispose), from pane `from` (a look's) or from /// plumb/send (null: the pane with the keyboard runs what it starts). -/// Null when it went somewhere, else why not, in Plan 9's words, in the -/// step's scratch. -pub fn send(p: *Pardes, from: ?usize, msg: Msg) ?[]const u8 { +/// `seen` is a look's, what it found of the name it sends. A refusal is in +/// the step's scratch. +pub fn send(p: *Pardes, from: ?usize, msg: Msg, seen: ?Seen) Sent { const arena = p.scratch.allocator(); - var s: Send = .{ .p = p, .from = from, .arena = arena, .rules = rulesOf(p, arena) catch return "plumb/rules: the rules in force do not read" }; + var s: Send = .{ .p = p, .from = from, .arena = arena, .rules = inForceRules(p) catch return .{ .refused = "plumb/rules: the rules in force do not read" } }; + if (seen) |look_seen| { + s.looked = msg.data; + s.memo_name = look_seen.name; + s.memo_wdir = msg.wdir; + s.memo = look_seen.found; + } var m = msg; var e: Exec = .{ .m = &m }; const set: ?Set = for (s.rules.items.items) |item| { @@ -727,36 +878,46 @@ pub fn send(p: *Pardes, from: ?usize, msg: Msg) ?[]const u8 { else => continue, }; e = .{ .m = &m }; - if (s.matchSet(candidate, &e) catch return "out of memory") break candidate; + if (s.matchSet(candidate, &e) catch return .{ .refused = "out of memory" }) break candidate; } else null; const id = from orelse p.view().active; // dispose. - if (m.dst.len == 0) return startup(&s, id, set orelse return e_no_port, &e); - if (std.meta.stringToEnum(Port, m.dst)) |port| { - deliver(&s, id, port, &m); - return null; + if (m.dst.len == 0) return startup(&s, id, set orelse return .{ .refused = e_no_port }, &e); + const port = portIndex(p, m.dst); + // A port pardes reads itself: its readers' copies (a program reading + // plumb/edit sees every open, plumber(4)'s fan-out), the authority's + // alone to hand out, so asked of nobody; then pardes's own. + if (std.meta.stringToEnum(Port, m.dst)) |own| { + if (port) |i| fanOut(p, i, &m); + return deliver(&s, id, own, &m); } if (p.kinds.byName(m.dst)) |k| { + if (port) |i| fanOut(p, i, &m); openInKind(&s, id, k, &m); - return null; + return .done; } - // A port nobody reads: what the rule set starts, if it is one a rule - // names; one no rule names is no port, and the message goes nowhere, - // as fsys.c's dispose finds no Dirtab for it. - if (!s.rules.named(m.dst)) return null; - return startup(&s, id, set orelse return e_no_start, &e); + // One no rule ever named is none, and the message goes nowhere, as + // fsys.c's dispose finds no Dirtab for it. Another goes to its readers, + // whom only the authority knows (its 9P opens); with none, what the + // rule set starts. + const i = port orelse return .done; + if (tape.authority(portRead, .{ p, i })) { + fanOut(p, i, &m); + return .done; + } + return startup(&s, id, set orelse return .{ .refused = e_no_start }, &e); } /// match.c's startup: the rule set's `start` or `client`, its words /// expanded, run. -fn startup(s: *Send, id: usize, set: Set, e: *const Exec) ?[]const u8 { +fn startup(s: *Send, id: usize, set: Set, e: *const Exec) Sent { const act = for (set.acts) |a| { if (a.verb == .start) break a; if (a.verb == .client) { - if (e.m.dst.len == 0) return e_client; + if (e.m.dst.len == 0) return .{ .refused = e_client }; break a; } - } else return e_no_start; + } else return .{ .refused = e_no_start }; // buildargv: one expansion a word. var argv: std.ArrayList([]const u8) = .empty; var rest = act.arg; @@ -764,63 +925,144 @@ fn startup(s: *Send, id: usize, set: Set, e: *const Exec) ?[]const u8 { rest = std.mem.trimStart(u8, rest, " \t"); if (rest.len == 0) break; var buf: [4096]u8 = undefined; - const word, const took = expand(&s.rules, e, rest, &buf) catch return "string-too-long"; - argv.append(s.arena, s.arena.dupe(u8, word) catch return "out of memory") catch return "out of memory"; + const word, const took = expand(&s.rules, e, rest, &buf) catch return .{ .refused = "string-too-long" }; + argv.append(s.arena, s.arena.dupe(u8, word) catch return .{ .refused = "out of memory" }) catch return .{ .refused = "out of memory" }; rest = rest[took..]; } - if (argv.items.len == 0) return e_empty; - run(s.p, id, e.m.wdir, argv.items); - return null; + if (argv.items.len == 0) return .{ .refused = e_empty }; + if (run(s.p, id, e.m.wdir, argv.items)) |why| return .{ .refused = why }; + // `client`: the message waits for the port's first reader, the program + // it started perhaps (plumber(4)'s hold); held messages past what the + // queue keeps push out the oldest. + if (act.verb == .client) if (portIndex(s.p, e.m.dst)) |i| { + if (!enqueue(s.p, &s.p.fs.plumb_held, &.{i}, e.m)) return .{ .refused = "plumb: message too big to hold for a client" }; + }; + return .done; } -/// What a `plumb start` (and, until ports are read, a `plumb client`) runs: +/// What a `plumb start` or a `plumb client` runs: /// the one place that decides it (question 4 of docs/next-plumber.md). -/// Its words as pardes's exec runs a line from the message's pane: a -/// builtin or a kind's word in place, any other line a command pane in -/// `wdir`, each word one argument to $SHELL -c however it is spelled. -/// Plan 9's runs detached, with no window. -fn run(p: *Pardes, id: usize, wdir: []const u8, argv: []const []const u8) void { +/// A builtin or a kind's word runs in place, from the message's pane, as +/// a line of it would; one that cannot do what the message asks declines +/// (Pardes.plumb_declined), saying nothing, and the send is refused, so a +/// look looks itself. Any other is a program, started as Plan 9's plumber +/// starts one (match.c's startup): detached, no pane, its argv exec'd in +/// `wdir` with no shell (a rule that wants one says `sh -c`), by the host +/// (Effect.start), which says a failure to start in the log. Null when it +/// ran, else why not. +fn run(p: *Pardes, id: usize, wdir: []const u8, argv: []const []const u8) ?[]const u8 { const arena = p.scratch.allocator(); - const line = std.mem.join(arena, " ", argv) catch return p.reportError(id, "plumb", error.OutOfMemory); - if (p.executeBuiltinLine(id, line)) return; - var quoted: std.Io.Writer.Allocating = .init(arena); - for (argv, 0..) |a, i| { - if (i > 0) quoted.writer.writeByte(' ') catch return; - quoted.writer.writeByte('\'') catch return; - for (a) |c| { - if (c == '\'') { - quoted.writer.writeAll("'\\''") catch return; - } else quoted.writer.writeByte(c) catch return; - } - quoted.writer.writeByte('\'') catch return; - } - p.exec_dir = if (wdir.len > 0) wdir else null; - defer p.exec_dir = null; - _ = exec.runCommand(p, id, quoted.written()); + const line = std.mem.join(arena, " ", argv) catch return "out of memory"; + const outer = p.plumb_declined; + p.plumb_declined = false; + defer p.plumb_declined = outer; + // Started, not clicked: no name said for it under Verbose. + const announce = p.announce; + p.announce = false; + defer p.announce = announce; + if (p.executeBuiltinLine(id, line)) return if (p.plumb_declined.?) e_declined else null; + // Its directory, then its words, each ended by a NUL. + var start: pardes.Effect.Buf(pardes.effect_path_cap) = .{}; + for ([_][]const []const u8{ &.{wdir}, argv }) |words| for (words) |w| { + if (std.mem.indexOfScalar(u8, w, 0) != null) return "plumb start: a NUL in a word"; + if (start.len + w.len + 1 > start.data.len) return std.fmt.comptimePrint("plumb start: over {d} bytes", .{pardes.effect_path_cap}); + @memcpy(start.data[start.len..][0..w.len], w); + start.data[start.len + w.len] = 0; + start.len += @intCast(w.len + 1); + }; + p.emit(.{ .start = .{ .pane = @intCast(id), .line = start } }); + return null; } /// What pardes does with a message to a port it reads. Like a message /// queued to a reader in Plan 9, the send is done: what goes wrong after /// is said as a look's failure is. -fn deliver(s: *Send, id: usize, port: Port, m: *const Msg) void { +fn deliver(s: *Send, id: usize, port: Port, m: *const Msg) Sent { const p = s.p; switch (port) { .web => { - if (m.data.len > 256) return p.reportFailure(id, "plumb: web: a URL is at most 256 bytes"); - p.emit(.{ .open_link = .from(m.data) }); + if (m.data.len > 256) p.reportFailure(id, "plumb: web: a URL is at most 256 bytes") else p.emit(.{ .open_link = .from(m.data) }); }, .edit => { - // acme's plumblook: the data a name in wdir, at its addr. + // acme's plumbshow, for `plumb -i`: the data shown, not a name. + var action_buf: [4096]u8 = undefined; + const action = attrValue(m.attr, "action", &action_buf) orelse ""; + if (std.mem.eql(u8, action, "showdata") or std.mem.eql(u8, action, "showdiff")) { + show(s, id, m, std.mem.eql(u8, action, "showdiff")); + return .done; + } var buf: [4096]u8 = undefined; const addr = attrValue(m.attr, "addr", &buf) orelse ""; + // A look's own name, as it sent it: its own look opens it. + if (s.looked) |data| if (addr.len == 0 and std.mem.eql(u8, data, m.data)) return .look; + // acme's plumblook: the data a name in wdir, at its addr, + // opened as Look opens one and not sent again. const relative = m.data.len > 0 and m.data[0] != '/' and m.data[0] != '~' and m.wdir.len > 0; const text = std.fmt.allocPrint(s.arena, "{s}{s}{s}{s}{s}", .{ if (relative) m.wdir else "", if (relative) "/" else "", m.data, if (addr.len > 0) ":" else "", addr, - }) catch return p.reportError(id, "plumb", error.OutOfMemory); + }) catch { + p.reportError(id, "plumb", error.OutOfMemory); + return .done; + }; + const was = p.look_text; + p.look_text = true; + defer p.look_text = was; look.lookAt(p, id, text); }, } + return .done; +} + +/// The edit port's `showdata` and `showdiff` (acme's plumbshow): the data +/// in the pane `filename` names, the pane that sent it first (a +Pager's +/// own text), else a new one so named (`+Plumbed` with none), clean; +/// `showdiff` then stacks it in a +Diff in that pane's place (hunks.paged), +/// as a diff paged always was. +fn show(s: *Send, id: usize, m: *const Msg, diff: bool) void { + const p = s.p; + var buf: [4096]u8 = undefined; + const filename = attrValue(m.attr, "filename", &buf) orelse ""; + const named = std.mem.eql(u8, filename, if (p.panes[id]) |pn| (if (pn.file) |f| f.path else "") else ""); + const shown: usize = if (named) id else shown: { + const name = if (filename.len > 0) filename else "+Plumbed"; + const free = p.freeSlot() orelse return p.reportError(id, "plumb", error.NoPaneSlots); + pardes.panes.newScratchFor(p, id, .scratch); + const made = p.panes[free] orelse return; + @import("ninep/pane.zig").nameBuffer(p, free, name, false) catch |err| return p.reportError(id, "plumb", err); + const f = &made.file.?; + _ = pardes.panes.File.replace(p, f, 0, f.content.len, m.data); + f.saved_revision = f.revision; + break :shown free; + }; + if (diff) @import("hunks.zig").paged(p, shown); +} + +/// A +Pager filled (ninep/ctl.zig fillPager) with a diff (File.looksLikeDiff: +/// `git show`, a mailed patch): sent to `edit`, as acme's `plumb -i` +/// sends what it shows, `type text/x-diff`, `action=showdata` and the +/// +Pager's name; the default rules make it `showdiff`, stacked in a +Diff +/// in the +Pager's place. Other text paged is not sent: the look rules +/// would read it whole (a `matches` over a MiB of output, up to the +/// regular expressions' budget, at each page). +pub fn paged(p: *Pardes, id: usize) void { + const pane = p.panes[id] orelse return; + const f = pane.file orelse return; + if (!f.pager_diff) return; + var attr: std.Io.Writer.Allocating = .init(p.scratch.allocator()); + attr.writer.writeAll("action=showdata filename=") catch return; + // mesg.c's quote, for a name with a blank, a quote, `=` or a tab. + const quote = std.mem.indexOfAny(u8, f.path, " '=\t") != null; + if (quote) attr.writer.writeByte('\'') catch return; + for (f.path) |c| { + if (c == '\'') attr.writer.writeByte('\'') catch return; + attr.writer.writeByte(c) catch return; + } + if (quote) attr.writer.writeByte('\'') catch return; + switch (send(p, id, .{ .src = "pager", .dst = "edit", .wdir = Pardes.paneDir(pane), .type = "text/x-diff", .attr = attr.written(), .data = f.content }, null)) { + .done, .look => {}, + .refused => |why| p.reportFailure(id, why), + } } /// A message to a loaded kind's port: its data, a file, opened in that kind @@ -992,7 +1234,7 @@ test "plumb: rc's quoting, variables and the message's in an expansion, the firs const Tried = struct { m: Msg, set: ?usize }; fn tryRules(p: *Pardes, text: []const u8, msg: Msg) !Tried { - try testing.expect(apply(p, false, text) == null); + try testing.expect(apply(p, false, "plumb/rules", text) == null); const arena = p.scratch.allocator(); var s: Send = .{ .p = p, .from = null, .arena = arena, .rules = try rulesOf(p, arena) }; var m = msg; @@ -1100,29 +1342,29 @@ test "plumb: dispose: no rule and no dst, a start, the web port, a port no rule const p = try Pardes.init(testing.allocator, .{ .cols = 80, .rows = 24 }); defer p.deinit(); _ = try p.setTestFile("x\n"); - try testing.expect(apply(p, false, "include basic\n\ntype\tis\tmsg\nplumb\tstart\tMsg $data\n\ntype\tis\tnone\nplumb\tto\tnobody\n\ntype\tis\tclient\nplumb\tclient\tMsg x\n\n") == null); - try testing.expectEqualStrings(e_no_port, send(p, null, .{ .type = "text", .data = "no such thing" }).?); + try testing.expect(apply(p, false, "plumb/rules", "include basic\n\ntype\tis\tmsg\nplumb\tstart\tMsg $data\n\ntype\tis\tnone\nplumb\tto\tnobody\n\ntype\tis\tclient\nplumb\tclient\tMsg x\n\n") == null); + try testing.expectEqualStrings(e_no_port, send(p, null, .{ .type = "text", .data = "no such thing" }, null).refused); // A start of a builtin runs it in place. - try testing.expect(send(p, null, .{ .type = "msg", .data = "hello" }) == null); + try testing.expect(send(p, null, .{ .type = "msg", .data = "hello" }, null) == .done); const pane = p.panes[p.view().active].?; try testing.expectEqualStrings("hello", pane.msg[0..pane.msg_len]); - try testing.expectEqualStrings(e_client, send(p, null, .{ .type = "client" }).?); - try testing.expectEqualStrings(e_no_start, send(p, null, .{ .type = "none" }).?); - try testing.expectEqualStrings(e_no_start, send(p, null, .{ .dst = "nobody", .type = "x" }).?); + try testing.expectEqualStrings(e_client, send(p, null, .{ .type = "client" }, null).refused); + try testing.expectEqualStrings(e_no_start, send(p, null, .{ .type = "none" }, null).refused); + try testing.expectEqualStrings(e_no_start, send(p, null, .{ .dst = "nobody", .type = "x" }, null).refused); // A port no rule names goes nowhere, said nothing (fsys.c's dispose). - try testing.expect(send(p, null, .{ .dst = "elsewhere", .data = "x" }) == null); + try testing.expect(send(p, null, .{ .dst = "elsewhere", .data = "x" }, null) == .done); // A URL to the web port: the host's opener. while (p.nextEffect()) |_| {} - try testing.expect(send(p, null, .{ .type = "text", .data = "https://ziglang.org" }) == null); - var opened = false; + try testing.expect(send(p, null, .{ .type = "text", .data = "https://ziglang.org" }, null) == .done); + var linked = false; while (p.nextEffect()) |e| switch (e) { .open_link => |u| { try testing.expectEqualStrings("https://ziglang.org", u.slice()); - opened = true; + linked = true; }, else => {}, }; - try testing.expect(opened); + try testing.expect(linked); } test "plumb: rules written replace or add, a refusal keeps them as they were, and a dump keeps them" { @@ -1131,10 +1373,10 @@ test "plumb: rules written replace or add, a refusal keeps them as they were, an // Every session starts with the defaults. try testing.expect(std.mem.indexOf(u8, inForce(p), "plumb\tto\tweb") != null); try testing.expect(!p.plumber.written); - try testing.expect(apply(p, false, "type is a\nplumb to edit\n") == null); - try testing.expect(apply(p, true, "type is b\nplumb to edit\n") == null); + try testing.expect(apply(p, false, "plumb/rules", "type is a\nplumb to edit\n") == null); + try testing.expect(apply(p, true, "plumb/rules", "type is b\nplumb to edit\n") == null); try testing.expectEqualStrings("type\tis\ta\nplumb\tto\tedit\n\ntype\tis\tb\nplumb\tto\tedit\n\n", p.plumber.text.items); - try testing.expectEqualStrings("plumb/rules:1: unknown verb isnt", apply(p, true, "type isnt c\n").?); + try testing.expectEqualStrings("plumb/rules:1: unknown verb isnt", apply(p, true, "plumb/rules", "type isnt c\n").?); try testing.expectEqualStrings("type\tis\ta\nplumb\tto\tedit\n\ntype\tis\tb\nplumb\tto\tedit\n\n", p.plumber.text.items); try pardes.dump.dumpState(p); const restored = try pardes.dump.restore(p, p.dump_out.?, "/tmp/pardes.dump.zon"); @@ -1239,3 +1481,86 @@ test "plumb: plan9port's basic parses, its ¡- classes UTF-8's bytes and its // The rune range as written is refused, in regexp.zig's words. try testing.expectEqualStrings("t:1: bad regular expression: a range of runes wider than 256 in [...] is not supported", try reread(arena.allocator(), "data matches '[a-zA-Z¡-0-9_\\-./]+'\nplumb to edit\n")); } + +test "plumb: the Plumb word opens the plumbing file, include basic until one is saved; saved, or read at boot, its rules are in force, a bad one said with its line" { + if (!fs.platform_has_fs) return; + var tmp = testing.tmpDir(.{}); + defer tmp.cleanup(); + var dir_buf: [4096]u8 = undefined; + const root = dir_buf[0..try tmp.dir.realPath(testing.io, &dir_buf)]; + const p = try Pardes.init(testing.allocator, .{ .cols = 100, .rows = 30, .config_dir = root }); + defer p.deinit(); + _ = try p.setTestFile("x\n"); + var path_buf: [4096]u8 = undefined; + const path = filePath(p, &path_buf).?; + try testing.expect(std.mem.endsWith(u8, path, "/plumbing")); + // Not there yet: a pane of its name holding `include basic`. + try testing.expect(p.executeBuiltinLine(0, "Plumb")); + const made = p.panes[p.view().active].?; + try testing.expectEqualStrings(path, made.file.?.path); + try testing.expectEqualStrings("include basic\n", made.file.?.content); + // A rule after the word is refused, in words. + try testing.expect(p.executeBuiltinLine(0, "Plumb suffix .svg to image")); + const first = p.panes[0].?; + try testing.expectEqualStrings(e_word, first.msg[0..first.msg_len]); + // Saved: its rules, or why not, the rules as they were. + saved(p, 0, path, "type is text\ndata matches 'x.*'\nplumb to web\n"); + try testing.expectEqualStrings("type\tis\ttext\ndata\tmatches\t'x.*'\nplumb\tto\tweb\n\n", inForce(p)); + saved(p, 0, path, "type is text\ndata isnt x\nplumb to web\n"); + try testing.expectEqualStrings("plumbing:2: unknown verb isnt", first.msg[0..first.msg_len]); + try testing.expectEqualStrings("type\tis\ttext\ndata\tmatches\t'x.*'\nplumb\tto\tweb\n\n", inForce(p)); + // Another file saved is no plumbing. + saved(p, 0, "/elsewhere/plumbing", "type is text\nplumb to edit\n"); + try testing.expect(std.mem.indexOf(u8, inForce(p), "'x.*'") != null); + // At boot: the file's rules. + try tmp.dir.writeFile(testing.io, .{ .sub_path = "plumbing", .data = "type is text\ndata matches 'y.*'\nplumb to web\n" }); + const q = try Pardes.init(testing.allocator, .{ .cols = 100, .rows = 30, .config_dir = root }); + defer q.deinit(); + try testing.expectEqualStrings("type\tis\ttext\ndata\tmatches\t'y.*'\nplumb\tto\tweb\n\n", inForce(q)); +} + +test "plumb: a diff paged is sent to edit, stacked in a +Diff by the default rule; without it the +Pager stays, and a reader of plumb/edit gets it" { + const p = try Pardes.init(testing.allocator, .{ .tty_only = true }); + defer p.deinit(); + const page = "commit 0123456789abcdef0123456789abcdef01234567\ndiff --git a/x b/x\n--- a/x\n+++ b/x\n@@ -1 +1 @@\n-old\n+new\n"; + const Page = struct { + fn fill(pp: *Pardes, text: []const u8) !usize { + const id = try pardes.panes.Output.openPager(pp, 0, "/pardes-plumb-page"); + var held: std.ArrayList(u8) = .empty; + defer held.deinit(pp.gpa); + try held.appendSlice(pp.gpa, text); + try @import("ninep/ctl.zig").fillPager(pp, pp.panes[id].?.serial, &held); + return id; + } + fn diffs(pp: *Pardes) usize { + var n: usize = 0; + for (pp.panes) |slot| if (slot) |pn| if (pn.file) |f| { + n += @intFromBool(std.mem.indexOf(u8, f.path, "/+Diff") != null); + }; + return n; + } + }; + // The defaults: the +Pager stacked into a +Diff, and gone. + const stacked = try Page.fill(p, page); + try testing.expect(p.panes[stacked] == null or !std.mem.endsWith(u8, p.panes[stacked].?.file.?.path, "+Pager")); + try testing.expectEqual(@as(usize, 1), Page.diffs(p)); + // Text that is no diff is not sent: its +Pager stays, as ever. + const plain = try Page.fill(p, "just text\n"); + try testing.expect(std.mem.endsWith(u8, p.panes[plain].?.file.?.path, "+Pager")); + // The paged-diff rule taken out: the edit port shows the data where + // it is, and the +Pager stays as text. + try testing.expect(apply(p, false, "plumb/rules", "type is text\narg isfile $data\nplumb to edit\n") == null); + const kept = try Page.fill(p, page); + try testing.expect(std.mem.endsWith(u8, p.panes[kept].?.file.?.path, "+Pager")); + try testing.expectEqualStrings(page, p.panes[kept].?.file.?.content); + try testing.expectEqual(@as(usize, 1), Page.diffs(p)); + // From another sender: shown in a pane of its filename's, clean, and + // with showdiff stacked. + try testing.expect(send(p, 0, .{ .src = "test", .dst = "edit", .type = "text", .attr = "action=showdata filename=/elsewhere/notes", .data = "a note\n" }, null) == .done); + const shown = p.panes[p.view().active].?; + try testing.expectEqualStrings("/elsewhere/notes", shown.file.?.path); + try testing.expectEqualStrings("a note\n", shown.file.?.content); + try testing.expectEqual(shown.file.?.revision, shown.file.?.saved_revision); + try testing.expect(send(p, 0, .{ .src = "test", .dst = "edit", .type = "text/x-diff", .attr = "action=showdiff filename=/elsewhere/change", .data = page }, null) == .done); + try testing.expectEqual(@as(usize, 2), Page.diffs(p)); +} |
