From 5bfce4371cd2c93f1e85e3ce5b0a176d3b17bef8 Mon Sep 17 00:00:00 2001 From: "Jeffrey C. Ollie" Date: Thu, 5 Nov 2026 10:09:32 -0600 Subject: [PATCH] diff-tree: -c, --cc, -v, --pretty, --format, --merge-base zig-git diff-tree now shows a merge as a combined diff (-c, --cc, --combined-all-paths), compares two commits' merge base with the second (--merge-base), and with -v, --pretty, --format or --oneline describes each commit as git log would in place of its line, as git was seen to: object IDs whole unless --abbrev is given, none of the log.* settings or format.pretty read, email without [PATCH], log's separators, and --always writing the commit once where nothing differs. --first-parent changes nothing, as in git. Found against git along the way, and fixed for every command that shares the code: a combined patch's index line takes the repository's abbreviation whatever --abbrev says; the empty line before a combined patch after --dirstat or an empty --summary; a type change written as M in a combined diff; the combined diff's names, mode lines and "Binary files differ" written past --line-prefix; the zero object ID lengthened in the raw formats like any other; --cc showing a stretch whose changes different parents make; diff-tree's --dirstat going into subtrees, and --find-copies-harder taking only top-level files without -r. A combined diff that would merge more than 2^26 pairs of lines the parents lost at one place is refused rather than made in gigabytes (as git makes it): commits given made-up parents on --stdin drove one run past 7 GB. Refused by name where git's answer was not established: a merge's combined diff with -t, -R, --relative, --diff-filter, --quiet, --exit-code or --check; --dirstat with -t; --line-prefix with a format: string; and the revision-walking options diff-tree takes. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01P9FTtTrkEbuvbZnRyJCBir --- README.md | 37 +++- src/diff/combined.zig | 52 +++++- src/diff/output.zig | 6 +- tools/describe.zig | 42 +++-- tools/diff_tree.zig | 359 +++++++++++++++++++++++++++++++++----- tools/diff_tree_tests.zig | 103 +++++++++++ tools/line_prefix.zig | 18 ++ tools/log_diff.zig | 123 ++++++++++--- tools/repo_diff.zig | 1 + tools/rev_list.zig | 1 + 10 files changed, 653 insertions(+), 89 deletions(-) diff --git a/README.md b/README.md index ceafca0..31323a8 100644 --- a/README.md +++ b/README.md @@ -444,9 +444,19 @@ two commits or trees (`A B`, `A..B`), with pathspecs, every format and option above, and the configuration `git diff` reads (`diff.context`, `diff.interHunkContext`, `diff.algorithm`, `diff.noprefix`, `diff.mnemonicPrefix`, `diff.srcPrefix`, `diff.dstPrefix`, the stat -widths, `diff.renames`); `zig-git diff-tree` compares two trees or a +widths, `diff.renames`); `zig-git diff-tree` compares two trees, a commit with its parents (`-r`, `-t`, `--root`, `-m`, `--always`, -`--no-commit-id`, `--stdin`), `zig-git diff-index` a tree with the index +`--no-commit-id`, `--stdin`), or two commits' merge base with the second +(`--merge-base`), shows a merge as a combined diff (`-c`, `--cc`, +`--combined-all-paths`), and with `-v`, `--pretty`, `--format` or +`--oneline` describes each commit as `git log` would in place of its +line (`--abbrev-commit`, `--date`, `--expand-tabs`, `--encoding`, +`i18n.logOutputEncoding`), as git was seen to: its object IDs whole +unless `--abbrev` is given, none of the `log.*` settings or +`format.pretty` read, `email` without `[PATCH]`, the commit separated from +its diff as `log` separates them, `--always` writing it once where +nothing differs, and `--first-parent` changing nothing; +`zig-git diff-index` a tree with the index or the working tree (`--cached`, `-m`), and `zig-git diff-files` the index with the working tree (`-0`, `-1`, `-2`, `-3`, `--base`, `--ours`, `--theirs`, `-q`), each reading only the configuration git's plumbing @@ -507,7 +517,9 @@ whatever the diff driver, from no further back than the hunk before, cut short at 40 bytes and then by one more) and binary files, as attributes and drivers decide them, said to differ. The dense form leaves out each stretch of changes where the parents have only two versions and the -result takes one of them as it is, as git-diff-tree(1) describes it; +result takes one of them as it is, as git-diff-tree(1) describes it, +and the same parents make every change of it (where parents lost the +same lines at different places, git shows the stretch); which changes make one stretch, and how a hunk is counted around a change left out, were found by experiment and matched over thousands of generated merges of two to four parents. Without context (`-U0`) only @@ -850,10 +862,21 @@ deliberate or not yet matched: `-R` is refused, and so is `--diff-filter` for a merge in `show`; - combined diffs (`-c`, `--cc`) with `--ignore-blank-lines`, where git leaves changes out by another rule, or of a rewrite `-B` broke, are - refused, and so are `diff-tree -c` and `--cc` (and with them - `diff-tree --combined-all-paths`), `diff-tree -v`, `--pretty` and - `--format`, `git diff-files -p` with unmerged paths (unless `-1`, `-2` - or `-3` chooses a stage), `--remerge-diff` and `--diff-merges=remerge`; + refused, and so is a combined diff that would merge more than 2^26 + pairs of lines the parents lost at one place (a table of a quarter of + a gigabyte, where git was seen to use gigabytes), and so are + `git diff-files -p` with unmerged paths (unless + `-1`, `-2` or `-3` chooses a stage), `--remerge-diff` and + `--diff-merges=remerge`; +- `diff-tree` refuses a merge's combined diff with `-t`, `-R`, + `--relative`, `--diff-filter`, `--quiet`, `--exit-code` or `--check`, + where git's answers were not established (under `-R` they are not a + reversal); `--dirstat` with `-t`, where git counts the trees' entries + by a rule not found; `--line-prefix` with a `format:` string, where git + puts the prefix before some separators and not others; and the + options of git's revision walking it takes without saying what they do + there (`--notes`, `--show-signature`, `--graph`, `--parents`, + `--left-right`, `--grep` and the like), each by name; - a function pattern with a back reference, which git takes, is refused, and so is one whose first group lies inside a repetition that may iterate more than once, where glibc's choice of iteration was matched diff --git a/src/diff/combined.zig b/src/diff/combined.zig index da7ea8e..3fbe7eb 100644 --- a/src/diff/combined.zig +++ b/src/diff/combined.zig @@ -73,7 +73,13 @@ const Lost = struct { }; /// What combining can fail with. -pub const Error = LineDiff.Error || Io.Writer.Error || error{TooManyParents}; +pub const Error = LineDiff.Error || Io.Writer.Error || error{ TooManyParents, TooManyLostLines }; + +/// The most pairs of lost lines merged at one place (`mergeLost`, a +/// table of four bytes a pair): beyond it the merge is refused rather than +/// made in more memory than the machine may have. git was seen to use +/// gigabytes on such merges, and more than six on some. +pub const max_lost_pairs = 1 << 26; /// How the lines are compared and the hunks written. pub const Options = struct { @@ -190,6 +196,7 @@ pub fn writeHunks(gpa: Allocator, w: *Io.Writer, parents: []const []const u8, re if (lost[g].items.len == 0) { try lost[g].appendSlice(arena, list.items); } else { + if ((lost[g].items.len + 1) * (list.items.len + 1) > max_lost_pairs) return error.TooManyLostLines; lost[g] = try mergeLost(arena, lost[g].items, list.items, pi); } } @@ -357,8 +364,10 @@ const Changes = struct { /// lines between them, or at most one where the first ends in lost /// lines and the context is one line. Such a stretch of changes is left /// out when the parents have only two versions of it and the result is -/// one of them as it is (git-diff-tree(1) describes it so); the rest are -/// shown, each with its context as under `-c`. +/// one of them as it is (git-diff-tree(1) describes it so), and the same +/// parents make every change of it (two parents losing the same lines at +/// different places make the same version, which git was seen to show); +/// the rest are shown, each with its context as under `-c`. /// /// Found by comparing a model with git over thousands of generated /// merges of two to four parents, at contexts of one to five lines. @@ -426,7 +435,25 @@ fn chooseDense(arena: Allocator, c: Changes, shown_gap: []bool, shown_line: []bo if (!sameVersion(v.items, parents[o].items)) two = false; } else other = pi; } - const picks = two and other != null and + // The same set of parents must make every change of the stretch: + // where the versions are the same only because parents lost the + // same lines at different places, git was seen to show it. + var mask: ?u32 = null; + const one_set = one: { + x = st.first; + while (x <= st.last) : (x += 1) { + const index = x / 2; + if (x % 2 == 0) { + for (c.lost[index].items) |l| { + if (mask) |m| (if (m != l.mask) break :one false) else mask = l.mask; + } + } else if (c.added[index] != 0) { + if (mask) |m| (if (m != c.added[index]) break :one false) else mask = c.added[index]; + } + } + break :one true; + }; + const picks = one_set and two and other != null and (sameVersion(result, parents[0].items) or sameVersion(result, parents[other.?].items)); if (picks) continue; x = st.first; @@ -681,3 +708,20 @@ test "fuzz: combined diff" { @embedFile("../fuzz/combined-merge"), } }); } + +test "lost lines too many to merge at one place are refused, not merged in gigabytes" { + const gpa = std.testing.allocator; + var texts: [2]std.ArrayList(u8) = .{ .empty, .empty }; + defer for (&texts) |*t| t.deinit(gpa); + // Two parents each losing 8,200 lines of their own before the same + // result line: more than `max_lost_pairs` pairs. + for (&texts, [_]u8{ 'a', 'b' }) |*t, side| { + for (0..8200) |i| try t.print(gpa, "{c}{d}\n", .{ side, i }); + try t.appendSlice(gpa, "end\n"); + } + var out: Io.Writer.Allocating = .init(gpa); + defer out.deinit(); + try std.testing.expectError(error.TooManyLostLines, writeHunks(gpa, &out.writer, &.{ texts[0].items, texts[1].items }, "end\n", .{})); + // Fewer still merge. + _ = try writeHunks(gpa, &out.writer, &.{ "a\nb\nend\n", "c\nend\n" }, "end\n", .{}); +} diff --git a/src/diff/output.zig b/src/diff/output.zig index 1f4baac..d5278ef 100644 --- a/src/diff/output.zig +++ b/src/diff/output.zig @@ -612,9 +612,9 @@ fn writeRawId(w: *Io.Writer, side: Side, options: Options) Io.Writer.Error!void var n = hex.len; if (options.raw_abbrev) |a| { n = @min(@max(a, 4), hex.len); - if (options.patch.shorten) |s| { - if (!id.eql(object.Id.zero(id.object_format))) n = @min(s.length(s.context, id, n), hex.len); - } + // Lengthened while another object begins the same way, the zero + // ID too, as git was seen to lengthen it. + if (options.patch.shorten) |s| n = @min(s.length(s.context, id, n), hex.len); } try w.writeAll(hex[0..n]); } diff --git a/tools/describe.zig b/tools/describe.zig index 7879524..d7c2a48 100644 --- a/tools/describe.zig +++ b/tools/describe.zig @@ -24,7 +24,10 @@ const revisions = @import("revisions.zig"); const log_diff = @import("log_diff.zig"); /// Which command is describing commits; each frames them its own way. -pub const Command = enum { rev_list, log, show }; +/// `diff_tree` frames them as `log` does, but reads none of the `log.*` +/// or `format.pretty` settings, and its `email` format is `rev-list`'s +/// after the `From` line. +pub const Command = enum { rev_list, log, show, diff_tree }; /// The formatting and searching options, as given. pub const Options = struct { @@ -326,14 +329,20 @@ pub const Describer = struct { if (!git.encoding.isWritable(e)) return tool.fatalMessage(stderr, "zig-git: i18n.commitEncoding '{s}' is not supported", .{e}); break :blk try a.dupe(u8, e); } else "UTF-8"; - if (command != .rev_list) { + // git diff-tree was seen to read none of the log.* settings. + const reads_log = command == .log or command == .show; + if (reads_log) { if ((repo.boolSetting("log.showSignature", null) catch null) orelse false) return tool.fatalMessage(stderr, "zig-git: log.showSignature is not supported", .{}); } // The format: the option, `format.pretty` for log and show, or // the command's default. - const default_text: ?[]const u8 = if (command == .rev_list) null else ((config.getString("format.pretty") catch null) orelse "medium"); + const default_text: ?[]const u8 = switch (command) { + .rev_list => null, + .diff_tree => "medium", + .log, .show => (config.getString("format.pretty") catch null) orelse "medium", + }; var format: ?pretty.Format = null; const header = command == .rev_list and options.header and options.pretty == null; if (header) { @@ -360,19 +369,19 @@ pub const Describer = struct { // Dates. var date_mode: git.date.Mode = .{}; var date_given = false; - const date_text: ?[]const u8 = options.date orelse if (command != .rev_list) (config.getString("log.date") catch null) else null; + const date_text: ?[]const u8 = options.date orelse if (reads_log) (config.getString("log.date") catch null) else null; if (date_text) |t| { var diag: Diagnostics = .{}; date_mode = git.date.parseMode(t, .{ .terminal = false }, &diag) catch return tool.fatalMessage(stderr, "{s}", .{diag.detail()}); - date_given = options.date != null or command != .rev_list; + date_given = options.date != null or reads_log; } // Abbreviation. - const abbrev_commit = options.abbrev_commit orelse if (command != .rev_list) ((repo.boolSetting("log.abbrevCommit", null) catch null) orelse false) else false; + const abbrev_commit = options.abbrev_commit orelse if (reads_log) ((repo.boolSetting("log.abbrevCommit", null) catch null) orelse false) else false; // The mailmap: `%aN` and the rest always, the built-in formats' // identities and the searches only when asked. - const use_mailmap = options.mailmap orelse if (command != .rev_list) ((repo.boolSetting("log.mailmap", null) catch null) orelse true) else false; + const use_mailmap = options.mailmap orelse if (reads_log) ((repo.boolSetting("log.mailmap", null) catch null) orelse true) else false; const mailmap = try gpa.create(git.Mailmap); errdefer gpa.destroy(mailmap); mailmap.* = .init(gpa); @@ -468,13 +477,13 @@ pub const Describer = struct { // Decorations: `--decorate`, or `log.decorate`, which `auto` and // output that is never a terminal leave off. var mode: DecorateMode = options.decorate orelse .auto; - if (options.decorate == null and command != .rev_list) if (config.getString("log.decorate") catch null) |v| { + if (options.decorate == null and reads_log) if (config.getString("log.decorate") catch null) |v| { mode = decorateMode(v) orelse if (git.Config.value.parseBool(v)) |b| (if (b) DecorateMode.short else .no) else .auto; }; const show_decorations = mode == .short or mode == .full; const wants_decorations = show_decorations or (if (format) |f| f == .user and f.user.usesDecorations() else false); var decoration_colors: pretty.DecorationColors = .{}; - if (command != .rev_list or wants_decorations) try readDecorationColors(config, a, &decoration_colors, stderr); + if (reads_log or wants_decorations) try readDecorationColors(config, a, &decoration_colors, stderr); var decorations: ?git.Decorations = null; errdefer if (decorations) |*x| x.deinit(); if (wants_decorations) decorations = try loadDecorations(ctx, repo, options, command, mode == .full, stderr); @@ -509,7 +518,7 @@ pub const Describer = struct { .expand_tabs = if (command == .rev_list) 0 else options.expand_tabs, .trailers = .{ .separators = separators, .configured = configured.items, .comment = comment }, .columns = columns, - .rev_list = command == .rev_list, + .rev_list = command == .rev_list or command == .diff_tree, .first_line = command != .rev_list, .decorate = show_decorations, .show_source = options.source, @@ -679,7 +688,7 @@ pub const Describer = struct { // two is a NUL, and nothing else is. const end: u8 = if (d.nul) 0 else '\n'; switch (d.command) { - .log, .show => { + .log, .show, .diff_tree => { if (user_like) { if (!f.terminated() and d.written) try stdout.writeByte(end); } else if (d.written and !oneline) try stdout.writeByte(end); @@ -709,7 +718,7 @@ pub const Describer = struct { }; const out = text.written(); switch (d.command) { - .log, .show => { + .log, .show, .diff_tree => { // --oneline's line ends in the line feed ending the // commit. if (oneline and d.nul and std.mem.endsWith(u8, out, "\n")) { @@ -742,17 +751,18 @@ pub const Describer = struct { /// The decorations the options and settings choose, `command` reading /// `log.excludeDecoration` and `log.initialDecorationSet` unless it is -/// `rev-list`, which decorates with every ref. +/// `rev-list` or `diff-tree`, which decorate with every ref. pub fn loadDecorations(ctx: Context, repo: *git.Repository, options: *const Options, command: Command, full: bool, stderr: *Io.Writer) !git.Decorations { const gpa = ctx.gpa; var arena: std.heap.ArenaAllocator = .init(gpa); defer arena.deinit(); const a = arena.allocator(); const config = &repo.config; - // rev-list decorates with every ref. - const all = command == .rev_list or options.clear_decorations or if (config.getString("log.initialDecorationSet") catch null) |v| std.mem.eql(u8, v, "all") else false; + // rev-list and diff-tree decorate with every ref. + const every_ref = command == .rev_list or command == .diff_tree; + const all = every_ref or options.clear_decorations or if (config.getString("log.initialDecorationSet") catch null) |v| std.mem.eql(u8, v, "all") else false; var config_exclude: std.ArrayList([]const u8) = .empty; - if (command != .rev_list) if (config.all("log.excludeDecoration") catch null) |found| { + if (!every_ref) if (config.all("log.excludeDecoration") catch null) |found| { var excludes = found; while (excludes.next()) |e| if (e.value) |v| try config_exclude.append(a, v); }; diff --git a/tools/diff_tree.zig b/tools/diff_tree.zig index f1dd04a..02ab9ab 100644 --- a/tools/diff_tree.zig +++ b/tools/diff_tree.zig @@ -4,13 +4,25 @@ //! `zig-git diff-tree`: two trees compared, or a commit with its parents, //! written as `git diff-tree` writes them. //! -//! zig-git diff-tree [-r] [-t] [--root] [-m] [--no-commit-id] [--always] -//! [--stdin] [-s] [...] [] [[--] ...] +//! zig-git diff-tree [--stdin] [-m] [-s] [-v] [--no-commit-id] [--pretty] +//! [-t] [-r] [-c | --cc] [--combined-all-paths] [--root] [--merge-base] +//! [] [] [...] //! //! A commit's line comes before its changes; a merge shows nothing -//! unless `-m` asks for each parent in turn, and a root commit nothing -//! unless `--root`. Combined diffs (`-c`, `--cc`) and `-v`/`--pretty` -//! are refused by name. +//! unless `-m` asks for each parent in turn, or `-c` or `--cc` for its +//! combined diff (`log_diff.Writer.writeCombined`), and a root commit +//! nothing unless `--root`. `--merge-base` compares two commits' merge +//! base with the second. +//! +//! `-v`, `--pretty`, `--format` and `--oneline` describe the commit as +//! `git log` would (`describe.zig`, as `.diff_tree`) in place of its line, +//! with what git was seen to do: the object IDs as long as the raw +//! format's (whole unless `--abbrev` says otherwise), none of the `log.*` +//! settings nor `format.pretty` read, `email` without `[PATCH]`, the +//! separator between the commit and its diff `log`'s, and `--always` +//! writing the commit once where nothing differs (after the diff under +//! `--no-commit-id`). `--first-parent` changes nothing. What is refused, +//! by name, is listed where it is refused. const std = @import("std"); const Allocator = std.mem.Allocator; @@ -29,25 +41,81 @@ const pathspecs = @import("pathspecs.zig"); const check_attr = @import("check_attr.zig"); const repo_diff = @import("repo_diff.zig"); const line_prefix = @import("line_prefix.zig"); +const describe = @import("describe.zig"); +const log_diff = @import("log_diff.zig"); +const history = @import("history.zig"); const usage = @embedFile("diff_tree_usage.txt"); +/// How a merge is shown: not at all, against each parent (`-m`), or as +/// a combined diff (`-c`, `--cc`); the last of them given wins. +const Merges = enum { none, separate, combined, dense }; + const Options = struct { recursive: bool = false, show_trees: bool = false, root: bool = false, - each_parent: bool = false, + merges: Merges = .none, + /// `--combined-all-paths`, which `-m`, `-c` and `--cc` given after it + /// forget, as git was seen to. + all_paths: bool = false, commit_id: bool = true, always: bool = false, stdin: bool = false, + /// `-v`, `--pretty`, `--format`, `--oneline`: the commit described + /// in place of its line. + verbose: bool = false, + /// `--merge-base`. + merge_base: bool = false, +}; + +/// The options of git's revision machinery that `git diff-tree` was seen +/// to take, whose effects are not matched: refused by name. +const refused_revision_options = [_][]const u8{ + "--notes", "--no-notes", "--show-notes", "--standard-notes", "--no-standard-notes", + "--show-signature", "--graph", "--log-size", "--no-walk", "--do-walk", + "--parents", "--children", "--left-right", "--cherry-mark", "--cherry-pick", + "--show-linear-break", "--reverse", "--max-count", "--skip", "--since", + "--until", "--after", "--before", "--merges", "--no-merges", + "--min-parents", "--max-parents", "--topo-order", "--date-order", "--author-date-order", + "--full-history", "--simplify-merges", "--simplify-by-decoration", "--sparse", "--dense", + "--ancestry-path", "--boundary", "--grep", "--author", "--committer", + "--all-match", "--invert-grep", "--extended-regexp", "--fixed-strings", "--basic-regexp", + "--perl-regexp", }; +/// Whether `arg` is one of `refused_revision_options`, or `-E`, `-F`, +/// `-P` or `-n`. (`-i` and `--regexp-ignore-case` are the pickaxe's.) +fn isRefusedRevisionOption(arg: []const u8) bool { + const name = arg[0 .. std.mem.findScalar(u8, arg, '=') orelse arg.len]; + for (refused_revision_options) |r| if (std.mem.eql(u8, r, name)) return true; + const short = [_][]const u8{ "-E", "-F", "-P", "-n" }; + for (short) |r| if (std.mem.eql(u8, r, arg)) return true; + return false; +} + +/// The options `describe` reads that `git diff-tree` takes: how the +/// commit is described under `-v`. +fn isDescribeOption(arg: []const u8) bool { + const name = arg[0 .. std.mem.findScalar(u8, arg, '=') orelse arg.len]; + const names = [_][]const u8{ + "--pretty", "--format", "--oneline", "--abbrev-commit", "--no-abbrev-commit", + "--date", "--relative-date", "--expand-tabs", "--no-expand-tabs", "--encoding", + }; + for (names) |n| if (std.mem.eql(u8, n, name)) return true; + return false; +} + /// Runs `zig-git diff-tree`. pub fn run(ctx: Context, args: []const []const u8, stdin: *Io.Reader, stdout: *Io.Writer, stderr: *Io.Writer) !void { const gpa = ctx.gpa; var s: repo_diff.Settings = .{ .command = .diff_tree }; defer s.deinit(gpa); var o: Options = .{}; + var described: describe.Options = .{}; + defer described.deinit(gpa); + var arena_state: std.heap.ArenaAllocator = .init(gpa); + defer arena_state.deinit(); var words: std.ArrayList([]const u8) = .empty; defer words.deinit(gpa); var after_dashdash: std.ArrayList([]const u8) = .empty; @@ -80,16 +148,42 @@ pub fn run(ctx: Context, args: []const []const u8, stdin: *Io.Reader, stdout: *I o.show_trees = true; } else if (std.mem.eql(u8, arg, "--root")) { o.root = true; - } else if (std.mem.eql(u8, arg, "-m")) { - o.each_parent = true; + } else if (std.mem.eql(u8, arg, "-m") or std.mem.eql(u8, arg, "-c") or std.mem.eql(u8, arg, "--cc")) { + o.merges = if (arg[1] == 'm') .separate else if (arg[1] == 'c') .combined else .dense; + o.all_paths = false; + } else if (std.mem.eql(u8, arg, "--combined-all-paths")) { + o.all_paths = true; + } else if (std.mem.eql(u8, arg, "-v")) { + o.verbose = true; + } else if (std.mem.eql(u8, arg, "--first-parent")) { + // git diff-tree was seen to show every parent under -m + // whether or not it is given. + } else if (std.mem.eql(u8, arg, "--merge-base")) { + o.merge_base = true; + } else if (isRefusedRevisionOption(arg)) { + return repo_diff.unsupported(stderr, .diff_tree, arg); + } else if (isDescribeOption(arg)) { + // `--date` and `--encoding` take the next argument when they + // have no value of their own, as git was seen to take it. + var given = arg; + if ((std.mem.eql(u8, arg, "--date") or std.mem.eql(u8, arg, "--encoding")) and i + 1 < args.len) { + given = try std.fmt.allocPrint(arena_state.allocator(), "{s}={s}", .{ arg, args[i + 1] }); + i += 1; + } + switch (try describe.parseOption(&described, gpa, given, null, stderr)) { + .yes, .took_next => {}, + .no => { + stderr.writeAll(usage) catch {}; + return error.UsageQuiet; + }, + } + if (std.mem.startsWith(u8, arg, "--pretty") or std.mem.startsWith(u8, arg, "--format") or std.mem.eql(u8, arg, "--oneline")) o.verbose = true; } else if (std.mem.eql(u8, arg, "--no-commit-id")) { o.commit_id = false; } else if (std.mem.eql(u8, arg, "--always")) { o.always = true; } else if (std.mem.eql(u8, arg, "--stdin")) { o.stdin = true; - } else if (std.mem.eql(u8, arg, "-v") or std.mem.startsWith(u8, arg, "--pretty") or std.mem.startsWith(u8, arg, "--format") or std.mem.eql(u8, arg, "--first-parent") or std.mem.eql(u8, arg, "--merge-base")) { - return repo_diff.unsupported(stderr, .diff_tree, arg); } else { const next: ?[]const u8 = if (i + 1 < args.len) args[i + 1] else null; switch (try repo_diff.parseOption(gpa, &s, arg, next, stderr)) { @@ -103,12 +197,21 @@ pub fn run(ctx: Context, args: []const []const u8, stdin: *Io.Reader, stdout: *I } } try repo_diff.check(&s, stderr); - if (!s.format_given) s.out.format.raw = true; + if (o.all_paths and o.merges != .combined and o.merges != .dense) + return tool.fatalMessage(stderr, "--combined-all-paths makes no sense without -c or --cc", .{}); + if (o.stdin and o.merge_base) return tool.fatalMessage(stderr, "options '--stdin' and '--merge-base' cannot be used together", .{}); + // --cc shows a patch unless a format is given; -c the raw format. + if (!s.format_given) { + if (o.merges == .dense) s.out.format.patch = true else s.out.format.raw = true; + } // The formats that read contents go into subtrees, unless the name // formats replace them. const fmt = s.out.format; - if (!fmt.name_only and !fmt.name_status and (fmt.patch or fmt.stat or fmt.numstat or fmt.shortstat or fmt.summary)) o.recursive = true; + if (!fmt.name_only and !fmt.name_status and (fmt.patch or fmt.stat or fmt.numstat or fmt.shortstat or fmt.summary or fmt.dirstat)) o.recursive = true; if (s.quiet) s.exit_code = true; + // With -t, git was seen to count the trees' own entries in the + // directories' shares, by a rule not found. + if (fmt.dirstat and o.show_trees) return repo_diff.unsupported(stderr, .diff_tree, "--dirstat with -t"); const settings = try object_names.settings(&repo.config, stderr); var names: object_names.Names = .init(ctx, &repo, settings); @@ -127,9 +230,10 @@ pub fn run(ctx: Context, args: []const []const u8, stdin: *Io.Reader, stdout: *I var paths: std.ArrayList([]const u8) = .empty; defer paths.deinit(gpa); var in_paths = false; + var range_given = false; for (words.items) |w| { if (!in_paths) { - if (try resolveWord(&revs, w, &trees)) continue; + if (try resolveWord(&revs, &repo, w, &trees, &range_given)) continue; in_paths = true; if (!try pathspecs.takenForPath(ctx, &repo, w)) { try stderr.print( @@ -151,6 +255,10 @@ pub fn run(ctx: Context, args: []const []const u8, stdin: *Io.Reader, stdout: *I } else if (trees.items.len == 0) { stderr.writeAll(usage) catch {}; return error.UsageQuiet; + } else if (o.merge_base) { + if (trees.items.len != 2) return tool.fatalMessage(stderr, "--merge-base only works with two commits", .{}); + if (range_given) return tool.fatalMessage(stderr, "--merge-base does not work with ranges", .{}); + trees.items[0] = try mergeBase(ctx, &repo, &revs, trees.items[0], trees.items[1], stderr); } else if (trees.items.len > 2) { return repo_diff.unsupported(stderr, .diff_tree, "more than two revisions"); } @@ -179,6 +287,24 @@ pub fn run(ctx: Context, args: []const []const u8, stdin: *Io.Reader, stdout: *I defer drivers.deinit(); var blobs: repo_diff.BlobSource = .{ .ctx = ctx, .repo = &repo }; + // The commit described as `log` describes it, its object IDs as long + // as the raw format's: whole unless --abbrev is given. + described.nul = s.out.nul; + described.abbrev = s.out.raw_abbrev; + described.no_abbrev = s.out.raw_abbrev == null; + var describer: ?describe.Describer = if (o.verbose) try describe.Describer.init(ctx, &repo, &names, &revs, &described, .diff_tree, stderr) else null; + defer if (describer) |*d| d.deinit(); + // Where a format: string leaves its line open, git was seen to put the + // prefix of --line-prefix before some of the separators and not + // others, by a rule not found. + if (describer) |*d| if (s.line_prefix != null) if (d.format) |*f| if (f.* == .user and !f.terminated() and !f.user.empty) + return repo_diff.unsupported(stderr, .diff_tree, "--line-prefix with a format: string"); + const combiner: ?*log_diff.Writer = if (o.merges == .combined or o.merges == .dense) + try log_diff.Writer.initCombined(ctx, &repo, &revs, &names, &s, &spec, if (o.merges == .dense) .dense_combined else .combined, o.all_paths, stderr) + else + null; + defer if (combiner) |c| c.deinit(); + var out_alloc: Io.Writer.Allocating = .init(gpa); defer out_alloc.deinit(); const base_w: *Io.Writer = if (s.output_path != null) &out_alloc.writer else stdout; @@ -186,6 +312,9 @@ pub fn run(ctx: Context, args: []const []const u8, stdin: *Io.Reader, stdout: *I var prefixed: line_prefix.LinePrefix = .init(base_w, s.line_prefix orelse "", &prefix_buffer); defer prefixed.writer.flush() catch {}; const w: *Io.Writer = if (s.line_prefix != null) &prefixed.writer else base_w; + if (combiner) |c| if (s.line_prefix != null) { + c.unprefixed = base_w; + }; var discarding: Io.Writer.Discarding = .init(&.{}); const sink = if (s.quiet) &discarding.writer else w; @@ -201,6 +330,9 @@ pub fn run(ctx: Context, args: []const []const u8, stdin: *Io.Reader, stdout: *I .header_w = w, .stdout = stdout, .stderr = stderr, + .describer = if (describer) |*d| d else null, + .combiner = combiner, + .prefixed = if (s.line_prefix != null) &prefixed else null, }; if (o.stdin) { var line: std.ArrayList(u8) = .empty; @@ -240,8 +372,9 @@ pub fn run(ctx: Context, args: []const []const u8, stdin: *Io.Reader, stdout: *I } /// Resolves `w` as a revision or a range, appending its objects; false -/// when it names none. -fn resolveWord(revs: *revisions.Revisions, w: []const u8, out: *std.ArrayList(ObjectId)) !bool { +/// when it names none. A symmetric difference `A...B` stands for three +/// objects, as git was seen to count it: its ends and their merge base. +fn resolveWord(revs: *revisions.Revisions, repo: *git.Repository, w: []const u8, out: *std.ArrayList(ObjectId), range_given: *bool) !bool { const gpa = revs.ctx.gpa; if (git.revision.parseSet(w)) |set| switch (set) { .range => |r| { @@ -249,6 +382,19 @@ fn resolveWord(revs: *revisions.Revisions, w: []const u8, out: *std.ArrayList(Ob const to = resolveOne(revs, if (r.to.len == 0) "HEAD" else r.to) orelse return false; try out.append(gpa, from); try out.append(gpa, to); + range_given.* = true; + return true; + }, + .symmetric => |r| { + const left = resolveOne(revs, if (r.left.len == 0) "HEAD" else r.left) orelse return false; + const right = resolveOne(revs, if (r.right.len == 0) "HEAD" else r.right) orelse return false; + try out.appendSlice(gpa, &.{ left, right }); + // Their merge bases follow, which make more than two; with + // none it is a range of two. + const found = try allBases(revs.ctx, repo, revs, left, right, null); + defer gpa.free(found); + try out.appendSlice(gpa, found); + range_given.* = true; return true; }, else => return false, @@ -258,6 +404,47 @@ fn resolveWord(revs: *revisions.Revisions, w: []const u8, out: *std.ArrayList(Ob return true; } +/// The merge base of commits `one` and `two`, for `--merge-base`, with +/// git's messages where there is none, or more than one. +fn mergeBase(ctx: Context, repo: *git.Repository, revs: *revisions.Revisions, one: ObjectId, two: ObjectId, stderr: *Io.Writer) !ObjectId { + const found = try allBases(ctx, repo, revs, one, two, stderr); + defer ctx.gpa.free(found); + if (found.len == 0) return tool.fatalMessage(stderr, "no merge base found", .{}); + if (found.len > 1) return tool.fatalMessage(stderr, "multiple merge bases found", .{}); + return found[0]; +} + +/// Every merge base of `one` and `two`. Where either is not a commit +/// there are none; with `stderr`, that is fatal, as `--merge-base` makes +/// it. +fn allBases(ctx: Context, repo: *git.Repository, revs: *revisions.Revisions, one: ObjectId, two: ObjectId, stderr: ?*Io.Writer) ![]ObjectId { + const gpa = ctx.gpa; + var ends: [2]ObjectId = undefined; + for ([_]ObjectId{ one, two }, &ends) |id, *end| { + end.* = try revs.resolver.peelToCommit(id) orelse { + const w = stderr orelse return gpa.alloc(ObjectId, 0); + var o = repo.objects().read(ctx.io, gpa, id, null) catch return tool.fatalMessage(w, "no merge base found", .{}); + defer o.deinit(gpa); + try w.print("error: object {f} is a {s}, not a commit\n", .{ id, @tagName(o.kind) }); + return tool.fatalMessage(w, "no merge base found", .{}); + }; + } + var discard: Io.Writer.Discarding = .init(&.{}); + const err_w = stderr orelse &discard.writer; + var h = try history.History.open(ctx, repo, err_w); + defer h.close(); + const store = &h.store; + var diag: Diagnostics = .{}; + const a = try store.name(ends[0]); + const b = try store.name(ends[1]); + const found = git.merge_base.bases(gpa, store, a, &.{b}, true, &diag) catch |err| return h.fail(err, &diag, null, err_w); + defer gpa.free(found); + try h.report(err_w); + const ids = try gpa.alloc(ObjectId, found.len); + for (found, ids) |f, *id| id.* = store.id(f); + return ids; +} + fn resolveOne(revs: *revisions.Revisions, text: []const u8) ?ObjectId { var diag: Diagnostics = .{}; const found = revs.resolver.resolve(text, &diag) catch { @@ -296,6 +483,15 @@ pub const Comparer = struct { /// `--line-prefix` and `--output`, as git was seen to write them. stdout: *Io.Writer, stderr: *Io.Writer, + /// Under `-v` and the rest, what describes each commit in place of + /// its line. + describer: ?*describe.Describer = null, + /// Under `-c` and `--cc`, what writes a merge's combined diff. + combiner: ?*log_diff.Writer = null, + /// Under `--line-prefix`, what puts the prefix before each line. + prefixed: ?*line_prefix.LinePrefix = null, + /// Whether the commit being compared has had its line written. + header_shown: bool = false, warnings: repo_diff.RenameWarnings = .{}, /// Whether `--check` found a problem. problems: bool = false, @@ -306,9 +502,9 @@ pub const Comparer = struct { /// not made, and counts as finding none. has_changes: bool = false, - /// Compares two tree-ishes, writing `header` first if anything is - /// written. Returns whether anything differs. - fn trees(t: *Comparer, old: ObjectId, new: ObjectId, header: ?[]const u8) !bool { + /// Compares two tree-ishes, writing the commit `header` names first + /// if anything is written. Returns whether anything differs. + fn trees(t: *Comparer, old: ObjectId, new: ObjectId, header: ?Header) !bool { const gpa = t.ctx.gpa; if (t.skipped()) return false; const old_tree = try t.treeOf(old); @@ -335,36 +531,64 @@ pub const Comparer = struct { } /// Finds renames and applies `--diff-filter`, then writes. - fn emitPrepared(t: *Comparer, pairs: *Pairs, source_tree: ?ObjectId, header: ?[]const u8) !bool { + fn emitPrepared(t: *Comparer, pairs: *Pairs, source_tree: ?ObjectId, header: ?Header) !bool { const gpa = t.ctx.gpa; var unchanged: Pairs = .init(gpa); defer unchanged.deinit(gpa); - if (t.settings.harder and t.settings.renames) try collectUnchanged(t.ctx, t.repo, t.spec, source_tree, pairs, t.settings, &unchanged, t.stderr); + if (t.settings.harder and t.settings.renames) { + try collectUnchanged(t.ctx, t.repo, t.spec, source_tree, pairs, t.settings, &unchanged, t.stderr); + // Without -r, only the files at the top are copy sources, as + // git was seen to look for them. + if (!t.options.recursive) { + var k: usize = 0; + for (unchanged.list.items) |p| if (std.mem.findScalar(u8, p.path, '/') == null) { + unchanged.list.items[k] = p; + k += 1; + }; + unchanged.list.shrinkRetainingCapacity(k); + } + } const shown = repo_diff.prepare(gpa, t.settings, pairs.list.items, unchanged.list.items, t.source, t.drivers, &t.warnings, t.stderr) catch |err| return t.failed(err); defer gpa.free(shown); return t.emit(shown, header); } - fn emit(t: *Comparer, all_pairs: []const output.Pair, header: ?[]const u8) !bool { + fn emit(t: *Comparer, all_pairs: []const output.Pair, header: ?Header) !bool { const s = t.settings; // The commit's line goes by what differs before a whitespace // option or -I drops anything, as git was seen to write it. - if (header) |h| if (t.options.commit_id and (all_pairs.len != 0 or t.options.always)) { - // The line's end is a NUL under -z. - try t.header_w.writeAll(h[0 .. h.len - 1]); - try t.header_w.writeByte(if (s.out.nul) 0 else '\n'); + if (header) |h| if (t.options.commit_id and all_pairs.len != 0) { + try t.writeHeader(h); + // A described commit is separated from its diff as `log` + // separates them, when anything differs and a format writes + // it. + if (t.describer) |d| if (all_pairs.len != 0 and s.out.format.any()) switch (d.framing()) { + .full => { + const f = s.out.format; + try t.w.writeAll(if (f.patch and f.stat and !f.name_only and !f.name_status) "---\n" else "\n"); + }, + .oneline, .empty => {}, + }; }; const outcome = output.write(t.ctx.gpa, t.w, all_pairs, t.source, t.drivers, s.out) catch |err| return t.failed(err); if (outcome.problems) t.problems = true; - // With --no-commit-id, --always still writes the commit's line, - // after what differs, as git was seen to. - if (header) |h| if (!t.options.commit_id and t.options.always) { - try t.header_w.writeAll(h[0 .. h.len - 1]); - try t.header_w.writeByte(if (s.out.nul) 0 else '\n'); - }; return outcome.differs; } + /// The commit's line, or under `-v` its description; the line's end + /// is a NUL under -z. + fn writeHeader(t: *Comparer, h: Header) !void { + t.header_shown = true; + if (t.describer) |d| { + if (t.prefixed) |p| try p.startLine(); + try d.writeCommit(t.header_w, .{ .id = h.id, .parents = h.parents, .from = h.from }, t.stderr); + if (t.prefixed) |p| try p.endLine(); + return; + } + try t.header_w.print("{f}", .{h.id}); + try t.header_w.writeByte(if (t.settings.out.nul) 0 else '\n'); + } + fn failed(t: *Comparer, err: anyerror) anyerror { return switch (err) { error.DriverUnsupported => error.Fatal, @@ -416,24 +640,73 @@ pub const Comparer = struct { var it = c.parents(); while (it.next()) |p| try parents.append(gpa, p); } - var header_buf: [2 * git.object_max_hex_length + 16]u8 = undefined; - const header = std.fmt.bufPrint(&header_buf, "{f}\n", .{id}) catch unreachable; - if (parents.items.len == 0) { + const header: Header = .{ .id = id, .parents = parents.items }; + t.header_shown = false; + const differs = try t.commitDiffs(id, c.tree, parents.items, header); + // --always writes the commit's line where nothing differs, once, + // and with --no-commit-id after all that differs, as git was + // seen to. + if (t.options.always and (!t.options.commit_id or !t.header_shown)) try t.writeHeader(header); + return differs; + } + + fn commitDiffs(t: *Comparer, id: ObjectId, tree: ObjectId, parents: []const ObjectId, header: Header) !bool { + const gpa = t.ctx.gpa; + if (parents.len == 0) { if (!t.options.root) return t.emit(&.{}, header); if (t.skipped()) return false; var pairs: Pairs = .init(gpa); defer pairs.deinit(gpa); - try collectTrees(t.ctx, t.repo, t.spec, null, c.tree, t.options.recursive, t.options.show_trees, t.settings, &pairs, t.stderr); - return t.compared(try t.emitPrepared(&pairs, if (t.settings.reverse) c.tree else null, header)); + try collectTrees(t.ctx, t.repo, t.spec, null, tree, t.options.recursive, t.options.show_trees, t.settings, &pairs, t.stderr); + return t.compared(try t.emitPrepared(&pairs, if (t.settings.reverse) tree else null, header)); } - if (parents.items.len > 1 and !t.options.each_parent) return t.emit(&.{}, header); + if (parents.len > 1) switch (t.options.merges) { + .none => return t.emit(&.{}, header), + .separate => {}, + .combined, .dense => return t.combined(id, parents, header), + }; var differs = false; - for (parents.items) |p| { - if (try t.trees(p, c.tree, header)) differs = true; + for (parents) |p| { + var h = header; + if (parents.len > 1) h.from = p; + if (try t.trees(p, tree, h)) differs = true; } return differs; } + /// A merge's combined diff (`-c`, `--cc`): the commit's line, or its + /// description, whatever differs, as git was seen to write it, and + /// then what `log_diff.Writer.writeCombined` writes. Refused by name + /// where what git does was not established: with `-t`, `-R`, `--relative`, + /// `--diff-filter`, `--quiet`, `--exit-code` and `--check`. + fn combined(t: *Comparer, id: ObjectId, parents: []const ObjectId, header: Header) !bool { + const s = t.settings; + const c = t.combiner.?; + const refusal: ?[]const u8 = if (t.options.show_trees) + "-t with a merge's combined diff" + else if (s.reverse) + "-R with a merge's combined diff" + else if (s.relative != null) + "--relative with a merge's combined diff" + else if (s.filter_given) + "--diff-filter with a merge's combined diff" + else if (s.quiet) + "--quiet with a merge's combined diff" + else if (s.exit_code) + "--exit-code with a merge's combined diff" + else if (s.out.format.check) + "--check with a merge's combined diff" + else + null; + if (refusal) |r| return repo_diff.unsupported(t.stderr, .diff_tree, r); + try c.checkCombined(parents); + if (s.output_path != null) return tool.fatalMessage(t.stderr, "combined diff and '--output' cannot be used together", .{}); + if (t.options.commit_id) try t.writeHeader(header); + const framing: log_diff.Framing = if (t.describer != null and t.options.commit_id) t.describer.?.framing() else .empty; + try c.writeCombined(t.w, id, parents, framing); + return t.compared(false); + } + /// A line of `--stdin`, without its newline (`terminated` says /// whether it had one), as git was seen to read it: /// @@ -530,6 +803,14 @@ pub const Comparer = struct { } }; +/// The commit a comparison is of, for its line: its parents, and under +/// `-m` the one compared with. +const Header = struct { + id: ObjectId, + parents: []const ObjectId, + from: ?ObjectId = null, +}; + /// Whether `c` separates the IDs of a `--stdin` line: a space, a tab or /// a carriage return, as git was seen to take them (and not a vertical /// tab or a form feed). diff --git a/tools/diff_tree_tests.zig b/tools/diff_tree_tests.zig index 68137a0..70b23eb 100644 --- a/tools/diff_tree_tests.zig +++ b/tools/diff_tree_tests.zig @@ -398,3 +398,106 @@ test "diff-tree: --exit-code and --quiet go by the last parent compared" { try same(&repo, &.{ "diff-tree", "-m", "-p", "--exit-code", ref }); } } + +/// `makeHistory`, then merges that differ from every parent: one with +/// a resolution and a change neither parent has, an octopus, and +/// commits in Latin-1 and with a tab in the message. +fn makeMerges(repo: *Repo) !void { + try makeHistory(repo); + try repo.git(&.{ "checkout", "-q", "-f", "-b", "left", "HEAD" }); + try write(repo, "mod", "one\nleft\nthree\nfour\nfive\nsix\nseven\neight\nnine\n10\neleven\n"); + try write(repo, "dir/g", "left g\n"); + try repo.git(&.{ "add", "-A" }); + try repo.commit("left"); + try repo.git(&.{ "checkout", "-q", "-f", "main" }); + try write(repo, "mod", "one\n2\nthree\nfour\nfive\nsix\nseven\neight\nnine\nmain\neleven\n"); + try write(repo, "dir/g", "main g\n"); + try repo.git(&.{ "add", "-A" }); + try repo.git(&.{ "-c", "i18n.commitEncoding=ISO-8859-1", "commit", "-q", "-m", "caf\xe9 on main\n\n\tindented body" }); + // Each merge stops at its conflicts, which are then resolved. + (try repo.runIn(".", &.{ "merge", "-q", "--no-commit", "left" }, "")).deinit(repo.gpa); + try write(repo, "mod", "one\nleft\nthree\nfour\nfive\nsix\nseven\neight\nnine\nmain\neleven\n"); + try write(repo, "dir/g", "resolved g\n"); + try write(repo, "evil", "no parent has this\n"); + try repo.git(&.{ "add", "-A" }); + try repo.commit("merge left"); + for ([_][]const u8{ "o1", "o2" }) |b| { + try repo.git(&.{ "checkout", "-q", "-f", "-b", b, "HEAD~" }); + try write(repo, "mod", b); + const name = try std.fmt.allocPrint(repo.gpa, "{s}.txt", .{b}); + defer repo.gpa.free(name); + try write(repo, name, b); + try repo.git(&.{ "add", "-A" }); + try repo.commit(b); + } + try repo.git(&.{ "checkout", "-q", "-f", "main" }); + (try repo.runIn(".", &.{ "merge", "-q", "--no-commit", "o1", "o2" }, "")).deinit(repo.gpa); + try write(repo, "mod", "octopus\n"); + try write(repo, "o1.txt", "o1"); + try write(repo, "o2.txt", "o2"); + try repo.git(&.{ "add", "-A" }); + try repo.commit("octopus"); +} + +test "diff-tree: combined diffs and described commits, every way of showing merges" { + const gpa = testing.allocator; + var repo = try Repo.init(gpa, testing.io); + defer repo.deinit(); + try makeMerges(&repo); + const input = try repo.output(&.{ "rev-list", "--all" }); + defer gpa.free(input); + const merges = [_][]const []const u8{ &.{}, &.{"-m"}, &.{"-c"}, &.{"--cc"}, &.{ "--cc", "-m" }, &.{ "-m", "-c" }, &.{ "-c", "--combined-all-paths", "-M" }, &.{ "-m", "--first-parent" } }; + const described = [_][]const []const u8{ + &.{}, &.{"-v"}, &.{"--pretty=oneline"}, &.{"--format=%h %s"}, &.{"--pretty=fuller"}, &.{"--pretty=email"}, + &.{"--format=format:%s"}, &.{"--format="}, &.{"--pretty=raw"}, &.{ "--oneline", "--abbrev=9" }, &.{ "--pretty=short", "--abbrev-commit", "--abbrev=10" }, &.{ "-v", "--encoding=UTF-8" }, + &.{ "--format=%P|%p|%d", "--no-commit-id", "--always" }, + }; + const formats = [_][]const []const u8{ &.{}, &.{"-p"}, &.{"--stat"}, &.{"--name-status"}, &.{"-s"}, &.{"-z"}, &.{"--patch-with-stat"}, &.{ "--summary", "-p" }, &.{"--dirstat"} }; + for (merges) |m| for (described) |d| for (formats) |f| { + var args: std.ArrayList([]const u8) = .empty; + defer args.deinit(gpa); + try args.appendSlice(gpa, &.{ "diff-tree", "--stdin" }); + try args.appendSlice(gpa, m); + try args.appendSlice(gpa, d); + try args.appendSlice(gpa, f); + try tool.expectSameAsGitHow(&repo, args.items, .{ .input = input }); + }; + // One at a time, with --always and without the commit's line. + for ([_][]const u8{ "HEAD", "HEAD~", "HEAD~2" }) |rev| { + for ([_][]const []const u8{ + &.{ "--cc", "-v" }, &.{ "-c", "-v", "--stat" }, &.{ "-m", "-v", "--always", "--no-commit-id" }, + &.{ "--cc", "--no-commit-id", "-v" }, &.{ "-m", "--always", "--format=%s" }, &.{ "--cc", "--line-prefix=> ", "-v", "--name-status" }, + &.{ "-c", "--line-prefix=> ", "--format=", "-p" }, &.{ "-v", "--date=iso", "-m" }, &.{ "-v", "--date", "raw", "-m" }, + }) |opts| { + var args: std.ArrayList([]const u8) = .empty; + defer args.deinit(gpa); + try args.append(gpa, "diff-tree"); + try args.appendSlice(gpa, opts); + try args.append(gpa, rev); + try same(&repo, args.items); + } + } +} + +test "diff-tree: --merge-base, and what git refuses with combined diffs" { + const gpa = testing.allocator; + var repo = try Repo.init(gpa, testing.io); + defer repo.deinit(); + try makeMerges(&repo); + try same(&repo, &.{ "diff-tree", "--merge-base", "left", "o1" }); + try same(&repo, &.{ "diff-tree", "--merge-base", "-v", "-p", "o1", "left" }); + try same(&repo, &.{ "diff-tree", "--merge-base", "side", "main" }); + try same(&repo, &.{ "diff-tree", "--merge-base", "HEAD" }); + try same(&repo, &.{ "diff-tree", "--merge-base", "HEAD", "HEAD~", "HEAD~2" }); + try same(&repo, &.{ "diff-tree", "--merge-base", "o1..o2" }); + try same(&repo, &.{ "diff-tree", "--merge-base", "o1...o2" }); + try same(&repo, &.{ "diff-tree", "--merge-base", "HEAD^{tree}", "HEAD" }); + try tool.expectSameAsGitHow(&repo, &.{ "diff-tree", "--merge-base", "--stdin" }, .{ .input = "" }); + try same(&repo, &.{ "diff-tree", "--combined-all-paths", "HEAD" }); + try same(&repo, &.{ "diff-tree", "--combined-all-paths", "-m", "HEAD" }); + try same(&repo, &.{ "diff-tree", "--combined-all-paths", "-c", "HEAD" }); + try same(&repo, &.{ "diff-tree", "--cc", "-I", "x", "HEAD" }); + try same(&repo, &.{ "diff-tree", "--pretty=bogus", "HEAD" }); + try same(&repo, &.{ "diff-tree", "--format", "HEAD" }); + try same(&repo, &.{ "diff-tree", "--decorate", "-v", "HEAD" }); +} diff --git a/tools/line_prefix.zig b/tools/line_prefix.zig index 8d23cb4..1e137bf 100644 --- a/tools/line_prefix.zig +++ b/tools/line_prefix.zig @@ -22,6 +22,24 @@ pub const LinePrefix = struct { return .{ .out = out, .prefix = prefix, .writer = .{ .vtable = &.{ .drain = drain }, .buffer = buffer } }; } + /// Starts a line of its own: the prefix, if nothing has been written + /// on the line, even if nothing follows it. git was seen to write the + /// prefix before a commit's description however little that writes. + pub fn startLine(lp: *LinePrefix) Io.Writer.Error!void { + try lp.writer.flush(); + if (lp.at_start) try lp.out.writeAll(lp.prefix); + lp.at_start = false; + } + + /// Ends what was written, so that the next thing written has the + /// prefix before it, as git was seen to put it before a diff after a + /// commit's description, even where the description did not end its + /// line. + pub fn endLine(lp: *LinePrefix) Io.Writer.Error!void { + try lp.writer.flush(); + lp.at_start = true; + } + fn emit(lp: *LinePrefix, bytes: []const u8) Io.Writer.Error!void { var rest = bytes; while (rest.len != 0) { diff --git a/tools/log_diff.zig b/tools/log_diff.zig index 808e5ff..940fe90 100644 --- a/tools/log_diff.zig +++ b/tools/log_diff.zig @@ -225,6 +225,14 @@ pub const Writer = struct { current: ?ObjectId = null, /// Whether `--check` found a problem in any diff written. problems: bool = false, + /// Whether `settings` is a copy of another's, which `deinit` leaves + /// alone (`initCombined`). + borrowed_settings: bool = false, + /// Where what git was seen to write past `--line-prefix` goes, when + /// not where the rest goes: a combined diff's names (`--name-only`, + /// `--name-status`), and its patch's `mode` and `Binary files differ` + /// lines. + unprefixed: ?*Io.Writer = null, /// Sets up the diffs `collected` asks for; null when they ask for /// none. `default_patch` is `show`'s: a patch when no format is given. @@ -332,12 +340,56 @@ pub const Writer = struct { return w; } + /// Sets up the combined diffs of `git diff-tree -c` and `--cc` + /// (`merges` says which), with the settings `settings` holds, which + /// must outlive the writer and are not changed by it. + pub fn initCombined(ctx: Context, repo: *git.Repository, revs: *revisions.Revisions, names: *object_names.Names, settings: *const repo_diff.Settings, spec: *const git.Pathspec, merges: MergeDiffs, all_paths: bool, stderr: *Io.Writer) !*Writer { + const gpa = ctx.gpa; + const w = try gpa.create(Writer); + errdefer gpa.destroy(w); + var from: check_attr.From = .worktree; + if (try check_attr.configuredTree(ctx, repo, revs, stderr)) |f| from = f; + const attrs = try check_attr.setup(ctx, repo, from, stderr); + errdefer attrs.deinit(); + const conversion_attrs = try check_attr.setup(ctx, repo, from, stderr); + errdefer conversion_attrs.deinit(); + const whitespace_attrs = try check_attr.setup(ctx, repo, from, stderr); + errdefer whitespace_attrs.deinit(); + w.* = .{ + .ctx = ctx, + .repo = repo, + .settings = settings.*, + .borrowed_settings = true, + .spec = spec, + .first_parent = false, + .merges = merges, + .all_paths = all_paths, + .show_root = true, + .command = settings.command, + .stderr = stderr, + .names = names, + .short = .{ .ctx = ctx, .names = names }, + .attrs = attrs, + .conversion_attrs = conversion_attrs, + .whitespace_attrs = whitespace_attrs, + .drivers = undefined, + .blobs = .{ .ctx = ctx, .repo = repo }, + .buffer = .init(gpa), + .unchanged = .init(gpa), + }; + w.settings.out.patch.shorten = .{ .context = &w.short, .length = diff_tree.Short.length }; + w.drivers = .{ .gpa = gpa, .config = &repo.config, .setup = attrs, .conversions = conversion_attrs, .whitespace = whitespace_attrs, .stderr = stderr, .command = settings.command }; + if (w.settings.out.format.check) w.drivers.check = w.settings.out.whitespace; + return w; + } + pub fn deinit(w: *Writer) void { const gpa = w.ctx.gpa; - // `show` has written them after each commit (`endCommit`). - if (w.command != .show) w.warnings.flush(w.stderr) catch {}; + // `show` has written them after each commit (`endCommit`); a + // combined diff never warns of them. + if (w.command != .show and !w.borrowed_settings) w.warnings.flush(w.stderr) catch {}; w.unchanged.deinit(gpa); - w.settings.deinit(gpa); + if (!w.borrowed_settings) w.settings.deinit(gpa); w.attrs.deinit(); w.conversion_attrs.deinit(); w.whitespace_attrs.deinit(); @@ -538,18 +590,22 @@ pub const Writer = struct { const end: u8 = if (nul) 0 else '\n'; if (framing != .empty) try stdout.writeByte(end); if (f.name_only or f.name_status) { + const names = try w.unprefixedFor(stdout); for (paths.items) |row| { if (f.name_status) { - for (row) |q| try stdout.writeByte(q.status.letter()); - try stdout.writeByte(if (nul) 0 else '\t'); + for (row) |q| try names.writeByte(combinedLetter(q.status)); + try names.writeByte(if (nul) 0 else '\t'); } - try w.writeParentPaths(stdout, row); - try rawPath(stdout, row[0].path, &w.settings); - try stdout.writeByte(end); + try w.writeParentPaths(names, row); + try rawPath(names, row[0].path, &w.settings); + try names.writeByte(end); } return; } var written = false; + // An empty --summary calls for the empty line only before a file + // the patch shows, as git was seen to write it. + var summary_pending = false; if (f.numstat or f.stat or f.shortstat or f.summary or f.dirstat) { const saved = w.settings.out.format; defer w.settings.out.format = saved; @@ -565,7 +621,11 @@ pub const Writer = struct { error.ContentsUnreadable => return tool.fatalMessage(w.stderr, "zig-git {s}: cannot read a blob", .{w.command.name()}), else => |e| return repo_diff.refuseComparison(w.stderr, w.command, e), }; - written = outcome.written; + // The directories' shares call for the empty line before the + // patch whatever they measure, and even when none is shown, + // as git was seen to write it before a combined patch. + written = outcome.written or (f.dirstat and shown.len != 0); + summary_pending = !written and f.summary and shown.len != 0; } if (f.raw) for (paths.items) |row| { // A colon for each parent. @@ -578,7 +638,7 @@ pub const Writer = struct { } try w.writeId(stdout, row[0].new.id, w.settings.out.raw_abbrev); try stdout.writeByte(' '); - for (row) |q| try stdout.writeByte(q.status.letter()); + for (row) |q| try stdout.writeByte(combinedLetter(q.status)); try stdout.writeByte(if (nul) 0 else '\t'); try w.writeParentPaths(stdout, row); try rawPath(stdout, row[0].path, &w.settings); @@ -587,10 +647,18 @@ pub const Writer = struct { }; if (f.patch and paths.items.len != 0) { if (written) try stdout.writeByte(end); - for (paths.items) |row| try w.writeCombinedPatch(stdout, row); + for (paths.items) |row| try w.writeCombinedPatch(stdout, row, &summary_pending); } } + /// Where to write what goes past `--line-prefix`, after what was + /// written to `out`. + fn unprefixedFor(w: *Writer, out: *Io.Writer) !*Io.Writer { + const u = w.unprefixed orelse return out; + try out.flush(); + return u; + } + /// Under `--combined-all-paths`, each parent's path ahead of the /// merge's in the raw and name formats, each followed by a tab (a NUL /// under `-z`): where it was renamed or copied from there, or the @@ -609,7 +677,8 @@ pub const Writer = struct { var len = hex.len; if (abbrev) |a| { len = @min(@max(a, 4), hex.len); - if (!oid.eql(ObjectId.zero(oid.object_format))) len = @min(diff_tree.Short.length(&w.short, oid, len), hex.len); + // The zero ID too, as git was seen to lengthen it. + len = @min(diff_tree.Short.length(&w.short, oid, len), hex.len); } try out.writeAll(hex[0..len]); } @@ -624,7 +693,9 @@ pub const Writer = struct { return gpa.dupe(u8, o.data); } - fn writeCombinedPatch(w: *Writer, out: *Io.Writer, row: []const output.Pair) !void { + /// Writes one file's combined patch, if it shows anything, after an + /// empty line if `pending` says one is owed. + fn writeCombinedPatch(w: *Writer, out: *Io.Writer, row: []const output.Pair, pending: *bool) !void { const gpa = w.ctx.gpa; const result = row[0].new; var texts: std.ArrayList([]u8) = .empty; @@ -678,15 +749,20 @@ pub const Writer = struct { }; if (hunk_text.written().len == 0 and !absent_everywhere and result.present() and !modes_differ) return; } + if (pending.*) try out.writeByte(if (w.settings.out.nul) 0 else '\n'); + pending.* = false; try out.writeAll(if (dense) "diff --cc " else "diff --combined "); try quotePath(out, row[0].path, &w.settings); try out.writeAll("\nindex "); + // The repository's length, whatever --abbrev says, as git was + // seen to shorten them; whole under --full-index. + const index_abbrev: ?usize = if (po.abbrev == null) null else w.names.defaultLength(); for (row, 0..) |q, k| { if (k != 0) try out.writeByte(','); - try w.writeId(out, q.old.id, po.abbrev orelse null); + try w.writeId(out, q.old.id, index_abbrev); } try out.writeAll(".."); - try w.writeId(out, result.id, po.abbrev orelse null); + try w.writeId(out, result.id, index_abbrev); try out.writeByte('\n'); if (absent_everywhere) { try out.print("new file mode {o:0>6}\n", .{result.mode}); @@ -698,15 +774,16 @@ pub const Writer = struct { } try out.writeByte('\n'); } else if (modes_differ) { - try out.writeAll("mode "); + const m = try w.unprefixedFor(out); + try m.writeAll("mode "); for (row, 0..) |q, k| { - if (k != 0) try out.writeByte(','); - try out.print("{o:0>6}", .{q.old.mode}); + if (k != 0) try m.writeByte(','); + try m.print("{o:0>6}", .{q.old.mode}); } - try out.print("..{o:0>6}\n", .{result.mode}); + try m.print("..{o:0>6}\n", .{result.mode}); } // A binary file gets no hunks, and no ---/+++ lines either. - if (binary) return out.writeAll("Binary files differ\n"); + if (binary) return (try w.unprefixedFor(out)).writeAll("Binary files differ\n"); if (w.all_paths) { // A line for each parent: its own path, or /dev/null where it // has none. @@ -981,6 +1058,12 @@ pub const Follower = struct { } }; +/// A parent's status letter in a combined diff, where git was seen to +/// write a type change as a modification. +fn combinedLetter(status: output.Status) u8 { + return if (status == .type_changed) 'M' else status.letter(); +} + /// A path in the raw format or a list of names: quoted, or under -z as /// it is. fn rawPath(out: *Io.Writer, path: []const u8, s: *const repo_diff.Settings) !void { diff --git a/tools/repo_diff.zig b/tools/repo_diff.zig index ef241c6..e43a54e 100644 --- a/tools/repo_diff.zig +++ b/tools/repo_diff.zig @@ -266,6 +266,7 @@ pub fn comparisonRefusal(err: anyerror) ?[]const u8 { // `LineDiff.splitLines` numbers bytes in 32 bits. error.TooManyLines => "a file of 4 GiB or more", error.BlankFileUnsupported => "--check of a file of blank lines alone", + error.TooManyLostLines => "a combined diff merging more than 2^26 pairs of lines the parents lost at one place", else => null, }; } diff --git a/tools/rev_list.zig b/tools/rev_list.zig index 4403a0e..3f3faf3 100644 --- a/tools/rev_list.zig +++ b/tools/rev_list.zig @@ -836,6 +836,7 @@ fn commandName(command: describe.Command, as_whatchanged: bool) []const u8 { .rev_list => "rev-list", .log => "log", .show => "show", + .diff_tree => "diff-tree", }; } -- knotmirror 0.0.1