From 0bca4596352b341cc2d4ea1bf50bc96eb2bd52f0 Mon Sep 17 00:00:00 2001 From: "Jeffrey C. Ollie" Date: Sun, 1 Nov 2026 05:49:43 -0600 Subject: [PATCH] Describe commits as git log does, and answer log, show and check-mailmap pretty writes the built-in formats and format strings of git log --pretty to an Io.Writer: every placeholder that needs no decorations, notes, signatures or reflogs, with padding, truncation, wrapping, colors, magic and %(trailers), down to git's handling of NULs, control characters and placeholders it cannot answer, found by comparing with git over thousands of generated formats and awkward commits. grep chooses commits by message and identity. The walk takes a filter for the searches, and orders commits by the commit date git reads, which is narrower than the committer line it shows. zig-git log walks as rev-list does and describes what it lists; rev-list takes the same formats; show -s shows commits, tags, trees and blobs; check-mailmap maps contacts. What needs diffs, decorations, notes, signatures or another encoding is refused by name. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01P9FTtTrkEbuvbZnRyJCBir --- src/Commits.zig | 39 +- src/Mailmap.zig | 86 ++ src/RevWalk.zig | 21 +- src/fuzz/pretty-formats | 1 + src/grep.zig | 245 +++++ src/pretty.zig | 1975 +++++++++++++++++++++++++++++++++++++++ src/root.zig | 13 +- src/width.zig | 195 ++++ tools/describe.zig | 553 +++++++++++ tools/log.zig | 275 ++++++ tools/log_tests.zig | 522 +++++++++++ tools/rev_list.zig | 207 +++- tools/walk_tests.zig | 4 +- tools/zig_git.zig | 19 +- 14 files changed, 4096 insertions(+), 59 deletions(-) create mode 100644 src/fuzz/pretty-formats create mode 100644 src/grep.zig create mode 100644 src/pretty.zig create mode 100644 src/width.zig create mode 100644 tools/describe.zig create mode 100644 tools/log.zig create mode 100644 tools/log_tests.zig diff --git a/src/Commits.zig b/src/Commits.zig index 252d14c..cee7ea4 100644 --- a/src/Commits.zig +++ b/src/Commits.zig @@ -315,10 +315,43 @@ pub fn authorTime(s: *Commits, i: Index, diag: ?*Diagnostics) Error!i64 { return t; } +/// The commit date git orders a walk by, which it reads more narrowly +/// than it reads the committer line it shows, as git was seen to: the +/// line straight after the parents must be an `author` line and the next +/// a `committer` line, and the date is the number after that line's last +/// `>`, read as `strtoul` reads one — blank space, a sign, digits, a +/// negative number wrapping round — or 0 when any of that is missing. +/// Dates past the largest signed 64-bit value are taken as that value. fn commitTime(c: Commit) i64 { - const ident = c.committer() orelse return 0; - const d = ident.date() orelse return 0; - return d.seconds; + const after_parents = @intFromPtr(c.parent_lines.ptr) + c.parent_lines.len - @intFromPtr(c.contents.ptr); + var rest = c.contents[after_parents..]; + if (!std.mem.startsWith(u8, rest, "author ")) return 0; + rest = rest[(std.mem.findScalar(u8, rest, '\n') orelse return 0) + 1 ..]; + if (!std.mem.startsWith(u8, rest, "committer ")) return 0; + const line = rest[0 .. std.mem.findScalar(u8, rest, '\n') orelse rest.len]; + const gt = std.mem.findScalarLast(u8, line, '>') orelse return 0; + var i = gt + 1; + while (i < line.len and (line[i] == ' ' or (line[i] >= '\t' and line[i] <= '\r'))) i += 1; + var negative = false; + if (i < line.len and (line[i] == '+' or line[i] == '-')) { + negative = line[i] == '-'; + i += 1; + } + var v: u64 = 0; + var overflow = false; + while (i < line.len and std.ascii.isDigit(line[i])) : (i += 1) { + const m = std.math.mul(u64, v, 10) catch { + overflow = true; + break; + }; + v = std.math.add(u64, m, line[i] - '0') catch { + overflow = true; + break; + }; + } + if (overflow) return std.math.maxInt(i64); + if (negative and v != 0) v = 0 -% v; + return if (v > std.math.maxInt(i64)) std.math.maxInt(i64) else @intCast(v); } fn authorTimeOf(c: Commit) i64 { diff --git a/src/Mailmap.zig b/src/Mailmap.zig index 422f652..e17fa5c 100644 --- a/src/Mailmap.zig +++ b/src/Mailmap.zig @@ -33,6 +33,10 @@ const std = @import("std"); const Allocator = std.mem.Allocator; const Io = std.Io; +const Repository = @import("Repository.zig"); +const Resolver = @import("Resolver.zig"); +const Diagnostics = @import("Diagnostics.zig"); + const Mailmap = @This(); arena: std.heap.ArenaAllocator, @@ -68,6 +72,88 @@ pub fn isEmpty(m: *const Mailmap) bool { return m.entries.count() == 0; } +/// What else to read besides a repository's own sources, as `git +/// check-mailmap`'s options name them; each takes precedence over what is +/// read before it. +pub const Extra = struct { + /// `--mailmap-blob`. + blob: ?[]const u8 = null, + /// `--mailmap-file`, relative to the directory git works from. + file: ?[]const u8 = null, + /// `$HOME`, for a `mailmap.file` beginning with `~`. + home: ?[]const u8 = null, +}; + +/// Something about a source git says on standard error and goes on past. +pub const Warning = union(enum) { + /// The work tree's `.mailmap` is a symbolic link, which git does not + /// follow: "unable to open mailmap at .mailmap: Too many levels of + /// symbolic links". + symbolic_link, +}; + +/// Reads `repo`'s mailmap sources, in the order git reads them, each +/// taking precedence over the ones before: `.mailmap` at the top of the +/// work tree, never through a symbolic link; `mailmap.blob`, or +/// `HEAD:.mailmap` in a bare repository, resolved by `resolver`; +/// `mailmap.file`, relative to the top of the work tree; and then +/// `extra`'s blob and file. A source that is not there, or a blob +/// revision that names no blob, is passed over without a word, as git +/// passes it over. +pub fn addRepository(m: *Mailmap, io: Io, repo: *Repository, resolver: *Resolver, extra: Extra, warnings: ?*std.ArrayList(Warning)) !void { + const gpa = m.arena.child_allocator; + if (repo.location.work_tree) |top| { + const path = try std.fs.path.join(gpa, &.{ top, ".mailmap" }); + defer gpa.free(path); + try m.addFile(io, repo.work_dir, path, warnings); + } + const default_blob: ?[]const u8 = if (repo.location.work_tree == null) "HEAD:.mailmap" else null; + const blob = (repo.config.getString("mailmap.blob") catch null) orelse default_blob; + if (blob) |b| try m.addBlob(io, repo, resolver, b); + if (repo.config.getPath(gpa, "mailmap.file", .{ .home = extra.home }) catch null) |p| { + defer gpa.free(p.path); + try m.addRelative(io, repo, p.path, warnings); + } + if (extra.blob) |b| try m.addBlob(io, repo, resolver, b); + if (extra.file) |f| try m.addRelative(io, repo, f, warnings); +} + +fn addRelative(m: *Mailmap, io: Io, repo: *Repository, path: []const u8, warnings: ?*std.ArrayList(Warning)) !void { + const gpa = m.arena.child_allocator; + const full = if (std.fs.path.isAbsolute(path) or repo.location.work_tree == null) + try gpa.dupe(u8, path) + else + try std.fs.path.join(gpa, &.{ repo.location.work_tree.?, path }); + defer gpa.free(full); + _ = warnings; + const contents = repo.work_dir.readFileAlloc(io, full, gpa, .limited(64 << 20)) catch return; + defer gpa.free(contents); + try m.add(contents); +} + +fn addFile(m: *Mailmap, io: Io, dir: Io.Dir, path: []const u8, warnings: ?*std.ArrayList(Warning)) !void { + const gpa = m.arena.child_allocator; + const st = dir.statFile(io, path, .{ .follow_symlinks = false }) catch return; + if (st.kind == .sym_link) { + if (warnings) |w| try w.append(gpa, .symbolic_link); + return; + } + const contents = dir.readFileAlloc(io, path, gpa, .limited(64 << 20)) catch return; + defer gpa.free(contents); + try m.add(contents); +} + +fn addBlob(m: *Mailmap, io: Io, repo: *Repository, resolver: *Resolver, revision: []const u8) !void { + const gpa = m.arena.child_allocator; + var diag: Diagnostics = .{}; + const found = resolver.resolve(revision, &diag) catch return; + resolver.clearMessages(); + var obj = repo.database.database().read(io, gpa, found.id, &diag) catch return; + defer obj.deinit(gpa); + if (obj.kind != .blob) return; + try m.add(obj.data); +} + /// One line of a mailmap, read. pub const Line = struct { /// The name to show, if any. diff --git a/src/RevWalk.zig b/src/RevWalk.zig index 1a91383..6816167 100644 --- a/src/RevWalk.zig +++ b/src/RevWalk.zig @@ -222,6 +222,18 @@ pub const Options = struct { children: bool = false, /// Path limiting and history simplification; null for neither. simplify: ?Simplify = null, + /// Whether to list each commit that the rest would list, as + /// `--grep`, `--author` and `--committer` decide; after every other + /// filter, and before `--skip` and `--max-count` count it. + filter: ?Filter = null, +}; + +/// A question asked of each commit about to be listed. +pub const Filter = struct { + context: *anyopaque, + /// Whether to list `commit`. On `FilterFailed` the filter keeps what + /// went wrong itself. + keep: *const fn (context: *anyopaque, commit: Index) error{FilterFailed}!bool, }; /// How a walk limited to paths is simplified, as git-rev-list(1)'s @@ -319,7 +331,7 @@ pub const Entry = struct { /// a walk without exclusions or an ordering, where git rewrites some /// parents in ways not matched and, with `--first-parent`, stops walking /// part-way. -pub const Error = Commits.Error || TreeDiff.Error || error{ UnsupportedGraphOrdering, UnsupportedParentRewrite }; +pub const Error = Commits.Error || TreeDiff.Error || error{ UnsupportedGraphOrdering, UnsupportedParentRewrite, FilterFailed }; const Queued = struct { time: i64, sequence: u64, commit: Index }; @@ -1048,7 +1060,7 @@ fn isLimited(w: *const RevWalk) bool { } /// Whether a commit that came out of the walk is listed. -fn keep(w: *RevWalk, c: Index) bool { +fn keep(w: *RevWalk, c: Index) error{FilterFailed}!bool { if (!w.shownBySimplification(c)) return false; const o = w.options; // With paths, the parents counted are those simplification left. @@ -1060,6 +1072,7 @@ fn keep(w: *RevWalk, c: Index) bool { if (o.since_filter) |s| if (t < s) return false; if (o.left_only and w.flag(c) & left_flag == 0) return false; if (o.right_only and w.flag(c) & left_flag != 0) return false; + if (o.filter) |f| return f.keep(f.context, c); return true; } @@ -1307,7 +1320,7 @@ fn listAll(w: *RevWalk, diag: ?*Diagnostics) Error!void { }; list.shrinkRetainingCapacity(kept); for (list.items) |c| { - if (!w.keep(c)) continue; + if (!try w.keep(c)) continue; switch (w.admit()) { .skip => continue, .stop => break, @@ -1335,7 +1348,7 @@ fn nextStreamed(w: *RevWalk, diag: ?*Diagnostics) Error!?Entry { return null; }; try w.process(c, diag); - if (!w.keep(c)) continue; + if (!try w.keep(c)) continue; // Skipped commits' parents are rewritten too, as git rewrites // them before it counts. if (w.rewriting()) try w.rewriteParents(c, diag); diff --git a/src/fuzz/pretty-formats b/src/fuzz/pretty-formats new file mode 100644 index 0000000..c975331 --- /dev/null +++ b/src/fuzz/pretty-formats @@ -0,0 +1 @@ +tformat:%C(auto)%h%Creset %<(30,trunc)%s %C(blue)%an%Creset %ar%n%w(72,4,8)%b%-(trailers:only,unfold)%+ad%x00 \ No newline at end of file diff --git a/src/grep.zig b/src/grep.zig new file mode 100644 index 0000000..f693b24 --- /dev/null +++ b/src/grep.zig @@ -0,0 +1,245 @@ +// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie +// SPDX-License-Identifier: MIT + +//! Choosing commits by their messages and identities, as `git log`'s +//! `--grep`, `--author` and `--committer` do, with `--all-match`, +//! `--invert-grep`, `-i` and the pattern dialects `--basic-regexp`, `-E` +//! and `-F`. +//! +//! git-log(1) says what each option is for; how they combine was found by +//! asking `git log`: +//! +//! - **Messages** are matched a line at a time, and the blank line +//! between a commit's headers and its message is one of the lines, so +//! that `^$` matches every commit. Several `--grep` patterns match a +//! commit when any does, or with `--all-match` when every one does. +//! - **Identities** are matched against the `author` or `committer` line's +//! name and email address, `Name `, without its date, after the +//! mailmap has mapped them when one is given. Several `--author` +//! patterns match when any does, and so do several `--committer` +//! patterns; `--all-match` changes neither. +//! - A commit is kept when its author, committer and message each match +//! whatever patterns there are for them. `--invert-grep` keeps instead +//! those whose message no `--grep` pattern matches, whatever +//! `--all-match` says, and leaves the identity patterns as they are. +//! - Patterns are glibc's basic or extended regular expressions with +//! GNU's escapes (`regex.zig`), or fixed strings, matched without regard +//! to the case of ASCII letters with `-i`. Perl's (`-P`) are refused +//! (`UnsupportedPatternType`). + +const std = @import("std"); +const Allocator = std.mem.Allocator; + +const regex = @import("regex.zig"); +const Commit = @import("commit.zig").Commit; +const Identity = @import("Identity.zig"); +const Mailmap = @import("Mailmap.zig"); +const object = @import("object.zig"); + +/// How patterns are read: `grep.patternType`, `--basic-regexp`, +/// `--extended-regexp`, `--fixed-strings` and `--perl-regexp`. +pub const PatternType = enum { basic, extended, fixed, perl }; + +/// The patterns and how they combine. +pub const Options = struct { + pattern_type: PatternType = .basic, + /// `-i`. + ignore_case: bool = false, + /// `--all-match`. + all_match: bool = false, + /// `--invert-grep`. + invert: bool = false, + /// `--grep`. + messages: []const []const u8 = &.{}, + /// `--author`. + authors: []const []const u8 = &.{}, + /// `--committer`. + committers: []const []const u8 = &.{}, +}; + +/// What compiling the patterns can fail with: a malformed pattern, which +/// `Failure` names; one using what `regex.zig` does not do; and Perl's +/// patterns. +pub const Error = error{ InvalidPattern, Unsupported, UnsupportedPatternType } || Allocator.Error; + +/// Which pattern failed to compile, and why. +pub const Failure = struct { + pattern: []const u8 = "", + /// Whether it was an identity's rather than a message's, which git + /// names as `header` rather than `command line`. + header: bool = false, + regex: regex.Failure = .{}, +}; + +const Pattern = union(enum) { + regex: regex.Regex, + fixed: []const u8, +}; + +/// Compiled patterns. +pub const Grep = struct { + arena: std.heap.ArenaAllocator, + options: Options, + messages: []Pattern, + authors: []Pattern, + committers: []Pattern, + + /// Compiles the patterns `options` gives. + pub fn init(gpa: Allocator, options: Options, failure: ?*Failure) Error!Grep { + if (options.pattern_type == .perl) return error.UnsupportedPatternType; + var arena: std.heap.ArenaAllocator = .init(gpa); + errdefer arena.deinit(); + const a = arena.allocator(); + var g: Grep = .{ .arena = undefined, .options = options, .messages = &.{}, .authors = &.{}, .committers = &.{} }; + // git compiles the header patterns first. + g.authors = try compileAll(gpa, a, options, options.authors, true, failure); + errdefer deinitAll(g.authors); + g.committers = try compileAll(gpa, a, options, options.committers, true, failure); + errdefer deinitAll(g.committers); + g.messages = try compileAll(gpa, a, options, options.messages, false, failure); + g.arena = arena; + return g; + } + + /// Frees the patterns. + pub fn deinit(g: *Grep) void { + deinitAll(g.messages); + deinitAll(g.authors); + deinitAll(g.committers); + g.arena.deinit(); + g.* = undefined; + } + + /// Whether there are any patterns at all. + pub fn any(g: *const Grep) bool { + return g.messages.len != 0 or g.authors.len != 0 or g.committers.len != 0; + } + + /// Whether `contents`, a commit's, is kept; identities are mapped + /// through `mailmap` first when it is given. + pub fn matches(g: *const Grep, gpa: Allocator, format: object.Format, contents: []const u8, mailmap: ?*const Mailmap) Allocator.Error!bool { + const commit = Commit.parse(format, contents) catch return false; + if (g.authors.len != 0) { + if (!try g.identityMatches(gpa, g.authors, commit.author(), headerLine(commit.headers, "author"), mailmap)) return false; + } + if (g.committers.len != 0) { + if (!try g.identityMatches(gpa, g.committers, commit.committer(), headerLine(commit.headers, "committer"), mailmap)) return false; + } + if (g.messages.len == 0) return true; + if (g.options.invert) { + for (g.messages) |*p| if (try g.messageMatches(gpa, p, commit.message)) return false; + return true; + } + if (g.options.all_match) { + for (g.messages) |*p| if (!try g.messageMatches(gpa, p, commit.message)) return false; + return true; + } + for (g.messages) |*p| if (try g.messageMatches(gpa, p, commit.message)) return true; + return false; + } + + fn identityMatches(g: *const Grep, gpa: Allocator, patterns: []Pattern, id: ?Identity, raw: ?[]const u8, mailmap: ?*const Mailmap) Allocator.Error!bool { + var buffer: std.ArrayList(u8) = .empty; + defer buffer.deinit(gpa); + const text: []const u8 = if (id) |i| text: { + const m: Mailmap.Mapped = if (mailmap) |mm| mm.map(i.name, i.email) else .{ .name = i.name, .email = i.email }; + try buffer.print(gpa, "{s} <{s}>", .{ m.name, m.email }); + break :text buffer.items; + } else raw orelse return false; + for (patterns) |*p| if (try g.lineMatches(gpa, p, text)) return true; + return false; + } + + fn messageMatches(g: *const Grep, gpa: Allocator, p: *const Pattern, message: []const u8) Allocator.Error!bool { + // The blank line before the message is one of the lines. + if (try g.lineMatches(gpa, p, "")) return true; + var lines = std.mem.splitScalar(u8, message, '\n'); + while (lines.next()) |line| if (try g.lineMatches(gpa, p, line)) return true; + return false; + } + + fn lineMatches(g: *const Grep, gpa: Allocator, p: *const Pattern, line: []const u8) Allocator.Error!bool { + switch (p.*) { + .regex => |*r| return r.matches(gpa, line), + .fixed => |f| { + if (!g.options.ignore_case) return std.mem.find(u8, line, f) != null; + return std.ascii.findIgnoreCase(line, f) != null; + }, + } + } +}; + +/// The text of the first header `name`, for an identity line git cannot +/// read. +fn headerLine(headers: []const u8, name: []const u8) ?[]const u8 { + var lines = std.mem.splitScalar(u8, headers, '\n'); + while (lines.next()) |line| { + if (line.len > name.len and std.mem.startsWith(u8, line, name) and line[name.len] == ' ') return line[name.len + 1 ..]; + } + return null; +} + +fn compileAll(gpa: Allocator, a: Allocator, options: Options, texts: []const []const u8, header: bool, failure: ?*Failure) Error![]Pattern { + const out = try a.alloc(Pattern, texts.len); + var done: usize = 0; + errdefer deinitAll(out[0..done]); + for (texts) |text| { + if (options.pattern_type == .fixed) { + out[done] = .{ .fixed = text }; + } else { + var f: regex.Failure = .{}; + const r = regex.Regex.compileWith(gpa, text, .{ + .syntax = if (options.pattern_type == .extended) .extended else .basic, + .ignore_case = options.ignore_case, + .newline = true, + .gnu = true, + }, &f) catch |err| { + if (failure) |fl| fl.* = .{ .pattern = text, .header = header, .regex = f }; + return err; + }; + out[done] = .{ .regex = r }; + } + done += 1; + } + return out; +} + +fn deinitAll(patterns: []Pattern) void { + for (patterns) |*p| switch (p.*) { + .regex => |*r| r.deinit(), + .fixed => {}, + }; +} + +const testing = std.testing; + +test "patterns combine as git log's do" { + const gpa = testing.allocator; + const commit = "tree 4b825dc642cb6eb9a060e54bf8d69288fbee4904\nauthor Alice Smith 1700000000 +0100\ncommitter Carol 1700000500 -0230\n\nfirst line\nsecond Line\n\nbody\n"; + const Case = struct { Options, bool }; + const cases = [_]Case{ + .{ .{ .authors = &.{"alice"} }, true }, + .{ .{ .authors = &.{"ALICE"} }, false }, + .{ .{ .authors = &.{"ALICE"}, .ignore_case = true }, true }, + .{ .{ .authors = &.{"1700000000"} }, false }, + .{ .{ .authors = &.{"x>$"} }, true }, + .{ .{ .committers = &.{"^Carol $"} }, true }, + .{ .{ .messages = &.{"^second"} }, true }, + .{ .{ .messages = &.{"line.second"} }, false }, + .{ .{ .messages = &.{"^$"} }, true }, + .{ .{ .messages = &.{ "body", "nothing" }, .all_match = true }, false }, + .{ .{ .messages = &.{ "body", "nothing" } }, true }, + .{ .{ .messages = &.{"body"}, .invert = true }, false }, + .{ .{ .messages = &.{ "body", "nothing" }, .invert = true, .all_match = true }, false }, + .{ .{ .messages = &.{"a|b"} }, false }, + .{ .{ .messages = &.{"e|b"}, .pattern_type = .extended }, true }, + .{ .{ .messages = &.{"Line$"}, .pattern_type = .fixed }, false }, + .{ .{ .messages = &.{"LINE"}, .pattern_type = .fixed, .ignore_case = true }, true }, + .{ .{ .messages = &.{"body"}, .authors = &.{"Bob"} }, false }, + }; + for (cases) |case| { + var g = try Grep.init(gpa, case[0], null); + defer g.deinit(); + try testing.expectEqual(case[1], try g.matches(gpa, .sha1, commit, null)); + } +} diff --git a/src/pretty.zig b/src/pretty.zig new file mode 100644 index 0000000..c9cbe53 --- /dev/null +++ b/src/pretty.zig @@ -0,0 +1,1975 @@ +// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie +// SPDX-License-Identifier: MIT + +//! Describing commits as `git log --pretty` does: the built-in formats +//! (`oneline`, `short`, `medium`, `full`, `fuller`, `reference`, `email`, +//! `mboxrd`, `raw`) and `format:`, `tformat:` and bare `%` strings, read +//! with no I/O (`parse`) and written to an `Io.Writer` (`write`), as +//! git-log(1)'s "PRETTY FORMATS" describes them and as git was seen to +//! write them where it does not say. +//! +//! **Placeholders.** Each one git-log(1) lists is here except those that +//! need what this library does not have yet — decorations (`%d`, `%D`, +//! `%(decorate)`, `%S`), `%(describe)`, notes (`%N`), signatures (`%G?` +//! and the rest) and reflogs (`%g*`) — which `parse` refuses by name +//! (`UnsupportedPlaceholder`). A placeholder git does not know is written +//! as it is, `%` and all; after a `+`, `-` or space it is written without +//! the `%` and that character. +//! +//! **The message**: `%s` is the first paragraph after any blank lines, its +//! lines with the blank space at their ends removed and joined with +//! spaces; `%b` everything after it and the blank lines that follow it, as +//! it is; `%B` the whole message as it is; and `%f` the subject with each +//! run of other ASCII characters made one `-`, runs of `.` made one, bytes +//! past ASCII left out, and no `-` or `.` at its end or `-` at its start. +//! +//! **Identities**: an identity line git cannot read shows nothing for +//! `%an`, `%ae`, `%ad`, `%at`, `%aD`, `%ar` and `%ai`, and is written as it +//! is for the others; one without a readable date does the same for the +//! date placeholders. `%aN`, `%aE` and `%aL` are mapped through the +//! mailmap, and so are the built-in formats' identities with +//! `--use-mailmap`. +//! +//! **Padding** (`%<(N)`, `%>(N)`, `%><(N)`, `%>>(N)` and their `|` +//! forms): the next placeholder that writes anything — not text, `%%` or a +//! color — is padded with spaces to `N` columns, or to column `N` (from +//! the terminal's right edge when negative), and truncated with `..` at +//! its end, start or middle when asked; columns are counted as `width` +//! counts them, color escapes taking none. +//! +//! **Wrapping** (`%w(width,indent1,indent2)`) applies to what is written +//! from it to the next `%w` or the end, as a unit: the first line is +//! indented `indent1` spaces and every other `indent2`, and a line is +//! broken at the last blank before a word that would pass `width` +//! columns; a line feed before a letter or digit joins its lines with a +//! space, two make a paragraph, and one before anything else is kept, the +//! blank after it dropped. Tabs move to the next multiple of eight, +//! counting the indentation, and other control characters count as one +//! column fewer, as git's own reckoning has them. +//! +//! **Color**: `%C()`, `%Cred`, `%Cgreen`, `%Cblue` and `%Creset` +//! write escape sequences when color is on, `%C(always,)` whether +//! or not, and `%C(auto)` turns on the default coloring of `%H` and `%h` +//! until the next color, after writing a reset if anything has been +//! written. A spec is read only when it is written, and one git refuses +//! is an error then (`InvalidColor`). +//! +//! **`email`** writes a name or subject past ASCII as RFC 2047 encoded +//! words, folded at 76 columns, quotes a name holding RFC 5322's +//! specials, folds an ASCII subject at 78 columns, and adds MIME headers +//! when the subject or body is past ASCII; `git rev-list` encodes nothing. +//! +//! **Encodings**: messages are taken to be UTF-8; a commit whose +//! `encoding` header names any other is refused (`UnsupportedEncoding`), +//! as re-encoding is not done. + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const Writer = std.Io.Writer; + +const object = @import("object.zig"); +const Id = object.Id; +const Commit = @import("commit.zig").Commit; +const Identity = @import("Identity.zig"); +const date = @import("date.zig"); +const Mailmap = @import("Mailmap.zig"); +const trailers = @import("trailers.zig"); +const width = @import("width.zig"); +const Diagnostics = @import("Diagnostics.zig"); + +/// The built-in formats. +pub const Builtin = enum { + oneline, + short, + medium, + full, + fuller, + reference, + email, + mboxrd, + raw, + + /// Whether the format indents the message by four spaces, expanding + /// tabs by default. + fn indented(b: Builtin) bool { + return switch (b) { + .medium, .full, .fuller => true, + else => false, + }; + } +}; + +/// A format: one of the built-in ones, or a format string. +pub const Format = union(enum) { + builtin: Builtin, + user: User, + + /// Frees a format string's parts. + pub fn deinit(f: *Format) void { + switch (f.*) { + .builtin => {}, + .user => |*u| u.arena.deinit(), + } + f.* = undefined; + } + + /// Whether every commit's output ends with a line feed (`tformat:`, or + /// a bare `%` string), rather than one separating commits (`format:`). + pub fn terminated(f: *const Format) bool { + return switch (f.*) { + .builtin => true, + .user => |u| u.terminated, + }; + } +}; + +/// A format string, read. +pub const User = struct { + arena: std.heap.ArenaAllocator, + items: []const Item, + /// `tformat:` rather than `format:`. + terminated: bool, + /// Whether it writes `%P` or `%p`, which needs a commit's parents + /// rewritten in a history limited to paths. + uses_parents: bool = false, + /// Whether it writes anything of the message or the identities, which + /// git would write in its output encoding. + reads_text: bool = false, +}; + +/// One piece of a format string. +pub const Item = struct { + kind: Kind, + magic: Magic = .none, + /// The text it was read from: the whole placeholder, `%` included, or + /// the literal text. + text: []const u8, +}; + +/// What `+`, `-` or a space after the `%` asks of a placeholder. +pub const Magic = enum { + none, + /// A line feed before it, if it writes anything. + plus, + /// The line feeds before it removed, if it writes nothing. + minus, + /// A space before it, if it writes anything. + space, +}; + +/// What a piece of a format string is. +pub const Kind = union(enum) { + /// Text written as it is. + literal, + /// `%%`. + percent, + /// `%n`. + newline, + /// `%xNN`. + byte: u8, + color: Color, + padding: Padding, + wrap: Wrap, + field: Field, + person: Person, + trailers: trailers.Options, + /// A placeholder git does not know, written as it is. + unknown, +}; + +/// A color placeholder. +pub const Color = union(enum) { + /// `%C(auto)`. + auto, + /// A color spec, as git-config(1)'s "color" type reads one. + spec: struct { + text: []const u8, + /// `%C(always,...)`: written even when color is off. + always: bool = false, + }, +}; + +/// `%<(N)` and its relatives. +pub const Padding = struct { + align_to: enum { left, right, center }, + /// `%>>(N)`: take spaces from the left when the text is too wide — + /// at most as many as were written just before the placeholder. + steal: bool = false, + /// The `|` forms: `columns` is a column, from the right edge when + /// negative, rather than a width. + column: bool = false, + columns: i64, + truncate: enum { none, end, start, middle } = .none, +}; + +/// `%w(...)`. +pub const Wrap = struct { + width: i64 = 0, + indent1: i64 = 0, + indent2: i64 = 0, +}; + +/// A placeholder for something about the commit. +pub const Field = enum { + commit, + commit_abbrev, + tree, + tree_abbrev, + parents, + parents_abbrev, + subject, + sanitized_subject, + body, + raw_body, + encoding, + mark, +}; + +/// `%a` or `%c`. +pub const Person = struct { + committer: bool, + /// The letter after `a` or `c`. + what: u8, +}; + +/// What `parse` can fail with: a name that is neither a built-in format +/// nor a format string, and placeholders this library does not support, +/// which the diagnostics name. +pub const ParseError = error{ UnknownFormat, UnsupportedPlaceholder } || Allocator.Error; + +const builtin_names = [_]struct { []const u8, Builtin }{ + .{ "oneline", .oneline }, .{ "short", .short }, .{ "medium", .medium }, + .{ "full", .full }, .{ "fuller", .fuller }, .{ "reference", .reference }, + .{ "email", .email }, .{ "mboxrd", .mboxrd }, .{ "raw", .raw }, +}; + +/// The built-in format `name` names, if any. +pub fn builtinNamed(name: []const u8) ?Builtin { + for (builtin_names) |b| if (std.mem.eql(u8, b[0], name)) return b[1]; + return null; +} + +/// Looks up `pretty.` aliases, for `resolve`. +pub const Aliases = struct { + context: *const anyopaque, + get: *const fn (context: *const anyopaque, name: []const u8) ?[]const u8, +}; + +/// What `--pretty=` means once `pretty.` aliases are followed: +/// the text of a built-in name, `format:`/`tformat:` string or bare `%` +/// string. An alias naming itself, directly or not, is the format git +/// refuses as unknown. +pub fn resolve(text: []const u8, aliases: ?Aliases) []const u8 { + var current = text; + var depth: usize = 0; + while (depth < 64) : (depth += 1) { + if (builtinNamed(current) != null) return current; + if (std.mem.startsWith(u8, current, "format:") or std.mem.startsWith(u8, current, "tformat:")) return current; + if (std.mem.findScalar(u8, current, '%') != null) return current; + const a = aliases orelse return current; + current = a.get(a.context, current) orelse return current; + } + return current; +} + +/// Reads `--pretty=` (or `--format=`), aliases already +/// followed. +pub fn parse(gpa: Allocator, text: []const u8, diag: ?*Diagnostics) ParseError!Format { + if (builtinNamed(text)) |b| return .{ .builtin = b }; + if (std.mem.startsWith(u8, text, "format:")) return .{ .user = try parseUser(gpa, text["format:".len..], false, diag) }; + if (std.mem.startsWith(u8, text, "tformat:")) return .{ .user = try parseUser(gpa, text["tformat:".len..], true, diag) }; + if (std.mem.findScalar(u8, text, '%') != null or text.len == 0) return .{ .user = try parseUser(gpa, text, true, diag) }; + if (diag) |d| d.setDetail("invalid --pretty format: {s}", .{text}); + return error.UnknownFormat; +} + +/// Reads a format string. +pub fn parseUser(gpa: Allocator, text: []const u8, terminated: bool, diag: ?*Diagnostics) ParseError!User { + var arena: std.heap.ArenaAllocator = .init(gpa); + errdefer arena.deinit(); + const a = arena.allocator(); + var items: std.ArrayList(Item) = .empty; + var uses_parents = false; + var reads_text = false; + var i: usize = 0; + var literal_start: usize = 0; + while (i < text.len) { + if (text[i] != '%') { + i += 1; + continue; + } + if (i > literal_start) try items.append(a, .{ .kind = .literal, .text = text[literal_start..i] }); + const start = i; + i += 1; + var magic: Magic = .none; + if (i < text.len) switch (text[i]) { + '+' => magic = .plus, + '-' => magic = .minus, + ' ' => magic = .space, + else => {}, + }; + if (magic != .none) i += 1; + const rest = text[i..]; + const read = try readPlaceholder(a, rest, diag); + i += read.len; + if (read.kind == .field and (read.kind.field == .parents or read.kind.field == .parents_abbrev)) uses_parents = true; + switch (read.kind) { + .person, .trailers => reads_text = true, + .field => |f| switch (f) { + .subject, .sanitized_subject, .body, .raw_body => reads_text = true, + else => {}, + }, + else => {}, + } + try items.append(a, .{ .kind = read.kind, .magic = magic, .text = text[start..i] }); + literal_start = i; + } + if (literal_start < text.len) try items.append(a, .{ .kind = .literal, .text = text[literal_start..] }); + return .{ .arena = arena, .items = items.items, .terminated = terminated, .uses_parents = uses_parents, .reads_text = reads_text }; +} + +const Read = struct { kind: Kind, len: usize }; + +fn unsupported(diag: ?*Diagnostics, name: []const u8) ParseError { + if (diag) |d| d.setDetail("{s}", .{name}); + return error.UnsupportedPlaceholder; +} + +fn readPlaceholder(a: Allocator, rest: []const u8, diag: ?*Diagnostics) ParseError!Read { + if (rest.len == 0) return .{ .kind = .unknown, .len = 0 }; + const c = rest[0]; + switch (c) { + '%' => return .{ .kind = .percent, .len = 1 }, + 'n' => return .{ .kind = .newline, .len = 1 }, + 'H' => return .{ .kind = .{ .field = .commit }, .len = 1 }, + 'h' => return .{ .kind = .{ .field = .commit_abbrev }, .len = 1 }, + 'T' => return .{ .kind = .{ .field = .tree }, .len = 1 }, + 't' => return .{ .kind = .{ .field = .tree_abbrev }, .len = 1 }, + 'P' => return .{ .kind = .{ .field = .parents }, .len = 1 }, + 'p' => return .{ .kind = .{ .field = .parents_abbrev }, .len = 1 }, + 's' => return .{ .kind = .{ .field = .subject }, .len = 1 }, + 'f' => return .{ .kind = .{ .field = .sanitized_subject }, .len = 1 }, + 'b' => return .{ .kind = .{ .field = .body }, .len = 1 }, + 'B' => return .{ .kind = .{ .field = .raw_body }, .len = 1 }, + 'e' => return .{ .kind = .{ .field = .encoding }, .len = 1 }, + 'm' => return .{ .kind = .{ .field = .mark }, .len = 1 }, + 'd', 'D', 'S', 'N' => return unsupported(diag, rest[0..1]), + 'G' => { + if (rest.len >= 2 and std.mem.findScalar(u8, "?GSKFPT", rest[1]) != null) return unsupported(diag, rest[0..2]); + return .{ .kind = .unknown, .len = 0 }; + }, + 'g' => { + if (rest.len >= 2 and std.mem.findScalar(u8, "DdnNeEs", rest[1]) != null) return unsupported(diag, rest[0..2]); + return .{ .kind = .unknown, .len = 0 }; + }, + 'a', 'c' => { + if (rest.len >= 2 and std.mem.findScalar(u8, "nNeElLdDrtiIsh", rest[1]) != null) + return .{ .kind = .{ .person = .{ .committer = c == 'c', .what = rest[1] } }, .len = 2 }; + return .{ .kind = .unknown, .len = 0 }; + }, + 'x' => { + if (rest.len >= 3 and std.ascii.isHex(rest[1]) and std.ascii.isHex(rest[2])) + return .{ .kind = .{ .byte = std.fmt.parseInt(u8, rest[1..3], 16) catch unreachable }, .len = 3 }; + return .{ .kind = .unknown, .len = 0 }; + }, + 'C' => return readColor(rest), + 'w' => return readWrap(rest), + '<', '>' => return readPadding(rest), + '(' => { + if (std.mem.startsWith(u8, rest, "(decorate")) return unsupported(diag, "%(decorate)"); + if (std.mem.startsWith(u8, rest, "(describe")) return unsupported(diag, "%(describe)"); + if (std.mem.startsWith(u8, rest, "(trailers")) return readTrailers(a, rest); + return .{ .kind = .unknown, .len = 0 }; + }, + else => return .{ .kind = .unknown, .len = 0 }, + } +} + +fn readColor(rest: []const u8) Read { + const named = [_]struct { []const u8, []const u8 }{ + .{ "Cred", "red" }, .{ "Cgreen", "green" }, .{ "Cblue", "blue" }, .{ "Creset", "reset" }, + }; + for (named) |n| if (std.mem.startsWith(u8, rest, n[0])) return .{ .kind = .{ .color = .{ .spec = .{ .text = n[1] } } }, .len = n[0].len }; + if (rest.len < 2 or rest[1] != '(') return .{ .kind = .unknown, .len = 0 }; + const close = std.mem.findScalar(u8, rest, ')') orelse return .{ .kind = .unknown, .len = 0 }; + var spec = rest[2..close]; + const len = close + 1; + if (std.mem.eql(u8, spec, "auto")) return .{ .kind = .{ .color = .auto }, .len = len }; + var always = false; + if (std.mem.startsWith(u8, spec, "always,")) { + always = true; + spec = spec["always,".len..]; + } else if (std.mem.startsWith(u8, spec, "auto,")) { + spec = spec["auto,".len..]; + } + return .{ .kind = .{ .color = .{ .spec = .{ .text = spec, .always = always } } }, .len = len }; +} + +/// A number as `strtol` reads it: blank space, a sign, digits; and where +/// it stopped. +fn strtol(text: []const u8) ?struct { value: i64, end: usize } { + var i: usize = 0; + while (i < text.len and (text[i] == ' ' or (text[i] >= '\t' and text[i] <= '\r'))) i += 1; + var negative = false; + if (i < text.len and (text[i] == '+' or text[i] == '-')) { + negative = text[i] == '-'; + i += 1; + } + const digits = i; + var v: i64 = 0; + while (i < text.len and std.ascii.isDigit(text[i])) : (i += 1) { + v = std.math.mul(i64, v, 10) catch std.math.maxInt(i64); + v = std.math.add(i64, v, text[i] - '0') catch std.math.maxInt(i64); + } + if (i == digits) return null; + return .{ .value = if (negative) -v else v, .end = i }; +} + +fn readWrap(rest: []const u8) Read { + if (rest.len < 2 or rest[1] != '(') return .{ .kind = .unknown, .len = 0 }; + const close = std.mem.findScalar(u8, rest, ')') orelse return .{ .kind = .unknown, .len = 0 }; + const args = rest[2..close]; + var values = [3]i64{ 0, 0, 0 }; + var it = std.mem.splitScalar(u8, args, ','); + var n: usize = 0; + while (it.next()) |part| : (n += 1) { + if (n == 3) return .{ .kind = .unknown, .len = 0 }; + if (part.len == 0 and args.len == 0) break; + const v = strtol(part) orelse return .{ .kind = .unknown, .len = 0 }; + if (v.end != part.len) return .{ .kind = .unknown, .len = 0 }; + if (v.value < 0) return .{ .kind = .unknown, .len = 0 }; + values[n] = v.value; + } + return .{ .kind = .{ .wrap = .{ .width = values[0], .indent1 = values[1], .indent2 = values[2] } }, .len = close + 1 }; +} + +fn readPadding(rest: []const u8) Read { + var p: Padding = .{ .align_to = .left, .columns = 0 }; + var i: usize = 1; + if (rest[0] == '<') { + p.align_to = .left; + } else if (i < rest.len and rest[i] == '<') { + p.align_to = .center; + i += 1; + } else if (i < rest.len and rest[i] == '>') { + p.align_to = .right; + p.steal = true; + i += 1; + } else p.align_to = .right; + if (i < rest.len and rest[i] == '|') { + p.column = true; + i += 1; + } + if (i >= rest.len or rest[i] != '(') return .{ .kind = .unknown, .len = 0 }; + i += 1; + const n = strtol(rest[i..]) orelse return .{ .kind = .unknown, .len = 0 }; + i += n.end; + while (i < rest.len and rest[i] == ' ') i += 1; + if (i >= rest.len) return .{ .kind = .unknown, .len = 0 }; + if (rest[i] == ',') { + i += 1; + const modes = [_]struct { []const u8, @TypeOf(p.truncate) }{ .{ "trunc)", .end }, .{ "ltrunc)", .start }, .{ "mtrunc)", .middle } }; + for (modes) |m| { + if (std.mem.startsWith(u8, rest[i..], m[0])) { + p.truncate = m[1]; + i += m[0].len; + break; + } + } else return .{ .kind = .unknown, .len = 0 }; + } else if (rest[i] == ')') { + i += 1; + } else return .{ .kind = .unknown, .len = 0 }; + if (p.column) { + if (n.value == 0) return .{ .kind = .unknown, .len = 0 }; + } else if (n.value <= 0) return .{ .kind = .unknown, .len = 0 }; + p.columns = n.value; + return .{ .kind = .{ .padding = p }, .len = i }; +} + +/// Reads a boolean option's value as git-config(1)'s "bool" type does. +fn parseBool(text: []const u8) ?bool { + const truths = [_][]const u8{ "true", "yes", "on", "1" }; + const lies = [_][]const u8{ "false", "no", "off", "0", "" }; + for (truths) |t| if (std.ascii.eqlIgnoreCase(t, text)) return true; + for (lies) |l| if (std.ascii.eqlIgnoreCase(l, text)) return false; + const n = std.fmt.parseInt(i64, text, 10) catch return null; + return n != 0; +} + +/// Expands `%xNN`, `%n` and `%%` in an option value, as git does for +/// `separator=` and `key_value_separator=`. +fn expandLiteral(a: Allocator, text: []const u8) Allocator.Error![]const u8 { + var out: std.ArrayList(u8) = .empty; + var i: usize = 0; + while (i < text.len) { + if (text[i] == '%' and i + 1 < text.len) { + const next_char = text[i + 1]; + if (next_char == 'n') { + try out.append(a, '\n'); + i += 2; + continue; + } + if (next_char == '%') { + try out.append(a, '%'); + i += 2; + continue; + } + if (next_char == 'x' and i + 3 < text.len + 0 and i + 3 <= text.len - 0 and i + 4 <= text.len and std.ascii.isHex(text[i + 2]) and std.ascii.isHex(text[i + 3])) { + try out.append(a, std.fmt.parseInt(u8, text[i + 2 .. i + 4], 16) catch unreachable); + i += 4; + continue; + } + } + try out.append(a, text[i]); + i += 1; + } + return out.items; +} + +fn readTrailers(a: Allocator, rest: []const u8) Allocator.Error!Read { + const name = "(trailers"; + var i = name.len; + if (i < rest.len and rest[i] == ')') return .{ .kind = .{ .trailers = .{} }, .len = i + 1 }; + if (i >= rest.len or rest[i] != ':') return .{ .kind = .unknown, .len = 0 }; + i += 1; + var o: trailers.Options = .{}; + var keys: std.ArrayList([]const u8) = .empty; + while (true) { + if (i >= rest.len) return .{ .kind = .unknown, .len = 0 }; + if (rest[i] == ')') { + i += 1; + break; + } + const end = std.mem.findAnyPos(u8, rest, i, ",)") orelse return .{ .kind = .unknown, .len = 0 }; + const option = rest[i..end]; + i = end; + if (rest[i] == ',') i += 1; + const eq = std.mem.findScalar(u8, option, '='); + const key = option[0 .. eq orelse option.len]; + const value: ?[]const u8 = if (eq) |e| option[e + 1 ..] else null; + const Flag = enum { only, unfold, keyonly, valueonly }; + if (std.meta.stringToEnum(Flag, key)) |flag| { + const b = if (value) |v| parseBool(v) orelse return .{ .kind = .unknown, .len = 0 } else true; + switch (flag) { + .only => o.only = b, + .unfold => o.unfold = b, + .keyonly => o.key_only = b, + .valueonly => o.value_only = b, + } + } else if (std.mem.eql(u8, key, "key") and value != null) { + var k = value.?; + if (k.len == 0) { + try keys.append(a, "\x00"); + } else { + if (k[k.len - 1] == ':') k = k[0 .. k.len - 1]; + try keys.append(a, k); + } + o.only = true; + } else if (std.mem.eql(u8, key, "separator") and value != null) { + o.separator = try expandLiteral(a, value.?); + } else if (std.mem.eql(u8, key, "key_value_separator") and value != null) { + o.key_value_separator = try expandLiteral(a, value.?); + } else if (option.len == 0 and rest[i - 1] != ',') { + // `%(trailers:)`. + } else return .{ .kind = .unknown, .len = 0 }; + } + o.keys = keys.items; + return .{ .kind = .{ .trailers = o }, .len = i }; +} + +// -- writing ------------------------------------------------------------------ + +/// Which side of a symmetric difference, or the boundary, a commit is on, +/// as `%m` and `--left-right` show it. +pub const Mark = enum { none, left, right, boundary }; + +/// A commit to describe. +pub const Shown = struct { + id: Id, + /// The commit's contents. + contents: []const u8, + /// Its parents as the walk shows them, rewritten in a history limited + /// to paths. + parents: []const Id, + /// Its children, for `--children`. + children: []const Id = &.{}, + mark: Mark = .none, +}; + +/// Shortens object IDs, as the object database can tell how many digits +/// are needed. +pub const Abbreviator = struct { + context: *anyopaque, + shorten: *const fn (context: *anyopaque, w: *Writer, id: Id, length: usize) ShortenError!void, + /// The fewest digits, `--abbrev` or `core.abbrev`. + length: usize, +}; + +/// What shortening an object ID can fail with. +pub const ShortenError = Writer.Error || error{ShortenFailed}; + +/// How commits are described, besides the format. +pub const Settings = struct { + abbreviator: Abbreviator, + /// `--abbrev-commit`: the built-in formats' commit IDs shortened. + abbrev_commit: bool = false, + /// `--no-abbrev`: the `Merge:` line's object IDs written whole. + full_merge_ids: bool = false, + /// The `--date=` mode. + date_mode: date.Mode = .{}, + /// Whether `--date=` was given, which `reference` follows only then. + date_given: bool = false, + /// The current time, for relative and human dates. + now: i64 = 0, + /// The local zone. + zone: *const date.Zone = &date.Zone.utc, + /// The mailmap, for `%aN` and the rest. + mailmap: ?*const Mailmap = null, + /// `--use-mailmap`: the built-in formats' identities mapped too. + use_mailmap: bool = false, + /// Whether color is on. + color: bool = false, + /// The escape sequence commit IDs are colored with (`color.diff.commit`). + commit_color: []const u8 = "\x1b[33m", + /// `--expand-tabs`; null for the default, eight in the formats that + /// indent the message and none in the others. + expand_tabs: ?usize = null, + /// How trailers are read. + trailers: trailers.Settings = .{}, + /// The terminal's width, for padding to a column from its edge. + columns: usize = 80, + /// `--parents`: the parents after the commit's own ID in the built-in + /// formats' first line. + show_parents: bool = false, + /// `--children`: the children after it. + show_children: bool = false, + /// Whether the mark is written before it: `--left-right` for the + /// sides, `--boundary` for a boundary commit. + show_mark: bool = false, + /// Whether the built-in formats write their first line, the commit's + /// own ID and what goes with it; `git rev-list` writes its own. + first_line: bool = true, + /// For `git rev-list`, whose built-in formats differ: `email` begins + /// with `commit` and has no `[PATCH]`. + rev_list: bool = false, +}; + +/// What `write` can fail with. `InvalidColor` is a color spec git refuses, +/// `TimestampBeforeEpoch` a date git refuses to show, and +/// `UnsupportedEncoding` what this library does not do; the diagnostics say which, in git's words where git has +/// them. `MalformedCommit` is a commit that cannot be read at all. +pub const Error = error{ + InvalidColor, + TimestampBeforeEpoch, + DateOutOfRange, + UnsupportedConversion, + UnsupportedEncoding, + MalformedCommit, +} || ShortenError || Allocator.Error; + +/// Writes `shown` as `format` describes it: what git writes for one +/// commit, without the line feeds that separate one commit from the next +/// (see `Format.terminated`). +pub fn write(gpa: Allocator, w: *Writer, format: *const Format, shown: Shown, settings: Settings, diag: ?*Diagnostics) Error!void { + var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); + const commit = Commit.parse(shown.id.object_format, shown.contents) catch return error.MalformedCommit; + const reads_text = switch (format.*) { + .builtin => true, + .user => |u| u.reads_text, + }; + if (commit.encoding()) |e| { + if (reads_text and !isUtf8Name(e)) { + if (diag) |d| d.setDetail("a commit encoded in {s}", .{e}); + return error.UnsupportedEncoding; + } + } + var r: Renderer = .{ .gpa = gpa, .out = &out, .shown = shown, .commit = commit, .settings = settings, .diag = diag }; + switch (format.*) { + .builtin => |b| try r.builtin(b), + .user => |u| try r.user(u.items), + } + w.writeAll(out.items) catch return error.WriteFailed; +} + +/// Writes an annotated tag as `git show` writes it before the object it +/// tags: `tag `, the tagger as `format` writes a commit's author (in +/// `medium` with the date, in `fuller` as `TaggerDate:`, in `email` as +/// `From:` and `Date:`, in `oneline` not at all, and otherwise without +/// the date), a blank line and the message as it is. +pub fn writeTag(gpa: Allocator, w: *Writer, format: *const Format, contents: []const u8, object_format: object.Format, settings: Settings, diag: ?*Diagnostics) (Error || error{MalformedTag})!void { + const Tag = @import("tag.zig").Tag; + const t = Tag.parse(object_format, contents, null) catch return error.MalformedTag; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); + try out.print(gpa, "tag {s}\n", .{t.name}); + const b: ?Builtin = switch (format.*) { + .builtin => |x| x, + .user => null, + }; + if (t.tagger()) |id| if (b != Builtin.oneline) { + const m: Mailmap.Mapped = if (settings.use_mailmap and settings.mailmap != null) settings.mailmap.?.map(id.name, id.email) else .{ .name = id.name, .email = id.email }; + const d = id.date() orelse date.Date{ .seconds = 0, .zone = 0 }; + var dw: std.Io.Writer.Allocating = .init(gpa); + defer dw.deinit(); + const Line = struct { label: []const u8, date_label: ?[]const u8, mode: ?date.Mode }; + const line: Line = if (b) |x| switch (x) { + .medium => .{ .label = "Tagger: ", .date_label = "Date: ", .mode = settings.date_mode }, + .fuller => .{ .label = "Tagger: ", .date_label = "TaggerDate: ", .mode = settings.date_mode }, + .email, .mboxrd => .{ .label = "From: ", .date_label = "Date: ", .mode = .{ .style = .rfc } }, + else => .{ .label = "Tagger: ", .date_label = null, .mode = null }, + } else .{ .label = "Tagger: ", .date_label = null, .mode = null }; + try out.print(gpa, "{s}{s} <{s}>\n", .{ line.label, m.name, m.email }); + if (line.date_label) |dl| { + date.format(&dw.writer, d, line.mode.?, .{ .now = settings.now, .zone = settings.zone }, diag) catch |err| switch (err) { + error.WriteFailed => return error.OutOfMemory, + error.TimestampBeforeEpoch => { + if (diag) |dg| dg.setDetail("Timestamp before Unix epoch: {d} {d}", .{ d.seconds, d.zone }); + return error.TimestampBeforeEpoch; + }, + else => |e| return e, + }; + try out.print(gpa, "{s}{s}\n", .{ dl, dw.written() }); + } + }; + try out.append(gpa, '\n'); + try out.appendSlice(gpa, t.message); + w.writeAll(out.items) catch return error.WriteFailed; +} + +/// Writes what git writes of a commit in `format` before anything that can +/// fail: the built-in formats' first line, which git writes as soon as it +/// begins a commit and leaves written when the rest of it fails. +pub fn writeFirstLine(gpa: Allocator, w: *Writer, format: *const Format, shown: Shown, settings: Settings) Error!void { + const b = switch (format.*) { + .builtin => |x| x, + .user => return, + }; + if (!settings.first_line) return; + const commit = Commit.parse(shown.id.object_format, shown.contents) catch return error.MalformedCommit; + var out: std.ArrayList(u8) = .empty; + defer out.deinit(gpa); + var r: Renderer = .{ .gpa = gpa, .out = &out, .shown = shown, .commit = commit, .settings = settings, .diag = null }; + switch (b) { + .oneline => { + try r.firstLine(null); + try r.append(" "); + }, + .reference => {}, + .email, .mboxrd => { + try r.append("From "); + try r.shorten(r.out, shown.id, null); + try r.append(" Mon Sep 17 00:00:00 2001\n"); + }, + else => try r.firstLine("commit "), + } + w.writeAll(out.items) catch return error.WriteFailed; +} + +fn isUtf8Name(name: []const u8) bool { + return std.ascii.eqlIgnoreCase(name, "utf-8") or std.ascii.eqlIgnoreCase(name, "utf8"); +} + +const Who = enum { author, committer }; + +/// One commit's message, taken apart as the placeholders want it. +const Message = struct { + whole: []const u8, + /// The subject paragraph, as it is. + subject_lines: []const u8, + /// Everything after the subject paragraph and the blank lines after it. + body: []const u8, +}; + +fn isBlankLine(line: []const u8) bool { + for (line) |c| if (!isBlank(c)) return false; + return true; +} + +fn isBlank(c: u8) bool { + return c == ' ' or c == '\t' or c == '\n' or c == '\r'; +} + +fn trimEndBlank(text: []const u8) []const u8 { + return std.mem.trimEnd(u8, text, " \t\n\r"); +} + +/// The line starting at `at`, without its line feed, and where the next +/// begins. +fn lineAt(text: []const u8, at: usize) struct { line: []const u8, next: usize } { + const nl = std.mem.findScalarPos(u8, text, at, '\n'); + return if (nl) |n| .{ .line = text[at..n], .next = n + 1 } else .{ .line = text[at..], .next = text.len }; +} + +fn splitMessage(message: []const u8) Message { + var at: usize = 0; + while (at < message.len) { + const l = lineAt(message, at); + if (!isBlankLine(l.line)) break; + at = l.next; + } + const subject_start = at; + while (at < message.len) { + const l = lineAt(message, at); + if (isBlankLine(l.line)) break; + at = l.next; + } + const subject_end = at; + while (at < message.len) { + const l = lineAt(message, at); + if (!isBlankLine(l.line)) break; + at = l.next; + } + return .{ .whole = message, .subject_lines = message[subject_start..subject_end], .body = message[at..] }; +} + +/// Writes the subject: its lines, ends trimmed, joined with spaces. +fn writeSubject(list: *std.ArrayList(u8), gpa: Allocator, subject_lines: []const u8) Allocator.Error!void { + var at: usize = 0; + var first = true; + while (at < subject_lines.len) { + const l = lineAt(subject_lines, at); + at = l.next; + if (!first) try list.append(gpa, ' '); + first = false; + try list.appendSlice(gpa, trimEndBlank(l.line)); + } +} + +fn writeSanitized(list: *std.ArrayList(u8), gpa: Allocator, subject: []const u8) Allocator.Error!void { + const start = list.items.len; + var dash = false; + for (subject) |c| { + if (std.ascii.isAlphanumeric(c) or c == '.' or c == '_') { + if (dash and list.items.len > start) try list.append(gpa, '-'); + dash = false; + if (c == '.' and list.items.len > start and list.items[list.items.len - 1] == '.') continue; + try list.append(gpa, c); + } else if (c >= 0x80) { + continue; + } else dash = true; + } + while (list.items.len > start and list.items[list.items.len - 1] == '.') list.items.len -= 1; +} + +const Renderer = struct { + gpa: Allocator, + out: *std.ArrayList(u8), + shown: Shown, + commit: Commit, + settings: Settings, + diag: ?*Diagnostics, + /// `%C(auto)` is in effect. + auto_color: bool = false, + padding: ?Padding = null, + /// A color has been written since the padding. + after_color: bool = false, + /// How many spaces `%>>` takes back once the text it pads is written, + /// and how many it may: those written just before it. + steal: usize = 0, + spaces_before: usize = 0, + /// The colors written since the padding, padded with what follows. + pending_colors: std.ArrayList(u8) = .empty, + /// The wrapping in effect, and where the text it applies to began. + wrap: Wrap = .{}, + wrap_start: usize = 0, + /// The trailer block, read when first asked for. + block: ?trailers.Block = null, + + fn list(r: *Renderer) *std.ArrayList(u8) { + return r.out; + } + + fn bytes(r: *Renderer) []const u8 { + return r.out.items; + } + + fn append(r: *Renderer, text: []const u8) Error!void { + try r.out.appendSlice(r.gpa, text); + } + + fn appendByte(r: *Renderer, b: u8) Error!void { + try r.out.append(r.gpa, b); + } + + fn message(r: *Renderer) Message { + return splitMessage(r.commit.message); + } + + fn identity(r: *Renderer, who: Who) ?Identity { + const line = switch (who) { + .author => r.commit.author(), + .committer => r.commit.committer(), + }; + return line; + } + + /// Writes `id`, shortened to at least `length` digits unless null. + fn shorten(r: *Renderer, out: *std.ArrayList(u8), id: Id, length: ?usize) Error!void { + var aw: std.Io.Writer.Allocating = .fromArrayList(r.gpa, out); + defer out.* = aw.toArrayList(); + const n = length orelse return aw.writer.print("{f}", .{id}) catch error.OutOfMemory; + const a = r.settings.abbreviator; + a.shorten(a.context, &aw.writer, id, n) catch |err| switch (err) { + error.WriteFailed => return error.OutOfMemory, + else => |e| return e, + }; + } + + // -- format strings ------------------------------------------------- + + fn user(r: *Renderer, items: []const Item) Error!void { + defer if (r.block) |*b| b.deinit(r.gpa); + defer r.pending_colors.deinit(r.gpa); + for (items) |item| try r.one(item); + // Padding and a color at the very end: git takes the end as a + // placeholder it does not know. + if (r.after_color) try r.padNothing(); + try r.finishWrap(); + } + + /// Writes the padding still pending around nothing at all, as a + /// placeholder that writes nothing, or one git does not know, takes + /// it. + fn padNothing(r: *Renderer) Error!void { + const p = r.padding orelse return; + r.padding = null; + r.after_color = false; + var padded: std.ArrayList(u8) = .empty; + defer padded.deinit(r.gpa); + try r.pad(p, r.pending_colors.items, &padded); + r.pending_colors.clearRetainingCapacity(); + try r.append(padded.items); + } + + fn one(r: *Renderer, item: Item) Error!void { + // Padding followed by a color: git writes the color and takes what + // follows as the placeholder to pad, its `%` already read, so that + // text or a placeholder it cannot answer is padded as nothing and + // written after, without that `%`. + if (r.padding != null and r.after_color) switch (item.kind) { + .color => |c| return r.writeColor(c), + .literal => { + try r.padNothing(); + return r.append(item.text); + }, + .percent, .unknown => { + try r.padNothing(); + return r.append(item.text[1..]); + }, + .padding => return r.padNothing(), + .wrap => |wr| return r.startWrap(wr), + else => if (item.magic != .none) { + try r.padNothing(); + return r.append(item.text[1..]); + } else { + var tmp: std.ArrayList(u8) = .empty; + defer tmp.deinit(r.gpa); + if (!try r.expand(item.kind, &tmp)) { + try r.padNothing(); + return r.append(item.text[1..]); + } + r.after_color = false; + try tmp.insertSlice(r.gpa, 0, r.pending_colors.items); + r.pending_colors.clearRetainingCapacity(); + return r.place(item, tmp.items, true); + }, + }; + switch (item.kind) { + .literal => return r.append(item.text), + .padding => |p| { + // A padding placeholder takes padding still pending, as + // nothing, and is itself used up by it. + if (r.padding != null) return r.padNothing(); + r.padding = p; + r.after_color = false; + const b = r.bytes(); + var n: usize = 0; + while (n < b.len and b[b.len - 1 - n] == ' ') n += 1; + r.spaces_before = n; + return; + }, + .wrap => |wr| return r.startWrap(wr), + .color => |c| return r.writeColor(c), + .percent => { + if (item.magic == .none) return r.append("%"); + return r.place(item, "%", false); + }, + .unknown => return r.unanswered(item), + else => {}, + } + var tmp: std.ArrayList(u8) = .empty; + defer tmp.deinit(r.gpa); + const handled = try r.expand(item.kind, &tmp); + if (!handled) return r.unanswered(item); + return r.place(item, tmp.items, true); + } + + /// Writes a placeholder git does not know or cannot answer as it is — + /// after magic, without the `%` and the magic character — after any + /// padding pending, which it takes as nothing, magic and all. + fn unanswered(r: *Renderer, item: Item) Error!void { + try r.place(item, "", true); + if (item.magic == .none) return r.append(item.text); + return r.append(item.text[2..]); + } + + /// Begins a wrapped region; padding still pending is written inside + /// it, as nothing. + fn startWrap(r: *Renderer, wr: Wrap) Error!void { + if (r.padding != null) { + // git writes the placeholder it pads into a buffer of its own, + // so the wrapping it begins there begins at that buffer's start, + // which is the start of the commit's output. + try r.padNothing(); + r.wrap = wr; + r.wrap_start = 0; + return; + } + try r.rewrap(wr); + } + + fn writeColor(r: *Renderer, c: Color) Error!void { + var tmp: std.ArrayList(u8) = .empty; + defer tmp.deinit(r.gpa); + try r.colorItem(c, &tmp); + if (r.padding != null) { + // Padded along with what follows, as git writes both into the + // buffer it pads. + try r.pending_colors.appendSlice(r.gpa, tmp.items); + r.after_color = true; + return; + } + try r.append(tmp.items); + } + + /// Writes an expansion with its magic, padded if padding is pending + /// and the placeholder takes it. + fn place(r: *Renderer, item: Item, text: []const u8, takes_padding: bool) Error!void { + var padded: std.ArrayList(u8) = .empty; + defer padded.deinit(r.gpa); + var result = text; + if (takes_padding) { + if (r.padding) |p| { + r.padding = null; + try r.pad(p, text, &padded); + result = padded.items; + } + } + switch (item.magic) { + .none => {}, + .plus => if (result.len != 0) try r.appendByte('\n'), + .space => if (result.len != 0) try r.appendByte(' '), + .minus => if (result.len == 0) { + const l = r.list(); + while (l.items.len > 0 and l.items[l.items.len - 1] == '\n') l.items.len -= 1; + }, + } + if (r.steal != 0) { + var excess = r.steal; + r.steal = 0; + const l = r.list(); + while (excess > 0 and l.items.len > 0 and l.items[l.items.len - 1] == ' ') { + l.items.len -= 1; + excess -= 1; + } + } + try r.append(result); + } + + /// The column output has reached on its last line. + fn currentColumn(r: *Renderer) usize { + // git looks for the line's start in a C string, which a NUL ends. + const all = r.bytes(); + const b = all[0 .. std.mem.findScalar(u8, all, 0) orelse all.len]; + const start = if (std.mem.findScalarLast(u8, b, '\n')) |n| n + 1 else 0; + return width.of(b[start..]); + } + + fn pad(r: *Renderer, p: Padding, text: []const u8, out: *std.ArrayList(u8)) Error!void { + const target: i64 = if (p.column) col: { + const c: i64 = if (p.columns < 0) @as(i64, @intCast(r.settings.columns)) + p.columns else p.columns; + break :col c - @as(i64, @intCast(r.currentColumn())); + } else p.columns; + const have = width.of(text); + if (target <= 0) { + try out.appendSlice(r.gpa, text); + return; + } + const want: usize = @intCast(target); + if (have > want) { + if (p.truncate != .none) return truncate(r.gpa, out, text, want, p.truncate); + // `%>>`: the spaces to take from what is already written, + // once any magic has been written. + if (p.steal) r.steal = @min(have - want, r.spaces_before); + try out.appendSlice(r.gpa, text); + return; + } + const spaces = want - have; + const left: usize = switch (p.align_to) { + .left => 0, + .right => spaces, + .center => spaces / 2, + }; + try out.appendNTimes(r.gpa, ' ', left); + try out.appendSlice(r.gpa, text); + try out.appendNTimes(r.gpa, ' ', spaces - left); + } + + /// Wraps what has been written since the wrapping in effect began, as + /// that wrapping says, and begins `next`; git does nothing when they + /// are the same. git wraps the text as a C string, so a NUL in it + /// ends it, even with no wrapping in effect. + fn rewrap(r: *Renderer, next: Wrap) Error!void { + const wr = r.wrap; + if (wr.width == next.width and wr.indent1 == next.indent1 and wr.indent2 == next.indent2) return; + const l = r.list(); + if (r.wrap_start < l.items.len) { + const whole = l.items[r.wrap_start..]; + const region = try r.gpa.dupe(u8, whole[0 .. std.mem.findScalar(u8, whole, 0) orelse whole.len]); + defer r.gpa.free(region); + l.items.len = r.wrap_start; + var wrapped: std.ArrayList(u8) = .empty; + defer wrapped.deinit(r.gpa); + try wrapText(r.gpa, &wrapped, region, @intCast(@max(0, wr.width)), @intCast(@max(0, wr.indent1)), @intCast(@max(0, wr.indent2)), false); + try r.append(wrapped.items); + } + r.wrap_start = l.items.len; + r.wrap = next; + } + + /// The wrapping at the end of a commit's output. + fn finishWrap(r: *Renderer) Error!void { + try r.rewrap(.{}); + } + + fn colorItem(r: *Renderer, c: Color, out: *std.ArrayList(u8)) Error!void { + switch (c) { + .auto => { + r.auto_color = true; + if (r.settings.color and r.bytes().len != 0) try out.appendSlice(r.gpa, "\x1b[m"); + }, + .spec => |s| { + r.auto_color = false; + if (!r.settings.color and !s.always) return; + var buffer: [color_max]u8 = undefined; + const escape = parseColor(s.text, &buffer) orelse { + if (r.diag) |d| d.setDetail("invalid color value: {s}", .{s.text}); + return error.InvalidColor; + }; + try out.appendSlice(r.gpa, escape); + }, + } + } + + /// Expands a placeholder into `out`; false if git writes it as it is. + fn expand(r: *Renderer, kind: Kind, out: *std.ArrayList(u8)) Error!bool { + const gpa = r.gpa; + switch (kind) { + .newline => try out.append(gpa, '\n'), + .byte => |b| try out.append(gpa, b), + .field => |f| { + const ab = r.settings.abbreviator.length; + switch (f) { + .commit, .commit_abbrev => { + const colored = r.auto_color and r.settings.color; + if (colored) try out.appendSlice(gpa, r.settings.commit_color); + try r.shorten(out, r.shown.id, if (f == .commit) null else ab); + if (colored) try out.appendSlice(gpa, "\x1b[m"); + }, + .tree, .tree_abbrev => try r.shorten(out, r.commit.tree, if (f == .tree) null else ab), + .parents, .parents_abbrev => for (r.shown.parents, 0..) |p, i| { + if (i != 0) try out.append(gpa, ' '); + try r.shorten(out, p, if (f == .parents) null else ab); + }, + .subject => try writeSubject(out, gpa, r.message().subject_lines), + // Only the subject's first line, unlike `%s`. + .sanitized_subject => try writeSanitized(out, gpa, lineAt(r.message().subject_lines, 0).line), + .body => try out.appendSlice(gpa, r.message().body), + .raw_body => try out.appendSlice(gpa, r.commit.message), + .encoding => if (r.commit.encoding()) |e| try out.appendSlice(gpa, e), + .mark => try out.append(gpa, switch (r.shown.mark) { + .boundary => '-', + .left => '<', + else => '>', + }), + } + }, + .person => |p| return r.expandPerson(p, out), + .trailers => |o| { + if (r.block == null) r.block = try trailers.parse(gpa, r.commit.message, r.settings.trailers); + var aw: std.Io.Writer.Allocating = .fromArrayList(gpa, out); + defer out.* = aw.toArrayList(); + trailers.write(&aw.writer, r.block.?, o, r.settings.trailers) catch return error.OutOfMemory; + }, + else => unreachable, + } + return true; + } + + fn expandPerson(r: *Renderer, p: Person, out: *std.ArrayList(u8)) Error!bool { + const gpa = r.gpa; + const id = r.identity(if (p.committer) .committer else .author) orelse { + // An identity line git cannot read: some placeholders show + // nothing, and the rest are written as they are. + return std.mem.findScalar(u8, "nedtDri", p.what) != null; + }; + const mapped: Mailmap.Mapped = if (r.settings.mailmap) |m| m.map(id.name, id.email) else .{ .name = id.name, .email = id.email }; + switch (p.what) { + 'n' => try out.appendSlice(gpa, id.name), + 'N' => try out.appendSlice(gpa, mapped.name), + 'e' => try out.appendSlice(gpa, id.email), + 'E' => try out.appendSlice(gpa, mapped.email), + 'l' => try out.appendSlice(gpa, localPart(id.email)), + 'L' => try out.appendSlice(gpa, localPart(mapped.email)), + 't' => try out.appendSlice(gpa, id.timestamp), + else => { + const d = id.date() orelse return std.mem.findScalar(u8, "dDri", p.what) != null; + const mode: date.Mode = switch (p.what) { + 'd' => r.settings.date_mode, + 'D' => .{ .style = .rfc }, + 'r' => .{ .style = .relative }, + 'i' => .{ .style = .iso }, + 'I' => .{ .style = .iso_strict }, + 's' => .{ .style = .short }, + 'h' => .{ .style = .human }, + else => unreachable, + }; + try r.writeDate(out, d, mode); + }, + } + return true; + } + + fn writeDate(r: *Renderer, out: *std.ArrayList(u8), d: date.Date, mode: date.Mode) Error!void { + var aw: std.Io.Writer.Allocating = .fromArrayList(r.gpa, out); + defer out.* = aw.toArrayList(); + date.format(&aw.writer, d, mode, .{ .now = r.settings.now, .zone = r.settings.zone }, r.diag) catch |err| switch (err) { + error.WriteFailed => return error.OutOfMemory, + error.TimestampBeforeEpoch => { + if (r.diag) |diag| diag.setDetail("Timestamp before Unix epoch: {d} {d}", .{ d.seconds, d.zone }); + return error.TimestampBeforeEpoch; + }, + else => |e| return e, + }; + } + + // -- built-in formats ------------------------------------------------- + + fn builtin(r: *Renderer, b: Builtin) Error!void { + const gpa = r.gpa; + switch (b) { + .oneline => { + if (r.settings.first_line) { + try r.firstLine(null); + try r.append(" "); + } + var s: std.ArrayList(u8) = .empty; + defer s.deinit(gpa); + try writeSubject(&s, gpa, r.message().subject_lines); + try r.append(s.items); + try r.append("\n"); + }, + .reference => { + var f = parseUser(gpa, "%C(auto)%h (%s, %ad)", false, null) catch |err| switch (err) { + error.OutOfMemory => return error.OutOfMemory, + else => unreachable, + }; + defer f.arena.deinit(); + const saved = r.settings; + defer r.settings = saved; + if (!r.settings.date_given) r.settings.date_mode = .{ .style = .short }; + try r.user(f.items); + }, + .email, .mboxrd => try r.email(b == .mboxrd), + .raw => { + try r.firstLine("commit "); + // The headers as they are, less the `encoding` header git + // drops when it has written the message in its output + // encoding. + var at: usize = 0; + var dropped = false; + const h = r.commit.headers; + while (at < h.len) { + const l = lineAt(h, at); + if (!dropped and std.mem.startsWith(u8, l.line, "encoding ")) { + dropped = true; + at = l.next; + // Continuation lines go with it. + while (at < h.len and h[at] == ' ') at = lineAt(h, at).next; + continue; + } + try r.append(l.line); + try r.append("\n"); + at = l.next; + } + try r.messageLines(false, 0); + }, + .short, .medium, .full, .fuller => { + try r.firstLine("commit "); + const body_start = r.bytes().len; + defer if (r.bytes().len == body_start) r.appendByte('\n') catch {}; + try r.mergeLine(); + const tabs = r.settings.expand_tabs orelse (if (b.indented()) @as(usize, 8) else 0); + switch (b) { + .short => try r.identityLine("Author: ", .author), + .medium => { + try r.identityLine("Author: ", .author); + try r.dateLine("Date: ", .author); + }, + .full => { + try r.identityLine("Author: ", .author); + try r.identityLine("Commit: ", .committer); + }, + .fuller => { + try r.identityLine("Author: ", .author); + try r.dateLine("AuthorDate: ", .author); + try r.identityLine("Commit: ", .committer); + try r.dateLine("CommitDate: ", .committer); + }, + else => unreachable, + } + try r.messageLines(b == .short, tabs); + }, + } + } + + /// The first line's commit ID, with what `--parents`, `--children` and + /// the marks put around it, colored as git colors it; `prefix` is + /// `commit ` for the formats that have it. + fn firstLine(r: *Renderer, prefix: ?[]const u8) Error!void { + const s = r.settings; + if (!s.first_line) return; + if (s.color) try r.append(s.commit_color); + if (prefix) |p| try r.append(p); + if (s.show_mark and r.shown.mark != .none) { + try r.appendByte(switch (r.shown.mark) { + .left => '<', + .right => '>', + .boundary => '-', + .none => unreachable, + }); + try r.appendByte(' '); + } + const length: ?usize = if (s.abbrev_commit) s.abbreviator.length else null; + try r.shorten(r.out, r.shown.id, length); + if (s.show_parents) for (r.shown.parents) |p| { + try r.appendByte(' '); + try r.shorten(r.out, p, length); + }; + if (s.show_children) for (r.shown.children) |c| { + try r.appendByte(' '); + try r.shorten(r.out, c, length); + }; + if (s.color) try r.append("\x1b[m"); + if (prefix != null) try r.append("\n"); + } + + fn mergeLine(r: *Renderer) Error!void { + if (r.shown.parents.len < 2) return; + try r.append("Merge:"); + const length: ?usize = if (r.settings.full_merge_ids) null else r.settings.abbreviator.length; + for (r.shown.parents) |p| { + try r.appendByte(' '); + try r.shorten(r.out, p, length); + } + try r.append("\n"); + } + + fn shownIdentity(r: *Renderer, who: Who) ?Mailmap.Mapped { + const id = r.identity(who) orelse return null; + if (r.settings.use_mailmap) if (r.settings.mailmap) |m| return m.map(id.name, id.email); + return .{ .name = id.name, .email = id.email }; + } + + fn identityLine(r: *Renderer, label: []const u8, who: Who) Error!void { + const m = r.shownIdentity(who) orelse return; + try r.append(label); + try r.append(m.name); + try r.append(" <"); + try r.append(m.email); + try r.append(">\n"); + } + + fn dateLine(r: *Renderer, label: []const u8, who: Who) Error!void { + const id = r.identity(who) orelse return; + try r.append(label); + const d = id.date() orelse date.Date{ .seconds = 0, .zone = 0 }; + var tmp: std.ArrayList(u8) = .empty; + defer tmp.deinit(r.gpa); + try r.writeDate(&tmp, d, r.settings.date_mode); + try r.append(tmp.items); + try r.append("\n"); + } + + /// The message, indented four spaces, from its first line that is not + /// blank to its last, each line's blank space at its end removed and + /// tabs expanded to multiples of `tabs`; only the subject paragraph if + /// `subject_only`. + fn messageLines(r: *Renderer, subject_only: bool, tabs: usize) Error!void { + const m = r.commit.message; + var at: usize = 0; + while (at < m.len) { + const l = lineAt(m, at); + if (!isBlankLine(l.line)) break; + at = l.next; + } + var end = m.len; + if (subject_only) { + var e = at; + while (e < m.len) { + const l = lineAt(m, e); + if (isBlankLine(l.line)) break; + e = l.next; + } + end = e; + } + // Back from the end over blank lines. + var last_end = at; + { + var p = at; + while (p < end) { + const l = lineAt(m[0..end], p); + if (!isBlankLine(l.line)) last_end = l.next; + p = l.next; + } + } + if (last_end <= at) return; + try r.append("\n"); + var p = at; + while (p < last_end) { + const l = lineAt(m[0..last_end], p); + p = l.next; + try r.append(" "); + const line = trimEndBlank(l.line); + if (tabs == 0) { + try r.append(line); + } else { + var column: usize = 0; + var i: usize = 0; + while (i < line.len) { + if (line[i] == '\t') { + const n = tabs - column % tabs; + for (0..n) |_| try r.appendByte(' '); + column += n; + i += 1; + continue; + } + const c = width.next(line[i..]); + try r.append(line[i..][0..c.len]); + column += c.width orelse 0; + i += c.len; + } + } + try r.append("\n"); + } + } + + fn email(r: *Renderer, mboxrd: bool) Error!void { + const gpa = r.gpa; + const s = r.settings; + if (!s.first_line) { + // `git rev-list` writes `commit ` itself. + } else { + try r.append("From "); + try r.shorten(r.out, r.shown.id, null); + try r.append(" Mon Sep 17 00:00:00 2001\n"); + } + const msg = r.message(); + var subject: std.ArrayList(u8) = .empty; + defer subject.deinit(gpa); + try writeSubject(&subject, gpa, msg.subject_lines); + if (r.shownIdentity(.author)) |m| { + try r.append("From: "); + // `git rev-list` encodes nothing. + if (!isAscii(m.name) and !s.rev_list) { + try encodeWord(gpa, r.out, m.name, "From: ".len, .phrase); + } else if (needsQuotes(m.name)) { + try r.appendByte('"'); + for (m.name) |c| { + if (c == '"' or c == '\\') try r.appendByte('\\'); + try r.appendByte(c); + } + try r.appendByte('"'); + } else try r.append(m.name); + try r.append(" <"); + try r.append(m.email); + try r.append(">\n"); + { + const d = r.identity(.author).?.date() orelse date.Date{ .seconds = 0, .zone = 0 }; + try r.append("Date: "); + var tmp: std.ArrayList(u8) = .empty; + defer tmp.deinit(gpa); + try r.writeDate(&tmp, d, .{ .style = .rfc }); + try r.append(tmp.items); + try r.append("\n"); + } + } + const prefix = if (s.rev_list) "Subject: " else "Subject: [PATCH] "; + try r.append(prefix); + if (!isAscii(subject.items) and !s.rev_list) { + try encodeWord(gpa, r.out, subject.items, prefix.len, .text); + } else if (subject.items.len != 0) { + var folded: std.ArrayList(u8) = .empty; + defer folded.deinit(gpa); + try foldHeader(gpa, &folded, subject.items, prefix.len); + try r.append(folded.items); + } else { + // No space after `[PATCH]` when there is no subject. + r.list().items.len -= 1; + } + try r.append("\n"); + if (!isAscii(msg.body) or !isAscii(subject.items)) try r.append("MIME-Version: 1.0\nContent-Type: text/plain; charset=UTF-8\nContent-Transfer-Encoding: 8bit\n"); + try r.append("\n"); + // The body, from its first line that is not blank to its last, the + // blank space at each line's end removed. + const body = msg.body; + var last_end: usize = 0; + { + var p: usize = 0; + while (p < body.len) { + const l = lineAt(body, p); + if (!isBlankLine(l.line)) last_end = l.next; + p = l.next; + } + } + var p: usize = 0; + while (p < last_end) { + const l = lineAt(body[0..last_end], p); + p = l.next; + const line = trimEndBlank(l.line); + if (mboxrd) { + const after = std.mem.trimStart(u8, line, ">"); + if (std.mem.startsWith(u8, after, "From ")) try r.appendByte('>'); + } + try r.append(line); + try r.append("\n"); + } + } +}; + +fn localPart(email_address: []const u8) []const u8 { + return email_address[0 .. std.mem.findScalar(u8, email_address, '@') orelse email_address.len]; +} + +fn isAscii(text: []const u8) bool { + for (text) |c| if (c >= 0x80) return false; + return true; +} + +/// Writes `text` as RFC 2047 encoded words, `=?UTF-8?q?...?=`, as git +/// writes a header past ASCII: every byte past ASCII, blank space and +/// control character as `=XX`, and those of the others a `phrase` may not +/// hold (anything but letters, digits and `!*+-/`) or `text` may not (`=`, +/// `?` and `_`) the same; a word is closed and another begun on a line of +/// its own before a character would take the line past 76 columns, and a +/// character is never split. +fn encodeWord(gpa: Allocator, out: *std.ArrayList(u8), text: []const u8, column: usize, kind: enum { phrase, text }) Allocator.Error!void { + const start = "=?UTF-8?q?"; + try out.appendSlice(gpa, start); + var line = column + start.len; + var i: usize = 0; + while (i < text.len) { + const len: usize = if (text[i] < 0x80) 1 else len: { + const l = std.unicode.utf8ByteSequenceLength(text[i]) catch break :len 1; + if (i + l > text.len) break :len 1; + _ = std.unicode.utf8Decode(text[i..][0..l]) catch break :len 1; + break :len l; + }; + const unit = text[i..][0..len]; + const c = unit[0]; + const plain = len == 1 and c > ' ' and c < 0x7f and switch (kind) { + .phrase => std.ascii.isAlphanumeric(c) or std.mem.findScalar(u8, "!*+-/", c) != null, + .text => c != '=' and c != '?' and c != '_', + }; + const width_needed: usize = if (plain) 1 else 3 * len; + if (line + width_needed + 2 > 76) { + try out.appendSlice(gpa, "?=\n " ++ start); + line = 1 + start.len; + } + if (plain) { + try out.append(gpa, c); + } else for (unit) |b| try out.print(gpa, "={X:0>2}", .{b}); + line += width_needed; + i += len; + } + try out.appendSlice(gpa, "?="); +} + +/// Whether a name must be quoted in an email header: RFC 5322's specials. +fn needsQuotes(name: []const u8) bool { + for (name) |c| if (std.mem.findScalar(u8, "()<>@,;:\\\".[]", c) != null) return true; + return false; +} + +/// Folds a header's value at 78 columns, starting at column `column`, the +/// way git folds a subject: as `%w(78,0,1)` would, with a break allowed +/// before the first word. +fn foldHeader(gpa: Allocator, out: *std.ArrayList(u8), text: []const u8, column: usize) Allocator.Error!void { + try wrapFrom(gpa, out, text, 78, column, 0, 1, true); +} + +/// Wraps `text` as `%w(line_width,indent1,indent2)` does; `break_first` +/// allows a break before the first word, as a folded header has. +pub fn wrapText(gpa: Allocator, out: *std.ArrayList(u8), text: []const u8, line_width: usize, indent1: usize, indent2: usize, break_first: bool) Allocator.Error!void { + return wrapFrom(gpa, out, text, line_width, indent1, indent1, indent2, break_first); +} + +/// The columns a character takes when wrapping, at `column`. +fn wrapWidth(text: []const u8, column: i64) struct { len: usize, width: i64 } { + const c = text[0]; + if (width.escapeLength(text)) |l| return .{ .len = l, .width = 0 }; + if (c == '\t') return .{ .len = 1, .width = 8 - @mod(column, 8) }; + if (c == '\r') return .{ .len = 1, .width = 1 }; + const ch = width.next(text); + return .{ .len = ch.len, .width = if (ch.width) |w| w else -1 }; +} + +fn wrapFrom(gpa: Allocator, out: *std.ArrayList(u8), text: []const u8, line_width: usize, start_column: usize, indent1: usize, indent2: usize, break_first: bool) Allocator.Error!void { + if (text.len == 0) return; + if (line_width == 0) { + try out.appendNTimes(gpa, ' ', indent1); + for (text, 0..) |c, k| { + try out.append(gpa, c); + if (c == '\n' and k + 1 < text.len) try out.appendNTimes(gpa, ' ', indent2); + } + return; + } + const base = out.items.len; + const w: i64 = @intCast(line_width); + var column: i64 = @intCast(start_column); + var pending: usize = indent1; + // Where a line may be broken: the blank to replace, or the place to + // insert a line feed. + const Break = struct { at: usize, replace: bool }; + var brk: ?Break = if (break_first) .{ .at = base, .replace = false } else null; + const S = struct { + fn put(g: Allocator, o: *std.ArrayList(u8), p: *usize, b: []const u8) Allocator.Error!void { + if (p.* != 0) { + try o.appendNTimes(g, ' ', p.*); + p.* = 0; + } + try o.appendSlice(g, b); + } + fn columnsOf(t: []const u8, from: i64) i64 { + var col = from; + var k: usize = 0; + while (k < t.len) { + const ch = wrapWidth(t[k..], col); + col += ch.width; + k += ch.len; + } + return col; + } + fn finish(g: Allocator, o: *std.ArrayList(u8), col: *i64, b: *?Break, p: *usize, lw: i64, indent: usize) Allocator.Error!void { + if (col.* <= lw) return; + const k = b.* orelse return; + const tail_start = if (k.replace) k.at + 1 else k.at; + const tail = try g.dupe(u8, o.items[tail_start..]); + defer g.free(tail); + o.items.len = k.at; + try o.append(g, '\n'); + if (tail.len != 0) { + try o.appendNTimes(g, ' ', indent); + try o.appendSlice(g, tail); + } else p.* = indent; + col.* = columnsOf(tail, @intCast(indent)); + b.* = null; + } + }; + var i: usize = 0; + while (i < text.len) { + const c = text[i]; + if (c == '\n') { + try S.finish(gpa, out, &column, &brk, &pending, w, indent2); + if (i + 1 == text.len) { + try S.put(gpa, out, &pending, "\n"); + i += 1; + break; + } + const nx = text[i + 1]; + if (nx == '\n') { + try S.put(gpa, out, &pending, "\n\n"); + pending = indent2; + column = @intCast(indent2); + brk = null; + i += 2; + continue; + } + if (!std.ascii.isAlphanumeric(nx)) { + try S.put(gpa, out, &pending, "\n"); + pending = indent2; + column = @intCast(indent2); + brk = null; + i += if (nx == ' ' or nx == '\t' or nx == '\r') 2 else 1; + continue; + } + try S.put(gpa, out, &pending, " "); + column += 1; + brk = .{ .at = out.items.len, .replace = false }; + i += 1; + continue; + } + if (c == ' ' or c == '\t' or c == '\r') { + try S.finish(gpa, out, &column, &brk, &pending, w, indent2); + try S.put(gpa, out, &pending, ""); + brk = .{ .at = out.items.len, .replace = true }; + column += wrapWidth(text[i..], column).width; + try out.append(gpa, c); + i += 1; + continue; + } + const ch = wrapWidth(text[i..], column); + column += ch.width; + try S.put(gpa, out, &pending, text[i..][0..ch.len]); + i += ch.len; + } + try S.finish(gpa, out, &column, &brk, &pending, w, indent2); +} + +/// Truncates `text` to `want` columns with `..` at its end, start or +/// middle, as git does: the characters taking columns in the part cut are +/// removed and `..` written where it began, while those taking none — +/// control characters, line feeds among them — are kept, after the `..`. +fn truncate(gpa: Allocator, out: *std.ArrayList(u8), text: []const u8, want: usize, mode: anytype) Allocator.Error!void { + const total = width.of(text); + const keep = if (want >= 2) want - 2 else 0; + // The columns cut: [from, to). + const from: usize, const to: usize = switch (mode) { + .end => .{ keep, total }, + .start => .{ 0, total - keep }, + .middle => .{ keep / 2, total - (keep - keep / 2) }, + .none => unreachable, + }; + var column: usize = 0; + var i: usize = 0; + var dots = false; + while (i < text.len) { + var len: usize = 0; + var w: usize = 0; + if (width.escapeLength(text[i..])) |l| { + len = l; + } else { + const c = width.next(text[i..]); + len = c.len; + w = c.width orelse 0; + } + const cut = w != 0 and column + w > from and column < to; + if (cut and !dots) { + try out.appendSlice(gpa, ".."); + dots = true; + } + if (!cut) try out.appendSlice(gpa, text[i..][0..len]); + column += w; + i += len; + } + if (!dots) try out.appendSlice(gpa, ".."); +} + +// -- colors ------------------------------------------------------------------- + +/// The longest escape sequence a color spec can make. +pub const color_max = 96; + +/// The escape sequence for a color spec, as git-config(1)'s "color" type +/// reads one, written into `buffer`; empty for a spec of no color, and +/// null for one git refuses. +pub fn parseColor(spec: []const u8, buffer: *[color_max]u8) ?[]const u8 { + const Color3 = union(enum) { none, basic: u8, bright: u8, default, index: u8, rgb: [3]u8 }; + var fg: Color3 = .none; + var bg: Color3 = .none; + var colors: usize = 0; + var reset = false; + var attributes: u32 = 0; + var it = std.mem.tokenizeAny(u8, spec, " \t"); + const names = [_][]const u8{ "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white" }; + const attribute_names = [_]struct { []const u8, u5 }{ + .{ "bold", 1 }, .{ "dim", 2 }, .{ "italic", 3 }, .{ "ul", 4 }, .{ "blink", 5 }, .{ "reverse", 7 }, .{ "strike", 9 }, + }; + while (it.next()) |word| { + var c: ?Color3 = null; + if (std.ascii.eqlIgnoreCase(word, "normal")) { + c = .none; + } else if (std.ascii.eqlIgnoreCase(word, "default")) { + c = .default; + } else if (std.mem.eql(u8, word, "reset")) { + reset = true; + continue; + } else if (word[0] == '#') { + const hex = word[1..]; + if (hex.len == 6) { + var rgb: [3]u8 = undefined; + for (0..3) |k| rgb[k] = std.fmt.parseInt(u8, hex[k * 2 ..][0..2], 16) catch return null; + c = .{ .rgb = rgb }; + } else if (hex.len == 3) { + var rgb: [3]u8 = undefined; + for (0..3) |k| { + const v = std.fmt.parseInt(u8, hex[k..][0..1], 16) catch return null; + rgb[k] = v * 17; + } + c = .{ .rgb = rgb }; + } else return null; + } else if (std.fmt.parseInt(i32, word, 10)) |n| { + if (n < -1 or n > 255) return null; + c = if (n == -1) .none else if (n < 8) .{ .basic = @intCast(n) } else if (n < 16) .{ .bright = @intCast(n - 8) } else .{ .index = @intCast(n) }; + } else |_| { + const bright = word.len > 6 and std.ascii.eqlIgnoreCase(word[0..6], "bright"); + const base = if (bright) word[6..] else word; + for (names, 0..) |n, k| if (std.ascii.eqlIgnoreCase(n, base)) { + c = if (bright) .{ .bright = @intCast(k) } else .{ .basic = @intCast(k) }; + }; + } + if (c) |color| { + switch (colors) { + 0 => fg = color, + 1 => bg = color, + else => return null, + } + colors += 1; + continue; + } + var negate = false; + var name = word; + if (std.mem.startsWith(u8, name, "no-")) { + negate = true; + name = name[3..]; + } else if (std.mem.startsWith(u8, name, "no")) { + negate = true; + name = name[2..]; + } + for (attribute_names) |a| { + if (std.mem.eql(u8, a[0], name)) { + // Turning off bold and dim are both 22. + const code: u5 = if (negate) (if (a[1] == 1) 22 else a[1] + 20) else a[1]; + attributes |= @as(u32, 1) << code; + break; + } + } else return null; + } + var w: Writer = .fixed(buffer); + if (!reset and attributes == 0 and fg == .none and bg == .none) return ""; + w.writeAll("\x1b[") catch return null; + var first = true; + if (reset) first = false; + var code: u6 = 0; + while (code < 32) : (code += 1) { + if (attributes & (@as(u32, 1) << @intCast(code)) == 0) continue; + if (!first) w.writeByte(';') catch return null; + first = false; + w.print("{d}", .{code}) catch return null; + } + for ([_]struct { Color3, u8 }{ .{ fg, 30 }, .{ bg, 40 } }) |pair| { + const color, const offset = pair; + if (color == .none) continue; + if (!first) w.writeByte(';') catch return null; + first = false; + switch (color) { + .none => unreachable, + .basic => |k| w.print("{d}", .{offset + k}) catch return null, + .bright => |k| w.print("{d}", .{offset + 60 + k}) catch return null, + .default => w.print("{d}", .{offset + 9}) catch return null, + .index => |k| w.print("{d};5;{d}", .{ offset + 8, k }) catch return null, + .rgb => |rgb| w.print("{d};2;{d};{d};{d}", .{ offset + 8, rgb[0], rgb[1], rgb[2] }) catch return null, + } + } + w.writeByte('m') catch return null; + return w.buffered(); +} + +const testing = std.testing; +const fuzz_input = @import("testing/fuzz.zig"); + +test "color specs are read as git reads them" { + const cases = [_]struct { []const u8, ?[]const u8 }{ + .{ "red", "\x1b[31m" }, + .{ "red bold", "\x1b[1;31m" }, + .{ "#ff0000", "\x1b[38;2;255;0;0m" }, + .{ "ul blink reverse italic strike dim nobold", "\x1b[2;3;4;5;7;9;22m" }, + .{ "123", "\x1b[38;5;123m" }, + .{ "red blue", "\x1b[31;44m" }, + .{ "brightred", "\x1b[91m" }, + .{ "", "" }, + .{ " ", "" }, + .{ "normal", "" }, + .{ "normal red", "\x1b[41m" }, + .{ "default", "\x1b[39m" }, + .{ "reset", "\x1b[m" }, + .{ "reset green", "\x1b[;32m" }, + .{ "no-bold", "\x1b[22m" }, + .{ "bold ul bold", "\x1b[1;4m" }, + .{ "red green blue", null }, + .{ "#F1b", "\x1b[38;2;255;17;187m" }, + .{ "256", null }, + .{ "-1", "" }, + .{ "brightdefault", null }, + .{ "BOLD", null }, + .{ "Red", "\x1b[31m" }, + .{ "1", "\x1b[31m" }, + .{ "15", "\x1b[97m" }, + .{ "0 1", "\x1b[30;41m" }, + .{ "noitalic noul noblink noreverse nostrike", "\x1b[23;24;25;27;29m" }, + .{ "bold nobold", "\x1b[1;22m" }, + .{ "bright red", null }, + .{ "default default", "\x1b[39;49m" }, + .{ "#12", null }, + .{ "#gggggg", null }, + .{ "bold reset", "\x1b[;1m" }, + }; + for (cases) |case| { + var buffer: [color_max]u8 = undefined; + const got = parseColor(case[0], &buffer); + errdefer std.debug.print("color \"{s}\"\n", .{case[0]}); + if (case[1]) |want| { + try testing.expect(got != null); + try testing.expectEqualStrings(want, got.?); + } else try testing.expect(got == null); + } +} + +test "fuzz: format strings" { + try testing.fuzz({}, struct { + fn one(_: void, smith: *testing.Smith) anyerror!void { + var buffer: [256]u8 = undefined; + const text = fuzz_input.bytes(smith, &buffer); + var f = parse(testing.allocator, text, null) catch |err| switch (err) { + error.UnsupportedPlaceholder, error.UnknownFormat => return, + else => return err, + }; + defer f.deinit(); + switch (f) { + .builtin => {}, + .user => |u| { + var total: usize = 0; + for (u.items) |item| total += item.text.len; + // The pieces cover the text, less a `format:` prefix. + try testing.expect(total <= text.len); + }, + } + } + }.one, .{ .corpus = &.{ @embedFile("fuzz/pretty-formats"), "%h %s%n%b", "%<(20,trunc)%s|%>>(5)%h", "%w(72,4,8)%B", "%C(auto)%h%Creset %C(red bold)%s", "%(trailers:key=Signed-off-by,valueonly,separator=%x2C )", "format:%x00%+s%-b% e" } }); +} + +test "wrapping matches git's %w" { + const cases = [_]struct { []const u8, usize, usize, usize, []const u8 }{ + .{ "a b c d e f", 3, 0, 0, "a b\nc d\ne f" }, + .{ "aa bb", 5, 0, 0, "aa \nbb" }, + .{ "a \nb", 5, 0, 0, "a b" }, + .{ "a\n b", 5, 0, 0, "a\nb" }, + .{ "a\n\n\nb", 5, 0, 0, "a\n\n b" }, + .{ "a\tb c", 10, 0, 0, "a\tb\nc" }, + .{ "\tb", 5, 0, 0, "\nb" }, + .{ "a bb ccc", 4, 1, 2, " a\n bb\n ccc" }, + .{ "trail \nnext", 10, 0, 0, "trail \nnext" }, + .{ "abc def\nghi", 6, 0, 0, "abc\ndef \nghi" }, + .{ "", 10, 1, 0, "" }, + .{ " \t", 1, 0, 3, " \n" }, + .{ "\raaaaa\nccc\n", 5, 0, 1, "\n aaaaa \n ccc\n" }, + }; + for (cases) |case| { + var out: std.ArrayList(u8) = .empty; + defer out.deinit(testing.allocator); + try wrapText(testing.allocator, &out, case[0], case[1], case[2], case[3], false); + errdefer std.debug.print("wrapping \"{f}\"\n", .{std.zig.fmtString(case[0])}); + try testing.expectEqualStrings(case[4], out.items); + } +} diff --git a/src/root.zig b/src/root.zig index cf8bc55..604959d 100644 --- a/src/root.zig +++ b/src/root.zig @@ -15,7 +15,10 @@ //! layer there are revisions, read by `revision` and resolved by //! `Resolver`, with the refspecs and upstream and push branches //! (`refspec`, `tracking`) they need; walking commits (`RevWalk`, over the -//! commits `Commits` reads); and merge bases (`merge_base`). +//! commits `Commits` reads); merge bases (`merge_base`); and describing +//! commits as `git log --pretty` does (`pretty`), with their trailers +//! (`trailers`), the mailmap (`Mailmap`) and searches by message and +//! identity (`grep`). const std = @import("std"); const builtin = @import("builtin"); @@ -140,6 +143,14 @@ pub const merge_base = @import("merge_base.zig"); pub const Mailmap = @import("Mailmap.zig"); /// Trailers: the `Key: value` lines at the end of a commit message. pub const trailers = @import("trailers.zig"); +/// Describing commits: the built-in formats and format strings of `git +/// log --pretty`. +pub const pretty = @import("pretty.zig"); +/// How many columns of a terminal text takes, as git counts them. +pub const width = @import("width.zig"); +/// Choosing commits by their messages and identities: `--grep`, +/// `--author` and `--committer`. +pub const grep = @import("grep.zig"); /// Repositories made with git for tests, including those of programs /// built on this module. diff --git a/src/width.zig b/src/width.zig new file mode 100644 index 0000000..76a7c7b --- /dev/null +++ b/src/width.zig @@ -0,0 +1,195 @@ +// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie +// SPDX-License-Identifier: MIT + +//! How many columns of a terminal text takes, as git counts them for +//! `%<()` and its relatives and for `%w(...)`: UTF-8 decoded, combining +//! marks and other characters of no width counted as none, East Asian wide +//! and fullwidth characters as two, everything else as one. +//! +//! Control characters are git's own case: padding counts them as no +//! columns, and wrapping as one column fewer (`Char.width` is null for +//! them, so each caller decides). A byte that does not begin a whole UTF-8 +//! sequence counts as one column, as git counts it. +//! +//! The tables are Unicode's, and may differ from the ones a given git was +//! built with for characters added or changed recently. + +const std = @import("std"); + +/// One character: how many bytes it takes and how many columns. +pub const Char = struct { + len: u3, + /// Columns, or null for a control character. + width: ?u2, +}; + +/// The character at the start of `text`, which must not be empty. +pub fn next(text: []const u8) Char { + const b = text[0]; + if (b < 0x80) { + if (b < 0x20 or b == 0x7f) return .{ .len = 1, .width = null }; + return .{ .len = 1, .width = 1 }; + } + const len = std.unicode.utf8ByteSequenceLength(b) catch return .{ .len = 1, .width = 1 }; + if (text.len < len) return .{ .len = 1, .width = 1 }; + const cp = std.unicode.utf8Decode(text[0..len]) catch return .{ .len = 1, .width = 1 }; + if (cp < 0xa0) return .{ .len = len, .width = null }; + return .{ .len = len, .width = codepointWidth(cp) }; +} + +/// The columns `text` takes, control characters counting as none: the +/// width padding measures. +pub fn of(text: []const u8) usize { + var n: usize = 0; + var i: usize = 0; + while (i < text.len) { + // Escape sequences a color placeholder wrote take no columns. + if (text[i] == 0x1b) { + if (escapeLength(text[i..])) |l| { + i += l; + continue; + } + } + const c = next(text[i..]); + n += c.width orelse 0; + i += c.len; + } + return n; +} + +/// The length of the color escape sequence `text` begins with, if it +/// begins with one. +pub fn escapeLength(text: []const u8) ?usize { + if (text.len < 2 or text[0] != 0x1b or text[1] != '[') return null; + var i: usize = 2; + while (i < text.len and (std.ascii.isDigit(text[i]) or text[i] == ';')) i += 1; + if (i < text.len and text[i] == 'm') return i + 1; + return null; +} + +const Range = struct { u21, u21 }; + +const zero_width = [_]Range{ + .{ 0x00ad, 0x00ad }, .{ 0x0300, 0x036f }, .{ 0x0483, 0x0489 }, .{ 0x0591, 0x05bd }, + .{ 0x05bf, 0x05bf }, .{ 0x05c1, 0x05c2 }, .{ 0x05c4, 0x05c5 }, .{ 0x05c7, 0x05c7 }, + .{ 0x0600, 0x0605 }, .{ 0x0610, 0x061a }, .{ 0x061c, 0x061c }, .{ 0x064b, 0x065f }, + .{ 0x0670, 0x0670 }, .{ 0x06d6, 0x06dd }, .{ 0x06df, 0x06e4 }, .{ 0x06e7, 0x06e8 }, + .{ 0x06ea, 0x06ed }, .{ 0x070f, 0x070f }, .{ 0x0711, 0x0711 }, .{ 0x0730, 0x074a }, + .{ 0x07a6, 0x07b0 }, .{ 0x07eb, 0x07f3 }, .{ 0x0816, 0x0819 }, .{ 0x081b, 0x0823 }, + .{ 0x0825, 0x0827 }, .{ 0x0829, 0x082d }, .{ 0x0859, 0x085b }, .{ 0x08d3, 0x0902 }, + .{ 0x093a, 0x093a }, .{ 0x093c, 0x093c }, .{ 0x0941, 0x0948 }, .{ 0x094d, 0x094d }, + .{ 0x0951, 0x0957 }, .{ 0x0962, 0x0963 }, .{ 0x0981, 0x0981 }, .{ 0x09bc, 0x09bc }, + .{ 0x09c1, 0x09c4 }, .{ 0x09cd, 0x09cd }, .{ 0x09e2, 0x09e3 }, .{ 0x0a01, 0x0a02 }, + .{ 0x0a3c, 0x0a3c }, .{ 0x0a41, 0x0a51 }, .{ 0x0a70, 0x0a71 }, .{ 0x0a75, 0x0a75 }, + .{ 0x0a81, 0x0a82 }, .{ 0x0abc, 0x0abc }, .{ 0x0ac1, 0x0ac8 }, .{ 0x0acd, 0x0acd }, + .{ 0x0ae2, 0x0ae3 }, .{ 0x0b01, 0x0b01 }, .{ 0x0b3c, 0x0b3c }, .{ 0x0b3f, 0x0b3f }, + .{ 0x0b41, 0x0b44 }, .{ 0x0b4d, 0x0b4d }, .{ 0x0b56, 0x0b56 }, .{ 0x0b62, 0x0b63 }, + .{ 0x0b82, 0x0b82 }, .{ 0x0bc0, 0x0bc0 }, .{ 0x0bcd, 0x0bcd }, .{ 0x0c00, 0x0c00 }, + .{ 0x0c3e, 0x0c40 }, .{ 0x0c46, 0x0c56 }, .{ 0x0c62, 0x0c63 }, .{ 0x0c81, 0x0c81 }, + .{ 0x0cbc, 0x0cbc }, .{ 0x0ccc, 0x0ccd }, .{ 0x0ce2, 0x0ce3 }, .{ 0x0d00, 0x0d01 }, + .{ 0x0d41, 0x0d44 }, .{ 0x0d4d, 0x0d4d }, .{ 0x0d62, 0x0d63 }, .{ 0x0dca, 0x0dca }, + .{ 0x0dd2, 0x0dd6 }, .{ 0x0e31, 0x0e31 }, .{ 0x0e34, 0x0e3a }, .{ 0x0e47, 0x0e4e }, + .{ 0x0eb1, 0x0eb1 }, .{ 0x0eb4, 0x0ebc }, .{ 0x0ec8, 0x0ecd }, .{ 0x0f18, 0x0f19 }, + .{ 0x0f35, 0x0f35 }, .{ 0x0f37, 0x0f37 }, .{ 0x0f39, 0x0f39 }, .{ 0x0f71, 0x0f7e }, + .{ 0x0f80, 0x0f84 }, .{ 0x0f86, 0x0f87 }, .{ 0x0f8d, 0x0fbc }, .{ 0x0fc6, 0x0fc6 }, + .{ 0x102d, 0x1030 }, .{ 0x1032, 0x1037 }, .{ 0x1039, 0x103a }, .{ 0x103d, 0x103e }, + .{ 0x1058, 0x1059 }, .{ 0x105e, 0x1060 }, .{ 0x1071, 0x1074 }, .{ 0x1082, 0x1082 }, + .{ 0x1085, 0x1086 }, .{ 0x108d, 0x108d }, .{ 0x109d, 0x109d }, .{ 0x1160, 0x11ff }, + .{ 0x135d, 0x135f }, .{ 0x1712, 0x1714 }, .{ 0x1732, 0x1734 }, .{ 0x1752, 0x1753 }, + .{ 0x1772, 0x1773 }, .{ 0x17b4, 0x17b5 }, .{ 0x17b7, 0x17bd }, .{ 0x17c6, 0x17c6 }, + .{ 0x17c9, 0x17d3 }, .{ 0x17dd, 0x17dd }, .{ 0x180b, 0x180e }, .{ 0x1885, 0x1886 }, + .{ 0x18a9, 0x18a9 }, .{ 0x1920, 0x1922 }, .{ 0x1927, 0x1928 }, .{ 0x1932, 0x1932 }, + .{ 0x1939, 0x193b }, .{ 0x1a17, 0x1a18 }, .{ 0x1a1b, 0x1a1b }, .{ 0x1a56, 0x1a56 }, + .{ 0x1a58, 0x1a60 }, .{ 0x1a62, 0x1a62 }, .{ 0x1a65, 0x1a6c }, .{ 0x1a73, 0x1a7f }, + .{ 0x1ab0, 0x1aff }, .{ 0x1b00, 0x1b03 }, .{ 0x1b34, 0x1b34 }, .{ 0x1b36, 0x1b3a }, + .{ 0x1b3c, 0x1b3c }, .{ 0x1b42, 0x1b42 }, .{ 0x1b6b, 0x1b73 }, .{ 0x1b80, 0x1b81 }, + .{ 0x1ba2, 0x1ba5 }, .{ 0x1ba8, 0x1ba9 }, .{ 0x1bab, 0x1bad }, .{ 0x1be6, 0x1be6 }, + .{ 0x1be8, 0x1be9 }, .{ 0x1bed, 0x1bed }, .{ 0x1bef, 0x1bf1 }, .{ 0x1c2c, 0x1c33 }, + .{ 0x1c36, 0x1c37 }, .{ 0x1cd0, 0x1cd2 }, .{ 0x1cd4, 0x1ce0 }, .{ 0x1ce2, 0x1ce8 }, + .{ 0x1ced, 0x1ced }, .{ 0x1cf4, 0x1cf4 }, .{ 0x1cf8, 0x1cf9 }, .{ 0x1dc0, 0x1dff }, + .{ 0x200b, 0x200f }, .{ 0x202a, 0x202e }, .{ 0x2060, 0x2064 }, .{ 0x2066, 0x206f }, + .{ 0x20d0, 0x20f0 }, .{ 0x2cef, 0x2cf1 }, .{ 0x2d7f, 0x2d7f }, .{ 0x2de0, 0x2dff }, + .{ 0x302a, 0x302d }, .{ 0x3099, 0x309a }, .{ 0xa66f, 0xa672 }, .{ 0xa674, 0xa67d }, + .{ 0xa69e, 0xa69f }, .{ 0xa6f0, 0xa6f1 }, .{ 0xa802, 0xa802 }, .{ 0xa806, 0xa806 }, + .{ 0xa80b, 0xa80b }, .{ 0xa825, 0xa826 }, .{ 0xa8c4, 0xa8c5 }, .{ 0xa8e0, 0xa8f1 }, + .{ 0xa8ff, 0xa8ff }, .{ 0xa926, 0xa92d }, .{ 0xa947, 0xa951 }, .{ 0xa980, 0xa982 }, + .{ 0xa9b3, 0xa9b3 }, .{ 0xa9b6, 0xa9b9 }, .{ 0xa9bc, 0xa9bd }, .{ 0xa9e5, 0xa9e5 }, + .{ 0xaa29, 0xaa2e }, .{ 0xaa31, 0xaa32 }, .{ 0xaa35, 0xaa36 }, .{ 0xaa43, 0xaa43 }, + .{ 0xaa4c, 0xaa4c }, .{ 0xaa7c, 0xaa7c }, .{ 0xaab0, 0xaab0 }, .{ 0xaab2, 0xaab4 }, + .{ 0xaab7, 0xaab8 }, .{ 0xaabe, 0xaabf }, .{ 0xaac1, 0xaac1 }, .{ 0xaaec, 0xaaed }, + .{ 0xaaf6, 0xaaf6 }, .{ 0xabe5, 0xabe5 }, .{ 0xabe8, 0xabe8 }, .{ 0xabed, 0xabed }, + .{ 0xd7b0, 0xd7ff }, .{ 0xfb1e, 0xfb1e }, .{ 0xfe00, 0xfe0f }, .{ 0xfe20, 0xfe2f }, + .{ 0xfeff, 0xfeff }, .{ 0xfff9, 0xfffb }, .{ 0x101fd, 0x101fd }, .{ 0x10376, 0x1037a }, + .{ 0x10a01, 0x10a0f }, .{ 0x10a38, 0x10a3f }, .{ 0x11001, 0x11001 }, .{ 0x11038, 0x11046 }, + .{ 0x1107f, 0x11081 }, .{ 0x110b3, 0x110b6 }, .{ 0x110b9, 0x110ba }, .{ 0x110bd, 0x110bd }, + .{ 0x11100, 0x11102 }, .{ 0x11127, 0x1112b }, .{ 0x1112d, 0x11134 }, .{ 0x16af0, 0x16af4 }, + .{ 0x16b30, 0x16b36 }, .{ 0x16f8f, 0x16f92 }, .{ 0x1bc9d, 0x1bc9e }, .{ 0x1bca0, 0x1bca3 }, + .{ 0x1d167, 0x1d169 }, .{ 0x1d173, 0x1d182 }, .{ 0x1d185, 0x1d18b }, .{ 0x1d1aa, 0x1d1ad }, + .{ 0x1d242, 0x1d244 }, .{ 0x1e000, 0x1e02a }, .{ 0x1e8d0, 0x1e8d6 }, .{ 0x1e944, 0x1e94a }, + .{ 0xe0001, 0xe0001 }, .{ 0xe0020, 0xe007f }, .{ 0xe0100, 0xe01ef }, +}; + +const double_width = [_]Range{ + .{ 0x1100, 0x115f }, .{ 0x231a, 0x231b }, .{ 0x2329, 0x232a }, .{ 0x23e9, 0x23ec }, + .{ 0x23f0, 0x23f0 }, .{ 0x23f3, 0x23f3 }, .{ 0x25fd, 0x25fe }, .{ 0x2614, 0x2615 }, + .{ 0x2648, 0x2653 }, .{ 0x267f, 0x267f }, .{ 0x2693, 0x2693 }, .{ 0x26a1, 0x26a1 }, + .{ 0x26aa, 0x26ab }, .{ 0x26bd, 0x26be }, .{ 0x26c4, 0x26c5 }, .{ 0x26ce, 0x26ce }, + .{ 0x26d4, 0x26d4 }, .{ 0x26ea, 0x26ea }, .{ 0x26f2, 0x26f3 }, .{ 0x26f5, 0x26f5 }, + .{ 0x26fa, 0x26fa }, .{ 0x26fd, 0x26fd }, .{ 0x2705, 0x2705 }, .{ 0x270a, 0x270b }, + .{ 0x2728, 0x2728 }, .{ 0x274c, 0x274c }, .{ 0x274e, 0x274e }, .{ 0x2753, 0x2755 }, + .{ 0x2757, 0x2757 }, .{ 0x2795, 0x2797 }, .{ 0x27b0, 0x27b0 }, .{ 0x27bf, 0x27bf }, + .{ 0x2b1b, 0x2b1c }, .{ 0x2b50, 0x2b50 }, .{ 0x2b55, 0x2b55 }, .{ 0x2e80, 0x2e99 }, + .{ 0x2e9b, 0x2ef3 }, .{ 0x2f00, 0x2fd5 }, .{ 0x2ff0, 0x2ffb }, .{ 0x3000, 0x3029 }, + .{ 0x302e, 0x303e }, .{ 0x3041, 0x3096 }, .{ 0x309b, 0x30ff }, .{ 0x3105, 0x312f }, + .{ 0x3131, 0x318e }, .{ 0x3190, 0x31e3 }, .{ 0x31f0, 0x321e }, .{ 0x3220, 0x3247 }, + .{ 0x3250, 0x4dbf }, .{ 0x4e00, 0xa48c }, .{ 0xa490, 0xa4c6 }, .{ 0xa960, 0xa97c }, + .{ 0xac00, 0xd7a3 }, .{ 0xf900, 0xfaff }, .{ 0xfe10, 0xfe19 }, .{ 0xfe30, 0xfe52 }, + .{ 0xfe54, 0xfe66 }, .{ 0xfe68, 0xfe6b }, .{ 0xff01, 0xff60 }, .{ 0xffe0, 0xffe6 }, + .{ 0x16fe0, 0x16fe4 }, .{ 0x16ff0, 0x16ff1 }, .{ 0x17000, 0x187f7 }, .{ 0x18800, 0x18cd5 }, + .{ 0x18d00, 0x18d08 }, .{ 0x1aff0, 0x1b122 }, .{ 0x1b150, 0x1b152 }, .{ 0x1b164, 0x1b167 }, + .{ 0x1b170, 0x1b2fb }, .{ 0x1f004, 0x1f004 }, .{ 0x1f0cf, 0x1f0cf }, .{ 0x1f18e, 0x1f18e }, + .{ 0x1f191, 0x1f19a }, .{ 0x1f200, 0x1f202 }, .{ 0x1f210, 0x1f23b }, .{ 0x1f240, 0x1f248 }, + .{ 0x1f250, 0x1f251 }, .{ 0x1f260, 0x1f265 }, .{ 0x1f300, 0x1f320 }, .{ 0x1f32d, 0x1f335 }, + .{ 0x1f337, 0x1f37c }, .{ 0x1f37e, 0x1f393 }, .{ 0x1f3a0, 0x1f3ca }, .{ 0x1f3cf, 0x1f3d3 }, + .{ 0x1f3e0, 0x1f3f0 }, .{ 0x1f3f4, 0x1f3f4 }, .{ 0x1f3f8, 0x1f43e }, .{ 0x1f440, 0x1f440 }, + .{ 0x1f442, 0x1f4fc }, .{ 0x1f4ff, 0x1f53d }, .{ 0x1f54b, 0x1f54e }, .{ 0x1f550, 0x1f567 }, + .{ 0x1f57a, 0x1f57a }, .{ 0x1f595, 0x1f596 }, .{ 0x1f5a4, 0x1f5a4 }, .{ 0x1f5fb, 0x1f64f }, + .{ 0x1f680, 0x1f6c5 }, .{ 0x1f6cc, 0x1f6cc }, .{ 0x1f6d0, 0x1f6d2 }, .{ 0x1f6d5, 0x1f6d7 }, + .{ 0x1f6dc, 0x1f6df }, .{ 0x1f6eb, 0x1f6ec }, .{ 0x1f6f4, 0x1f6fc }, .{ 0x1f7e0, 0x1f7eb }, + .{ 0x1f7f0, 0x1f7f0 }, .{ 0x1f90c, 0x1f93a }, .{ 0x1f93c, 0x1f945 }, .{ 0x1f947, 0x1f9ff }, + .{ 0x1fa70, 0x1fa7c }, .{ 0x1fa80, 0x1fa88 }, .{ 0x1fa90, 0x1fabd }, .{ 0x1fabf, 0x1fac5 }, + .{ 0x1face, 0x1fadb }, .{ 0x1fae0, 0x1fae8 }, .{ 0x1faf0, 0x1faf8 }, .{ 0x20000, 0x2fffd }, + .{ 0x30000, 0x3fffd }, +}; + +fn inTable(cp: u21, table: []const Range) bool { + var lo: usize = 0; + var hi: usize = table.len; + while (lo < hi) { + const mid = (lo + hi) / 2; + if (cp < table[mid][0]) { + hi = mid; + } else if (cp > table[mid][1]) { + lo = mid + 1; + } else return true; + } + return false; +} + +/// The columns a code point at or past U+00A0 takes. +pub fn codepointWidth(cp: u21) u2 { + if (inTable(cp, &zero_width)) return 0; + if (inTable(cp, &double_width)) return 2; + return 1; +} + +test "widths" { + try std.testing.expectEqual(10, of("Merge side")); + try std.testing.expectEqual(6, of("\xe4\xb8\xad\xe4\xb8\xad\xe4\xb8\xad")); + try std.testing.expectEqual(1, of("e\xcc\x81")); + try std.testing.expectEqual(0, of("\x01\t")); + try std.testing.expectEqual(1, of("\x80")); + try std.testing.expectEqual(7, of("\x1b[33m8fbe330\x1b[m")); + for (zero_width[1..], 0..) |r, i| try std.testing.expect(r[0] > zero_width[i][1]); + for (double_width[1..], 0..) |r, i| try std.testing.expect(r[0] > double_width[i][1]); +} diff --git a/tools/describe.zig b/tools/describe.zig new file mode 100644 index 0000000..9c01f6e --- /dev/null +++ b/tools/describe.zig @@ -0,0 +1,553 @@ +// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie +// SPDX-License-Identifier: MIT + +//! Describing commits on `zig-git`'s command lines, for `log`, `show` and +//! `rev-list`: the formatting and searching options they share, read as +//! git reads them; the configuration git consults (`format.pretty`, +//! `pretty.`, `log.date`, `log.abbrevCommit`, `log.mailmap`, the +//! color settings, `grep.*`, `trailer.*`, `core.commentChar`, the mailmap +//! sources); and each commit written with the separators each command +//! puts between them. + +const std = @import("std"); +const Allocator = std.mem.Allocator; +const Io = std.Io; + +const git = @import("git"); +const ObjectId = git.ObjectId; +const Diagnostics = git.Diagnostics; +const pretty = git.pretty; +const tool = @import("zig_git.zig"); +const Context = tool.Context; +const object_names = @import("object_names.zig"); +const revisions = @import("revisions.zig"); + +/// Which command is describing commits; each frames them its own way. +pub const Command = enum { rev_list, log, show }; + +/// The formatting and searching options, as given. +pub const Options = struct { + /// `--pretty[=]` or `--format=`, the last given. + pretty: ?[]const u8 = null, + /// `--abbrev-commit` or `--no-abbrev-commit`, or `--oneline`'s. + abbrev_commit: ?bool = null, + /// `--abbrev=`; null for the default. + abbrev: ?usize = null, + /// `--no-abbrev`. + no_abbrev: bool = false, + /// `--date=`. + date: ?[]const u8 = null, + /// `--use-mailmap` or `--no-use-mailmap`. + mailmap: ?bool = null, + /// `--expand-tabs[=]`, `--no-expand-tabs`. + expand_tabs: ?usize = null, + /// `--color[=]`, `--no-color`. + color: ?enum { always, never, auto } = null, + /// `rev-list --header`. + header: bool = false, + /// `--grep`. + messages: std.ArrayList([]const u8) = .empty, + /// `--author`. + authors: std.ArrayList([]const u8) = .empty, + /// `--committer`. + committers: std.ArrayList([]const u8) = .empty, + all_match: bool = false, + invert_grep: bool = false, + ignore_case: bool = false, + pattern_type: ?git.grep.PatternType = null, + + pub fn deinit(o: *Options, gpa: Allocator) void { + o.messages.deinit(gpa); + o.authors.deinit(gpa); + o.committers.deinit(gpa); + } + + /// Whether a format was asked for at all. + pub fn formatted(o: *const Options) bool { + return o.pretty != null or o.header; + } +}; + +/// What `parseOption` made of an argument. +pub const Parsed = enum { + /// Not one of these options. + no, + /// One of them. + yes, + /// One of them, which took the next argument as its value. + took_next, +}; + +/// Reads `arg`, and `next` if it takes it, as a formatting or searching +/// option. +pub fn parseOption(o: *Options, gpa: Allocator, arg: []const u8, next: ?[]const u8, stderr: *Io.Writer) !Parsed { + const eq = std.mem.findScalar(u8, arg, '='); + const name = arg[0 .. eq orelse arg.len]; + const value: ?[]const u8 = if (eq) |e| arg[e + 1 ..] else null; + const Name = enum { + @"--pretty", + @"--format", + @"--oneline", + @"--abbrev-commit", + @"--no-abbrev-commit", + @"--abbrev", + @"--no-abbrev", + @"--date", + @"--relative-date", + @"--use-mailmap", + @"--mailmap", + @"--no-use-mailmap", + @"--no-mailmap", + @"--expand-tabs", + @"--no-expand-tabs", + @"--color", + @"--no-color", + @"--encoding", + @"--header", + @"--grep", + @"--author", + @"--committer", + @"--all-match", + @"--no-all-match", + @"--invert-grep", + @"--no-invert-grep", + @"-i", + @"--regexp-ignore-case", + @"-E", + @"--extended-regexp", + @"-F", + @"--fixed-strings", + @"--basic-regexp", + @"-P", + @"--perl-regexp", + }; + const n = std.meta.stringToEnum(Name, name) orelse return .no; + switch (n) { + .@"--pretty" => o.pretty = value orelse "medium", + .@"--format" => o.pretty = value orelse return .no, + .@"--oneline" => { + o.pretty = "oneline"; + o.abbrev_commit = true; + }, + .@"--abbrev-commit" => o.abbrev_commit = true, + .@"--no-abbrev-commit" => o.abbrev_commit = false, + .@"--abbrev" => { + o.no_abbrev = false; + o.abbrev = if (value) |v| abbrevLength(v) else null; + }, + .@"--no-abbrev" => o.no_abbrev = true, + .@"--date" => o.date = value orelse return .no, + .@"--relative-date" => o.date = "relative", + .@"--use-mailmap", .@"--mailmap" => o.mailmap = true, + .@"--no-use-mailmap", .@"--no-mailmap" => o.mailmap = false, + .@"--expand-tabs" => o.expand_tabs = if (value) |v| @intCast(@max(0, object_names.optionNumber(v) orelse return tool.fatalMessage(stderr, "'{s}': not an integer", .{v}))) else 8, + .@"--no-expand-tabs" => o.expand_tabs = 0, + .@"--color" => { + const v = value orelse "always"; + o.color = if (std.mem.eql(u8, v, "always")) .always else if (std.mem.eql(u8, v, "never")) .never else if (std.mem.eql(u8, v, "auto")) .auto else { + try stderr.print("error: option `color' expects \"always\", \"auto\", or \"never\"\n", .{}); + return error.UsageQuiet; + }; + }, + .@"--no-color" => o.color = .never, + .@"--encoding" => { + const v = value orelse return .no; + if (!utf8Name(v)) return tool.fatalMessage(stderr, "zig-git: '--encoding={s}' is not supported; only UTF-8 is", .{v}); + }, + .@"--header" => o.header = true, + .@"--grep", .@"--author", .@"--committer" => { + const v = value orelse next orelse return .no; + const list = switch (n) { + .@"--grep" => &o.messages, + .@"--author" => &o.authors, + else => &o.committers, + }; + try list.append(gpa, v); + if (value == null) return .took_next; + }, + .@"--all-match" => o.all_match = true, + .@"--no-all-match" => o.all_match = false, + .@"--invert-grep" => o.invert_grep = true, + .@"--no-invert-grep" => o.invert_grep = false, + .@"-i", .@"--regexp-ignore-case" => o.ignore_case = true, + .@"-E", .@"--extended-regexp" => o.pattern_type = .extended, + .@"-F", .@"--fixed-strings" => o.pattern_type = .fixed, + .@"--basic-regexp" => o.pattern_type = .basic, + .@"-P", .@"--perl-regexp" => return tool.fatalMessage(stderr, "zig-git: '{s}' is not supported: Perl's regular expressions are not", .{arg}), + } + if (value != null) switch (n) { + .@"--pretty", .@"--format", .@"--abbrev", .@"--date", .@"--expand-tabs", .@"--color", .@"--encoding", .@"--grep", .@"--author", .@"--committer" => {}, + else => return .no, + }; + return .yes; +} + +fn abbrevLength(text: []const u8) ?usize { + const n = object_names.optionNumber(text) orelse return null; + if (n <= 0) return null; + return @intCast(@max(4, @min(n, git.object_max_hex_length))); +} + +fn utf8Name(name: []const u8) bool { + return std.ascii.eqlIgnoreCase(name, "utf-8") or std.ascii.eqlIgnoreCase(name, "utf8"); +} + +/// The options that need what this does not have, refused by name. +pub const unsupported = [_][]const u8{ + "-p", "-u", "--patch", "--stat", "--numstat", "--shortstat", + "--dirstat", "--summary", "--name-only", "--name-status", "--raw", "--patch-with-raw", + "--patch-with-stat", "--cc", "-c", "-m", "--dd", "--diff-merges", + "--remerge-diff", "-S", "-G", "--pickaxe-all", "--pickaxe-regex", "--check", + "--full-diff", "-L", "--graph", "--decorate", "--decorate-refs", "--decorate-refs-exclude", + "--clear-decorations", "--source", "--notes", "--show-notes", "--standard-notes", "--show-signature", + "--log-size", "--follow", "--walk-reflogs", "-g", "--grep-reflog", "--show-linear-break", + "-z", "--line-prefix", "--word-diff", "--color-words", "--binary", "--full-index", + "--simplify-by-decoration", +}; + +/// Whether `arg` is one of the options refused by name. +pub fn isUnsupported(arg: []const u8) bool { + const eq = std.mem.findScalar(u8, arg, '='); + const name = arg[0 .. eq orelse arg.len]; + for (unsupported) |u| if (std.mem.eql(u8, u, name)) return true; + // `-S` and `-G`, `-L:`. + if (arg.len > 2 and arg[0] == '-' and (arg[1] == 'S' or arg[1] == 'G' or arg[1] == 'L')) return true; + return false; +} + +/// Commits described: the format, its settings and everything they read. +pub const Describer = struct { + ctx: Context, + repo: *git.Repository, + command: Command, + format: ?pretty.Format, + settings: pretty.Settings, + names: *object_names.Names, + mailmap: *git.Mailmap, + grep: ?git.grep.Grep = null, + configured: []git.trailers.Configured = &.{}, + comment: []u8 = &.{}, + separators: ?[]const u8 = null, + /// Text the format string's options borrow. + arena: std.heap.ArenaAllocator, + /// Whether a commit has been written, for the separators. + written: bool = false, + /// `--no-commit-header`. + commit_header: bool = true, + /// `--timestamp`. + timestamp: bool = false, + header: bool = false, + + /// Sets up describing for `command` from `options` and `repo`'s + /// configuration. + pub fn init(ctx: Context, repo: *git.Repository, names: *object_names.Names, revs: *revisions.Revisions, options: *const Options, command: Command, stderr: *Io.Writer) !Describer { + const gpa = ctx.gpa; + var arena: std.heap.ArenaAllocator = .init(gpa); + errdefer arena.deinit(); + const a = arena.allocator(); + const config = &repo.config; + + if (config.getString("i18n.logOutputEncoding") catch null) |e| if (!utf8Name(e)) + return tool.fatalMessage(stderr, "zig-git: i18n.logOutputEncoding '{s}' is not supported; only UTF-8 is", .{e}); + if (command != .rev_list) { + if (config.getString("log.decorate") catch null) |v| { + const off = std.mem.eql(u8, v, "auto") or (git.Config.value.parseBool(v) == false); + if (!off) return tool.fatalMessage(stderr, "zig-git: log.decorate is not supported", .{}); + } + 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"); + var format: ?pretty.Format = null; + const header = command == .rev_list and options.header and options.pretty == null; + if (header) { + format = .{ .builtin = .raw }; + } else if (options.pretty orelse default_text) |text| { + const Lookup = struct { + fn get(context: *const anyopaque, name: []const u8) ?[]const u8 { + const c: *const git.Config = @ptrCast(@alignCast(context)); + var buffer: [256]u8 = undefined; + const key = std.fmt.bufPrint(&buffer, "pretty.{s}", .{name}) catch return null; + return c.getString(key) catch null; + } + }; + const resolved = pretty.resolve(text, .{ .context = config, .get = Lookup.get }); + var diag: Diagnostics = .{}; + format = pretty.parse(gpa, resolved, &diag) catch |err| switch (err) { + error.UnknownFormat => return tool.fatalMessage(stderr, "invalid --pretty format: {s}", .{text}), + error.UnsupportedPlaceholder => return tool.fatalMessage(stderr, "zig-git: the placeholder '{s}' is not supported", .{diag.detail()}), + else => |e| return e, + }; + } + errdefer if (format) |*f| f.deinit(); + + // 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; + 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; + } + + // Abbreviation. + const abbrev_commit = options.abbrev_commit orelse if (command != .rev_list) ((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 mailmap = try gpa.create(git.Mailmap); + errdefer gpa.destroy(mailmap); + mailmap.* = .init(gpa); + errdefer mailmap.deinit(); + var warnings: std.ArrayList(git.Mailmap.Warning) = .empty; + defer warnings.deinit(gpa); + try mailmap.addRepository(ctx.io, repo, &revs.resolver, .{ .home = ctx.env.get("HOME") }, &warnings); + for (warnings.items) |w| switch (w) { + .symbolic_link => try stderr.writeAll("error: unable to open mailmap at .mailmap: Too many levels of symbolic links\n"), + }; + + // Color: the option, then `color.diff`, then `color.ui`; output is + // never a terminal here. + const color = color: { + if (options.color) |c| break :color c == .always; + for ([_][]const u8{ "color.diff", "color.ui" }) |key| { + if (config.getString(key) catch null) |v| { + if (std.mem.eql(u8, v, "always")) break :color true; + break :color false; + } + } + break :color false; + }; + var commit_color: []const u8 = "\x1b[33m"; + if (color) if (config.getString("color.diff.commit") catch null) |spec| { + var buffer: [pretty.color_max]u8 = undefined; + const escape = pretty.parseColor(spec, &buffer) orelse return tool.fatalMessage(stderr, "invalid color value: {s}", .{spec}); + commit_color = try a.dupe(u8, escape); + }; + + // Trailers. + var configured: std.ArrayList(git.trailers.Configured) = .empty; + for (config.entries.items) |e| { + const parts = e.parts(); + if (!std.ascii.eqlIgnoreCase(parts.section, "trailer")) continue; + const sub = parts.subsection orelse continue; + const slot = for (configured.items) |*c| { + if (std.mem.eql(u8, c.name, sub)) break c; + } else slot: { + try configured.append(a, .{ .name = try a.dupe(u8, sub) }); + break :slot &configured.items[configured.items.len - 1]; + }; + if (std.ascii.eqlIgnoreCase(parts.name, "key")) if (e.value) |v| { + slot.key = try a.dupe(u8, v); + }; + } + const separators: []const u8 = if (config.getString("trailer.separators") catch null) |s| try a.dupe(u8, s) else ":"; + const comment: []const u8 = comment: { + if (config.getString("core.commentString") catch null) |s| break :comment try a.dupe(u8, s); + if (config.getString("core.commentChar") catch null) |s| { + if (std.mem.eql(u8, s, "auto")) break :comment "#"; + break :comment try a.dupe(u8, s); + } + break :comment "#"; + }; + + // Searches. + var grep: ?git.grep.Grep = null; + if (options.messages.items.len != 0 or options.authors.items.len != 0 or options.committers.items.len != 0) { + var pattern_type: git.grep.PatternType = .basic; + if (options.pattern_type) |t| { + pattern_type = t; + } else if (config.getString("grep.patternType") catch null) |t| { + const Type = enum { basic, extended, fixed, perl, default }; + const kind = std.meta.stringToEnum(Type, t) orelse return tool.fatalMessage(stderr, "bad grep.patterntype argument: {s}", .{t}); + pattern_type = switch (kind) { + .basic => .basic, + .extended => .extended, + .fixed => .fixed, + .perl => return tool.fatalMessage(stderr, "zig-git: grep.patternType 'perl' is not supported: Perl's regular expressions are not", .{}), + .default => if ((repo.boolSetting("grep.extendedRegexp", null) catch null) orelse false) .extended else .basic, + }; + } else if ((repo.boolSetting("grep.extendedRegexp", null) catch null) orelse false) { + pattern_type = .extended; + } + var failure: git.grep.Failure = .{}; + grep = git.grep.Grep.init(gpa, .{ + .pattern_type = pattern_type, + .ignore_case = options.ignore_case, + .all_match = options.all_match, + .invert = options.invert_grep, + .messages = options.messages.items, + .authors = options.authors.items, + .committers = options.committers.items, + }, &failure) catch |err| switch (err) { + error.InvalidPattern => return tool.fatalMessage(stderr, "{s}, '{s}': {s}", .{ if (failure.header) "header" else "command line", failure.pattern, failure.regex.problem.message() }), + error.Unsupported => return tool.fatalMessage(stderr, "zig-git: a search pattern using {s} is not supported", .{failure.regex.unsupported}), + error.UnsupportedPatternType => return tool.fatalMessage(stderr, "zig-git: Perl's regular expressions are not supported", .{}), + else => |e| return e, + }; + } + + const columns: usize = if (ctx.env.get("COLUMNS")) |c| (std.fmt.parseInt(usize, c, 10) catch 80) else 80; + return .{ + .ctx = ctx, + .repo = repo, + .command = command, + .format = format, + .names = names, + .mailmap = mailmap, + .grep = grep, + .configured = configured.items, + .arena = arena, + .header = header, + .settings = .{ + .abbreviator = .{ .context = names, .shorten = shorten, .length = if (options.no_abbrev) git.object_max_hex_length else options.abbrev orelse names.defaultLength() }, + .abbrev_commit = abbrev_commit and !options.no_abbrev, + .full_merge_ids = options.no_abbrev, + .date_mode = date_mode, + .date_given = date_given, + .now = revisions.now(ctx), + .zone = revs.zone, + .mailmap = mailmap, + .use_mailmap = use_mailmap, + .color = color, + .commit_color = commit_color, + // rev-list expands no tabs, whatever it is asked. + .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, + .first_line = command != .rev_list, + }, + }; + } + + pub fn deinit(d: *Describer) void { + if (d.format) |*f| f.deinit(); + if (d.grep) |*g| g.deinit(); + d.mailmap.deinit(); + d.ctx.gpa.destroy(d.mailmap); + d.arena.deinit(); + } + + fn shorten(context: *anyopaque, w: *Io.Writer, id: ObjectId, length: usize) pretty.ShortenError!void { + const names: *object_names.Names = @ptrCast(@alignCast(context)); + names.write(w, id, length) catch |err| switch (err) { + error.WriteFailed => return error.WriteFailed, + else => return error.ShortenFailed, + }; + } + + /// Whether the searches keep a commit, by its contents. + pub fn keeps(d: *Describer, contents: []const u8) !bool { + const g = &(d.grep orelse return true); + return g.matches(d.ctx.gpa, d.repo.objectFormat(), contents, if (d.settings.use_mailmap) d.mailmap else null); + } + + /// What one commit is shown as, besides its contents. + pub const Entry = struct { + id: ObjectId, + parents: []const ObjectId, + children: []const ObjectId = &.{}, + mark: pretty.Mark = .none, + /// Whether the mark is written before the commit ID. + show_mark: bool = false, + /// `--timestamp`'s. + time: ?i64 = null, + /// Whether `git rev-list` writes the parents after the commit ID: + /// `--parents`. + header_parents: bool = false, + }; + + /// Writes one commit, as `command` frames it. + pub fn writeCommit(d: *Describer, stdout: *Io.Writer, entry: Entry, stderr: *Io.Writer) !void { + const gpa = d.ctx.gpa; + var diag: Diagnostics = .{}; + var obj = d.repo.database.database().read(d.ctx.io, gpa, entry.id, &diag) catch |err| + return tool.fatalMessage(stderr, "zig-git: cannot read commit {f}: {t}", .{ entry.id, err }); + defer obj.deinit(gpa); + const f = &(d.format orelse unreachable); + var settings = d.settings; + settings.show_mark = entry.show_mark; + var text: Io.Writer.Allocating = .init(gpa); + defer text.deinit(); + const shown: pretty.Shown = .{ .id = entry.id, .contents = obj.data, .parents = entry.parents, .children = entry.children, .mark = entry.mark }; + const user_like = switch (f.*) { + .user => true, + .builtin => |x| x == .reference, + }; + const oneline = f.* == .builtin and f.builtin == .oneline; + // What comes before the commit is written first, as git writes it + // before anything that can fail. + switch (d.command) { + .log, .show => { + if (user_like) { + if (!f.terminated() and d.written) try stdout.writeByte('\n'); + } else if (d.written and !oneline) try stdout.writeByte('\n'); + }, + .rev_list => { + if (entry.time) |t| try stdout.print("{d} ", .{t}); + if (!user_like or d.commit_header) { + if (!oneline and !d.header) try stdout.writeAll("commit "); + if (entry.show_mark) try stdout.writeByte(switch (entry.mark) { + .left => '<', + .right => '>', + .boundary => '-', + .none => ' ', + }); + try d.names.write(stdout, entry.id, if (d.settings.abbrev_commit) d.settings.abbreviator.length else null); + if (entry.header_parents) for (entry.parents) |p| try stdout.print(" {f}", .{p}); + for (entry.children) |c| try stdout.print(" {f}", .{c}); + try stdout.writeByte(if (oneline) ' ' else '\n'); + } + }, + } + d.written = true; + pretty.write(gpa, &text.writer, f, shown, settings, &diag) catch |err| { + if (err != error.OutOfMemory and err != error.WriteFailed) + pretty.writeFirstLine(gpa, stdout, f, shown, settings) catch {}; + return describeFailure(err, &diag, stderr); + }; + const out = text.written(); + switch (d.command) { + .log, .show => { + try stdout.writeAll(out); + if (user_like and f.terminated()) try stdout.writeByte('\n'); + }, + .rev_list => { + if (d.header) { + try stdout.writeAll(out); + try stdout.writeByte(0); + } else if (user_like) { + if (out.len != 0) { + try stdout.writeAll(out); + try stdout.writeByte('\n'); + } + } else { + try stdout.writeAll(out); + if (!oneline) try stdout.writeByte('\n'); + } + }, + } + d.written = true; + } +}; + +/// Says what git says of a commit it could not describe, or refuses what +/// is not supported. +pub fn describeFailure(err: anyerror, diag: *const Diagnostics, stderr: *Io.Writer) error{Fatal} { + switch (err) { + error.InvalidColor => { + stderr.print("error: {s}\n", .{diag.detail()}) catch {}; + return tool.fatalMessage(stderr, "unable to parse --pretty format", .{}); + }, + error.TimestampBeforeEpoch => return tool.fatalMessage(stderr, "{s}", .{diag.detail()}), + error.UnsupportedEncoding, error.UnsupportedConversion => return tool.fatalMessage(stderr, "zig-git: {s} is not supported", .{diag.detail()}), + error.DateOutOfRange => return tool.fatalMessage(stderr, "zig-git: a date out of the range supported", .{}), + else => return tool.fatalMessage(stderr, "zig-git: cannot describe a commit: {t}", .{err}), + } +} diff --git a/tools/log.zig b/tools/log.zig new file mode 100644 index 0000000..01027c2 --- /dev/null +++ b/tools/log.zig @@ -0,0 +1,275 @@ +// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie +// SPDX-License-Identifier: MIT + +//! `zig-git show` and `zig-git check-mailmap`; `zig-git log` is +//! `rev_list.zig`'s walk, described as log describes commits. +//! +//! zig-git show (-s | --no-patch) [