Skip to content
zit Artifact [636ecc6325]
Login

Artifact [636ecc6325]

Artifact 636ecc63252487b48f76f98b6ce10b704e159673c7606819fb7170967d577cc6:


//! `zit info`: describe check-ins by name, or the current checkout.

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 not_a_repo_msg = diagnostics.not_a_repo_msg;
const openRepo = diagnostics.openRepo;
const info_help = help_pages.info_help;

const checkin_display = @import("checkin_display.zig");
const lessByHash = checkin_display.lessByHash;

/// Largest `-` (stdin) name list `zit info` reads: 64 KiB is a name per
/// line for every check-in of a very large store, with room to spare.
const max_info_stdin: usize = 8 * 1024 * 1024;

/// `zit info [NAME...]` — resolve each NAME through the repo-state §8
/// procedure and describe the check-in it names: full artifact ID, branch
/// (§6.1), leaf status (§7), and parents (§3.2/§3.3). A thin renderer over the
/// shared resolver: it calls `resolve(name, .checkin)` exactly as `tag` does,
/// never a second resolver. §8.5: resolution is recency-based (§8.2
/// max-mtime), so a name can name a closed or non-leaf check-in that `leaves`
/// would not list — name resolution is not open-leaf enumeration. Read-only;
/// joins the leaves/branch/tag family through `openRepo`.
///
/// Many names share one store open (a forge rendering a
/// page asks about hundreds of check-ins). Blocks are separated by a blank
/// line so a consumer can split them; a single name prints exactly what it
/// always did. A name that fails to resolve gets its diagnostic and the batch
/// goes on; the exit is 1 if any name failed. `-F json` prints one object per
/// name in input order, so a failed name is a row (`"error"`), not a hole.
pub fn runInfo(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    const parsed = switch (cli.parseInfoArgs(gpa, verb_args) catch return stateOom(streams, "info")) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "info", .unknown_option, tok),
    };
    defer gpa.free(parsed.names);
    if (parsed.help) {
        streams.out.writeAll(info_help) catch {};
        return .ok;
    }
    if (parsed.imported_head) {
        if (parsed.names.len != 0) {
            streams.err.writeAll("zit info: --imported-head cannot be combined with NAMEs\n") catch {};
            return .usage;
        }
        return infoImportedHead(gpa, io, arena, streams, amb, parsed);
    }
    // With no NAME, print Fossil's checkout block (the same one `status`
    // leads with) and the check-in count — Fossil's bare `info`.
    if (parsed.names.len == 0) return infoCheckout(gpa, io, arena, streams, parsed.no_cache);

    // Expand a lone `-` into the names on stdin, one per line, in place.
    var names: std.ArrayList([]const u8) = .empty;
    defer names.deinit(gpa);
    for (parsed.names) |n| {
        if (!std.mem.eql(u8, n, "-")) {
            names.append(gpa, n) catch return stateOom(streams, "info");
            continue;
        }
        const stdin = std.Io.File.stdin();
        var read_buf: [64 * 1024]u8 = undefined;
        var reader = stdin.readerStreaming(io, &read_buf);
        const blob = reader.interface.allocRemaining(arena, .limited(max_info_stdin)) catch {
            streams.err.print("zit info: cannot read names from stdin, or more than {d} bytes were given\n", .{max_info_stdin}) catch {};
            return .failure;
        };
        var lines = std.mem.splitScalar(u8, blob, '\n');
        while (lines.next()) |raw| {
            const line = std.mem.trimEnd(u8, raw, "\r");
            if (line.len == 0) continue; // A trailing newline is not a name.
            names.append(gpa, line) catch return stateOom(streams, "info");
        }
    }
    if (names.items.len == 0) return cli.usageError(streams, "info", .no_name, "");

    var repo: Repository = undefined;
    var root_dir: std.Io.Dir = undefined;
    const rc = openRepo(gpa, io, arena, streams, "info", amb.repo_override, parsed.no_cache, true, &repo, &root_dir);
    if (rc != .ok) return rc;
    defer root_dir.close(io);
    defer repo.deinit(gpa);

    var failed = false;
    for (names.items, 0..) |name, i| {
        // §8.3 full dispatch. §8.2's two MUST-NOTs: closed-ness and leaf-ness
        // of a candidate never filter the selection — that lives in `resolve`.
        const rid = repo.resolve(name, .checkin) catch |e| {
            const why: []const u8 = switch (e) {
                error.NotFound => "not found",
                error.Ambiguous => "ambiguous",
                error.OutOfMemory => return stateOom(streams, "info"),
            };
            failed = true;
            switch (parsed.format) {
                .text => switch (e) {
                    error.NotFound => {
                        streams.err.print("zit info: check-in '{s}' not found\n", .{name}) catch {};
                        cli.horizonNameHint(gpa, repo.io, repo.root_dir, streams, "info");
                    },
                    else => streams.err.print("zit info: name '{s}' is ambiguous\n", .{name}) catch {},
                },
                .json => renderInfoJsonError(streams, name, why),
            }
            continue;
        };
        switch (parsed.format) {
            .text => {
                if (i > 0) streams.out.writeAll("\n") catch {};
                const r = renderInfo(gpa, arena, &repo, rid, streams);
                if (r != .ok) return r;
            },
            .json => {
                const r = renderInfoJson(gpa, arena, &repo, name, rid, streams);
                if (r != .ok) return r;
            },
        }
    }
    return if (failed) .failure else .ok;
}

