Skip to content
zit Artifact [7a6433ef20]
Login

Artifact [7a6433ef20]

Artifact 7a6433ef207e47727960a6599489d4f124db753f74dc48ebdbbc65f625a6ef1a:


const std = @import("std");
const cli = @import("zit").cli;
const support = @import("support.zig");
const expectContains = support.expectContains;
const expectExit = support.expectExit;
const expectExitDiag = support.expectExitDiag;
const freeResult = support.freeResult;
const runZit = support.runZit;

test "cli help: sync, pull and exit-codes document the fork exit status and -F json" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    for ([_][]const u8{ "sync", "pull" }) |verb| {
        var res = try runZit(gpa, io, tmp.dir, &.{ "help", verb });
        defer freeResult(gpa, &res);
        try expectExitDiag(res.term, 0, res);
        try expectContains(res.stdout, "-F json");
        try expectContains(res.stdout, "  9  ");
        try expectContains(res.stdout, "fork on BRANCH: N leaves");
    }
    var codes = try runZit(gpa, io, tmp.dir, &.{ "help", "exit-codes" });
    defer freeResult(gpa, &codes);
    try expectExitDiag(codes.term, 0, codes);
    try expectContains(codes.stdout, "  sync, pull\n          9 = ");
}

// --- help audit -----------------------------------------------------------

/// Whether `help` lists `verb` as a command entry — an indented line whose
/// first token is exactly `verb`. Column-anchored on purpose: a bare substring
/// match would pass vacuously when a verb NAME shows up only inside another
/// verb's prose (e.g. "sync" in serve's one-liner, or "stat" inside "status"),
/// so a dropped command line would slip through unnoticed. Indent-width
/// agnostic — it keys on "leading whitespace, then the verb, then a space".
fn helpListsVerb(help: []const u8, verb: []const u8) bool {
    var lines = std.mem.splitScalar(u8, help, '\n');
    while (lines.next()) |line| {
        const body = std.mem.trimStart(u8, line, " ");
        if (body.len == line.len) continue; // no indent → a heading, not an entry
        if (std.mem.startsWith(u8, body, verb) and
            body.len > verb.len and body[verb.len] == ' ')
        {
            return true;
        }
    }
    return false;
}
/// Converts a Zig enum tag into its public CLI spelling. Command words use
/// hyphens, while Zig enum identifiers use underscores.
fn publicVerbName(tag: []const u8, buffer: []u8) []const u8 {
    std.debug.assert(buffer.len >= tag.len);
    for (tag, 0..) |byte, i| {
        buffer[i] = if (byte == '_') '-' else byte;
    }
    return buffer[0..tag.len];
}

test "cli help audit: 'zit help' names every dispatched verb (anti-rot guard)" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    var res = try runZit(gpa, io, tmp.dir, &.{"help"});
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);

    // Structural pin: the candidate set is the dispatched `Verb` enum itself,
    // not a hand-copied list, so a verb added to the dispatcher without a help
    // line fails HERE rather than shipping undiscoverable. `.unknown` is the
    // catch-all sentinel — never a command — so it is the sole exclusion.
    inline for (comptime std.enums.values(cli.Verb)) |v| {
        if (v == .unknown) continue;
        // Plumbing exemption: machine verbs are dispatched but
        // deliberately unlisted — another process is their audience, and the
        // porcelain a person browses should not offer them. Their own help
        // and `zit help <verb>` stay pinned by the e2e, so "unlisted"
        // can never rot into "undocumented".
        if (v == .wiki or v == .ticket or v == .forum or v == .technote or v == .attach) continue;
        var public_verb_buffer: [@tagName(v).len]u8 = undefined;
        const public_verb = publicVerbName(@tagName(v), &public_verb_buffer);
        if (!helpListsVerb(res.stdout, public_verb)) {
            std.debug.print(
                "dispatched verb '{s}' is absent from 'zit help' output\n",
                .{public_verb},
            );
            return error.VerbMissingFromHelp;
        }
    }
}

