Skip to content
zit Artifact [0d0a15a91e]
Login

Artifact [0d0a15a91e]

Artifact 0d0a15a91ee2c35eb8af82b56e38b1e1fce9284945d357f0764aa6a33bac0f6c:


//! `zit ls`: list the files of a check-in or of the current checkout.

const std = @import("std");
const zit = @import("zit");
const cli = @import("zit").cli;
const cmd_pull = @import("pull.zig");
const logstore = @import("zit").logstore;
const Repository = @import("zit").Repository;
const diagnostics = @import("../cli/diagnostics.zig");
const help_pages = @import("../cli/help.zig");
const stateOom = diagnostics.stateOom;
const not_a_repo_msg = diagnostics.not_a_repo_msg;
const repoOpenFail = diagnostics.repoOpenFail;
const openRepo = diagnostics.openRepo;
const ls_help = help_pages.ls_help;

/// `zit ls [VERSION]` — list the effective file set of a resolved check-in, one
/// `<blob-id> <filename>` line per file in canonical §4.5.3 order. Thin over the
/// `Repository` facade: resolve VERSION (or fall back to the current checkout),
/// then stream `repo.files`' iterator. All the §8.2 merge and §8.3 baseline
/// policy lives in the library; this only selects the check-in and renders.
pub fn runLs(
    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.parseLsArgs(verb_args)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "ls", .unknown_option, tok),
        .extra_argument => |tok| return cli.usageError(streams, "ls", .extra_argument, tok),
    };
    if (parsed.help) {
        streams.out.writeAll(ls_help) catch {};
        return .ok;
    }
    var tree: cmd_pull.ElidedTree = .{};
    const rc = lsOnce(gpa, io, arena, parsed, streams, amb, &tree);
    if (!tree.fetch(gpa, io, arena, streams, amb, "ls")) return rc;
    return lsOnce(gpa, io, arena, parsed, streams, amb, &tree);
}

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

    // An explicit VERSION resolves through the §8.3 name procedure; an omitted
    // VERSION lists the current checkout (§7.5). An unborn or absent checkout has
    // no check-in to list — a failure, not empty output.
    const rid = if (parsed.version) |name|
        repo.resolve(name, .checkin) catch |e| return lsResolveFail(gpa, &repo, streams, name, e)
    else
        repo.currentCheckoutRid() orelse return lsNoCheckout(streams);

    // `--under` reads only the cards in its name range; `lsUnder` below still
    // decides the segment boundary, since `src` begins `src-other` too.
    const range = if (parsed.under) |p| std.mem.trimEnd(u8, p, "/") else "";
    var list = (repo.filesWithPrefix(gpa, rid, range) catch |e| return lsFilesFail(streams, e, tree)) orelse
        return lsMissingContent(streams);
    defer list.deinit(gpa);

    // `--long` and `--size` open the store; the default listing does not and
    // must not start paying for one. The plaintext memo pays for itself when
    // `--long` does reconstruct: consecutive files in a tree routinely share
    // delta bases, so reconstructing without it re-resolves the same base once
    // per file.
    var log: ?*logstore.LogStore = null;
    var plaintext: logstore.PlaintextCache = .{ .memoize_undeltaed = parsed.long and !parsed.no_cache };
    defer plaintext.deinit(gpa);
    if (parsed.long or parsed.size) {
        log = repo.logStore(gpa) catch |e| return repoOpenFail(streams, "ls", e);
    }
    // `--long` reads a blob once for its class and remembers the answer: the
    // class is a function of the bytes, so a recorded one never goes stale.
    // `--no-cache` reads every blob afresh and records nothing.
    const memoize = parsed.long and !parsed.no_cache;
    var classes: zit.blobclass.Memo = if (memoize)
        zit.blobclass.Memo.load(gpa, io, repo.root_dir) catch return stateOom(streams, "ls")
    else
        .{};
    defer classes.deinit(gpa);

    // Rows whose bytes this store cannot produce; under a horizon the
    // listing says why once, after the data.
    var absent: usize = 0;
    // Data only: one line per effective file, in canonical filename order.
    var it = list.iterator();
    while (it.next()) |f| {
        std.debug.assert(f.hash != null); // the iterator suppresses delete markers
        if (parsed.under) |prefix| {
            if (!lsUnder(f.filename, prefix)) continue;
        }
        if (!parsed.long and !parsed.size) {
            streams.out.print("{s}\n", .{f.filename}) catch {}; // names, as Fossil lists them
            continue;
        }
        // The permission token is the one fact a consumer cannot recover by
        // spending more: it lives in the MANIFEST's F card, and the blob it
        // names does not know it is executable or a symlink.
        const perm = if (f.perm) |p| p else "-";

        // `--size` reads the length out of the frame header instead of
        // reconstructing the blob to measure it. A sparse elision, a shun or a
        // phantom is `absent`. It never claims to have read content.
        if (parsed.size) {
            if (lsBlobSize(gpa, log.?, f.hash.?)) |n| {
                streams.out.print("{s} {d} {s} {s}\n", .{ f.hash.?, n, perm, f.filename }) catch {};
            } else {
                streams.out.print("{s} absent {s} {s}\n", .{ f.hash.?, perm, f.filename }) catch {};
            }
            continue;
        }
        // A recorded class answers `--long` the way Fossil's `ls -v` answers
        // from its blob table: the size comes from the frame header and the
        // class from the memo, and no content is reconstructed. The header
        // read applies the same masks as a content read (purged, shunned,
        // elided and phantom blobs all read null), so those rows are absent
        // exactly as before. What it gives up is proof that every delta
        // basis still reconstructs, which a listing should not re-establish
        // per row on every run; `zit verify` is the tool that proves content.
        if (classes.get(f.hash.?)) |known| {
            if (lsBlobSize(gpa, log.?, f.hash.?)) |n| {
                streams.out.print("{s} {d} {s} {t} {s}\n", .{ f.hash.?, n, perm, known, f.filename }) catch {};
            } else {
                streams.out.print("{s} 0 {s} absent {s}\n", .{ f.hash.?, perm, f.filename }) catch {};
                absent += 1;
            }
            continue;
        }
        var size: u64 = 0;
        var class: []const u8 = "text";
        if (lsBlobBytes(gpa, log.?, &plaintext, f.hash.?)) |bytes| {
            defer gpa.free(bytes);
            size = bytes.len;
            const binary = zit.textdiff.isBinary(bytes);
            if (binary) class = "binary";
            if (memoize) classes.put(gpa, f.hash.?, if (binary) .binary else .text) catch return stateOom(streams, "ls");
        } else {
            // Elided by a sparse store, shunned, or a phantom. Say so rather
            // than reporting a zero-byte text file, which is a lie that looks
            // like data.
            class = "absent";
            absent += 1;
        }
        streams.out.print("{s} {d} {s} {s} {s}\n", .{ f.hash.?, size, perm, class, f.filename }) catch {};
    }
    if (memoize) classes.store(gpa, io, repo.root_dir) catch return stateOom(streams, "ls");
    if (absent != 0) _ = cli.horizonContentNote(gpa, io, repo.root_dir, streams, "ls");
    return .ok;
}