fn infoImportedHead(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    streams: cli.Streams,
    amb: cli.Ambient,
    parsed: cli.InfoArgs,
) cli.Exit {
    var repo: Repository = undefined;
    var root_dir: std.Io.Dir = undefined;
    const rc = openRepo(gpa, io, arena, streams, "info", amb.repo_override, parsed.no_cache, true, &repo, &root_dir);
    if (rc != .ok) return rc;
    defer root_dir.close(io);
    defer repo.deinit(gpa);

    var map = zit.git_import_map.load(gpa, io, repo.root_dir) catch |err| {
        streams.err.print("zit info: imported head unavailable: import metadata {s}\n", .{@errorName(err)}) catch {};
        return .failure;
    };
    defer map.deinit();
    if (!std.meta.eql(repo.publication_witness, @as(?[32]u8, map.publication_witness))) {
        streams.err.writeAll("zit info: imported head unavailable: publication changed; retry\n") catch {};
        return .failure;
    }
    const log = repo.logStore(gpa) catch |err| {
        streams.err.print("zit info: imported head unavailable: cannot read store: {s}\n", .{@errorName(err)}) catch {};
        return .failure;
    };
    switch (zit.git_import_map.sinceImport(gpa, log, map.contents.artifact_count) catch return stateOom(streams, "info")) {
        .unchanged, .annotated => {},
        .diverged => {
            streams.err.writeAll("zit info: imported head unavailable: the store holds a check-in or branch change its last import did not write\n") catch {};
            return .failure;
        },
        .shrunk => {
            streams.err.writeAll("zit info: imported head unavailable: the store holds fewer artifacts than its last import wrote\n") catch {};
            return .failure;
        },
    }
    const source_ref = std.fmt.allocPrint(arena, "refs/heads/{s}", .{map.contents.settings.default_branch}) catch return stateOom(streams, "info");
    const ref = map.lookupRef(source_ref) orelse {
        streams.err.print("zit info: imported head unavailable: source ref '{s}' was not imported\n", .{source_ref}) catch {};
        return .failure;
    };
    const commit = map.lookupOid(ref.oid) orelse {
        streams.err.writeAll("zit info: imported head unavailable: source ref has no imported check-in\n") catch {};
        return .failure;
    };
    const rid = repo.resolve(commit.checkin, .checkin) catch {
        streams.err.writeAll("zit info: imported head unavailable: recorded check-in is not present\n") catch {};
        return .failure;
    };
    return switch (parsed.format) {
        .text => renderInfo(gpa, arena, &repo, rid, streams),
        .json => renderInfoJson(gpa, arena, &repo, source_ref["refs/".len..], rid, streams),
    };
}

