Skip to content
zit Artifact [916d24d4b8]
Login

Artifact [916d24d4b8]

Artifact 916d24d4b8f4602d0be729a0bca47a1d3ff5afb711b979dd872a4ed55648ceb3:


//! `zit artifact`: describe or dump one stored artifact by hash.

const std = @import("std");
const zit = @import("zit");
const cli = @import("zit").cli;
const merge3 = @import("zit").merge3;
const logstore = @import("zit").logstore;
const Repository = @import("zit").Repository;
const artifact = zit.artifact;
const diagnostics = @import("../diagnostics.zig");
const help_pages = @import("../help.zig");
const repoOpenFail = diagnostics.repoOpenFail;
const openRepo = diagnostics.openRepo;
const artifact_help = help_pages.artifact_help;

/// `zit artifact HASH [--raw]` — zit's plumbing window (contracts/artifact.md).
/// A strictly read-only describe/dump of ONE stored artifact addressed by its
/// hash. HASH covers every artifact kind (file blobs included), so it resolves
/// through the artifact store's prefix lookup, not the symbolic-name procedure
/// `info`/`ls`/`cat` use. No flag → the whatis summary; `--raw` → the exact
/// stored bytes. All card interpretation flows through the one `artifact`
/// parser — never a CLI-side re-parse.
pub fn runArtifact(
    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.parseArtifactArgs(verb_args)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "artifact", .unknown_option, tok),
        .extra_argument => |tok| return cli.usageError(streams, "artifact", .extra_argument, tok),
    };
    if (parsed.help) {
        streams.out.writeAll(artifact_help) catch {};
        return .ok;
    }
    const hash_arg = parsed.hash orelse return cli.usageError(streams, "artifact", .no_hash, "");

    var repo: Repository = undefined;
    var root_dir: std.Io.Dir = undefined;
    // The image path: everything below reads the CONTENT LOG and
    // nothing else -- `resolveArtifactPrefix` and `blob` both go through
    // `logStore`, and no query here touches the derived view. A `.full` derive
    // was work whose product this verb never read.
    const rc = openRepo(gpa, io, arena, streams, "artifact", amb.repo_override, false, true, &repo, &root_dir);
    if (rc != .ok) return rc;
    defer root_dir.close(io);
    defer repo.deinit(gpa);

    // Canonicalize HASH: lowercase, hex-only, length band 4..64 (§3.2/§3.6). A
    // syntactically invalid HASH is the SAME not-found family as an unknown one
    // (B-artifact-8) — no distinct error surface.
    var canon_buf: [2 * logstore.max_hash_len]u8 = undefined;
    const canon = canonicalizeHexPrefix(hash_arg, &canon_buf) orelse return artifactNotFound(streams, hash_arg);

    var full_buf: [2 * logstore.max_hash_len]u8 = undefined;
    const full = (repo.resolveArtifactPrefix(gpa, canon, &full_buf) catch |e| switch (e) {
        error.Ambiguous => return artifactAmbiguous(streams, hash_arg), // B-artifact-7
        error.OutOfMemory => return artifactOom(streams),
        error.NotARepo, error.CannotRead, error.Corrupt, error.ImportPending => |oe| return repoOpenFail(streams, "artifact", oe),
    }) orelse {
        // An artifact a horizon elides is a name the store knows it lacks on
        // purpose: say so, rather than that nothing matches.
        if (zit.absence.blobElision(gpa, io, root_dir, canon)) |e| if (e.elided) {
            var dbuf: [160]u8 = undefined;
            streams.err.print("zit artifact: '{s}' is elided by this store's {s}\n", .{ hash_arg, zit.absence.describeCone(&e, &dbuf) }) catch {};
            streams.err.writeAll("zit artifact: deepen with 'zit update CHECKIN' (fetches from the saved remote), or read it at the origin\n") catch {};
            return .failure;
        };
        _ = artifactNotFound(streams, hash_arg); // B-artifact-8
        cli.horizonNameHint(gpa, io, root_dir, streams, "artifact");
        return .failure;
    };

    // §7.2-verified stored bytes. `resolveArtifactPrefix` named a real stored
    // artifact, so a null here would be a store race, not user input.
    const bytes = (repo.blob(gpa, full) catch |e| return repoOpenFail(streams, "artifact", e)) orelse
        return artifactNotFound(streams, hash_arg);
    defer gpa.free(bytes);
    // B-artifact-4 round-trip invariant: the emitted bytes hash back to HASH.
    std.debug.assert(artifact.verify(full, bytes));

    if (parsed.raw) {
        // B-artifact-4: verbatim, no trailing newline, binary-safe (mirrors cat).
        // Never parses or verifies Z.
        streams.out.writeAll(bytes) catch {};
        return .ok;
    }
    return renderArtifactSummary(streams, gpa, full, bytes);
}