/// Whether `path` is at or beneath `prefix`, on a path-segment boundary so
/// `--under=src` never matches `src-other`. A prefix naming the file itself
/// matches, which is how a consumer asks about one entry.
fn lsUnder(path: []const u8, prefix: []const u8) bool {
    const p = std.mem.trimEnd(u8, prefix, "/");
    if (p.len == 0) return true; // `--under=/` is the whole tree
    if (!std.mem.startsWith(u8, path, p)) return false;
    if (path.len == p.len) return true;
    return path[p.len] == '/';
}

/// Blobs `ls` asked the store to reconstruct. `zit` reports it on exit under
/// `ZIT_LS_CONTENT_READS`, and the e2e suite pins that a listing whose
/// classes are recorded reconstructs none.
pub var ls_content_reads: u64 = 0;

/// One blob's plaintext, or null when the store cannot produce it (a sparse
/// elision, a shun, or a phantom). Never fails the listing: a file whose bytes
/// are unavailable is reported as such, because `ls` answers about the
/// MANIFEST, and the manifest is intact whatever the store holds.
fn lsBlobBytes(
    gpa: std.mem.Allocator,
    log: *logstore.LogStore,
    cache: *logstore.PlaintextCache,
    hash: []const u8,
) ?[]u8 {
    ls_content_reads += 1;
    // The F card carries the 64-hex artifact NAME (§4.7.1 wire form); the
    // store's index is keyed by the binary digest, so the hex resolver is the
    // right door. A full name can never be ambiguous, but the error is handled
    // rather than asserted — a listing must not crash on a damaged store.
    const rid = (log.resolveHexPrefix(hash) catch return null) orelse return null;
    return (log.contentCached(gpa, rid, cache) catch return null) orelse null;
}

