diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-23 13:12:37 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-23 15:09:24 -0300 |
| commit | 5296843dd27297bee3cbcf123426a9de17b33dfb (patch) | |
| tree | 6a9dc2abc8096ea79f33d9083e93f4a4dc02850e | |
| parent | 62c6caf414fd5a2be556f76eb21d1d6d8d3beadb (diff) | |
| download | pardes-5296843dd27297bee3cbcf123426a9de17b33dfb.tar.gz pardes-5296843dd27297bee3cbcf123426a9de17b33dfb.zip | |
changes layer: `Compare <rev> <rev> [<rev> ...]`, the user's three-way view compressed: between each two consecutive points of the history ONE change, the file's whole difference between them however many commits lie between (the user, 2026-11-23, of `Changes (9ef..ea6) | (ea6..master@origin)`'s six lanes on cpi.rs: "they should be compressed so its only two changes"), each a pin of the layer as a commit is, so every part of the layer and what round 8 does to pins serves it with no second implementation: TESTS FIRST (core/jj.zig, a throwaway jj repository, the pane's surface, terminal and window): three points on one line of history (`Compare @----- @--- @-` over five commits) are two pins, each pair's row `from..to 2 changes day` after its last line, who wrote each line (b2 the first pair, d2 and e the second), the rows as the view shows them with the lines each took away where they stood and no number on the layer's, each pair's lane its own colour, `]g`, bare `Compare` hiding and showing the set without asking jj, `Changes` after it replacing it and it `Changes`'; two points neither the other's ancestor (two branches: `1 change, 1 undone`, each changed line's old text above it, the patch's `+` and `-` lines); a revision's pane at the middle point (`At @---`: the first pair behind, as at the last; the second drawn as round 7 draws a change ahead, as behind it: the test's want is marked for round 8's merge); one point, bare with nothing pinned, a point naming two commits (jj's words, `more than one revision`) and an unknown one refused, nothing pinned; a B3 on a pair's row's first word opening its patch (`Compare from..to`, the changes between newest first each signed, the hunks, the cursor on the pair's last line, typed the same); a client replaying it equal and its pairs crossing a join whole (`loadsAsSession`); on a worker, the word returning at once and the answer landing as one input; each failing on the base (no word `Compare`); THE CHANGE: the struct `Ask` (its `Kind` gains `compare`, and `word`, each kind's name in its notices: a rename is that line and the builtin's) and two functions, `answer` (one line: a Compare's runs are `pairsAnswer`'s) and `parse` (one line: who wrote each line from the pairs' hunks, `pairOwners`, where a Changes reads jj's annotation); `pairsAnswer`/`pairRuns` answer in the shape a `Changes` gets: the clock, for each pair an entry line as `logTemplate` writes one (its id the first point's change, its title the pair's row from one `jj log` a pair: `f`/`t` the points, `+` a change in the second not the first, `-` the other way, the author's day) then `jj diff --from --to --git --context=0 -- FILE` (an empty difference: an entry not pinned), then from the last point to the revision shown an entry not pinned whose hunks carry the places (`carried`, unchanged), and jj's text of the revision shown (`jj file show`, lined up with the pane's as the annotation's text is); `pairOwners` walks that text back through the steps' hunks, the newest step a line's (a carrier's nobody's), and `provenance`'s last lines are `linedUp`, shared; `describe` gives a pair its row (`isPair`: a title starting with its id and `..`), `lookGhost` passes a pair row's first word whole (`Diff from..to path:line`), `diffPair` (hunks.zig's `Diff` before `diffChange`) is that patch: `jj diff --from --to --git [-- path]` under `Compare from..to` and the changes between (no plumbing rule for `x..y`: a `matches` rule compiles its regexp at every plumb, and an open plumbs: it cost every open about 9,100 instructions in the perf gate, so a Look on `from..to` in running text searches), `standAt` is `diffChange`'s cursor placing, shared; `changesWord`'s body is `pinWord(kind)` for both words (bare as bare Changes; fewer than two points refused in words), `ask`/`receive`/`pinAnswer` name the kind's word; config.zig `Compare` has no leader path (it needs its points); builtins.zig, both builtins lists; NOT TOUCHED: `File.fillBody`, the ghosts' geometry, `ghostsOf`, `carried`, `nest`, `hunksOf`, the paint; nothing new in any replicated struct (a pair is a `Pin`, its row in `ghost_text`, its points in `Changes.revset`, all made by `parse` in every process from the one input): wire 31; THE GATE (ws-svc, loads 2-8): tui core-test 943/1109 (166 skipped) and shell-test 1151/1154 (3 skipped) in Debug and in ReleaseSafe (the base, my first run: 936/1102 and 1144/1147; ReleaseSafe run under bin/sig: from a background chain without it the four host_io Ctrl-C tests fail, as the rules say), behaviour-test and --replay 276/276 (20 seeds, 0 failures), test/daemon.py plain and --clients on the Debug install, the user's case run (agave's cpi.rs, `Compare 9ef6312813 ea63317630 master@origin`: two lanes, rows `ozlwptts..pyquzokk 4 changes, 1 undone 2026-09-25..2026-11-03` and `pyquzokk..rmrksrzs 2 changes 2026-11-05..2026-11-09`, jj's answer on the worker in 1.5 s, agave's operation log untouched); the frame and perf gate against tree6 (gpu/cmp1-g2): 77/77 frames, gui unit-test 1748/1752 (no failure the base has not), perfab corpus2x +0.022% (noise 0.044%), perfops 33 of 121 over against tree6, exactly the base line's own 33 (the coordinator's gpu/merge63-g: body-appends +12.026%/+8.068%), and against that gate's candidate all 121 within 0.1% (largest client-key-down small +0.037%)
Co-Authored-By: Claude Opus <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
| -rw-r--r-- | core/builtins.zig | 6 | ||||
| -rw-r--r-- | core/config.zig | 1 | ||||
| -rw-r--r-- | core/hunks.zig | 8 | ||||
| -rw-r--r-- | core/jj.zig | 694 | ||||
| -rw-r--r-- | docs/typ/builtins-gui.json | 1 | ||||
| -rw-r--r-- | docs/typ/builtins-tui.json | 1 |
6 files changed, 678 insertions, 33 deletions
diff --git a/core/builtins.zig b/core/builtins.zig index e6d22c17..51f22bcb 100644 --- a/core/builtins.zig +++ b/core/builtins.zig @@ -1086,6 +1086,12 @@ pub const Changes = struct { pub const run = @import("jj.zig").changesWord; }; +/// Pin on a file's pane the file's whole difference between each two of `points` (jj revisions, a blank between, two or more) as one change, however many changes lie between them, and show them in this view as `Changes` shows a change: a lane each, the lines it wrote and took away, its row `from..to N changes dates` after its last line; bare, as bare `Changes`. +pub const Compare = struct { + pub const takes_arg = true; + pub const run = @import("jj.zig").compareWord; +}; + /// Count, for each declaration of a file's pane, the changes in `window` (jj) that touched it, and show it in this view: a heat lane after the line number and a strip by the scroll thumb, the line numbers' grey to the theme's red on a log scale; `window` a revset or a span of time (`3d`, `2w`, `6m`, `1y`); bare, shown here or not (none counted yet: the file's whole history). pub const Churn = struct { pub const takes_arg = true; diff --git a/core/config.zig b/core/config.zig index aae832f4..a2911dad 100644 --- a/core/config.zig +++ b/core/config.zig @@ -78,6 +78,7 @@ pub const leader_path = paths: { .Diff = null, .At = null, .Changes = "tc", + .Compare = null, .Churn = "tu", .Mode = null, .Togglettymode = null, diff --git a/core/hunks.zig b/core/hunks.zig index e109b788..d8c5e2de 100644 --- a/core/hunks.zig +++ b/core/hunks.zig @@ -703,7 +703,9 @@ fn trimmedWidth(ctx: *const Ctx, section: []const u8) usize { /// a digit among them), `git show` of it, paged into a +Pager that stacks /// its hunks (ctl.fillPager), run in the pane's git work tree; with a jj /// change (`Diff wrnnmymq [path[:line]]`: jj.diffChange), its patch, header -/// and all, the cursor at that place in it. A plumbing +/// and all, the cursor at that place in it; with two points joined by `..` +/// (`Diff ozlwptts..pyquzokk [path[:line]]`: jj.diffPair), the difference +/// between them, the changes between on top. A plumbing /// rule's Diff that cannot (no hunk, no work tree) declines, saying /// nothing (Pardes.plumb_declined), and the look looks itself. pub fn word(c: pardes.builtins.Ctx) void { @@ -733,7 +735,9 @@ pub fn word(c: pardes.builtins.Ctx) void { if (p.panes[dst]) |cp| cp.command_pages = true; return; } - // A jj change (its letters k to z), with a place in its patch to stand at. + // A jj change (its letters k to z), with a place in its patch to stand at; + // two points joined by `..`, a `Compare`'s pair. + if (@import("jj.zig").diffPair(p, c.id, arg)) return; if (@import("jj.zig").diffChange(p, c.id, arg)) return; if (@import("jj.zig").isChangeId(arg[0 .. std.mem.indexOfAny(u8, arg, " \t") orelse arg.len])) return declined(p, c.id, "Diff: no such change"); var buf: [4096]u8 = undefined; diff --git a/core/jj.zig b/core/jj.zig index 1ec1a0dc..86c12d3c 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -403,9 +403,29 @@ pub const Ghost = struct { /// yet: `@`, the change against its parent). What jj refuses is said in /// its words. pub fn changesWord(c: pardes.builtins.Ctx) void { + pinWord(c, .changes); +} + +/// The `Compare` word (builtins.zig registers it): in a file's pane (or a +/// revision's), between each two of its points (revisions, a blank +/// between, each one commit: a commit or change id, a bookmark, `@`), in +/// their order, the whole difference of the file, however many changes lie +/// between the two, pinned as `Changes` pins a change (`pairsAnswer`): a +/// lane, the lines it wrote and took away, its row `from..to N changes +/// dates`. Bare: as bare `Changes`. One set a pane: the last of the two +/// words asked replaces the other's. +pub fn compareWord(c: pardes.builtins.Ctx) void { + pinWord(c, .compare); +} + +/// `Changes`' and `Compare`'s one road (`kind`): a revset, or two points +/// or more, asked of jj for the pane; bare, the pane's set hidden in this +/// view or shown. +fn pinWord(c: pardes.builtins.Ctx, kind: Ask.Kind) void { const p = c.p; const pane = c.pane; - const f = if (pane.file) |*file| file else return p.reportFailure(c.id, "Changes: only a file's pane takes it"); + var said: pardes.Kind.Buf(128) = .{}; + const f = if (pane.file) |*file| file else return p.reportFailure(c.id, said.print("{s}: only a file's pane takes it", .{kind.word()})); const arg = std.mem.trim(u8, c.arg orelse "", " \t\r\n"); if (arg.len == 0 and pane.layers.lanes > 0) { pane.layers.lanes = 0; @@ -417,15 +437,20 @@ pub fn changesWord(c: pardes.builtins.Ctx) void { return; } const revset = if (arg.len == 0) "@" else arg; - if (revset.len > Changes.revset_max) return p.reportFailure(c.id, "Changes: a revset that long"); + if (kind == .compare) { + var points = std.mem.tokenizeAny(u8, arg, " \t"); + _ = points.next(); + if (points.next() == null) return p.reportFailure(c.id, said.print("{s}: two points or more, each one revision", .{kind.word()})); + } + if (revset.len > Changes.revset_max) return p.reportFailure(c.id, said.print("{s}: a revset that long", .{kind.word()})); const shown: struct { path: []const u8, rev: []const u8 } = if (of(f)) |r| .{ .path = r.path, .rev = r.rev } else if (f.output == null and pardes.filesystem.localPath(f.path) != null) .{ .path = f.path, .rev = "@" } else - return p.reportFailure(c.id, "Changes: only a file's pane takes it"); + return p.reportFailure(c.id, said.print("{s}: only a file's pane takes it", .{kind.word()})); pane.layers.lanes = cells; - ask(p, .changes, c.id, pane.serial, shown.path, shown.rev, revset); + ask(p, kind, c.id, pane.serial, shown.path, shown.rev, revset); } /// The `Churn` word (builtins.zig registers it): in a file's pane (or a @@ -498,9 +523,24 @@ pub const Ask = struct { rev: []u8, revset: []u8, - /// `Changes`' (with who wrote each line), or `Churn`'s (with jj's text - /// of the revision, which the counts are lined up with). - pub const Kind = enum(u8) { changes, churn }; + /// `Changes`' (with who wrote each line), `Churn`'s (with jj's text + /// of the revision, which the counts are lined up with), or `Compare`'s + /// (its pairs as `Changes`' changes, with jj's text of the revision: + /// `pairsAnswer`). + pub const Kind = enum(u8) { + changes, + churn, + compare, + + /// The word that asks it, as its notices name it. + pub fn word(k: Kind) []const u8 { + return switch (k) { + .changes => "Changes", + .churn => "Churn", + .compare => "Compare", + }; + } + }; fn make(gpa: std.mem.Allocator, kind: Kind, gen: u32, serial: u32, path: []const u8, rev: []const u8, revset: []const u8) error{OutOfMemory}!*Ask { const a = try gpa.create(Ask); @@ -579,7 +619,8 @@ fn liveGen(c: *const Session) u32 { fn ask(p: *Pardes, kind: Ask.Kind, id: usize, serial: u32, path: []const u8, rev: []const u8, revset: []const u8) void { p.changes.count +%= 1; const a = Ask.make(p.gpa, kind, liveGen(&p.changes), serial, path, rev, revset) catch return p.reportFailure(id, "Changes: out of memory"); - p.setStatus(.at(id), if (kind == .churn) "Churn: jj\u{2026}" else "Changes: jj\u{2026}"); + var said: pardes.Kind.Buf(32) = .{}; + p.setStatus(.at(id), said.print("{s}: jj\u{2026}", .{kind.word()})); if (p.changes.task != null) { if (p.changes.next) |old| old.deinit(); p.changes.next = a; @@ -624,6 +665,7 @@ pub fn runHere(p: *Pardes, gen: u32, comptime in_call: bool) void { /// jj's two answers for `a`, raw, in `gpa`: through `p`'s tape when given /// (on the loop), else run here (a worker). fn answer(p: ?*Pardes, gpa: std.mem.Allocator, a: *const Ask) pardes.Stream.Batch { + if (a.kind == .compare) return pairsAnswer(p, gpa, a); const failed = struct { fn f(g: std.mem.Allocator, at: *const Ask, why: []u8) pardes.Stream.Batch { _ = g; @@ -688,6 +730,135 @@ fn runJj(p: ?*Pardes, gpa: std.mem.Allocator, dir: []const u8, args: []const []c return if (p) |q| q.tape.site(.jj, gpa, runHost, .{ gpa, dir, args }) else runHost(gpa, dir, args); } +/// A `Compare`'s runs (`answer`), its answer in the shape a `Changes` gets, +/// which `parse` reads: the wall clock; for each two points in their order +/// an entry as `logTemplate` writes one, its id the first point's change, +/// its title the pair's row (`pairRow`), then the file's difference +/// between the two (`jj diff --from --to --git --context=0`: a pin whose +/// hunks are two trees' difference; an entry not pinned when there is +/// none); then from the last point to the revision shown an entry not +/// pinned, whose hunks carry the pairs' places there (none when the two +/// texts are one); and, for who wrote each line (`pairOwners`: jj has no +/// annotation of a pair), jj's text of the revision shown. What lies +/// between two points is named by ancestry (one `jj log` a pair: its row's +/// counts and dates); what is drawn is the two trees. +fn pairsAnswer(p: ?*Pardes, gpa: std.mem.Allocator, a: *const Ask) pardes.Stream.Batch { + var scratch: std.heap.ArenaAllocator = .init(gpa); + defer scratch.deinit(); + var rows: std.ArrayList(u8) = .empty; + const got = pairRuns(p, gpa, scratch.allocator(), a, &rows) catch refusal(gpa, "out of memory"); + switch (got) { + .refused => |why| { + rows.deinit(gpa); + return .{ .gen = a.gen, .rows = why, .end = .failed }; + }, + .bytes => |shown| { + const logged = rows.toOwnedSlice(gpa) catch { + rows.deinit(gpa); + gpa.free(shown); + return .{ .gen = a.gen, .rows = refusal(gpa, "out of memory").refused, .end = .failed }; + }; + return .{ .gen = a.gen, .rows = logged, .styles = shown, .end = .done }; + }, + } +} + +/// `pairsAnswer`'s runs, its entries and diffs onto `rows`: jj's text of +/// the revision shown, or what jj refused, in its words. +fn pairRuns(p: ?*Pardes, gpa: std.mem.Allocator, arena: std.mem.Allocator, a: *const Ask, rows: *std.ArrayList(u8)) error{OutOfMemory}!Shown { + const dir = dirOf(a.path); + const set = try fileset(arena, a.path); + const now = if (p) |q| q.tape.value(.clock, wallSeconds, .{}) else wallSeconds(); + try rows.print(gpa, "{d}\n", .{now}); + var points = std.mem.tokenizeAny(u8, a.revset, " \t"); + var from = points.next() orelse return refusal(gpa, "two points or more"); + var last: [8]u8 = @splat('z'); + while (points.next()) |to| { + const diffed = switch (runJj(p, gpa, dir, &.{ "diff", "--from", from, "--to", to, "--git", "--context=0", "--", set })) { + .refused => |why| return .{ .refused = why }, + .bytes => |b| b, + }; + defer gpa.free(diffed); + const between = try std.fmt.allocPrint(arena, "(({s})..({s}) | ({s})..({s})) & files({s})", .{ from, to, to, from, set }); + const revset = try std.fmt.allocPrint(arena, "({s}) | ({s}) | {s}", .{ from, to, between }); + const template = try std.fmt.allocPrint(arena, "change_id.short(8) ++ \"\\t\" ++ if(self.contained_in(\"({s})\"), \"f\") ++ if(self.contained_in(\"({s})\"), \"t\") ++ if(self.contained_in(\"{s}\"), if(self.contained_in(\"::({s})\"), \"+\", \"-\")) ++ \"\\t\" ++ author.timestamp().utc().format(\"%Y-%m-%d\") ++ \"\\n\"", .{ try quoted(arena, from), try quoted(arena, to), try quoted(arena, between), try quoted(arena, to) }); + const logged = switch (runJj(p, gpa, dir, &.{ "log", "--no-graph", "-r", revset, "-T", template })) { + .refused => |why| return .{ .refused = why }, + .bytes => |b| b, + }; + defer gpa.free(logged); + const row = pairRow(logged); + try rows.print(gpa, "{s}\t{c}\t0\t\t", .{ &row.from, @as(u8, if (diffed.len > 0) 'p' else 'c') }); + try row.say(gpa, rows); + try rows.append(gpa, '\n'); + try rows.appendSlice(gpa, diffed); + if (diffed.len > 0 and diffed[diffed.len - 1] != '\n') try rows.append(gpa, '\n'); + last = row.to; + from = to; + } + const carried_diff = switch (runJj(p, gpa, dir, &.{ "diff", "--from", from, "--to", a.rev, "--git", "--context=0", "--", set })) { + .refused => |why| return .{ .refused = why }, + .bytes => |b| b, + }; + defer gpa.free(carried_diff); + try rows.print(gpa, "{s}\tc\t0\t\t\n", .{&last}); + try rows.appendSlice(gpa, carried_diff); + return runJj(p, gpa, dir, &.{ "file", "show", "-r", a.rev, "--", set }); +} + +/// `text` as it goes inside a template's string literal. +fn quoted(arena: std.mem.Allocator, text: []const u8) error{OutOfMemory}![]u8 { + var out: std.ArrayList(u8) = .empty; + for (text) |c| { + if (c == '"' or c == '\\') try out.append(arena, '\\'); + try out.append(arena, c); + } + return out.toOwnedSlice(arena); +} + +/// A pair of points as its row says it (`pairsAnswer`'s `jj log`, a line a +/// change: its id, `f` the first point, `t` the second, `+` a change +/// between in the second and not the first, `-` one the other way (what +/// the difference takes back), its author's day). +const PairRow = struct { + from: [8]u8 = @splat('z'), + to: [8]u8 = @splat('z'), + brought: u32 = 0, + undone: u32 = 0, + first: [10]u8 = @splat(' '), + last: [10]u8 = @splat(' '), + + /// `from..to N changes, M undone first..last` (the parts there are). + fn say(r: *const PairRow, gpa: std.mem.Allocator, out: *std.ArrayList(u8)) error{OutOfMemory}!void { + try out.print(gpa, "{s}..{s}", .{ &r.from, &r.to }); + if (r.brought + r.undone == 0) return; + try out.print(gpa, " {d} change{s}", .{ r.brought, if (r.brought == 1) "" else "s" }); + if (r.undone > 0) try out.print(gpa, ", {d} undone", .{r.undone}); + try out.print(gpa, " {s}", .{&r.first}); + if (!std.mem.eql(u8, &r.first, &r.last)) try out.print(gpa, "..{s}", .{&r.last}); + } +}; + +fn pairRow(logged: []const u8) PairRow { + var r: PairRow = .{}; + var lines = std.mem.splitScalar(u8, logged, '\n'); + while (lines.next()) |l| { + var cols = std.mem.splitScalar(u8, l, '\t'); + const id = cols.next() orelse continue; + const marks = cols.next() orelse continue; + const day = cols.next() orelse continue; + if (id.len != 8) continue; + if (std.mem.indexOfScalar(u8, marks, 'f') != null) r.from = id[0..8].*; + if (std.mem.indexOfScalar(u8, marks, 't') != null) r.to = id[0..8].*; + const side = std.mem.indexOfAny(u8, marks, "+-") orelse continue; + if (marks[side] == '+') r.brought += 1 else r.undone += 1; + if (day.len != 10) continue; + if (r.first[0] == ' ' or std.mem.order(u8, day, &r.first) == .lt) r.first = day[0..10].*; + if (r.last[0] == ' ' or std.mem.order(u8, day, &r.last) == .gt) r.last = day[0..10].*; + } + return r; +} + /// A `Changes` answer (`Event.search` with a `Changes` generation), /// borrowed: the last asked of its kind is parsed and pinned (or counted, /// a `Churn`'s) on its pane (the ask names it); an earlier one's, or a gone @@ -715,7 +886,7 @@ pub fn receive(p: *Pardes, b: *const pardes.Stream.Batch) void { if (p.changes.next) |n| if (n.kind == kind) return; const id = p.paneBySerial(serial) orelse return; switch (kind) { - .changes => pinAnswer(p, id, b, revset[0..revset_len]), + .changes, .compare => pinAnswer(p, id, b, revset[0..revset_len], kind), .churn => heatAnswer(p, id, b, revset[0..revset_len]), } } @@ -793,9 +964,9 @@ fn spliceValues(comptime T: type, gpa: std.mem.Allocator, values: *[]T, none: T, return .{ .from = from, .take = take, .put = put }; } -/// jj's answer `b` for `revset` parsed and pinned on pane `id`, or its -/// refusal said there. -fn pinAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, revset: []const u8) void { +/// jj's answer `b` for `revset` (a `Compare`'s points: `kind`) parsed and +/// pinned on pane `id`, or its refusal said there. +fn pinAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, revset: []const u8, kind: Ask.Kind) void { const pane = p.panes[id].?; var line: pardes.Kind.Buf(512) = .{}; const f = if (pane.file) |*file| file else return; @@ -803,18 +974,20 @@ fn pinAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, revset: []con defer if (answered(p, pane.serial) == null) { pane.layers.lanes = 0; }; - if (b.end == .failed) return p.reportFailure(id, line.print("Changes: {s}", .{b.rows[0..@min(b.rows.len, 480)]})); - var got = parse(p.gpa, p.scratch.allocator(), b.rows, b.styles, f.content) catch |err| return p.reportFailure(id, line.print("Changes: {s}", .{@errorName(err)})); + const name = kind.word(); + if (b.end == .failed) return p.reportFailure(id, line.print("{s}: {s}", .{ name, b.rows[0..@min(b.rows.len, 480)] })); + var got = parse(p.gpa, p.scratch.allocator(), b.rows, b.styles, f.content, kind == .compare) catch |err| return p.reportFailure(id, line.print("{s}: {s}", .{ name, @errorName(err) })); switch (got) { .refused => |why| { defer p.gpa.free(why); - return p.reportFailure(id, line.print("Changes: {s}", .{why[0..@min(why.len, 480)]})); + return p.reportFailure(id, line.print("{s}: {s}", .{ name, why[0..@min(why.len, 480)] })); }, .read => |*changes| { if (changes.pins.len == 0) { changes.deinit(p.gpa); - const shown = if (of(f)) |r| r.path else f.path; - return p.reportFailure(id, line.print("Changes: no change of `{s}` touches {s}", .{ revset, std.Io.Dir.path.basename(shown) })); + const shown = std.Io.Dir.path.basename(if (of(f)) |r| r.path else f.path); + if (kind == .compare) return p.reportFailure(id, line.print("{s}: no difference in {s} between `{s}`", .{ name, shown, revset })); + return p.reportFailure(id, line.print("{s}: no change of `{s}` touches {s}", .{ name, revset, shown })); } @memcpy(changes.revset[0..revset.len], revset); changes.revset_len = @intCast(revset.len); @@ -824,7 +997,7 @@ fn pinAnswer(p: *Pardes, id: usize, b: *const pardes.Stream.Batch, revset: []con kept.* = changes.*; } else p.changes.answers.append(p.gpa, changes.*) catch { changes.deinit(p.gpa); - return p.reportFailure(id, "Changes: out of memory"); + return p.reportFailure(id, line.print("{s}: out of memory", .{name})); }; p.setStatus(.at(id), ""); showGhosts(p, pane); @@ -961,8 +1134,9 @@ const Read = union(enum) { refused: []u8, read: Changes }; /// jj's answers parsed: `logged` (the pins, each with its diff of the /// file) and `annotated` (who wrote each line of `text`, what the pane -/// shows: a line is matched to the line its change added by its text). -fn parse(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, annotated: []const u8, text: []const u8) error{OutOfMemory}!Read { +/// shows: a line is matched to the line its change added by its text; a +/// `Compare`'s, `pairs`: jj's text of the revision shown, `pairOwners`). +fn parse(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, annotated: []const u8, text: []const u8, pairs: bool) error{OutOfMemory}!Read { var out: Changes = .{ .serial = 0 }; const now = std.fmt.parseInt(i64, logged[0 .. std.mem.indexOfScalar(u8, logged, '\n') orelse logged.len], 10) catch 0; var kept = false; @@ -987,7 +1161,7 @@ fn parse(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, a return .{ .read = out }; } var moved: Moved = undefined; - out.lines = try provenance(gpa, arena, annotated, out.pins, text, &moved); + out.lines = if (pairs) try pairOwners(gpa, arena, logged, steps.items, annotated, text, &moved) else try provenance(gpa, arena, annotated, out.pins, text, &moved); // Each change's hunks, and which of its lines a pin added whole. var hunks: std.ArrayList(Hunk) = .empty; defer hunks.deinit(gpa); @@ -1061,15 +1235,76 @@ pub fn provenance(gpa: std.mem.Allocator, arena: std.mem.Allocator, annotated: [ try was.append(arena, '\n'); } if (!std.mem.endsWith(u8, annotated, "\n") and was.items.len > 0) was.items.len -= 1; + return linedUp(gpa, owners.items, was.items, text, moved); +} + +/// A value a line of `text` from `owners`, a pin a line of jj's text +/// `was`: the two lined up by what they agree on at either end (`Moved`), +/// a line between nobody's; `moved`, where jj's lines stand in `text`. +fn linedUp(gpa: std.mem.Allocator, owners: []const PinIndex, was: []const u8, text: []const u8, moved: *Moved) error{OutOfMemory}![]Line { const out = try gpa.alloc(Line, lineCount(text)); @memset(out, .{ .pin = .none }); - moved.* = .of(was.items, text); - for (out[0..@min(moved.head, owners.items.len)], owners.items[0..@min(moved.head, owners.items.len)]) |*l, pin| l.pin = pin; - const tail = @min(moved.tail, owners.items.len); - for (out[out.len - tail ..], owners.items[owners.items.len - tail ..]) |*l, pin| l.pin = pin; + moved.* = .of(was, text); + for (out[0..@min(moved.head, owners.len)], owners[0..@min(moved.head, owners.len)]) |*l, pin| l.pin = pin; + const tail = @min(moved.tail, owners.len); + for (out[out.len - tail ..], owners[owners.len - tail ..]) |*l, pin| l.pin = pin; return out; } +/// Which pair of a `Compare` wrote each line of `text` (`provenance`'s +/// answer where jj annotates no pair): jj's text of the revision shown, +/// `was`, walked back through the steps' hunks from the last (each step's +/// diff in `logged`, from its entry to the next's): a line is the newest +/// step's that wrote it (a step not pinned writes it nobody's), one no +/// step wrote nobody's; then lined up with `text` as an annotation is. +fn pairOwners(gpa: std.mem.Allocator, arena: std.mem.Allocator, logged: []const u8, steps: anytype, was: []const u8, text: []const u8, moved: *Moved) error{OutOfMemory}![]Line { + const none = std.math.maxInt(u32); + const owners = try arena.alloc(PinIndex, lineCount(was)); + @memset(owners, .none); + const claimed = try arena.alloc(bool, owners.len); + @memset(claimed, false); + // Each line of the step's newer revision: its line of `was`, or none. + var at = try arena.alloc(u32, owners.len); + for (at, 0..) |*a, i| a.* = @intCast(i); + var k = steps.len - 1; + while (k > 0) { + k -= 1; + var hunks: std.ArrayList(diff.HunkHeader) = .empty; + var walk: diff.Walk = .{}; + var lines = std.mem.splitScalar(u8, logged[steps[k].diff..steps[k + 1].diff], '\n'); + while (lines.next()) |raw| if (walk.step(raw).kind == .hunk) try hunks.append(arena, diff.parseHunk(std.mem.trimEnd(u8, raw, "\r")).?); + var grew: i64 = 0; + for (hunks.items) |h| { + for (h.new_start -| 1..h.new_start -| 1 + h.new_count) |j| { + if (j >= at.len or at[j] == none or claimed[at[j]]) continue; + claimed[at[j]] = true; + if (steps[k].pin != Hunk.carrier) owners[at[j]] = @enumFromInt(steps[k].pin); + } + grew += @as(i64, @intCast(h.new_count)) - @as(i64, @intCast(h.old_count)); + } + // The older revision's lines: one a hunk took away is none. + const older = try arena.alloc(u32, @intCast(@max(0, @as(i64, @intCast(at.len)) - grew))); + var o: usize = 0; + var n: usize = 0; + for (hunks.items) |h| { + const old_from = if (h.old_count == 0) h.old_start else h.old_start -| 1; + const new_from = if (h.new_count == 0) h.new_start else h.new_start -| 1; + while (o < @min(old_from, older.len)) : ({ + o += 1; + n += 1; + }) older[o] = if (n < at.len) at[n] else none; + while (o < @min(old_from + h.old_count, older.len)) : (o += 1) older[o] = none; + n = new_from + h.new_count; + } + while (o < older.len) : ({ + o += 1; + n += 1; + }) older[o] = if (n < at.len) at[n] else none; + at = older; + } + return linedUp(gpa, owners, was, text, moved); +} + /// Where jj's lines (the revision it annotated) stand in the pane's text, /// which has keys typed since (before the word, never snapshotted, or /// while jj ran): its first `head` lines and its last `tail` are the same @@ -1369,8 +1604,10 @@ fn carried(hunks: []const Hunk, from: u16, after: u32, moved: Moved) ?u32 { /// A pin's description row (PARDES.md: compact, one blank between): its /// id's first four letters, its title, its author's first name, its age -/// short (`5h`, `2d`, `3w`, `4m`, `1y`; under an hour `now`), no "ago". +/// short (`5h`, `2d`, `3w`, `4m`, `1y`; under an hour `now`), no "ago". A +/// `Compare`'s pair: its row (`PairRow.say`), its title. fn describe(gpa: std.mem.Allocator, text: *std.ArrayList(u8), pin: Pin, now: i64) error{OutOfMemory}!void { + if (isPair(pin)) return text.appendSlice(gpa, pin.title[0..pin.title_len]); const author = pin.author[0..pin.author_len]; try text.print(gpa, "{s} {s} {s} ", .{ pin.id[0..4], pin.title[0..pin.title_len], author[0 .. std.mem.indexOfScalar(u8, author, ' ') orelse author.len] }); const s = @max(0, now - pin.time); @@ -1381,6 +1618,13 @@ fn describe(gpa: std.mem.Allocator, text: *std.ArrayList(u8), pin: Pin, now: i64 try text.appendSlice(gpa, "now"); } +/// A pin a `Compare` made of two points (`pairsAnswer`): its title, its +/// row, starts with its id (the first point's) and `..`. +fn isPair(pin: Pin) bool { + const title = pin.title[0..pin.title_len]; + return title.len > 10 and std.mem.startsWith(u8, title, &pin.id) and std.mem.startsWith(u8, title[8..], ".."); +} + /// The bytes a description row has at most, cut (`fitted`). pub const row_max = 256; @@ -1522,7 +1766,9 @@ pub fn lookGhost(p: *Pardes, id: usize, vr: i32, col: i32) bool { last = @max(last, h.new_start + h.new_len -| 1); }; var line: [4200]u8 = undefined; - const arg = std.fmt.bufPrint(&line, "{s} {s}:{d}", .{ ch.pins[g.pin].id, path, last }) catch return true; + // A pair's row starts with its two points (`from..to`): its patch. + const change: []const u8 = if (isPair(ch.pins[g.pin])) what else &ch.pins[g.pin].id; + const arg = std.fmt.bufPrint(&line, "{s} {s}:{d}", .{ change, path, last }) catch return true; pardes.exec.runBuiltin(p, .Diff, id, "Diff", arg); return true; } @@ -1579,14 +1825,20 @@ pub fn diffChange(p: *Pardes, id: usize, arg: []const u8) bool { const hid = @import("hunks.zig").openDiff(p, id, std.fmt.bufPrint(&name, "{s}/{s}", .{ std.mem.trimEnd(u8, dir, "/"), change }) catch return false, bytes) catch return false; p.view().active = hid; const place = look.parsePathLine(words.next() orelse return true); + standAt(p, hid, std.Io.Dir.path.resolvePosix(p.scratch.allocator(), &.{ dir, place.path }) catch return true, place.at.line); + return true; +} + +/// The cursor of +Diff `hid` on the patch's row for line `line` of `want` +/// (absolute): that file's first row when the line is not in it; none of +/// it, where it was. +fn standAt(p: *Pardes, hid: usize, want: []const u8, line: usize) void { const pane = p.panes[hid].?; - const rows = pane.file.?.location_rows; - const want = std.Io.Dir.path.resolvePosix(p.scratch.allocator(), &.{ dir, place.path }) catch return true; var best: ?usize = null; - for (rows, 0..) |row, i| { + for (pane.file.?.location_rows, 0..) |row, i| { if (!std.mem.endsWith(u8, want, row.path) or row.path.len == 0) continue; if (best == null) best = i; - if (row.at.line == place.at.line) { + if (row.at.line == line) { best = i; break; } @@ -1596,6 +1848,67 @@ pub fn diffChange(p: *Pardes, id: usize, arg: []const u8) bool { pane.body.cur_col = 0; pane.ensureCursorVisible(p.settings.tab); } +} + +/// `Diff <from>..<to> [path[:line]]` (hunks.zig): a `Compare`'s pair, its +/// patch: the difference between the two points as `jj diff --from --to +/// --git` prints it (of `path` alone when one is given), on top the changes +/// between them, newest first, a line each, `+ id title author day` for one +/// in `to` and not in `from`, `-` the other way (what the difference takes +/// back); stacked in a +Diff, the cursor on the row of `path`'s `line`. +/// What jj refuses is said in its words. False when the word is not two +/// ids (a change's or a commit's) joined by `..`. +pub fn diffPair(p: *Pardes, id: usize, arg: []const u8) bool { + var words = std.mem.tokenizeAny(u8, arg, " \t"); + const range = words.next() orelse return false; + const dots = std.mem.indexOf(u8, range, "..") orelse return false; + const from = range[0..dots]; + const to = range[dots + 2 ..]; + if (!isRevisionId(from) or !isRevisionId(to)) return false; + const dir = pardes.filesystem.localPath(Pardes.paneDir(p.panes[id].?)) orelse return false; + const arena = p.scratch.allocator(); + const place = look.parsePathLine(words.next() orelse ""); + const path: ?[]const u8 = if (place.path.len == 0) null else std.Io.Dir.path.resolvePosix(arena, &.{ dir, place.path }) catch return true; + const at = if (path) |f| dirOf(f) else dir; + const set: ?[]const u8 = if (path) |f| fileset(arena, f) catch return true else null; + const between = std.fmt.allocPrint(arena, "(({s})..({s}) | ({s})..({s})){s}{s}{s}", .{ from, to, to, from, if (set != null) " & files(" else "", set orelse "", if (set != null) ")" else "" }) catch return true; + const template = std.fmt.allocPrint(arena, "if(self.contained_in(\"::({s})\"), \"+ \", \"- \") ++ change_id.short(8) ++ \" \" ++ description.first_line() ++ \" \" ++ author.name() ++ \" \" ++ author.timestamp().utc().format(\"%Y-%m-%d\") ++ \"\\n\"", .{to}) catch return true; + const listed = switch (p.tape.site(.jj, p.gpa, runHost, .{ p.gpa, at, @as([]const []const u8, &.{ "log", "--no-graph", "-r", between, "-T", template }) })) { + .refused => |why| return pairRefused(p, id, why), + .bytes => |b| b, + }; + defer p.gpa.free(listed); + const argv = [_][]const u8{ "diff", "--from", from, "--to", to, "--git", "--", set orelse "" }; + const diffed = switch (p.tape.site(.jj, p.gpa, runHost, .{ p.gpa, at, @as([]const []const u8, argv[0 .. if (set != null) argv.len else argv.len - 2]) })) { + .refused => |why| return pairRefused(p, id, why), + .bytes => |b| b, + }; + defer p.gpa.free(diffed); + const bytes = std.fmt.allocPrint(arena, "Compare {s}..{s}\n{s}\n{s}", .{ from, to, listed, diffed }) catch return true; + const name = std.fmt.allocPrint(arena, "{s}/{s}..{s}", .{ std.mem.trimEnd(u8, dir, "/"), from, to }) catch return true; + const hid = @import("hunks.zig").openDiff(p, id, name, bytes) catch |err| return pairRefused(p, id, p.gpa.dupe(u8, if (err == error.NoHunks) "no difference" else @errorName(err)) catch return true); + p.view().active = hid; + if (path) |f| standAt(p, hid, f, place.at.line); + return true; +} + +/// A `Diff` of a pair that jj refused (`why`, freed): said in its words; +/// a plumbing rule's declines, saying nothing. +fn pairRefused(p: *Pardes, id: usize, why: []u8) bool { + defer p.gpa.free(why); + if (p.plumb_declined) |*d| { + d.* = true; + return true; + } + var line: pardes.Kind.Buf(512) = .{}; + p.reportFailure(id, line.print("Diff: {s}", .{why[0..@min(why.len, 480)]})); + return true; +} + +/// A word that may be a change id or a commit id: 4 to 40 of `0-9`, `a-z`. +fn isRevisionId(text: []const u8) bool { + if (text.len < 4 or text.len > 40) return false; + for (text) |c| if (!std.ascii.isDigit(c) and !std.ascii.isLower(c)) return false; return true; } @@ -3002,3 +3315,322 @@ test "a revision's text is read-only over 9P too: an open to write it is refused try testing.expectEqual(@as(u16, 0), th.call(p, .{ .tag = 1, .op = .open, .node = tree.Node.of(pane.serial, .body), .omode = 0 }).errno()); try testing.expectEqualStrings(Repo.two, pane.file.?.content); } + +/// Five commits of a function on one line of history, a `Compare`'s points +/// the first, the third and the fifth (`@-----`, `@---`, `@-`): `two` +/// changes `b();`, `three` takes `c();` away (the first pair's two +/// changes); `four` changes `d();`, `five` adds `e();` (the second's). +const Points = struct { + const one = "fn f() void {\n a();\n b();\n c();\n d();\n}\n"; + const two = "fn f() void {\n a();\n b2();\n c();\n d();\n}\n"; + const three = "fn f() void {\n a();\n b2();\n d();\n}\n"; + const four = "fn f() void {\n a();\n b2();\n d2();\n}\n"; + const five = "fn f() void {\n a();\n b2();\n d2();\n e();\n}\n"; + const word = "Compare @----- @--- @-"; + + fn repo() !?Repo { + return Repo.with(testing.allocator, &.{ .{ one, "one" }, .{ two, "two" }, .{ three, "three" }, .{ four, "four" }, .{ five, "five" } }, null); + } + + /// Each pin's row (its description's ghost row), by pin. + fn rows(ch: *const Changes, out: [][]const u8) [][]const u8 { + for (ch.ghosts) |g| if (g.kind == .description) { + out[g.pin] = ch.ghost_text[g.text..][0..g.len]; + }; + return out[0..ch.pins.len]; + } + + /// `row` is a pair's as `PairRow.say` writes it, two changes of one + /// day between: `from..to 2 changes YYYY-MM-DD`. + fn isRow(row: []const u8, from: []const u8, to: ?[]const u8) bool { + if (row.len != 41 or !std.mem.startsWith(u8, row, from) or !std.mem.eql(u8, row[8..10], "..")) return false; + if (to) |t| if (!std.mem.eql(u8, row[10..18], t)) return false; + return std.mem.eql(u8, row[18..31], " 2 changes ") and row[35] == '-' and row[38] == '-'; + } +}; + +test "Compare pins the whole difference between each two points as one change: three points on one line of history are two lanes, each pair's row `from..to N changes day` after its last line, what each took away where it stood; bare hides and shows them; Changes after it replaces them, and it Changes'" { + const gpa = testing.allocator; + var repo = try Points.repo() orelse return error.SkipZigTest; + defer repo.deinit(gpa); + for ([_]bool{ false, true }) |windowed| { + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 70, .rows = 24, .windowed = windowed }); + defer p.deinit(); + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + const id = p.view().active; + const pane = p.panes[id].?; + p.update(.{ .command = Points.word }); + const ch = answered(p, pane.serial) orelse { + std.debug.print("told: {s}\n", .{told(p, id)}); + return error.TestUnexpectedResult; + }; + try testing.expectEqualStrings("@----- @--- @-", ch.pinned()); + try testing.expectEqual(@as(usize, 2), ch.pins.len); + // Each pair's row: its two points, the two changes between, their day. + var buf: [2][]const u8 = undefined; + const said = Points.rows(ch, &buf); + errdefer std.debug.print("rows: [{s}] [{s}]\n", .{ said[0], said[1] }); + try testing.expect(Points.isRow(said[0], &ch.pins[0].id, &ch.pins[1].id)); + try testing.expect(Points.isRow(said[1], &ch.pins[1].id, null)); + // Who wrote each line: b2 the first pair; d2 and e the second. + const pins = [_]PinIndex{ .none, .none, @enumFromInt(0), @enumFromInt(1), @enumFromInt(1), .none }; + for (pins, ch.lines) |w, l| try testing.expectEqual(w, l.pin); + // The rows as the view shows them, no number on the layer's. + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var rbuf: [64][]const u8 = undefined; + const got = try Ghosts.rows(p, pane, arena.allocator(), &rbuf); + const want = [_][]const u8{ "fn f() void {", " a();", " b();", " b2();", " c();", said[0], " d();", " d2();", " e();", said[1], "}" }; + const numbers = [_][]const u8{ "1", "2", "", "3", "", "", "", "4", "5", "", "6" }; + for (want, numbers, got[0..want.len]) |w, n, row| { + try testing.expectEqualStrings(w, Ghosts.text(pane, row)); + try testing.expectEqualStrings(n, Ghosts.number(pane, row)); + } + // Two lanes, each pair its own colour (several pinned). + p.sync(); + const s = try p.render(arena.allocator()); + const body = s.region(.body, id).?.rect; + const first = body.x + File.gutterWidth(pane) - File.laneCells(pane); + var cbuf: [8][3]u8 = undefined; + const colours = laneColours(p.theme(), &cbuf); + for ([_]u16{ 3, 7, 8 }, [_]usize{ 0, 1, 1 }) |row, pin| { + if (windowed) { + var n: usize = 0; + for (s.lanes.items) |lane| if (lane.y == body.y + row) { + try testing.expectEqual(colours[pin], lane.rgb); + n += 1; + }; + try testing.expectEqual(@as(usize, 1), n); + } else { + try testing.expectEqualStrings("\u{258e}", s.at(first, body.y + row).grapheme()); + try testing.expectEqual(pardes.Color{ .rgb = colours[pin] }, s.at(first, body.y + row).style.fg); + } + } + // ]g and [g step through the pairs' places as through any change's. + p.update(.{ .command = "Look a.zig:1" }); + for ([_]i32{ 2, 3 }) |want_row| { + for ("]g") |k| p.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }); + try testing.expectEqual(want_row, pane.body.cur_row); + } + // Bare: hidden in this view, shown again without asking jj. + p.update(.{ .command = "Compare" }); + try testing.expectEqual(0, pane.layers.lanes); + p.update(.{ .command = "Compare" }); + try testing.expect(pane.layers.lanes > 0); + try testing.expectEqual(ch, answered(p, pane.serial).?); + // `Changes` asked after it replaces its set (one set a pane), and + // `Compare` after `Changes` replaces that. + p.update(.{ .command = "Changes @-" }); + const commit = answered(p, pane.serial).?; + try testing.expectEqualStrings("@-", commit.pinned()); + try testing.expectEqual(@as(usize, 1), commit.pins.len); + try testing.expect(!isPair(commit.pins[0])); + p.update(.{ .command = "Compare @--- @-" }); + try testing.expectEqual(@as(usize, 1), answered(p, pane.serial).?.pins.len); + try testing.expect(isPair(answered(p, pane.serial).?.pins[0])); + } +} + +test "Compare between two points neither the other's ancestor (two branches): one change, the second point's change brought in and the first's undone, both in its row; the lines as the second has them" { + const gpa = testing.allocator; + const base = "fn f() void {\n a();\n b();\n c();\n}\n"; + const x = "fn f() void {\n a();\n bx();\n c();\n}\n"; + const y = "fn f() void {\n a();\n b();\n cy();\n}\n"; + var repo = try Repo.with(gpa, &.{ .{ base, "base" }, .{ x, "x" } }, null) orelse return error.SkipZigTest; + defer repo.deinit(gpa); + // `x` a bookmark; `y` a branch of its own from `base`, the working copy on it. + if (!try Repo.run(gpa, repo.dir, &.{ "bookmark", "create", "bx", "-r", "@-" })) return error.SkipZigTest; + if (!try Repo.run(gpa, repo.dir, &.{ "new", "@--" })) return error.SkipZigTest; + try repo.tmp.dir.writeFile(testing.io, .{ .sub_path = "a.zig", .data = y }); + if (!try Repo.run(gpa, repo.dir, &.{ "commit", "-m", "y" })) return error.SkipZigTest; + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 70, .rows = 24, .windowed = false }); + defer p.deinit(); + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + const id = p.view().active; + const pane = p.panes[id].?; + p.update(.{ .command = "Compare bx @-" }); + const ch = answered(p, pane.serial) orelse { + std.debug.print("told: {s}\n", .{told(p, id)}); + return error.TestUnexpectedResult; + }; + try testing.expectEqual(@as(usize, 1), ch.pins.len); + var buf: [1][]const u8 = undefined; + const said = Points.rows(ch, &buf)[0]; + errdefer std.debug.print("row: [{s}]\n", .{said}); + try testing.expectStringStartsWith(said, &ch.pins[0].id); + try testing.expectEqualStrings("..", said[8..10]); + try testing.expectEqualStrings(" 1 change, 1 undone ", said[18..40]); + // `bx` went back to `b`, `c` became `cy`: each old text above its line. + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var rbuf: [64][]const u8 = undefined; + const got = try Ghosts.rows(p, pane, arena.allocator(), &rbuf); + const want = [_][]const u8{ "fn f() void {", " a();", " bx();", " b();", " c();", " cy();", said, "}" }; + const numbers = [_][]const u8{ "1", "2", "", "3", "", "4", "", "5" }; + for (want, numbers, got[0..want.len]) |w, n, row| { + try testing.expectEqualStrings(w, Ghosts.text(pane, row)); + try testing.expectEqualStrings(n, Ghosts.number(pane, row)); + } + // The patch: `y` brought in, `x` undone. + p.update(.{ .command = try std.fmt.bufPrint(&line, "Diff {s} a.zig:4", .{said[0..18]}) }); + const patch = p.panes[p.view().active].?.file.?.content; + errdefer std.debug.print("patch:\n{s}\n", .{patch}); + var brought = false; + var undone = false; + var rows = std.mem.splitScalar(u8, patch, '\n'); + while (rows.next()) |row| { + if (row.len < 12) continue; + brought = brought or (std.mem.startsWith(u8, row, "+ ") and std.mem.endsWith(u8, row[0 .. row.len - 10], " y t ")); + undone = undone or (std.mem.startsWith(u8, row, "- ") and std.mem.endsWith(u8, row[0 .. row.len - 10], " x t ")); + } + try testing.expect(brought and undone); +} + +test "Compare in a revision's pane at its middle point: the first pair behind the text as at the last (ROUND 8 at the merge: the second ahead of it, its lines the read-only ones)" { + const gpa = testing.allocator; + var repo = try Points.repo() orelse return error.SkipZigTest; + defer repo.deinit(gpa); + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 70, .rows = 48, .windowed = false }); + defer p.deinit(); + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + p.update(.{ .command = "At @---" }); + const id = p.view().active; + const pane = p.panes[id].?; + try testing.expectEqualStrings(Points.three, pane.file.?.content); + p.update(.{ .command = Points.word }); + const ch = answered(p, pane.serial).?; + try testing.expectEqual(@as(usize, 2), ch.pins.len); + var buf: [2][]const u8 = undefined; + const said = Points.rows(ch, &buf); + // The first pair: behind, as when the last point is shown (b2 its + // line, `b();` and `c();` what it took away, its row after them). + try testing.expect(Points.isRow(said[0], &ch.pins[0].id, &ch.pins[1].id)); + const pins = [_]PinIndex{ .none, .none, @enumFromInt(0), .none, .none }; + for (pins, ch.lines) |w, l| try testing.expectEqual(w, l.pin); + // The second, on this base, drawn as round 7 draws a change ahead of + // the text: as behind it, its lines nowhere (the step from the last + // point back to the shown one took them away), the line it changes as + // its ghost row above the text's own. ROUND 8 (ahead): `d();` the + // text's, marked going; `d2();` and `e();` read-only lines after it; + // its row after them. This want changes at that merge. + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + var rbuf: [64][]const u8 = undefined; + const got = try Ghosts.rows(p, pane, arena.allocator(), &rbuf); + const want = [_][]const u8{ "fn f() void {", " a();", " b();", " b2();", " c();", said[0], " d();", said[1], " d();", "}" }; + errdefer for (got) |row| std.debug.print("[{s}]\n", .{row}); + try testing.expect(got.len >= want.len); + for (want, got[0..want.len]) |w, row| try testing.expectEqualStrings(w, Ghosts.text(pane, row)); +} + +test "Compare refuses one point and a point that names several commits, and says what jj refuses in its words; nothing is pinned" { + const gpa = testing.allocator; + var repo = try Repo.init(gpa) orelse return error.SkipZigTest; + defer repo.deinit(gpa); + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 100, .rows = 30, .windowed = false }); + defer p.deinit(); + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}@@-", .{repo.file}) }); + const id = p.view().active; + const pane = p.panes[id].?; + for ([_][]const u8{ "Compare @-", "Compare" }) |word_| { + p.update(.{ .command = word_ }); + try testing.expect(std.mem.indexOf(u8, told(p, id), "Compare: two points or more, each one revision") != null); + } + p.update(.{ .command = "Compare @--|@- @-" }); + errdefer std.debug.print("told: {s}\n", .{told(p, id)}); + try testing.expectStringStartsWith(told(p, id), "Compare: "); + try testing.expect(std.mem.indexOf(u8, told(p, id), "more than one revision") != null); + p.update(.{ .command = "Compare nosuch @-" }); + try testing.expect(std.mem.indexOf(u8, told(p, id), "Compare: Revision `nosuch` doesn't exist") != null); + try testing.expect(answered(p, pane.serial) == null); + try testing.expectEqual(0, pane.layers.lanes); +} + +test "a Look on a pair's row opens its patch: the changes between on top, newest first, each signed, then the file's difference between the two points, the cursor on its last line there; typed, the same" { + const gpa = testing.allocator; + var repo = try Points.repo() orelse return error.SkipZigTest; + defer repo.deinit(gpa); + const p = try Pardes.init(gpa, .{ .tty_only = true, .cols = 80, .rows = 30, .windowed = false }); + defer p.deinit(); + var line: [4200]u8 = undefined; + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + const id = p.view().active; + const pane = p.panes[id].?; + p.update(.{ .command = Points.word }); + const ch = answered(p, pane.serial).?; + var buf: [2][]const u8 = undefined; + const said = Points.rows(ch, &buf); + p.sync(); + var arena: std.heap.ArenaAllocator = .init(gpa); + defer arena.deinit(); + const s = try p.render(arena.allocator()); + const body = s.region(.body, id).?.rect; + // The first pair's row (row 5): a B3 on its first word. + const x = body.x + File.gutterWidth(pane) + 1; + p.update(.{ .mouse = .{ .button = .right, .kind = .press, .col = x, .row = body.y + 5 } }); + p.update(.{ .mouse = .{ .button = .right, .kind = .release, .col = x, .row = body.y + 5 } }); + const hid = p.view().active; + try testing.expect(hid != id); + const patch = p.panes[hid].?; + const f = &patch.file.?; + errdefer std.debug.print("patch:\n{s}\n", .{f.content}); + var rows = std.mem.splitScalar(u8, f.content, '\n'); + try testing.expectEqualStrings(try std.fmt.allocPrint(arena.allocator(), "Compare {s}", .{said[0][0..18]}), rows.next().?); + const three = rows.next().?; + const two = rows.next().?; + try testing.expectStringStartsWith(three, "+ "); + try testing.expect(std.mem.endsWith(u8, three[0 .. three.len - 10], " three t ")); + try testing.expectStringStartsWith(two, "+ "); + try testing.expect(std.mem.endsWith(u8, two[0 .. two.len - 10], " two t ")); + try testing.expect(std.mem.indexOf(u8, f.content, "- c();") != null); + // The cursor on the pair's last line in a.zig, `b2();` (its line 3 at the second point). + const at = f.location_rows[@intCast(patch.body.cur_row)]; + try testing.expectEqualStrings("a.zig:3", try std.fmt.allocPrint(arena.allocator(), "{s}:{d}", .{ std.Io.Dir.path.basename(at.path), at.at.line })); + // The same, typed, at another line. + p.update(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) }); + p.update(.{ .command = try std.fmt.bufPrint(&line, "Diff {s} a.zig:2", .{said[0][0..18]}) }); + const typed = p.panes[p.view().active].?; + try testing.expectStringStartsWith(typed.file.?.content, "Compare "); + try testing.expectEqual(@as(usize, 2), typed.file.?.location_rows[@intCast(typed.body.cur_row)].at.line); +} + +test "a client replays Compare from what the session's jj answered and ends equal; its pairs cross a join whole" { + const gpa = testing.allocator; + var repo = try Points.repo() orelse return error.SkipZigTest; + defer repo.deinit(gpa); + const R = pardes.replica; + const a = try R.Authority.init(gpa, .{ .cols = 80, .rows = 24 }, .{}); + defer a.deinit(); + const r = try R.Replica.init(gpa, 1, try a.unit(0, 0)); + defer r.deinit(); + var line: [4200]u8 = undefined; + r.confirm(try a.local(.{ .command = try std.fmt.bufPrint(&line, "Look {s}", .{repo.file}) })); + r.confirm(try a.local(.{ .command = Points.word })); + r.settle(); + try testing.expect(r.diverged == null); + const id = a.core.view().active; + const ours = answered(a.core, a.core.panes[id].?.serial).?; + const theirs = answered(r.core(), r.core().panes[id].?.serial).?; + try testing.expectEqual(@as(usize, 2), ours.pins.len); + try testing.expectEqualSlices(Line, ours.lines, theirs.lines); + try testing.expectEqualStrings(ours.ghost_text, theirs.ghost_text); + try testing.expectEqual(pardes.tape.digestOf(a.core), pardes.tape.digestOf(r.core())); + try R.loadsAsSession(a, 2); +} + +test "Compare asks jj on a worker: the word says so and returns, its answer lands as one input and pins its pairs; a client replays that input and ends equal" { + var repo = try Points.repo() orelse return error.SkipZigTest; + defer repo.deinit(testing.allocator); + var w = try WorkerJj.init(&repo, ""); + defer w.deinit(); + try w.word(Points.word); + try testing.expect(answered(w.a.core, w.serial) == null); + try testing.expect(std.mem.indexOf(u8, told(w.a.core, w.id), "Compare: jj") != null); + try w.land(); + try testing.expectEqual(@as(usize, 2), answered(w.a.core, w.serial).?.pins.len); + try testing.expectEqualSlices(Line, answered(w.a.core, w.serial).?.lines, answered(w.r.core(), w.serial).?.lines); +} diff --git a/docs/typ/builtins-gui.json b/docs/typ/builtins-gui.json index aeaf6953..82d5e279 100644 --- a/docs/typ/builtins-gui.json +++ b/docs/typ/builtins-gui.json @@ -19,6 +19,7 @@ {"name": "ClipYankMain", "leader": "SPC Y", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "helix `<space>Y`: the PRIMARY selection alone, where `SPC y` joins every cursor's."}, {"name": "CodeAction", "leader": "SPC l a", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the language server's code actions for the cursor."}, {"name": "Collapse", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Fold a pane to its tag, or restore its share of the column."}, + {"name": "Compare", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pin on a file's pane the file's whole difference between each two of `points` (jj revisions, a blank between, two or more) as one change, however many changes lie between them, and show them in this view as `Changes` shows a change: a lane each, the lines it wrote and took away, its row `from..to N changes dates` after its last line; bare, as bare `Changes`."}, {"name": "Config", "leader": "SPC f c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the startup file, `init`, in a pane: its pane when it is open, else the file, else a pane of that name for Save to make it and its directory."}, {"name": "CursorBlink", "leader": null, "also": [], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "The cursor blinks, solid while typing, on or off."}, {"name": "Debug", "leader": "SPC t d", "also": ["topbar"], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A small box of frame statistics at the top right, on or off."}, diff --git a/docs/typ/builtins-tui.json b/docs/typ/builtins-tui.json index 2263df44..5b171469 100644 --- a/docs/typ/builtins-tui.json +++ b/docs/typ/builtins-tui.json @@ -19,6 +19,7 @@ {"name": "ClipYankMain", "leader": "SPC Y", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "helix `<space>Y`: the PRIMARY selection alone, where `SPC y` joins every cursor's."}, {"name": "CodeAction", "leader": "SPC l a", "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "List the language server's code actions for the cursor."}, {"name": "Collapse", "leader": null, "also": [], "arg": false, "scope": "pane", "setting": false, "choices": null, "doc": "Fold a pane to its tag, or restore its share of the column."}, + {"name": "Compare", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Pin on a file's pane the file's whole difference between each two of `points` (jj revisions, a blank between, two or more) as one change, however many changes lie between them, and show them in this view as `Changes` shows a change: a lane each, the lines it wrote and took away, its row `from..to N changes dates` after its last line; bare, as bare `Changes`."}, {"name": "Config", "leader": "SPC f c", "also": ["topbar"], "arg": false, "scope": "root", "setting": false, "choices": null, "doc": "Open the startup file, `init`, in a pane: its pane when it is open, else the file, else a pane of that name for Save to make it and its directory."}, {"name": "Debug", "leader": "SPC t d", "also": ["topbar"], "arg": true, "scope": "root", "setting": true, "choices": "on, off", "doc": "A small box of frame statistics at the top right, on or off."}, {"name": "Def", "leader": null, "also": [], "arg": true, "scope": "pane", "setting": false, "choices": null, "doc": "Go to the definition of the symbol under the cursor; with an argument (a 2-1 chord's selection), of that symbol, where it is nearest."}, |
