//! The failure wording verbs share, so one cause reads the same under every
//! verb: library errors mapped to a phrase and an exit status, the
//! missing-checkout report, and `openRepo`, the discover-and-open funnel the
//! read verbs pass through.
const std = @import("std");
const zit = @import("zit");
const cli = zit.cli;
const checkout = zit.checkout;
const managed = zit.managed;
const repoview = zit.repoview;
const Repository = zit.Repository;
/// Maps a raw error to a short, honest, human phrase for the B-init-9 line.
/// Pure rendering, not logic — the switch is over the union of every error
/// the init path can surface (filesystem, `LogStore`, `checkout`).
pub fn reasonOf(err: anyerror) []const u8 {
return switch (err) {
error.OutOfMemory => "out of memory",
error.AccessDenied, error.PermissionDenied => "permission denied",
error.ReadOnlyFileSystem => "read-only file system",
error.NoSpaceLeft, error.DiskQuota => "no space left on device",
error.FileNotFound => "no such file or directory",
error.Corrupt => "repository is corrupt",
// A prepared import fences readers and writers until it is finished.
error.ImportPending, error.ImportRecoveryRequired => "an incremental import is pending; run 'zit import-git --recover DIR'",
// `error.Storage` (LogStore/checkout device failure) and every other
// device/OS error collapse to one honest phrase.
else => "input/output error",
};
}
/// Renders a checkout-state read failure for any verb; the verb prefixes the
/// message so one mapper serves both the read-only working-tree verbs and commit.
pub fn checkoutFail(s: cli.Streams, verb: []const u8, err: checkout.CheckoutError) cli.Exit {
switch (err) {
error.Corrupt => s.err.print(
"zit {s}: cannot read checkout state: .zit-checkout is corrupt\n",
.{verb},
) catch {},
error.Storage => s.err.print(
"zit {s}: cannot read checkout state: input/output error\n",
.{verb},
) catch {},
}
return .failure;
}
/// Renders a managed-set read failure for any verb; the verb prefixes the
/// message so one mapper serves both the read-only working-tree verbs and commit.
pub fn managedFail(s: cli.Streams, verb: []const u8, err: managed.ManagedError) cli.Exit {
switch (err) {
error.Corrupt => s.err.print(
"zit {s}: cannot read tracked files: .zit-checkout is corrupt\n",
.{verb},
) catch {},
error.Storage => s.err.print(
"zit {s}: cannot read tracked files: input/output error\n",
.{verb},
) catch {},
error.TooLong => s.err.print(
"zit {s}: cannot read tracked files: a tracked path is too long\n",
.{verb},
) catch {},
error.TooMany => s.err.print("zit {s}: cannot read tracked files: too many tracked files\n", .{verb}) catch {},
error.OutOfMemory => s.err.print("zit {s}: out of memory\n", .{verb}) catch {},
}
return .failure;
}
pub fn stateOom(s: cli.Streams, verb: []const u8) cli.Exit {
s.err.print("zit {s}: out of memory\n", .{verb}) catch {};
return .failure;
}
/// The diagnostic every working-tree verb (add/rm/status) prints when discovery
/// finds no repository. Shared so all three fail identically (B-add-8 / B-rm-8 /
/// B-status-9 "identical shape") — a single, byte-identical line, exactly as each
/// contract quotes it.
/// Say what was actually looked for. Discovery requires a CHECKOUT
/// (`probeRoot` tests for `.zit-checkout` first), so the old wording — "no .zit
/// found" — was flatly false in the case that matters: a bare store, where
/// `.zit` is sitting right there in the directory being complained about. An
/// operator reading it had every reason to think the repository was corrupt.
///
/// The second line is the actual remedy, and it is why this stayed one constant
/// rather than becoming a probe at 54 call sites: naming `-R` is right for a
/// bare repository AND harmless where there is none.
pub const not_a_repo_msg =
"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";
/// Report a `cli.resolveRoot` that found nothing.
///
/// The message above is right for a DISCOVERY failure and wrong for a `-R`
/// one: it tells the operator to name the repository with `-R` when `-R` is
/// exactly what they named. Worse, it reads identically whether the path was
/// mistyped or simply holds no repository, so a stale path in a script looks
/// like a bug in the verb.
///
/// Re-probes the given path to separate the two mistakes an operator actually
/// makes. The probe is one `openDir` on a path already known to have failed,
/// so it costs nothing on the success path and runs once on the way out.
pub fn reportNoRoot(streams: cli.Streams, io: std.Io, verb: []const u8, override: ?[]const u8) void {
const given = override orelse {
streams.err.writeAll(not_a_repo_msg) catch {};
return;
};
// `-R <dir>/.zit` names the store file; the repository is its parent, and
// the resolver accepts both spellings, so the probe must too or the
// diagnostic would contradict what was accepted.
const probe = if (std.mem.eql(u8, std.fs.path.basename(given), ".zit"))
(std.fs.path.dirname(given) orelse ".")
else
given;
var dir = std.Io.Dir.cwd().openDir(io, probe, .{}) catch {
streams.err.print("zit {s}: no such repository: {s}\n", .{ verb, given }) catch {};
return;
};
defer dir.close(io);
streams.err.print(
"zit {s}: no repository at '{s}' (no .zit there)\n",
.{ verb, given },
) catch {};
}
/// One honest phrase for a repository the read-only family cannot open or stat.
/// A store open failure, named by cause: a pending import is not damage.
pub fn storeReadFail(s: cli.Streams, verb: []const u8, err: anyerror) cli.Exit {
s.err.print("zit {s}: cannot read repository: {s}\n", .{ verb, reasonOf(err) }) catch {};
return .failure;
}
pub fn repoReadFail(s: cli.Streams, verb: []const u8) cli.Exit {
s.err.print("zit {s}: cannot read repository: input/output error\n", .{verb}) catch {};
return .failure;
}
/// A read that failed walking check-in `rid`'s tree: the tree's fault when
/// the walk found one (`Repository.tree_fault`), else `repoReadFail`'s line.
/// Two causes a caller must tell apart: a sub-manifest the store does not
/// hold yet, which a sync may bring, and a tree the walk refuses, which no
/// sync mends. Both exit 1, the status every verb gives missing or damaged
/// content; `absent` (8) is content removed by policy, which neither is. The
/// lines keep `cannot read repository:` in front for whatever matched on it.
pub fn repoTreeFail(s: cli.Streams, verb: []const u8, repo: *Repository, rid: Repository.Rid) cli.Exit {
const fault = repo.tree_fault orelse return repoReadFail(s, verb);
switch (fault) {
.missing => |a| s.err.print("zit {s}: cannot read repository: sub-manifest {s} is missing; a sync may bring it\n", .{ verb, a.name().? }) catch {},
.malformed => |e| s.err.print("zit {s}: cannot read repository: check-in {s} has a malformed tree: {s}\n", .{ verb, repo.hashOf(rid), treeFaultText(e) }) catch {},
}
return .failure;
}
/// What the §5.1 walk refused, in a phrase.
fn treeFaultText(e: zit.artifact.TreeError) []const u8 {
return switch (e) {
error.SubUnresolvable => "an S card names an artifact that is not a sub-manifest",
error.OrderViolation => "its file names are not in strictly ascending order",
error.FirstFilenameMismatch => "a sub-manifest does not begin at the name its S card gives",
error.DepthExceeded => "it is nested deeper than 16 levels",
error.ReferenceCycle => "a sub-manifest names itself",
};
}
/// A derive that rejected a specific artifact, named. Distinct from
/// `repoOpenFail`'s bare corruption line because it is a different claim: the
/// repository is readable, and ONE artifact in it is not the shape the deriver
/// requires. The name is actionable — `zit cat` it, or look it up in an import
/// map — where "repository is corrupt" is not.
pub fn repoDeriveFault(s: cli.Streams, verb: []const u8, f: repoview.RepoView.Fault) cli.Exit {
const why: []const u8 = switch (f.reason) {
.missing_timestamp => "carries no D-card timestamp",
.unparsable_timestamp => "carries a D-card timestamp that cannot be parsed",
};
s.err.print(
"zit {s}: cannot read repository: artifact {s} {s}\n",
.{ verb, f.artifactName(), why },
) catch {};
return .failure;
}
/// Maps a `Repository.open` failure to the verb's diagnostic + exit 1. Closed
/// over `Repository.OpenError` so the CLI switch stays exhaustive; general over
/// the verb name so every read-only verb shares one map. The `not-a-repo` and
/// corrupt/IO phrasings are byte-identical to the pre-facade hand-wired opens.
pub fn repoOpenFail(s: cli.Streams, verb: []const u8, err: Repository.OpenError) cli.Exit {
switch (err) {
error.OutOfMemory => s.err.print("zit {s}: out of memory\n", .{verb}) catch {},
error.NotARepo => s.err.writeAll(not_a_repo_msg) catch {},
error.CannotRead => s.err.print("zit {s}: cannot read repository: input/output error\n", .{verb}) catch {},
error.ImportPending => s.err.print("zit {s}: an incremental import is pending; run 'zit import-git --recover DIR'\n", .{verb}) catch {},
error.Corrupt => s.err.print("zit {s}: cannot read repository: repository is corrupt\n", .{verb}) catch {},
}
return .failure;
}
/// Discover the checkout root and open the repository through the `Repository`
/// facade for the read-only verb family (leaves, branch, tag, info). One place
/// owns the discover + open + per-verb diagnostics so every read-only verb reads
/// identical text. On `.ok`, `repo` is filled (caller `deinit`s it) and
/// `root_dir` is set (caller closes it AFTER `repo.deinit`); on any non-`.ok`
/// the diagnostic is already on stderr, `repo` is untouched, and any opened root
/// dir has been closed here.
pub fn openRepo(
gpa: std.mem.Allocator,
io: std.Io,
arena: std.mem.Allocator,
streams: cli.Streams,
verb: []const u8,
repo_override: ?[]const u8,
bypass_cache: bool,
fast_read: bool,
repo: *Repository,
root_dir: *std.Io.Dir,
) cli.Exit {
// `resolveRoot` is the one place the `-R` route and the walk-up-from-cwd
// route converge, so no verb below has to know which one it got.
const root = (cli.resolveRoot(arena, io, repo_override) catch
return stateOom(streams, verb)) orelse {
reportNoRoot(streams, io, verb, repo_override);
return .failure;
};
// Hot verbs take the zero-parse image path (`.fast_read`). That now
// includes everything needing ancestry: the image carries adjacency, so
// That is every read verb: the image carries adjacency and the
// resolved §5 tag surface, so nothing here re-derives the log to answer a
// name, a branch listing, or a display override. The write verbs stay on
// the full derive because an image is read-only by construction.
repo.open(gpa, io, root.dir, .{
.bypass_cache = bypass_cache,
.mode = if (fast_read) .fast_read else .full,
}) catch |e| {
var d = root.dir;
d.close(io);
// The derive records WHICH artifact it rejected. Reported here because
// this is the one funnel every verb's open passes through, and because
// `error.Corrupt` on its own sends whoever hit it to bisect a store that
// took minutes to walk.
if (repo.view.fault) |f| return repoDeriveFault(streams, verb, f);
return repoOpenFail(streams, verb, e);
};
// With a checkout under foot, `current`/`prev`/`next` have a
// referent. A bare store named with -R has none.
if (repo_override == null) {
var ck_buf: [checkout.max_ck_payload + 1]u8 = undefined;
if (checkout.read(io, root.dir, &ck_buf) catch null) |ck| {
repo.setCurrentHint(ck.version);
}
}
root_dir.* = root.dir;
return .ok;
}
/// A config write that could not take the writer lock. A busy lock already
/// said who holds it; anything else is the unreadable-repository failure.
pub fn storeAppendFail(s: cli.Streams, verb: []const u8, err: anyerror) cli.Exit {
if (err == error.StoreBusy) return .failure;
return repoReadFail(s, verb);
}