exec.zig

63.2 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}746747pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {748    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });749}750751pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {752    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });753}754755pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {756    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });757}758759pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {760    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });761}762763pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {764    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });765    defer gpa.free(r.stderr);766    if (r.exit_code != 0) {767        gpa.free(r.stdout);768        return error.ProcessFailed;769    }770    return r.stdout;771}772773// --- Build / Run / Develop ---774775pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {776    if (attr) |a| {777        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});778        defer gpa.free(ref);779        return stream(io, machine, gpa, &.{ "nix", "build", ref });780    }781    return stream(io, machine, gpa, &.{ "nix", "build" });782}783784pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {785    // nix run always gets --no-write-lock-file for remote URLs786    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");787    if (is_url) {788        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });789    }790    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.791    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {792        return stream(io, machine, gpa, &.{ "nix", "run", pkg });793    }794    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});795    defer gpa.free(ref);796    return stream(io, machine, gpa, &.{ "nix", "run", ref });797}798799pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {800    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});801    defer gpa.free(ref);802    return stream(io, machine, gpa, &.{ "nix", "shell", ref });803}804805pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {806    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});807    defer gpa.free(ref);808    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});809    defer gpa.free(ps1);810    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);811}812813pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {814    if (run_cmd) |cmd| {815        // sh -c so a multi-word command isn't treated as a single executable name.816        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });817    }818    return stream(io, machine, gpa, &.{ "nix", "develop" });819}820821pub 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 {822    if (run_cmd) |cmd| {823        // sh -c so a multi-word command isn't treated as a single executable name.824        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });825    }826    return streamEnv(io, machine, gpa, &.{ "nix", "develop" }, base_env, "(nina: dev) -> ");827}828829pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {830    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });831}832833// --- Format ---834835pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {836    if (check) {837        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });838    }839    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });840}841842// --- Info ---843844pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {845    const r = try capture(gpa, io, machine, &.{"nixos-version"});846    defer gpa.free(r.stderr);847    if (r.exit_code != 0) {848        gpa.free(r.stdout);849        return error.ProcessFailed;850    }851    return r.stdout;852}853854pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {855    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });856    defer gpa.free(r.stderr);857    if (r.exit_code != 0) {858        gpa.free(r.stdout);859        return error.ProcessFailed;860    }861    return r.stdout;862}863864pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {865    const r = try capture(gpa, io, machine, &.{"uptime"});866    defer gpa.free(r.stderr);867    if (r.exit_code != 0) {868        gpa.free(r.stdout);869        return error.ProcessFailed;870    }871    return r.stdout;872}873874// --- Boot ---875876pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {877    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });878    defer gpa.free(r.stderr);879    defer gpa.free(r.stdout);880    if (r.exit_code != 0) return error.ProcessFailed;881    return parseBootEntries(gpa, r.stdout);882}883884fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {885    var entries: std.ArrayList(types.BootEntry) = .empty;886    var lines = std.mem.splitScalar(u8, output_str, '\n');887    while (lines.next()) |line| {888        const trimmed = std.mem.trim(u8, line, " \t\r");889        if (std.mem.startsWith(u8, trimmed, "title:")) {890            const title = std.mem.trim(u8, trimmed[6..], " \t");891            const current = std.mem.indexOf(u8, title, "(current)") != null;892            try entries.append(gpa, .{893                .title = try gpa.dupe(u8, title),894                .current = current,895            });896        }897    }898    return entries.toOwnedSlice(gpa);899}900901// --- Pkg info ---902903pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {904    return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });905}906907pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {908    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });909}910911pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {912    // A bare name ("ripgrep") isn't a valid installable; resolve via nixpkgs# like913    // `pkg path` does. -S -h gives closure size, human-readable. Output is914    // "<store-path>   <size>"; return just the size.915    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});916    defer gpa.free(ref);917    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref });918    defer gpa.free(r.stderr);919    defer gpa.free(r.stdout);920    if (r.exit_code != 0) return error.ProcessFailed;921922    const line = std.mem.trim(u8, r.stdout, " \t\n\r");923    var it = std.mem.tokenizeAny(u8, line, " \t");924    _ = it.next(); // store path925    const size = std.mem.trim(u8, it.rest(), " \t");926    if (size.len == 0) return error.ProcessFailed;927    return gpa.dupe(u8, size);928}929930pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {931    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });932}933934// --- Hash / Fetch ---935936pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {937    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });938    defer gpa.free(r.stderr);939    if (r.exit_code != 0) {940        gpa.free(r.stdout);941        return error.ProcessFailed;942    }943    return r.stdout;944}945946pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {947    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });948    defer gpa.free(r.stderr);949    if (r.exit_code != 0) {950        gpa.free(r.stdout);951        return error.ProcessFailed;952    }953    return r.stdout;954}955956// --- Pin ---957958pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {959    // Stub: full implementation would parse and edit flake.lock JSON960    // The pin/unpin flow works via nix flake update which regenerates flake.lock961}962963pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {964    if (line) |l| {965        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});966        defer gpa.free(line_arg);967        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });968    }969    return stream(io, &types.Machine{}, gpa, &.{ editor, path });970}971972pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {973    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});974    defer gpa.free(a_str);975    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});976    defer gpa.free(b_str);977    // On a tty, the child's own color is fine — stream it directly.978    if (output.colorEnabled()) {979        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });980    }981    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,982    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.983    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });984    defer gpa.free(r.stdout);985    defer gpa.free(r.stderr);986    const cleaned = try stripAnsi(gpa, r.stdout);987    defer gpa.free(cleaned);988    output.raw(cleaned);989    return r.exit_code;990}991992// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a993// child process's color when it writes ANSI unconditionally.994fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {995    var out: std.ArrayList(u8) = .empty;996    errdefer out.deinit(gpa);997    var i: usize = 0;998    while (i < input.len) {999        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1000            i += 2;1001            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1002            if (i < input.len) i += 1; // consume the final byte1003            continue;1004        }1005        try out.append(gpa, input[i]);1006        i += 1;1007    }1008    return out.toOwnedSlice(gpa);1009}10101011test "stripAnsi removes CSI color sequences" {1012    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1013    defer std.testing.allocator.free(cleaned);1014    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1015}10161017// --- Doctor checks ---10181019pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1020    var checks: std.ArrayList(types.DoctorCheck) = .empty;10211022    // Check nix daemon1023    {1024        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1025        defer gpa.free(r.stdout);1026        defer gpa.free(r.stderr);1027        const active = std.mem.indexOf(u8, r.stdout, "active") != null;1028        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1029    }10301031    // Check config syntax1032    {1033        const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });1034        defer gpa.free(r.stdout);1035        defer gpa.free(r.stderr);1036        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1037    }10381039    // Check channel1040    {1041        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1042        defer gpa.free(r.stdout);1043        defer gpa.free(r.stderr);1044        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1045        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1046    }10471048    return checks.toOwnedSlice(gpa);1049}10501051// --- Home Manager ---1052//1053// Home Manager has three usage modes. nina detects which one is in play before1054// any `home` command so it can either drive the standalone CLI or redirect the1055// user to `nina apply` (when HM is a NixOS/flake module activated by rebuild).10561057pub const HomeManagerMode = enum {1058    // home-manager binary on PATH — manages the user env on its own.1059    standalone,1060    // No binary, but a home.nix exists — HM is a NixOS/flake module rebuilt by1061    // nixos-rebuild. `nina home apply` redirects to `nina apply`.1062    module,1063    none,1064};10651066fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1067    const home = environ.get("HOME") orelse return null;1068    return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1069}10701071// Path to the standalone home.nix. Caller frees.1072pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1073    const dir = homeConfigDir(gpa, environ) orelse return null;1074    defer gpa.free(dir);1075    return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1076}10771078fn pathExists(io: std.Io, path: []const u8) bool {1079    const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1080    f.close(io);1081    return true;1082}10831084// `command -v <name>` — true if the binary resolves on PATH. Silent (captured),1085// unlike streamLocal which would inherit stdio.1086fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1087    var buf: [256]u8 = undefined;1088    const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1089    const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1090    defer gpa.free(r.stdout);1091    defer gpa.free(r.stderr);1092    return switch (r.term) {1093        .exited => |code| code == 0,1094        else => false,1095    };1096}10971098pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1099    if (commandExists(gpa, io, "home-manager")) return .standalone;1100    if (homeNixPath(gpa, environ)) |p| {1101        defer gpa.free(p);1102        if (pathExists(io, p)) return .module;1103    }1104    return .none;1105}11061107// If the home-manager config dir holds a flake.nix, returns the flake ref1108// "<dir>#<user>" for `home-manager switch --flake`. Username comes from $USER.1109// Caller frees. null when there's no flake.nix (channel-based home config).1110pub fn homeFlakeRef(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1111    const dir = homeConfigDir(gpa, environ) orelse return null;1112    defer gpa.free(dir);1113    const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch return null;1114    defer gpa.free(flake);1115    if (!pathExists(io, flake)) return null;1116    const user = environ.get("USER") orelse "default";1117    return std.fmt.allocPrint(gpa, "{s}#{s}", .{ dir, user }) catch null;1118}11191120pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1121    return stream(io, machine, gpa, &.{ "home-manager", "switch" });1122}11231124pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8) !u8 {1125    return stream(io, machine, gpa, &.{ "home-manager", "switch", "--flake", flake_ref });1126}11271128// home-manager has no system-profile rollback; it re-activates the previous1129// generation via `switch --rollback`.1130pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1131    return stream(io, machine, gpa, &.{ "home-manager", "switch", "--rollback" });1132}11331134// Build (and validate) the home config without activating it — used by `home1135// check` and `home apply --dry`.1136pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1137    return stream(io, machine, gpa, &.{ "home-manager", "build" });1138}11391140pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1141    const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1142    defer gpa.free(r.stderr);1143    if (r.exit_code != 0) {1144        gpa.free(r.stdout);1145        return error.ProcessFailed;1146    }1147    return r.stdout;1148}11491150// Store paths referenced by a home generation — used to list managed packages.1151pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1152    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1153    defer gpa.free(r.stderr);1154    if (r.exit_code != 0) {1155        gpa.free(r.stdout);1156        return error.ProcessFailed;1157    }1158    return r.stdout;1159}11601161// diff-closures between two arbitrary store paths (home generations), mirroring1162// diffClosures' tty/piped color handling.1163pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1164    if (output.colorEnabled()) {1165        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1166    }1167    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1168    defer gpa.free(r.stdout);1169    defer gpa.free(r.stderr);1170    const cleaned = try stripAnsi(gpa, r.stdout);1171    defer gpa.free(cleaned);1172    output.raw(cleaned);1173    return r.exit_code;1174}11751176// --- Log ---11771178pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1179    const home = environ.get("HOME") orelse return error.FileNotFound;1180    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1181    defer gpa.free(path);1182    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1183    if (last == 0) return content;11841185    // Collect non-empty lines, then keep only the final `last`. Slices point into1186    // `content`, so copy them out before freeing it.1187    var lines: std.ArrayList([]const u8) = .empty;1188    defer lines.deinit(gpa);1189    var it = std.mem.splitScalar(u8, content, '\n');1190    while (it.next()) |line| {1191        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1192        try lines.append(gpa, line);1193    }1194    if (lines.items.len <= last) return content;11951196    var out: std.ArrayList(u8) = .empty;1197    errdefer out.deinit(gpa);1198    for (lines.items[lines.items.len - last ..]) |line| {1199        try out.appendSlice(gpa, line);1200        try out.append(gpa, '\n');1201    }1202    gpa.free(content);1203    return out.toOwnedSlice(gpa);1204}12051206// nina is a one-shot process, so "did the last apply fail this session?" can't1207// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1208// other ~/.nina-* state files. This lets a later successful apply earn the1209// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1210pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1211    const home = environ.get("HOME") orelse return;1212    var buf: [512]u8 = undefined;1213    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1214    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1215    file.close(io);1216}12171218pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1219    const home = environ.get("HOME") orelse return false;1220    var buf: [512]u8 = undefined;1221    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1222    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1223        f.close(io);1224        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1225        return true;1226    } else |_| {1227        return false;1228    }1229}12301231pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1232    const home = environ.get("HOME") orelse return;1233    var path_buf: [512]u8 = undefined;1234    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1235    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1236        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1237    defer file.close(io);1238    const size = file.length(io) catch 0;1239    file.writePositionalAll(io, entry, size) catch {};1240}12411242// --- Update helpers ---12431244// Fetch a URL with curl and return the response body. Caller must free.1245// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.1246pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1247    const argv = [_][]const u8{1248        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1249    };1250    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1251    defer gpa.free(result.stderr);12521253    const marker = "\nHTTP_STATUS:";1254    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1255        gpa.free(result.stdout);1256        return error.NetworkError;1257    };1258    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1259    const status = std.fmt.parseInt(u16, status_str, 10) catch {1260        gpa.free(result.stdout);1261        return error.NetworkError;1262    };1263    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1264    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1265    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1266        gpa.free(result.stdout);1267        return e;1268    };1269    gpa.free(result.stdout);1270    return body;1271}12721273// Download a URL to a temp file. Returns the temp path (caller must gpa.free).1274// The file is written to /tmp/nina-update-<pid> and left for the caller to use.1275pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1276    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1277    errdefer gpa.free(tmp_path);12781279    var child = std.process.spawn(io, .{1280        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1281        .stdin = .close,1282        .stdout = .close,1283        .stderr = .inherit,1284    }) catch return error.NetworkError;1285    const term = child.wait(io) catch return error.NetworkError;1286    switch (term) {1287        .exited => |c| if (c != 0) return error.NetworkError,1288        else => return error.NetworkError,1289    }1290    return tmp_path;1291}12921293// Get the current executable path into buf. Returns slice of buf.1294pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1295    const len = try std.process.executablePath(io, buf);1296    return buf[0..len];1297}12981299// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1300// atomically install the binary to install_path. Errors: ChecksumMismatch,1301// AccessDenied (with error_info set), or underlying I/O errors.1302pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1303    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1304        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1305        return error.FileNotFound;1306    };1307    defer gpa.free(bytes);13081309    var hasher = std.crypto.hash.Blake3.init(.{});1310    hasher.update(bytes);1311    var raw: [32]u8 = undefined;1312    hasher.final(&raw);1313    const hex = std.fmt.bytesToHex(raw, .lower);1314    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;13151316    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1317    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1318        return error.NameTooLong;13191320    {1321        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1322            errors.error_info.setMessage("cannot write to {s}", .{install_path});1323            errors.error_info.setSuggestion("try: sudo nina update", .{});1324            return error.AccessDenied;1325        };1326        defer f.close(io);1327        f.writePositionalAll(io, bytes, 0) catch {1328            errors.error_info.setMessage("cannot write to {s}", .{install_path});1329            return error.AccessDenied;1330        };1331        try f.setPermissions(io, .fromMode(0o755));1332    }1333    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};13341335    if (comptime builtin.os.tag == .macos) {1336        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1337    }13381339    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1340        error.AccessDenied => {1341            errors.error_info.setMessage("cannot replace {s}", .{install_path});1342            errors.error_info.setSuggestion("try: sudo nina update", .{});1343            return error.AccessDenied;1344        },1345        else => return e,1346    };1347}13481349// --- Nix feature setup ---13501351pub const NixFeatureStatus = struct {1352    nix_command: bool = false,1353    flakes: bool = false,13541355    pub fn allEnabled(self: NixFeatureStatus) bool {1356        return self.nix_command and self.flakes;1357    }1358};13591360fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1361    var lines = std.mem.splitScalar(u8, conf, '\n');1362    while (lines.next()) |line| {1363        const trimmed = std.mem.trim(u8, line, " \t");1364        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1365        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1366        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1367    }1368}13691370pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1371    var status = NixFeatureStatus{};13721373    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1374        defer gpa.free(conf);1375        scanConfFeatures(conf, &status);1376    }13771378    if (environ.get("HOME")) |home| {1379        var buf: [512]u8 = undefined;1380        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1381        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1382            defer gpa.free(conf);1383            scanConfFeatures(conf, &status);1384        }1385    }13861387    return status;1388}13891390pub fn isNixOS(io: std.Io) bool {1391    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1392    file.close(io);1393    return true;1394}13951396// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.1397// Returns the path written (caller must free).1398pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1399    const home = environ.get("HOME") orelse {1400        errors.error_info.setMessage("HOME not set", .{});1401        return error.ConfigNotFound;1402    };14031404    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1405    defer gpa.free(dir_path);1406    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1407    errdefer gpa.free(file_path);14081409    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};14101411    const line = "experimental-features = nix-command flakes\n";1412    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1413        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1414        errors.error_info.setMessage("could not write {s}", .{file_path});1415        return error.FileNotFound;1416    });1417    defer file.close(io);14181419    const size = file.length(io) catch 0;1420    file.writePositionalAll(io, line, size) catch {1421        errors.error_info.setMessage("could not write {s}", .{file_path});1422        return error.FileNotFound;1423    };14241425    return file_path;1426}14271428// --- NixOS: declarative experimental-features ---1429//1430// On NixOS the permanent, declarative home for these flags is configuration.nix,1431// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves1432// the `nixos-rebuild switch` to the user.14331434pub const NIXOS_FEATURES_LINE =1435    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";14361437// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns1438// false on any read error so the caller still offers to add the line.1439pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1440    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1441    defer gpa.free(conf);1442    return std.mem.indexOf(u8, conf, "experimental-features") != null and1443        std.mem.indexOf(u8, conf, "nix-command") != null and1444        std.mem.indexOf(u8, conf, "flakes") != null;1445}14461447fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1448    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1449    return captureLocal(gpa, io, &.{ "sudo", "cat", path });1450}14511452// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix1453// (i.e. inside the top-level attribute set) and write it back via a single1454// `sudo cp`, which prompts for the password on the terminal. Returns an error1455// for the caller to fall back to printed manual instructions.1456pub fn appendFeaturesToNixosConfig(1457    gpa: std.mem.Allocator,1458    io: std.Io,1459    environ: *const std.process.Environ.Map,1460    path: []const u8,1461) !void {1462    const conf = readMaybeSudo(gpa, io, path) catch {1463        errors.error_info.setMessage("could not read {s}", .{path});1464        return error.ConfigNotFound;1465    };1466    defer gpa.free(conf);14671468    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared14691470    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1471        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1472        return error.MalformedConfig;1473    };14741475    const home = environ.get("HOME") orelse {1476        errors.error_info.setMessage("HOME not set", .{});1477        return error.ConfigNotFound;1478    };1479    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1480    defer gpa.free(tmp_path);14811482    var buf: std.ArrayList(u8) = .empty;1483    defer buf.deinit(gpa);1484    try buf.appendSlice(gpa, conf[0..brace]);1485    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1486    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");1487    try buf.appendSlice(gpa, "  ");1488    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1489    try buf.append(gpa, '\n');1490    try buf.appendSlice(gpa, conf[brace..]);14911492    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1493        errors.error_info.setMessage("could not write {s}", .{tmp_path});1494        return error.FileNotFound;1495    };1496    tmp.writePositionalAll(io, buf.items, 0) catch {1497        tmp.close(io);1498        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1499        errors.error_info.setMessage("could not write {s}", .{tmp_path});1500        return error.FileNotFound;1501    };1502    tmp.close(io);15031504    // Back up the existing config, then replace it — in one sudo call so the1505    // password is asked for at most once. Paths travel as positional args ($0,1506    // $1) to sidestep shell quoting.1507    const code = streamLocal(io, &.{1508        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1509    }) catch {1510        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1511        errors.error_info.setMessage("could not write {s}", .{path});1512        return error.ProcessFailed;1513    };1514    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1515    if (code != 0) {1516        errors.error_info.setMessage("sudo cp into {s} failed", .{path});1517        return error.ProcessFailed;1518    }1519}