Skip to content
zit Artifact [b5465dcec0]
Login

Artifact [b5465dcec0]

Artifact b5465dcec03dce3725efd530d56d2b552917646ea68d224696c41ceb4185da32:


const std = @import("std");
const File = std.Io.File;
const support = @import("support.zig");
const addManaged = support.addManaged;
const corruptSection = support.corruptSection;
const expectExit = support.expectExit;
const expectExitDiag = support.expectExitDiag;
const fileExists = support.fileExists;
const freeResult = support.freeResult;
const initRepo = support.initRepo;
const readFile = support.readFile;
const runShell = support.runShell;
const runZit = support.runZit;
const sectionExists = support.sectionExists;
const touch = support.touch;
const writeFile = support.writeFile;
const writeNestedCheckouts = support.writeNestedCheckouts;

test "cli clean: a nested zit or fossil checkout is left alone" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try writeNestedCheckouts(gpa, io, tmp.dir);

    {
        var res = try runZit(gpa, io, tmp.dir, &.{ "clean", "--dry-run" });
        defer freeResult(gpa, &res);
        try expectExitDiag(res.term, 0, res);
        try std.testing.expectEqualStrings("a.txt\njunk/j.c\nsub/s.txt\n", res.stdout);
    }
    {
        var res = try runZit(gpa, io, tmp.dir, &.{ "clean", "--force", "--emptydirs", "--dotfiles" });
        defer freeResult(gpa, &res);
        try expectExitDiag(res.term, 0, res);
    }
    try std.testing.expect(!fileExists(io, tmp.dir, "a.txt"));
    try std.testing.expect(!fileExists(io, tmp.dir, "junk/j.c"));
    try std.testing.expect(!fileExists(io, tmp.dir, "sub/s.txt"));
    for ([_][]const u8{
        "vendor/lib/lib.c",
        "vendor/lib/.zit",
        "vendor/lib/.zit-checkout",
        "vendor/fsl/f.c",
        "vendor/fsl/.fslckout",
    }) |path| try std.testing.expect(fileExists(io, tmp.dir, path));
}

// ==========================================================================
// `zit clean` (contracts/clean.md, B-clean-1..18). The destructive companion to
// `extras`: it consumes the SAME sweep unchanged and adds deletion, gated behind
// `--force`. Each test drives the real binary; expected bytes come from the
// clause text and the settled help/refusal strings, never from running fossil.
// ==========================================================================

/// The verbatim `zit clean` help — an independent transcription of `main.zig`'s
/// `clean_help` (B-clean-12/cli-help-verbatim-stdout-exit-0), so a drift between
/// the two is caught here.
const clean_help_expected =
    \\usage: zit clean [-n|--dry-run] [-f|--force] [--emptydirs] [--dotfiles]
    \\
    \\Delete every file in the checkout that zit is not tracking — the same set
    \\`zit extras` lists. This is destructive and cannot be undone: `zit undo` does
    \\not recover a clean.
    \\
    \\By default clean refuses and deletes nothing: it reports how many untracked
    \\files would be deleted and stops. Pass --force to delete them, or --dry-run to
    \\preview the exact list first. clean never prompts.
    \\
    \\Files matching the `clean-glob` setting are the exception: the setting has
    \\already declared them disposable, so they are deleted without --force and the
    \\run says how many went. `keep-glob` wins over `clean-glob`, and --dry-run
    \\still deletes nothing.
    \\
    \\Tracked files and zit's control files are never touched, and names beginning
    \\with a dot are left alone unless --dotfiles is given, the files zit reads
    \\from the tree (.zitignore, .fossil-settings/ and the like) included, even
    \\though extras lists those. Only files are deleted;
    \\directories left empty stay unless --emptydirs is given, and a directory the
    \\`empty-dirs` setting names is never removed.
    \\
    \\options:
    \\  -n, --dry-run list what would be deleted, one path per line; delete nothing
    \\  -f, --force   delete the untracked files
    \\      --emptydirs
    \\                also remove the directories the deletions leave empty
    \\      --dotfiles
    \\                also consider names beginning with a dot (also settable
    \\                with `zit settings dotfiles on`)
    \\  -h, --help    show this help and exit
    \\
    \\If both --dry-run and --force are given, --dry-run wins and nothing is deleted.
    \\
    \\exit status:
    \\  0  nothing to delete, a --dry-run preview, or every file deleted
    \\  1  refused (no --force), a file could not be deleted, or not a zit repository
    \\  2  usage error (an unknown option or an unexpected argument)
    \\
