//! `zit tag`: list and manage tags on check-ins.
const std = @import("std");
const zit = @import("zit");
const cli = @import("zit").cli;
const Repository = @import("zit").Repository;
const repostate = zit.repostate;
const artifact = zit.artifact;
const control_artifact = @import("control_artifact.zig");
const diagnostics = @import("../diagnostics.zig");
const help_pages = @import("../help.zig");
const stateOom = diagnostics.stateOom;
const openRepo = diagnostics.openRepo;
const mintControlArtifact = control_artifact.mintControlArtifact;
const tag_help = help_pages.tag_help;
const checkin_display = @import("checkin_display.zig");
const sym_prefix = checkin_display.sym_prefix;
/// `zit tag list [--raw] [CHECKIN]` (alias `ls`), `zit tag add [--raw]
/// [--propagate] NAME CHECKIN [VALUE]`, and `zit tag cancel [--raw] NAME
/// CHECKIN`.
///
/// `list` is read-only enumeration over the crosslinked repo-view (repo-state
/// §5.1/§5.2): without `--raw`, only singleton `sym-` tags are shown, with the
/// prefix stripped, so branch machinery, raw properties, and inherited names
/// cannot masquerade as one-check-in release names. With `--raw`, every active
/// tag is shown with its stored prefix. The views are pure presentation over
/// the `tagNames`/`tagNamesOfType`/`tagsOf` derivations.
///
/// `add` and `cancel` are the write paths (REGRESSION B6): each mints one
/// control artifact carrying a single T card.
pub fn runTag(
gpa: std.mem.Allocator,
io: std.Io,
arena: std.mem.Allocator,
verb_args: []const []const u8,
streams: cli.Streams,
amb: cli.Ambient,
) cli.Exit {
const parsed = switch (cli.parseTagArgs(verb_args)) {
.ok => |p| p,
.unknown_option => |tok| return cli.usageError(streams, "tag", .unknown_option, tok),
.extra_argument => |tok| return cli.usageError(streams, "tag", .extra_argument, tok),
.bad_subcommand => |tok| return cli.usageError(streams, "tag", .bad_subcommand, tok),
.no_name => return cli.usageError(streams, "tag", .no_name, ""),
.no_checkin => return cli.usageError(streams, "tag", .no_checkin, ""),
.option_not_for_subcommand => |tok| return cli.usageError(streams, "tag", .option_not_for_subcommand, tok),
};
if (parsed.help) {
streams.out.writeAll(tag_help) catch {};
return .ok;
}
// The mutating arms own their own repository lifetime: the read view must
// be CLOSED before the read-write append, so they cannot share the listing
// path's `defer repo.deinit`.
if (parsed.sub != .list) return runTagWrite(gpa, io, arena, parsed, streams, amb);
var repo: Repository = undefined;
var root_dir: std.Io.Dir = undefined;
const rc = openRepo(gpa, io, arena, streams, "tag", amb.repo_override, parsed.no_cache, true, &repo, &root_dir);
if (rc != .ok) return rc;
defer root_dir.close(io);
defer repo.deinit(gpa);
if (parsed.checkin) |name| return runTagCheckin(gpa, &repo, name, parsed.raw, streams);
// §5.1/§2: plain output is the singleton symbolic release namespace;
// --raw retains the complete active tag-name view.
const names = if (parsed.raw)
repo.state().tagNames(gpa)
else
repo.state().tagNamesOfType(gpa, .singleton);
const owned = names catch return stateOom(streams, "tag");
defer gpa.free(owned);
renderTagNames(streams.out, owned, parsed.raw);
return .ok;
}
/// The `zit tag list CHECKIN` arm: resolve CHECKIN through the §8.3 procedure
/// and list tags visible on it. Plain output is restricted to singleton
/// symbolic release names; `raw` exposes every active tag with its stored
/// prefix and value. An unresolvable or ambiguous name is a failure (exit 1,
/// diagnostic to stderr); a resolved check-in with no matching tags lists
/// nothing (empty stdout, exit 0).
fn runTagCheckin(
gpa: std.mem.Allocator,
repo: *Repository,
name: []const u8,
raw: bool,
streams: cli.Streams,
) cli.Exit {
const rid = repo.resolve(name, .checkin) catch |e| {
switch (e) {
error.NotFound => {
streams.err.print("zit tag: check-in '{s}' not found\n", .{name}) catch {};
cli.horizonNameHint(gpa, repo.io, repo.root_dir, streams, "tag");
},
error.Ambiguous => streams.err.print("zit tag: check-in '{s}' is ambiguous\n", .{name}) catch {},
// Settling an equal-mtime tie by ancestry allocates (`MtimeMaxPick`).
error.OutOfMemory => return stateOom(streams, "tag"),
}
return .failure;
};
const tags = repo.state().tagsOf(gpa, rid) catch return stateOom(streams, "tag");
defer gpa.free(tags);
renderTagList(streams.out, tags, raw);
return .ok;
}
/// Tag-name prefixes fossil reserves for its own crosslinking of wiki pages,
/// tickets, and technotes. A T card in one of these namespaces asserts that
/// its target IS such an artifact, so minting one from the tag verb would
/// forge that association — fossil refuses them here for the same reason, and
/// matching the refusal keeps a zit-written repository readable by fossil
/// without surprises.
const reserved_tag_prefixes = [_][]const u8{ "wiki-", "tkt-", "event-" };
/// The `zit tag add` / `zit tag cancel` arm (REGRESSION B6): mint one control
/// artifact carrying a single `T <sign><name> <hash> [value]` card.
///
/// Mirrors `amend`'s shape, which is the point — both resolve a check-in, then
/// compose a T run, then mint. Resolution first, over a read view that is closed
/// before the read-write append (commit's durability pattern); the resolved hash
/// is duped onto `arena` so it outlives that view. A failure to resolve mints
/// NOTHING: every diagnostic below happens before the single fsync.
///
/// Default sign is SINGLETON (`+`), so a symbolic name pins to exactly this
/// check-in and is not inherited by its descendants — see `composeTagCards`
/// for why that sign is the whole correctness argument, and why `--propagate`
/// belongs to the raw namespace.
fn runTagWrite(
gpa: std.mem.Allocator,
io: std.Io,
arena: std.mem.Allocator,
parsed: cli.TagArgs,
streams: cli.Streams,
amb: cli.Ambient,
) cli.Exit {
const name = parsed.name.?; // the parser's `no_name` arm guarantees it
const checkin = parsed.checkin.?; // likewise `no_checkin`
// An empty NAME names nothing (repo-state §2), rejected before any store is
// opened — the same early check `commit --branch` makes.
if (name.len == 0) {
streams.err.writeAll("zit tag: NAME must not be empty\n") catch {};
return .failure;
}
// An empty VALUE cannot be written: §4.7.16's value is `[ SP value ]`, so
// "present but empty" has no spelling on the wire. Omitting VALUE is how
// you say valueless.
if (parsed.value) |v| {
if (v.len == 0) {
streams.err.writeAll("zit tag: VALUE must not be empty; omit it for a valueless tag\n") catch {};
return .failure;
}
}
for (reserved_tag_prefixes) |prefix| {
if (std.mem.startsWith(u8, name, prefix)) {
streams.err.print(
"zit tag: '{s}' is reserved for fossil's own crosslinking; pick a name outside it\n",
.{prefix},
) catch {};
return .failure;
}
}
var repo: Repository = undefined;
var root_dir: std.Io.Dir = undefined;
const rc = openRepo(gpa, io, arena, streams, "tag", amb.repo_override, parsed.no_cache, true, &repo, &root_dir);
if (rc != .ok) return rc;
defer root_dir.close(io);
var target_hash: []const u8 = undefined;
{
defer repo.deinit(gpa);
const rid = repo.resolve(checkin, .checkin) catch |e| {
switch (e) {
error.NotFound => {
streams.err.print("zit tag: check-in '{s}' not found\n", .{checkin}) catch {};
cli.horizonNameHint(gpa, io, root_dir, streams, "tag");
},
error.Ambiguous => streams.err.print("zit tag: check-in '{s}' is ambiguous\n", .{checkin}) catch {},
// Settling an equal-mtime tie by ancestry allocates.
error.OutOfMemory => return stateOom(streams, "tag"),
}
return .failure;
};
target_hash = arena.dupe(u8, repo.hashOf(rid)) catch return stateOom(streams, "tag");
}
// The mint targets a resolved check-in by its full §3.6 artifact id.
std.debug.assert(artifact.validateName(target_hash));
const sign: artifact.TSign = switch (parsed.sub) {
.cancel => .cancel,
.add => if (parsed.propagate) .propagate else .add,
.list => unreachable, // the caller routes `.list` elsewhere
};
const tags = cli.composeTagCards(arena, target_hash, .{
.sign = sign,
.name = name,
.raw = parsed.raw,
.value = parsed.value,
}) catch return stateOom(streams, "tag");
var cname_buf: [64]u8 = undefined;
const control_name = mintControlArtifact(gpa, io, root_dir, amb, tags, &cname_buf) catch |e|
return tagLogFail(streams, e);
// One confirmation line naming the control artifact, as `amend` reports its
// mint. Every diagnostic already went to stderr.
streams.out.print("tag {s}\n", .{control_name}) catch {};
return .ok;
}
/// Renders a `tag add` mint failure. Exhaustive over the widest closed set
/// (`logstore.OpenError`); the narrower put/commit sets coerce into it.
fn tagLogFail(s: cli.Streams, err: control_artifact.MintError) cli.Exit {
switch (err) {
error.StoreBusy => {}, // the lock notice already said it
error.OutOfMemory => s.err.writeAll("zit tag: out of memory\n") catch {},
error.Storage => s.err.writeAll("zit tag: cannot write the tag: input/output error\n") catch {},
error.Corrupt => s.err.writeAll("zit tag: the repository is corrupt\n") catch {},
}
return .failure;
}
/// §5.1/§2 no-arg listing: one tag name per line, ascending. By default only
/// symbolic ('sym-') tags are listed — they are the user-facing names, and are
/// surfaced with the prefix stripped. The machinery tags (`branch`, `closed`)
/// and other reserved prefixes are not listed as bare names: branch identity
/// is already present via its stripped 'sym-' tag.
///
/// `raw` lists every tag name verbatim, prefixes intact. It is the read half
/// of `tag add --raw`: a property tag is deliberately outside the name space,
/// so without this the tag you just wrote would be invisible here. Pure;
/// bounded by `names.len`.
fn renderTagNames(out: *std.Io.Writer, names: []const []const u8, raw: bool) void {
for (names) |name| {
if (raw) {
out.writeAll(name) catch {};
} else {
if (!std.mem.startsWith(u8, name, sym_prefix)) continue;
out.writeAll(name[sym_prefix.len..]) catch {};
}
out.writeAll("\n") catch {};
}
}
/// §5.1/§5.2 CHECKIN listing: active tags in raw-name order, as `tagsOf`
/// returns them. Plain output includes only singleton `sym-` tags, stripped to
/// their user-facing names. Raw output includes every active tag with its
/// stored prefix intact. A tag carrying a value payload (§5.2) prints
/// `<name> <value>`; a valueless tag prints `<name>` alone. Pure; bounded by
/// `tags.len`.
fn renderTagList(
out: *std.Io.Writer,
tags: []const repostate.RepoState.TagEntry,
raw: bool,
) void {
for (tags) |tag| {
if (!raw and (tag.tagtype != .singleton or !std.mem.startsWith(u8, tag.name, sym_prefix))) {
continue;
}
const shown = if (raw) tag.name else tag.name[sym_prefix.len..];
out.writeAll(shown) catch {};
if (tag.value) |v| {
out.writeAll(" ") catch {};
out.writeAll(v) catch {};
}
out.writeAll("\n") catch {};
}
}