/// One blob's plaintext SIZE, without reconstructing it, or null when
/// the header reports no available artifact. Unlike `lsBlobBytes`, this does
/// not prove readability: it never resolves or verifies a delta basis, because
/// every frame kind already carries its plaintext length.
fn lsBlobSize(gpa: std.mem.Allocator, log: *logstore.LogStore, hash: []const u8) ?u64 {
    const rid = (log.resolveHexPrefix(hash) catch return null) orelse return null;
    return (log.plaintextSize(gpa, rid) catch return null) orelse null;
}

/// Maps a `Repository.resolve` failure for `ls` to its diagnostic + exit 1.
fn lsResolveFail(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 ls: check-in '{s}' not found\n", .{name}) catch {};
            cli.horizonNameHint(gpa, repo.io, repo.root_dir, s, "ls");
        },
        error.Ambiguous => s.err.print("zit ls: name '{s}' is ambiguous\n", .{name}) catch {},
        error.OutOfMemory => s.err.writeAll("zit ls: out of memory\n") catch {},
    }
    return .failure;
}

/// Maps a `Repository.files` failure to its diagnostic + exit 1. Closed over
/// `FilesError` so the switch stays exhaustive; the open/content phrasings match
/// the shared `repoOpenFail` text.
fn lsFilesFail(s: cli.Streams, e: Repository.FilesError, tree: *cmd_pull.ElidedTree) cli.Exit {
    switch (e) {
        error.OutOfMemory => s.err.writeAll("zit ls: out of memory\n") catch {},
        error.NotARepo => s.err.writeAll(not_a_repo_msg) catch {},
        error.CannotRead => s.err.writeAll("zit ls: cannot read repository: input/output error\n") catch {},
        error.ImportPending => s.err.writeAll("zit ls: an incremental import is pending; run 'zit import-git --recover DIR'\n") catch {},
        error.Corrupt => s.err.writeAll("zit ls: cannot read repository: repository is corrupt\n") catch {},
        error.NotManifest => s.err.writeAll("zit ls: not a check-in\n") catch {},
        error.BaselineUnresolvable => s.err.writeAll("zit ls: cannot resolve the baseline of a delta check-in\n") catch {},
        error.ElidedByCone => tree.note(s, "ls"),
    }
    return .failure;
}

fn lsNoCheckout(s: cli.Streams) cli.Exit {
    s.err.writeAll("zit ls: no check-in to list (the working checkout is unborn); name a version\n") catch {};
    return .failure;
}

fn lsMissingContent(s: cli.Streams) cli.Exit {
    s.err.writeAll("zit ls: check-in content is missing\n") catch {};
    return .failure;
}