;

/// The verbatim B-clean-1 refusal, naming a plural count of extras.
const clean_refuse_three =
    "zit clean: 3 untracked files would be deleted; refusing without --force\n" ++
    "run 'zit clean --dry-run' to preview, or 'zit clean --force' to delete\n";

test "cli clean B-clean-1: no flags with extras present refuses, exit 1, names the count, deletes nothing" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    for ([_][]const u8{ "zebra", "apple", "mango" }) |name| try touch(io, tmp.dir, name);

    var res = try runZit(gpa, io, tmp.dir, &.{"clean"});
    defer freeResult(gpa, &res);
    try expectExit(res.term, 1);
    // The gate: stdout stays empty; the two-line refusal (count + pointers) is on
    // stderr; and every extra is still on disk (nothing was deleted).
    try std.testing.expectEqualStrings("", res.stdout);
    try std.testing.expectEqualStrings(clean_refuse_three, res.stderr);
    for ([_][]const u8{ "zebra", "apple", "mango" }) |name|
        try std.testing.expect(fileExists(io, tmp.dir, name));
}

test "cli clean B-clean-2: the refusal is non-interactive — stdin closed behaves identically" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    for ([_][]const u8{ "zebra", "apple", "mango" }) |name| try touch(io, tmp.dir, name);

    // stdin redirected from /dev/null: clean never reads it, never prompts — the
    // output is byte-identical to the plain B-clean-1 run.
    var res = try runShell(gpa, io, tmp.dir, "\"$ZIT\" clean < /dev/null");
    defer freeResult(gpa, &res);
    try expectExit(res.term, 1);
    try std.testing.expectEqualStrings("", res.stdout);
    try std.testing.expectEqualStrings(clean_refuse_three, res.stderr);
    for ([_][]const u8{ "zebra", "apple", "mango" }) |name|
        try std.testing.expect(fileExists(io, tmp.dir, name));
}

test "cli clean B-clean-3: --dry-run previews to stdout, exit 0, leaving the tree byte-identical" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    for ([_][]const u8{ "zebra", "apple", "mango" }) |name| try touch(io, tmp.dir, name);

    var res = try runZit(gpa, io, tmp.dir, &.{ "clean", "--dry-run" });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    try std.testing.expectEqualStrings("apple\nmango\nzebra\n", res.stdout);
    try std.testing.expectEqualStrings("", res.stderr);
    // --dry-run deletes nothing (B-clean-3): every file is still present.
    for ([_][]const u8{ "zebra", "apple", "mango" }) |name|
        try std.testing.expect(fileExists(io, tmp.dir, name));
}

test "cli clean B-clean-4: the --dry-run preview is byte-identical to `zit extras`" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    for ([_][]const u8{ "zebra", "apple", "mango" }) |name| try touch(io, tmp.dir, name);

    var dry = try runZit(gpa, io, tmp.dir, &.{ "clean", "--dry-run" });
    defer freeResult(gpa, &dry);
    var ext = try runZit(gpa, io, tmp.dir, &.{"extras"});
    defer freeResult(gpa, &ext);
    try expectExit(dry.term, 0);
    try expectExit(ext.term, 0);
    // Same paths, same order, same form — clean and extras share the ONE sweep.
    try std.testing.expectEqualStrings(ext.stdout, dry.stdout);
    try std.testing.expectEqualStrings("apple\nmango\nzebra\n", dry.stdout);
}

