summaryrefslogtreecommitdiff
path: root/src/hunks.zig
diff options
context:
space:
mode:
authorGabriel Schneider <[email protected]>2026-11-17 00:51:40 -0300
committerGabriel Schneider <[email protected]>2026-11-17 12:15:01 -0300
commit4a33b8d2bd409d4a06205f28e0eb1b4cdaf49889 (patch)
tree0451135691e451216ad89167884b42b2b0a33dca /src/hunks.zig
parentdd5aa28c89e2ca31a4cd806d6087ce4ac52398fc (diff)
downloadpardes-4a33b8d2bd409d4a06205f28e0eb1b4cdaf49889.tar.gz
pardes-4a33b8d2bd409d4a06205f28e0eb1b4cdaf49889.zip
hunks: the +Diff's editor side in one place: openDiff, showDiffText and diffSource move from Output.zig, the `Diff` word's body and PaneKind.diff's test from builtins.zig, lookCommit (as lookedAtCommit) and its test from look.zig; builtins.zig's Diff is its one registration (its doc, traits and `run = hunks.word`); the three open hooks a plumber's rules would replace are a call each, look.zig's `hunks.lookedAt` (a bare look at a .diff or .patch) and `hunks.lookedAtCommit` (a commit hash) and ninep/ctl.zig's `hunks.paged` (a +Pager filled with a diff), their conditions inside them; the diff language (diff.zig, syntax.zig's highlightDiff, look's diff-line address) stays where the languages are; code locality's far share 0.575 before and after (codeloc.py --compare); goldens unchanged
Co-Authored-By: Claude Opus 5.5 <[email protected]> Claude-Session: https://claude.ai/code/session_016Y9MNBECMWcJD5pdS4SR6T
Diffstat (limited to 'src/hunks.zig')
-rw-r--r--src/hunks.zig185
1 files changed, 181 insertions, 4 deletions
diff --git a/src/hunks.zig b/src/hunks.zig
index 28fffa38..afd2ac9d 100644
--- a/src/hunks.zig
+++ b/src/hunks.zig
@@ -10,12 +10,17 @@ const diff = @import("diff.zig");
const syntax = @import("syntax.zig");
const locations = @import("locations.zig");
+const pardes = @import("pardes.zig");
+const Pardes = pardes.Pardes;
+const Pane = pardes.Pane;
+const Output = pardes.panes.Output;
+
const Row = locations.Row;
/// What `format` takes of the editor it stacks for: its allocators, the
/// files a diff names read as the editor reads them (in pardes an open
/// pane's text, else the disk's, each read a site of the step's tape:
-/// Output.openDiff), their declarations, and one setting.
+/// openDiff), their declarations, and one setting.
pub const Ctx = struct {
/// The text and rows made, the caller's.
gpa: std.mem.Allocator,
@@ -594,6 +599,171 @@ fn trimmedWidth(section: []const u8) usize {
return @import("File.zig").displayWidth(std.mem.trim(u8, section, " \t"));
}
+// ---- the +Diff in the editor ----
+//
+// Its word (Diff), the open and the text it goes back to; and the three
+// hooks the generic code calls, one call each (look.zig's bare look and
+// commit look, ninep/ctl.zig's filled +Pager), which a plumber's rules
+// would replace.
+
+/// The `Diff` word (builtins.zig registers it): on a +Diff, the diff it
+/// stacks as text; on a diff, its hunks stacked in a +Diff.
+pub fn word(c: pardes.builtins.Ctx) void {
+ const f = &c.pane.file.?;
+ if (diffSource(c.p, f)) |source| return showDiffText(c.p, c.id, source);
+ _ = openDiff(c.p, c.id, f.path, f.content) catch |err| switch (err) {
+ error.NoHunks => c.p.reportFailure(c.id, "Diff: no hunk in it"),
+ else => c.p.reportError(c.id, "hunks", err),
+ };
+}
+
+/// A pane the word works on: a diff (a .diff, a .patch, a +Pager holding
+/// one) or a +Diff.
+pub fn shows(pane: *const Pane) bool {
+ const f = pane.file orelse return false;
+ return pane.colorAlgo() == .diff or (f.output != null and std.meta.eql(f.output.?.from, Output.Origin{ .cmd = .Diff }));
+}
+
+/// The hook of a bare look at a .diff or a .patch (look.zig's open): its
+/// hunks stacked in a +Diff, which takes the keyboard as the file would;
+/// false, for look to open it as text, when it is no such file, a place in
+/// one, one with no hunk, or the text is what is asked (showDiffText).
+pub fn lookedAt(p: *Pardes, id: usize, path: []const u8, at: pardes.look.Spot) bool {
+ if (p.look_text or at.line != 0 or !(std.mem.endsWith(u8, path, ".diff") or std.mem.endsWith(u8, path, ".patch"))) return false;
+ const bytes = pardes.filesystem.read(p, path) catch return false;
+ defer p.gpa.free(bytes);
+ p.view().active = openDiff(p, id, path, bytes) catch return false;
+ return true;
+}
+
+/// The hook of a +Pager filled with a diff (ninep/ctl.zig's fillPager:
+/// `git show`, difftui's patches): its hunks stacked in a +Diff in the
+/// +Pager's place, the +Pager closed. The keyboard stays where it was, as
+/// a page's.
+pub fn paged(p: *Pardes, id: usize) void {
+ const f = &p.panes[id].?.file.?;
+ const keyboard = p.view().active;
+ if (openDiff(p, id, f.path, f.content)) |hid| {
+ // ponytail: the text is gone with it; Diff on the +Diff says no such file.
+ p.removePane(id, hid) catch |err| p.reportError(id, "pager", err);
+ } else |_| {}
+ if (p.panes[keyboard] != null) p.view().active = keyboard;
+}
+
+/// The hook of a commit hash (7 to 40 hex digits, a letter and a digit
+/// among them; look.zig's look at a word) looked at inside a git repository: `git show` it, paged into a +Pager,
+/// which stacks its hunks in a +Diff (ctl.fillPager); the command pane
+/// goes when it succeeds (Pane.commandDone).
+// ponytail: a hex word that names no commit leaves git's error in a command pane, not a search; check the object first if that bites.
+pub fn lookedAtCommit(p: *Pardes, id: usize, pane: *Pane, hash: []const u8) bool {
+ if (!isCommitHash(hash)) return false;
+ var dir = pardes.filesystem.localPath(Pardes.paneDir(pane)) orelse return false;
+ while (true) {
+ var buf: [4096]u8 = undefined;
+ const dot_git = std.fmt.bufPrint(&buf, "{s}/.git", .{dir}) catch return false;
+ if (pardes.exec.kindOf(dot_git) != null) break;
+ dir = std.Io.Dir.path.dirname(dir) orelse return false;
+ }
+ var line: [64]u8 = undefined;
+ const dst = pardes.exec.execute(p, id, std.fmt.bufPrint(&line, "git show {s}", .{hash}) catch return false) orelse return true;
+ if (p.panes[dst]) |c| c.command_pages = true;
+ return true;
+}
+
+fn isCommitHash(hex: []const u8) bool {
+ if (hex.len < 7 or hex.len > 40) return false;
+ var digit = false;
+ var letter = false;
+ for (hex) |c| switch (c) {
+ '0'...'9' => digit = true,
+ 'a'...'f' => letter = true,
+ else => return false,
+ };
+ return digit and letter;
+}
+
+/// Diff: `content`, the diff at `path` (a file, a +Pager), stacked as a
+/// diff viewer shows it (format), in a +Diff where its files are found
+/// (sourceRoot), placed by pane `id`, refilled when it is there. Its
+/// arg names the diff (its base name, or its whole path when the +Diff
+/// stands elsewhere), for Diff to go back to it; a commit's (`git show`, a
+/// mailed patch) is named for it too, `+Diff-<12 hex>`, so each commit
+/// keeps a +Diff of its own. The +Diff's id; NoHunks when there is none in
+/// it.
+pub fn openDiff(p: *Pardes, id: usize, path: []const u8, content: []const u8) !usize {
+ const dir = std.Io.Dir.path.dirname(path) orelse p.sessionDir();
+ // Each file read is a site of the step's tape (fs.zig): a replica
+ // replays the authority's bytes and reads no disk of its own.
+ const Read = struct {
+ fn source(ctx: *const Ctx, from: []const u8, name: []const u8) ?Source {
+ const pp: *Pardes = @ptrCast(@alignCast(ctx.host));
+ const text = locations.sourceText(pp, ctx.arena, from, name) orelse return null;
+ return .{ .path = text.path, .bytes = text.bytes };
+ }
+ fn declarations(ctx: *const Ctx, name: []const u8, bytes: []const u8) error{OutOfMemory}![]const syntax.ContextDeclaration {
+ const pp: *Pardes = @ptrCast(@alignCast(ctx.host));
+ var hit = pp.locations_cache.get(pp.tree_sitter_gpa, name, bytes, true, false) catch
+ locations.Cache.Hit{ .analysis = syntax.analyzeSource(ctx.arena, name, bytes, true, false) catch .{} };
+ defer hit.deinit(pp.tree_sitter_gpa);
+ // The cache's may go at its next use: kept for the call.
+ return ctx.arena.dupe(syntax.ContextDeclaration, hit.analysis.declarations);
+ }
+ };
+ const ctx: Ctx = .{
+ .gpa = p.gpa,
+ .arena = p.scratch.allocator(),
+ .source = Read.source,
+ .declarations = Read.declarations,
+ .host = p,
+ .tslocations = p.locations_config.tslocations,
+ };
+ const root = sourceRoot(&ctx, dir, content);
+ const result = try format(&ctx, root, content);
+ errdefer {
+ p.gpa.free(result.content);
+ locations.freeRows(p.gpa, result.rows);
+ }
+ var has_hunk = false;
+ for (result.rows) |row| has_hunk = has_hunk or row.kind == .match;
+ if (!has_hunk) return error.NoHunks;
+ const arg = if (std.mem.eql(u8, root, dir) or path.len > Output.max_arg) std.Io.Dir.path.basename(path) else path;
+ var name_buf: [pardes.config.diff_buffer.len + 13]u8 = undefined;
+ const name = if (diff.commitHash(content)) |hash|
+ std.fmt.bufPrint(&name_buf, "{s}-{s}", .{ pardes.config.diff_buffer, hash[0..@min(hash.len, 12)] }) catch unreachable
+ else
+ null;
+ return Output.fillRows(p, id, root, .{ .cmd = .Diff }, name, arg, result.content, result.rows, null);
+}
+
+/// Diff on a +Diff: the diff it stacks, as text. A pane holding it
+/// already (the newest: a +Pager folded under its +Diff unfolds) is
+/// shown; else the file is opened as text.
+pub fn showDiffText(p: *Pardes, id: usize, source: []const u8) void {
+ var newest: ?usize = null;
+ for (p.panes, 0..) |slot, i| {
+ const f = (slot orelse continue).file orelse continue;
+ if (!std.mem.eql(u8, f.path, source)) continue;
+ if (newest == null or p.panes[newest.?].?.serial < slot.?.serial) newest = i;
+ }
+ if (newest) |i| {
+ if (p.panes[i].?.collapsed) pardes.layout.toggleCollapse(p, i);
+ p.view().active = i;
+ return;
+ }
+ p.look_text = true;
+ defer p.look_text = false;
+ pardes.look.lookAt(p, id, source);
+}
+
+/// The diff a +Diff stacks (openDiff's arg): its path.
+pub fn diffSource(p: *Pardes, f: *const pardes.panes.File.State) ?[]const u8 {
+ const o = f.output orelse return null;
+ if (!std.meta.eql(o.from, Output.Origin{ .cmd = .Diff })) return null;
+ const arg = o.arg();
+ if (arg.len > 0 and arg[0] == '/') return arg;
+ return std.Io.Dir.path.join(p.scratch.allocator(), &.{ std.Io.Dir.path.dirname(f.path) orelse "", arg }) catch null;
+}
+
// ---- tests ----
const testing = std.testing;
@@ -762,9 +932,6 @@ test "a mailed patch keeps its headers, message and diffstat above its hunks" {
try testing.expectEqualStrings("From 0123 Mon Sep 17 00:00:00 2001\nSubject: [PATCH] change x\n\nWhy it changed.\n---\n x.txt | 2 +-\n\nx.txt:1\n-a\n+b\n", result.content);
}
-const pardes = @import("pardes.zig");
-const Pardes = pardes.Pardes;
-
test "a .patch looked at opens its +Diff, and Diff goes to the text and back" {
const p = try Pardes.init(testing.allocator, .{ .tty_only = true });
defer p.deinit();
@@ -888,3 +1055,13 @@ test "patch panes keep different commits and reuse only the same commit" {
try testing.expectEqual(first, try Page.open(p, a));
try testing.expectEqualStrings(original, p.panes[first].?.file.?.content);
}
+
+test "a commit hash is 7 to 40 lowercase hex digits with a letter and a digit" {
+ try std.testing.expect(isCommitHash("9bffa7041c"));
+ try std.testing.expect(isCommitHash("9bffa7041cd2e8a0b6b1f7c3e4d5a6b7c8d9e0f1"));
+ try std.testing.expect(!isCommitHash("9bffa7"));
+ try std.testing.expect(!isCommitHash("defaced"));
+ try std.testing.expect(!isCommitHash("1234567"));
+ try std.testing.expect(!isCommitHash("0x9bffa7041c"));
+ try std.testing.expect(!isCommitHash("9BFFA7041C"));
+}