Skip to content
zit Artifact [12ce4a8446]
Login

Artifact [12ce4a8446]

Artifact 12ce4a844628b198596d8e1f42afe6aa2bf8dac5197d0b6ba2dc1b35576d5bdf:


//! `zit revert`: restore managed files to their content at the current
//! check-in.

const std = @import("std");
const zit = @import("zit");
const cli = @import("zit").cli;
const cmd_sync = @import("sync.zig");
const cmd_tracking = @import("tracking.zig");
const update = @import("zit").update;
const Repository = @import("zit").Repository;
const managed = zit.managed;
const artifact = zit.artifact;
const diagnostics = @import("../diagnostics.zig");
const help_pages = @import("../help.zig");
const managedFail = diagnostics.managedFail;
const repoOpenFail = diagnostics.repoOpenFail;
const not_a_repo_msg = diagnostics.not_a_repo_msg;
const revert_help = help_pages.revert_help;

// ==========================================================================
// `zit revert` — restore managed files to their content at the current
// check-in (artifact §8.4 effective file + §7.2 verified blob). A thin consumer
// of the Repository read path (`fileAt`/`blob`) plus `update.restoreFile`: no
// format work, no managed-set mutation. Content-restore only.
// ==========================================================================

/// `zit revert [PATH...]` — restore managed files to their checked-in content.
/// With no paths, every managed file; with paths, only the named managed files.
pub fn runRevert(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
) cli.Exit {
    const parsed = switch (cli.parseRevertArgs(gpa, verb_args) catch return revertOom(streams)) {
        .ok => |p| p,
        .unknown_option => |tok| return cli.usageError(streams, "revert", .unknown_option, tok),
    };
    defer gpa.free(parsed.paths);
    if (parsed.help) {
        streams.out.writeAll(revert_help) catch {};
        return .ok;
    }
    // A demand fetch has no ambient environment of its own; the stored login
    // still authenticates, and a prompt is never raised from here.
    const amb: cli.Ambient = .{ .now_epoch = 0, .user_env = null };
    var tree: cmd_sync.ElidedTree = .{};
    const rc = revertOnce(gpa, io, arena, parsed, streams, &tree);
    if (!tree.fetch(gpa, io, arena, streams, amb, "revert")) return rc;
    return revertOnce(gpa, io, arena, parsed, streams, &tree);
}