test "cli clean B-clean-5: --force deletes exactly the extras set, exit 0, tracked and control survive" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    try touch(io, tmp.dir, "keep");
    try touch(io, tmp.dir, "loose1");
    try touch(io, tmp.dir, "loose2");
    try addManaged(gpa, io, tmp.dir, &.{"keep"});

    var res = try runZit(gpa, io, tmp.dir, &.{ "clean", "--force" });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    // Full success is silent on both streams (cli-stream-separation).
    try std.testing.expectEqualStrings("", res.stdout);
    try std.testing.expectEqualStrings("", res.stderr);
    // Exactly the extras set is gone; the tracked file and every control entry
    // remain — untouchable by construction (B-clean-7).
    try std.testing.expect(!fileExists(io, tmp.dir, "loose1"));
    try std.testing.expect(!fileExists(io, tmp.dir, "loose2"));
    try std.testing.expect(fileExists(io, tmp.dir, "keep"));
    try std.testing.expect(fileExists(io, tmp.dir, ".zit"));
    try std.testing.expect(fileExists(io, tmp.dir, ".zit-checkout"));
    try std.testing.expect(sectionExists(gpa, io, tmp.dir, .managed));
}

test "cli clean B-clean-6: --force is idempotent — a subsequent extras lists nothing" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    try touch(io, tmp.dir, "one");
    try touch(io, tmp.dir, "two");

    var first = try runZit(gpa, io, tmp.dir, &.{ "clean", "--force" });
    defer freeResult(gpa, &first);
    try expectExit(first.term, 0);

    // The extras that were deleted are gone and nothing tracked/control became an
    // extra: extras (and a re-run clean --dry-run) over the now-clean tree is empty.
    var ext = try runZit(gpa, io, tmp.dir, &.{"extras"});
    defer freeResult(gpa, &ext);
    try expectExit(ext.term, 0);
    try std.testing.expectEqualStrings("", ext.stdout);

    var again = try runZit(gpa, io, tmp.dir, &.{ "clean", "--dry-run" });
    defer freeResult(gpa, &again);
    try expectExit(again.term, 0);
    try std.testing.expectEqualStrings("", again.stdout);
}

test "cli clean B-clean-7: a tracked file and every control entry survive a --force byte-for-byte" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    {
        var f = try tmp.dir.createFile(io, "tracked", .{});
        defer f.close(io);
        try f.writePositionalAll(io, "PAYLOAD\n", 0);
    }
    try addManaged(gpa, io, tmp.dir, &.{"tracked"});
    try touch(io, tmp.dir, "extra");

    var res = try runZit(gpa, io, tmp.dir, &.{ "clean", "--force" });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);
    try std.testing.expect(!fileExists(io, tmp.dir, "extra"));
    // The tracked file's content is unchanged, and the object store / checkout
    // record / managed list are all intact — clean never re-checks membership.
    const body = try readFile(gpa, io, tmp.dir, "tracked");
    defer gpa.free(body);
    try std.testing.expectEqualStrings("PAYLOAD\n", body);
    try std.testing.expect(fileExists(io, tmp.dir, ".zit"));
    try std.testing.expect(fileExists(io, tmp.dir, ".zit-checkout"));
    try std.testing.expect(sectionExists(gpa, io, tmp.dir, .managed));
}

test "cli clean B-clean-8: an empty extras set is a success no-op for both --force and un-forced" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir); // only the control files exist — no extras

    const invocations = [_][]const []const u8{
        &.{ "clean", "--force" },
        &.{"clean"},
    };
    for (invocations) |argv| {
        var res = try runZit(gpa, io, tmp.dir, argv);
        defer freeResult(gpa, &res);
        // Emptiness is a success, never a refusal: no diagnostic, no count.
        try expectExit(res.term, 0);
        try std.testing.expectEqualStrings("", res.stdout);
        try std.testing.expectEqualStrings("", res.stderr);
    }
}

