Skip to content
zit Artifact [4807822ad6]
Login

Artifact [4807822ad6]

Artifact 4807822ad6f8cb59fdfbfa4b978f86523d359cc51e0a3171b5765758c6c80a2d:


//! `zit init`: create an empty repository and its checkout. `clone` lays down
//! its destination through the same function.

const std = @import("std");
const zit = @import("zit");
const cli = zit.cli;
const artifact = zit.artifact;
const checkout = zit.checkout;
const logstore = zit.logstore;
const storage = zit.storage;
const diagnostics = @import("../cli/diagnostics.zig");
const help_pages = @import("../cli/help.zig");

/// `zit init [-q|--quiet] [--] [directory]` — the thin wiring: parse, resolve
/// an absolute target, then drive the existing library sequence (create `.zit`,
/// `LogStore.open`/`commit`/`deinit`, `checkout.write`). Filesystem access is
/// confined to this function. All-or-nothing: any failure after `.zit` is
/// created rolls it back so a failed init never poisons the already-exists
/// guard (B-init-9). (contracts/init.md B-init-1..12.)
pub fn runInit(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
) cli.Exit {
    // 1. Parse (B-init-1). Usage errors → exit 2 (B-init-10).
    const parsed = switch (cli.parseInitArgs(verb_args)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "init", .unknown_option, tok),
        .extra_argument => |tok| return cli.usageError(streams, "init", .extra_argument, tok),
    };
    // --help wins over every effect (B-init-11).
    if (parsed.help) {
        streams.out.writeAll(help_pages.init_help) catch {};
        return .ok;
    }
    // draft-fossil-submanifests-00 §6.3: the operator supplies k. With no
    // check-in there is nothing to select it from, so it is never chosen here.
    const submanifest_k: ?u8 = if (parsed.submanifest) |tok| blk: {
        const k = std.fmt.parseInt(u8, tok, 10) catch null;
        if (k == null or !zit.submanifest.inRange(k.?)) {
            streams.err.print("zit init: --submanifest takes k from {d} to {d} (got '{s}')\n", .{ zit.artifact.min_k, zit.artifact.max_k, tok }) catch {};
            return .usage;
        }
        break :blk k.?;
    } else null;

    // 2. Resolve an absolute target directory and repo path (B-init-2/5/12).
    //    `resolve` normalizes `.`/`..` and, when `dir_arg` is already
    //    absolute, ignores the cwd — yielding a stable, parseable success token.
    const dir_arg = parsed.directory orelse ".";
    // Uses the grow-buffer helper (not std's `currentPathAlloc`, which aborts on
    // a cwd deeper than the platform PATH_MAX). A cwd we cannot name is reported
    // honestly, never a crash.
    const cwd = (cli.currentPathAlloc(arena, io) catch |e|
        return renderStorage(streams, dir_arg, diagnostics.reasonOf(e))) orelse
        return renderStorage(streams, dir_arg, "cannot determine the current directory");
    const abs_dir = std.fs.path.resolve(arena, &.{ cwd, dir_arg }) catch |e|
        return renderStorage(streams, dir_arg, diagnostics.reasonOf(e));
    const abs_zit = std.fs.path.join(arena, &.{ abs_dir, zit.repo_filename }) catch |e|
        return renderStorage(streams, abs_dir, diagnostics.reasonOf(e));

    // 3. Ensure the target directory exists (B-init-5); a file in the way is
    //    "not a directory" (B-init-8).
    const cwd_dir = std.Io.Dir.cwd();
    cwd_dir.createDirPath(io, abs_dir) catch |e| switch (e) {
        error.NotDir => return renderNotDir(streams, abs_dir),
        else => return renderStorage(streams, abs_dir, diagnostics.reasonOf(e)),
    };

    // 4. Open a handle to the target dir; all subsequent file ops go through it
    //    so `.zit`/`.zit-checkout` land in the resolved directory.
    var target = cwd_dir.openDir(io, abs_dir, .{}) catch |e| switch (e) {
        error.NotDir => return renderNotDir(streams, abs_dir),
        else => return renderStorage(streams, abs_dir, diagnostics.reasonOf(e)),
    };
    defer target.close(io);

    // 5. Create `.zit` exclusively — this defines the "already exists" error
    //    out of existence (no separate stat probe, no TOCTOU). Detection is
    //    precisely the presence of `.zit`; an orphan `.zit-checkout` is
    //    irrelevant (B-init-7).
    var file = target.createFile(io, zit.repo_filename, .{ .read = true, .exclusive = true }) catch |e| switch (e) {
        error.PathAlreadyExists => return renderAlreadyExists(streams, abs_zit),
        error.IsDir, error.NotDir => return renderNotDir(streams, abs_zit),
        else => return renderStorage(streams, abs_dir, diagnostics.reasonOf(e)),
    };

    // 6. Default hash policy (B-init-3): a fresh repo with no SHA-named
    //    artifacts is SHA3-256 (`.sha3` = 2). Threaded opaquely into the header.
    const hash_kind: u8 = @backingInt(zit.artifact.defaultPolicy(false, false));

    // 7. Log lifecycle (B-init-2): `open` on the empty file writes the 64-byte
    //    header (zero frames); `commit` fsyncs it (durability before success).
    //    On any failure, close and roll back `.zit` (B-init-9).
    var fs = storage.FileStorage.init(io, file, 0);
    var log = logstore.LogStore.open(gpa, fs.storageFile(), hash_kind) catch |e| {
        file.close(io);
        target.deleteFile(io, zit.repo_filename) catch {};
        return renderStorage(streams, abs_dir, diagnostics.reasonOf(e));
    };
    // §9.1 — give the repository a stable, unique project code (sync §9.1:
    // `projectcode = artifact-hash`). Derived deterministically from the
    // repo's absolute path — reproducible, distinct per repository, and with
    // no ambient RNG (the determinism seam). Persisted as repo config so
    // `serve` emits it in the clone reply's `push` card and a clone adopts it.
    const project_code = zit.sync.deriveProjectCode(&.{abs_zit});
    log.putConfig(.{
        .hash_policy = hash_kind,
        .default_branch = "trunk",
        .project_id = "",
        .project_code = &project_code,
        .enable_submanifests = submanifest_k != null,
        .submanifest_k = submanifest_k orelse 0,
    }) catch |e| {
        log.deinit(gpa);
        file.close(io);
        target.deleteFile(io, zit.repo_filename) catch {};
        return renderStorage(streams, abs_dir, diagnostics.reasonOf(e));
    };
    log.commit() catch |e| {
        log.deinit(gpa);
        file.close(io);
        target.deleteFile(io, zit.repo_filename) catch {};
        return renderStorage(streams, abs_dir, diagnostics.reasonOf(e));
    };
    log.deinit(gpa);
    file.close(io);

    // 8. Checkout record (B-init-2/4): trunk unborn (`version == ""`).
    //    `checkout.write` is itself atomic, so a partial record is impossible;
    //    on failure roll back `.zit` (B-init-9).
    checkout.write(io, target, .{ .version = "", .branch = "trunk", .merge_parent = "", .special_op = "", .manifest_flags = "" }) catch |e| {
        target.deleteFile(io, zit.repo_filename) catch {};
        return renderStorage(streams, abs_dir, diagnostics.reasonOf(e));
    };

    // 9. Success feedback (B-init-2/6/12): a single plain-ASCII line whose
    //    trailing whitespace-delimited token is the absolute `.zit` path;
    //    `-q`/`--quiet` writes nothing.
    if (!parsed.quiet) {
        streams.out.print("Initialized empty zit repository in {s}\n", .{abs_zit}) catch {};
        if (submanifest_k) |k| streams.out.print("sub-manifests on (submanifest-k pinned to {d})\n", .{k}) catch {};
    }
    return .ok;
}

// --- educating diagnostics (all to err, all exit 1) -----------------------

fn renderAlreadyExists(s: cli.Streams, abs_zit: []const u8) cli.Exit {
    s.err.print("zit: a zit repository already exists at {s}\n", .{abs_zit}) catch {};
    return .failure;
}

fn renderNotDir(s: cli.Streams, path: []const u8) cli.Exit {
    s.err.print("zit: cannot initialize: {s} is not a directory\n", .{path}) catch {};
    return .failure;
}

pub fn renderStorage(s: cli.Streams, abs_dir: []const u8, reason: []const u8) cli.Exit {
    s.err.print("zit: cannot initialize repository at {s}: {s}\n", .{ abs_dir, reason }) catch {};
    return .failure;
}