/// Renders the resolved check-in's facts to stdout only: its full artifact ID,
/// branch (§6.1, config-threaded main-branch as fallback), leaf status
/// (§7.1 membership + §7.4 open/closed), the primary parent (§3.2), and each
/// merge parent (§3.3). Values left-align at a fixed column. Data only — every
/// diagnostic already went to stderr. Bounded by the check-in's parent count.
fn infoCheckout(gpa: std.mem.Allocator, io: std.Io, arena: std.mem.Allocator, streams: cli.Streams, bypass_cache: bool) cli.Exit {
    const root = (cli.discoverRoot(arena, io) catch return stateOom(streams, "info")) orelse {
        streams.err.writeAll(not_a_repo_msg) catch {};
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);
    var ck_buf: [zit.checkout.max_ck_payload + 1]u8 = undefined;
    const ck = (zit.checkout.read(io, root_dir, &ck_buf) catch null) orelse {
        streams.err.writeAll("zit info: not an open checkout; name a check-in\n") catch {};
        return .failure;
    };
    var report: std.ArrayList(u8) = .empty;
    defer report.deinit(gpa);
    if (ck.version.len == 0) {
        const branch = if (ck.branch.len == 0) "trunk" else ck.branch;
        report.print(gpa, "repository:   {s}/.zit\nlocal-root:   {s}/\ncheckout:     none yet\ntags:         {s}\ncheck-ins:    0\n", .{ root.abs, root.abs, branch }) catch return stateOom(streams, "info");
        streams.out.writeAll(report.items) catch {};
        return .ok;
    }
    @import("tracking.zig").statusHeader(gpa, io, arena, streams, root.abs, ck.version, &report);
    var repo: Repository = undefined;
    var repo_root: std.Io.Dir = undefined;
    const rc = diagnostics.openRepo(gpa, io, arena, streams, "info", null, bypass_cache, true, &repo, &repo_root);
    if (rc != .ok) return rc;
    defer repo_root.close(io);
    defer repo.deinit(gpa);
    const rids = repo.state().checkinsByMtime(gpa) catch return stateOom(streams, "info");
    defer gpa.free(rids);
    report.print(gpa, "check-ins:    {d}\n", .{rids.len}) catch return stateOom(streams, "info");
    // A horizon clone says where it starts and, when the origin named one,
    // where to ask about the history it does not hold.
    if (zit.repocache.readStoreCone(gpa, io, repo_root)) |cone_val| {
        var cone = cone_val;
        defer cone.deinit(gpa);
        if (cone.horizon) |h| {
            report.print(gpa, "horizon:      {s} ({s}, {s})\n", .{ h.hash, h.rule.name(), h.depth.name() }) catch return stateOom(streams, "info");
            if (zit.repocache.readHorizonUrl(gpa, io, repo_root)) |url| {
                defer gpa.free(url);
                report.print(gpa, "horizon-url:  {s}\n", .{url}) catch return stateOom(streams, "info");
            }
        }
    }
    streams.out.writeAll(report.items) catch {};
    return .ok;
}