test "cli clean B-clean-9: partial failure continues siblings, reports the failure, exit 1" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    try touch(io, tmp.dir, "a");
    try tmp.dir.createDirPath(io, "sub");
    try touch(io, tmp.dir, "sub/stuck");

    // Make `sub` non-writable so unlinking `sub/stuck` fails with EACCES, while
    // the sweep can still read `sub` (r-x). `a` (sorted first) deletes cleanly.
    try tmp.dir.setFilePermissions(io, "sub", File.Permissions.fromMode(0o555), .{ .follow_symlinks = false });
    defer tmp.dir.setFilePermissions(io, "sub", File.Permissions.fromMode(0o777), .{ .follow_symlinks = false }) catch {};

    var res = try runZit(gpa, io, tmp.dir, &.{ "clean", "--force" });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 1);
    try std.testing.expectEqualStrings("", res.stdout);
    try std.testing.expectEqualStrings(
        "zit clean: 'sub/stuck': could not delete: permission denied\n",
        res.stderr,
    );

    // Restore write access before the readback so traversal (and cleanup) is
    // unhindered: the deletable sibling `a` is gone, the undeletable one remains.
    try tmp.dir.setFilePermissions(io, "sub", File.Permissions.fromMode(0o777), .{ .follow_symlinks = false });
    try std.testing.expect(!fileExists(io, tmp.dir, "a"));
    try std.testing.expect(fileExists(io, tmp.dir, "sub/stuck"));
}

test "cli clean B-clean-10: exit is 0 on full success and exactly 1 on a partial failure, never 2" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;

    // All deletions succeed → exit 0.
    {
        var tmp = std.testing.tmpDir(.{});
        defer tmp.cleanup();
        try initRepo(gpa, io, tmp.dir);
        try touch(io, tmp.dir, "x");
        var ok = try runZit(gpa, io, tmp.dir, &.{ "clean", "--force" });
        defer freeResult(gpa, &ok);
        try expectExit(ok.term, 0);
    }

    // At least one deletion fails → exit exactly 1 (operation class, not usage 2).
    {
        var tmp = std.testing.tmpDir(.{});
        defer tmp.cleanup();
        try initRepo(gpa, io, tmp.dir);
        try tmp.dir.createDirPath(io, "sub");
        try touch(io, tmp.dir, "sub/stuck");
        try tmp.dir.setFilePermissions(io, "sub", File.Permissions.fromMode(0o555), .{ .follow_symlinks = false });
        defer tmp.dir.setFilePermissions(io, "sub", File.Permissions.fromMode(0o777), .{ .follow_symlinks = false }) catch {};

        var bad = try runZit(gpa, io, tmp.dir, &.{ "clean", "--force" });
        defer freeResult(gpa, &bad);
        try expectExit(bad.term, 1);

        try tmp.dir.setFilePermissions(io, "sub", File.Permissions.fromMode(0o777), .{ .follow_symlinks = false });
    }
}

test "cli clean B-clean-11: --dry-run wins over --force — preview, exit 0, nothing deleted" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    for ([_][]const u8{ "zebra", "apple", "mango" }) |name| try touch(io, tmp.dir, name);

    const invocations = [_][]const []const u8{
        &.{ "clean", "--dry-run", "--force" },
        &.{ "clean", "--force", "--dry-run" },
    };
    for (invocations) |argv| {
        var res = try runZit(gpa, io, tmp.dir, argv);
        defer freeResult(gpa, &res);
        // --dry-run is the safety override: it can never be upgraded into a delete.
        try expectExit(res.term, 0);
        try std.testing.expectEqualStrings("apple\nmango\nzebra\n", res.stdout);
        for ([_][]const u8{ "zebra", "apple", "mango" }) |name|
            try std.testing.expect(fileExists(io, tmp.dir, name));
    }
}

test "cli clean B-clean-12: -h/--help print verbatim help to stdout, exit 0, help wins and deletes nothing" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    try touch(io, tmp.dir, "extra");

    // Help wins over a trailing invalid token, an unknown option, and --force.
    const invocations = [_][]const []const u8{
        &.{ "clean", "--help" },
        &.{ "clean", "-h" },
        &.{ "clean", "--help", "foo" },
        &.{ "clean", "-h", "--all" },
        &.{ "clean", "--force", "--help" },
    };
    for (invocations) |argv| {
        var res = try runZit(gpa, io, tmp.dir, argv);
        defer freeResult(gpa, &res);
        try expectExit(res.term, 0);
        try std.testing.expectEqualStrings(clean_help_expected, res.stdout);
        try std.testing.expectEqualStrings("", res.stderr);
        // Help never sweeps and never deletes (B-clean-12).
        try std.testing.expect(fileExists(io, tmp.dir, "extra"));
    }
}

