//! `zit update`: move the checkout to another check-in, and the receipt,
//! demand-fetch and project-policy helpers `cone` and `commit` reuse.
const std = @import("std");
const zit = @import("zit");
const cli = @import("zit").cli;
const merge3 = @import("zit").merge3;
const cmd_sync = @import("sync.zig");
const cmd_pull = @import("pull.zig");
const logstore = @import("zit").logstore;
const storage = @import("zit").storage;
const update = @import("zit").update;
const checkout = @import("zit").checkout;
const Repository = @import("zit").Repository;
const artifact = zit.artifact;
const diagnostics = @import("../cli/diagnostics.zig");
const help_pages = @import("../cli/help.zig");
const reasonOf = diagnostics.reasonOf;
const stateOom = diagnostics.stateOom;
const openRepo = diagnostics.openRepo;
const not_a_repo_msg = diagnostics.not_a_repo_msg;
const update_help = help_pages.update_help;
/// `zit update CHECKIN` — parse one canonical artifact ID, discover the
/// worktree, open the repository read-only, and delegate the transaction to
/// the private update module.
pub fn runUpdate(
gpa: std.mem.Allocator,
io: std.Io,
arena: std.mem.Allocator,
verb_args: []const []const u8,
streams: cli.Streams,
amb: cli.Ambient,
) cli.Exit {
var parsed = switch (cli.parseUpdateArgs(verb_args)) {
.ok => |p| p,
.unknown_option => |tok| return cli.usageError(streams, "update", .unknown_option, tok),
.extra_argument => |tok| return cli.usageError(streams, "update", .extra_argument, tok),
.empty_value => |tok| return cli.usageError(streams, "update", .empty_value, tok),
.too_many_cones => |tok| return cli.usageError(streams, "update", .too_many_cones, tok),
.cone_and_dense => return cli.usageError(streams, "update", .cone_and_dense, ""),
};
if (parsed.help) {
streams.out.writeAll(update_help) catch {};
return .ok;
}
if (parsed.latest and parsed.checkin != null)
return cli.usageError(streams, "update", .extra_argument, parsed.checkin.?);
// Fossil's bare `update` moves to the newest check-in on the current
// branch; a missing CHECKIN means --latest, not a usage error.
if (parsed.checkin == null) parsed.latest = true;
// Autosync pull, BEFORE resolution: the freshly pulled DAG may be the
// very thing the named check-in resolves against.
if (!parsed.no_sync) cmd_sync.autosyncPull(gpa, io, arena, streams, "update");
// SF1 (BLOCKER-FIX-PLAN.md §3): `update` used to accept ONLY a canonical
// 40/64-hex ID, so `zit update trunk` — the single most obvious thing to
// type — failed as an "invalid check-in ID". Its argument is a check-in
// name like every other verb's, so it goes through the same §8.3 procedure.
const root = (cli.discoverRoot(arena, io) catch {
streams.err.writeAll("zit update: out of memory\n") catch {};
return .failure;
}) orelse {
streams.err.writeAll(not_a_repo_msg) catch {};
return .failure;
};
var root_dir = root.dir;
defer root_dir.close(io);
// Where the checkout is now: the receipt's "updated-from" side, and the
// branch `--latest` names. An unborn checkout has neither.
var ck_buf: [checkout.max_ck_payload + 1]u8 = undefined;
const current_ck = checkout.read(io, root_dir, &ck_buf) catch null;
const cur_version: []const u8 = if (current_ck) |c| c.version else "";
const requested: []const u8 = if (parsed.latest) blk: {
const c = current_ck orelse {
streams.err.writeAll("zit update: --latest needs a checkout on a branch\n") catch {};
return .failure;
};
if (c.branch.len == 0) {
streams.err.writeAll("zit update: --latest needs a checkout on a branch\n") catch {};
return .failure;
}
break :blk c.branch;
} else parsed.checkin.?;
// One repository for the whole verb: name resolution, the branch facts
// the record carries, and the content log the materialization reads all
// come from it. Each used to open the store on its own -- three
// repo-state derives and a full frame-header scan per update.
// `.full` derive, not `.fast_read`: plain-name resolution reads the tag
// tables, which the read-image does not materialize.
var repo: Repository = undefined;
var repo_root: std.Io.Dir = undefined;
const open_rc = openRepo(gpa, io, arena, streams, "update", null, false, false, &repo, &repo_root);
if (open_rc != .ok) return open_rc;
defer repo_root.close(io);
defer repo.deinit(gpa);
const target_id = switch (updateResolveTarget(arena, &repo, requested, streams)) {
.ok => |h| h,
.fail => |exit| return exit,
};
// The receipt: what this move changes, computed from the two
// check-ins' file sets before anything is written, so a dry run and the
// real thing say the same lines.
var receipt = updateReceipt(gpa, arena, &repo, cur_version, target_id, parsed.verbose) catch return stateOom(streams, "update");
if (parsed.dry_run) {
receipt.print(streams, &repo, &.{}, &.{}, true);
return .ok;
}
const log = repo.logStore(gpa) catch |err| switch (err) {
error.OutOfMemory => return stateOom(streams, "update"),
else => {
streams.err.writeAll("zit update: cannot read repository: input/output error\n") catch {};
return .failure;
},
};
// Sparse-cone RFC section 4.1: --cone replaces the stored cone, --dense
// drops it, absent inherits. Cone.init validates members (worktree-path
// rules, coverage minimality); the parser only collected tokens.
var cone_members = parsed.cone_members;
var cone_len = parsed.cone_len;
var cone_not_members = parsed.cone_not_members;
var cone_not_len = parsed.cone_not_len;
if (parsed.cone_file) |cf| {
const lens = cli.appendConeFile(arena, io, cf, &cone_members, cone_len, &cone_not_members, cone_not_len) orelse {
streams.err.print("zit update: cannot read --cone-file '{s}' (or it overflows the {d}-member cap)\n", .{ cf, zit.cone.max_members }) catch {};
return .failure;
};
cone_len = lens.members;
cone_not_len = lens.not_members;
}
if (parsed.cone_parents and cone_len == 0) {
streams.err.writeAll("zit update: --cone-parents needs --cone=PATH: it is a property of the cone being set\n") catch {};
return .failure;
}
var new_cone: ?zit.cone.Cone = null;
defer if (new_cone) |*c| c.deinit(gpa);
const sparse: update.SparseOpt = if (parsed.dense)
.{ .set = null }
else if (cone_len + cone_not_len != 0) blk: {
new_cone = zit.cone.Cone.initWith(gpa, cone_members[0..cone_len], cone_not_members[0..cone_not_len], .{ .parents = parsed.cone_parents }) catch |e|
return coneInitFail(streams, "update", e);
break :blk .{ .set = &new_cone.? };
} else .inherit;
// The mutation entry: `target_id` is a full §3.6 artifact id — either the
// canonical argument or the resolved-and-duped hash (both validated above).
std.debug.assert(artifact.validateName(target_id));
// The project's `manifest` setting supplies the stamp selection when
// this checkout has none of its own, so a repository that adopts the
// setting starts stamping at the next update rather than only after a
// fresh `open`. A checkout that made its own choice keeps it.
// One repository, one open. The config this verb already holds
// answers the project setting, so nothing here re-opens the store.
var update_config: ?logstore.OwnedConfig = log.readConfig(gpa) catch null;
defer if (update_config) |*c| c.deinit(gpa);
const project: ProjectPolicy = projectPolicy(io, arena, root_dir, amb, if (update_config) |*c| &c.config else null);
// A dirty tree is merged INTO, not refused. `update` used to reject
// it, which left an operator whose branch tip had moved under uncommitted
// work with no way forward at all — `merge` refused for the same reason and
// `stash` cannot replay onto a different check-in, so the only exit was
// `commit --allow-fork`. The guard meant to keep forks deliberate was
// manufacturing them. Carrying the edits across the move is fossil's own
// answer (`www/branching.wiki`: update "merges them into his own changes"),
// and it leaves the next commit an ordinary child of the tip.
//
// The policy is handed DOWN rather than computed first: the divergences it
// needs come from the same tree scan the materialization already runs, and
// asking for them separately would scan every clean update twice.
var policy = CarryPolicy{
.gpa = gpa,
.io = io,
.arena = arena,
.repo = &repo,
.root_dir = root_dir,
.target_id = target_id,
.streams = streams,
};
update.applyCheckinWith(gpa, io, root_dir, log, target_id, .{ .inherit_or = project.manifest }, sparse, &repo, policy.resolver()) catch |err| {
// The policy already named the paths it could not merge; the generic
// "not clean" line below would only bury them.
if (policy.refused) return .failure;
// Sparse-cone RFC section 6.4, policy form, update's half: content
// missing on a SPARSE store while the operator widens (or densifies)
// is elision meeting new coverage intent -- write the requested cone
// as store policy, pull through the saved remote, and retry once.
// On a dense store the same error stays the corruption it always was.
// Horizon draft section 5.8 -- a check-in this clone does not hold at
// all (its manifest lies below a structural horizon) is a deepen as
// much as missing content is: the same fetch, keyed on the target.
const below_horizon_shape = err == error.CheckinNotFound or err == error.CheckinContentMissing;
// A tree node the wider cone now reaches is the same elision one
// level up (sparse-cone section 5.1): the walk cannot resolve it.
var deepen_wanted = err == error.FileContentMissing or err == error.BaselineNotFound;
if (below_horizon_shape) {
if (zit.repocache.readStoreCone(gpa, io, root_dir)) |c_const| {
var c = c_const;
defer c.deinit(gpa);
deepen_wanted = c.horizon != null and c.horizon.?.depth == .structural;
}
}
if (deepen_wanted) {
var probe = zit.repocache.readStoreCone(gpa, io, root_dir);
const store_is_sparse = probe != null;
if (probe) |*c| c.deinit(gpa);
const fetch: DemandFetch = if (store_is_sparse) updateDemandFetch(gpa, io, arena, root_dir, streams, &sparse, target_id) else .failed;
// A deepen that could not run said why, naming the horizon; the
// generic content-missing explanation would only contradict it.
if (fetch == .refused) return .failure;
if (fetch == .fetched) {
// The log handle predates the fetch; the retry reopens
// everything through a fresh verb pass with fetching spent.
var file2 = cli.openStoreRead(io, root_dir) catch {
streams.err.writeAll("zit update: cannot reopen the repository after fetching\n") catch {};
return .failure;
};
defer file2.close(io);
const st2 = file2.stat(io) catch {
streams.err.writeAll("zit update: cannot reopen the repository after fetching\n") catch {};
return .failure;
};
var fs2 = storage.FileStorage.init(io, file2, st2.size);
var log2 = logstore.LogStore.openReadOnly(gpa, fs2.storageFile()) catch |e2|
return updateLogFail(streams, e2);
defer log2.deinit(gpa);
// The retry carries the same working-tree content:
// re-resolving against the reopened store is what keeps the
// post-fetch path from silently overwriting local edits that
// the pre-fetch path preserves.
update.applyCheckinWith(gpa, io, root_dir, &log2, target_id, .{ .inherit_or = project.manifest }, sparse, null, policy.resolver()) catch |err2| {
if (policy.refused) return .failure;
if (err2 == error.FileContentMissing and updateElidedRefusal(gpa, io, root_dir, streams)) return .failure;
return updateApplyFail(streams, target_id, err2);
};
cli.stampWorktreeRegistry(gpa, io, root_dir, root.abs);
// The tree exists now, so the empty-dirs shape
// can be laid over it (fossil's update.c does the same after
// its own materialization).
update.ensureEmptyDirs(io, root_dir, project.empty_dirs, streams.err);
// The receipt is read from the store as it stands after the
// fetch: the view opened before it may not hold the target at
// all (a structural deepen), and asking it for the target's
// branch reads a check-in that view never derived.
var fetched: Repository = undefined;
var fetched_root: std.Io.Dir = undefined;
if (openRepo(gpa, io, arena, streams, "update", null, false, false, &fetched, &fetched_root) != .ok) return .failure;
defer fetched_root.close(io);
defer fetched.deinit(gpa);
var fetched_receipt = updateReceipt(gpa, arena, &fetched, cur_version, target_id, parsed.verbose) catch return stateOom(streams, "update");
fetched_receipt.print(streams, &fetched, policy.merged.items, policy.conflicts.items, false);
return policy.report(streams);
}
// Section 6.4: a tree the fetch could not complete is named as
// elision, never as a missing baseline.
if (store_is_sparse and err == error.BaselineNotFound) {
streams.err.print(
"zit update: check-in '{s}': part of its tree is elided by the store's sparse cone and was not fetched\n",
.{target_id},
) catch {};
return .failure;
}
}
if (err == error.FileContentMissing) {
if (updateElidedRefusal(gpa, io, root_dir, streams)) return .failure;
}
return updateApplyFail(streams, target_id, err);
};
// A successful update stamps this tree into the store's worktree
// registry (best-effort; discovery data never gates the update).
cli.stampWorktreeRegistry(gpa, io, root_dir, root.abs);
// After a SUCCESSFUL materialization only, and never on
// --dry-run, which returned above.
update.ensureEmptyDirs(io, root_dir, project.empty_dirs, streams.err);
receipt.print(streams, &repo, policy.merged.items, policy.conflicts.items, false);
return policy.report(streams);
}
/// One line of the update receipt: Fossil's vocabulary, so the
/// report reads the same to someone coming from `fossil update`.
const ReceiptOp = enum { update, add, remove, unchanged };
const ReceiptLine = struct { op: ReceiptOp, path: []const u8 };
const Receipt = struct {
gpa: std.mem.Allocator,
arena: std.mem.Allocator,
from: []const u8,
to: []const u8,
lines: []const ReceiptLine,
modified: usize,
added: usize,
removed: usize,
/// Print to stderr: per-file lines (carried paths shown as MERGE,
/// conflicted as CONFLICT, overriding the store's view), the from/to
/// block, and the undo hint. stdout stays script-clean — the split
/// `merge`'s conflict lines already use.
fn print(self: *const Receipt, streams: cli.Streams, repo: *Repository, merged: []const []const u8, conflicts: []const []const u8, dry_run: bool) void {
const e = streams.err;
for (self.lines) |l| {
const word: []const u8 = if (containsPath(conflicts, l.path)) "CONFLICT" else if (containsPath(merged, l.path)) "MERGE" else switch (l.op) {
.update => "UPDATE",
.add => "ADD",
.remove => "REMOVE",
.unchanged => "UNCHANGED",
};
e.print("{s} {s}\n", .{ word, l.path }) catch {};
}
// A carried path the store's diff did not list (a local edit to a
// file the target leaves alone) still merged; say so.
for (merged) |p| {
if (!self.listed(p)) e.print("{s} {s}\n", .{ if (containsPath(conflicts, p)) "CONFLICT" else "MERGE", p }) catch {};
}
e.writeAll("-------------------------------------------------------------------------------\n") catch {};
if (std.mem.eql(u8, self.from, self.to)) {
// Fossil's no-op receipt: where you already are, not a from/to pair.
e.print("checkout: {s} {s}\n", .{ cli.shortHash(self.to), checkinDate(self.gpa, self.arena, repo, self.to) }) catch {};
} else {
if (self.from.len != 0) e.print("updated-from: {s} {s}\n", .{ cli.shortHash(self.from), checkinDate(self.gpa, self.arena, repo, self.from) }) catch {};
e.print("updated-to: {s} {s}\n", .{ cli.shortHash(self.to), checkinDate(self.gpa, self.arena, repo, self.to) }) catch {};
}
// The view can predate a deepen that fetched the target: there the
// target is a phantom, not a check-in, and has no branch to name.
if (repo.lookup(self.to)) |rid| if (repo.view.state.hasEvent(rid)) {
e.print("tags: {s}\n", .{repo.branchOf(rid)}) catch {};
if (repo.manifest(self.gpa, rid) catch null) |om_const| {
var om = om_const;
defer om.deinit(self.gpa);
const comment: []const u8 = if (om.manifest.c) |c| blk: {
const buf = self.arena.alloc(u8, c.comment.len) catch break :blk c.comment;
break :blk artifact.decodeEscapes(c.comment, buf);
} else "";
const user = if (om.manifest.u) |u| u.login else "";
e.print("comment: {s} (user: {s})\n", .{ comment, user }) catch {};
}
};
if (std.mem.eql(u8, self.from, self.to)) {
e.writeAll("changes: none. Already up-to-date.\n") catch {};
} else {
// Fossil's sentence — `1 file modified.` — extended only when
// something was added or removed.
e.print("changes: {d} file{s} modified", .{ self.modified, if (self.modified == 1) "" else "s" }) catch {};
if (self.added != 0) e.print(", {d} added", .{self.added}) catch {};
if (self.removed != 0) e.print(", {d} removed", .{self.removed}) catch {};
e.writeAll(".\n") catch {};
}
if (dry_run) {
e.writeAll("(dry run: nothing was changed)\n") catch {};
} else if (!std.mem.eql(u8, self.from, self.to) or merged.len != 0) {
e.writeAll(" \"zit undo\" is available to undo changes to the working checkout.\n") catch {};
}
}
fn listed(self: *const Receipt, path: []const u8) bool {
for (self.lines) |l| if (std.mem.eql(u8, l.path, path)) return true;
return false;
}
};
fn containsPath(list: []const []const u8, path: []const u8) bool {
for (list) |p| if (std.mem.eql(u8, p, path)) return true;
return false;
}
/// The check-in's D card as written, or "" when it cannot be read.
/// The check-in's time as the receipt says it: weekday first, like the
/// timeline and status block.
fn checkinDate(gpa: std.mem.Allocator, arena: std.mem.Allocator, repo: *Repository, hash: []const u8) []const u8 {
_ = gpa;
const rid = repo.lookup(hash) orelse return "";
const mtime = repo.state().mtimeOf(rid) orelse return "";
var buf: [32]u8 = undefined;
return arena.dupe(u8, cli.humanTime(mtime, &buf)) catch "";
}
/// The store's view of the move: the target's file set against the current
/// check-in's, in canonical order. An unborn checkout (no `from`) lists every
/// target file as ADD.
fn updateReceipt(gpa: std.mem.Allocator, arena: std.mem.Allocator, repo: *Repository, from: []const u8, to: []const u8, verbose: bool) error{OutOfMemory}!Receipt {
var lines: std.ArrayList(ReceiptLine) = .empty;
var modified: usize = 0;
var added: usize = 0;
var removed: usize = 0;
var old_cards: std.ArrayList(artifact.FCard) = .empty;
var new_cards: std.ArrayList(artifact.FCard) = .empty;
const same_checkin = std.mem.eql(u8, from, to);
if (from.len != 0 and !same_checkin) {
if (repo.lookup(from)) |rid| {
if (repo.files(gpa, rid) catch null) |fl_const| {
var fl = fl_const;
defer fl.deinit(gpa);
var it = fl.iterator();
while (it.next()) |f| try old_cards.append(arena, try dupeCardInto(arena, f));
}
}
}
if (!same_checkin or verbose) {
if (repo.lookup(to)) |rid| {
if (repo.files(gpa, rid) catch null) |fl_const| {
var fl = fl_const;
defer fl.deinit(gpa);
var it = fl.iterator();
while (it.next()) |f| try new_cards.append(arena, try dupeCardInto(arena, f));
}
}
}
if (!same_checkin) {
var i: usize = 0;
var j: usize = 0;
const o = old_cards.items;
const n = new_cards.items;
while (i < o.len or j < n.len) {
if (j >= n.len or (i < o.len and std.mem.order(u8, o[i].filename, n[j].filename) == .lt)) {
try lines.append(arena, .{ .op = .remove, .path = o[i].filename });
removed += 1;
i += 1;
} else if (i >= o.len or std.mem.order(u8, o[i].filename, n[j].filename) == .gt) {
try lines.append(arena, .{ .op = .add, .path = n[j].filename });
added += 1;
j += 1;
} else {
const same = std.mem.eql(u8, o[i].hash orelse "", n[j].hash orelse "") and std.mem.eql(u8, o[i].perm orelse "", n[j].perm orelse "");
if (!same) {
try lines.append(arena, .{ .op = .update, .path = n[j].filename });
modified += 1;
} else if (verbose) {
try lines.append(arena, .{ .op = .unchanged, .path = n[j].filename });
}
i += 1;
j += 1;
}
}
} else if (verbose) {
for (new_cards.items) |c| try lines.append(arena, .{ .op = .unchanged, .path = c.filename });
}
return .{ .gpa = gpa, .arena = arena, .from = from, .to = to, .lines = lines.items, .modified = modified, .added = added, .removed = removed };
}
fn dupeCardInto(arena: std.mem.Allocator, f: artifact.FCard) error{OutOfMemory}!artifact.FCard {
return .{
.filename = try arena.dupe(u8, f.filename),
.hash = if (f.hash) |h| try arena.dupe(u8, h) else null,
.perm = if (f.perm) |p| try arena.dupe(u8, p) else null,
.old_name = null,
.mode = f.mode,
};
}
/// The section 6.4 policy-form fetch for `update`: persist the REQUESTED
/// coverage as the store cone (a widened cone, or dense for --dense /
/// inherit-dense requests), then pull -- suppression and receive filtering
/// read the new policy. True on a completed pull; false (with the remedy
/// diagnostic) when no remote is saved.
/// The saved remote's URL, or null when none is stored. Mirrors the sync
/// verbs' resolver without importing their error mapping.
pub fn updateResolveRemote(gpa: std.mem.Allocator, io: std.Io, dir: std.Io.Dir, buf: *[logstore.max_config_str]u8) ?[]const u8 {
var file = cli.openStoreRead(io, dir) catch return null;
defer file.close(io);
const st = file.stat(io) catch return null;
var fs = storage.FileStorage.init(io, file, st.size);
var log = logstore.LogStore.openReadOnly(gpa, fs.storageFile()) catch return null;
defer log.deinit(gpa);
var oc = (log.readConfig(gpa) catch return null) orelse return null;
defer oc.deinit(gpa);
const saved = oc.config.remote_url;
if (saved.len == 0 or saved.len > buf.len) return null;
@memcpy(buf[0..saved.len], saved);
return buf[0..saved.len];
}
/// `fetched`: the store now holds what the update needs, retry. `failed`:
/// nothing was fetched and the caller explains. `refused`: a horizon deepen
/// could not run, and its diagnostic is already printed.
const DemandFetch = enum { fetched, failed, refused };
fn updateDemandFetch(
gpa: std.mem.Allocator,
io: std.Io,
arena: std.mem.Allocator,
root_dir: std.Io.Dir,
streams: cli.Streams,
sparse: *const update.SparseOpt,
target_id: []const u8,
) DemandFetch {
// Horizon draft section 5.7 -- under a horizon, content missing for the
// target check-in means the target lies below C (or its tree reaches
// below it), or the requested cone reaches paths the store leaves out:
// the remedy is DEEPEN and WIDEN, never densify. Move C to a common
// ancestor of C and the target (C itself when the target is above it),
// keeping the rule, take the requested paths as the store's (the stored
// ones when none were requested), and pull: the origin then serves K of
// that ancestor under those paths. Nothing held is replaced.
var deepened: ?zit.cone.Cone = null;
defer if (deepened) |*c| c.deinit(gpa);
var point_buf: [64]u8 = undefined;
var point: []const u8 = target_id;
if (zit.repocache.readStoreCone(gpa, io, root_dir)) |stored_const| {
var stored = stored_const;
defer stored.deinit(gpa);
if (stored.horizon) |h| {
// The remote first: without one there is neither a merge-base
// answer nor a deepen, and that is the remedy to name.
var url_buf: [logstore.max_config_str]u8 = undefined;
_ = updateResolveRemote(gpa, io, root_dir, &url_buf) orelse {
streams.err.writeAll(
"zit update: this check-in's content lies below the store's horizon and no remote is saved\n" ++
"zit update: set one with 'zit remote URL', or re-clone with an earlier --horizon\n",
) catch {};
return .refused;
};
point = cmd_pull.deepenPoint(gpa, io, root_dir, streams, .{ .now_epoch = 0, .user_env = null }, "update", h.hash, target_id, &point_buf) orelse return .refused;
// The requested cone's paths when one was given (none when
// densifying), the stored ones otherwise.
const paths: ?*const zit.cone.Cone = switch (sparse.*) {
.set => |c| c,
.inherit => &stored,
};
// The depth travels with the deepen: a structural clone stays
// structural, so the pull asks for the seed at the new C.
const deepen_to: zit.cone.Horizon = .{ .hash = point, .rule = h.rule, .depth = h.depth };
deepened = (if (paths) |c| zit.cone.Cone.initFrom(gpa, c, deepen_to) else zit.cone.Cone.initHorizon(gpa, &.{}, &.{}, deepen_to)) catch {
streams.err.writeAll("zit update: the requested cone cannot be combined with the store's horizon\n") catch {};
return .refused;
};
if (std.ascii.eqlIgnoreCase(point, h.hash)) {
streams.err.writeAll("zit update: content lies outside the store's cone; widening it under the same horizon from the saved remote\n") catch {};
} else {
streams.err.print("zit update: this check-in's content lies below the store's horizon; deepening to {s} from the saved remote\n", .{point}) catch {};
}
}
}
if (deepened) |*c| {
return if (cmd_pull.deepenHorizon(gpa, io, arena, root_dir, streams, "update", c) == .ok) .fetched else .refused;
}
const requested: ?*const zit.cone.Cone = switch (sparse.*) {
.set => |c| c,
.inherit => blk: {
// Inheriting on a sparse store and still missing content means
// the WORKTREE cone exceeds the STORE cone (or the store lost
// members); densify-to-worktree is not derivable here, so the
// honest policy write is the worktree's own stored cone -- which
// `applyCheckin` resolves itself. Densify fully instead: absent
// a --cone, the operator asked for whatever the checkout wants,
// and the store must at least hold that.
break :blk null;
},
};
var url_buf: [logstore.max_config_str]u8 = undefined;
_ = updateResolveRemote(gpa, io, root_dir, &url_buf) orelse {
streams.err.writeAll(
"zit update: content is elided by the store's sparse cone and no remote is saved\n" ++
"zit update: set one with 'zit remote URL', or re-clone with a wider --cone\n",
) catch {};
return .failed;
};
streams.err.writeAll("zit update: content is elided by the store's sparse cone; fetching from the saved remote\n") catch {};
zit.repocache.writeStoreCone(gpa, io, root_dir, requested);
// A demand fetch has no ambient environment of its own; the stored login
// still authenticates, and a prompt is never raised from here.
const pull_exit = cmd_pull.runPull(gpa, io, arena, &.{}, streams, .{ .now_epoch = 0, .user_env = null });
return if (pull_exit == .ok) .fetched else .failed;
}
/// Sparse-cone RFC section 5.2 -- when the content `update` could not stage is
/// elided under the store's cone, say so and the remedy, and never the
/// foreign-check-in explanation, which alleges a cause this store does not
/// have. True when the refusal was printed.
fn updateElidedRefusal(gpa: std.mem.Allocator, io: std.Io, root_dir: std.Io.Dir, streams: cli.Streams) bool {
const f = update.last_stage_fault orelse return false;
if (f.reason != .content_absent) return false;
// A version purged or shunned on purpose is named as such, in the words
// `cat` uses; the exit stays 1, since update is not a reader.
const absence = zit.absence.absenceAt(gpa, io, root_dir, f.artifactName());
if (absence == .thinned or absence == .shunned or absence == .erased) {
var wbuf: [512]u8 = undefined;
const what = std.fmt.bufPrint(&wbuf, "content for '{s}'", .{f.filePath()}) catch "content";
zit.absence.describeAbsence(streams.err, "update", what, &absence);
streams.err.writeAll("zit update: nothing was modified\n") catch {};
return true;
}
const e = zit.absence.blobElision(gpa, io, root_dir, f.artifactName()) orelse return false;
if (!e.elided) return false;
var dbuf: [160]u8 = undefined;
streams.err.print("zit update: '{s}' is elided by this store's {s}; nothing was modified\n", .{ f.filePath(), zit.absence.describeCone(&e, &dbuf) }) catch {};
if (e.horizon != null) {
streams.err.writeAll("zit update: deepening needs a saved remote ('zit remote URL'); or re-clone with an earlier --horizon\n") catch {};
} else {
streams.err.writeAll("zit update: widen the store cone ('zit update --cone PATH') with a saved remote to fetch it\n") catch {};
}
return true;
}
/// Map a Cone.init refusal. The message states the rule, not a guess at the
/// operator's intent, and never says "missing" or "corrupt" (sparse-cone RFC
/// section 4.1 diagnostic discipline).
fn coneInitFail(s: cli.Streams, verb: []const u8, err: zit.cone.Error) cli.Exit {
switch (err) {
error.OutOfMemory => s.err.print("zit {s}: out of memory\n", .{verb}) catch {},
error.InvalidMember => s.err.print(
"zit {s}: invalid --cone member: members are repository-relative paths using '/', with no '.', '..', or empty components\n",
.{verb},
) catch {},
error.ReservedMember => s.err.print("zit {s}: a --cone member names a reserved control path\n", .{verb}) catch {},
error.Bounds => s.err.print("zit {s}: --cone needs between 1 and 255 members (exclusions included), at least one inclusion\n", .{verb}) catch {},
error.DeadExclusion => s.err.print("zit {s}: a --cone-not member no --cone member covers is a dead rule\n", .{verb}) catch {},
error.Contradiction => s.err.print("zit {s}: one path given as both --cone and --cone-not\n", .{verb}) catch {},
}
return .failure;
}
/// Resolve `update`'s check-in argument to a canonical artifact ID (SF1).
///
/// A canonical 40/64-hex ID short-circuits: it needs no repository state, so
/// update's cold path (open the log read-only, hand the ID to the update
/// engine) is byte-for-byte what it was. Anything else — `trunk`, `tip`, a hash
/// prefix, a date form — opens the repository read-only and runs the shared
/// §8.3 procedure, then hands back the arena-owned canonical ID. The
/// repository view is closed again before the update transaction opens the log,
/// so the two never hold it at once.
fn updateResolveTarget(
arena: std.mem.Allocator,
repo: *Repository,
requested: []const u8,
streams: cli.Streams,
) union(enum) { ok: []const u8, fail: cli.Exit } {
if (requested.len == 0) {
streams.err.writeAll("zit update: check-in '' not found\n") catch {};
return .{ .fail = .failure };
}
if (artifact.validateName(requested)) return .{ .ok = requested };
const rid = repo.resolve(requested, .checkin) catch |e| switch (e) {
error.NotFound => {
// Horizon draft section 5.5 -- under a structural horizon a tag
// applied below the horizon still names a hash, because the
// control artifact is held while the check-in is not. Resolve it
// that way; the apply below then deepens to it.
if (repo.state().symTagTarget(requested)) |target_rid| {
const owned = arena.dupe(u8, repo.hashOf(target_rid)) catch
return .{ .fail = stateOom(streams, "update") };
if (artifact.validateName(owned)) return .{ .ok = owned };
}
streams.err.print("zit update: check-in '{s}' not found\n", .{requested}) catch {};
cli.horizonNameHint(arena, repo.io, repo.root_dir, streams, "update");
return .{ .fail = .failure };
},
error.Ambiguous => {
streams.err.print("zit update: name '{s}' is ambiguous\n", .{requested}) catch {};
return .{ .fail = .failure };
},
error.OutOfMemory => return .{ .fail = stateOom(streams, "update") },
};
// The hash borrows `repo`'s view; copy it out so it outlives the caller's
// repository.
const owned = arena.dupe(u8, repo.hashOf(rid)) catch
return .{ .fail = stateOom(streams, "update") };
std.debug.assert(artifact.validateName(owned));
return .{ .ok = owned };
}
fn updateLogFail(s: cli.Streams, err: logstore.OpenError) cli.Exit {
switch (err) {
error.OutOfMemory => s.err.writeAll("zit update: out of memory\n") catch {},
else => s.err.print("zit update: cannot read repository: {s}\n", .{reasonOf(err)}) catch {},
}
return .failure;
}
/// The merge policy behind `update`'s `CarryResolver`: what uncommitted
/// work becomes when the checkout moves to another check-in.
///
/// This is the same three-way merge `zit merge` runs, with the sides picked for
/// a move rather than a join: base = the check-in the tree is on, ours = the
/// working file, theirs = the target. The result is NOT a merge in the recorded
/// sense — no merge parent is written, because nothing is being joined. The
/// operator's edits simply land on top of the new check-in, which is what makes
/// the subsequent commit an ordinary child of the tip instead of a fork.
///
/// Lives on the CLI side of the seam because it needs the repository and the
/// merge engine; `update.applyCheckinWith` owns the scan and the transaction
/// and needs neither.
const CarryPolicy = struct {
gpa: std.mem.Allocator,
io: std.Io,
/// Owns every byte slice handed back as a carry, so all of them outlive the
/// materialization that writes them.
arena: std.mem.Allocator,
repo: *Repository,
root_dir: std.Io.Dir,
target_id: []const u8,
streams: cli.Streams,
/// Paths whose merge produced conflict markers. Reported after the update
/// commits, not refused: the markers are in the working files to settle.
conflicts: std.ArrayList([]const u8) = .empty,
/// Every path carried across the move (the receipt's MERGE lines).
merged: std.ArrayList([]const u8) = .empty,
/// How many paths were carried, for the success line.
carried: usize = 0,
/// Set when `resolve` returned `Refused`, so the caller knows the paths were
/// already named and does not print a second, generic diagnostic over them.
refused: bool = false,
fn resolver(self: *CarryPolicy) update.CarryResolver {
return .{ .ctx = self, .resolve = resolve };
}
fn resolve(
ctx: *anyopaque,
divergences: []const update.Divergence,
) error{ OutOfMemory, Refused }![]const update.Carry {
const self: *CarryPolicy = @ptrCast(@alignCast(ctx));
return self.build(divergences) catch |err| switch (err) {
error.OutOfMemory => error.OutOfMemory,
error.Refused => {
self.refused = true;
return error.Refused;
},
};
}
fn build(
self: *CarryPolicy,
divergences: []const update.Divergence,
) error{ OutOfMemory, Refused }![]const update.Carry {
// The two check-ins bracketing the move. A checkout with no current
// check-in cannot be dirty against one — the scan reports every managed
// path as `added` — so the base side is simply the empty file set.
const target_rid = self.repo.resolve(self.target_id, .checkin) catch return self.fault("repository is corrupt");
var base_files: ?Repository.FileList = if (self.repo.currentCheckoutRid()) |rid|
(self.repo.files(self.gpa, rid) catch return self.fault("repository is corrupt")) orelse
return self.fault("repository is corrupt")
else
null;
defer if (base_files) |*l| l.deinit(self.gpa);
var target_files = (self.repo.files(self.gpa, target_rid) catch return self.fault("repository is corrupt")) orelse
return self.fault("repository is corrupt");
defer target_files.deinit(self.gpa);
var base_by_path = std.StringHashMap(artifact.FCard).init(self.arena);
if (base_files) |*l| {
var bit = l.iterator();
while (bit.next()) |f| try base_by_path.put(f.filename, f);
}
var target_by_path = std.StringHashMap(artifact.FCard).init(self.arena);
{
var tit = target_files.iterator();
while (tit.next()) |f| try target_by_path.put(f.filename, f);
}
var carry: std.ArrayList(update.Carry) = .empty;
var unmergeable: std.ArrayList([]const u8) = .empty;
for (divergences) |d| {
// Own the path up front. It arrives borrowing storage that dies
// with the scan, and both the carry list (read during
// materialization) and the conflict list (read after the whole call
// returns) outlive that. One dupe per DIVERGENT path only, so a
// clean-ish tree pays nothing.
const path = try self.arena.dupe(u8, d.path);
// Ours: what the operator has right now. A `removed`/`missing` path
// is absent on our side by definition and is not re-read.
const ours: update.WorktreeContent = switch (d.kind) {
.missing, .removed => .absent,
.modified, .added => update.readWorktreeContent(self.arena, self.io, self.root_dir, path) catch
return self.fault("cannot read the working tree"),
};
if (ours == .unsupported) {
try unmergeable.append(self.arena, path);
continue;
}
const ours_side: merge3.Side = switch (ours) {
.content => |c| c.bytes,
.absent => null,
.unsupported => unreachable,
};
const before: ?update.Carry.Content = switch (ours) {
.content => |c| c,
.absent, .unsupported => null,
};
const base_side: merge3.Side = if (base_by_path.get(path)) |f|
(self.repo.blob(self.arena, f.hash.?) catch return self.fault("repository is corrupt")) orelse
return self.fault("repository is corrupt")
else
null;
const target_card = target_by_path.get(path);
const theirs_side: merge3.Side = if (target_card) |f|
(self.repo.blob(self.arena, f.hash.?) catch return self.fault("repository is corrupt")) orelse
return self.fault("repository is corrupt")
else
null;
// B-merge-23: the working file keeps its own mode. When the path is
// absent on our side the target's is the only one there.
const mode: artifact.FileMode = if (before) |c|
c.mode
else if (target_card) |f|
(if (f.perm != null and std.mem.eql(u8, f.perm.?, "x")) .executable else .regular)
else
.regular;
const outcome = try merge3.classifyFile(self.arena, base_side, ours_side, theirs_side, .conflict);
const after: ?update.Carry.Content = switch (outcome) {
// Our side is already correct — which for a dirty tree means the
// file on disk stays exactly as the operator left it.
.unchanged => before,
.take_other => if (theirs_side) |b| .{ .bytes = b, .mode = mode } else null,
.delete => null,
.clean_merge => |r| .{ .bytes = r.bytes, .mode = mode },
.text_conflict => |r| blk: {
try self.conflicts.append(self.arena, path);
break :blk .{ .bytes = r.bytes, .mode = mode };
},
.whole_file_conflict => blk: {
// A type change, or edited-here/deleted-there. Either
// reading silently destroys work, so it is named and
// refused rather than guessed at — the line `merge` draws.
if (ours_side == null or theirs_side == null) {
try unmergeable.append(self.arena, path);
break :blk before;
}
try self.conflicts.append(self.arena, path);
break :blk .{ .bytes = try merge3.writeEnvelope(self.arena, ours_side, base_side, theirs_side), .mode = mode };
},
};
try carry.append(self.arena, .{ .path = path, .after = after, .before = before });
try self.merged.append(self.arena, path);
}
// Refuse before the update mutates anything, and name the paths. Already
// ascending: the divergence list is sorted and this walks it in order.
if (unmergeable.items.len != 0) {
for (unmergeable.items) |p| {
self.streams.err.print("zit update: cannot merge local changes to {s}\n", .{p}) catch {};
}
self.streams.err.print(
"zit update: {d} path(s) changed here and changed type or were removed there;\n" ++
"commit or revert them, then update again\n",
.{unmergeable.items.len},
) catch {};
return error.Refused;
}
self.carried = carry.items.len;
return carry.items;
}
/// A read fault mid-merge: report it, then refuse. `Refused` (not a raw
/// error) so the update aborts down the one path that has already
/// guaranteed nothing was mutated.
fn fault(self: *CarryPolicy, reason: []const u8) error{Refused} {
self.streams.err.print("zit update: cannot merge local changes: {s}\n", .{reason}) catch {};
return error.Refused;
}
/// What a carrying update says when it is done.
///
/// Silence on a clean tree: an update that carried nothing is the update
/// that always was, and its success has never printed anything. Otherwise
/// the carried count goes to stdout, and any conflict goes to stderr with
/// exit 1 — the same split and status `merge` uses, because the operator is
/// in the same position either way.
fn report(self: *const CarryPolicy, streams: cli.Streams) cli.Exit {
if (self.carried == 0) return .ok;
if (self.conflicts.items.len != 0) {
for (self.conflicts.items) |p| {
streams.err.print("zit update: conflict in {s}\n", .{p}) catch {};
}
streams.err.print(
"zit update: {d} conflict(s); resolve them and commit\n",
.{self.conflicts.items.len},
) catch {};
return .failure;
}
streams.out.print("carried {d} local change(s) onto the new check-in\n", .{self.carried}) catch {};
return .ok;
}
};
/// The project-level settings one `update` needs, read from the ONE config
/// frame the verb already holds. Both degrade to empty when the setting is
/// absent or unreadable: empty `manifest` is the pre-setting behaviour (no build
/// stamps) and empty `empty_dirs` creates nothing, so a settings source that
/// cannot be read costs the operator neither the materialization nor any data.
const ProjectPolicy = struct {
/// The stamp selection a checkout with no choice of its own inherits.
manifest: []const u8,
/// The directories to create after the tree is written.
empty_dirs: []const u8,
};
/// Reads both of `ProjectPolicy`'s values in one place, before update forks
/// into its apply and retry arms, so the retry gets them for free and neither
/// arm can resolve a different value than the other. Fossil reads `empty-dirs`
/// at the same point (update.c calls `ensure_empty_dirs_created` before the
/// update begins, and its cached value is what the post-update call sees), so
/// a `.fossil-settings/empty-dirs` arriving in THIS update takes effect at the
/// next one — as in fossil.
fn projectPolicy(
io: std.Io,
arena: std.mem.Allocator,
root_dir: std.Io.Dir,
amb: cli.Ambient,
cfg: ?*const logstore.Config,
) ProjectPolicy {
return .{
.manifest = projectSetting(io, arena, root_dir, amb, cfg, .manifest),
.empty_dirs = projectSetting(io, arena, root_dir, amb, cfg, .empty_dirs),
};
}
/// One setting's value from the frame the caller holds, or empty when no tier
/// answers and no default applies. The `catch` is the whole reason it exists:
/// its callers want a string, not an error union, for a setting whose absence
/// is an ordinary state.
pub fn projectSetting(
io: std.Io,
arena: std.mem.Allocator,
root_dir: std.Io.Dir,
amb: cli.Ambient,
cfg: ?*const logstore.Config,
setting: zit.settings.Setting,
) []const u8 {
const r = zit.repo_config.localSetting(io, arena, root_dir, .{ .environ = amb.environ }, cfg, setting) catch return "";
return r.value;
}
pub fn updateApplyFail(s: cli.Streams, target_id: []const u8, err: update.ApplyError) cli.Exit {
switch (err) {
// applyCheckin never emits this: only applyMerge's cross-cone guard
// does, and this switch maps a checkin materialization. The unreachable
// IS the assertion; a future emitter trips it in tests immediately.
error.SparseMergeUnsupported => unreachable,
error.FileContentMissing => {
var b: [512]u8 = undefined;
s.err.print("zit update: {s}\n", .{update.stageFaultReason(&b)}) catch {};
// Same class `open`'s preflight names. `update` is handed its target
// rather than resolving one, so it has no preflight — but the cause
// and the wording should not depend on which verb met it.
var lines = std.mem.splitScalar(u8, update.foreign_checkin_note, '\n');
while (lines.next()) |line| {
if (line.len == 0) continue;
s.err.print("zit update: {s}\n", .{line}) catch {};
}
},
error.OutOfMemory => s.err.writeAll("zit update: out of memory\n") catch {},
error.InvalidCheckinId => s.err.print(
"zit update: invalid check-in ID '{s}' (expected 40 or 64 lowercase hexadecimal digits)\n",
.{target_id},
) catch {},
error.CheckinNotFound => s.err.print("zit update: check-in '{s}' not found\n", .{target_id}) catch {},
error.CheckinContentMissing => s.err.print(
"zit update: cannot read repository: check-in '{s}' content is missing\n",
.{target_id},
) catch {},
error.CheckinNameMismatch => s.err.print(
"zit update: cannot read repository: check-in '{s}' content does not match its name\n",
.{target_id},
) catch {},
error.AggregateChecksumMismatch => s.err.print(
"zit update: check-in '{s}' R checksum disagrees with the content its F cards name\n",
.{target_id},
) catch {},
error.TargetNotManifest => s.err.print("zit update: check-in '{s}' is not a valid manifest\n", .{target_id}) catch {},
error.BaselineNotFound => s.err.print(
"zit update: cannot read repository: check-in '{s}' baseline is not found\n",
.{target_id},
) catch {},
error.BaselineContentMissing => s.err.print(
"zit update: cannot read repository: check-in '{s}' baseline content is missing\n",
.{target_id},
) catch {},
error.BaselineNameMismatch => s.err.print(
"zit update: cannot read repository: check-in '{s}' baseline content does not match its name\n",
.{target_id},
) catch {},
error.BaselineNotManifest => s.err.print(
"zit update: check-in '{s}' baseline is not a valid manifest\n",
.{target_id},
) catch {},
error.StateRecordInvalid => s.err.writeAll("zit update: cannot read repository: " ++ update.state_record_invalid_reason ++ "\n") catch {},
error.Corrupt => s.err.writeAll("zit update: cannot read repository: repository is corrupt\n") catch {},
error.InvalidPath => s.err.print("zit update: check-in '{s}' names an invalid file path\n", .{target_id}) catch {},
error.ReservedPath => s.err.print("zit update: check-in '{s}' names a reserved file path\n", .{target_id}) catch {},
error.SymlinkUnsupported => s.err.print(
"zit update: check-in '{s}' contains an unsupported symlink entry\n",
.{target_id},
) catch {},
error.CurrentStateInvalid => s.err.writeAll("zit update: current working-tree state is invalid\n") catch {},
error.WorktreeNotClean => s.err.writeAll("zit update: working tree is not clean\n") catch {},
error.UnmanagedCollision => s.err.writeAll("zit update: an untracked file or directory is in the way\n") catch {},
error.Storage => s.err.writeAll("zit update: cannot update working tree: input/output error\n") catch {},
error.TransactionUnavailable => s.err.writeAll("zit update: cannot create a transaction directory\n") catch {},
error.RollbackFailed => s.err.writeAll(
"zit update: update failed and could not be rolled back; the previous working-tree state is retained for recovery\n",
) catch {},
error.CleanupFailed => s.err.writeAll(
"zit update: update committed, but the transaction directory could not be removed\n",
) catch {},
}
return .failure;
}