test "cli help topics: names/sparse/repo/exit-codes/options answer, typos refuse, verbs fall back" {
    // Goal: the help-topic surface. Each topic prints its own text on
    // stdout (exit 0); a token that is neither verb nor topic refuses with
    // exit 2 and a diagnostic on stderr; a real verb without dedicated help
    // (version) keeps the command-list fallback; the top-level help lists
    // the topics.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const topics = [_]struct { name: []const u8, marker: []const u8 }{
        .{ .name = "names", .marker = "how a check-in name resolves" },
        .{ .name = "sparse", .marker = "sparse checkouts and sparse stores" },
        .{ .name = "repo", .marker = "without a working tree" },
        .{ .name = "exit-codes", .marker = "the exit-status contract" },
        .{ .name = "options", .marker = "end-of-options marker" },
    };
    for (topics) |t| {
        var res = try runZit(gpa, io, tmp.dir, &.{ "help", t.name });
        defer freeResult(gpa, &res);
        try expectExitDiag(res.term, 0, res);
        try std.testing.expect(std.mem.indexOf(u8, res.stdout, t.marker) != null);
        try std.testing.expectEqualStrings("", res.stderr);
    }

    // The names topic documents the timestamp forms (the drift fix).
    var names = try runZit(gpa, io, tmp.dir, &.{ "help", "names" });
    defer freeResult(gpa, &names);
    try expectExitDiag(names.term, 0, names);
    try std.testing.expect(std.mem.indexOf(u8, names.stdout, "BRANCH:TIMESTAMP") != null);

    // Every departure a verb's own help states is listed in the topic.
    var codes = try runZit(gpa, io, tmp.dir, &.{ "help", "exit-codes" });
    defer freeResult(gpa, &codes);
    try expectExitDiag(codes.term, 0, codes);
    try expectContains(codes.stdout, "  commit  3 = -R: the edits change nothing; the parent is printed");

    // A typo refuses: exit 2, stderr names it, nothing on stdout.
    var bogus = try runZit(gpa, io, tmp.dir, &.{ "help", "bogus-topic" });
    defer freeResult(gpa, &bogus);
    try expectExit(bogus.term, 2);
    try std.testing.expectEqualStrings("", bogus.stdout);
    try std.testing.expect(std.mem.indexOf(u8, bogus.stderr, "no command or topic named 'bogus-topic'") != null);

    // A real verb with no dedicated help still gets the command list.
    var ver = try runZit(gpa, io, tmp.dir, &.{ "help", "version" });
    defer freeResult(gpa, &ver);
    try expectExitDiag(ver.term, 0, ver);
    try std.testing.expect(std.mem.indexOf(u8, ver.stdout, "commands:") != null);

    // The top-level help advertises the topics.
    var top = try runZit(gpa, io, tmp.dir, &.{"help"});
    defer freeResult(gpa, &top);
    try expectExitDiag(top.term, 0, top);
    try std.testing.expect(std.mem.indexOf(u8, top.stdout, "topics ('zit help TOPIC'):") != null);
}

// ==========================================================================
// The reference's FLAG-level pin.
//
// `src/reference_test.zig` pins that every verb has a section. That is not
// enough, and the gap was not hypothetical: an audit of all 57 verbs found
// `zit pack --drop-elided` — the sparse spec's narrow-then-compact deletion,
// destructive and irreversible — present in the parser, doing real work, and
// named in NO help output at all. The help-topic guard could not see it either, since
// that one checks options-table flags against the usage block and this flag
// was in neither. A verb can be documented while its flags are not.
//
// So this holds each verb's real `--help` against its reference section, both
// directions. It lives in the e2e lane because it needs the help TEXT, which
// only the spawned binary produces.
// ==========================================================================

const reference_doc = @embedFile("reference_doc");

/// The shared conventions block: everything before the first group heading.
/// `-R` and `--no-cache` are documented once there rather than on each of the
/// dozen-plus verbs that accept them, so a flag found there counts as covered.
fn conventionsBlock() []const u8 {
    const end = std.mem.indexOf(u8, reference_doc, "<h2 class=\"grp-head\"") orelse reference_doc.len;
    return reference_doc[0..end];
}

/// One verb's `<section class="cmd" id="...">` body, or null when absent.
fn referenceSection(id: []const u8, buf: []u8) ?[]const u8 {
    const open = std.fmt.bufPrint(buf, "<section class=\"cmd\" id=\"{s}\">", .{id}) catch return null;
    const at = std.mem.indexOf(u8, reference_doc, open) orelse return null;
    const from = at + open.len;
    const to = std.mem.indexOfPos(u8, reference_doc, from, "</section>") orelse return null;
    return reference_doc[from..to];
}

/// A flag token starts at a `-` that is not preceded by a word character, and
/// runs while the bytes stay flag-shaped. Rejects `--` and bare `-`.
fn flagAt(s: []const u8, i: usize) ?[]const u8 {
    if (s[i] != '-') return null;
    if (i > 0 and (std.ascii.isAlphanumeric(s[i - 1]) or s[i - 1] == '-' or s[i - 1] == '_')) return null;
    var j = i;
    while (j < s.len and s[j] == '-') j += 1;
    if (j - i > 2 or j == s.len or !std.ascii.isAlphabetic(s[j])) return null;
    while (j < s.len and (std.ascii.isAlphanumeric(s[j]) or s[j] == '-')) j += 1;
    return s[i..j];
}

fn mentionsFlag(hay: []const u8, flag: []const u8) bool {
    var i: usize = 0;
    while (std.mem.indexOfPos(u8, hay, i, flag)) |hit| {
        i = hit + 1;
        const after = hit + flag.len;
        // A whole token: `--cone` must not satisfy a search for `--cone-not`'s
        // prefix, and vice versa.
        if (after < hay.len and (std.ascii.isAlphanumeric(hay[after]) or hay[after] == '-')) continue;
        if (hit > 0 and (std.ascii.isAlphanumeric(hay[hit - 1]) or hay[hit - 1] == '-')) continue;
        return true;
    }
    return false;
}

