Skip to content
zit Artifact [c25a706f7f]
Login

Artifact [c25a706f7f]

Artifact c25a706f7fbc41ee977f78cf9d5bc1a99a54450f2a09e9e4a03e0ad2c91b61d5:


//! `zit annotate` (also `blame`, `praise`): per-line provenance of one
//! tracked file.

const std = @import("std");
const zit = @import("zit");
const cli = @import("zit").cli;
const Repository = @import("zit").Repository;
const repostate = zit.repostate;
const diagnostics = @import("../diagnostics.zig");
const help_pages = @import("../help.zig");
const stateOom = diagnostics.stateOom;
const openRepo = diagnostics.openRepo;
const annotate_help = help_pages.annotate_help;

// The PATH walk is the library core's, shared with the daemon's `log`.
const filelog = zit.filelog;
const loadPathIndex = filelog.loadPathIndex;

// The annotation gather is the library core's, shared with the daemon.
const core_blame = zit.blame;
const AnnotateReadError = core_blame.ReadError;

fn annotateReadFail(streams: cli.Streams, e: AnnotateReadError) cli.Exit {
    switch (e) {
        error.OutOfMemory => streams.err.writeAll("zit annotate: out of memory\n") catch {},
        error.Storage => streams.err.writeAll("zit annotate: cannot read repository: input/output error\n") catch {},
        error.Corrupt => streams.err.writeAll("zit annotate: cannot read repository: repository is corrupt\n") catch {},
    }
    return .failure;
}

/// The B-annotate-10 refusal: PATH is not in the current check-out's managed set.
/// Distinguishes an untracked-but-present working file from a nonexistent one so
/// the diagnostic tells the user which mistake they made. Exit 1, stdout empty.
fn annotateNotTracked(io: std.Io, root_dir: std.Io.Dir, path: []const u8, streams: cli.Streams) cli.Exit {
    const present = blk: {
        var f = root_dir.openFile(io, path, .{}) catch break :blk false;
        f.close(io);
        break :blk true;
    };
    if (present)
        streams.err.print("zit annotate: '{s}' is not tracked at the current check-out\n", .{path}) catch {}
    else
        streams.err.print("zit annotate: '{s}': no such tracked file\n", .{path}) catch {};
    return .failure;
}

/// `zit annotate PATH` — parse (one repo-relative positional via the shared
/// one-positional grammar), open the repository read-only, and render the
/// annotation. `-h`/`--help` wins; a missing PATH / unknown option / second
/// positional is a usage error (exit 2). (B-annotate-12/-13/-16.)
pub fn runAnnotate(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
    /// `blame`/`praise`: Fossil's user column in place of the line number.
    blame: bool,
) cli.Exit {
    const parsed = switch (cli.parseAnnotateArgs(verb_args)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "annotate", .unknown_option, tok),
        .extra_argument => |tok| return cli.usageError(streams, "annotate", .extra_argument, tok),
    };
    if (parsed.help) {
        streams.out.writeAll(annotate_help) catch {};
        return .ok;
    }
    const path = parsed.path orelse return cli.usageError(streams, "annotate", .no_file, "");

    var repo: Repository = undefined;
    var root_dir: std.Io.Dir = undefined;
    // The image carries what the walk needs (adjacency, mtimes, names), and
    // the per-path change set comes from the cache body either way.
    const rc = openRepo(gpa, io, arena, streams, "annotate", amb.repo_override, false, true, &repo, &root_dir);
    if (rc != .ok) return rc;
    defer root_dir.close(io);
    defer repo.deinit(gpa);

    // VERSION resolves exactly as `cat`'s (the §8.3 name procedure); omitted
    // means the current checkout, so a bare repository (-R with no working
    // tree) names its target explicitly.
    const at: ?repostate.Rid = if (parsed.version) |name|
        repo.resolve(name, .checkin) catch |e| return annotateResolveFail(gpa, &repo, streams, name, e)
    else
        null;

    return annotateFile(gpa, io, &repo, root_dir, path, at, .{
        .full_ids = parsed.full,
        .limit = parsed.limit,
        .log_versions = parsed.log,
        .blame = blame,
        .follow = !parsed.no_follow,
        .partial = parsed.partial,
    }, streams);
}