fn renderInfo(
    gpa: std.mem.Allocator,
    arena: std.mem.Allocator,
    repo: *Repository,
    rid: repostate.Rid,
    streams: cli.Streams,
) cli.Exit {
    // `resolve`'s postcondition: a resolved rid always bears an event, so every
    // derived query below has a defined answer — no failure path to invent.
    std.debug.assert(repo.state().mtimeOf(rid) != null);

    // Line 1: the canonical full artifact ID (echoes the resolved id even when
    // NAME was a prefix or a symbolic name).
    streams.out.print("{s}\n", .{repo.hashOf(rid)}) catch {};

    // §6.1: the active-tag branch value, config main-branch as the fallback —
    // never the literal "trunk".
    streams.out.print("branch:  {s}\n", .{repo.branchOf(rid)}) catch {};

    // §7.1/§7.4 leaf status: open, closed, or no.
    streams.out.print("leaf:    {s}\n", .{leafWord(repo, rid)}) catch {};

    // §3.2: the primary parent line (omitted for a root).
    const primary = repo.state().primaryParentOf(rid);
    if (primary) |p| streams.out.print("parent:  {s}\n", .{repo.hashOf(p)}) catch {};

    const mp = renderMergeParents(arena, repo, rid, primary, streams);
    if (mp != .ok) return mp;

    // §4.7.14 cherrypick/backout provenance (B-merge-41): a Q card on this
    // check-in surfaces as a `cherrypick:`/`backout:` line naming the picked
    // REV. The state carries the cards — reading the manifest here
    // was the one parse that made `info NAME` cost more than `leaves` — and
    // REV is not a parent, so no edge is implied. A check-in with no Q card
    // prints nothing here — byte-identical to its pre-B-merge-41 baseline
    // (negative space). The value column widens past the fixed lines above
    // because `cherrypick:` overflows their 8-space field.
    if (repo.state().picksOf(gpa, rid) catch null) |picks| {
        defer gpa.free(picks);
        for (picks) |pk| {
            const label: []const u8 = switch (pk.sign) {
                .cherrypick => "cherrypick: ",
                .backout => "backout:    ",
            };
            streams.out.print("{s}{s}\n", .{ label, pk.target }) catch {};
        }
    }

    // Display overrides (repo-state §5.2, minted by `zit amend`): emit a
    // `comment:`/`user:`/`date:` line for each override ONLY when it is active, so
    // an un-amended check-in's info output stays byte-identical to its B-info
    // baseline (negative space). This is the one render path that surfaces a
    // check-in's overridden user and date. Values align at the same column as the
    // fixed lines above (8-space field, so `comment:`+1, `user:`/`date:`+4).
    // Read through `displayOverride` so this works on either backing. The
    // image carries these three resolved; `activeTagValue` would refuse here.
    for (std.enums.values(zit.repoimage.DisplayOverride)) |kind| {
        const name = zit.repoimage.override_names[@backingInt(kind)];
        std.debug.assert(name.len >= 1 and name.len <= 7);
        if (repo.state().displayOverride(rid, kind)) |v| {
            const pad = "        "; // 8 spaces; the value column lands at index 9
            streams.out.print("{s}:{s}{s}\n", .{ name, pad[0 .. 8 - name.len], v }) catch {};
        }
    }
    return .ok;
}

/// The `-F json` row for one resolved name: the same facts as the text block,
/// as one object on one line. Keys are the text block's labels; `parent` is
/// null for a root, `merge` and the pick lists are arrays (possibly empty),
/// and an override key is present only when the override is active — the
/// same negative space as the text form. Bounded by the parent count.
fn renderInfoJson(
    gpa: std.mem.Allocator,
    arena: std.mem.Allocator,
    repo: *Repository,
    name: []const u8,
    rid: repostate.Rid,
    streams: cli.Streams,
) cli.Exit {
    std.debug.assert(repo.state().mtimeOf(rid) != null);
    var aw: std.Io.Writer.Allocating = .init(gpa);
    defer aw.deinit();
    var jw: std.json.Stringify = .{ .writer = &aw.writer };
    // An Allocating writer fails only on OOM, so every error here is one.
    writeInfoJson(gpa, arena, repo, name, rid, &jw) catch return stateOom(streams, "info");
    aw.writer.writeByte('\n') catch return stateOom(streams, "info");
    streams.out.writeAll(aw.written()) catch {};
    return .ok;
}

fn writeInfoJson(
    gpa: std.mem.Allocator,
    arena: std.mem.Allocator,
    repo: *Repository,
    name: []const u8,
    rid: repostate.Rid,
    jw: *std.json.Stringify,
) !void {
    try jw.beginObject();
    try jw.objectField("name");
    try jw.write(name);
    try jw.objectField("hash");
    try jw.write(repo.hashOf(rid));
    try jw.objectField("branch");
    try jw.write(repo.branchOf(rid));
    try jw.objectField("leaf");
    try jw.write(leafWord(repo, rid));
    const primary = repo.state().primaryParentOf(rid);
    try jw.objectField("parent");
    if (primary) |p| try jw.write(repo.hashOf(p)) else try jw.write(null);
    try jw.objectField("merge");
    try jw.beginArray();
    const merges = try mergeParentsSorted(arena, repo, rid, primary);
    for (merges) |h| try jw.write(h);
    try jw.endArray();
    try jw.objectField("cherrypick");
    try writePicks(gpa, repo, rid, .cherrypick, jw);
    try jw.objectField("backout");
    try writePicks(gpa, repo, rid, .backout, jw);
    for (std.enums.values(zit.repoimage.DisplayOverride)) |kind| {
        if (repo.state().displayOverride(rid, kind)) |v| {
            try jw.objectField(zit.repoimage.override_names[@backingInt(kind)]);
            try jw.write(v);
        }
    }
    try jw.endObject();
}