test "cli clean B-clean-13: an unknown option is a usage error, exit 2, stderr, empty stdout" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    // `-f` and `-n` are the --force/--dry-run aliases; these are not options.
    inline for (.{ "--all", "-0", "-x", "--emptydir" }) |flag| {
        var res = try runZit(gpa, io, tmp.dir, &.{ "clean", flag });
        defer freeResult(gpa, &res);
        try expectExit(res.term, 2);
        try std.testing.expectEqualStrings("", res.stdout);
        const expected = try std.fmt.allocPrint(
            gpa,
            "zit clean: unknown option '{s}'\ntry 'zit clean --help'\n",
            .{flag},
        );
        defer gpa.free(expected);
        try std.testing.expectEqualStrings(expected, res.stderr);
    }
}

test "cli clean B-clean-14: a positional or a token after -- is a usage error, exit 2, stderr" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);

    const Case = struct { argv: []const []const u8, token: []const u8 };
    const cases = [_]Case{
        .{ .argv = &.{ "clean", "foo" }, .token = "foo" },
        .{ .argv = &.{ "clean", "--", "foo" }, .token = "foo" },
        .{ .argv = &.{ "clean", "--", "--force" }, .token = "--force" },
    };
    for (cases) |c| {
        var res = try runZit(gpa, io, tmp.dir, c.argv);
        defer freeResult(gpa, &res);
        try expectExit(res.term, 2);
        try std.testing.expectEqualStrings("", res.stdout);
        const expected = try std.fmt.allocPrint(
            gpa,
            "zit clean: unexpected argument '{s}'\ntry 'zit clean --help'\n",
            .{c.token},
        );
        defer gpa.free(expected);
        try std.testing.expectEqualStrings(expected, res.stderr);
    }
}

test "cli clean B-clean-15: outside a repository, exit 1, not_a_repo on stderr, empty stdout" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try touch(io, tmp.dir, "a"); // a file, but no repo anywhere above

    // The repository check precedes any sweep, regardless of --force/--dry-run.
    const invocations = [_][]const []const u8{
        &.{"clean"},
        &.{ "clean", "--force" },
        &.{ "clean", "--dry-run" },
    };
    for (invocations) |argv| {
        var res = try runZit(gpa, io, tmp.dir, argv);
        defer freeResult(gpa, &res);
        try expectExit(res.term, 1);
        try std.testing.expectEqualStrings("", res.stdout);
        try std.testing.expectEqualStrings(
            "zit: no zit checkout here (looked for .zit-checkout in this directory and its parents)\n" ++
                "if this is a bare repository, name it with -R, or run 'zit open' to create a working tree\n",
            res.stderr,
        );
    }
}

test "cli clean B-clean-16: a corrupt .zit-managed fails cleanly BEFORE any deletion, exit 1" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    try touch(io, tmp.dir, "extra");
    try corruptSection(io, tmp.dir, .managed);

    // Even with --force, a tracked set that cannot be read is a tree clean must
    // not touch: nothing is deleted (the extra is still on disk).
    var res = try runZit(gpa, io, tmp.dir, &.{ "clean", "--force" });
    defer freeResult(gpa, &res);
    try expectExit(res.term, 1);
    try std.testing.expectEqualStrings("", res.stdout);
    try std.testing.expectEqualStrings(
        "zit clean: cannot read tracked files: .zit-checkout is corrupt\n",
        res.stderr,
    );
    try std.testing.expect(fileExists(io, tmp.dir, "extra"));
}