/// Maps a `Repository.resolve` failure for `annotate` to its diagnostic + exit 1.
fn annotateResolveFail(gpa: std.mem.Allocator, repo: *const Repository, s: cli.Streams, name: []const u8, e: Repository.ResolveError) cli.Exit {
    switch (e) {
        error.NotFound => {
            s.err.print("zit annotate: check-in '{s}' not found\n", .{name}) catch {};
            cli.horizonNameHint(gpa, repo.io, repo.root_dir, s, "annotate");
        },
        error.Ambiguous => s.err.print("zit annotate: name '{s}' is ambiguous\n", .{name}) catch {},
        error.OutOfMemory => s.err.writeAll("zit annotate: out of memory\n") catch {},
    }
    return .failure;
}

/// Annotate PATH as of `at` (the current check-out when null) through the
/// library core's gather (`blame.annotate`), and render it: the text lines,
/// or the refusal's message and exit. A scratch arena owns the answer; the
/// versions walked live on `gpa` only while the walk needs them.
fn annotateFile(
    gpa: std.mem.Allocator,
    io: std.Io,
    repo: *Repository,
    root_dir: std.Io.Dir,
    path: []const u8,
    at: ?repostate.Rid,
    opts: AnnotateOptions,
    streams: cli.Streams,
) cli.Exit {
    var arena_state = std.heap.ArenaAllocator.init(gpa);
    defer arena_state.deinit();
    const arena = arena_state.allocator();
    const cur = at orelse repo.currentCheckoutRid() orelse
        return annotateNotTracked(io, root_dir, path, streams);
    // The file index `log PATH` reads finds the file's versions; without
    // one the walk covers the whole ancestry, to the same answer.
    var index: ?filelog.PathIndex = if (repo.logStore(gpa)) |log|
        loadPathIndex(gpa, io, root_dir, repo, log) catch return stateOom(streams, "annotate")
    else |_|
        null;
    defer if (index) |*ix| ix.deinit(gpa);

    var elision: ElisionCtx = .{ .io = io, .root_dir = root_dir };
    const result = core_blame.annotate(gpa, arena, io, repo, path, cur, .{
        .limit = opts.limit,
        .list_versions = opts.log_versions,
        .follow = opts.follow,
        .partial = opts.partial,
    }, elision.hook(), if (index) |*ix| ix else null) catch |err| return annotateReadFail(streams, err);
    const ann = switch (result) {
        .ok => |a| a,
        .refused => |r| return annotateRefused(gpa, io, repo, root_dir, path, r, streams),
    };
    if (opts.log_versions) {
        // -l: the versions walked, newest first, before the lines.
        for (ann.versions) |rid| {
            var iso: [19]u8 = undefined;
            const mt = repo.state().mtimeOf(rid) orelse 0;
            const full = repo.hashOf(rid);
            streams.out.print("version {s} {s}\n", .{ if (opts.full_ids) full else full[0..@min(full.len, 10)], cli.formatWriterTimestamp(@intCast(mt / 1000), &iso) }) catch {};
        }
        streams.out.writeAll("---\n") catch {};
    }

    // Render one output line per file line: the origin's 12-char artifact-hash
    // prefix, a space, the ISO date (UTC, from the origin's event mtime), a space,
    // then the file line verbatim (its own trailing newline carries the break).
    for (ann.origins, 0..) |o, n| {
        const full = repo.hashOf(o.rid);
        // --full: the whole artifact ID, safe as an index key; the default
        // 12-character prefix stays for eyeballs.
        const shown = if (opts.full_ids) full else cli.shortHash(full);
        var iso_buf: [19]u8 = undefined;
        const ts = cli.formatWriterTimestamp(@intCast(o.mtime / 1000), &iso_buf);
        const iso_date = ts[0..10]; // YYYY-MM-DD
        if (o.approx) streams.out.writeAll("~") catch {};
        // Fossil's columns: the line number for annotate, the user
        // for blame and praise. Older than the -n limit reached, Fossil
        // blanks the attribution columns and prints the rest.
        if (o.beyond) {
            streams.out.splatByteAll(' ', shown.len + 1 + iso_date.len) catch {};
            if (opts.blame) {
                streams.out.print("{s:>15} {s}", .{ "", ann.text(n) }) catch {};
            } else {
                streams.out.print(" {d:>5}: {s}", .{ n + 1, ann.text(n) }) catch {};
            }
        } else if (opts.blame) {
            streams.out.print("{s} {s} {s:>13}: {s}", .{ shown, iso_date, o.user orelse "", ann.text(n) }) catch {};
        } else {
            streams.out.print("{s} {s} {d:>5}: {s}", .{ shown, iso_date, n + 1, ann.text(n) }) catch {};
        }
    }
    if (ann.any_gap) streams.err.print(
        "zit annotate: versions of '{s}' were purged or shunned; lines marked '~' are approximate\n",
        .{path},
    ) catch {};
    return .ok;
}

