Skip to content
zit Artifact [6a587e5332]
Login

Artifact [6a587e5332]

Artifact 6a587e53328d898d2c01768ae356575c551081839fb20dcb88ae862a80dfaca5:


//! `zit worktrees`: list the store's registered working trees, pruning
//! dead entries.

const std = @import("std");
const zit = @import("zit");
const cli = @import("zit").cli;
const checkout = @import("zit").checkout;
const diagnostics = @import("../diagnostics.zig");
const help_pages = @import("../help.zig");
const stateOom = diagnostics.stateOom;

/// `zit worktrees` — list the store's registered working trees, lazily
/// pruning entries whose path died or whose checkout re-pointed at some
/// other store. The identity test is the store file's inode: an entry
/// counts iff its own resolved store names the same `.zit` this invocation
/// resolved. Pruning rewrites only the disposable cache tier.
pub fn runWorktrees(
    gpa: std.mem.Allocator,
    io: std.Io,
    arena: std.mem.Allocator,
    verb_args: []const []const u8,
    streams: cli.Streams,
    amb: cli.Ambient,
) cli.Exit {
    for (verb_args) |tok| {
        if (std.mem.eql(u8, tok, "-h") or std.mem.eql(u8, tok, "--help")) {
            streams.out.writeAll(help_pages.worktrees_help) catch {};
            return .ok;
        }
        return cli.usageError(streams, "worktrees", .extra_argument, tok);
    }

    const root = (cli.resolveRoot(arena, io, amb.repo_override) catch return stateOom(streams, "worktrees")) orelse {
        diagnostics.reportNoRoot(streams, io, "worktrees", amb.repo_override);
        return .failure;
    };
    var root_dir = root.dir;
    defer root_dir.close(io);

    // The store root: the resolved pointer for a detached tree, the root
    // itself otherwise (including the bare -R form, where root IS the store).
    var store_dir = blk: {
        if (checkout.storeDirOf(io, root_dir) catch null) |resolved| break :blk resolved;
        break :blk root_dir.openDir(io, ".", .{}) catch {
            streams.err.writeAll("zit worktrees: cannot open the repository\n") catch {};
            return .failure;
        };
    };
    defer store_dir.close(io);
    const store_inode = (store_dir.statFile(io, zit.repo_filename, .{}) catch {
        streams.err.writeAll("zit worktrees: cannot read the repository\n") catch {};
        return .failure;
    }).inode;

    const registered = zit.repocache.readWorktrees(gpa, io, store_dir);
    defer zit.repocache.freeWorktrees(gpa, registered);

    var live: std.ArrayListUnmanaged([]const u8) = .empty;
    defer live.deinit(gpa);
    for (registered) |path| {
        if (worktreeServesStore(io, path, store_inode)) {
            live.append(gpa, path) catch return stateOom(streams, "worktrees");
        }
    }
    if (live.items.len != registered.len) {
        zit.repocache.writeWorktrees(gpa, io, store_dir, live.items); // lazy prune
    }

    if (live.items.len == 0) {
        streams.out.writeAll("no working trees are registered against this store\n") catch {};
        return .ok;
    }
    for (live.items) |path| {
        // The invoking-tree marker only makes sense when the invocation RAN
        // in a tree; under -R the resolved root is the store, not us.
        const marker: []const u8 = if (amb.repo_override == null and std.mem.eql(u8, path, root.abs)) "* " else "  ";
        var tree = std.Io.Dir.cwd().openDir(io, path, .{}) catch continue;
        defer tree.close(io);
        var ck_buf: [checkout.max_ck_payload + 1]u8 = undefined;
        const state = checkout.read(io, tree, &ck_buf) catch null;
        if (state) |st| {
            if (st.version.len != 0) {
                streams.out.print("{s}{s}  ({s} at {s})\n", .{ marker, path, st.branch, st.version[0..@min(st.version.len, 10)] }) catch {};
                continue;
            }
            streams.out.print("{s}{s}  ({s}, unborn)\n", .{ marker, path, st.branch }) catch {};
            continue;
        }
        streams.out.print("{s}{s}\n", .{ marker, path }) catch {};
    }
    return .ok;
}

/// Does the checkout at `path` still serve the store identified by
/// `store_inode`? Total: any failure reads as "no" and the entry prunes —
/// the registry's self-healing contract.
fn worktreeServesStore(io: std.Io, path: []const u8, store_inode: std.Io.File.INode) bool {
    var tree = std.Io.Dir.cwd().openDir(io, path, .{}) catch return false;
    defer tree.close(io);
    _ = tree.statFile(io, checkout.filename, .{}) catch return false;
    if (checkout.storeDirOf(io, tree) catch null) |resolved| {
        var sd = resolved;
        defer sd.close(io);
        const st = sd.statFile(io, zit.repo_filename, .{}) catch return false;
        return st.inode == store_inode;
    }
    const st = tree.statFile(io, zit.repo_filename, .{}) catch return false;
    return st.inode == store_inode;
}