test "cli reference: every flag a verb accepts is documented in its section" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const conv = conventionsBlock();
    var missing: usize = 0;
    inline for (comptime std.enums.values(cli.Verb)) |v| {
        if (v != .unknown and v != .help and v != .version) {
            var id_buf: [64]u8 = undefined;
            const tag = @tagName(v);
            @memcpy(id_buf[0..tag.len], tag);
            for (id_buf[0..tag.len]) |*c| {
                if (c.* == '_') c.* = '-';
            }
            const id = id_buf[0..tag.len];

            var res = try runZit(gpa, io, tmp.dir, &.{ id, "--help" });
            defer freeResult(gpa, &res);

            var sec_buf: [96]u8 = undefined;
            // A missing section is reference_test.zig's failure, not this one.
            const section = referenceSection(id, &sec_buf) orelse &[_]u8{};
            // Only the options table: prose legitimately names other verbs'
            // flags, and a usage line repeats what the table already lists.
            const opts_at = std.mem.indexOf(u8, res.stdout, "\noptions:\n") orelse res.stdout.len;
            var rest: []const u8 = if (opts_at == res.stdout.len) &[_]u8{} else res.stdout[opts_at + "\noptions:\n".len ..];
            if (std.mem.indexOf(u8, rest, "\nexit status:")) |stop| rest = rest[0..stop];
            if (section.len == 0) rest = &[_]u8{};

            var lines = std.mem.splitScalar(u8, rest, '\n');
            while (lines.next()) |line| {
                const t = std.mem.trimStart(u8, line, " ");
                if (t.len == 0 or t[0] != '-') continue; // a wrapped description line
                // The flag column ends at the first run of two spaces.
                const col = if (std.mem.indexOf(u8, t, "  ")) |e| t[0..e] else t;
                var k: usize = 0;
                while (k < col.len) {
                    if (flagAt(col, k)) |flag| {
                        k += flag.len;
                        if (std.mem.eql(u8, flag, "-h") or std.mem.eql(u8, flag, "--help")) continue;
                        if (mentionsFlag(section, flag) or mentionsFlag(conv, flag)) continue;
                        std.debug.print(
                            "\nreference pin: `zit {s} {s}` is accepted but www/reference.html's " ++
                                "\"{s}\" section never names it. A flag can ship undocumented while " ++
                                "the verb looks covered -- that is how `pack --drop-elided` stayed " ++
                                "invisible. Document it in the same commit that adds it.\n",
                            .{ id, flag, id },
                        );
                        missing += 1;
                    } else k += 1;
                }
            }
        }
    }
    try std.testing.expectEqual(@as(usize, 0), missing);
}

test "cli reference: every flag the reference documents is one the verb accepts" {
    // The other direction. A reference that promises a flag is worse than one
    // that omits it: the omission is discoverable from `--help`, the promise
    // sends someone looking for something that is not there.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    const conv = conventionsBlock();
    var stale: usize = 0;
    inline for (comptime std.enums.values(cli.Verb)) |v| {
        if (v != .unknown and v != .help and v != .version) {
            var id_buf: [64]u8 = undefined;
            const tag = @tagName(v);
            @memcpy(id_buf[0..tag.len], tag);
            for (id_buf[0..tag.len]) |*c| {
                if (c.* == '_') c.* = '-';
            }
            const id = id_buf[0..tag.len];

            var sec_buf: [96]u8 = undefined;
            const section = referenceSection(id, &sec_buf) orelse &[_]u8{};
            var res = try runZit(gpa, io, tmp.dir, &.{ id, "--help" });
            defer freeResult(gpa, &res);

            // Only `<td class="f">` cells: the flag table is the reference's
            // CLAIM about this verb, while its prose may mention neighbours.
            var scan: usize = 0;
            while (std.mem.indexOfPos(u8, section, scan, "<td class=\"f\">")) |cell| {
                const from = cell + "<td class=\"f\">".len;
                const to = std.mem.indexOfPos(u8, section, from, "</td>") orelse break;
                scan = to;
                const text = section[from..to];
                var k: usize = 0;
                while (k < text.len) {
                    if (flagAt(text, k)) |flag| {
                        k += flag.len;
                        if (mentionsFlag(res.stdout, flag) or mentionsFlag(conv, flag)) continue;
                        std.debug.print(
                            "\nreference pin: www/reference.html's \"{s}\" section documents `{s}`, " ++
                                "which `zit {s} --help` never mentions. Either the flag was removed " ++
                                "and its row outlived it, or the help lost it.\n",
                            .{ id, flag, id },
                        );
                        stale += 1;
                    } else k += 1;
                }
            }
        }
    }
    try std.testing.expectEqual(@as(usize, 0), stale);
}