diff options
| author | Gabriel Schneider <[email protected]> | 2026-11-23 15:10:44 -0300 |
|---|---|---|
| committer | Gabriel Schneider <[email protected]> | 2026-11-23 15:38:37 -0300 |
| commit | 3e60c54651f10fe9233a40bc1f1fdaed141d2116 (patch) | |
| tree | d6023a7f7e1bc02319e7f9bf75b76e4eed90517d /core/jj.zig | |
| parent | 0e2012de121a9735d3c2ab7871a04d144636b849 (diff) | |
| parent | f34d3a74cc4a6b735c98ce98cef0df42bd065e67 (diff) | |
| download | pardes-3e60c54651f10fe9233a40bc1f1fdaed141d2116.tar.gz pardes-3e60c54651f10fe9233a40bc1f1fdaed141d2116.zip | |
merge: the Changes layer as the pane's read-only text (pardes-m64-base: round 8's two changes on pardes-merge63c) and Compare (pardes-merge64: `ntlsszul`, `qkksrtsn`), resolved by function: `pinWord` (Compare's road for both words) keeps round 8's `setLanes` (the layer the pane's: shown or hidden in every view of it), `pinAnswer` parses the file's text (`File.fileText`) and names its kind's word in every notice, `describe` gives a pair its row whole (no author; `fitted` gone with round 8's cut) and returns where an author would start, `isPair` kept beside it, `lookGhost` reads a description line as round 8 does (a buffer line, `readOnlyRow`) and opens a pair's patch by its row's first word (`from..to`), hunks.zig `word` tries a pair then a change (`diffChange(.., false)`) and keeps round 8's revset word at no such file, its doc saying both; round 8's rule made Compare's (the coordinator's 15:10: "a pair is ahead when its FROM point's text is the shown one"): `pairRuns` finds where the revision shown stands among the points (an empty `jj diff --from POINT --to REV`: the last point first, the one diff already run; then from the first), marks every pair from there on `a` (pinned, ahead) or `d`, and adds the step from the last point to the revision shown only when no point's text is the shown one; `pairOwners` skips a step ahead (it wrote none of the shown lines); the test marked ROUND 8 ("Compare in a revision's pane at its middle point ...") now wants the second pair ahead (`d();` the text's, going; `d2();` and `e();` read-only lines after it; its row after them) and passes; the first Compare test's `]g` wants each run's first line, a layer's line among them (rows 2 and 6, where ghost rows were no lines: 2 and 3); the guide's *Points.* paragraph says a middle point's pairs as built, the cheatsheet's and the guide's table rows both sides', `pinWord`'s and Compare's docs (builtins.zig, both JSON lists) "in every view of it"; core-test filtered on jj (Debug tui): 54/54 with the next changes' tests left out
Co-Authored-By: Claude Opus <[email protected]>
Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'core/jj.zig')
| -rw-r--r-- | core/jj.zig | 725 |
1 files changed, 692 insertions, 33 deletions
diff --git a/core/jj.zig b/core/jj.zig index 2ecd58a7..963e4c42 100644 --- a/core/jj.zig +++ b/core/jj.zig @@ -418,9 +418,29 @@ pub const Ghost = struct { /// `@`, 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 or shown +/// (in every view of it: its lines are its buffer's). +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) { hideLayer(p, f); @@ -433,15 +453,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()})); setLanes(p, f, true); - 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 layer shown in every view of every pane on `f`'s buffer, or in @@ -530,9 +555,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); @@ -611,7 +651,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; @@ -656,6 +697,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; @@ -723,6 +765,158 @@ 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; and, for who wrote +/// each line (`pairOwners`: jj has no annotation of a pair), jj's text of +/// the revision shown. A pair whose first point's text is the revision +/// shown's, and every pair after it, is AHEAD of it (`a`, as a change ahead +/// is: the lines it will write are the read-only ones), and no step +/// carries their places: none is needed. 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.ArrayList([]const u8) = .empty; + var words = std.mem.tokenizeAny(u8, a.revset, " \t"); + while (words.next()) |point| try points.append(arena, point); + if (points.items.len < 2) return refusal(gpa, "two points or more"); + // Where the revision shown stands: at the first point whose text is + // its (no difference between the two), the pairs from there on ahead + // of it; at the last, or at none (after the last), every pair behind. + const to_shown = switch (runJj(p, gpa, dir, &.{ "diff", "--from", points.items[points.items.len - 1], "--to", a.rev, "--git", "--context=0", "--", set })) { + .refused => |why| return .{ .refused = why }, + .bytes => |b| b, + }; + defer gpa.free(to_shown); + var shown_at = points.items.len; + if (to_shown.len == 0) shown_at = points.items.len - 1 else for (points.items[0 .. points.items.len - 1], 0..) |point, k| { + const differs = switch (runJj(p, gpa, dir, &.{ "diff", "--from", point, "--to", a.rev, "--git", "--context=0", "--", set })) { + .refused => |why| return .{ .refused = why }, + .bytes => |b| b, + }; + defer gpa.free(differs); + if (differs.len == 0) { + shown_at = k; + break; + } + } + var last: [8]u8 = @splat('z'); + for (points.items[0 .. points.items.len - 1], points.items[1..], 0..) |from, to, k| { + 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); + // `logTemplate`'s marks: pinned or not (no difference), behind or ahead. + const mark: u8 = if (k >= shown_at) (if (diffed.len > 0) 'a' else 'd') else if (diffed.len > 0) 'p' else 'c'; + try rows.print(gpa, "{s}\t{c}\t0\t\t", .{ &row.from, mark }); + 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; + } + if (shown_at == points.items.len) { + try rows.print(gpa, "{s}\tc\t0\t\t\n", .{&last}); + try rows.appendSlice(gpa, to_shown); + } + 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 @@ -750,7 +944,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]), } } @@ -841,28 +1035,30 @@ 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; // Nothing pinned yet: no gutter for it. defer if (answered(p, pane.serial) == null) setLanes(p, f, false); - if (b.end == .failed) return p.reportFailure(id, line.print("Changes: {s}", .{b.rows[0..@min(b.rows.len, 480)]})); + 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)] })); // jj's lines lined up with the file's (the layer's are none of it). - const text = File.fileText(f, p.scratch.allocator()) catch |err| return p.reportFailure(id, line.print("Changes: {s}", .{@errorName(err)})); - var got = parse(p.gpa, p.scratch.allocator(), b.rows, b.styles, text) catch |err| return p.reportFailure(id, line.print("Changes: {s}", .{@errorName(err)})); + const text = File.fileText(f, p.scratch.allocator()) catch |err| return p.reportFailure(id, line.print("{s}: {s}", .{ name, @errorName(err) })); + var got = parse(p.gpa, p.scratch.allocator(), b.rows, b.styles, text, 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); @@ -874,7 +1070,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), ""); if (pane.layers.lanes > 0) showLayer(p, f, pane.serial); @@ -1090,8 +1286,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; @@ -1120,7 +1317,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); @@ -1205,15 +1402,78 @@ 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; + // A step ahead of the revision shown wrote none of its lines. + if (steps[k].ahead) continue; + 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 @@ -1597,8 +1857,13 @@ fn going(lines: []Line, hunks: []const Hunk, moved: Moved) void { /// description's first line), its whole author, its age short (`5h`, `2d`, /// `3w`, `4m`, `1y`; under an hour `now`), no "ago". Nothing is cut: a /// line too long for its pane wraps as any line does. Where its author -/// starts in `text`. +/// starts in `text`. A `Compare`'s pair: its row (`PairRow.say`), its +/// title, whole; no author. fn describe(gpa: std.mem.Allocator, text: *std.ArrayList(u8), pin: Pin, author: []const u8, title: []const u8, now: i64) error{OutOfMemory}!usize { + if (isPair(pin)) { + try text.appendSlice(gpa, title); + return text.items.len; + } try text.print(gpa, "{s} {s} ", .{ pin.id[0..4], title }); const at = text.items.len; try text.print(gpa, "{s} ", .{author}); @@ -1614,6 +1879,13 @@ fn describe(gpa: std.mem.Allocator, text: *std.ArrayList(u8), pin: Pin, author: return at; } +/// 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 lanes on ghost line `gi` (`ghosts[gi]`): those of the line above it /// that run on below it or whose description is this line or one after it /// at the same place, then its own pin's (on a description's rows after @@ -1770,14 +2042,17 @@ pub fn lookGhost(p: *Pardes, id: usize, vr: i32, col: i32) bool { if (g.kind != .description) return false; const said = File.sourceLine(pane, w.line); const at = File.byteAtRowDisplay(tab, pane, w.line, 0, col - @as(i32, File.gutterWidth(pane)) - w.pad); - if (at < 0 or at >= (std.mem.indexOfScalar(u8, said, ' ') orelse said.len)) return false; + const id_end = std.mem.indexOfScalar(u8, said, ' ') orelse said.len; + if (at < 0 or at >= id_end) return false; const path = if (of(f)) |r| r.path else f.path; var last: u32 = g.line; for (ch.hunks) |h| if (h.pin == g.pin) { 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])) said[0..id_end] 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; } @@ -1817,14 +2092,20 @@ pub fn diffChange(p: *Pardes, id: usize, arg: []const u8, any: bool) 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; } @@ -1834,6 +2115,67 @@ pub fn diffChange(p: *Pardes, id: usize, arg: []const u8, any: bool) 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; } @@ -3732,3 +4074,320 @@ 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: + // each run's first line, a layer's line among them (`b();`, `d();`). + p.update(.{ .command = "Look a.zig:1" }); + for ([_]i32{ 2, 6 }) |want_row| { + for ("]g") |k| p.update(.{ .key = .{ .cp = k, .text = &[_]u8{k} } }); + try testing.expectEqual(want_row, pane.body.cur_row); + } + // Bare: hidden, 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; the second ahead of it (its first point's text is the one shown): the line it takes away the text's, going, the lines it writes read-only lines after it, its row after them" { + 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, ahead (a change ahead's rule): `d();` the text's, going; + // `d2();` and `e();` read-only lines after it; its row after them. + 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], "}" }; + try testing.expectEqual(@as(PinIndex, @enumFromInt(1)), ch.lines[3].going); + 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); +} |
