exec.zig

63.6 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.178pub fn configHasFlake(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {179    if (!machine.local) return false;180    const flake_path = std.fs.path.join(gpa, &.{ machine.config_path, "flake.nix" }) catch return false;181    defer gpa.free(flake_path);182    const f = std.Io.Dir.openFile(.cwd(), io, flake_path, .{}) catch return false;183    f.close(io);184    return true;185}186187// nixos-rebuild auto-detects /etc/nixos/flake.nix, so the --flake flag is only188// needed when the flake lives elsewhere. A flake at a non-default path must be189// passed explicitly or nixos-rebuild falls back to channels.190fn useFlakeFlag(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {191    return configHasFlake(gpa, io, machine) and !std.mem.eql(u8, machine.config_path, "/etc/nixos");192}193194fn nixosRebuildRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, flake: bool) !u8 {195    if (flake) {196        return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb, "--flake", machine.config_path });197    }198    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb });199}200201pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {202    const flake = useFlakeFlag(gpa, io, machine);203    if (flake) {204        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});205    } else {206        output.printSubstep("nixos-rebuild switch", .{});207    }208    return nixosRebuildRun(io, machine, gpa, "switch", flake);209}210211pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {212    return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine));213}214215pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {216    return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine));217}218219// --- Generations ---220221// Read system-profile generations WITHOUT root. `nix-env --list-generations -p222// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user223// ("system.lock: Permission denied"). The generation symlinks themselves are224// world-readable, so list them directly: parse `system-N-link` names, take each225// link's own mtime for the date/time, and mark the one the `system` symlink226// points at as current. Output matches the `nix-env --list-generations` columns227// (num date time [current]) so parseGenerations is unchanged.228const GEN_LIST_SCRIPT =229    \\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 }'230;231232pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {233    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });234    defer gpa.free(r.stderr);235    defer gpa.free(r.stdout);236    if (r.exit_code != 0) return error.ProcessFailed;237    return parseGenerations(gpa, r.stdout);238}239240fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {241    var gens: std.ArrayList(types.GenerationInfo) = .empty;242    var lines = std.mem.splitScalar(u8, output_str, '\n');243    while (lines.next()) |line| {244        const trimmed = std.mem.trim(u8, line, " \t");245        if (trimmed.len == 0) continue;246        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");247        const num_str = parts.next() orelse continue;248        const date_str = parts.next() orelse continue;249        const time_str = parts.next() orelse continue;250        const rest = parts.rest();251        const current = std.mem.indexOf(u8, rest, "current") != null;252        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;253        try gens.append(gpa, .{254            .number = num,255            .date = try gpa.dupe(u8, date_str),256            .time = try gpa.dupe(u8, time_str),257            .current = current,258        });259    }260    return gens.toOwnedSlice(gpa);261}262263pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {264    const gens = try getGenerations(gpa, io, machine);265    defer gpa.free(gens);266    for (gens) |g| {267        if (g.current) return g.number;268    }269    return 0;270}271272pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {273    // Switch the system profile to generation n, then activate it (bootloader +274    // services). Without switch-to-configuration the change isn't applied.275    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 });276    defer gpa.free(cmd);277    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });278}279280pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {281    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });282}283284pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {285    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});286    defer gpa.free(n_str);287    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });288}289290pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {291    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });292}293294// --- Garbage collection ---295296pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {297    if (delete_old) {298        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });299    }300    // Keep the `keep` most recent system generations (+N deletes all but N),301    // then collect now-unreferenced store paths. `--delete-older-than` wants a302    // duration (e.g. 14d), not a generation count.303    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });304    defer gpa.free(cmd);305    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });306}307308// --- Channels ---309310pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {311    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });312    defer gpa.free(r.stderr);313    defer gpa.free(r.stdout);314    if (r.exit_code != 0) return error.ProcessFailed;315    return parseChannels(gpa, r.stdout);316}317318fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {319    var channels: std.ArrayList(types.ChannelInfo) = .empty;320    var lines = std.mem.splitScalar(u8, output_str, '\n');321    while (lines.next()) |line| {322        const trimmed = std.mem.trim(u8, line, " \t\r");323        if (trimmed.len == 0) continue;324        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;325        try channels.append(gpa, .{326            .name = try gpa.dupe(u8, trimmed[0..space]),327            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),328        });329    }330    return channels.toOwnedSlice(gpa);331}332333pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {334    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });335}336337pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {338    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });339}340341pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {342    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });343}344345// --- Services ---346347pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {348    const cmd: []const []const u8 = if (user)349        &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }350    else351        &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };352    const r = try capture(gpa, io, machine, cmd);353    defer gpa.free(r.stderr);354    defer gpa.free(r.stdout);355    if (r.exit_code != 0) return error.ProcessFailed;356    return parseServices(gpa, r.stdout);357}358359fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {360    var svcs: std.ArrayList(types.ServiceInfo) = .empty;361    var lines = std.mem.splitScalar(u8, output_str, '\n');362    while (lines.next()) |line| {363        const trimmed = std.mem.trim(u8, line, " \t\r");364        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines365        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");366        const name = parts.next() orelse continue;367        _ = parts.next(); // load368        const active_str = parts.next() orelse continue;369        const sub_str = parts.next() orelse "unknown";370371        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))372            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)373        else if (std.mem.eql(u8, active_str, "failed"))374            .failed375        else376            .inactive;377378        try svcs.append(gpa, .{379            .name = try gpa.dupe(u8, name),380            .state = state,381            .uptime = null,382        });383    }384    return svcs.toOwnedSlice(gpa);385}386387pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {388    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.389    // User services run under the caller's own systemd manager, so no sudo.390    if (user) {391        return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });392    }393    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });394}395396pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {397    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});398    defer gpa.free(n_str);399    if (user) {400        if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });401        return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });402    }403    if (follow) {404        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });405    }406    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });407}408409// --- Profile ---410411pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {412    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});413    defer gpa.free(pkg_ref);414    // `nix profile add` is the current verb; `install` is a deprecated alias that415    // prints a warning on modern nix.416    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });417}418419pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {420    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not421    // by flake ref — passing nixpkgs#ripgrep matches nothing.422    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });423}424425pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {426    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });427    defer gpa.free(r.stderr);428    if (r.exit_code != 0) return error.ProcessFailed;429    return r.stdout;430}431432// Machine-readable profile listing — caller parses elements -> name + version.433pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {434    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });435    defer gpa.free(r.stderr);436    if (r.exit_code != 0) {437        gpa.free(r.stdout);438        return error.ProcessFailed;439    }440    return r.stdout;441}442443// Returns the profile element name to pass to `nix profile remove/upgrade`444// (e.g. "nina" or "default"), or null if nina is not found. Caller owns the445// returned slice. A NixOS system-package install also resolves into /nix/store446// so the store path alone can't distinguish it from a profile install — the447// profile list can. A missing/empty profile (or no nix) returns null.448pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {449    const js = profileListJson(gpa, io, machine) catch return null;450    defer gpa.free(js);451    return profileJsonNinaElement(gpa, js);452}453454pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {455    const name = profileNinaElement(gpa, io, machine) orelse return false;456    gpa.free(name);457    return true;458}459460// True when a nix store path belongs to the nina package. Store paths have the461// form /nix/store/<32-char-hash>-<pname>-<version>[/<subpath>]. We check that462// the 33 chars after /nix/store/ are the hash+dash, and the pname that follows463// is exactly "nina" (followed by "-" or end-of-component).464fn storePathIsNina(path: []const u8) bool {465    const prefix = "/nix/store/";466    if (!std.mem.startsWith(u8, path, prefix)) return false;467    const rel = path[prefix.len..];468    // The store entry name ends at the first "/" (if any sub-path follows).469    const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];470    if (entry.len < 34) return false; // 32-char hash + dash + at least one char471    const pname_ver = entry[33..]; // skip hash + dash472    return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");473}474475// Pure parse of `nix profile list --json` for a nina element, returning its476// element name (the key to pass to `nix profile remove/upgrade`) or null.477// Newer nix (2.18+) keys elements by pname ("nina"). Older nix uses an array478// with an "attrPath" field. Tarball installs via the `default` output may use479// the key "default" instead of "nina"; we detect those via storePaths.480fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {481    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;482    defer parsed.deinit();483    const root = parsed.value;484    if (root != .object) return null;485    const elements = root.object.get("elements") orelse return null;486    switch (elements) {487        .object => |obj| {488            // Fast path: exact "nina" key (nix 2.18+ with nixpkgs#nina install).489            if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;490            // Fallback: scan storePaths. Handles tarball installs where the default491            // output is selected and nix names the element "default" (older nix) or492            // some other key derived from the attrPath rather than the pname.493            var it = obj.iterator();494            while (it.next()) |kv| {495                const val = kv.value_ptr.*;496                if (val != .object) continue;497                const sps = val.object.get("storePaths") orelse continue;498                if (sps != .array) continue;499                for (sps.array.items) |sp| {500                    if (sp == .string and storePathIsNina(sp.string))501                        return gpa.dupe(u8, kv.key_ptr.*) catch null;502                }503            }504            return null;505        },506        .array => |arr| {507            // Older nix array format. Element name is the last component of attrPath.508            for (arr.items) |el| {509                if (el != .object) continue;510                const ap = el.object.get("attrPath") orelse continue;511                if (ap != .string) continue;512                if (std.mem.eql(u8, ap.string, "nina") or513                    std.mem.endsWith(u8, ap.string, ".nina"))514                    return gpa.dupe(u8, "nina") catch null;515                // Tarball default-output install: attrPath ends in ".default" but516                // storePaths point to nina. Return "default" as the element name.517                const sps = el.object.get("storePaths") orelse continue;518                if (sps != .array) continue;519                for (sps.array.items) |sp| {520                    if (sp != .string) continue;521                    if (!storePathIsNina(sp.string)) continue;522                    const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;523                    const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;524                    return gpa.dupe(u8, el_name) catch null;525                }526            }527            return null;528        },529        else => return null,530    }531}532533test "profileJsonNinaElement finds element name from profile JSON" {534    const a = std.testing.allocator;535536    // Newer nix: elements keyed by pname. "nina" key present.537    const named =538        \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},539        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}540    ;541    const r1 = profileJsonNinaElement(a, named);542    defer if (r1) |n| a.free(n);543    try std.testing.expectEqualStrings("nina", r1.?);544545    // Tarball install via default output: element keyed as "default", storePath is nina.546    const default_key =547        \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}548    ;549    const r2 = profileJsonNinaElement(a, default_key);550    defer if (r2) |n| a.free(n);551    try std.testing.expectEqualStrings("default", r2.?);552553    // Decoy: storePath of another package contains "nina" as a substring but is not nina.554    const decoy =555        \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}556    ;557    const r3 = profileJsonNinaElement(a, decoy);558    try std.testing.expectEqual(@as(?[]const u8, null), r3);559560    // Older nix array schema, attrPath ending in ".nina".561    const arr =562        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}563    ;564    const r4 = profileJsonNinaElement(a, arr);565    defer if (r4) |n| a.free(n);566    try std.testing.expectEqualStrings("nina", r4.?);567568    // Older nix array schema, tarball default-output install.569    const arr_default =570        \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}571    ;572    const r5 = profileJsonNinaElement(a, arr_default);573    defer if (r5) |n| a.free(n);574    try std.testing.expectEqualStrings("default", r5.?);575576    // Empty / malformed → null.577    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));578    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));579}580581// The store paths that make up the running system environment. Each reference is582// a <hash>-<name>-<version> path, so the caller can list system packages with583// versions — there is no cleaner per-package list for environment.systemPackages.584pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {585    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });586    defer gpa.free(r.stderr);587    if (r.exit_code != 0) {588        gpa.free(r.stdout);589        return error.ProcessFailed;590    }591    return r.stdout;592}593594pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {595    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });596}597598// --- Store ---599600pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {601    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });602}603604pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {605    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });606}607608pub const SystemStatus = struct { size: []u8, age: []u8 };609610// One read-only pass for `nina status`: the current system's closure size (a611// single `path-info -S` of /run/current-system — fast, unlike -S over the whole612// store) and seconds since the system profile was last switched (its symlink613// mtime). Both are world-readable; no root needed.614const STATUS_SCRIPT =615    \\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} ))"616;617618pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {619    const unknown = SystemStatus{620        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },621        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },622    };623    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;624    defer gpa.free(r.stdout);625    defer gpa.free(r.stderr);626    if (r.exit_code != 0) return unknown;627628    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");629    const sz_str = it.next() orelse return unknown;630    const age_str = it.next() orelse return unknown;631    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;632    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;633634    gpa.free(unknown.size);635    gpa.free(unknown.age);636    return .{637        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),638        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),639    };640}641642// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A643// one-word health signal; exits non-zero when degraded, so we read stdout, not644// the code. Caller owns the returned slice.645pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {646    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch647        return gpa.dupe(u8, "unknown");648    defer gpa.free(r.stderr);649    const state = std.mem.trim(u8, r.stdout, " \t\n\r");650    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");651    gpa.free(r.stdout);652    return owned;653}654655fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {656    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});657    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});658    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});659    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});660}661662pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {663    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });664}665666pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {667    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)668    // graph work that takes minutes on a real store (59k+ paths) and hangs the669    // command. We don't need closures: `--all --json` (no -S) carries each path's670    // own narSize, so one fast pass gives the path count and the summed store size.671    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.672    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.673    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });674    defer gpa.free(pi.stdout);675    defer gpa.free(pi.stderr);676677    const scan = scanStoreJson(pi.stdout);678    const total_owned = try humanSize(gpa, scan.total_bytes);679680    return .{681        .total_size = total_owned,682        .live_paths = scan.count,683        .reclaimable_paths = 0,684    };685}686687const StoreScan = struct { count: u64, total_bytes: u64 };688689// One linear pass over `nix path-info --json`: each path object has exactly one690// "narSize": field, so counting them gives the true path count and summing the691// values gives the total store size — no per-path closure walk.692fn scanStoreJson(json_str: []const u8) StoreScan {693    const needle = "\"narSize\":";694    var count: u64 = 0;695    var total: u64 = 0;696    var i: usize = 0;697    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {698        var j = pos + needle.len;699        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}700        var val: u64 = 0;701        var any = false;702        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {703            val = val * 10 + (json_str[j] - '0');704            any = true;705        }706        if (any) {707            count += 1;708            total += val;709        }710        i = j;711    }712    return .{ .count = count, .total_bytes = total };713}714715fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {716    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };717    var val: f64 = @floatFromInt(bytes);718    var unit: usize = 0;719    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;720    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });721    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });722}723724pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {725    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the726    // flake registry), not a flake in the current directory.727    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});728    defer gpa.free(expr);729    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });730    defer gpa.free(r.stderr);731    if (r.exit_code != 0) {732        gpa.free(r.stdout);733        return error.ProcessFailed;734    }735    return r.stdout;736}737738// --- Flake ---739740pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {741    if (input) |inp| {742        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });743    }744    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });745}746747// Update flake inputs for the flake living in `dir` (the config dir). `nix flake748// update` operates on the flake in the working directory, so we cd there first.749// Used by `nina upgrade` on a flake system in place of nix-channel --update.750pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {751    return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });752}753754pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {755    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });756}757758pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {759    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });760}761762pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {763    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });764}765766pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {767    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });768}769770pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {771    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });772    defer gpa.free(r.stderr);773    if (r.exit_code != 0) {774        gpa.free(r.stdout);775        return error.ProcessFailed;776    }777    return r.stdout;778}779780// --- Build / Run / Develop ---781782pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {783    if (attr) |a| {784        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});785        defer gpa.free(ref);786        return stream(io, machine, gpa, &.{ "nix", "build", ref });787    }788    return stream(io, machine, gpa, &.{ "nix", "build" });789}790791pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {792    // nix run always gets --no-write-lock-file for remote URLs793    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");794    if (is_url) {795        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });796    }797    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.798    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {799        return stream(io, machine, gpa, &.{ "nix", "run", pkg });800    }801    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});802    defer gpa.free(ref);803    return stream(io, machine, gpa, &.{ "nix", "run", ref });804}805806pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {807    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});808    defer gpa.free(ref);809    return stream(io, machine, gpa, &.{ "nix", "shell", ref });810}811812pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {813    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});814    defer gpa.free(ref);815    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});816    defer gpa.free(ps1);817    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);818}819820pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {821    if (run_cmd) |cmd| {822        // sh -c so a multi-word command isn't treated as a single executable name.823        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });824    }825    return stream(io, machine, gpa, &.{ "nix", "develop" });826}827828pub 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 {829    if (run_cmd) |cmd| {830        // sh -c so a multi-word command isn't treated as a single executable name.831        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });832    }833    return streamEnv(io, machine, gpa, &.{ "nix", "develop" }, base_env, "(nina: dev) -> ");834}835836pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {837    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });838}839840// --- Format ---841842pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {843    if (check) {844        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });845    }846    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });847}848849// --- Info ---850851pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {852    const r = try capture(gpa, io, machine, &.{"nixos-version"});853    defer gpa.free(r.stderr);854    if (r.exit_code != 0) {855        gpa.free(r.stdout);856        return error.ProcessFailed;857    }858    return r.stdout;859}860861pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {862    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });863    defer gpa.free(r.stderr);864    if (r.exit_code != 0) {865        gpa.free(r.stdout);866        return error.ProcessFailed;867    }868    return r.stdout;869}870871pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {872    const r = try capture(gpa, io, machine, &.{"uptime"});873    defer gpa.free(r.stderr);874    if (r.exit_code != 0) {875        gpa.free(r.stdout);876        return error.ProcessFailed;877    }878    return r.stdout;879}880881// --- Boot ---882883pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {884    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });885    defer gpa.free(r.stderr);886    defer gpa.free(r.stdout);887    if (r.exit_code != 0) return error.ProcessFailed;888    return parseBootEntries(gpa, r.stdout);889}890891fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {892    var entries: std.ArrayList(types.BootEntry) = .empty;893    var lines = std.mem.splitScalar(u8, output_str, '\n');894    while (lines.next()) |line| {895        const trimmed = std.mem.trim(u8, line, " \t\r");896        if (std.mem.startsWith(u8, trimmed, "title:")) {897            const title = std.mem.trim(u8, trimmed[6..], " \t");898            const current = std.mem.indexOf(u8, title, "(current)") != null;899            try entries.append(gpa, .{900                .title = try gpa.dupe(u8, title),901                .current = current,902            });903        }904    }905    return entries.toOwnedSlice(gpa);906}907908// --- Pkg info ---909910pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {911    return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });912}913914pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {915    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });916}917918pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {919    // A bare name ("ripgrep") isn't a valid installable; resolve via nixpkgs# like920    // `pkg path` does. -S -h gives closure size, human-readable. Output is921    // "<store-path>   <size>"; return just the size.922    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});923    defer gpa.free(ref);924    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref });925    defer gpa.free(r.stderr);926    defer gpa.free(r.stdout);927    if (r.exit_code != 0) return error.ProcessFailed;928929    const line = std.mem.trim(u8, r.stdout, " \t\n\r");930    var it = std.mem.tokenizeAny(u8, line, " \t");931    _ = it.next(); // store path932    const size = std.mem.trim(u8, it.rest(), " \t");933    if (size.len == 0) return error.ProcessFailed;934    return gpa.dupe(u8, size);935}936937pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {938    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });939}940941// --- Hash / Fetch ---942943pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {944    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });945    defer gpa.free(r.stderr);946    if (r.exit_code != 0) {947        gpa.free(r.stdout);948        return error.ProcessFailed;949    }950    return r.stdout;951}952953pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {954    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });955    defer gpa.free(r.stderr);956    if (r.exit_code != 0) {957        gpa.free(r.stdout);958        return error.ProcessFailed;959    }960    return r.stdout;961}962963// --- Pin ---964965pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {966    // Stub: full implementation would parse and edit flake.lock JSON967    // The pin/unpin flow works via nix flake update which regenerates flake.lock968}969970pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {971    if (line) |l| {972        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});973        defer gpa.free(line_arg);974        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });975    }976    return stream(io, &types.Machine{}, gpa, &.{ editor, path });977}978979pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {980    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});981    defer gpa.free(a_str);982    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});983    defer gpa.free(b_str);984    // On a tty, the child's own color is fine — stream it directly.985    if (output.colorEnabled()) {986        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });987    }988    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,989    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.990    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });991    defer gpa.free(r.stdout);992    defer gpa.free(r.stderr);993    const cleaned = try stripAnsi(gpa, r.stdout);994    defer gpa.free(cleaned);995    output.raw(cleaned);996    return r.exit_code;997}998999// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a1000// child process's color when it writes ANSI unconditionally.1001fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1002    var out: std.ArrayList(u8) = .empty;1003    errdefer out.deinit(gpa);1004    var i: usize = 0;1005    while (i < input.len) {1006        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1007            i += 2;1008            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1009            if (i < input.len) i += 1; // consume the final byte1010            continue;1011        }1012        try out.append(gpa, input[i]);1013        i += 1;1014    }1015    return out.toOwnedSlice(gpa);1016}10171018test "stripAnsi removes CSI color sequences" {1019    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1020    defer std.testing.allocator.free(cleaned);1021    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1022}10231024// --- Doctor checks ---10251026pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1027    var checks: std.ArrayList(types.DoctorCheck) = .empty;10281029    // Check nix daemon1030    {1031        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1032        defer gpa.free(r.stdout);1033        defer gpa.free(r.stderr);1034        const active = std.mem.indexOf(u8, r.stdout, "active") != null;1035        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1036    }10371038    // Check config syntax1039    {1040        const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });1041        defer gpa.free(r.stdout);1042        defer gpa.free(r.stderr);1043        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1044    }10451046    // Check channel1047    {1048        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1049        defer gpa.free(r.stdout);1050        defer gpa.free(r.stderr);1051        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1052        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1053    }10541055    return checks.toOwnedSlice(gpa);1056}10571058// --- Home Manager ---1059//1060// Home Manager has three usage modes. nina detects which one is in play before1061// any `home` command so it can either drive the standalone CLI or redirect the1062// user to `nina apply` (when HM is a NixOS/flake module activated by rebuild).10631064pub const HomeManagerMode = enum {1065    // home-manager binary on PATH — manages the user env on its own.1066    standalone,1067    // No binary, but a home.nix exists — HM is a NixOS/flake module rebuilt by1068    // nixos-rebuild. `nina home apply` redirects to `nina apply`.1069    module,1070    none,1071};10721073fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1074    const home = environ.get("HOME") orelse return null;1075    return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1076}10771078// Path to the standalone home.nix. Caller frees.1079pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1080    const dir = homeConfigDir(gpa, environ) orelse return null;1081    defer gpa.free(dir);1082    return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1083}10841085fn pathExists(io: std.Io, path: []const u8) bool {1086    const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1087    f.close(io);1088    return true;1089}10901091// `command -v <name>` — true if the binary resolves on PATH. Silent (captured),1092// unlike streamLocal which would inherit stdio.1093fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1094    var buf: [256]u8 = undefined;1095    const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1096    const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1097    defer gpa.free(r.stdout);1098    defer gpa.free(r.stderr);1099    return switch (r.term) {1100        .exited => |code| code == 0,1101        else => false,1102    };1103}11041105pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1106    if (commandExists(gpa, io, "home-manager")) return .standalone;1107    if (homeNixPath(gpa, environ)) |p| {1108        defer gpa.free(p);1109        if (pathExists(io, p)) return .module;1110    }1111    return .none;1112}11131114// If the home-manager config dir holds a flake.nix, returns the flake ref1115// "<dir>#<user>" for `home-manager switch --flake`. Username comes from $USER.1116// Caller frees. null when there's no flake.nix (channel-based home config).1117pub fn homeFlakeRef(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1118    const dir = homeConfigDir(gpa, environ) orelse return null;1119    defer gpa.free(dir);1120    const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch return null;1121    defer gpa.free(flake);1122    if (!pathExists(io, flake)) return null;1123    const user = environ.get("USER") orelse "default";1124    return std.fmt.allocPrint(gpa, "{s}#{s}", .{ dir, user }) catch null;1125}11261127pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1128    return stream(io, machine, gpa, &.{ "home-manager", "switch" });1129}11301131pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8) !u8 {1132    return stream(io, machine, gpa, &.{ "home-manager", "switch", "--flake", flake_ref });1133}11341135// home-manager has no system-profile rollback; it re-activates the previous1136// generation via `switch --rollback`.1137pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1138    return stream(io, machine, gpa, &.{ "home-manager", "switch", "--rollback" });1139}11401141// Build (and validate) the home config without activating it — used by `home1142// check` and `home apply --dry`.1143pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1144    return stream(io, machine, gpa, &.{ "home-manager", "build" });1145}11461147pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1148    const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1149    defer gpa.free(r.stderr);1150    if (r.exit_code != 0) {1151        gpa.free(r.stdout);1152        return error.ProcessFailed;1153    }1154    return r.stdout;1155}11561157// Store paths referenced by a home generation — used to list managed packages.1158pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1159    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1160    defer gpa.free(r.stderr);1161    if (r.exit_code != 0) {1162        gpa.free(r.stdout);1163        return error.ProcessFailed;1164    }1165    return r.stdout;1166}11671168// diff-closures between two arbitrary store paths (home generations), mirroring1169// diffClosures' tty/piped color handling.1170pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1171    if (output.colorEnabled()) {1172        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1173    }1174    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1175    defer gpa.free(r.stdout);1176    defer gpa.free(r.stderr);1177    const cleaned = try stripAnsi(gpa, r.stdout);1178    defer gpa.free(cleaned);1179    output.raw(cleaned);1180    return r.exit_code;1181}11821183// --- Log ---11841185pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1186    const home = environ.get("HOME") orelse return error.FileNotFound;1187    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1188    defer gpa.free(path);1189    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1190    if (last == 0) return content;11911192    // Collect non-empty lines, then keep only the final `last`. Slices point into1193    // `content`, so copy them out before freeing it.1194    var lines: std.ArrayList([]const u8) = .empty;1195    defer lines.deinit(gpa);1196    var it = std.mem.splitScalar(u8, content, '\n');1197    while (it.next()) |line| {1198        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1199        try lines.append(gpa, line);1200    }1201    if (lines.items.len <= last) return content;12021203    var out: std.ArrayList(u8) = .empty;1204    errdefer out.deinit(gpa);1205    for (lines.items[lines.items.len - last ..]) |line| {1206        try out.appendSlice(gpa, line);1207        try out.append(gpa, '\n');1208    }1209    gpa.free(content);1210    return out.toOwnedSlice(gpa);1211}12121213// nina is a one-shot process, so "did the last apply fail this session?" can't1214// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1215// other ~/.nina-* state files. This lets a later successful apply earn the1216// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1217pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1218    const home = environ.get("HOME") orelse return;1219    var buf: [512]u8 = undefined;1220    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1221    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1222    file.close(io);1223}12241225pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1226    const home = environ.get("HOME") orelse return false;1227    var buf: [512]u8 = undefined;1228    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1229    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1230        f.close(io);1231        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1232        return true;1233    } else |_| {1234        return false;1235    }1236}12371238pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1239    const home = environ.get("HOME") orelse return;1240    var path_buf: [512]u8 = undefined;1241    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1242    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1243        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1244    defer file.close(io);1245    const size = file.length(io) catch 0;1246    file.writePositionalAll(io, entry, size) catch {};1247}12481249// --- Update helpers ---12501251// Fetch a URL with curl and return the response body. Caller must free.1252// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.1253pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1254    const argv = [_][]const u8{1255        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1256    };1257    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1258    defer gpa.free(result.stderr);12591260    const marker = "\nHTTP_STATUS:";1261    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1262        gpa.free(result.stdout);1263        return error.NetworkError;1264    };1265    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1266    const status = std.fmt.parseInt(u16, status_str, 10) catch {1267        gpa.free(result.stdout);1268        return error.NetworkError;1269    };1270    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1271    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1272    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1273        gpa.free(result.stdout);1274        return e;1275    };1276    gpa.free(result.stdout);1277    return body;1278}12791280// Download a URL to a temp file. Returns the temp path (caller must gpa.free).1281// The file is written to /tmp/nina-update-<pid> and left for the caller to use.1282pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1283    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1284    errdefer gpa.free(tmp_path);12851286    var child = std.process.spawn(io, .{1287        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1288        .stdin = .close,1289        .stdout = .close,1290        .stderr = .inherit,1291    }) catch return error.NetworkError;1292    const term = child.wait(io) catch return error.NetworkError;1293    switch (term) {1294        .exited => |c| if (c != 0) return error.NetworkError,1295        else => return error.NetworkError,1296    }1297    return tmp_path;1298}12991300// Get the current executable path into buf. Returns slice of buf.1301pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1302    const len = try std.process.executablePath(io, buf);1303    return buf[0..len];1304}13051306// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1307// atomically install the binary to install_path. Errors: ChecksumMismatch,1308// AccessDenied (with error_info set), or underlying I/O errors.1309pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1310    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1311        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1312        return error.FileNotFound;1313    };1314    defer gpa.free(bytes);13151316    var hasher = std.crypto.hash.Blake3.init(.{});1317    hasher.update(bytes);1318    var raw: [32]u8 = undefined;1319    hasher.final(&raw);1320    const hex = std.fmt.bytesToHex(raw, .lower);1321    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;13221323    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1324    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1325        return error.NameTooLong;13261327    {1328        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1329            errors.error_info.setMessage("cannot write to {s}", .{install_path});1330            errors.error_info.setSuggestion("try: sudo nina update", .{});1331            return error.AccessDenied;1332        };1333        defer f.close(io);1334        f.writePositionalAll(io, bytes, 0) catch {1335            errors.error_info.setMessage("cannot write to {s}", .{install_path});1336            return error.AccessDenied;1337        };1338        try f.setPermissions(io, .fromMode(0o755));1339    }1340    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};13411342    if (comptime builtin.os.tag == .macos) {1343        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1344    }13451346    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1347        error.AccessDenied => {1348            errors.error_info.setMessage("cannot replace {s}", .{install_path});1349            errors.error_info.setSuggestion("try: sudo nina update", .{});1350            return error.AccessDenied;1351        },1352        else => return e,1353    };1354}13551356// --- Nix feature setup ---13571358pub const NixFeatureStatus = struct {1359    nix_command: bool = false,1360    flakes: bool = false,13611362    pub fn allEnabled(self: NixFeatureStatus) bool {1363        return self.nix_command and self.flakes;1364    }1365};13661367fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1368    var lines = std.mem.splitScalar(u8, conf, '\n');1369    while (lines.next()) |line| {1370        const trimmed = std.mem.trim(u8, line, " \t");1371        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1372        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1373        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1374    }1375}13761377pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1378    var status = NixFeatureStatus{};13791380    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1381        defer gpa.free(conf);1382        scanConfFeatures(conf, &status);1383    }13841385    if (environ.get("HOME")) |home| {1386        var buf: [512]u8 = undefined;1387        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1388        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1389            defer gpa.free(conf);1390            scanConfFeatures(conf, &status);1391        }1392    }13931394    return status;1395}13961397pub fn isNixOS(io: std.Io) bool {1398    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1399    file.close(io);1400    return true;1401}14021403// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.1404// Returns the path written (caller must free).1405pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1406    const home = environ.get("HOME") orelse {1407        errors.error_info.setMessage("HOME not set", .{});1408        return error.ConfigNotFound;1409    };14101411    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1412    defer gpa.free(dir_path);1413    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1414    errdefer gpa.free(file_path);14151416    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};14171418    const line = "experimental-features = nix-command flakes\n";1419    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1420        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1421        errors.error_info.setMessage("could not write {s}", .{file_path});1422        return error.FileNotFound;1423    });1424    defer file.close(io);14251426    const size = file.length(io) catch 0;1427    file.writePositionalAll(io, line, size) catch {1428        errors.error_info.setMessage("could not write {s}", .{file_path});1429        return error.FileNotFound;1430    };14311432    return file_path;1433}14341435// --- NixOS: declarative experimental-features ---1436//1437// On NixOS the permanent, declarative home for these flags is configuration.nix,1438// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves1439// the `nixos-rebuild switch` to the user.14401441pub const NIXOS_FEATURES_LINE =1442    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";14431444// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns1445// false on any read error so the caller still offers to add the line.1446pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1447    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1448    defer gpa.free(conf);1449    return std.mem.indexOf(u8, conf, "experimental-features") != null and1450        std.mem.indexOf(u8, conf, "nix-command") != null and1451        std.mem.indexOf(u8, conf, "flakes") != null;1452}14531454fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1455    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1456    return captureLocal(gpa, io, &.{ "sudo", "cat", path });1457}14581459// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix1460// (i.e. inside the top-level attribute set) and write it back via a single1461// `sudo cp`, which prompts for the password on the terminal. Returns an error1462// for the caller to fall back to printed manual instructions.1463pub fn appendFeaturesToNixosConfig(1464    gpa: std.mem.Allocator,1465    io: std.Io,1466    environ: *const std.process.Environ.Map,1467    path: []const u8,1468) !void {1469    const conf = readMaybeSudo(gpa, io, path) catch {1470        errors.error_info.setMessage("could not read {s}", .{path});1471        return error.ConfigNotFound;1472    };1473    defer gpa.free(conf);14741475    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared14761477    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1478        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1479        return error.MalformedConfig;1480    };14811482    const home = environ.get("HOME") orelse {1483        errors.error_info.setMessage("HOME not set", .{});1484        return error.ConfigNotFound;1485    };1486    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1487    defer gpa.free(tmp_path);14881489    var buf: std.ArrayList(u8) = .empty;1490    defer buf.deinit(gpa);1491    try buf.appendSlice(gpa, conf[0..brace]);1492    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1493    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");1494    try buf.appendSlice(gpa, "  ");1495    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1496    try buf.append(gpa, '\n');1497    try buf.appendSlice(gpa, conf[brace..]);14981499    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1500        errors.error_info.setMessage("could not write {s}", .{tmp_path});1501        return error.FileNotFound;1502    };1503    tmp.writePositionalAll(io, buf.items, 0) catch {1504        tmp.close(io);1505        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1506        errors.error_info.setMessage("could not write {s}", .{tmp_path});1507        return error.FileNotFound;1508    };1509    tmp.close(io);15101511    // Back up the existing config, then replace it — in one sudo call so the1512    // password is asked for at most once. Paths travel as positional args ($0,1513    // $1) to sidestep shell quoting.1514    const code = streamLocal(io, &.{1515        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1516    }) catch {1517        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1518        errors.error_info.setMessage("could not write {s}", .{path});1519        return error.ProcessFailed;1520    };1521    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1522    if (code != 0) {1523        errors.error_info.setMessage("sudo cp into {s} failed", .{path});1524        return error.ProcessFailed;1525    }1526}