//! `zit cone`: show or edit the checkout's sparse cone.
const std = @import("std");
const zit = @import("zit");
const cli = @import("zit").cli;
const update = @import("zit").update;
const checkout = @import("zit").checkout;
const diagnostics = @import("../cli/diagnostics.zig");
const help_pages = @import("../cli/help.zig");
const not_a_repo_msg = diagnostics.not_a_repo_msg;
const cmd_update = @import("update.zig");
const runUpdate = cmd_update.runUpdate;
/// `zit cone [add PATH... | remove PATH...]` — show or edit the checkout's
/// sparse cone (sparse-cone RFC section 3). Pure sugar: the edit composes
/// the stored member set with the delta and drives `runUpdate` with
/// `--cone=` flags at the current check-in, so demand fetch (section 6.4),
/// dematerialization, and the store-policy-follows rule all come free and
/// stay in one code path.
pub fn runCone(
gpa: std.mem.Allocator,
io: std.Io,
arena: std.mem.Allocator,
verb_args: []const []const u8,
streams: cli.Streams,
amb: cli.Ambient,
) cli.Exit {
if (verb_args.len >= 1 and (std.mem.eql(u8, verb_args[0], "-h") or std.mem.eql(u8, verb_args[0], "--help"))) {
streams.out.writeAll(help_pages.cone_help) catch {};
return .ok;
}
const root = (cli.discoverRoot(arena, io) catch {
streams.err.writeAll("zit cone: 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);
// The worktree cone: the checkout container's section, absent = dense.
var stored = update.readStoredCone(gpa, io, root_dir) catch {
streams.err.writeAll("zit cone: cannot read the checkout state\n") catch {};
return .failure;
};
defer if (stored) |*c| c.deinit(gpa);
if (verb_args.len == 0) {
if (stored) |*c| {
// A comment in the cone-file grammar: the listing stays a valid
// --cone-file, and the property, which a cone file cannot carry,
// is still said.
if (c.parents) streams.out.writeAll("# parent levels: on (--cone-parents)\n") catch {};
for (c.members) |m| streams.out.print("{s}\n", .{m}) catch {};
// The cone-file grammar's marker: `!member` is an exclusion.
for (c.not_members) |m| streams.out.print("!{s}\n", .{m}) catch {};
} else {
streams.out.writeAll("dense\n") catch {};
}
return .ok;
}
const action = verb_args[0];
const paths = verb_args[1..];
if (std.mem.eql(u8, action, "test")) {
return coneTest(gpa, io, arena, paths, streams, root_dir, &stored);
}
const adding = std.mem.eql(u8, action, "add");
const removing = std.mem.eql(u8, action, "remove");
if (!adding and !removing) return cli.usageError(streams, "cone", .bad_subcommand, action);
if (paths.len == 0) return cli.usageError(streams, "cone", .no_paths, "");
if (removing and stored == null) {
streams.err.writeAll("zit cone: this checkout is dense; there is no cone to remove from\n") catch {};
return .failure;
}
// Compose the new member set: stored ∪ paths, or stored ∖ paths. Bounded
// by the cone cap; Cone.init re-validates and re-normalizes the result.
var members: std.ArrayListUnmanaged([]const u8) = .empty;
defer members.deinit(gpa);
var not_members: std.ArrayListUnmanaged([]const u8) = .empty;
defer not_members.deinit(gpa);
if (stored) |*c| {
for (c.members) |m| {
if (removing) {
var drop = false;
for (paths) |p2| {
if (std.mem.eql(u8, m, p2)) drop = true;
}
if (drop) continue;
}
members.append(gpa, m) catch return coneOom(streams);
}
for (c.not_members) |m| {
if (removing) {
var drop = false;
for (paths) |p2| {
if (std.mem.eql(u8, m, p2)) drop = true;
}
if (drop) continue;
}
not_members.append(gpa, m) catch return coneOom(streams);
}
}
if (adding) {
for (paths) |p2| members.append(gpa, p2) catch return coneOom(streams);
}
if (removing and members.items.len == 0) {
streams.err.writeAll("zit cone: removing every member would leave an empty cone; use 'zit update --dense' to densify\n") catch {};
return .failure;
}
if (members.items.len + not_members.items.len > zit.cone.max_members) {
streams.err.print("zit cone: the cone holds at most {d} members\n", .{zit.cone.max_members}) catch {};
return .failure;
}
// Resolve the current check-in and drive the one materialization path.
var ck_buf: [checkout.max_ck_payload + 1]u8 = undefined;
const current = (checkout.read(io, root_dir, &ck_buf) catch {
streams.err.writeAll("zit cone: cannot read the checkout state\n") catch {};
return .failure;
}) orelse {
streams.err.writeAll("zit cone: no check-in is open\n") catch {};
return .failure;
};
if (current.version.len == 0) {
streams.err.writeAll("zit cone: no check-in is open\n") catch {};
return .failure;
}
var update_args: std.ArrayListUnmanaged([]const u8) = .empty;
defer update_args.deinit(gpa);
for (members.items) |m| {
const flag = std.fmt.allocPrint(arena, "--cone={s}", .{m}) catch return coneOom(streams);
update_args.append(gpa, flag) catch return coneOom(streams);
}
for (not_members.items) |m| {
const flag = std.fmt.allocPrint(arena, "--cone-not={s}", .{m}) catch return coneOom(streams);
update_args.append(gpa, flag) catch return coneOom(streams);
}
// `update --cone=` replaces the cone wholesale; the property is restated
// so an edit to the members keeps it.
if (stored) |*c| if (c.parents) update_args.append(gpa, "--cone-parents") catch return coneOom(streams);
const version_owned = arena.dupe(u8, current.version) catch return coneOom(streams);
update_args.append(gpa, version_owned) catch return coneOom(streams);
return runUpdate(gpa, io, arena, update_args.items, streams, amb);
}
fn coneOom(s: cli.Streams) cli.Exit {
s.err.writeAll("zit cone: out of memory\n") catch {};
return .failure;
}
/// Largest `-` (stdin) path list `zit cone test` reads. Paths are not
/// members, so the cone's 255-member cap does not bound this list; the bound
/// exists so the read is finite by inspection rather than by trusting the
/// writer at the other end of the pipe. Generous enough for the full file
/// list of a very large tree.
const max_cone_test_stdin: usize = 8 * 1024 * 1024;
/// `zit cone test PATH...` — classify paths against a stored cone and
/// name the member that decided each, materializing nothing.
///
/// The verdict alone is all git's `sparse-checkout check-rules` can answer,
/// because every match there is a hash lookup against a directory set. Here
/// coverage is decided by the LONGEST member across both polarities, so the
/// deciding member is the real answer to "why isn't this file here" — and it
/// is exactly the token to hand `zit cone remove`, the usual next step. The
/// member prints bare for that reason: the verdict column already carries the
/// polarity (a named member under `elided` is necessarily an exclusion), so a
/// marker would only make the column unpasteable.
fn coneTest(
gpa: std.mem.Allocator,
io: std.Io,
arena: std.mem.Allocator,
args: []const []const u8,
streams: cli.Streams,
root_dir: std.Io.Dir,
worktree_cone: *?zit.cone.Cone,
) cli.Exit {
var use_store = false;
var quiet = false;
var read_stdin = false;
var paths: std.ArrayListUnmanaged([]const u8) = .empty;
defer paths.deinit(gpa);
for (args) |a| {
if (std.mem.eql(u8, a, "-h") or std.mem.eql(u8, a, "--help")) {
streams.out.writeAll(help_pages.cone_help) catch {};
return .ok;
} else if (std.mem.eql(u8, a, "--store")) {
use_store = true;
} else if (std.mem.eql(u8, a, "--quiet")) {
quiet = true;
} else if (std.mem.eql(u8, a, "-")) {
read_stdin = true;
} else if (a.len >= 2 and a[0] == '-') {
return cli.usageError(streams, "cone test", .unknown_option, a);
} else {
paths.append(gpa, a) catch return coneOom(streams);
}
}
if (read_stdin) {
const stdin = std.Io.File.stdin();
var read_buf: [64 * 1024]u8 = undefined;
var reader = stdin.readerStreaming(io, &read_buf);
const blob = reader.interface.allocRemaining(arena, .limited(max_cone_test_stdin)) catch {
streams.err.print(
"zit cone test: cannot read paths from stdin, or more than {d} bytes were given\n",
.{max_cone_test_stdin},
) catch {};
return .failure;
};
var lines = std.mem.splitScalar(u8, blob, '\n');
while (lines.next()) |raw| {
// Only the line ending is stripped: a leading or trailing space
// is part of the path, and validation is what refuses it.
const line = std.mem.trimEnd(u8, raw, "\r");
if (line.len == 0) continue; // A trailing newline is not a path.
paths.append(gpa, line) catch return coneOom(streams);
}
}
if (paths.items.len == 0) return cli.usageError(streams, "cone test", .no_paths, "");
// Validated before any classification, so a path that could never be
// tracked is a usage error rather than a silent `elided` (§3.2 defers
// member validation to the tracked-path rules; the same rules apply to
// what we classify).
for (paths.items) |p| {
zit.control_paths.validateWorktreePath(p) catch {
streams.err.print(
"zit cone test: not a repository-relative path: {s}\n",
.{p},
) catch {};
return .usage;
};
}
// `--store` asks about the STORE cone, which is a different question:
// a path present in the checkout but absent from the store is a real
// condition, and the two cones need not agree.
var store_cone = if (use_store) zit.repocache.readStoreCone(gpa, io, root_dir) else null;
defer if (store_cone) |*c| c.deinit(gpa);
const cone: ?*const zit.cone.Cone = if (use_store)
(if (store_cone) |*c| c else null)
else
(if (worktree_cone.*) |*c| c else null);
var width: usize = 0;
for (paths.items) |p| width = @max(width, p.len);
var any_elided = false;
for (paths.items) |p| {
// A dense cone elides nothing, so every path is covered and no member
// decided it. Reporting that truthfully keeps the exit code usable as
// a predicate: in a dense checkout the file really is there.
const d: zit.cone.Decision = if (cone) |c| c.decide(p) else .{ .covered = true, .member = null };
if (!d.covered) any_elided = true;
if (quiet) continue;
const verdict = if (d.covered) "covered" else "elided";
const reason = if (d.member) |m| m else if (cone == null) "(dense)" else if (d.parents) "(parent directory)" else "(no member covers)";
streams.out.print("{s}", .{verdict}) catch {};
conePad(streams.out, verdict.len, 8);
streams.out.print("{s}", .{p}) catch {};
conePad(streams.out, p.len, width + 2);
streams.out.print("{s}\n", .{reason}) catch {};
}
return if (any_elided) .failure else .ok;
}
/// Column padding for `cone test`, so the deciding member lines up under a
/// list of unequal paths. Widths are computed from the input, never fixed.
fn conePad(w: *std.Io.Writer, have: usize, want: usize) void {
var i = have;
while (i < want) : (i += 1) w.writeByte(' ') catch return;
}