fn revertOnce(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    parsed: cli.RevertArgs,
    streams: cli.Streams,
    tree: *cmd_sync.ElidedTree,
) cli.Exit {
    // Discover the root (its absolute path drives path-scoped `repoRelative`),
    // then open the read-only derived view.
    const root = (cli.discoverRoot(arena, io) catch return revertOom(streams)) orelse {
        streams.err.writeAll(not_a_repo_msg) catch {};
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);
    var repo: Repository = undefined;
    repo.open(gpa, io, root_dir, .{ .mode = .full }) catch |e| return repoOpenFail(streams, "revert", e);
    defer repo.deinit(gpa);

    // §7.5: the current checkout names the check-in whose content is restored;
    // an unborn/absent checkout has nothing to revert to.
    const current = repo.currentCheckoutRid() orelse return revertNoCheckout(streams);
    repo.current_hint = current; // checkout-relative names (prev, current) resolve here too
    // -r restores another check-in's content into this tree without
    // moving the checkout (Fossil's `revert -r`).
    const rid = if (parsed.version) |v| repo.resolve(v, .checkin) catch |e| switch (e) {
        error.NotFound => {
            streams.err.print("zit revert: check-in '{s}' not found\n", .{v}) catch {};
            cli.horizonNameHint(gpa, repo.io, repo.root_dir, streams, "revert");
            return .failure;
        },
        error.Ambiguous => {
            streams.err.print("zit revert: name '{s}' is ambiguous\n", .{v}) catch {};
            return .failure;
        },
        error.OutOfMemory => return revertOom(streams),
    } else current;
    const where: []const u8 = if (parsed.version) |v|
        std.fmt.allocPrint(arena, "check-in '{s}'", .{v}) catch return revertOom(streams)
    else
        "the current check-in";

    // The managed set — read, never written: revert restores content only.
    var set = managed.ManagedSet.read(gpa, io, root_dir) catch |e|
        return managedFail(streams, "revert", e);
    defer set.deinit();

    // Gather the resolved restore targets first, so the undo journal captures
    // every path's pre-revert bytes in ONE seam before the first file is
    // rewritten (B-undo-2/14). Untracked or unresolvable args are reported here
    // and excluded from both the journal image and the restore.
    var targets: std.ArrayList([]const u8) = .empty;
    defer targets.deinit(gpa);
    var had_error = false;

    // The check-in parsed once, as Fossil's revert parses its manifest once
    // and finds each file by binary search (`manifest_file_find`). Null when
    // it cannot be opened -- a tree node this store withholds, say -- and the
    // per-file lookup below then reports what it meets.
    var baseline: cmd_tracking.CheckinBaseline = undefined;
    const have_baseline = if (baseline.open(gpa, io, root_dir, repo.hashOf(rid))) |_| true else |_| false;
    defer if (have_baseline) baseline.deinit(io);

    if (parsed.paths.len == 0) {
        // Fossil's revert first finds what changed (`vfile_check_signature`:
        // size and mtime, hashing only what they cannot clear) and reverts
        // only that; an unchanged file is never read, journaled or rewritten.
        // `status`'s walk is the same scan here.
        if (have_baseline) {
            var sink: RevertScanSink = .{ .gpa = gpa, .targets = &targets };
            cmd_tracking.walkWorkingTree(gpa, io, root_dir, set.iterate(), &baseline.walk, &sink) catch |e| switch (e) {
                error.OutOfMemory => return revertOom(streams),
                error.Storage, error.Corrupt => {
                    targets.clearRetainingCapacity();
                    for (set.iterate()) |path| targets.append(gpa, path) catch return revertOom(streams);
                },
            };
        } else {
            for (set.iterate()) |path| targets.append(gpa, path) catch return revertOom(streams);
        }
    } else {
        const cwd_abs = (cli.currentPathAlloc(arena, io) catch return revertOom(streams)) orelse {
            streams.err.writeAll("zit revert: cannot determine the current directory\n") catch {};
            return .failure;
        };
        for (parsed.paths) |arg| {
            const key = switch (cli.repoRelative(arena, root.abs, cwd_abs, arg) catch return revertOom(streams)) {
                .key => |k| k,
                .root, .outside => {
                    revertNotTracked(streams, arg);
                    had_error = true;
                    continue;
                },
            };
            if (!set.contains(key)) {
                revertNotTracked(streams, key);
                had_error = true;
                continue;
            }
            targets.append(gpa, key) catch return revertOom(streams);
        }
    }

    // Every restore target is a managed path (gathered from the set, or gated on
    // `set.contains` for an explicit arg) — revert never rewrites an untracked file.
    if (std.debug.runtime_safety) {
        for (targets.items) |t| std.debug.assert(set.contains(t));
    }

    // Every target's card at `rid`, looked up before the journal: a run that
    // meets withheld tree nodes returns having written nothing, so the run
    // after the fetch journals the tree as it stands.
    const cards = gpa.alloc(RevertLookup, targets.items.len) catch return revertOom(streams);
    var looked: usize = 0;
    defer {
        for (cards[0..looked]) |c| if (c == .card) Repository.freeFileCard(gpa, c.card);
        gpa.free(cards);
    }
    for (targets.items) |name| {
        if (have_baseline) {
            cards[looked] = if (baseline.findFile(name)) |c| .{ .borrowed = c } else .absent;
            looked += 1;
            continue;
        }
        cards[looked] = if (repo.fileAt(gpa, rid, name)) |found|
            (if (found) |c| .{ .card = c } else .absent)
        else |e| blk: {
            if (e == error.ElidedByCone) {
                tree.note(streams, "revert");
                if (tree.pending) return .failure;
            } else revertFileFail(streams, name, e);
            break :blk .failed;
        };
        looked += 1;
    }

    // Journal-before-mutate (B-undo-3): the undo image is written and fsynced
    // before the first restore. A journal fault aborts with nothing mutated —
    // the durability rule forbids restoring without a recoverable pre-image.
    if (targets.items.len != 0 and !parsed.dry_run) {
        update.journal.record(gpa, io, root_dir, targets.items) catch |e|
            return revertJournalFail(streams, e);
    }

    var reverted: usize = 0;
    for (targets.items, cards) |name, lookup| {
        switch (revertOne(gpa, io, &repo, root_dir, lookup, where, name, parsed.dry_run, streams)) {
            .failed => had_error = true,
            .reverted => reverted += 1,
            .skipped => {},
        }
    }
    if (reverted != 0 and !parsed.dry_run) streams.err.writeAll(" \"zit undo\" is available to undo changes to the working checkout.\n") catch {};
    return if (had_error) .failure else .ok;
}