const AnnotateOptions = struct {
    /// --full: whole artifact IDs instead of the 12-character prefix.
    full_ids: bool,
    /// -n N: walk at most N versions of the file.
    limit: ?usize,
    /// -l: list the versions walked before the lines.
    log_versions: bool,
    /// blame/praise: the user column in place of the line number.
    blame: bool,
    follow: bool,
    partial: bool,
};

/// `zit.absence.blobElision` in the core's words, for `blame.annotate`.
const ElisionCtx = struct {
    io: std.Io,
    root_dir: std.Io.Dir,

    fn hook(self: *ElisionCtx) core_blame.ElisionHook {
        return .{ .ctx = self, .of = of };
    }

    fn of(ctx: ?*anyopaque, gpa: std.mem.Allocator, hash: []const u8) ?core_blame.Elision {
        const self: *ElisionCtx = @ptrCast(@alignCast(ctx.?));
        const e = zit.absence.blobElision(gpa, self.io, self.root_dir, hash) orelse return null;
        return .{ .elided = e.elided, .horizon = e.horizon != null };
    }
};

/// What `annotate` says when the core refuses, and its exit.
fn annotateRefused(
    gpa: std.mem.Allocator,
    io: std.Io,
    repo: *Repository,
    root_dir: std.Io.Dir,
    path: []const u8,
    r: core_blame.Refusal,
    streams: cli.Streams,
) cli.Exit {
    switch (r) {
        .not_tracked => return annotateNotTracked(io, root_dir, path, streams),
        .binary => {
            streams.err.print("zit annotate: '{s}': cannot annotate binary content\n", .{path}) catch {};
            return .failure;
        },
        .absent, .missing => {
            const name, const rid = switch (r) {
                .absent => |x| .{ x.name, x.rid },
                .missing => |x| .{ x.name, x.rid },
                else => unreachable,
            };
            var wbuf: [512]u8 = undefined;
            const what = std.fmt.bufPrint(&wbuf, "content for '{s}' at check-in {s}", .{ name, cli.shortHash(repo.hashOf(rid)) }) catch "content";
            switch (r) {
                .absent => |x| {
                    const absence: zit.absence.Absence = switch (x.why) {
                        .purged => .thinned,
                        .shunned => .shunned,
                        .erased => .erased,
                    };
                    zit.absence.describeAbsence(streams.err, "annotate", what, &absence);
                    return .absent;
                },
                else => {
                    streams.err.print("zit annotate: {s} is missing\n", .{what}) catch {};
                    return .failure;
                },
            }
        },
        .elided, .elided_below => {
            const name, const hash = switch (r) {
                .elided => |x| .{ x.name, x.hash },
                .elided_below => |x| .{ x.name, x.hash },
                else => unreachable,
            };
            var e = zit.absence.blobElision(gpa, io, root_dir, hash) orelse return .absent;
            // Below the horizon the renamed file's own blob may be here;
            // what is elided is the old name's history under the cut.
            if (r == .elided_below) e.elided = true;
            annotateElisionMessage(streams, name, &e);
            return .absent;
        },
    }
}

/// The elision message: what is elided, by which cut, and the remedy.
fn annotateElisionMessage(streams: cli.Streams, name: []const u8, e: *const zit.absence.Elision) void {
    var dbuf: [160]u8 = undefined;
    streams.err.print("zit annotate: '{s}' is elided by this store's {s}\n", .{ name, zit.absence.describeCone(e, &dbuf) }) catch {};
    streams.err.writeAll(if (e.horizon != null)
        "zit annotate: history below the horizon is answered by the origin; deepen with 'zit update <check-in>' to annotate it here\n"
    else
        "zit annotate: widen the cone with 'zit update --cone PATH' to fetch it\n") catch {};
}