test "cli clean B-clean-17: `zit clean --dry-run >> log` appends, rows to stdout (O_APPEND honored)" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    try touch(io, tmp.dir, "g1");

    // The shell creates `log` (itself now an untracked file) BEFORE clean runs, so
    // the preview lists both `g1` and `log`; appending must preserve the
    // pre-existing line. ASCII: `g1` < `log`.
    var res = try runShell(gpa, io, tmp.dir, "printf 'PRE-EXISTING-LINE\\n' > log; \"$ZIT\" clean --dry-run >> log");
    defer freeResult(gpa, &res);
    try expectExit(res.term, 0);

    const log = try readFile(gpa, io, tmp.dir, "log");
    defer gpa.free(log);
    try std.testing.expectEqualStrings("PRE-EXISTING-LINE\ng1\nlog\n", log);
}

test "cli clean B-clean-18: over a deep nested tree --dry-run equals extras and --force deletes that exact set" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    try tmp.dir.createDirPath(io, "x/y/z");
    try touch(io, tmp.dir, "x/y/z/deep");
    try touch(io, tmp.dir, "top");

    // The ONE shared sweep, bounds included: preview equals extras and equals the
    // derived ascending listing ("top" < "x/y/z/deep").
    var ext = try runZit(gpa, io, tmp.dir, &.{"extras"});
    defer freeResult(gpa, &ext);
    var dry = try runZit(gpa, io, tmp.dir, &.{ "clean", "--dry-run" });
    defer freeResult(gpa, &dry);
    try expectExit(dry.term, 0);
    try std.testing.expectEqualStrings(ext.stdout, dry.stdout);
    try std.testing.expectEqualStrings("top\nx/y/z/deep\n", dry.stdout);

    // --force deletes exactly that set; a subsequent extras lists nothing.
    var force = try runZit(gpa, io, tmp.dir, &.{ "clean", "--force" });
    defer freeResult(gpa, &force);
    try expectExit(force.term, 0);
    try std.testing.expect(!fileExists(io, tmp.dir, "top"));
    try std.testing.expect(!fileExists(io, tmp.dir, "x/y/z/deep"));

    var after = try runZit(gpa, io, tmp.dir, &.{"extras"});
    defer freeResult(gpa, &after);
    try expectExit(after.term, 0);
    try std.testing.expectEqualStrings("", after.stdout);
}

test "cli clean B-clean-12: 'clean' is listed in the command help and suggested for a near-miss" {
    // The verb joins the single-source Verb enum, so the command list names it,
    // `zit help clean` routes to the verb's own verbatim help (B-clean-12), and
    // the did-you-mean suggester finds a near-miss.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();

    var help = try runZit(gpa, io, tmp.dir, &.{"help"});
    defer freeResult(gpa, &help);
    try expectExit(help.term, 0);
    try std.testing.expect(std.mem.indexOf(u8, help.stdout, "clean") != null);

    var topic = try runZit(gpa, io, tmp.dir, &.{ "help", "clean" });
    defer freeResult(gpa, &topic);
    try expectExit(topic.term, 0);
    try std.testing.expectEqualStrings(clean_help_expected, topic.stdout);

    var typo = try runZit(gpa, io, tmp.dir, &.{"cleen"});
    defer freeResult(gpa, &typo);
    try expectExit(typo.term, 2);
    try std.testing.expect(std.mem.indexOf(u8, typo.stderr, "did you mean 'clean'?") != null);
}

test "cli clean: clean-glob deletes, the remainder still refuses" {
    // fossil's clean removes a clean-glob match without prompting (checkin.c
    // skips the prompt for it) and prompts for everything else. zit has no
    // prompt: the glob-matched files go, the rest keeps today's refusal, and
    // the note about what WAS deleted precedes the refusal so the output can
    // never read as if nothing happened.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    try tmp.dir.createDir(io, ".fossil-settings", .default_dir);
    try writeFile(io, tmp.dir, ".fossil-settings/clean-glob", "*.o\n");
    try writeFile(io, tmp.dir, "x.o", "object\n");
    try writeFile(io, tmp.dir, "notes.txt", "keep me\n");

    var c = try runZit(gpa, io, tmp.dir, &.{"clean"});
    defer freeResult(gpa, &c);
    try expectExit(c.term, 1);
    try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(io, "x.o", .{}));
    try std.testing.expect(fileExists(io, tmp.dir, "notes.txt"));
    const note = std.mem.indexOf(u8, c.stderr, "deleted by clean-glob") orelse
        return error.MissingCleanGlobNote;
    const refusal = std.mem.indexOf(u8, c.stderr, "refusing without --force") orelse
        return error.MissingRefusal;
    try std.testing.expect(note < refusal);
}

