exec.zig

89.7 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};1819pub const HookResult = enum {20    ok,21    failed,22    not_found,23};2425pub const HookRun = struct {26    result: HookResult,27    exit_code: u8 = 0,28    output: []u8,29};3031// Run a process and capture stdout+stderr (not streaming).32pub fn capture(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, cmd: []const []const u8) !RunResult {33    const argv = try buildArgv(gpa, machine, cmd);34    defer if (!machine.local) gpa.free(argv);3536    const result = std.process.run(gpa, io, .{ .argv = argv }) catch |e| {37        errors.error_info.setMessage("process failed: {s}", .{cmd[0]});38        return e;39    };4041    return .{42        .stdout = result.stdout,43        .stderr = result.stderr,44        .exit_code = switch (result.term) {45            .exited => |c| c,46            else => 1,47        },48    };49}5051// Run a process and stream its output to the terminal (inherit stdio).52pub fn stream(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8) !u8 {53    // The child inherits stdout and writes directly to the fd; flush any buffered54    // nina header first so it isn't reordered after the child's output.55    output.flush();56    const argv = try buildArgv(gpa, machine, cmd);57    defer if (!machine.local) gpa.free(argv);5859    var child = std.process.spawn(io, .{60        .argv = argv,61        .stdin = .inherit,62        .stdout = .inherit,63        .stderr = .inherit,64    }) catch |e| {65        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});66        return e;67    };6869    const term = child.wait(io) catch |e| {70        errors.error_info.setMessage("process wait failed", .{});71        return e;72    };7374    return switch (term) {75        .exited => |c| c,76        else => 1,77    };78}7980// Stream a process with an overridden PS1 in the child environment.81fn 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 {82    output.flush();83    const argv = try buildArgv(gpa, machine, cmd);84    defer if (!machine.local) gpa.free(argv);8586    var env = try base_env.clone(gpa);87    defer env.deinit();88    try env.put("PS1", ps1);89    try env.put("NINA_PS1", ps1);9091    var child = std.process.spawn(io, .{92        .argv = argv,93        .stdin = .inherit,94        .stdout = .inherit,95        .stderr = .inherit,96        .environ_map = &env,97    }) catch |e| {98        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});99        return e;100    };101102    const term = child.wait(io) catch |e| {103        errors.error_info.setMessage("process wait failed", .{});104        return e;105    };106107    return switch (term) {108        .exited => |c| c,109        else => 1,110    };111}112113fn createInteractiveShellRc(gpa: std.mem.Allocator, io: std.Io) ![]u8 {114    const out = try captureLocal(gpa, io, &.{ "mktemp", "/tmp/nina-shell-rc.XXXXXX" });115    defer gpa.free(out);116117    const path = std.mem.trim(u8, out, " \t\r\n");118    if (path.len == 0) return error.FileNotFound;119    const owned_path = try gpa.dupe(u8, path);120    errdefer gpa.free(owned_path);121122    const file = std.Io.Dir.createFile(.cwd(), io, owned_path, .{}) catch {123        errors.error_info.setMessage("could not write shell prompt setup", .{});124        return error.FileNotFound;125    };126    errdefer file.close(io);127128    const content =129        \\PS1="${NINA_PS1:-$PS1}"130        \\trap 'exit 130' INT131        \\132    ;133    file.writePositionalAll(io, content, 0) catch {134        errors.error_info.setMessage("could not write shell prompt setup", .{});135        return error.FileNotFound;136    };137    file.close(io);138139    return owned_path;140}141142// Stream a local process with inherited stdio (no SSH routing — for nix commands).143pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 {144    output.flush();145    var child = std.process.spawn(io, .{146        .argv = cmd,147        .stdin = .inherit,148        .stdout = .inherit,149        .stderr = .inherit,150    }) catch |e| {151        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});152        return e;153    };154    const term = child.wait(io) catch {155        errors.error_info.setMessage("process wait failed", .{});156        return error.ProcessFailed;157    };158    return switch (term) {159        .exited => |c| c,160        else => 1,161    };162}163164// Run a process and capture output as a single string (no SSH routing — for local nix commands).165pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {166    const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;167    defer gpa.free(result.stderr);168    switch (result.term) {169        .exited => |c| if (c != 0) {170            gpa.free(result.stdout);171            return error.ProcessFailed;172        },173        else => {174            gpa.free(result.stdout);175            return error.ProcessFailed;176        },177    }178    return result.stdout;179}180181// Create a directory and its parents, best-effort. Shelling out to `mkdir -p`182// matches how the rest of exec.zig provisions config locations (~/.config/nix).183pub fn ensureDir(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) void {184    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir }) catch {};185}186187// Optional user hooks live in ~/.config/nina/hooks and must be executable.188// They are always local: hooks protect the user's local workflow before nina189// starts state-changing work.190pub fn runHook(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, hook_name: []const u8) !HookRun {191    const home = environ.get("HOME") orelse return .{192        .result = .not_found,193        .output = try gpa.dupe(u8, ""),194    };195196    const hook_dir = try std.fs.path.join(gpa, &.{ home, ".config", "nina", "hooks" });197    defer gpa.free(hook_dir);198    ensureDir(gpa, io, hook_dir);199200    const hook_path = try std.fs.path.join(gpa, &.{ hook_dir, hook_name });201    defer gpa.free(hook_path);202203    const executable = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", "test -x \"$1\"", "nina-hook-check", hook_path } }) catch return .{204        .result = .not_found,205        .output = try gpa.dupe(u8, ""),206    };207    defer gpa.free(executable.stdout);208    defer gpa.free(executable.stderr);209    const is_executable = switch (executable.term) {210        .exited => |code| code == 0,211        else => false,212    };213    if (!is_executable) return .{214        .result = .not_found,215        .output = try gpa.dupe(u8, ""),216    };217218    const tmp_raw = try captureLocal(gpa, io, &.{ "mktemp", "/tmp/nina-hook.XXXXXX" });219    defer gpa.free(tmp_raw);220    const tmp_output = std.mem.trim(u8, tmp_raw, " \t\r\n");221    defer if (std.fs.path.isAbsolute(tmp_output)) std.Io.Dir.deleteFileAbsolute(io, tmp_output) catch {};222223    const result = try std.process.run(gpa, io, .{224        .argv = &.{225            "sh",226            "-c",227            "$1 > \"$2\" 2>&1; code=$?; tail -c 4096 \"$2\"; exit \"$code\"",228            "nina-hook-run",229            hook_path,230            tmp_output,231        },232        .stdout_limit = .limited(4096),233        .stderr_limit = .limited(512),234    });235    defer gpa.free(result.stdout);236    defer gpa.free(result.stderr);237238    const exit_code = switch (result.term) {239        .exited => |code| code,240        else => 1,241    };242    return .{243        .result = if (exit_code == 0) .ok else .failed,244        .exit_code = exit_code,245        .output = try std.fmt.allocPrint(gpa, "{s}{s}", .{ result.stdout, result.stderr }),246    };247}248249test "runHook ignores non-executable hooks and captures failures" {250    const a = std.testing.allocator;251    const io = std.testing.io;252253    var tmp = std.testing.tmpDir(.{});254    defer tmp.cleanup();255256    const home = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{&tmp.sub_path});257    defer a.free(home);258259    var env: std.process.Environ.Map = .init(a);260    defer env.deinit();261    try env.put("HOME", home);262263    var hook_dir = try tmp.dir.createDirPathOpen(io, ".config/nina/hooks", .{});264    defer hook_dir.close(io);265266    const script =267        \\#!/bin/sh268        \\echo hook says no269        \\echo detail >&2270        \\exit 3271        \\272    ;273    {274        const file = try hook_dir.createFile(io, "pre-apply", .{});275        defer file.close(io);276        try file.writePositionalAll(io, script, 0);277        try file.setPermissions(io, .fromMode(0o644));278    }279280    const missing = try runHook(a, io, &env, "pre-apply");281    defer a.free(missing.output);282    try std.testing.expectEqual(HookResult.not_found, missing.result);283284    try hook_dir.setFilePermissions(io, "pre-apply", .fromMode(0o755), .{});285286    const failed = try runHook(a, io, &env, "pre-apply");287    defer a.free(failed.output);288    try std.testing.expectEqual(HookResult.failed, failed.result);289    try std.testing.expectEqual(@as(u8, 3), failed.exit_code);290    try std.testing.expect(std.mem.indexOf(u8, failed.output, "hook says no") != null);291    try std.testing.expect(std.mem.indexOf(u8, failed.output, "detail") != null);292}293294fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {295    if (machine.local) return cmd;296297    const host = machine.host orelse {298        errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});299        return error.SshFailed;300    };301302    var ssh: std.ArrayList([]const u8) = .empty;303    try ssh.append(gpa, "ssh");304    try ssh.append(gpa, "-o");305    try ssh.append(gpa, "BatchMode=yes");306    try ssh.append(gpa, "-o");307    try ssh.append(gpa, "StrictHostKeyChecking=accept-new");308    if (machine.ssh_key) |key| {309        try ssh.append(gpa, "-i");310        try ssh.append(gpa, key);311    }312    const addr = if (machine.user) |u|313        try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })314    else315        try gpa.dupe(u8, host);316    try ssh.append(gpa, addr);317    for (cmd) |arg| try ssh.append(gpa, arg);318    return ssh.toOwnedSlice(gpa);319}320321// --- NixOS rebuild ---322323// True if the machine's config dir holds a flake.nix. Only meaningful for a local324// machine — the file lives on the local filesystem. Remote flake detection would325// need an ssh round-trip; a remote flake at the default /etc/nixos needs no flag326// anyway, so we don't bother.327// True if `dir` contains a flake.nix (local filesystem check).328pub fn dirHasFlake(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) bool {329    const flake_path = std.fs.path.join(gpa, &.{ dir, "flake.nix" }) catch return false;330    defer gpa.free(flake_path);331    return pathExists(io, flake_path);332}333334pub fn configHasFlake(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {335    if (!machine.local) return false;336    return dirHasFlake(gpa, io, machine.config_path);337}338339// nixos-rebuild auto-detects /etc/nixos/flake.nix, so the --flake flag is only340// needed when the flake lives elsewhere. A flake at a non-default path must be341// passed explicitly or nixos-rebuild falls back to channels. Compare with342// trailing slashes trimmed so "/etc/nixos/" is still treated as the default.343fn useFlakeFlag(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {344    if (!configHasFlake(gpa, io, machine)) return false;345    var path = machine.config_path;346    while (path.len > 1 and path[path.len - 1] == '/') path = path[0 .. path.len - 1];347    return !std.mem.eql(u8, path, "/etc/nixos");348}349350// Capture nixos-rebuild stderr for the translation pipeline. Raw nix build351// output is suppressed; on failure, reportError() translates stderr via352// errors.translateError(). The substep line above the call tells the user what353// is running; silence during the build is intentional per the error-wrapping brief.354fn nixosRebuildRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, flake: bool, extra_flags: []const []const u8) !u8 {355    var argv: std.ArrayList([]const u8) = .empty;356    defer argv.deinit(gpa);357    try argv.appendSlice(gpa, &.{ "sudo", "nixos-rebuild", verb });358    if (flake) try argv.appendSlice(gpa, &.{ "--flake", machine.config_path });359    try argv.appendSlice(gpa, extra_flags);360361    output.flush();362    const r = try capture(gpa, io, machine, argv.items);363    defer gpa.free(r.stdout);364    defer gpa.free(r.stderr);365    errors.setBuildStderr(r.stderr);366    return r.exit_code;367}368369pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {370    const flake = useFlakeFlag(gpa, io, machine);371    if (flake) {372        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});373    } else {374        output.printSubstep("nixos-rebuild switch", .{});375    }376    return nixosRebuildRun(io, machine, gpa, "switch", flake, extra_flags);377}378379// Live-streaming variant used by `apply` when stdout is a TTY. Each stderr line380// from nixos-rebuild is fed to the build panel for real-time progress display381// while the full stderr is also accumulated for the error translation pipeline.382// Falls back to the silent capture path when not a TTY.383pub fn nixosRebuildSwitchWithPanel(384    io: std.Io,385    machine: *const types.Machine,386    gpa: std.mem.Allocator,387    panel: *output.BuildPanel,388    extra_flags: []const []const u8,389) !u8 {390    const flake = useFlakeFlag(gpa, io, machine);391    if (flake) {392        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});393    } else {394        output.printSubstep("nixos-rebuild switch", .{});395    }396    if (!output.colorEnabled()) return nixosRebuildRun(io, machine, gpa, "switch", flake, extra_flags);397    return nixosRebuildRunStreamed(io, machine, gpa, "switch", flake, panel, extra_flags);398}399400// Spawn argv with stderr piped, feed each line to the build panel for live progress,401// and accumulate the full stderr (newlines preserved) for errors.translateError.402// Factored out of nixosRebuildRunStreamed so the read loop is testable without a403// real nixos-rebuild binary.404fn runStreamedCapture(io: std.Io, gpa: std.mem.Allocator, argv: []const []const u8, panel: *output.BuildPanel) !u8 {405    var child = std.process.spawn(io, .{406        .argv = argv,407        .stdin = .ignore,408        .stdout = .ignore,409        .stderr = .pipe,410    }) catch |e| {411        errors.error_info.setMessage("failed to spawn nixos-rebuild", .{});412        return e;413    };414415    var accumulated: std.ArrayList(u8) = .empty;416    defer accumulated.deinit(gpa);417418    if (child.stderr) |stderr_file| {419        var reader_buf: [8192]u8 = undefined;420        var fr = std.Io.File.Reader.initStreaming(stderr_file, io, &reader_buf);421        while (true) {422            const raw = fr.interface.takeDelimiter('\n') catch |err| switch (err) {423                // A single line exceeded the reader's buffer — routine for nix eval424                // traces/derivation lists. Discard the oversized remainder instead of425                // abandoning the pipe: breaking here would leave stderr undrained, and426                // once the kernel pipe buffer filled the child would block on write()427                // forever, hanging child.wait() below.428                error.StreamTooLong => {429                    _ = fr.interface.discardDelimiterInclusive('\n') catch break;430                    continue;431                },432                error.ReadFailed => break,433            } orelse break;434            // takeDelimiter excludes the delimiter, so re-add it or every downstream435            // line-oriented consumer in errors.zig sees one giant concatenated line.436            accumulated.appendSlice(gpa, raw) catch {};437            accumulated.append(gpa, '\n') catch {};438            const line = std.mem.trimEnd(u8, raw, "\r");439            panel.update(line);440            panel.render();441        }442    }443444    errors.setBuildStderr(accumulated.items);445446    const term = child.wait(io) catch |e| {447        errors.error_info.setMessage("nixos-rebuild wait failed", .{});448        return e;449    };450    return switch (term) {451        .exited => |code| code,452        else => 1,453    };454}455456fn nixosRebuildRunStreamed(457    io: std.Io,458    machine: *const types.Machine,459    gpa: std.mem.Allocator,460    verb: []const u8,461    flake: bool,462    panel: *output.BuildPanel,463    extra_flags: []const []const u8,464) !u8 {465    var argv_list: std.ArrayList([]const u8) = .empty;466    defer argv_list.deinit(gpa);467    try argv_list.appendSlice(gpa, &.{ "sudo", "nixos-rebuild", verb });468    if (flake) try argv_list.appendSlice(gpa, &.{ "--flake", machine.config_path });469    try argv_list.appendSlice(gpa, extra_flags);470471    output.flush();472    const built_argv = try buildArgv(gpa, machine, argv_list.items);473    defer if (!machine.local) gpa.free(built_argv);474475    return runStreamedCapture(io, gpa, built_argv, panel);476}477478test "runStreamedCapture preserves newlines and survives an oversized stderr line (NINA-001/002)" {479    const a = std.testing.allocator;480    const io = std.testing.io;481482    var panel: output.BuildPanel = .{};483484    // A single stderr line over 8192 bytes (the reader's fixed buffer size) used to485    // trip error.StreamTooLong and abandon the pipe (NINA-002); it must now be486    // discarded and draining must continue for the lines that follow.487    var oversized: [9000]u8 = undefined;488    @memset(&oversized, 'x');489490    const script = try std.fmt.allocPrint(a,491        \\printf 'these 3 paths will be fetched (12.3 MiB download, 45.6 MiB unpacked)\n'492        \\printf '%s\n' "{s}"493        \\printf 'error: nina test canary xyz-explanation\n'494        \\printf 'For full logs, run some-command\n'495        \\exit 1496    , .{oversized});497    defer a.free(script);498499    const exit_code = try runStreamedCapture(io, a, &.{ "sh", "-c", script }, &panel);500    try std.testing.expectEqual(@as(u8, 1), exit_code);501502    const stderr = errors.getBuildStderr();503    // Newlines must survive accumulation (NINA-001) — without them, every504    // line-oriented consumer downstream (innermostError, extractLocation,505    // extractWarnings) sees one giant concatenated line instead of real lines.506    try std.testing.expect(std.mem.indexOf(u8, stderr, "error: nina test canary xyz-explanation\n") != null);507508    const translated = errors.translateError(a, stderr);509    // Must reach Layer 2's structured extraction (innermostError needs a trimmed510    // line starting with "error:") rather than falling through to the generic511    // Layer-3 fallback, which is only reachable when line structure is lost.512    try std.testing.expect(!std.mem.eql(u8, translated.body, "something went wrong that nina couldn't translate."));513}514515pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {516    return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine), extra_flags);517}518519pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {520    return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine), extra_flags);521}522523// --- Generations ---524525// Read system-profile generations WITHOUT root. `nix-env --list-generations -p526// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user527// ("system.lock: Permission denied"). The generation symlinks themselves are528// world-readable, so list them directly: parse `system-N-link` names, take each529// link's own mtime for the date/time, and mark the one the `system` symlink530// points at as current. Output matches the `nix-env --list-generations` columns531// (num date time [current]) so parseGenerations is unchanged.532const GEN_LIST_SCRIPT =533    \\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 }'534;535536pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {537    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });538    defer gpa.free(r.stderr);539    defer gpa.free(r.stdout);540    if (r.exit_code != 0) return error.ProcessFailed;541    return parseGenerations(gpa, r.stdout);542}543544fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {545    var gens: std.ArrayList(types.GenerationInfo) = .empty;546    var lines = std.mem.splitScalar(u8, output_str, '\n');547    while (lines.next()) |line| {548        const trimmed = std.mem.trim(u8, line, " \t");549        if (trimmed.len == 0) continue;550        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");551        const num_str = parts.next() orelse continue;552        const date_str = parts.next() orelse continue;553        const time_str = parts.next() orelse continue;554        const rest = parts.rest();555        const current = std.mem.indexOf(u8, rest, "current") != null;556        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;557        try gens.append(gpa, .{558            .number = num,559            .date = try gpa.dupe(u8, date_str),560            .time = try gpa.dupe(u8, time_str),561            .current = current,562        });563    }564    return gens.toOwnedSlice(gpa);565}566567pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {568    const gens = try getGenerations(gpa, io, machine);569    defer gpa.free(gens);570    for (gens) |g| {571        if (g.current) return g.number;572    }573    return 0;574}575576pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {577    // Switch the system profile to generation n, then activate it (bootloader +578    // services). Without switch-to-configuration the change isn't applied.579    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 });580    defer gpa.free(cmd);581    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });582}583584pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {585    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });586}587588pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {589    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});590    defer gpa.free(n_str);591    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });592}593594pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {595    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });596}597598// --- Garbage collection ---599600pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {601    if (delete_old) {602        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });603    }604    // Keep the `keep` most recent system generations (+N deletes all but N),605    // then collect now-unreferenced store paths. `--delete-older-than` wants a606    // duration (e.g. 14d), not a generation count.607    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });608    defer gpa.free(cmd);609    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });610}611612// --- Channels ---613614pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {615    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });616    defer gpa.free(r.stderr);617    defer gpa.free(r.stdout);618    if (r.exit_code != 0) return error.ProcessFailed;619    return parseChannels(gpa, r.stdout);620}621622fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {623    var channels: std.ArrayList(types.ChannelInfo) = .empty;624    var lines = std.mem.splitScalar(u8, output_str, '\n');625    while (lines.next()) |line| {626        const trimmed = std.mem.trim(u8, line, " \t\r");627        if (trimmed.len == 0) continue;628        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;629        try channels.append(gpa, .{630            .name = try gpa.dupe(u8, trimmed[0..space]),631            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),632        });633    }634    return channels.toOwnedSlice(gpa);635}636637pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {638    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });639}640641pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {642    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });643}644645pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {646    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });647}648649// --- Services ---650651pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {652    const cmd: []const []const u8 = if (user)653        &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }654    else655        &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };656    const r = try capture(gpa, io, machine, cmd);657    defer gpa.free(r.stderr);658    defer gpa.free(r.stdout);659    if (r.exit_code != 0) return error.ProcessFailed;660    return parseServices(gpa, r.stdout);661}662663fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {664    var svcs: std.ArrayList(types.ServiceInfo) = .empty;665    var lines = std.mem.splitScalar(u8, output_str, '\n');666    while (lines.next()) |line| {667        const trimmed = std.mem.trim(u8, line, " \t\r");668        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines669        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");670        const name = parts.next() orelse continue;671        _ = parts.next(); // load672        const active_str = parts.next() orelse continue;673        const sub_str = parts.next() orelse "unknown";674675        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))676            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)677        else if (std.mem.eql(u8, active_str, "failed"))678            .failed679        else680            .inactive;681682        try svcs.append(gpa, .{683            .name = try gpa.dupe(u8, name),684            .state = state,685            .uptime = null,686        });687    }688    return svcs.toOwnedSlice(gpa);689}690691pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {692    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.693    // User services run under the caller's own systemd manager, so no sudo.694    if (user) {695        return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });696    }697    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });698}699700pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {701    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});702    defer gpa.free(n_str);703    if (user) {704        if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });705        return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });706    }707    if (follow) {708        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });709    }710    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });711}712713// --- Profile ---714715// Stream with one extra environment variable injected alongside the inherited env.716// Used for cases like NIXPKGS_ALLOW_UNFREE=1 where we need a single override717// without replacing the full parent environment.718fn streamWithEnvVar(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8, base_env: *const std.process.Environ.Map, key: []const u8, val: []const u8) !u8 {719    output.flush();720    const argv = try buildArgv(gpa, machine, cmd);721    defer if (!machine.local) gpa.free(argv);722723    var env = try base_env.clone(gpa);724    defer env.deinit();725    try env.put(key, val);726727    var child = std.process.spawn(io, .{728        .argv = argv,729        .stdin = .inherit,730        .stdout = .inherit,731        .stderr = .inherit,732        .environ_map = &env,733    }) catch |e| {734        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});735        return e;736    };737738    const term = child.wait(io) catch |e| {739        errors.error_info.setMessage("process wait failed", .{});740        return e;741    };742743    return switch (term) {744        .exited => |c| c,745        else => 1,746    };747}748749pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, environ: *const std.process.Environ.Map, attr: []const u8, allow_unfree: bool) !u8 {750    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});751    defer gpa.free(pkg_ref);752    // `nix profile add` is the current verb; `install` is a deprecated alias that753    // prints a warning on modern nix.754    if (allow_unfree) {755        // The package is unfree and the user's system-wide allowUnfree setting756        // doesn't propagate to imperative nix commands. Pass NIXPKGS_ALLOW_UNFREE=1757        // and --impure so the profile add succeeds: --impure allows builtins.getEnv758        // to read the env var inside the nixpkgs flake's pure evaluation context.759        return streamWithEnvVar(io, machine, gpa, &.{ "nix", "profile", "add", "--impure", pkg_ref }, environ, "NIXPKGS_ALLOW_UNFREE", "1");760    }761    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });762}763764pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {765    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not766    // by flake ref — passing nixpkgs#ripgrep matches nothing.767    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });768}769770pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {771    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });772    defer gpa.free(r.stderr);773    if (r.exit_code != 0) return error.ProcessFailed;774    return r.stdout;775}776777// Machine-readable profile listing — caller parses elements -> name + version.778pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {779    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });780    defer gpa.free(r.stderr);781    if (r.exit_code != 0) {782        gpa.free(r.stdout);783        return error.ProcessFailed;784    }785    return r.stdout;786}787788// Returns the profile element name to pass to `nix profile remove/upgrade`789// (e.g. "nina" or "default"), or null if nina is not found. Caller owns the790// returned slice. A NixOS system-package install also resolves into /nix/store791// so the store path alone can't distinguish it from a profile install — the792// profile list can. A missing/empty profile (or no nix) returns null.793pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {794    const js = profileListJson(gpa, io, machine) catch return null;795    defer gpa.free(js);796    return profileJsonNinaElement(gpa, js);797}798799800pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {801    const name = profileNinaElement(gpa, io, machine) orelse return false;802    gpa.free(name);803    return true;804}805806// True when a nix store path belongs to the nina package. Store paths have the807// form /nix/store/<32-char-hash>-<pname>-<version>[/<subpath>]. We check that808// the 33 chars after /nix/store/ are the hash+dash, and the pname that follows809// is exactly "nina" (followed by "-" or end-of-component).810fn storePathIsNina(path: []const u8) bool {811    const prefix = "/nix/store/";812    if (!std.mem.startsWith(u8, path, prefix)) return false;813    const rel = path[prefix.len..];814    // The store entry name ends at the first "/" (if any sub-path follows).815    const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];816    if (entry.len < 34) return false; // 32-char hash + dash + at least one char817    const pname_ver = entry[33..]; // skip hash + dash818    return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");819}820821// Pure parse of `nix profile list --json` for a nina element, returning its822// element name (the key to pass to `nix profile remove/upgrade`) or null.823// Newer nix (2.18+) keys elements by pname ("nina"). Older nix uses an array824// with an "attrPath" field. Tarball installs via the `default` output may use825// the key "default" instead of "nina"; we detect those via storePaths.826fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {827    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;828    defer parsed.deinit();829    const root = parsed.value;830    if (root != .object) return null;831    const elements = root.object.get("elements") orelse return null;832    switch (elements) {833        .object => |obj| {834            // Fast path: exact "nina" key (nix 2.18+ with nixpkgs#nina install).835            if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;836            // Fallback: scan storePaths. Handles tarball installs where the default837            // output is selected and nix names the element "default" (older nix) or838            // some other key derived from the attrPath rather than the pname.839            var it = obj.iterator();840            while (it.next()) |kv| {841                const val = kv.value_ptr.*;842                if (val != .object) continue;843                const sps = val.object.get("storePaths") orelse continue;844                if (sps != .array) continue;845                for (sps.array.items) |sp| {846                    if (sp == .string and storePathIsNina(sp.string))847                        return gpa.dupe(u8, kv.key_ptr.*) catch null;848                }849            }850            return null;851        },852        .array => |arr| {853            // Older nix array format. Element name is the last component of attrPath.854            for (arr.items) |el| {855                if (el != .object) continue;856                const ap = el.object.get("attrPath") orelse continue;857                if (ap != .string) continue;858                if (std.mem.eql(u8, ap.string, "nina") or859                    std.mem.endsWith(u8, ap.string, ".nina"))860                    return gpa.dupe(u8, "nina") catch null;861                // Tarball default-output install: attrPath ends in ".default" but862                // storePaths point to nina. Return "default" as the element name.863                const sps = el.object.get("storePaths") orelse continue;864                if (sps != .array) continue;865                for (sps.array.items) |sp| {866                    if (sp != .string) continue;867                    if (!storePathIsNina(sp.string)) continue;868                    const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;869                    const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;870                    return gpa.dupe(u8, el_name) catch null;871                }872            }873            return null;874        },875        else => return null,876    }877}878879test "profileJsonNinaElement finds element name from profile JSON" {880    const a = std.testing.allocator;881882    // Newer nix: elements keyed by pname. "nina" key present.883    const named =884        \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},885        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}886    ;887    const r1 = profileJsonNinaElement(a, named);888    defer if (r1) |n| a.free(n);889    try std.testing.expectEqualStrings("nina", r1.?);890891    // Tarball install via default output: element keyed as "default", storePath is nina.892    const default_key =893        \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}894    ;895    const r2 = profileJsonNinaElement(a, default_key);896    defer if (r2) |n| a.free(n);897    try std.testing.expectEqualStrings("default", r2.?);898899    // Decoy: storePath of another package contains "nina" as a substring but is not nina.900    const decoy =901        \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}902    ;903    const r3 = profileJsonNinaElement(a, decoy);904    try std.testing.expectEqual(@as(?[]const u8, null), r3);905906    // Older nix array schema, attrPath ending in ".nina".907    const arr =908        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}909    ;910    const r4 = profileJsonNinaElement(a, arr);911    defer if (r4) |n| a.free(n);912    try std.testing.expectEqualStrings("nina", r4.?);913914    // Older nix array schema, tarball default-output install.915    const arr_default =916        \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}917    ;918    const r5 = profileJsonNinaElement(a, arr_default);919    defer if (r5) |n| a.free(n);920    try std.testing.expectEqualStrings("default", r5.?);921922    // Empty / malformed → null.923    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));924    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));925}926927// The store paths that make up the running system environment. Each reference is928// a <hash>-<name>-<version> path, so the caller can list system packages with929// versions — there is no cleaner per-package list for environment.systemPackages.930pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {931    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });932    defer gpa.free(r.stderr);933    if (r.exit_code != 0) {934        gpa.free(r.stdout);935        return error.ProcessFailed;936    }937    return r.stdout;938}939940pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {941    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });942}943944// --- Store ---945946pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {947    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });948}949950pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {951    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });952}953954// Deduplicate identical store files via hard links — frees space without955// garbage-collecting any paths.956pub fn storeOptimise(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {957    return stream(io, machine, gpa, &.{ "nix", "store", "optimise" });958}959960pub const SystemStatus = struct { size: []u8, age: []u8 };961962// One read-only pass for `nina status`: the current system's closure size (a963// single `path-info -S` of /run/current-system — fast, unlike -S over the whole964// store) and seconds since the system profile was last switched (its symlink965// mtime). Both are world-readable; no root needed.966const STATUS_SCRIPT =967    \\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} ))"968;969970pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {971    const unknown = SystemStatus{972        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },973        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },974    };975    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;976    defer gpa.free(r.stdout);977    defer gpa.free(r.stderr);978    if (r.exit_code != 0) return unknown;979980    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");981    const sz_str = it.next() orelse return unknown;982    const age_str = it.next() orelse return unknown;983    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;984    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;985986    gpa.free(unknown.size);987    gpa.free(unknown.age);988    return .{989        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),990        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),991    };992}993994// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A995// one-word health signal; exits non-zero when degraded, so we read stdout, not996// the code. Caller owns the returned slice.997pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {998    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch999        return gpa.dupe(u8, "unknown");1000    defer gpa.free(r.stderr);1001    const state = std.mem.trim(u8, r.stdout, " \t\n\r");1002    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");1003    gpa.free(r.stdout);1004    return owned;1005}10061007fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {1008    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});1009    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});1010    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});1011    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});1012}10131014pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1015    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });1016}10171018pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {1019    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)1020    // graph work that takes minutes on a real store (59k+ paths) and hangs the1021    // command. We don't need closures: `--all --json` (no -S) carries each path's1022    // own narSize, so one fast pass gives the path count and the summed store size.1023    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.1024    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.1025    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });1026    defer gpa.free(pi.stdout);1027    defer gpa.free(pi.stderr);10281029    const scan = scanStoreJson(pi.stdout);1030    const total_owned = try humanSize(gpa, scan.total_bytes);10311032    return .{1033        .total_size = total_owned,1034        .live_paths = scan.count,1035        .reclaimable_paths = 0,1036    };1037}10381039const StoreScan = struct { count: u64, total_bytes: u64 };10401041// One linear pass over `nix path-info --json`: each path object has exactly one1042// "narSize": field, so counting them gives the true path count and summing the1043// values gives the total store size — no per-path closure walk.1044fn scanStoreJson(json_str: []const u8) StoreScan {1045    const needle = "\"narSize\":";1046    var count: u64 = 0;1047    var total: u64 = 0;1048    var i: usize = 0;1049    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {1050        var j = pos + needle.len;1051        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}1052        var val: u64 = 0;1053        var any = false;1054        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {1055            val = val * 10 + (json_str[j] - '0');1056            any = true;1057        }1058        if (any) {1059            count += 1;1060            total += val;1061        }1062        i = j;1063    }1064    return .{ .count = count, .total_bytes = total };1065}10661067fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1068    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };1069    var val: f64 = @floatFromInt(bytes);1070    var unit: usize = 0;1071    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1072    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1073    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1074}10751076pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {1077    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the1078    // flake registry), not a flake in the current directory.1079    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});1080    defer gpa.free(expr);1081    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });1082    defer gpa.free(r.stderr);1083    if (r.exit_code != 0) {1084        gpa.free(r.stdout);1085        return error.ProcessFailed;1086    }1087    return r.stdout;1088}10891090// --- Flake ---10911092pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8, extra_flags: []const []const u8) !u8 {1093    var argv: std.ArrayList([]const u8) = .empty;1094    defer argv.deinit(gpa);1095    try argv.appendSlice(gpa, &.{ "nix", "flake", "update" });1096    if (input) |inp| try argv.append(gpa, inp);1097    try argv.appendSlice(gpa, extra_flags);1098    return stream(io, machine, gpa, argv.items);1099}11001101// Update flake inputs for the flake living in `dir` (the config dir). `nix flake1102// update` operates on the flake in the working directory, so we cd there first.1103// Used by `nina upgrade` on a flake system in place of nix-channel --update.1104pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {1105    return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });1106}11071108pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {1109    var argv: std.ArrayList([]const u8) = .empty;1110    defer argv.deinit(gpa);1111    try argv.appendSlice(gpa, &.{ "nix", "flake", "check" });1112    try argv.appendSlice(gpa, extra_flags);1113    return stream(io, machine, gpa, argv.items);1114}11151116pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1117    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });1118}11191120pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1121    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });1122}11231124pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {1125    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });1126}11271128pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1129    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });1130    defer gpa.free(r.stderr);1131    if (r.exit_code != 0) {1132        gpa.free(r.stdout);1133        return error.ProcessFailed;1134    }1135    return r.stdout;1136}11371138// --- Build / Run / Develop ---11391140pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8, extra_flags: []const []const u8) !u8 {1141    var argv: std.ArrayList([]const u8) = .empty;1142    defer argv.deinit(gpa);1143    try argv.append(gpa, "nix");1144    try argv.append(gpa, "build");1145    var ref_buf: ?[]u8 = null;1146    defer if (ref_buf) |r| gpa.free(r);1147    if (attr) |a| {1148        ref_buf = try std.fmt.allocPrint(gpa, ".#{s}", .{a});1149        try argv.append(gpa, ref_buf.?);1150    }1151    try argv.appendSlice(gpa, extra_flags);1152    return stream(io, machine, gpa, argv.items);1153}11541155pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, extra_flags: []const []const u8) !u8 {1156    // nix run always gets --no-write-lock-file for remote URLs1157    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");11581159    var argv: std.ArrayList([]const u8) = .empty;1160    defer argv.deinit(gpa);1161    try argv.append(gpa, "nix");1162    try argv.append(gpa, "run");11631164    var ref_buf: ?[]u8 = null;1165    defer if (ref_buf) |r| gpa.free(r);1166    if (is_url) {1167        try argv.append(gpa, pkg);1168        try argv.append(gpa, "--no-write-lock-file");1169    } else if (std.mem.indexOfScalar(u8, pkg, '#') != null) {1170        // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.1171        try argv.append(gpa, pkg);1172    } else {1173        ref_buf = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1174        try argv.append(gpa, ref_buf.?);1175    }11761177    // extra_flags carries any `-- <program args>` separator verbatim, so this1178    // naturally reconstructs `nix run <ref> -- <args>` — nix's own convention.1179    try argv.appendSlice(gpa, extra_flags);1180    return stream(io, machine, gpa, argv.items);1181}11821183pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1184    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1185    defer gpa.free(ref);1186    return stream(io, machine, gpa, &.{ "nix", "shell", ref });1187}11881189pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {1190    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1191    defer gpa.free(ref);1192    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});1193    defer gpa.free(ps1);1194    if (machine.local) {1195        const rc_path = try createInteractiveShellRc(gpa, io);1196        defer {1197            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1198            gpa.free(rc_path);1199        }1200        return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref, "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, ps1);1201    }1202    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);1203}12041205pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8, extra_flags: []const []const u8) !u8 {1206    if (run_cmd) |cmd| {1207        // sh -c so a multi-word command isn't treated as a single executable name.1208        var argv: std.ArrayList([]const u8) = .empty;1209        defer argv.deinit(gpa);1210        try argv.appendSlice(gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1211        try argv.appendSlice(gpa, extra_flags);1212        return stream(io, machine, gpa, argv.items);1213    }1214    var argv: std.ArrayList([]const u8) = .empty;1215    defer argv.deinit(gpa);1216    try argv.append(gpa, "nix");1217    try argv.append(gpa, "develop");1218    try argv.appendSlice(gpa, extra_flags);1219    return stream(io, machine, gpa, argv.items);1220}12211222pub fn nixDevelopPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8, base_env: *const std.process.Environ.Map, extra_flags: []const []const u8) !u8 {1223    if (run_cmd) |cmd| {1224        // sh -c so a multi-word command isn't treated as a single executable name.1225        var argv: std.ArrayList([]const u8) = .empty;1226        defer argv.deinit(gpa);1227        try argv.appendSlice(gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1228        try argv.appendSlice(gpa, extra_flags);1229        return stream(io, machine, gpa, argv.items);1230    }1231    if (machine.local) {1232        const rc_path = try createInteractiveShellRc(gpa, io);1233        defer {1234            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1235            gpa.free(rc_path);1236        }1237        var argv: std.ArrayList([]const u8) = .empty;1238        defer argv.deinit(gpa);1239        try argv.append(gpa, "nix");1240        try argv.append(gpa, "develop");1241        try argv.appendSlice(gpa, extra_flags);1242        try argv.appendSlice(gpa, &.{ "--command", "bash", "--rcfile", rc_path, "-i" });1243        return streamEnv(io, machine, gpa, argv.items, base_env, "(nina: dev) -> ");1244    }1245    var argv: std.ArrayList([]const u8) = .empty;1246    defer argv.deinit(gpa);1247    try argv.append(gpa, "nix");1248    try argv.append(gpa, "develop");1249    try argv.appendSlice(gpa, extra_flags);1250    return streamEnv(io, machine, gpa, argv.items, base_env, "(nina: dev) -> ");1251}12521253pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1254    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });1255}12561257// --- Format ---12581259pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {1260    if (check) {1261        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });1262    }1263    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });1264}12651266// --- Info ---12671268pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1269    const r = try capture(gpa, io, machine, &.{"nixos-version"});1270    defer gpa.free(r.stderr);1271    if (r.exit_code != 0) {1272        gpa.free(r.stdout);1273        return error.ProcessFailed;1274    }1275    return r.stdout;1276}12771278pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1279    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });1280    defer gpa.free(r.stderr);1281    if (r.exit_code != 0) {1282        gpa.free(r.stdout);1283        return error.ProcessFailed;1284    }1285    return r.stdout;1286}12871288pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1289    const r = try capture(gpa, io, machine, &.{"uptime"});1290    defer gpa.free(r.stderr);1291    if (r.exit_code != 0) {1292        gpa.free(r.stdout);1293        return error.ProcessFailed;1294    }1295    return r.stdout;1296}12971298// --- Boot ---12991300pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {1301    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });1302    defer gpa.free(r.stderr);1303    defer gpa.free(r.stdout);1304    if (r.exit_code != 0) return error.ProcessFailed;1305    return parseBootEntries(gpa, r.stdout);1306}13071308fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {1309    var entries: std.ArrayList(types.BootEntry) = .empty;1310    var lines = std.mem.splitScalar(u8, output_str, '\n');1311    while (lines.next()) |line| {1312        const trimmed = std.mem.trim(u8, line, " \t\r");1313        if (std.mem.startsWith(u8, trimmed, "title:")) {1314            const title = std.mem.trim(u8, trimmed[6..], " \t");1315            const current = std.mem.indexOf(u8, title, "(current)") != null;1316            try entries.append(gpa, .{1317                .title = try gpa.dupe(u8, title),1318                .current = current,1319            });1320        }1321    }1322    return entries.toOwnedSlice(gpa);1323}13241325// --- Pkg info ---13261327fn pkgInstallable(gpa: std.mem.Allocator, pkg: []const u8) ![]u8 {1328    return std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1329}13301331fn resolvePkgStorePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, installable: []const u8) ![]u8 {1332    const r = try capture(gpa, io, machine, &.{ "nix", "build", "--no-link", "--print-out-paths", installable });1333    defer gpa.free(r.stderr);1334    defer gpa.free(r.stdout);1335    if (r.exit_code != 0) return error.PackageNotFound;13361337    var lines = std.mem.tokenizeAny(u8, r.stdout, "\r\n");1338    const first_path = lines.next() orelse return error.PackageNotFound;1339    const store_path = std.mem.trim(u8, first_path, " \t");1340    if (store_path.len == 0) return error.PackageNotFound;1341    return gpa.dupe(u8, store_path);1342}13431344pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1345    const installable = try pkgInstallable(gpa, pkg);1346    defer gpa.free(installable);1347    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1348    defer gpa.free(store_path);1349    return stream(io, machine, gpa, &.{ "nix", "why-depends", "/run/current-system", store_path });1350}13511352pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1353    const installable = try pkgInstallable(gpa, pkg);1354    defer gpa.free(installable);1355    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1356    defer gpa.free(store_path);1357    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", store_path });1358}13591360pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {1361    const installable = try pkgInstallable(gpa, pkg);1362    defer gpa.free(installable);1363    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", "--json", installable });1364    defer gpa.free(r.stderr);1365    defer gpa.free(r.stdout);1366    if (r.exit_code != 0) return error.ProcessFailed;13671368    const nar_size = try pathInfoNarSize(gpa, r.stdout);1369    return humanPkgSize(gpa, nar_size);1370}13711372pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1373    const installable = try pkgInstallable(gpa, pkg);1374    defer gpa.free(installable);1375    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1376    defer gpa.free(store_path);1377    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", store_path });1378}13791380fn pathInfoNarSize(gpa: std.mem.Allocator, json_str: []const u8) !u64 {1381    var parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.ProcessFailed;1382    defer parsed.deinit();1383    switch (parsed.value) {1384        .object => |obj| {1385            var it = obj.iterator();1386            while (it.next()) |entry| {1387                if (entry.value_ptr.* == .object) {1388                    if (entry.value_ptr.object.get("narSize")) |v| {1389                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1390                    }1391                }1392            }1393        },1394        .array => |arr| {1395            for (arr.items) |item| {1396                if (item == .object) {1397                    if (item.object.get("narSize")) |v| {1398                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1399                    }1400                }1401            }1402        },1403        else => {},1404    }1405    return error.ProcessFailed;1406}14071408fn humanPkgSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1409    const units = [_][]const u8{ "B", "KiB", "MiB", "GiB", "TiB" };1410    var val: f64 = @floatFromInt(bytes);1411    var unit: usize = 0;1412    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1413    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1414    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1415}14161417test "pathInfoNarSize parses object and array shapes" {1418    try std.testing.expectEqual(@as(u64, 1064629862), try pathInfoNarSize(std.testing.allocator,1419        \\{"/nix/store/abc-ffmpeg":{"narSize":1064629862}}1420    ));1421    try std.testing.expectEqual(@as(u64, 2048), try pathInfoNarSize(std.testing.allocator,1422        \\[{"path":"/nix/store/abc-pkg","narSize":2048}]1423    ));1424}14251426// --- Hash / Fetch ---14271428pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {1429    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });1430    defer gpa.free(r.stderr);1431    if (r.exit_code != 0) {1432        gpa.free(r.stdout);1433        return error.ProcessFailed;1434    }1435    return r.stdout;1436}14371438pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {1439    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });1440    defer gpa.free(r.stderr);1441    if (r.exit_code != 0) {1442        gpa.free(r.stdout);1443        return error.ProcessFailed;1444    }1445    return r.stdout;1446}14471448// --- Pin ---14491450pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {1451    // Stub: full implementation would parse and edit flake.lock JSON1452    // The pin/unpin flow works via nix flake update which regenerates flake.lock1453}14541455pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {1456    if (line) |l| {1457        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});1458        defer gpa.free(line_arg);1459        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });1460    }1461    return stream(io, &types.Machine{}, gpa, &.{ editor, path });1462}14631464// Open a config directory as root with `sudo -E <editor> <path>` — `-E`1465// preserves the user's environment (PATH, TERM, EDITOR config) so the editor1466// behaves the same as it does unprivileged. Used by `nina edit --dir`.1467pub fn openEditorSudo(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8) !u8 {1468    return stream(io, &types.Machine{}, gpa, &.{ "sudo", "-E", editor, path });1469}14701471pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {1472    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});1473    defer gpa.free(a_str);1474    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});1475    defer gpa.free(b_str);1476    // On a tty, the child's own color is fine — stream it directly.1477    if (output.colorEnabled()) {1478        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });1479    }1480    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,1481    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.1482    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });1483    defer gpa.free(r.stdout);1484    defer gpa.free(r.stderr);1485    const cleaned = try stripAnsi(gpa, r.stdout);1486    defer gpa.free(cleaned);1487    output.raw(cleaned);1488    return r.exit_code;1489}14901491// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a1492// child process's color when it writes ANSI unconditionally.1493fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1494    var out: std.ArrayList(u8) = .empty;1495    errdefer out.deinit(gpa);1496    var i: usize = 0;1497    while (i < input.len) {1498        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1499            i += 2;1500            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1501            if (i < input.len) i += 1; // consume the final byte1502            continue;1503        }1504        try out.append(gpa, input[i]);1505        i += 1;1506    }1507    return out.toOwnedSlice(gpa);1508}15091510test "stripAnsi removes CSI color sequences" {1511    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1512    defer std.testing.allocator.free(cleaned);1513    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1514}15151516// --- Doctor checks ---15171518pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1519    var checks: std.ArrayList(types.DoctorCheck) = .empty;15201521    // Check nix daemon1522    {1523        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1524        defer gpa.free(r.stdout);1525        defer gpa.free(r.stderr);1526        const active = std.mem.indexOf(u8, r.stdout, "active") != null;1527        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1528    }15291530    // Check config syntax. Flake-aware like apply/upgrade: on a flake system a1531    // plain `nixos-rebuild dry-build` evaluates <nixpkgs/nixos> + <nixos-config>1532    // (channel style) and fails, so pass --flake when the config dir has one.1533    {1534        const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1535            &.{ "sudo", "nixos-rebuild", "dry-build", "--flake", machine.config_path }1536        else1537            &.{ "sudo", "nixos-rebuild", "dry-build" };1538        const r = try capture(gpa, io, machine, argv);1539        defer gpa.free(r.stdout);1540        defer gpa.free(r.stderr);1541        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1542    }15431544    // Check channel1545    {1546        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1547        defer gpa.free(r.stdout);1548        defer gpa.free(r.stderr);1549        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1550        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1551    }15521553    return checks.toOwnedSlice(gpa);1554}15551556// --- Home Manager ---1557//1558// Home Manager has three usage modes. nina detects which one is in play before1559// any `home` command so it can either drive the standalone CLI or redirect the1560// user to `nina apply` (when HM is a NixOS/flake module activated by rebuild).15611562pub const HomeManagerMode = enum {1563    // home-manager binary on PATH — manages the user env on its own.1564    standalone,1565    // No binary, but a home.nix exists — HM is a NixOS/flake module rebuilt by1566    // nixos-rebuild. `nina home apply` redirects to `nina apply`.1567    module,1568    none,1569};15701571fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1572    const home = environ.get("HOME") orelse return null;1573    return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1574}15751576// Path to the standalone home.nix. Caller frees.1577pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1578    const dir = homeConfigDir(gpa, environ) orelse return null;1579    defer gpa.free(dir);1580    return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1581}15821583pub fn pathExists(io: std.Io, path: []const u8) bool {1584    const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1585    f.close(io);1586    return true;1587}15881589// `command -v <name>` — true if the binary resolves on PATH. Silent (captured),1590// unlike streamLocal which would inherit stdio.1591fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1592    var buf: [256]u8 = undefined;1593    const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1594    const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1595    defer gpa.free(r.stdout);1596    defer gpa.free(r.stderr);1597    return switch (r.term) {1598        .exited => |code| code == 0,1599        else => false,1600    };1601}16021603pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1604    if (commandExists(gpa, io, "home-manager")) return .standalone;1605    if (homeNixPath(gpa, environ)) |p| {1606        defer gpa.free(p);1607        if (pathExists(io, p)) return .module;1608    }1609    return .none;1610}16111612// The home-manager config dir when it holds a flake.nix (a flake-based home1613// config that `home-manager switch --flake` drives). null for a channel-based1614// config, which uses a plain `home-manager switch`. Caller frees.1615pub fn homeFlakeDir(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1616    const dir = homeConfigDir(gpa, environ) orelse return null;1617    const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch {1618        gpa.free(dir);1619        return null;1620    };1621    defer gpa.free(flake);1622    if (!pathExists(io, flake)) {1623        gpa.free(dir);1624        return null;1625    }1626    return dir;1627}16281629// Platform-specific home-manager attribute "<user>-<arch>-<os>" (e.g.1630// murazaki-x86_64-linux) — the homeConfigurations key many flakes derive from1631// ${USER}-${system}. arch/os come from uname on the local host (home commands1632// are local-only). Caller frees.1633pub fn homeManagerAttr(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, environ: *const std.process.Environ.Map) ![]const u8 {1634    const user = environ.get("USER") orelse "user";16351636    const arch_r = try capture(gpa, io, machine, &.{ "uname", "-m" });1637    defer gpa.free(arch_r.stdout);1638    defer gpa.free(arch_r.stderr);1639    if (arch_r.exit_code != 0) return error.ProcessFailed;1640    const arch = std.mem.trim(u8, arch_r.stdout, " \t\r\n");16411642    const os_r = try capture(gpa, io, machine, &.{ "uname", "-s" });1643    defer gpa.free(os_r.stdout);1644    defer gpa.free(os_r.stderr);1645    if (os_r.exit_code != 0) return error.ProcessFailed;1646    const os = try gpa.dupe(u8, std.mem.trim(u8, os_r.stdout, " \t\r\n"));1647    defer gpa.free(os);1648    for (os) |*ch| ch.* = std.ascii.toLower(ch.*);16491650    if (arch.len == 0 or os.len == 0) return error.ProcessFailed;1651    return std.fmt.allocPrint(gpa, "{s}-{s}-{s}", .{ user, arch, os });1652}16531654// Map a nixos-version string to the matching home-manager branch: an unstable1655// channel ("…pre…"/"unstable") → master; a stable release like1656// "25.05.20250115.abcdef (Warbler)" → release-25.05. Anything unparseable1657// falls back to master. Caller frees.1658fn homeBranchFromVersion(gpa: std.mem.Allocator, version_raw: []const u8) ![]const u8 {1659    const v = std.mem.trim(u8, version_raw, " \t\r\n");1660    if (std.mem.indexOf(u8, v, "pre") != null or1661        std.mem.indexOf(u8, v, "unstable") != null)1662        return gpa.dupe(u8, "master");16631664    const head = v[0 .. std.mem.indexOfScalar(u8, v, ' ') orelse v.len];1665    var it = std.mem.splitScalar(u8, head, '.');1666    const major = it.next() orelse "";1667    const minor = it.next() orelse "";1668    if (allDigits(major) and allDigits(minor))1669        return std.fmt.allocPrint(gpa, "release-{s}.{s}", .{ major, minor });16701671    return gpa.dupe(u8, "master");1672}16731674fn allDigits(s: []const u8) bool {1675    if (s.len == 0) return false;1676    for (s) |ch| if (!std.ascii.isDigit(ch)) return false;1677    return true;1678}16791680test "homeBranchFromVersion maps channels to HM branches" {1681    const a = std.testing.allocator;1682    const cases = [_]struct { in: []const u8, want: []const u8 }{1683        .{ .in = "25.05.20250115.abcdef (Warbler)", .want = "release-25.05" },1684        .{ .in = "24.11.20241201.deadbee (Vicuna)", .want = "release-24.11" },1685        .{ .in = "25.11pre-git", .want = "master" },1686        .{ .in = "25.05pre789012.abcdef (Warbler)", .want = "master" },1687        .{ .in = "nixos-unstable", .want = "master" },1688        .{ .in = "garbage", .want = "master" },1689    };1690    for (cases) |c| {1691        const got = try homeBranchFromVersion(a, c.in);1692        defer a.free(got);1693        try std.testing.expectEqualStrings(c.want, got);1694    }1695}16961697// The home-manager branch matching the running nixpkgs. Falls back to master1698// when nixos-version is unavailable (non-NixOS host). Caller frees.1699fn detectHomeManagerBranch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]const u8 {1700    const r = capture(gpa, io, machine, &.{"nixos-version"}) catch1701        return gpa.dupe(u8, "master");1702    defer gpa.free(r.stdout);1703    defer gpa.free(r.stderr);1704    if (r.exit_code != 0) return gpa.dupe(u8, "master");1705    return homeBranchFromVersion(gpa, r.stdout);1706}17071708// `nix run home-manager/<branch> -- init [--switch] [dir]` — generates1709// flake.nix + home.nix (in dir, or ~/.config/home-manager by default),1710// activating immediately when switch_on_init is set.1711pub fn homeManagerInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, switch_on_init: bool, dir: ?[]const u8) !u8 {1712    const branch = try detectHomeManagerBranch(gpa, io, machine);1713    defer gpa.free(branch);1714    const flake_ref = try std.fmt.allocPrint(gpa, "home-manager/{s}", .{branch});1715    defer gpa.free(flake_ref);17161717    var argv: std.ArrayList([]const u8) = .empty;1718    defer argv.deinit(gpa);1719    try argv.appendSlice(gpa, &.{ "nix", "run", flake_ref, "--", "init" });1720    if (switch_on_init) try argv.append(gpa, "--switch");1721    if (dir) |d| try argv.append(gpa, d);17221723    return stream(io, machine, gpa, argv.items);1724}17251726pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {1727    output.flush();1728    var argv: std.ArrayList([]const u8) = .empty;1729    defer argv.deinit(gpa);1730    try argv.appendSlice(gpa, &.{ "home-manager", "switch" });1731    try argv.appendSlice(gpa, extra_flags);1732    const r = try capture(gpa, io, machine, argv.items);1733    defer gpa.free(r.stdout);1734    defer gpa.free(r.stderr);1735    errors.setBuildStderr(r.stderr);1736    return r.exit_code;1737}17381739// Outcome of a flake-based switch, so the caller can fall back to a less1740// specific attribute on a missing-attribute evaluation error — but never on a1741// genuine build failure.1742pub const SwitchOutcome = enum { ok, attr_missing, failed };17431744pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8, extra_flags: []const []const u8) !SwitchOutcome {1745    output.flush();1746    var argv: std.ArrayList([]const u8) = .empty;1747    defer argv.deinit(gpa);1748    try argv.appendSlice(gpa, &.{ "home-manager", "switch", "--flake", flake_ref });1749    try argv.appendSlice(gpa, extra_flags);1750    const r = try capture(gpa, io, machine, argv.items);1751    defer gpa.free(r.stdout);1752    defer gpa.free(r.stderr);1753    if (r.exit_code == 0) return .ok;1754    // A flake that doesn't define this homeConfiguration fails during evaluation1755    // with "does not provide attribute" — surface that so the caller can retry a1756    // different attr rather than treating it as a build failure.1757    if (std.mem.indexOf(u8, r.stderr, "does not provide attribute") != null)1758        return .attr_missing;1759    errors.setBuildStderr(r.stderr);1760    return .failed;1761}17621763// home-manager has no system-profile rollback; it re-activates the previous1764// generation via `switch --rollback`.1765pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1766    output.flush();1767    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch", "--rollback" });1768    defer gpa.free(r.stdout);1769    defer gpa.free(r.stderr);1770    errors.setBuildStderr(r.stderr);1771    return r.exit_code;1772}17731774// Build (and validate) the home config without activating it — used by `home1775// check` and `home apply --dry`. `home-manager build` drops a ./result symlink1776// in the cwd, so run it in a throwaway temp dir to avoid littering the directory1777// nina was invoked from.1778pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {1779    output.flush();1780    // extra_flags are passed as real argv elements after the literal `--`, picked1781    // up via "$@" — never interpolated into the script text, so an extra flag1782    // can't smuggle shell metacharacters into the command.1783    var argv: std.ArrayList([]const u8) = .empty;1784    defer argv.deinit(gpa);1785    try argv.appendSlice(gpa, &.{ "sh", "-c", "d=$(mktemp -d) && cd \"$d\" && home-manager build \"$@\"", "--" });1786    try argv.appendSlice(gpa, extra_flags);1787    const r = try capture(gpa, io, machine, argv.items);1788    defer gpa.free(r.stdout);1789    defer gpa.free(r.stderr);1790    errors.setBuildStderr(r.stderr);1791    return r.exit_code;1792}17931794pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1795    const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1796    defer gpa.free(r.stderr);1797    if (r.exit_code != 0) {1798        gpa.free(r.stdout);1799        return error.ProcessFailed;1800    }1801    return r.stdout;1802}18031804// Store paths referenced by a home generation — used to list managed packages.1805pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1806    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1807    defer gpa.free(r.stderr);1808    if (r.exit_code != 0) {1809        gpa.free(r.stdout);1810        return error.ProcessFailed;1811    }1812    return r.stdout;1813}18141815// diff-closures between two arbitrary store paths (home generations), mirroring1816// diffClosures' tty/piped color handling.1817pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1818    if (output.colorEnabled()) {1819        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1820    }1821    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1822    defer gpa.free(r.stdout);1823    defer gpa.free(r.stderr);1824    const cleaned = try stripAnsi(gpa, r.stdout);1825    defer gpa.free(cleaned);1826    output.raw(cleaned);1827    return r.exit_code;1828}18291830// --- Log ---18311832pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1833    const home = environ.get("HOME") orelse return error.FileNotFound;1834    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1835    defer gpa.free(path);1836    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1837    if (last == 0) return content;18381839    // Collect non-empty lines, then keep only the final `last`. Slices point into1840    // `content`, so copy them out before freeing it.1841    var lines: std.ArrayList([]const u8) = .empty;1842    defer lines.deinit(gpa);1843    var it = std.mem.splitScalar(u8, content, '\n');1844    while (it.next()) |line| {1845        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1846        try lines.append(gpa, line);1847    }1848    if (lines.items.len <= last) return content;18491850    var out: std.ArrayList(u8) = .empty;1851    errdefer out.deinit(gpa);1852    for (lines.items[lines.items.len - last ..]) |line| {1853        try out.appendSlice(gpa, line);1854        try out.append(gpa, '\n');1855    }1856    gpa.free(content);1857    return out.toOwnedSlice(gpa);1858}18591860// nina is a one-shot process, so "did the last apply fail this session?" can't1861// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1862// other ~/.nina-* state files. This lets a later successful apply earn the1863// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1864pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1865    const home = environ.get("HOME") orelse return;1866    var buf: [512]u8 = undefined;1867    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1868    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1869    file.close(io);1870}18711872pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1873    const home = environ.get("HOME") orelse return false;1874    var buf: [512]u8 = undefined;1875    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1876    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1877        f.close(io);1878        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1879        return true;1880    } else |_| {1881        return false;1882    }1883}18841885pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1886    const home = environ.get("HOME") orelse return;1887    var path_buf: [512]u8 = undefined;1888    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1889    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1890        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1891    defer file.close(io);1892    const size = file.length(io) catch 0;1893    file.writePositionalAll(io, entry, size) catch {};1894}18951896// --- Update helpers ---18971898// Fetch a URL with curl and return the response body. Caller must free.1899// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.1900pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1901    const argv = [_][]const u8{1902        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1903    };1904    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1905    defer gpa.free(result.stderr);19061907    const marker = "\nHTTP_STATUS:";1908    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1909        gpa.free(result.stdout);1910        return error.NetworkError;1911    };1912    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1913    const status = std.fmt.parseInt(u16, status_str, 10) catch {1914        gpa.free(result.stdout);1915        return error.NetworkError;1916    };1917    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1918    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1919    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1920        gpa.free(result.stdout);1921        return e;1922    };1923    gpa.free(result.stdout);1924    return body;1925}19261927// Download a URL to a temp file. Returns the temp path (caller must gpa.free).1928// The file is written to /tmp/nina-update-<pid> and left for the caller to use.1929pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1930    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1931    errdefer gpa.free(tmp_path);19321933    var child = std.process.spawn(io, .{1934        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1935        .stdin = .close,1936        .stdout = .close,1937        .stderr = .inherit,1938    }) catch return error.NetworkError;1939    const term = child.wait(io) catch return error.NetworkError;1940    switch (term) {1941        .exited => |c| if (c != 0) return error.NetworkError,1942        else => return error.NetworkError,1943    }1944    return tmp_path;1945}19461947// Get the current executable path into buf. Returns slice of buf.1948pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1949    const len = try std.process.executablePath(io, buf);1950    return buf[0..len];1951}19521953// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1954// atomically install the binary to install_path. Errors: ChecksumMismatch,1955// AccessDenied (with error_info set), or underlying I/O errors.1956pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1957    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1958        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1959        return error.FileNotFound;1960    };1961    defer gpa.free(bytes);19621963    var hasher = std.crypto.hash.Blake3.init(.{});1964    hasher.update(bytes);1965    var raw: [32]u8 = undefined;1966    hasher.final(&raw);1967    const hex = std.fmt.bytesToHex(raw, .lower);1968    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;19691970    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1971    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1972        return error.NameTooLong;19731974    {1975        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1976            errors.error_info.setMessage("cannot write to {s}", .{install_path});1977            errors.error_info.setSuggestion("try: sudo nina update", .{});1978            return error.AccessDenied;1979        };1980        defer f.close(io);1981        f.writePositionalAll(io, bytes, 0) catch {1982            errors.error_info.setMessage("cannot write to {s}", .{install_path});1983            return error.AccessDenied;1984        };1985        try f.setPermissions(io, .fromMode(0o755));1986    }1987    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};19881989    if (comptime builtin.os.tag == .macos) {1990        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1991    }19921993    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1994        error.AccessDenied => {1995            errors.error_info.setMessage("cannot replace {s}", .{install_path});1996            errors.error_info.setSuggestion("try: sudo nina update", .{});1997            return error.AccessDenied;1998        },1999        else => return e,2000    };2001}20022003// --- Nix feature setup ---20042005pub const NixFeatureStatus = struct {2006    nix_command: bool = false,2007    flakes: bool = false,20082009    pub fn allEnabled(self: NixFeatureStatus) bool {2010        return self.nix_command and self.flakes;2011    }2012};20132014fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {2015    var lines = std.mem.splitScalar(u8, conf, '\n');2016    while (lines.next()) |line| {2017        const trimmed = std.mem.trim(u8, line, " \t");2018        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;2019        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;2020        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;2021    }2022}20232024pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {2025    var status = NixFeatureStatus{};20262027    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {2028        defer gpa.free(conf);2029        scanConfFeatures(conf, &status);2030    }20312032    if (environ.get("HOME")) |home| {2033        var buf: [512]u8 = undefined;2034        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;2035        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {2036            defer gpa.free(conf);2037            scanConfFeatures(conf, &status);2038        }2039    }20402041    return status;2042}20432044pub fn isNixOS(io: std.Io) bool {2045    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;2046    file.close(io);2047    return true;2048}20492050// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.2051// Returns the path written (caller must free).2052pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {2053    const home = environ.get("HOME") orelse {2054        errors.error_info.setMessage("HOME not set", .{});2055        return error.ConfigNotFound;2056    };20572058    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});2059    defer gpa.free(dir_path);2060    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});2061    errdefer gpa.free(file_path);20622063    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};20642065    const line = "experimental-features = nix-command flakes\n";2066    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch2067        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {2068        errors.error_info.setMessage("could not write {s}", .{file_path});2069        return error.FileNotFound;2070    });2071    defer file.close(io);20722073    const size = file.length(io) catch 0;2074    file.writePositionalAll(io, line, size) catch {2075        errors.error_info.setMessage("could not write {s}", .{file_path});2076        return error.FileNotFound;2077    };20782079    return file_path;2080}20812082// --- NixOS: declarative experimental-features ---2083//2084// On NixOS the permanent, declarative home for these flags is configuration.nix,2085// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves2086// the `nixos-rebuild switch` to the user.20872088pub const NIXOS_FEATURES_LINE =2089    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";20902091// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns2092// false on any read error so the caller still offers to add the line.2093pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {2094    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;2095    defer gpa.free(conf);2096    return std.mem.indexOf(u8, conf, "experimental-features") != null and2097        std.mem.indexOf(u8, conf, "nix-command") != null and2098        std.mem.indexOf(u8, conf, "flakes") != null;2099}21002101fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {2102    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;2103    return captureLocal(gpa, io, &.{ "sudo", "cat", path });2104}21052106// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix2107// (i.e. inside the top-level attribute set) and write it back via a single2108// `sudo cp`, which prompts for the password on the terminal. Returns an error2109// for the caller to fall back to printed manual instructions.2110pub fn appendFeaturesToNixosConfig(2111    gpa: std.mem.Allocator,2112    io: std.Io,2113    environ: *const std.process.Environ.Map,2114    path: []const u8,2115) !void {2116    const conf = readMaybeSudo(gpa, io, path) catch {2117        errors.error_info.setMessage("could not read {s}", .{path});2118        return error.ConfigNotFound;2119    };2120    defer gpa.free(conf);21212122    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared21232124    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {2125        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});2126        return error.MalformedConfig;2127    };21282129    const home = environ.get("HOME") orelse {2130        errors.error_info.setMessage("HOME not set", .{});2131        return error.ConfigNotFound;2132    };2133    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});2134    defer gpa.free(tmp_path);21352136    var buf: std.ArrayList(u8) = .empty;2137    defer buf.deinit(gpa);2138    try buf.appendSlice(gpa, conf[0..brace]);2139    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');2140    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");2141    try buf.appendSlice(gpa, "  ");2142    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);2143    try buf.append(gpa, '\n');2144    try buf.appendSlice(gpa, conf[brace..]);21452146    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {2147        errors.error_info.setMessage("could not write {s}", .{tmp_path});2148        return error.FileNotFound;2149    };2150    tmp.writePositionalAll(io, buf.items, 0) catch {2151        tmp.close(io);2152        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2153        errors.error_info.setMessage("could not write {s}", .{tmp_path});2154        return error.FileNotFound;2155    };2156    tmp.close(io);21572158    // Back up the existing config, then replace it — in one sudo call so the2159    // password is asked for at most once. Paths travel as positional args ($0,2160    // $1) to sidestep shell quoting.2161    const code = streamLocal(io, &.{2162        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,2163    }) catch {2164        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2165        errors.error_info.setMessage("could not write {s}", .{path});2166        return error.ProcessFailed;2167    };2168    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2169    if (code != 0) {2170        errors.error_info.setMessage("sudo cp into {s} failed", .{path});2171        return error.ProcessFailed;2172    }2173}