/// Canonicalize a HASH argument into `out`: lowercase every byte, accept only
/// hex digits and only a 4..64-length token (§3.2 length band, §3.6 case-
/// insensitive prefix). Returns null for anything outside that — the caller
/// folds null into the not-found refusal, so a bad HASH never has its own
/// error surface (B-artifact-8). No allocation.
fn canonicalizeHexPrefix(arg: []const u8, out: *[2 * logstore.max_hash_len]u8) ?[]const u8 {
    if (arg.len < 4 or arg.len > out.len) return null;
    for (arg, 0..) |c, i| {
        const lc = std.ascii.toLower(c);
        if (!((lc >= '0' and lc <= '9') or (lc >= 'a' and lc <= 'f'))) return null;
        out[i] = lc;
    }
    return out[0..arg.len];
}

/// Render the whatis summary of a resolved artifact to stdout (data-only). Tries
/// the Z-tolerant `parseWindow`: on success the artifact is structural (its type,
/// size, one line per card, and the §6.2 Z verdict); on any framing/grammar/
/// classification fault it is an opaque blob (B-artifact-3) — type file, size,
/// and the NUL binary verdict, never an error. Exit 0 either way.
fn renderArtifactSummary(streams: cli.Streams, gpa: std.mem.Allocator, full: []const u8, bytes: []const u8) cli.Exit {
    streams.out.print("{s}\n", .{full}) catch {};

    var m = artifact.parseWindow(gpa, bytes) catch |e| switch (e) {
        error.OutOfMemory => return artifactOom(streams),
        else => {
            // A blob is a first-class answer (B-artifact-3), not a failure.
            streams.out.writeAll("type: file\n") catch {};
            streams.out.print("size: {d} bytes\n", .{bytes.len}) catch {};
            streams.out.print("binary: {s}\n", .{if (merge3.isBinary(bytes)) "yes" else "no"}) catch {};
            // A quarry attachment stub is a pointer, and the honest
            // description is what it points at, not its own hundred bytes.
            if (zit.attachstub.parse(bytes)) |st| {
                streams.out.print("attachment-stub: {s}, {d} bytes external (sha256 {s}{s}{s})\n", .{
                    st.name, st.size, st.sha256, if (st.mimetype.len != 0) ", " else "", st.mimetype,
                }) catch {};
            }
            return .ok;
        },
    };
    defer m.deinit();

    streams.out.print("type: {s}\n", .{m.kind.diagnosticName()}) catch {};
    streams.out.print("size: {d} bytes\n", .{bytes.len}) catch {};
    // PRESENCE, never validity: reporting "valid" would mean shelling
    // to gpg from a read verb and inheriting its keyring's answer, which
    // makes an offline or key-less reader print alarming things about
    // artifacts that are fine. Presence is what the store knows; validity is
    // the operator's own `gpg --verify` on `artifact --raw` output.
    if (artifact.isSignatureWrapped(bytes)) {
        streams.out.writeAll("signature: clearsigned (cards read from the stripped body)\n") catch {};
    }
    renderCardLines(streams, m);

    // B-artifact-5: the Z verdict is REPORTED, not enforced — a mismatch stays
    // exit 0 (this is a window, not a gate). Emitted only when a Z card is
    // present; `parseWindow` succeeded so the framed content is recoverable.
    if (m.z != null) {
        const content = artifact.frameNoZ(bytes).?; // non-null: parseWindow framed it
        const verdict = artifact.verifyZCard(content);
        std.debug.assert(verdict != .absent); // a present Z card is structurally last
        streams.out.print("Z: {s}\n", .{if (verdict == .match) "verified" else "checksum mismatch"}) catch {};
    }
    return .ok;
}