test "cli clean: keep-glob wins over clean-glob" {
    // fossil tests keep-glob first and `continue`s, so a file in both lists is
    // KEPT. The preview shows both candidates and deletes neither.
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    try tmp.dir.createDir(io, ".fossil-settings", .default_dir);
    try writeFile(io, tmp.dir, ".fossil-settings/clean-glob", "*.o\n");
    try writeFile(io, tmp.dir, ".fossil-settings/keep-glob", "keep.o\n");
    try writeFile(io, tmp.dir, "keep.o", "protected\n");
    try writeFile(io, tmp.dir, "x.o", "object\n");
    try writeFile(io, tmp.dir, "notes.txt", "keep me\n");

    // --dry-run deletes nothing at all, clean-glob match included.
    var dry = try runZit(gpa, io, tmp.dir, &.{ "clean", "--dry-run" });
    defer freeResult(gpa, &dry);
    try expectExitDiag(dry.term, 0, dry);
    try std.testing.expectEqualStrings("notes.txt\nx.o\n", dry.stdout);
    try std.testing.expect(fileExists(io, tmp.dir, "x.o"));

    var c = try runZit(gpa, io, tmp.dir, &.{"clean"});
    defer freeResult(gpa, &c);
    try expectExit(c.term, 1);
    try std.testing.expect(fileExists(io, tmp.dir, "keep.o"));
    try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(io, "x.o", .{}));
    try std.testing.expect(fileExists(io, tmp.dir, "notes.txt"));

    // --force takes the remainder and still never takes the kept file.
    var f = try runZit(gpa, io, tmp.dir, &.{ "clean", "--force" });
    defer freeResult(gpa, &f);
    try expectExitDiag(f.term, 0, f);
    try std.testing.expect(fileExists(io, tmp.dir, "keep.o"));
    try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(io, "notes.txt", .{}));
}

test "cli clean: --emptydirs prunes what clean-glob emptied, and spares an empty-dirs name" {
    const gpa = std.testing.allocator;
    const io = std.testing.io;
    var tmp = std.testing.tmpDir(.{});
    defer tmp.cleanup();
    try initRepo(gpa, io, tmp.dir);
    try tmp.dir.createDir(io, ".fossil-settings", .default_dir);
    try writeFile(io, tmp.dir, ".fossil-settings/clean-glob", "*.o\n");
    try tmp.dir.createDir(io, "build", .default_dir);
    try writeFile(io, tmp.dir, "build/x.o", "object\n");
    try writeFile(io, tmp.dir, "notes.txt", "keep me\n");

    // The directory pass runs even though the run ends in a refusal: fossil
    // gates it on the flag alone, after the file pass, whatever was answered.
    var c = try runZit(gpa, io, tmp.dir, &.{ "clean", "--emptydirs" });
    defer freeResult(gpa, &c);
    try expectExit(c.term, 1);
    try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(io, "build/x.o", .{}));
    try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(io, "build", .{}));
    try std.testing.expect(fileExists(io, tmp.dir, "notes.txt"));

    // With the name listed in empty-dirs the directory stands, because the
    // project asked for it to exist with nothing in it.
    try writeFile(io, tmp.dir, ".fossil-settings/empty-dirs", "build\n");
    try tmp.dir.createDir(io, "build", .default_dir);
    try writeFile(io, tmp.dir, "build/x.o", "object\n");
    var c2 = try runZit(gpa, io, tmp.dir, &.{ "clean", "--emptydirs" });
    defer freeResult(gpa, &c2);
    try expectExit(c2.term, 1);
    try std.testing.expectError(error.FileNotFound, tmp.dir.statFile(io, "build/x.o", .{}));
    var d = try tmp.dir.openDir(io, "build", .{});
    d.close(io);
}