fn writePicks(gpa: std.mem.Allocator, repo: *Repository, rid: repostate.Rid, sign: zit.artifact.QSign, jw: *std.json.Stringify) !void {
    try jw.beginArray();
    const picks = try repo.state().picksOf(gpa, rid);
    defer gpa.free(picks);
    for (picks) |pk| if (pk.sign == sign) try jw.write(pk.target);
    try jw.endArray();
}

fn renderInfoJsonError(streams: cli.Streams, name: []const u8, why: []const u8) void {
    var buf: [256]u8 = undefined;
    var w: std.Io.Writer = .fixed(&buf);
    var jw: std.json.Stringify = .{ .writer = &w };
    const ok = blk: {
        jw.beginObject() catch break :blk false;
        jw.objectField("name") catch break :blk false;
        jw.write(name) catch break :blk false;
        jw.objectField("error") catch break :blk false;
        jw.write(why) catch break :blk false;
        jw.endObject() catch break :blk false;
        w.writeByte('\n') catch break :blk false;
        break :blk true;
    };
    if (ok) {
        streams.out.writeAll(w.buffered()) catch {};
    } else {
        // A name too long for the fixed row still gets a row a consumer can
        // split on; the name itself is in the stderr diagnostic's place.
        streams.out.writeAll("{\"name\":null,\"error\":\"name too long\"}\n") catch {};
    }
}

/// §7.1/§7.4: open (a leaf with no active closed tag), closed (a leaf that
/// carries one), or no (not a leaf at all). open/closed is defined only over
/// leaves, so a non-leaf's closed tag — if any — is not surfaced here. The
/// three arms are total over {isLeaf, hasActiveClosed}.
fn leafWord(repo: *Repository, rid: repostate.Rid) []const u8 {
    return if (repo.state().isOpenLeaf(rid))
        "open"
    else if (repo.state().isLeaf(rid))
        "closed"
    else
        "no";
}

/// Renders the §3.3 merge parents of `rid` — every parent but the primary —
/// one `merge:` line each, sorted by artifact ID ascending. Gathered into an
/// arena vector bounded by the parent count; OOM → exit 1.
fn renderMergeParents(
    arena: std.mem.Allocator,
    repo: *Repository,
    rid: repostate.Rid,
    primary: ?repostate.Rid,
    streams: cli.Streams,
) cli.Exit {
    const merges = mergeParentsSorted(arena, repo, rid, primary) catch {
        streams.err.writeAll("zit info: out of memory\n") catch {};
        return .failure;
    };
    for (merges) |hash| streams.out.print("merge:   {s}\n", .{hash}) catch {};
    return .ok;
}

/// The §3.3 merge parents of `rid` — every parent but the primary — as
/// artifact IDs sorted ascending, in an arena slice bounded by the parent count.
fn mergeParentsSorted(
    arena: std.mem.Allocator,
    repo: *Repository,
    rid: repostate.Rid,
    primary: ?repostate.Rid,
) error{OutOfMemory}![]const []const u8 {
    var merges: std.ArrayList([]const u8) = .empty;
    const bound = repo.state().parentCount(rid);
    var scanned: usize = 0;
    var it = repo.state().parentsOf(rid);
    while (it.next()) |parent| {
        scanned += 1;
        std.debug.assert(scanned <= bound);
        if (primary != null and parent == primary.?) continue;
        try merges.append(arena, repo.hashOf(parent));
    }
    // Negative space: exactly the parents minus the single §3.2 primary — no
    // parent dropped or doubled.
    std.debug.assert(merges.items.len == bound - @as(usize, if (primary == null) 0 else 1));
    std.mem.sort([]const u8, merges.items, {}, lessByHash);
    return merges.items;
}