//! `zit branch`: list and manage branches.
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 branch_help = help_pages.branch_help;
pub fn runBranch(
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.parseBranchArgs(verb_args)) {
.ok => |a| a,
.unknown_option => |tok| return cli.usageError(streams, "branch", .unknown_option, tok),
.extra_argument => |tok| return cli.usageError(streams, "branch", .extra_argument, tok),
};
if (parsed.help) {
streams.out.writeAll(branch_help) catch {};
return .ok;
}
var repo: Repository = undefined;
var root_dir: std.Io.Dir = undefined;
const rc = openRepo(gpa, io, arena, streams, "branch", amb.repo_override, parsed.no_cache, true, &repo, &root_dir);
if (rc != .ok) return rc;
defer root_dir.close(io);
defer repo.deinit(gpa);
// §6.3: the branch set is derived by grouping active branch tags — never
// stored, never re-hardcoded here.
const entries = repo.state().branches(gpa) catch return stateOom(streams, "branch");
defer gpa.free(entries);
// §6.1/§6.4: mark the checked-out check-in's branch, resolved through the
// active-tag filter and the config main-branch. `currentCheckoutRid`
// guarantees `cur` bears an event, so `branchOf`'s precondition holds.
const cur = repo.currentCheckoutRid();
const current_name: ?[]const u8 =
if (cur) |r| repo.branchOf(r) else null;
switch (parsed.action) {
.list => {
// -c keeps closed branches only; -t orders by most
// recent change; -r reverses whichever order is in force.
var rows: std.ArrayList(repostate.RepoState.BranchEntry) = .empty;
defer rows.deinit(gpa);
for (entries) |e| {
if (parsed.closed_only and !e.closed) continue;
rows.append(gpa, e) catch return stateOom(streams, "branch");
}
if (parsed.by_time) std.mem.sort(repostate.RepoState.BranchEntry, rows.items, {}, struct {
fn newer(_: void, a: repostate.RepoState.BranchEntry, b: repostate.RepoState.BranchEntry) bool {
return a.mtime > b.mtime;
}
}.newer);
if (parsed.reverse) std.mem.reverse(repostate.RepoState.BranchEntry, rows.items);
if (parsed.verbose) {
// -v: where each branch is. The bare list stays
// Fossil's names, one per line.
for (rows.items) |e| {
var tbuf: [32]u8 = undefined;
const is_cur = current_name != null and std.mem.eql(u8, current_name.?, e.name);
streams.out.print("{s} {s} {s} {s}{s}\n", .{ if (is_cur) "*" else " ", e.name, cli.shortHash(repo.hashOf(e.tip)), cli.humanTime(e.mtime, &tbuf), if (e.closed) " (closed)" else "" }) catch {};
}
return .ok;
}
renderBranchList(streams.out, rows.items, current_name);
return .ok;
},
.current => {
const name = current_name orelse {
streams.err.writeAll("zit branch current: no checkout here\n") catch {};
return .failure;
};
streams.out.print("{s}\n", .{name}) catch {};
return .ok;
},
.info => {
const name = parsed.name orelse return cli.usageError(streams, "branch", .no_name, "");
for (entries) |e| {
if (!std.mem.eql(u8, e.name, name)) continue;
var iso_buf: [19]u8 = undefined;
const iso = cli.formatWriterTimestamp(@intCast(e.mtime / 1000), &iso_buf);
const root_rid = repo.resolve(name, .branch) catch null;
streams.out.print("branch: {s}{s}\ntip: {s} {s}\ncheck-ins: {d}\n", .{ e.name, if (e.closed) " (closed)" else "", repo.hashOf(e.tip), iso, e.count }) catch {};
if (root_rid) |r| streams.out.print("root: {s}\n", .{repo.hashOf(r)}) catch {};
return .ok;
}
streams.err.print("zit branch: no branch named '{s}'\n", .{name}) catch {};
cli.horizonNameHint(gpa, io, root_dir, streams, "branch");
return .failure;
},
.close, .reopen, .hide, .unhide => {
const name = parsed.name orelse return cli.usageError(streams, "branch", .no_name, "");
const tip_rid = repo.resolve(name, .checkin) catch {
streams.err.print("zit branch: no branch named '{s}'\n", .{name}) catch {};
cli.horizonNameHint(gpa, io, root_dir, streams, "branch");
return .failure;
};
const target_hash = arena.dupe(u8, repo.hashOf(tip_rid)) catch return stateOom(streams, "branch");
const raw_name: []const u8 = switch (parsed.action) {
.close, .reopen => "closed",
else => "hidden",
};
const sign: artifact.TSign = switch (parsed.action) {
.close, .hide => .add,
else => .cancel,
};
const tags = cli.composeTagCards(arena, target_hash, .{ .sign = sign, .name = raw_name, .raw = true, .value = null }) catch return stateOom(streams, "branch");
var cname_buf: [64]u8 = undefined;
const control_name = mintControlArtifact(gpa, io, root_dir, amb, tags, &cname_buf) catch |e|
return branchLogFail(streams, e);
streams.out.print("branch {s} {s} at {s} ({s})\n", .{ @tagName(parsed.action), name, target_hash[0..12], control_name }) catch {};
return .ok;
},
.new => {
// A new branch is a check-in on it (repo-state §6.2), so this is
// the commit path with --branch and --allow-empty, from the
// checkout it is on. A BASIS other than the checkout needs an
// update first; saying so beats minting from the wrong parent.
const name = parsed.name orelse return cli.usageError(streams, "branch", .no_name, "");
if (parsed.basis) |b| {
const want = repo.resolve(b, .checkin) catch {
streams.err.print("zit branch new: '{s}' is not a check-in\n", .{b}) catch {};
return .failure;
};
if (cur == null or cur.? != want) {
streams.err.print("zit branch new: the checkout is not at '{s}'; run 'zit update {s}' first\n", .{ b, b }) catch {};
return .failure;
}
}
const msg = std.fmt.allocPrint(arena, "Create new branch named \"{s}\"", .{name}) catch return stateOom(streams, "branch");
return @import("commit.zig").runCommitIn(gpa, io, arena, &.{ "-m", msg, "--branch", name, "--allow-empty" }, streams, amb, null);
},
}
}
fn branchLogFail(s: cli.Streams, err: anyerror) cli.Exit {
if (err == error.StoreBusy) return .failure; // the lock notice already said it
s.err.print("zit branch: cannot write the control artifact: {s}\n", .{@errorName(err)}) catch {};
return .failure;
}
/// Renders the §6.3 branch listing to stdout, one line per entry in `entries`
/// order (name-ascending, as `branches` returns them). `current` is the branch
/// name of the checked-out check-in (§6.1/§6.4) or null; the matching entry —
/// at most one, since §6.3 grouping yields distinct names — gets a leading
/// "* ", every other a two-space indent. A representative-closed branch (§6.3)
/// appends " (closed)". Pure; bounded by `entries.len`.
pub fn renderBranchList(
out: *std.Io.Writer,
entries: []const repostate.RepoState.BranchEntry,
current: ?[]const u8,
) void {
var marked: usize = 0;
for (entries) |entry| {
const is_current = current != null and std.mem.eql(u8, entry.name, current.?);
if (is_current) marked += 1;
std.debug.assert(marked <= 1); // distinct names ⇒ at most one mark
out.writeAll(if (is_current) "* " else " ") catch {};
out.writeAll(entry.name) catch {};
if (entry.closed) out.writeAll(" (closed)") catch {};
out.writeAll("\n") catch {};
}
std.debug.assert(marked <= 1);
}