/// One line per card of a structural artifact, in ascending card-letter order
/// (A..W; Z is the separate verdict line the caller prints). §4.4 makes wire
/// order non-decreasing, so lane order == stored order — this reads decoded
/// struct fields, never re-walking the bytes. Repeatable lanes (F/J/M/P/Q/S/T)
/// render in retained wire order, one line per card. Best-effort writes.
fn renderCardLines(s: cli.Streams, m: artifact.Manifest) void {
    if (m.a) |a| {
        s.out.print("A {s} {s}", .{ a.name, a.target }) catch {};
        if (a.source) |src| s.out.print(" {s}", .{src}) catch {};
        s.out.writeAll("\n") catch {};
    }
    if (m.b) |b| s.out.print("B {s}\n", .{b.hash}) catch {};
    if (m.c) |c| s.out.print("C {s}\n", .{c.comment}) catch {};
    if (m.d) |d| s.out.print("D {s}\n", .{d.timestamp}) catch {};
    if (m.e) |e| s.out.print("E {s} {s}\n", .{ e.timestamp, e.technote_id }) catch {};
    for (m.f) |f| {
        s.out.print("F {s}", .{f.filename}) catch {};
        if (f.hash) |h| s.out.print(" {s}", .{h}) catch {};
        if (f.perm) |p| s.out.print(" {s}", .{p}) catch {};
        if (f.old_name) |o| s.out.print(" {s}", .{o}) catch {};
        s.out.writeAll("\n") catch {};
    }
    if (m.g) |g| s.out.print("G {s}\n", .{g.hash}) catch {};
    if (m.h) |h| s.out.print("H {s}\n", .{h.title}) catch {};
    if (m.i) |i| s.out.print("I {s}\n", .{i.hash}) catch {};
    for (m.j) |j| s.out.print("J {s} {s}\n", .{ j.field, j.value }) catch {};
    if (m.k) |k| s.out.print("K {s}\n", .{k.ticket_id}) catch {};
    if (m.l) |l| s.out.print("L {s}\n", .{l.title}) catch {};
    for (m.m) |mc| s.out.print("M {s}\n", .{mc.hash}) catch {};
    if (m.n) |n| s.out.print("N {s}\n", .{n.mimetype}) catch {};
    for (m.p) |p| {
        s.out.writeAll("P") catch {};
        var it = p.hashes();
        while (it.next()) |hh| s.out.print(" {s}", .{hh}) catch {};
        s.out.writeAll("\n") catch {};
    }
    for (m.q) |q| {
        const sign_byte: u8 = if (q.sign == .cherrypick) '+' else '-';
        s.out.print("Q {c}{s}", .{ sign_byte, q.target }) catch {};
        if (q.baseline) |base| s.out.print(" {s}", .{base}) catch {};
        s.out.writeAll("\n") catch {};
    }
    if (m.r) |r| s.out.print("R {s}\n", .{r.checksum}) catch {};
    // submanifests §3.6: a tree check-in carries its whole file set by S
    // cards and no F cards, so dropping this lane showed a manifest with no
    // files at all while `ls` on the same hash listed thousands.
    for (m.s) |sc| s.out.print("S {s} {s}\n", .{ sc.filename, sc.hash }) catch {};
    for (m.t) |t| {
        const tgt = t.target orelse "*"; // §4.7.16 self-referential tag
        s.out.print("T {c}{s} {s}", .{ t.sign.byte(), t.name, tgt }) catch {};
        if (t.value) |v| s.out.print(" {s}", .{v}) catch {};
        s.out.writeAll("\n") catch {};
    }
    if (m.u) |u| s.out.print("U {s}\n", .{u.login}) catch {};
    if (m.w) |w| s.out.print("W {d} bytes\n", .{w.len}) catch {};
}

fn artifactNotFound(s: cli.Streams, arg: []const u8) cli.Exit {
    s.err.print("zit artifact: no artifact matches '{s}'\n", .{arg}) catch {};
    return .failure;
}

fn artifactAmbiguous(s: cli.Streams, arg: []const u8) cli.Exit {
    s.err.print("zit artifact: hash '{s}' is ambiguous\n", .{arg}) catch {};
    return .failure;
}

fn artifactOom(s: cli.Streams) cli.Exit {
    s.err.writeAll("zit artifact: out of memory\n") catch {};
    return .failure;
}