exec.zig

64.5 KB · raw

1// exec.zig — all process execution and SSH routing2// Commands call these functions; output is streamed or captured here.3const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const output = @import("output.zig");89// nixos-rebuild manages this profile; generation commands must target it10// explicitly. Bare nix-env defaults to the per-user profile, which is empty.11const SYSTEM_PROFILE = "/nix/var/nix/profiles/system";1213pub const RunResult = struct {14    stdout: []u8,15    stderr: []u8,16    exit_code: u8,17};1819// Run a process and capture stdout+stderr (not streaming).20pub fn capture(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, cmd: []const []const u8) !RunResult {21    const argv = try buildArgv(gpa, machine, cmd);22    defer if (!machine.local) gpa.free(argv);2324    const result = std.process.run(gpa, io, .{ .argv = argv }) catch |e| {25        errors.error_info.setMessage("process failed: {s}", .{cmd[0]});26        return e;27    };2829    return .{30        .stdout = result.stdout,31        .stderr = result.stderr,32        .exit_code = switch (result.term) {33            .exited => |c| c,34            else => 1,35        },36    };37}3839// Run a process and stream its output to the terminal (inherit stdio).40pub fn stream(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8) !u8 {41    // The child inherits stdout and writes directly to the fd; flush any buffered42    // nina header first so it isn't reordered after the child's output.43    output.flush();44    const argv = try buildArgv(gpa, machine, cmd);45    defer if (!machine.local) gpa.free(argv);4647    var child = std.process.spawn(io, .{48        .argv = argv,49        .stdin = .inherit,50        .stdout = .inherit,51        .stderr = .inherit,52    }) catch |e| {53        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});54        return e;55    };5657    const term = child.wait(io) catch |e| {58        errors.error_info.setMessage("process wait failed", .{});59        return e;60    };6162    return switch (term) {63        .exited => |c| c,64        else => 1,65    };66}6768// Stream a process with an overridden PS1 in the child environment.69fn streamEnv(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8, base_env: *const std.process.Environ.Map, ps1: []const u8) !u8 {70    output.flush();71    const argv = try buildArgv(gpa, machine, cmd);72    defer if (!machine.local) gpa.free(argv);7374    var env = try base_env.clone(gpa);75    defer env.deinit();76    try env.put("PS1", ps1);7778    var child = std.process.spawn(io, .{79        .argv = argv,80        .stdin = .inherit,81        .stdout = .inherit,82        .stderr = .inherit,83        .environ_map = &env,84    }) catch |e| {85        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});86        return e;87    };8889    const term = child.wait(io) catch |e| {90        errors.error_info.setMessage("process wait failed", .{});91        return e;92    };9394    return switch (term) {95        .exited => |c| c,96        else => 1,97    };98}99100// Stream a local process with inherited stdio (no SSH routing — for nix commands).101pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 {102    output.flush();103    var child = std.process.spawn(io, .{104        .argv = cmd,105        .stdin = .inherit,106        .stdout = .inherit,107        .stderr = .inherit,108    }) catch |e| {109        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});110        return e;111    };112    const term = child.wait(io) catch {113        errors.error_info.setMessage("process wait failed", .{});114        return error.ProcessFailed;115    };116    return switch (term) {117        .exited => |c| c,118        else => 1,119    };120}121122// Run a process and capture output as a single string (no SSH routing — for local nix commands).123pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {124    const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;125    defer gpa.free(result.stderr);126    switch (result.term) {127        .exited => |c| if (c != 0) {128            gpa.free(result.stdout);129            return error.ProcessFailed;130        },131        else => {132            gpa.free(result.stdout);133            return error.ProcessFailed;134        },135    }136    return result.stdout;137}138139// Create a directory and its parents, best-effort. Shelling out to `mkdir -p`140// matches how the rest of exec.zig provisions config locations (~/.config/nix).141pub fn ensureDir(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) void {142    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir }) catch {};143}144145fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {146    if (machine.local) return cmd;147148    const host = machine.host orelse {149        errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});150        return error.SshFailed;151    };152153    var ssh: std.ArrayList([]const u8) = .empty;154    try ssh.append(gpa, "ssh");155    try ssh.append(gpa, "-o");156    try ssh.append(gpa, "BatchMode=yes");157    try ssh.append(gpa, "-o");158    try ssh.append(gpa, "StrictHostKeyChecking=accept-new");159    if (machine.ssh_key) |key| {160        try ssh.append(gpa, "-i");161        try ssh.append(gpa, key);162    }163    const addr = if (machine.user) |u|164        try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })165    else166        try gpa.dupe(u8, host);167    try ssh.append(gpa, addr);168    for (cmd) |arg| try ssh.append(gpa, arg);169    return ssh.toOwnedSlice(gpa);170}171172// --- NixOS rebuild ---173174// True if the machine's config dir holds a flake.nix. Only meaningful for a local175// machine — the file lives on the local filesystem. Remote flake detection would176// need an ssh round-trip; a remote flake at the default /etc/nixos needs no flag177// anyway, so we don't bother.178// True if `dir` contains a flake.nix (local filesystem check).179pub fn dirHasFlake(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) bool {180    const flake_path = std.fs.path.join(gpa, &.{ dir, "flake.nix" }) catch return false;181    defer gpa.free(flake_path);182    return pathExists(io, flake_path);183}184185pub fn configHasFlake(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {186    if (!machine.local) return false;187    return dirHasFlake(gpa, io, machine.config_path);188}189190// nixos-rebuild auto-detects /etc/nixos/flake.nix, so the --flake flag is only191// needed when the flake lives elsewhere. A flake at a non-default path must be192// passed explicitly or nixos-rebuild falls back to channels. Compare with193// trailing slashes trimmed so "/etc/nixos/" is still treated as the default.194fn useFlakeFlag(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {195    if (!configHasFlake(gpa, io, machine)) return false;196    var path = machine.config_path;197    while (path.len > 1 and path[path.len - 1] == '/') path = path[0 .. path.len - 1];198    return !std.mem.eql(u8, path, "/etc/nixos");199}200201fn nixosRebuildRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, flake: bool) !u8 {202    if (flake) {203        return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb, "--flake", machine.config_path });204    }205    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb });206}207208pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {209    const flake = useFlakeFlag(gpa, io, machine);210    if (flake) {211        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});212    } else {213        output.printSubstep("nixos-rebuild switch", .{});214    }215    return nixosRebuildRun(io, machine, gpa, "switch", flake);216}217218pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {219    return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine));220}221222pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {223    return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine));224}225226// --- Generations ---227228// Read system-profile generations WITHOUT root. `nix-env --list-generations -p229// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user230// ("system.lock: Permission denied"). The generation symlinks themselves are231// world-readable, so list them directly: parse `system-N-link` names, take each232// link's own mtime for the date/time, and mark the one the `system` symlink233// points at as current. Output matches the `nix-env --list-generations` columns234// (num date time [current]) so parseGenerations is unchanged.235const GEN_LIST_SCRIPT =236    \\cur=$(readlink /nix/var/nix/profiles/system 2>/dev/null | sed 's/.*system-\([0-9]*\)-link/\1/'); find /nix/var/nix/profiles -maxdepth 1 -name 'system-*-link' -printf '%f %TY-%Tm-%Td %TH:%TM\n' 2>/dev/null | sed 's/system-\([0-9]*\)-link/\1/' | sort -n | awk -v c="$cur" '{ if ($1==c) print $0" current"; else print $0 }'237;238239pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {240    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });241    defer gpa.free(r.stderr);242    defer gpa.free(r.stdout);243    if (r.exit_code != 0) return error.ProcessFailed;244    return parseGenerations(gpa, r.stdout);245}246247fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {248    var gens: std.ArrayList(types.GenerationInfo) = .empty;249    var lines = std.mem.splitScalar(u8, output_str, '\n');250    while (lines.next()) |line| {251        const trimmed = std.mem.trim(u8, line, " \t");252        if (trimmed.len == 0) continue;253        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");254        const num_str = parts.next() orelse continue;255        const date_str = parts.next() orelse continue;256        const time_str = parts.next() orelse continue;257        const rest = parts.rest();258        const current = std.mem.indexOf(u8, rest, "current") != null;259        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;260        try gens.append(gpa, .{261            .number = num,262            .date = try gpa.dupe(u8, date_str),263            .time = try gpa.dupe(u8, time_str),264            .current = current,265        });266    }267    return gens.toOwnedSlice(gpa);268}269270pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {271    const gens = try getGenerations(gpa, io, machine);272    defer gpa.free(gens);273    for (gens) |g| {274        if (g.current) return g.number;275    }276    return 0;277}278279pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {280    // Switch the system profile to generation n, then activate it (bootloader +281    // services). Without switch-to-configuration the change isn't applied.282    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --switch-generation {d} && {s}/bin/switch-to-configuration switch", .{ SYSTEM_PROFILE, n, SYSTEM_PROFILE });283    defer gpa.free(cmd);284    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });285}286287pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {288    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });289}290291pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {292    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});293    defer gpa.free(n_str);294    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });295}296297pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {298    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });299}300301// --- Garbage collection ---302303pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {304    if (delete_old) {305        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });306    }307    // Keep the `keep` most recent system generations (+N deletes all but N),308    // then collect now-unreferenced store paths. `--delete-older-than` wants a309    // duration (e.g. 14d), not a generation count.310    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });311    defer gpa.free(cmd);312    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });313}314315// --- Channels ---316317pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {318    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });319    defer gpa.free(r.stderr);320    defer gpa.free(r.stdout);321    if (r.exit_code != 0) return error.ProcessFailed;322    return parseChannels(gpa, r.stdout);323}324325fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {326    var channels: std.ArrayList(types.ChannelInfo) = .empty;327    var lines = std.mem.splitScalar(u8, output_str, '\n');328    while (lines.next()) |line| {329        const trimmed = std.mem.trim(u8, line, " \t\r");330        if (trimmed.len == 0) continue;331        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;332        try channels.append(gpa, .{333            .name = try gpa.dupe(u8, trimmed[0..space]),334            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),335        });336    }337    return channels.toOwnedSlice(gpa);338}339340pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {341    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });342}343344pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {345    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });346}347348pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {349    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });350}351352// --- Services ---353354pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {355    const cmd: []const []const u8 = if (user)356        &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }357    else358        &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };359    const r = try capture(gpa, io, machine, cmd);360    defer gpa.free(r.stderr);361    defer gpa.free(r.stdout);362    if (r.exit_code != 0) return error.ProcessFailed;363    return parseServices(gpa, r.stdout);364}365366fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {367    var svcs: std.ArrayList(types.ServiceInfo) = .empty;368    var lines = std.mem.splitScalar(u8, output_str, '\n');369    while (lines.next()) |line| {370        const trimmed = std.mem.trim(u8, line, " \t\r");371        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines372        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");373        const name = parts.next() orelse continue;374        _ = parts.next(); // load375        const active_str = parts.next() orelse continue;376        const sub_str = parts.next() orelse "unknown";377378        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))379            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)380        else if (std.mem.eql(u8, active_str, "failed"))381            .failed382        else383            .inactive;384385        try svcs.append(gpa, .{386            .name = try gpa.dupe(u8, name),387            .state = state,388            .uptime = null,389        });390    }391    return svcs.toOwnedSlice(gpa);392}393394pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {395    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.396    // User services run under the caller's own systemd manager, so no sudo.397    if (user) {398        return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });399    }400    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });401}402403pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {404    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});405    defer gpa.free(n_str);406    if (user) {407        if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });408        return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });409    }410    if (follow) {411        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });412    }413    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });414}415416// --- Profile ---417418pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {419    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});420    defer gpa.free(pkg_ref);421    // `nix profile add` is the current verb; `install` is a deprecated alias that422    // prints a warning on modern nix.423    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });424}425426pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {427    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not428    // by flake ref — passing nixpkgs#ripgrep matches nothing.429    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });430}431432pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {433    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });434    defer gpa.free(r.stderr);435    if (r.exit_code != 0) return error.ProcessFailed;436    return r.stdout;437}438439// Machine-readable profile listing — caller parses elements -> name + version.440pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {441    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });442    defer gpa.free(r.stderr);443    if (r.exit_code != 0) {444        gpa.free(r.stdout);445        return error.ProcessFailed;446    }447    return r.stdout;448}449450// Returns the profile element name to pass to `nix profile remove/upgrade`451// (e.g. "nina" or "default"), or null if nina is not found. Caller owns the452// returned slice. A NixOS system-package install also resolves into /nix/store453// so the store path alone can't distinguish it from a profile install — the454// profile list can. A missing/empty profile (or no nix) returns null.455pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {456    const js = profileListJson(gpa, io, machine) catch return null;457    defer gpa.free(js);458    return profileJsonNinaElement(gpa, js);459}460461pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {462    const name = profileNinaElement(gpa, io, machine) orelse return false;463    gpa.free(name);464    return true;465}466467// True when a nix store path belongs to the nina package. Store paths have the468// form /nix/store/<32-char-hash>-<pname>-<version>[/<subpath>]. We check that469// the 33 chars after /nix/store/ are the hash+dash, and the pname that follows470// is exactly "nina" (followed by "-" or end-of-component).471fn storePathIsNina(path: []const u8) bool {472    const prefix = "/nix/store/";473    if (!std.mem.startsWith(u8, path, prefix)) return false;474    const rel = path[prefix.len..];475    // The store entry name ends at the first "/" (if any sub-path follows).476    const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];477    if (entry.len < 34) return false; // 32-char hash + dash + at least one char478    const pname_ver = entry[33..]; // skip hash + dash479    return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");480}481482// Pure parse of `nix profile list --json` for a nina element, returning its483// element name (the key to pass to `nix profile remove/upgrade`) or null.484// Newer nix (2.18+) keys elements by pname ("nina"). Older nix uses an array485// with an "attrPath" field. Tarball installs via the `default` output may use486// the key "default" instead of "nina"; we detect those via storePaths.487fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {488    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;489    defer parsed.deinit();490    const root = parsed.value;491    if (root != .object) return null;492    const elements = root.object.get("elements") orelse return null;493    switch (elements) {494        .object => |obj| {495            // Fast path: exact "nina" key (nix 2.18+ with nixpkgs#nina install).496            if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;497            // Fallback: scan storePaths. Handles tarball installs where the default498            // output is selected and nix names the element "default" (older nix) or499            // some other key derived from the attrPath rather than the pname.500            var it = obj.iterator();501            while (it.next()) |kv| {502                const val = kv.value_ptr.*;503                if (val != .object) continue;504                const sps = val.object.get("storePaths") orelse continue;505                if (sps != .array) continue;506                for (sps.array.items) |sp| {507                    if (sp == .string and storePathIsNina(sp.string))508                        return gpa.dupe(u8, kv.key_ptr.*) catch null;509                }510            }511            return null;512        },513        .array => |arr| {514            // Older nix array format. Element name is the last component of attrPath.515            for (arr.items) |el| {516                if (el != .object) continue;517                const ap = el.object.get("attrPath") orelse continue;518                if (ap != .string) continue;519                if (std.mem.eql(u8, ap.string, "nina") or520                    std.mem.endsWith(u8, ap.string, ".nina"))521                    return gpa.dupe(u8, "nina") catch null;522                // Tarball default-output install: attrPath ends in ".default" but523                // storePaths point to nina. Return "default" as the element name.524                const sps = el.object.get("storePaths") orelse continue;525                if (sps != .array) continue;526                for (sps.array.items) |sp| {527                    if (sp != .string) continue;528                    if (!storePathIsNina(sp.string)) continue;529                    const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;530                    const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;531                    return gpa.dupe(u8, el_name) catch null;532                }533            }534            return null;535        },536        else => return null,537    }538}539540test "profileJsonNinaElement finds element name from profile JSON" {541    const a = std.testing.allocator;542543    // Newer nix: elements keyed by pname. "nina" key present.544    const named =545        \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},546        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}547    ;548    const r1 = profileJsonNinaElement(a, named);549    defer if (r1) |n| a.free(n);550    try std.testing.expectEqualStrings("nina", r1.?);551552    // Tarball install via default output: element keyed as "default", storePath is nina.553    const default_key =554        \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}555    ;556    const r2 = profileJsonNinaElement(a, default_key);557    defer if (r2) |n| a.free(n);558    try std.testing.expectEqualStrings("default", r2.?);559560    // Decoy: storePath of another package contains "nina" as a substring but is not nina.561    const decoy =562        \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}563    ;564    const r3 = profileJsonNinaElement(a, decoy);565    try std.testing.expectEqual(@as(?[]const u8, null), r3);566567    // Older nix array schema, attrPath ending in ".nina".568    const arr =569        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}570    ;571    const r4 = profileJsonNinaElement(a, arr);572    defer if (r4) |n| a.free(n);573    try std.testing.expectEqualStrings("nina", r4.?);574575    // Older nix array schema, tarball default-output install.576    const arr_default =577        \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}578    ;579    const r5 = profileJsonNinaElement(a, arr_default);580    defer if (r5) |n| a.free(n);581    try std.testing.expectEqualStrings("default", r5.?);582583    // Empty / malformed → null.584    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));585    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));586}587588// The store paths that make up the running system environment. Each reference is589// a <hash>-<name>-<version> path, so the caller can list system packages with590// versions — there is no cleaner per-package list for environment.systemPackages.591pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {592    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });593    defer gpa.free(r.stderr);594    if (r.exit_code != 0) {595        gpa.free(r.stdout);596        return error.ProcessFailed;597    }598    return r.stdout;599}600601pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {602    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });603}604605// --- Store ---606607pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {608    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });609}610611pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {612    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });613}614615pub const SystemStatus = struct { size: []u8, age: []u8 };616617// One read-only pass for `nina status`: the current system's closure size (a618// single `path-info -S` of /run/current-system — fast, unlike -S over the whole619// store) and seconds since the system profile was last switched (its symlink620// mtime). Both are world-readable; no root needed.621const STATUS_SCRIPT =622    \\sz=$(nix path-info -S /run/current-system 2>/dev/null | awk '{print $NF}'); mt=$(stat -c %Y /nix/var/nix/profiles/system 2>/dev/null); now=$(date +%s); echo "${sz:-0} $(( ${now:-0} - ${mt:-0} ))"623;624625pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {626    const unknown = SystemStatus{627        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },628        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },629    };630    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;631    defer gpa.free(r.stdout);632    defer gpa.free(r.stderr);633    if (r.exit_code != 0) return unknown;634635    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");636    const sz_str = it.next() orelse return unknown;637    const age_str = it.next() orelse return unknown;638    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;639    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;640641    gpa.free(unknown.size);642    gpa.free(unknown.age);643    return .{644        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),645        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),646    };647}648649// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A650// one-word health signal; exits non-zero when degraded, so we read stdout, not651// the code. Caller owns the returned slice.652pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {653    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch654        return gpa.dupe(u8, "unknown");655    defer gpa.free(r.stderr);656    const state = std.mem.trim(u8, r.stdout, " \t\n\r");657    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");658    gpa.free(r.stdout);659    return owned;660}661662fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {663    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});664    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});665    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});666    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});667}668669pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {670    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });671}672673pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {674    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)675    // graph work that takes minutes on a real store (59k+ paths) and hangs the676    // command. We don't need closures: `--all --json` (no -S) carries each path's677    // own narSize, so one fast pass gives the path count and the summed store size.678    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.679    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.680    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });681    defer gpa.free(pi.stdout);682    defer gpa.free(pi.stderr);683684    const scan = scanStoreJson(pi.stdout);685    const total_owned = try humanSize(gpa, scan.total_bytes);686687    return .{688        .total_size = total_owned,689        .live_paths = scan.count,690        .reclaimable_paths = 0,691    };692}693694const StoreScan = struct { count: u64, total_bytes: u64 };695696// One linear pass over `nix path-info --json`: each path object has exactly one697// "narSize": field, so counting them gives the true path count and summing the698// values gives the total store size — no per-path closure walk.699fn scanStoreJson(json_str: []const u8) StoreScan {700    const needle = "\"narSize\":";701    var count: u64 = 0;702    var total: u64 = 0;703    var i: usize = 0;704    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {705        var j = pos + needle.len;706        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}707        var val: u64 = 0;708        var any = false;709        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {710            val = val * 10 + (json_str[j] - '0');711            any = true;712        }713        if (any) {714            count += 1;715            total += val;716        }717        i = j;718    }719    return .{ .count = count, .total_bytes = total };720}721722fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {723    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };724    var val: f64 = @floatFromInt(bytes);725    var unit: usize = 0;726    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;727    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });728    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });729}730731pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {732    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the733    // flake registry), not a flake in the current directory.734    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});735    defer gpa.free(expr);736    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });737    defer gpa.free(r.stderr);738    if (r.exit_code != 0) {739        gpa.free(r.stdout);740        return error.ProcessFailed;741    }742    return r.stdout;743}744745// --- Flake ---746747pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {748    if (input) |inp| {749        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });750    }751    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });752}753754// Update flake inputs for the flake living in `dir` (the config dir). `nix flake755// update` operates on the flake in the working directory, so we cd there first.756// Used by `nina upgrade` on a flake system in place of nix-channel --update.757pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {758    return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });759}760761pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {762    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });763}764765pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {766    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });767}768769pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {770    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });771}772773pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {774    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });775}776777pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {778    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });779    defer gpa.free(r.stderr);780    if (r.exit_code != 0) {781        gpa.free(r.stdout);782        return error.ProcessFailed;783    }784    return r.stdout;785}786787// --- Build / Run / Develop ---788789pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {790    if (attr) |a| {791        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});792        defer gpa.free(ref);793        return stream(io, machine, gpa, &.{ "nix", "build", ref });794    }795    return stream(io, machine, gpa, &.{ "nix", "build" });796}797798pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {799    // nix run always gets --no-write-lock-file for remote URLs800    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");801    if (is_url) {802        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });803    }804    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.805    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {806        return stream(io, machine, gpa, &.{ "nix", "run", pkg });807    }808    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});809    defer gpa.free(ref);810    return stream(io, machine, gpa, &.{ "nix", "run", ref });811}812813pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {814    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});815    defer gpa.free(ref);816    return stream(io, machine, gpa, &.{ "nix", "shell", ref });817}818819pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {820    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});821    defer gpa.free(ref);822    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});823    defer gpa.free(ps1);824    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);825}826827pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {828    if (run_cmd) |cmd| {829        // sh -c so a multi-word command isn't treated as a single executable name.830        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });831    }832    return stream(io, machine, gpa, &.{ "nix", "develop" });833}834835pub fn nixDevelopPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8, base_env: *const std.process.Environ.Map) !u8 {836    if (run_cmd) |cmd| {837        // sh -c so a multi-word command isn't treated as a single executable name.838        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });839    }840    return streamEnv(io, machine, gpa, &.{ "nix", "develop" }, base_env, "(nina: dev) -> ");841}842843pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {844    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });845}846847// --- Format ---848849pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {850    if (check) {851        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });852    }853    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });854}855856// --- Info ---857858pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {859    const r = try capture(gpa, io, machine, &.{"nixos-version"});860    defer gpa.free(r.stderr);861    if (r.exit_code != 0) {862        gpa.free(r.stdout);863        return error.ProcessFailed;864    }865    return r.stdout;866}867868pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {869    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });870    defer gpa.free(r.stderr);871    if (r.exit_code != 0) {872        gpa.free(r.stdout);873        return error.ProcessFailed;874    }875    return r.stdout;876}877878pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {879    const r = try capture(gpa, io, machine, &.{"uptime"});880    defer gpa.free(r.stderr);881    if (r.exit_code != 0) {882        gpa.free(r.stdout);883        return error.ProcessFailed;884    }885    return r.stdout;886}887888// --- Boot ---889890pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {891    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });892    defer gpa.free(r.stderr);893    defer gpa.free(r.stdout);894    if (r.exit_code != 0) return error.ProcessFailed;895    return parseBootEntries(gpa, r.stdout);896}897898fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {899    var entries: std.ArrayList(types.BootEntry) = .empty;900    var lines = std.mem.splitScalar(u8, output_str, '\n');901    while (lines.next()) |line| {902        const trimmed = std.mem.trim(u8, line, " \t\r");903        if (std.mem.startsWith(u8, trimmed, "title:")) {904            const title = std.mem.trim(u8, trimmed[6..], " \t");905            const current = std.mem.indexOf(u8, title, "(current)") != null;906            try entries.append(gpa, .{907                .title = try gpa.dupe(u8, title),908                .current = current,909            });910        }911    }912    return entries.toOwnedSlice(gpa);913}914915// --- Pkg info ---916917pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {918    return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });919}920921pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {922    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });923}924925pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {926    // A bare name ("ripgrep") isn't a valid installable; resolve via nixpkgs# like927    // `pkg path` does. -S -h gives closure size, human-readable. Output is928    // "<store-path>   <size>"; return just the size.929    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});930    defer gpa.free(ref);931    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref });932    defer gpa.free(r.stderr);933    defer gpa.free(r.stdout);934    if (r.exit_code != 0) return error.ProcessFailed;935936    const line = std.mem.trim(u8, r.stdout, " \t\n\r");937    var it = std.mem.tokenizeAny(u8, line, " \t");938    _ = it.next(); // store path939    const size = std.mem.trim(u8, it.rest(), " \t");940    if (size.len == 0) return error.ProcessFailed;941    return gpa.dupe(u8, size);942}943944pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {945    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });946}947948// --- Hash / Fetch ---949950pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {951    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });952    defer gpa.free(r.stderr);953    if (r.exit_code != 0) {954        gpa.free(r.stdout);955        return error.ProcessFailed;956    }957    return r.stdout;958}959960pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {961    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });962    defer gpa.free(r.stderr);963    if (r.exit_code != 0) {964        gpa.free(r.stdout);965        return error.ProcessFailed;966    }967    return r.stdout;968}969970// --- Pin ---971972pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {973    // Stub: full implementation would parse and edit flake.lock JSON974    // The pin/unpin flow works via nix flake update which regenerates flake.lock975}976977pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {978    if (line) |l| {979        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});980        defer gpa.free(line_arg);981        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });982    }983    return stream(io, &types.Machine{}, gpa, &.{ editor, path });984}985986pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {987    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});988    defer gpa.free(a_str);989    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});990    defer gpa.free(b_str);991    // On a tty, the child's own color is fine — stream it directly.992    if (output.colorEnabled()) {993        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });994    }995    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,996    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.997    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });998    defer gpa.free(r.stdout);999    defer gpa.free(r.stderr);1000    const cleaned = try stripAnsi(gpa, r.stdout);1001    defer gpa.free(cleaned);1002    output.raw(cleaned);1003    return r.exit_code;1004}10051006// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a1007// child process's color when it writes ANSI unconditionally.1008fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1009    var out: std.ArrayList(u8) = .empty;1010    errdefer out.deinit(gpa);1011    var i: usize = 0;1012    while (i < input.len) {1013        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1014            i += 2;1015            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1016            if (i < input.len) i += 1; // consume the final byte1017            continue;1018        }1019        try out.append(gpa, input[i]);1020        i += 1;1021    }1022    return out.toOwnedSlice(gpa);1023}10241025test "stripAnsi removes CSI color sequences" {1026    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1027    defer std.testing.allocator.free(cleaned);1028    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1029}10301031// --- Doctor checks ---10321033pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1034    var checks: std.ArrayList(types.DoctorCheck) = .empty;10351036    // Check nix daemon1037    {1038        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1039        defer gpa.free(r.stdout);1040        defer gpa.free(r.stderr);1041        const active = std.mem.indexOf(u8, r.stdout, "active") != null;1042        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1043    }10441045    // Check config syntax. Flake-aware like apply/upgrade: on a flake system a1046    // plain `nixos-rebuild dry-build` evaluates <nixpkgs/nixos> + <nixos-config>1047    // (channel style) and fails, so pass --flake when the config dir has one.1048    {1049        const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1050            &.{ "sudo", "nixos-rebuild", "dry-build", "--flake", machine.config_path }1051        else1052            &.{ "sudo", "nixos-rebuild", "dry-build" };1053        const r = try capture(gpa, io, machine, argv);1054        defer gpa.free(r.stdout);1055        defer gpa.free(r.stderr);1056        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1057    }10581059    // Check channel1060    {1061        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1062        defer gpa.free(r.stdout);1063        defer gpa.free(r.stderr);1064        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1065        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1066    }10671068    return checks.toOwnedSlice(gpa);1069}10701071// --- Home Manager ---1072//1073// Home Manager has three usage modes. nina detects which one is in play before1074// any `home` command so it can either drive the standalone CLI or redirect the1075// user to `nina apply` (when HM is a NixOS/flake module activated by rebuild).10761077pub const HomeManagerMode = enum {1078    // home-manager binary on PATH — manages the user env on its own.1079    standalone,1080    // No binary, but a home.nix exists — HM is a NixOS/flake module rebuilt by1081    // nixos-rebuild. `nina home apply` redirects to `nina apply`.1082    module,1083    none,1084};10851086fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1087    const home = environ.get("HOME") orelse return null;1088    return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1089}10901091// Path to the standalone home.nix. Caller frees.1092pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1093    const dir = homeConfigDir(gpa, environ) orelse return null;1094    defer gpa.free(dir);1095    return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1096}10971098pub fn pathExists(io: std.Io, path: []const u8) bool {1099    const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1100    f.close(io);1101    return true;1102}11031104// `command -v <name>` — true if the binary resolves on PATH. Silent (captured),1105// unlike streamLocal which would inherit stdio.1106fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1107    var buf: [256]u8 = undefined;1108    const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1109    const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1110    defer gpa.free(r.stdout);1111    defer gpa.free(r.stderr);1112    return switch (r.term) {1113        .exited => |code| code == 0,1114        else => false,1115    };1116}11171118pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1119    if (commandExists(gpa, io, "home-manager")) return .standalone;1120    if (homeNixPath(gpa, environ)) |p| {1121        defer gpa.free(p);1122        if (pathExists(io, p)) return .module;1123    }1124    return .none;1125}11261127// If the home-manager config dir holds a flake.nix, returns the flake ref1128// "<dir>#<user>" for `home-manager switch --flake`. Username comes from $USER.1129// Caller frees. null when there's no flake.nix (channel-based home config).1130pub fn homeFlakeRef(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1131    const dir = homeConfigDir(gpa, environ) orelse return null;1132    defer gpa.free(dir);1133    const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch return null;1134    defer gpa.free(flake);1135    if (!pathExists(io, flake)) return null;1136    const user = environ.get("USER") orelse "default";1137    return std.fmt.allocPrint(gpa, "{s}#{s}", .{ dir, user }) catch null;1138}11391140pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1141    return stream(io, machine, gpa, &.{ "home-manager", "switch" });1142}11431144pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8) !u8 {1145    return stream(io, machine, gpa, &.{ "home-manager", "switch", "--flake", flake_ref });1146}11471148// home-manager has no system-profile rollback; it re-activates the previous1149// generation via `switch --rollback`.1150pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1151    return stream(io, machine, gpa, &.{ "home-manager", "switch", "--rollback" });1152}11531154// Build (and validate) the home config without activating it — used by `home1155// check` and `home apply --dry`. `home-manager build` drops a ./result symlink1156// in the cwd, so run it in a throwaway temp dir to avoid littering the directory1157// nina was invoked from.1158pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1159    return stream(io, machine, gpa, &.{ "sh", "-c", "d=$(mktemp -d) && cd \"$d\" && home-manager build" });1160}11611162pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1163    const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1164    defer gpa.free(r.stderr);1165    if (r.exit_code != 0) {1166        gpa.free(r.stdout);1167        return error.ProcessFailed;1168    }1169    return r.stdout;1170}11711172// Store paths referenced by a home generation — used to list managed packages.1173pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1174    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1175    defer gpa.free(r.stderr);1176    if (r.exit_code != 0) {1177        gpa.free(r.stdout);1178        return error.ProcessFailed;1179    }1180    return r.stdout;1181}11821183// diff-closures between two arbitrary store paths (home generations), mirroring1184// diffClosures' tty/piped color handling.1185pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1186    if (output.colorEnabled()) {1187        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1188    }1189    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1190    defer gpa.free(r.stdout);1191    defer gpa.free(r.stderr);1192    const cleaned = try stripAnsi(gpa, r.stdout);1193    defer gpa.free(cleaned);1194    output.raw(cleaned);1195    return r.exit_code;1196}11971198// --- Log ---11991200pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1201    const home = environ.get("HOME") orelse return error.FileNotFound;1202    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1203    defer gpa.free(path);1204    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1205    if (last == 0) return content;12061207    // Collect non-empty lines, then keep only the final `last`. Slices point into1208    // `content`, so copy them out before freeing it.1209    var lines: std.ArrayList([]const u8) = .empty;1210    defer lines.deinit(gpa);1211    var it = std.mem.splitScalar(u8, content, '\n');1212    while (it.next()) |line| {1213        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1214        try lines.append(gpa, line);1215    }1216    if (lines.items.len <= last) return content;12171218    var out: std.ArrayList(u8) = .empty;1219    errdefer out.deinit(gpa);1220    for (lines.items[lines.items.len - last ..]) |line| {1221        try out.appendSlice(gpa, line);1222        try out.append(gpa, '\n');1223    }1224    gpa.free(content);1225    return out.toOwnedSlice(gpa);1226}12271228// nina is a one-shot process, so "did the last apply fail this session?" can't1229// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1230// other ~/.nina-* state files. This lets a later successful apply earn the1231// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1232pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1233    const home = environ.get("HOME") orelse return;1234    var buf: [512]u8 = undefined;1235    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1236    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1237    file.close(io);1238}12391240pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1241    const home = environ.get("HOME") orelse return false;1242    var buf: [512]u8 = undefined;1243    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1244    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1245        f.close(io);1246        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1247        return true;1248    } else |_| {1249        return false;1250    }1251}12521253pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1254    const home = environ.get("HOME") orelse return;1255    var path_buf: [512]u8 = undefined;1256    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1257    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1258        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1259    defer file.close(io);1260    const size = file.length(io) catch 0;1261    file.writePositionalAll(io, entry, size) catch {};1262}12631264// --- Update helpers ---12651266// Fetch a URL with curl and return the response body. Caller must free.1267// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.1268pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1269    const argv = [_][]const u8{1270        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1271    };1272    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1273    defer gpa.free(result.stderr);12741275    const marker = "\nHTTP_STATUS:";1276    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1277        gpa.free(result.stdout);1278        return error.NetworkError;1279    };1280    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1281    const status = std.fmt.parseInt(u16, status_str, 10) catch {1282        gpa.free(result.stdout);1283        return error.NetworkError;1284    };1285    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1286    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1287    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1288        gpa.free(result.stdout);1289        return e;1290    };1291    gpa.free(result.stdout);1292    return body;1293}12941295// Download a URL to a temp file. Returns the temp path (caller must gpa.free).1296// The file is written to /tmp/nina-update-<pid> and left for the caller to use.1297pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1298    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1299    errdefer gpa.free(tmp_path);13001301    var child = std.process.spawn(io, .{1302        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1303        .stdin = .close,1304        .stdout = .close,1305        .stderr = .inherit,1306    }) catch return error.NetworkError;1307    const term = child.wait(io) catch return error.NetworkError;1308    switch (term) {1309        .exited => |c| if (c != 0) return error.NetworkError,1310        else => return error.NetworkError,1311    }1312    return tmp_path;1313}13141315// Get the current executable path into buf. Returns slice of buf.1316pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1317    const len = try std.process.executablePath(io, buf);1318    return buf[0..len];1319}13201321// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1322// atomically install the binary to install_path. Errors: ChecksumMismatch,1323// AccessDenied (with error_info set), or underlying I/O errors.1324pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1325    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1326        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1327        return error.FileNotFound;1328    };1329    defer gpa.free(bytes);13301331    var hasher = std.crypto.hash.Blake3.init(.{});1332    hasher.update(bytes);1333    var raw: [32]u8 = undefined;1334    hasher.final(&raw);1335    const hex = std.fmt.bytesToHex(raw, .lower);1336    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;13371338    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1339    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1340        return error.NameTooLong;13411342    {1343        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1344            errors.error_info.setMessage("cannot write to {s}", .{install_path});1345            errors.error_info.setSuggestion("try: sudo nina update", .{});1346            return error.AccessDenied;1347        };1348        defer f.close(io);1349        f.writePositionalAll(io, bytes, 0) catch {1350            errors.error_info.setMessage("cannot write to {s}", .{install_path});1351            return error.AccessDenied;1352        };1353        try f.setPermissions(io, .fromMode(0o755));1354    }1355    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};13561357    if (comptime builtin.os.tag == .macos) {1358        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1359    }13601361    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1362        error.AccessDenied => {1363            errors.error_info.setMessage("cannot replace {s}", .{install_path});1364            errors.error_info.setSuggestion("try: sudo nina update", .{});1365            return error.AccessDenied;1366        },1367        else => return e,1368    };1369}13701371// --- Nix feature setup ---13721373pub const NixFeatureStatus = struct {1374    nix_command: bool = false,1375    flakes: bool = false,13761377    pub fn allEnabled(self: NixFeatureStatus) bool {1378        return self.nix_command and self.flakes;1379    }1380};13811382fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1383    var lines = std.mem.splitScalar(u8, conf, '\n');1384    while (lines.next()) |line| {1385        const trimmed = std.mem.trim(u8, line, " \t");1386        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1387        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1388        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1389    }1390}13911392pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1393    var status = NixFeatureStatus{};13941395    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1396        defer gpa.free(conf);1397        scanConfFeatures(conf, &status);1398    }13991400    if (environ.get("HOME")) |home| {1401        var buf: [512]u8 = undefined;1402        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1403        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1404            defer gpa.free(conf);1405            scanConfFeatures(conf, &status);1406        }1407    }14081409    return status;1410}14111412pub fn isNixOS(io: std.Io) bool {1413    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1414    file.close(io);1415    return true;1416}14171418// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.1419// Returns the path written (caller must free).1420pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1421    const home = environ.get("HOME") orelse {1422        errors.error_info.setMessage("HOME not set", .{});1423        return error.ConfigNotFound;1424    };14251426    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1427    defer gpa.free(dir_path);1428    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1429    errdefer gpa.free(file_path);14301431    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};14321433    const line = "experimental-features = nix-command flakes\n";1434    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1435        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1436        errors.error_info.setMessage("could not write {s}", .{file_path});1437        return error.FileNotFound;1438    });1439    defer file.close(io);14401441    const size = file.length(io) catch 0;1442    file.writePositionalAll(io, line, size) catch {1443        errors.error_info.setMessage("could not write {s}", .{file_path});1444        return error.FileNotFound;1445    };14461447    return file_path;1448}14491450// --- NixOS: declarative experimental-features ---1451//1452// On NixOS the permanent, declarative home for these flags is configuration.nix,1453// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves1454// the `nixos-rebuild switch` to the user.14551456pub const NIXOS_FEATURES_LINE =1457    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";14581459// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns1460// false on any read error so the caller still offers to add the line.1461pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1462    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1463    defer gpa.free(conf);1464    return std.mem.indexOf(u8, conf, "experimental-features") != null and1465        std.mem.indexOf(u8, conf, "nix-command") != null and1466        std.mem.indexOf(u8, conf, "flakes") != null;1467}14681469fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1470    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1471    return captureLocal(gpa, io, &.{ "sudo", "cat", path });1472}14731474// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix1475// (i.e. inside the top-level attribute set) and write it back via a single1476// `sudo cp`, which prompts for the password on the terminal. Returns an error1477// for the caller to fall back to printed manual instructions.1478pub fn appendFeaturesToNixosConfig(1479    gpa: std.mem.Allocator,1480    io: std.Io,1481    environ: *const std.process.Environ.Map,1482    path: []const u8,1483) !void {1484    const conf = readMaybeSudo(gpa, io, path) catch {1485        errors.error_info.setMessage("could not read {s}", .{path});1486        return error.ConfigNotFound;1487    };1488    defer gpa.free(conf);14891490    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared14911492    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1493        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1494        return error.MalformedConfig;1495    };14961497    const home = environ.get("HOME") orelse {1498        errors.error_info.setMessage("HOME not set", .{});1499        return error.ConfigNotFound;1500    };1501    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1502    defer gpa.free(tmp_path);15031504    var buf: std.ArrayList(u8) = .empty;1505    defer buf.deinit(gpa);1506    try buf.appendSlice(gpa, conf[0..brace]);1507    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1508    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");1509    try buf.appendSlice(gpa, "  ");1510    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1511    try buf.append(gpa, '\n');1512    try buf.appendSlice(gpa, conf[brace..]);15131514    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1515        errors.error_info.setMessage("could not write {s}", .{tmp_path});1516        return error.FileNotFound;1517    };1518    tmp.writePositionalAll(io, buf.items, 0) catch {1519        tmp.close(io);1520        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1521        errors.error_info.setMessage("could not write {s}", .{tmp_path});1522        return error.FileNotFound;1523    };1524    tmp.close(io);15251526    // Back up the existing config, then replace it — in one sudo call so the1527    // password is asked for at most once. Paths travel as positional args ($0,1528    // $1) to sidestep shell quoting.1529    const code = streamLocal(io, &.{1530        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1531    }) catch {1532        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1533        errors.error_info.setMessage("could not write {s}", .{path});1534        return error.ProcessFailed;1535    };1536    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1537    if (code != 0) {1538        errors.error_info.setMessage("sudo cp into {s} failed", .{path});1539        return error.ProcessFailed;1540    }1541}