/// A journal-write failure before revert touches any file — exit 1, nothing
/// mutated. `record` only surfaces `OutOfMemory`/`Storage`; the `else` folds the
/// device faults into the honest I/O message.
fn revertJournalFail(s: cli.Streams, e: update.journal.JournalError) cli.Exit {
    switch (e) {
        error.OutOfMemory => s.err.writeAll("zit revert: out of memory\n") catch {},
        else => s.err.writeAll("zit revert: cannot write the undo journal: input/output error\n") catch {},
    }
    return .failure;
}

/// The per-file revert verdict: content restored, nothing to restore (absent
/// from the effective set — informational, not an error), or a genuine fault.
const RevertOutcome = enum { reverted, skipped, failed };

/// One target's §8.4 lookup at the revert's check-in: its card, absent from
/// the effective set, or a read fault already reported.
/// `borrowed` points into the revert's open `CheckinBaseline` and is not
/// freed; `card` is the revert's own copy.
const RevertLookup = union(enum) { card: artifact.FCard, borrowed: artifact.FCard, absent, failed };

/// Restore one managed file `name` to its content at the revert's check-in,
/// given its §8.4 effective `lookup`: a file absent from the effective set
/// (never present, or a §4.7.6 delete marker) has no content to restore —
/// reported and left unchanged, never fabricated (`.skipped`). A read/write
/// fault is `.failed`.
fn revertOne(
    gpa: std.mem.Allocator,
    io: std.Io,
    repo: *Repository,
    root_dir: std.Io.Dir,
    lookup: RevertLookup,
    where: []const u8,
    name: []const u8,
    dry_run: bool,
    streams: cli.Streams,
) RevertOutcome {
    const card = switch (lookup) {
        .card, .borrowed => |c| c,
        .failed => return .failed,
        .absent => {
            streams.err.print("zit revert: '{s}' is not in {s}; left unchanged\n", .{ name, where }) catch {};
            return .skipped;
        },
    };
    // A file already at its check-in bytes is not "reverted": Fossil names
    // only the files it changes, and so does zit (a missing or edited file
    // still is).
    if (revertAlreadyClean(gpa, io, root_dir, name, card.hash.?, repo)) return .skipped;
    if (dry_run) {
        streams.out.print("would revert {s}\n", .{name}) catch {};
        return .reverted;
    }
    std.debug.assert(card.hash != null); // fileAt yields only hash-bearing cards (§4.7.6)

    // §7.2: the blob is verified to hash to its F-card id before it lands.
    const bytes = (repo.blob(gpa, card.hash.?) catch |e| {
        revertFileFail(streams, name, e);
        return .failed;
    }) orelse {
        const absence = cmd_sync.absenceOf(gpa, io, root_dir, repo, card.hash.?);
        if (absence == .thinned or absence == .shunned or absence == .erased) {
            var wbuf: [512]u8 = undefined;
            const what = std.fmt.bufPrint(&wbuf, "content for '{s}'", .{name}) catch "content";
            cmd_sync.describeAbsence(streams.err, "revert", what, &absence);
            streams.err.print("zit revert: '{s}' left unchanged\n", .{name}) catch {};
            return .failed;
        }
        streams.err.print("zit revert: content for '{s}' is missing; left unchanged\n", .{name}) catch {};
        _ = cli.horizonContentNote(gpa, io, root_dir, streams, "revert");
        return .failed;
    };
    defer gpa.free(bytes);

    update.restoreFile(io, root_dir, name, bytes, card.mode) catch |e| {
        switch (e) {
            error.SymlinkUnsupported => streams.err.print(
                "zit revert: '{s}' is a symlink, which zit does not support; left unchanged\n",
                .{name},
            ) catch {},
            error.Storage => streams.err.print(
                "zit revert: cannot restore '{s}': input/output error\n",
                .{name},
            ) catch {},
        }
        return .failed;
    };
    streams.out.print("REVERT   {s}\n", .{name}) catch {};
    return .reverted;
}

/// Collects the paths a no-path revert restores: every tracked path whose
/// working state differs from the check-in -- edited, missing, or tracked but
/// not in it (reported and left alone, as an explicit path is). Paths the walk
/// reports only from the check-in side are untracked, and revert never
/// touches those.
const RevertScanSink = struct {
    gpa: std.mem.Allocator,
    targets: *std.ArrayList([]const u8),

    pub fn emit(self: *RevertScanSink, entry: cmd_tracking.WorkingTreeEntry) cmd_tracking.WalkError!void {
        if (!entry.tracked) return;
        switch (entry.inspection) {
            .same => return,
            .oom => return error.OutOfMemory,
            .none, .added, .modified, .deleted, .io_error, .corrupt => {},
        }
        try self.targets.append(self.gpa, entry.path);
    }
};

/// True when the working file exists and already hashes to the check-in's
/// blob. Any read failure answers false, so the restore path runs and reports.
fn revertAlreadyClean(gpa: std.mem.Allocator, io: std.Io, root_dir: std.Io.Dir, name: []const u8, hash_hex: []const u8, repo: *Repository) bool {
    _ = repo;
    const st = root_dir.statFile(io, name, .{ .follow_symlinks = false }) catch return false;
    if (st.kind != .file) return false;
    const bytes = root_dir.readFileAlloc(io, name, gpa, .limited(1 << 30)) catch return false;
    defer gpa.free(bytes);
    var name_buf: [64]u8 = undefined;
    const algo: artifact.HashAlgo = if (hash_hex.len == 40) .sha1 else .sha3_256;
    const hex = artifact.artifactName(algo, bytes, &name_buf);
    return std.mem.eql(u8, hex, hash_hex);
}

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

fn revertNoCheckout(s: cli.Streams) cli.Exit {
    s.err.writeAll("zit revert: nothing to revert to (the working checkout is unborn)\n") catch {};
    return .failure;
}

fn revertNotTracked(s: cli.Streams, path: []const u8) void {
    s.err.print("zit revert: '{s}' is not tracked (use 'zit add' to track it)\n", .{path}) catch {};
}

/// Maps a `Repository.fileAt`/`blob` failure to a per-file diagnostic (no exit
/// code — the caller aggregates). Switches the full `FilesError` set
/// exhaustively; `blob`'s narrower `OpenError` coerces in. Phrasings match
/// `ls`/`cat`.
fn revertFileFail(s: cli.Streams, name: []const u8, e: Repository.FilesError) void {
    switch (e) {
        error.OutOfMemory => s.err.writeAll("zit revert: out of memory\n") catch {},
        error.NotARepo => s.err.writeAll(not_a_repo_msg) catch {},
        error.CannotRead => s.err.print("zit revert: cannot read '{s}': input/output error\n", .{name}) catch {},
        error.ImportPending => s.err.writeAll("zit revert: an incremental import is pending; run 'zit import-git --recover DIR'\n") catch {},
        error.Corrupt => s.err.print("zit revert: cannot read '{s}': repository is corrupt\n", .{name}) catch {},
        error.NotManifest => s.err.writeAll("zit revert: not a check-in\n") catch {},
        error.BaselineUnresolvable => s.err.writeAll("zit revert: cannot resolve the baseline of a delta check-in\n") catch {},
        // The caller routes the tree's elision through `ElidedTree`.
        error.ElidedByCone => unreachable,
    }
}