exec.zig

95.9 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}293294// Single-quote-wrap `arg` for a POSIX shell, escaping embedded single quotes as295// '\''. ssh joins its trailing command arguments with spaces and hands the296// result to the remote login shell for re-parsing, so passing nina's argv297// through unquoted lets a package name, config path, or channel URL containing298// shell metacharacters or spaces be word-split or executed on the remote host.299fn shellQuote(gpa: std.mem.Allocator, arg: []const u8) ![]u8 {300    var out: std.ArrayList(u8) = .empty;301    try out.append(gpa, '\'');302    for (arg) |ch| {303        if (ch == '\'') {304            try out.appendSlice(gpa, "'\\''");305        } else {306            try out.append(gpa, ch);307        }308    }309    try out.append(gpa, '\'');310    return out.toOwnedSlice(gpa);311}312313fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {314    if (machine.local) return cmd;315316    const host = machine.host orelse {317        errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});318        return error.SshFailed;319    };320321    var ssh: std.ArrayList([]const u8) = .empty;322    try ssh.append(gpa, "ssh");323    try ssh.append(gpa, "-o");324    try ssh.append(gpa, "BatchMode=yes");325    try ssh.append(gpa, "-o");326    try ssh.append(gpa, "StrictHostKeyChecking=accept-new");327    if (machine.ssh_key) |key| {328        try ssh.append(gpa, "-i");329        try ssh.append(gpa, key);330    }331    const addr = if (machine.user) |u|332        try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })333    else334        try gpa.dupe(u8, host);335    try ssh.append(gpa, addr);336337    // Quote every word and join into one ssh argument, so ssh has nothing left338    // to re-join with spaces — the remote shell receives exactly our argv.339    var quoted_cmd: std.ArrayList(u8) = .empty;340    for (cmd, 0..) |arg, i| {341        if (i > 0) try quoted_cmd.append(gpa, ' ');342        const q = try shellQuote(gpa, arg);343        defer gpa.free(q);344        try quoted_cmd.appendSlice(gpa, q);345    }346    try ssh.append(gpa, try quoted_cmd.toOwnedSlice(gpa));347    return ssh.toOwnedSlice(gpa);348}349350test "shellQuote round-trips metacharacters through a real shell" {351    const a = std.testing.allocator;352    const io = std.testing.io;353354    const dangerous = [_][]const u8{355        "foo;reboot",356        "foo && rm -rf /",357        "has space",358        "quo'te",359        "$(whoami)",360        "`whoami`",361        "a|b>c<d",362    };363364    for (dangerous) |arg| {365        const quoted = try shellQuote(a, arg);366        defer a.free(quoted);367368        // A shell asked to print out the quoted word verbatim must reproduce369        // exactly the original string, byte for byte — proving the metacharacters370        // stayed inert instead of being word-split or executed.371        const script = try std.fmt.allocPrint(a, "printf '%s' {s}", .{quoted});372        defer a.free(script);373374        const r = try std.process.run(a, io, .{ .argv = &.{ "sh", "-c", script } });375        defer a.free(r.stdout);376        defer a.free(r.stderr);377378        try std.testing.expectEqual(@as(u8, 0), switch (r.term) {379            .exited => |c| c,380            else => 1,381        });382        try std.testing.expectEqualStrings(arg, r.stdout);383    }384}385386test "buildArgv joins a remote command into a single quoted ssh argument" {387    const a = std.testing.allocator;388389    const machine: types.Machine = .{390        .name = "box",391        .local = false,392        .host = "example.com",393        .user = "june",394    };395396    const argv = try buildArgv(a, &machine, &.{ "nix-env", "-iA", "foo;reboot" });397    defer {398        // Indices 5 (addr) and 6 (the joined quoted command) are the only399        // gpa-owned strings; the rest are literals baked into buildArgv.400        a.free(@constCast(argv[5]));401        a.free(@constCast(argv[6]));402        a.free(argv);403    }404405    // Everything after the ssh destination must collapse into exactly one406    // argument — if ssh received the dangerous word as its own separate407    // argument, it would rejoin it with spaces for the remote shell to408    // re-parse, defeating the quoting.409    try std.testing.expectEqualStrings("ssh", argv[0]);410    try std.testing.expectEqualStrings("[email protected]", argv[5]);411    try std.testing.expectEqual(@as(usize, 7), argv.len);412    try std.testing.expectEqualStrings("'nix-env' '-iA' 'foo;reboot'", argv[6]);413}414415// --- NixOS rebuild ---416417// True if the machine's config dir holds a flake.nix. Only meaningful for a local418// machine — the file lives on the local filesystem. Remote flake detection would419// need an ssh round-trip; a remote flake at the default /etc/nixos needs no flag420// anyway, so we don't bother.421// True if `dir` contains a flake.nix (local filesystem check).422pub fn dirHasFlake(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) bool {423    const flake_path = std.fs.path.join(gpa, &.{ dir, "flake.nix" }) catch return false;424    defer gpa.free(flake_path);425    return pathExists(io, flake_path);426}427428pub fn configHasFlake(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {429    if (!machine.local) return false;430    return dirHasFlake(gpa, io, machine.config_path);431}432433// nixos-rebuild auto-detects /etc/nixos/flake.nix, so the --flake flag is only434// needed when the flake lives elsewhere. A flake at a non-default path must be435// passed explicitly or nixos-rebuild falls back to channels. Compare with436// trailing slashes trimmed so "/etc/nixos/" is still treated as the default.437fn useFlakeFlag(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {438    if (!configHasFlake(gpa, io, machine)) return false;439    var path = machine.config_path;440    while (path.len > 1 and path[path.len - 1] == '/') path = path[0 .. path.len - 1];441    return !std.mem.eql(u8, path, "/etc/nixos");442}443444// Capture nixos-rebuild stderr for the translation pipeline. Raw nix build445// output is suppressed; on failure, reportError() translates stderr via446// errors.translateError(). The substep line above the call tells the user what447// is running; silence during the build is intentional per the error-wrapping brief.448fn nixosRebuildRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, flake: bool, extra_flags: []const []const u8) !u8 {449    var argv: std.ArrayList([]const u8) = .empty;450    defer argv.deinit(gpa);451    try argv.appendSlice(gpa, &.{ "sudo", "nixos-rebuild", verb });452    if (flake) try argv.appendSlice(gpa, &.{ "--flake", machine.config_path });453    try argv.appendSlice(gpa, extra_flags);454455    output.flush();456    const r = try capture(gpa, io, machine, argv.items);457    defer gpa.free(r.stdout);458    defer gpa.free(r.stderr);459    errors.setBuildStderr(r.stderr);460    return r.exit_code;461}462463pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {464    const flake = useFlakeFlag(gpa, io, machine);465    if (flake) {466        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});467    } else {468        output.printSubstep("nixos-rebuild switch", .{});469    }470    return nixosRebuildRun(io, machine, gpa, "switch", flake, extra_flags);471}472473// Live-streaming variant used by `apply` when stdout is a TTY. Each stderr line474// from nixos-rebuild is fed to the build panel for real-time progress display475// while the full stderr is also accumulated for the error translation pipeline.476// Falls back to the silent capture path when not a TTY.477pub fn nixosRebuildSwitchWithPanel(478    io: std.Io,479    machine: *const types.Machine,480    gpa: std.mem.Allocator,481    panel: *output.BuildPanel,482    extra_flags: []const []const u8,483) !u8 {484    const flake = useFlakeFlag(gpa, io, machine);485    if (flake) {486        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});487    } else {488        output.printSubstep("nixos-rebuild switch", .{});489    }490    if (!output.colorEnabled()) return nixosRebuildRun(io, machine, gpa, "switch", flake, extra_flags);491    return nixosRebuildRunStreamed(io, machine, gpa, "switch", flake, panel, extra_flags);492}493494// Spawn argv with stderr piped, feed each line to the build panel for live progress,495// and accumulate the full stderr (newlines preserved) for errors.translateError.496// Factored out of nixosRebuildRunStreamed so the read loop is testable without a497// real nixos-rebuild binary.498fn runStreamedCapture(io: std.Io, gpa: std.mem.Allocator, argv: []const []const u8, panel: *output.BuildPanel) !u8 {499    var child = std.process.spawn(io, .{500        .argv = argv,501        .stdin = .ignore,502        .stdout = .ignore,503        .stderr = .pipe,504    }) catch |e| {505        errors.error_info.setMessage("failed to spawn nixos-rebuild", .{});506        return e;507    };508509    var accumulated: std.ArrayList(u8) = .empty;510    defer accumulated.deinit(gpa);511512    if (child.stderr) |stderr_file| {513        var reader_buf: [8192]u8 = undefined;514        var fr = std.Io.File.Reader.initStreaming(stderr_file, io, &reader_buf);515        while (true) {516            const raw = fr.interface.takeDelimiter('\n') catch |err| switch (err) {517                // A single line exceeded the reader's buffer — routine for nix eval518                // traces/derivation lists. Discard the oversized remainder instead of519                // abandoning the pipe: breaking here would leave stderr undrained, and520                // once the kernel pipe buffer filled the child would block on write()521                // forever, hanging child.wait() below.522                error.StreamTooLong => {523                    _ = fr.interface.discardDelimiterInclusive('\n') catch break;524                    continue;525                },526                error.ReadFailed => break,527            } orelse break;528            // takeDelimiter excludes the delimiter, so re-add it or every downstream529            // line-oriented consumer in errors.zig sees one giant concatenated line.530            accumulated.appendSlice(gpa, raw) catch {};531            accumulated.append(gpa, '\n') catch {};532            const line = std.mem.trimEnd(u8, raw, "\r");533            panel.update(line);534            panel.render();535        }536    }537538    errors.setBuildStderr(accumulated.items);539540    const term = child.wait(io) catch |e| {541        errors.error_info.setMessage("nixos-rebuild wait failed", .{});542        return e;543    };544    return switch (term) {545        .exited => |code| code,546        else => 1,547    };548}549550fn nixosRebuildRunStreamed(551    io: std.Io,552    machine: *const types.Machine,553    gpa: std.mem.Allocator,554    verb: []const u8,555    flake: bool,556    panel: *output.BuildPanel,557    extra_flags: []const []const u8,558) !u8 {559    var argv_list: std.ArrayList([]const u8) = .empty;560    defer argv_list.deinit(gpa);561    try argv_list.appendSlice(gpa, &.{ "sudo", "nixos-rebuild", verb });562    if (flake) try argv_list.appendSlice(gpa, &.{ "--flake", machine.config_path });563    try argv_list.appendSlice(gpa, extra_flags);564565    output.flush();566    const built_argv = try buildArgv(gpa, machine, argv_list.items);567    defer if (!machine.local) gpa.free(built_argv);568569    return runStreamedCapture(io, gpa, built_argv, panel);570}571572test "runStreamedCapture preserves newlines and survives an oversized stderr line (NINA-001/002)" {573    const a = std.testing.allocator;574    const io = std.testing.io;575576    // panel.render() writes through output's global writer, which only main.zig577    // initializes in real runs. Point it at a discard sink with color off so the578    // test exercises the real render() call path without a live terminal.579    var discard_buf: [256]u8 = undefined;580    var discarding: std.Io.Writer.Discarding = .init(&discard_buf);581    var env: std.process.Environ.Map = .init(a);582    defer env.deinit();583    output.init(&discarding.writer, io, &env, false);584585    var panel: output.BuildPanel = .{};586587    // A single stderr line over 8192 bytes (the reader's fixed buffer size) used to588    // trip error.StreamTooLong and abandon the pipe (NINA-002); it must now be589    // discarded and draining must continue for the lines that follow.590    var oversized: [9000]u8 = undefined;591    @memset(&oversized, 'x');592593    const script = try std.fmt.allocPrint(a,594        \\exec >&2595        \\printf 'these 3 paths will be fetched (12.3 MiB download, 45.6 MiB unpacked)\n'596        \\printf '%s\n' "{s}"597        \\printf 'error: nina test canary xyz-explanation\n'598        \\printf 'For full logs, run some-command\n'599        \\exit 1600    , .{oversized});601    defer a.free(script);602603    const exit_code = try runStreamedCapture(io, a, &.{ "sh", "-c", script }, &panel);604    try std.testing.expectEqual(@as(u8, 1), exit_code);605606    const stderr = errors.getBuildStderr();607    // Newlines must survive accumulation (NINA-001) — without them, every608    // line-oriented consumer downstream (innermostError, extractLocation,609    // extractWarnings) sees one giant concatenated line instead of real lines.610    try std.testing.expect(std.mem.indexOf(u8, stderr, "error: nina test canary xyz-explanation\n") != null);611612    // translateError's returned strings are a mix of literals and heap allocations613    // depending which layer matched; an arena sidesteps the ownership ambiguity.614    var arena = std.heap.ArenaAllocator.init(a);615    defer arena.deinit();616    const translated = errors.translateError(arena.allocator(), stderr);617    // Must reach Layer 2's structured extraction (innermostError needs a trimmed618    // line starting with "error:") rather than falling through to the generic619    // Layer-3 fallback, which is only reachable when line structure is lost.620    try std.testing.expect(!std.mem.eql(u8, translated.body, "something went wrong that nina couldn't translate."));621}622623pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {624    return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine), extra_flags);625}626627pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {628    return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine), extra_flags);629}630631// --- Generations ---632633// Read system-profile generations WITHOUT root. `nix-env --list-generations -p634// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user635// ("system.lock: Permission denied"). The generation symlinks themselves are636// world-readable, so list them directly: parse `system-N-link` names, take each637// link's own mtime for the date/time, and mark the one the `system` symlink638// points at as current. Output matches the `nix-env --list-generations` columns639// (num date time [current]) so parseGenerations is unchanged.640const GEN_LIST_SCRIPT =641    \\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 }'642;643644pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {645    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });646    defer gpa.free(r.stderr);647    defer gpa.free(r.stdout);648    if (r.exit_code != 0) return error.ProcessFailed;649    return parseGenerations(gpa, r.stdout);650}651652fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {653    var gens: std.ArrayList(types.GenerationInfo) = .empty;654    var lines = std.mem.splitScalar(u8, output_str, '\n');655    while (lines.next()) |line| {656        const trimmed = std.mem.trim(u8, line, " \t");657        if (trimmed.len == 0) continue;658        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");659        const num_str = parts.next() orelse continue;660        const date_str = parts.next() orelse continue;661        const time_str = parts.next() orelse continue;662        const rest = parts.rest();663        const current = std.mem.indexOf(u8, rest, "current") != null;664        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;665        try gens.append(gpa, .{666            .number = num,667            .date = try gpa.dupe(u8, date_str),668            .time = try gpa.dupe(u8, time_str),669            .current = current,670        });671    }672    return gens.toOwnedSlice(gpa);673}674675pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {676    const gens = try getGenerations(gpa, io, machine);677    defer gpa.free(gens);678    for (gens) |g| {679        if (g.current) return g.number;680    }681    return 0;682}683684pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {685    // Switch the system profile to generation n, then activate it (bootloader +686    // services). Without switch-to-configuration the change isn't applied.687    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 });688    defer gpa.free(cmd);689    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });690}691692pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {693    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });694}695696pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {697    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});698    defer gpa.free(n_str);699    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });700}701702pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {703    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });704}705706// --- Garbage collection ---707708pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {709    if (delete_old) {710        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });711    }712    // Keep the `keep` most recent system generations (+N deletes all but N),713    // then collect now-unreferenced store paths. `--delete-older-than` wants a714    // duration (e.g. 14d), not a generation count.715    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });716    defer gpa.free(cmd);717    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });718}719720// --- Channels ---721722pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {723    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });724    defer gpa.free(r.stderr);725    defer gpa.free(r.stdout);726    if (r.exit_code != 0) return error.ProcessFailed;727    return parseChannels(gpa, r.stdout);728}729730fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {731    var channels: std.ArrayList(types.ChannelInfo) = .empty;732    var lines = std.mem.splitScalar(u8, output_str, '\n');733    while (lines.next()) |line| {734        const trimmed = std.mem.trim(u8, line, " \t\r");735        if (trimmed.len == 0) continue;736        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;737        try channels.append(gpa, .{738            .name = try gpa.dupe(u8, trimmed[0..space]),739            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),740        });741    }742    return channels.toOwnedSlice(gpa);743}744745pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {746    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });747}748749pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {750    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });751}752753pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {754    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });755}756757// --- Services ---758759pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {760    const cmd: []const []const u8 = if (user)761        &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }762    else763        &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };764    const r = try capture(gpa, io, machine, cmd);765    defer gpa.free(r.stderr);766    defer gpa.free(r.stdout);767    if (r.exit_code != 0) return error.ProcessFailed;768    return parseServices(gpa, r.stdout);769}770771fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {772    var svcs: std.ArrayList(types.ServiceInfo) = .empty;773    var lines = std.mem.splitScalar(u8, output_str, '\n');774    while (lines.next()) |line| {775        const trimmed = std.mem.trim(u8, line, " \t\r");776        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines777        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");778        const name = parts.next() orelse continue;779        _ = parts.next(); // load780        const active_str = parts.next() orelse continue;781        const sub_str = parts.next() orelse "unknown";782783        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))784            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)785        else if (std.mem.eql(u8, active_str, "failed"))786            .failed787        else788            .inactive;789790        try svcs.append(gpa, .{791            .name = try gpa.dupe(u8, name),792            .state = state,793            .uptime = null,794        });795    }796    return svcs.toOwnedSlice(gpa);797}798799pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {800    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.801    // User services run under the caller's own systemd manager, so no sudo.802    if (user) {803        return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });804    }805    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });806}807808pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {809    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});810    defer gpa.free(n_str);811    if (user) {812        if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });813        return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });814    }815    if (follow) {816        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });817    }818    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });819}820821// --- Profile ---822823// Stream with one extra environment variable injected alongside the inherited env.824// Used for cases like NIXPKGS_ALLOW_UNFREE=1 where we need a single override825// without replacing the full parent environment.826fn 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 {827    output.flush();828    const argv = try buildArgv(gpa, machine, cmd);829    defer if (!machine.local) gpa.free(argv);830831    var env = try base_env.clone(gpa);832    defer env.deinit();833    try env.put(key, val);834835    var child = std.process.spawn(io, .{836        .argv = argv,837        .stdin = .inherit,838        .stdout = .inherit,839        .stderr = .inherit,840        .environ_map = &env,841    }) catch |e| {842        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});843        return e;844    };845846    const term = child.wait(io) catch |e| {847        errors.error_info.setMessage("process wait failed", .{});848        return e;849    };850851    return switch (term) {852        .exited => |c| c,853        else => 1,854    };855}856857pub 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 {858    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});859    defer gpa.free(pkg_ref);860    // `nix profile add` is the current verb; `install` is a deprecated alias that861    // prints a warning on modern nix.862    if (allow_unfree) {863        // The package is unfree and the user's system-wide allowUnfree setting864        // doesn't propagate to imperative nix commands. Pass NIXPKGS_ALLOW_UNFREE=1865        // and --impure so the profile add succeeds: --impure allows builtins.getEnv866        // to read the env var inside the nixpkgs flake's pure evaluation context.867        return streamWithEnvVar(io, machine, gpa, &.{ "nix", "profile", "add", "--impure", pkg_ref }, environ, "NIXPKGS_ALLOW_UNFREE", "1");868    }869    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });870}871872pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {873    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not874    // by flake ref — passing nixpkgs#ripgrep matches nothing.875    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });876}877878pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {879    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });880    defer gpa.free(r.stderr);881    if (r.exit_code != 0) return error.ProcessFailed;882    return r.stdout;883}884885// Machine-readable profile listing — caller parses elements -> name + version.886pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {887    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });888    defer gpa.free(r.stderr);889    if (r.exit_code != 0) {890        gpa.free(r.stdout);891        return error.ProcessFailed;892    }893    return r.stdout;894}895896// Returns the profile element name to pass to `nix profile remove/upgrade`897// (e.g. "nina" or "default"), or null if nina is not found. Caller owns the898// returned slice. A NixOS system-package install also resolves into /nix/store899// so the store path alone can't distinguish it from a profile install — the900// profile list can. A missing/empty profile (or no nix) returns null.901pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {902    const js = profileListJson(gpa, io, machine) catch return null;903    defer gpa.free(js);904    return profileJsonNinaElement(gpa, js);905}906907908pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {909    const name = profileNinaElement(gpa, io, machine) orelse return false;910    gpa.free(name);911    return true;912}913914// True when a nix store path belongs to the nina package. Store paths have the915// form /nix/store/<32-char-hash>-<pname>-<version>[/<subpath>]. We check that916// the 33 chars after /nix/store/ are the hash+dash, and the pname that follows917// is exactly "nina" (followed by "-" or end-of-component).918fn storePathIsNina(path: []const u8) bool {919    const prefix = "/nix/store/";920    if (!std.mem.startsWith(u8, path, prefix)) return false;921    const rel = path[prefix.len..];922    // The store entry name ends at the first "/" (if any sub-path follows).923    const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];924    if (entry.len < 34) return false; // 32-char hash + dash + at least one char925    const pname_ver = entry[33..]; // skip hash + dash926    return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");927}928929// Pure parse of `nix profile list --json` for a nina element, returning its930// element name (the key to pass to `nix profile remove/upgrade`) or null.931// Newer nix (2.18+) keys elements by pname ("nina"). Older nix uses an array932// with an "attrPath" field. Tarball installs via the `default` output may use933// the key "default" instead of "nina"; we detect those via storePaths.934fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {935    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;936    defer parsed.deinit();937    const root = parsed.value;938    if (root != .object) return null;939    const elements = root.object.get("elements") orelse return null;940    switch (elements) {941        .object => |obj| {942            // Fast path: exact "nina" key (nix 2.18+ with nixpkgs#nina install).943            if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;944            // Fallback: scan storePaths. Handles tarball installs where the default945            // output is selected and nix names the element "default" (older nix) or946            // some other key derived from the attrPath rather than the pname.947            var it = obj.iterator();948            while (it.next()) |kv| {949                const val = kv.value_ptr.*;950                if (val != .object) continue;951                const sps = val.object.get("storePaths") orelse continue;952                if (sps != .array) continue;953                for (sps.array.items) |sp| {954                    if (sp == .string and storePathIsNina(sp.string))955                        return gpa.dupe(u8, kv.key_ptr.*) catch null;956                }957            }958            return null;959        },960        .array => |arr| {961            // Older nix array format. Element name is the last component of attrPath.962            for (arr.items) |el| {963                if (el != .object) continue;964                const ap = el.object.get("attrPath") orelse continue;965                if (ap != .string) continue;966                if (std.mem.eql(u8, ap.string, "nina") or967                    std.mem.endsWith(u8, ap.string, ".nina"))968                    return gpa.dupe(u8, "nina") catch null;969                // Tarball default-output install: attrPath ends in ".default" but970                // storePaths point to nina. Return "default" as the element name.971                const sps = el.object.get("storePaths") orelse continue;972                if (sps != .array) continue;973                for (sps.array.items) |sp| {974                    if (sp != .string) continue;975                    if (!storePathIsNina(sp.string)) continue;976                    const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;977                    const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;978                    return gpa.dupe(u8, el_name) catch null;979                }980            }981            return null;982        },983        else => return null,984    }985}986987test "profileJsonNinaElement finds element name from profile JSON" {988    const a = std.testing.allocator;989990    // Newer nix: elements keyed by pname. "nina" key present.991    const named =992        \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},993        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}994    ;995    const r1 = profileJsonNinaElement(a, named);996    defer if (r1) |n| a.free(n);997    try std.testing.expectEqualStrings("nina", r1.?);998999    // Tarball install via default output: element keyed as "default", storePath is nina.1000    const default_key =1001        \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}1002    ;1003    const r2 = profileJsonNinaElement(a, default_key);1004    defer if (r2) |n| a.free(n);1005    try std.testing.expectEqualStrings("default", r2.?);10061007    // Decoy: storePath of another package contains "nina" as a substring but is not nina.1008    const decoy =1009        \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}1010    ;1011    const r3 = profileJsonNinaElement(a, decoy);1012    try std.testing.expectEqual(@as(?[]const u8, null), r3);10131014    // Older nix array schema, attrPath ending in ".nina".1015    const arr =1016        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}1017    ;1018    const r4 = profileJsonNinaElement(a, arr);1019    defer if (r4) |n| a.free(n);1020    try std.testing.expectEqualStrings("nina", r4.?);10211022    // Older nix array schema, tarball default-output install.1023    const arr_default =1024        \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}1025    ;1026    const r5 = profileJsonNinaElement(a, arr_default);1027    defer if (r5) |n| a.free(n);1028    try std.testing.expectEqualStrings("default", r5.?);10291030    // Empty / malformed → null.1031    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));1032    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));1033}10341035// The store paths that make up the running system environment. Each reference is1036// a <hash>-<name>-<version> path, so the caller can list system packages with1037// versions — there is no cleaner per-package list for environment.systemPackages.1038pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1039    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });1040    defer gpa.free(r.stderr);1041    if (r.exit_code != 0) {1042        gpa.free(r.stdout);1043        return error.ProcessFailed;1044    }1045    return r.stdout;1046}10471048pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1049    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });1050}10511052// --- Store ---10531054pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1055    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });1056}10571058pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1059    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });1060}10611062// Deduplicate identical store files via hard links — frees space without1063// garbage-collecting any paths.1064pub fn storeOptimise(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1065    return stream(io, machine, gpa, &.{ "nix", "store", "optimise" });1066}10671068pub const SystemStatus = struct { size: []u8, age: []u8 };10691070// One read-only pass for `nina status`: the current system's closure size (a1071// single `path-info -S` of /run/current-system — fast, unlike -S over the whole1072// store) and seconds since the system profile was last switched (its symlink1073// mtime). Both are world-readable; no root needed.1074const STATUS_SCRIPT =1075    \\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} ))"1076;10771078pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {1079    const unknown = SystemStatus{1080        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },1081        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },1082    };1083    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;1084    defer gpa.free(r.stdout);1085    defer gpa.free(r.stderr);1086    if (r.exit_code != 0) return unknown;10871088    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");1089    const sz_str = it.next() orelse return unknown;1090    const age_str = it.next() orelse return unknown;1091    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;1092    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;10931094    gpa.free(unknown.size);1095    gpa.free(unknown.age);1096    return .{1097        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),1098        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),1099    };1100}11011102// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A1103// one-word health signal; exits non-zero when degraded, so we read stdout, not1104// the code. Caller owns the returned slice.1105pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1106    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch1107        return gpa.dupe(u8, "unknown");1108    defer gpa.free(r.stderr);1109    const state = std.mem.trim(u8, r.stdout, " \t\n\r");1110    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");1111    gpa.free(r.stdout);1112    return owned;1113}11141115fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {1116    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});1117    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});1118    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});1119    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});1120}11211122pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1123    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });1124}11251126pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {1127    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)1128    // graph work that takes minutes on a real store (59k+ paths) and hangs the1129    // command. We don't need closures: `--all --json` (no -S) carries each path's1130    // own narSize, so one fast pass gives the path count and the summed store size.1131    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.1132    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.1133    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });1134    defer gpa.free(pi.stdout);1135    defer gpa.free(pi.stderr);11361137    const scan = scanStoreJson(pi.stdout);1138    const total_owned = try humanSize(gpa, scan.total_bytes);11391140    return .{1141        .total_size = total_owned,1142        .live_paths = scan.count,1143        .reclaimable_paths = 0,1144    };1145}11461147const StoreScan = struct { count: u64, total_bytes: u64 };11481149// One linear pass over `nix path-info --json`: each path object has exactly one1150// "narSize": field, so counting them gives the true path count and summing the1151// values gives the total store size — no per-path closure walk.1152fn scanStoreJson(json_str: []const u8) StoreScan {1153    const needle = "\"narSize\":";1154    var count: u64 = 0;1155    var total: u64 = 0;1156    var i: usize = 0;1157    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {1158        var j = pos + needle.len;1159        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}1160        var val: u64 = 0;1161        var any = false;1162        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {1163            val = val * 10 + (json_str[j] - '0');1164            any = true;1165        }1166        if (any) {1167            count += 1;1168            total += val;1169        }1170        i = j;1171    }1172    return .{ .count = count, .total_bytes = total };1173}11741175fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1176    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };1177    var val: f64 = @floatFromInt(bytes);1178    var unit: usize = 0;1179    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1180    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1181    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1182}11831184pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {1185    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the1186    // flake registry), not a flake in the current directory.1187    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});1188    defer gpa.free(expr);1189    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });1190    defer gpa.free(r.stderr);1191    if (r.exit_code != 0) {1192        gpa.free(r.stdout);1193        return error.ProcessFailed;1194    }1195    return r.stdout;1196}11971198// --- Flake ---11991200pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8, extra_flags: []const []const u8) !u8 {1201    var argv: std.ArrayList([]const u8) = .empty;1202    defer argv.deinit(gpa);1203    try argv.appendSlice(gpa, &.{ "nix", "flake", "update" });1204    if (input) |inp| try argv.append(gpa, inp);1205    try argv.appendSlice(gpa, extra_flags);1206    return stream(io, machine, gpa, argv.items);1207}12081209// Update flake inputs for the flake living in `dir` (the config dir). `nix flake1210// update` operates on the flake in the working directory, so we cd there first.1211// Used by `nina upgrade` on a flake system in place of nix-channel --update.1212pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {1213    return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });1214}12151216pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {1217    var argv: std.ArrayList([]const u8) = .empty;1218    defer argv.deinit(gpa);1219    try argv.appendSlice(gpa, &.{ "nix", "flake", "check" });1220    try argv.appendSlice(gpa, extra_flags);1221    return stream(io, machine, gpa, argv.items);1222}12231224pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1225    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });1226}12271228pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1229    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });1230}12311232pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {1233    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });1234}12351236pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1237    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });1238    defer gpa.free(r.stderr);1239    if (r.exit_code != 0) {1240        gpa.free(r.stdout);1241        return error.ProcessFailed;1242    }1243    return r.stdout;1244}12451246// --- Build / Run / Develop ---12471248pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8, extra_flags: []const []const u8) !u8 {1249    var argv: std.ArrayList([]const u8) = .empty;1250    defer argv.deinit(gpa);1251    try argv.append(gpa, "nix");1252    try argv.append(gpa, "build");1253    var ref_buf: ?[]u8 = null;1254    defer if (ref_buf) |r| gpa.free(r);1255    if (attr) |a| {1256        ref_buf = try std.fmt.allocPrint(gpa, ".#{s}", .{a});1257        try argv.append(gpa, ref_buf.?);1258    }1259    try argv.appendSlice(gpa, extra_flags);1260    return stream(io, machine, gpa, argv.items);1261}12621263pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, extra_flags: []const []const u8) !u8 {1264    // nix run always gets --no-write-lock-file for remote URLs1265    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");12661267    var argv: std.ArrayList([]const u8) = .empty;1268    defer argv.deinit(gpa);1269    try argv.append(gpa, "nix");1270    try argv.append(gpa, "run");12711272    var ref_buf: ?[]u8 = null;1273    defer if (ref_buf) |r| gpa.free(r);1274    if (is_url) {1275        try argv.append(gpa, pkg);1276        try argv.append(gpa, "--no-write-lock-file");1277    } else if (std.mem.indexOfScalar(u8, pkg, '#') != null) {1278        // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.1279        try argv.append(gpa, pkg);1280    } else {1281        ref_buf = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1282        try argv.append(gpa, ref_buf.?);1283    }12841285    // extra_flags carries any `-- <program args>` separator verbatim, so this1286    // naturally reconstructs `nix run <ref> -- <args>` — nix's own convention.1287    try argv.appendSlice(gpa, extra_flags);1288    return stream(io, machine, gpa, argv.items);1289}12901291pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1292    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1293    defer gpa.free(ref);1294    return stream(io, machine, gpa, &.{ "nix", "shell", ref });1295}12961297pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {1298    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1299    defer gpa.free(ref);1300    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});1301    defer gpa.free(ps1);1302    if (machine.local) {1303        const rc_path = try createInteractiveShellRc(gpa, io);1304        defer {1305            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1306            gpa.free(rc_path);1307        }1308        return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref, "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, ps1);1309    }1310    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);1311}13121313pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8, extra_flags: []const []const u8) !u8 {1314    if (run_cmd) |cmd| {1315        // sh -c so a multi-word command isn't treated as a single executable name.1316        var argv: std.ArrayList([]const u8) = .empty;1317        defer argv.deinit(gpa);1318        try argv.appendSlice(gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1319        try argv.appendSlice(gpa, extra_flags);1320        return stream(io, machine, gpa, argv.items);1321    }1322    var argv: std.ArrayList([]const u8) = .empty;1323    defer argv.deinit(gpa);1324    try argv.append(gpa, "nix");1325    try argv.append(gpa, "develop");1326    try argv.appendSlice(gpa, extra_flags);1327    return stream(io, machine, gpa, argv.items);1328}13291330pub 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 {1331    if (run_cmd) |cmd| {1332        // sh -c so a multi-word command isn't treated as a single executable name.1333        var argv: std.ArrayList([]const u8) = .empty;1334        defer argv.deinit(gpa);1335        try argv.appendSlice(gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1336        try argv.appendSlice(gpa, extra_flags);1337        return stream(io, machine, gpa, argv.items);1338    }1339    if (machine.local) {1340        const rc_path = try createInteractiveShellRc(gpa, io);1341        defer {1342            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1343            gpa.free(rc_path);1344        }1345        var argv: std.ArrayList([]const u8) = .empty;1346        defer argv.deinit(gpa);1347        try argv.append(gpa, "nix");1348        try argv.append(gpa, "develop");1349        try argv.appendSlice(gpa, extra_flags);1350        try argv.appendSlice(gpa, &.{ "--command", "bash", "--rcfile", rc_path, "-i" });1351        return streamEnv(io, machine, gpa, argv.items, base_env, "(nina: dev) -> ");1352    }1353    var argv: std.ArrayList([]const u8) = .empty;1354    defer argv.deinit(gpa);1355    try argv.append(gpa, "nix");1356    try argv.append(gpa, "develop");1357    try argv.appendSlice(gpa, extra_flags);1358    return streamEnv(io, machine, gpa, argv.items, base_env, "(nina: dev) -> ");1359}13601361pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1362    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });1363}13641365// --- Format ---13661367pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {1368    if (check) {1369        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });1370    }1371    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });1372}13731374// --- Info ---13751376pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1377    const r = try capture(gpa, io, machine, &.{"nixos-version"});1378    defer gpa.free(r.stderr);1379    if (r.exit_code != 0) {1380        gpa.free(r.stdout);1381        return error.ProcessFailed;1382    }1383    return r.stdout;1384}13851386pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1387    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });1388    defer gpa.free(r.stderr);1389    if (r.exit_code != 0) {1390        gpa.free(r.stdout);1391        return error.ProcessFailed;1392    }1393    return r.stdout;1394}13951396pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1397    const r = try capture(gpa, io, machine, &.{"uptime"});1398    defer gpa.free(r.stderr);1399    if (r.exit_code != 0) {1400        gpa.free(r.stdout);1401        return error.ProcessFailed;1402    }1403    return r.stdout;1404}14051406// --- Boot ---14071408pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {1409    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });1410    defer gpa.free(r.stderr);1411    defer gpa.free(r.stdout);1412    if (r.exit_code != 0) return error.ProcessFailed;1413    return parseBootEntries(gpa, r.stdout);1414}14151416fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {1417    var entries: std.ArrayList(types.BootEntry) = .empty;1418    var lines = std.mem.splitScalar(u8, output_str, '\n');1419    while (lines.next()) |line| {1420        const trimmed = std.mem.trim(u8, line, " \t\r");1421        if (std.mem.startsWith(u8, trimmed, "title:")) {1422            const title = std.mem.trim(u8, trimmed[6..], " \t");1423            const current = std.mem.indexOf(u8, title, "(current)") != null;1424            try entries.append(gpa, .{1425                .title = try gpa.dupe(u8, title),1426                .current = current,1427            });1428        }1429    }1430    return entries.toOwnedSlice(gpa);1431}14321433// --- Pkg info ---14341435fn pkgInstallable(gpa: std.mem.Allocator, pkg: []const u8) ![]u8 {1436    return std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1437}14381439fn resolvePkgStorePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, installable: []const u8) ![]u8 {1440    const r = try capture(gpa, io, machine, &.{ "nix", "build", "--no-link", "--print-out-paths", installable });1441    defer gpa.free(r.stderr);1442    defer gpa.free(r.stdout);1443    if (r.exit_code != 0) return error.PackageNotFound;14441445    var lines = std.mem.tokenizeAny(u8, r.stdout, "\r\n");1446    const first_path = lines.next() orelse return error.PackageNotFound;1447    const store_path = std.mem.trim(u8, first_path, " \t");1448    if (store_path.len == 0) return error.PackageNotFound;1449    return gpa.dupe(u8, store_path);1450}14511452pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1453    const installable = try pkgInstallable(gpa, pkg);1454    defer gpa.free(installable);1455    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1456    defer gpa.free(store_path);1457    return stream(io, machine, gpa, &.{ "nix", "why-depends", "/run/current-system", store_path });1458}14591460pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1461    const installable = try pkgInstallable(gpa, pkg);1462    defer gpa.free(installable);1463    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1464    defer gpa.free(store_path);1465    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", store_path });1466}14671468pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {1469    const installable = try pkgInstallable(gpa, pkg);1470    defer gpa.free(installable);1471    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", "--json", installable });1472    defer gpa.free(r.stderr);1473    defer gpa.free(r.stdout);1474    if (r.exit_code != 0) return error.ProcessFailed;14751476    const nar_size = try pathInfoNarSize(gpa, r.stdout);1477    return humanPkgSize(gpa, nar_size);1478}14791480pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1481    const installable = try pkgInstallable(gpa, pkg);1482    defer gpa.free(installable);1483    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1484    defer gpa.free(store_path);1485    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", store_path });1486}14871488fn pathInfoNarSize(gpa: std.mem.Allocator, json_str: []const u8) !u64 {1489    var parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.ProcessFailed;1490    defer parsed.deinit();1491    switch (parsed.value) {1492        .object => |obj| {1493            var it = obj.iterator();1494            while (it.next()) |entry| {1495                if (entry.value_ptr.* == .object) {1496                    if (entry.value_ptr.object.get("narSize")) |v| {1497                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1498                    }1499                }1500            }1501        },1502        .array => |arr| {1503            for (arr.items) |item| {1504                if (item == .object) {1505                    if (item.object.get("narSize")) |v| {1506                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1507                    }1508                }1509            }1510        },1511        else => {},1512    }1513    return error.ProcessFailed;1514}15151516fn humanPkgSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1517    const units = [_][]const u8{ "B", "KiB", "MiB", "GiB", "TiB" };1518    var val: f64 = @floatFromInt(bytes);1519    var unit: usize = 0;1520    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1521    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1522    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1523}15241525test "pathInfoNarSize parses object and array shapes" {1526    try std.testing.expectEqual(@as(u64, 1064629862), try pathInfoNarSize(std.testing.allocator,1527        \\{"/nix/store/abc-ffmpeg":{"narSize":1064629862}}1528    ));1529    try std.testing.expectEqual(@as(u64, 2048), try pathInfoNarSize(std.testing.allocator,1530        \\[{"path":"/nix/store/abc-pkg","narSize":2048}]1531    ));1532}15331534// --- Hash / Fetch ---15351536pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {1537    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });1538    defer gpa.free(r.stderr);1539    if (r.exit_code != 0) {1540        gpa.free(r.stdout);1541        return error.ProcessFailed;1542    }1543    return r.stdout;1544}15451546pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {1547    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });1548    defer gpa.free(r.stderr);1549    if (r.exit_code != 0) {1550        gpa.free(r.stdout);1551        return error.ProcessFailed;1552    }1553    return r.stdout;1554}15551556// --- Pin ---15571558pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {1559    // Stub: full implementation would parse and edit flake.lock JSON1560    // The pin/unpin flow works via nix flake update which regenerates flake.lock1561}15621563pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {1564    if (line) |l| {1565        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});1566        defer gpa.free(line_arg);1567        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });1568    }1569    return stream(io, &types.Machine{}, gpa, &.{ editor, path });1570}15711572// Open a config directory as root with `sudo -E <editor> <path>` — `-E`1573// preserves the user's environment (PATH, TERM, EDITOR config) so the editor1574// behaves the same as it does unprivileged. Used by `nina edit --dir`.1575pub fn openEditorSudo(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8) !u8 {1576    return stream(io, &types.Machine{}, gpa, &.{ "sudo", "-E", editor, path });1577}15781579pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {1580    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});1581    defer gpa.free(a_str);1582    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});1583    defer gpa.free(b_str);1584    // On a tty, the child's own color is fine — stream it directly.1585    if (output.colorEnabled()) {1586        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });1587    }1588    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,1589    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.1590    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });1591    defer gpa.free(r.stdout);1592    defer gpa.free(r.stderr);1593    const cleaned = try stripAnsi(gpa, r.stdout);1594    defer gpa.free(cleaned);1595    output.raw(cleaned);1596    return r.exit_code;1597}15981599// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a1600// child process's color when it writes ANSI unconditionally.1601fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1602    var out: std.ArrayList(u8) = .empty;1603    errdefer out.deinit(gpa);1604    var i: usize = 0;1605    while (i < input.len) {1606        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1607            i += 2;1608            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1609            if (i < input.len) i += 1; // consume the final byte1610            continue;1611        }1612        try out.append(gpa, input[i]);1613        i += 1;1614    }1615    return out.toOwnedSlice(gpa);1616}16171618test "stripAnsi removes CSI color sequences" {1619    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1620    defer std.testing.allocator.free(cleaned);1621    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1622}16231624// --- Doctor checks ---16251626pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1627    var checks: std.ArrayList(types.DoctorCheck) = .empty;16281629    // Check nix daemon1630    {1631        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1632        defer gpa.free(r.stdout);1633        defer gpa.free(r.stderr);1634        const active = std.mem.indexOf(u8, r.stdout, "active") != null;1635        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1636    }16371638    // Check config syntax. Flake-aware like apply/upgrade: on a flake system a1639    // plain `nixos-rebuild dry-build` evaluates <nixpkgs/nixos> + <nixos-config>1640    // (channel style) and fails, so pass --flake when the config dir has one.1641    {1642        const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1643            &.{ "sudo", "nixos-rebuild", "dry-build", "--flake", machine.config_path }1644        else1645            &.{ "sudo", "nixos-rebuild", "dry-build" };1646        const r = try capture(gpa, io, machine, argv);1647        defer gpa.free(r.stdout);1648        defer gpa.free(r.stderr);1649        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1650    }16511652    // Check channel1653    {1654        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1655        defer gpa.free(r.stdout);1656        defer gpa.free(r.stderr);1657        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1658        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1659    }16601661    return checks.toOwnedSlice(gpa);1662}16631664// --- Home Manager ---1665//1666// Home Manager has three usage modes. nina detects which one is in play before1667// any `home` command so it can either drive the standalone CLI or redirect the1668// user to `nina apply` (when HM is a NixOS/flake module activated by rebuild).16691670pub const HomeManagerMode = enum {1671    // home-manager binary on PATH — manages the user env on its own.1672    standalone,1673    // No binary, but a home.nix exists — HM is a NixOS/flake module rebuilt by1674    // nixos-rebuild. `nina home apply` redirects to `nina apply`.1675    module,1676    none,1677};16781679fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1680    const home = environ.get("HOME") orelse return null;1681    return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1682}16831684// Path to the standalone home.nix. Caller frees.1685pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1686    const dir = homeConfigDir(gpa, environ) orelse return null;1687    defer gpa.free(dir);1688    return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1689}16901691pub fn pathExists(io: std.Io, path: []const u8) bool {1692    const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1693    f.close(io);1694    return true;1695}16961697// `command -v <name>` — true if the binary resolves on PATH. Silent (captured),1698// unlike streamLocal which would inherit stdio.1699fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1700    var buf: [256]u8 = undefined;1701    const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1702    const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1703    defer gpa.free(r.stdout);1704    defer gpa.free(r.stderr);1705    return switch (r.term) {1706        .exited => |code| code == 0,1707        else => false,1708    };1709}17101711pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1712    if (commandExists(gpa, io, "home-manager")) return .standalone;1713    if (homeNixPath(gpa, environ)) |p| {1714        defer gpa.free(p);1715        if (pathExists(io, p)) return .module;1716    }1717    return .none;1718}17191720// The home-manager config dir when it holds a flake.nix (a flake-based home1721// config that `home-manager switch --flake` drives). null for a channel-based1722// config, which uses a plain `home-manager switch`. Caller frees.1723pub fn homeFlakeDir(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1724    const dir = homeConfigDir(gpa, environ) orelse return null;1725    const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch {1726        gpa.free(dir);1727        return null;1728    };1729    defer gpa.free(flake);1730    if (!pathExists(io, flake)) {1731        gpa.free(dir);1732        return null;1733    }1734    return dir;1735}17361737// Platform-specific home-manager attribute "<user>-<arch>-<os>" (e.g.1738// murazaki-x86_64-linux) — the homeConfigurations key many flakes derive from1739// ${USER}-${system}. arch/os come from uname on the local host (home commands1740// are local-only). Caller frees.1741pub fn homeManagerAttr(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, environ: *const std.process.Environ.Map) ![]const u8 {1742    const user = environ.get("USER") orelse "user";17431744    const arch_r = try capture(gpa, io, machine, &.{ "uname", "-m" });1745    defer gpa.free(arch_r.stdout);1746    defer gpa.free(arch_r.stderr);1747    if (arch_r.exit_code != 0) return error.ProcessFailed;1748    const arch = std.mem.trim(u8, arch_r.stdout, " \t\r\n");17491750    const os_r = try capture(gpa, io, machine, &.{ "uname", "-s" });1751    defer gpa.free(os_r.stdout);1752    defer gpa.free(os_r.stderr);1753    if (os_r.exit_code != 0) return error.ProcessFailed;1754    const os = try gpa.dupe(u8, std.mem.trim(u8, os_r.stdout, " \t\r\n"));1755    defer gpa.free(os);1756    for (os) |*ch| ch.* = std.ascii.toLower(ch.*);17571758    if (arch.len == 0 or os.len == 0) return error.ProcessFailed;1759    return std.fmt.allocPrint(gpa, "{s}-{s}-{s}", .{ user, arch, os });1760}17611762// Map a nixos-version string to the matching home-manager branch: an unstable1763// channel ("…pre…"/"unstable") → master; a stable release like1764// "25.05.20250115.abcdef (Warbler)" → release-25.05. Anything unparseable1765// falls back to master. Caller frees.1766fn homeBranchFromVersion(gpa: std.mem.Allocator, version_raw: []const u8) ![]const u8 {1767    const v = std.mem.trim(u8, version_raw, " \t\r\n");1768    if (std.mem.indexOf(u8, v, "pre") != null or1769        std.mem.indexOf(u8, v, "unstable") != null)1770        return gpa.dupe(u8, "master");17711772    const head = v[0 .. std.mem.indexOfScalar(u8, v, ' ') orelse v.len];1773    var it = std.mem.splitScalar(u8, head, '.');1774    const major = it.next() orelse "";1775    const minor = it.next() orelse "";1776    if (allDigits(major) and allDigits(minor))1777        return std.fmt.allocPrint(gpa, "release-{s}.{s}", .{ major, minor });17781779    return gpa.dupe(u8, "master");1780}17811782fn allDigits(s: []const u8) bool {1783    if (s.len == 0) return false;1784    for (s) |ch| if (!std.ascii.isDigit(ch)) return false;1785    return true;1786}17871788test "homeBranchFromVersion maps channels to HM branches" {1789    const a = std.testing.allocator;1790    const cases = [_]struct { in: []const u8, want: []const u8 }{1791        .{ .in = "25.05.20250115.abcdef (Warbler)", .want = "release-25.05" },1792        .{ .in = "24.11.20241201.deadbee (Vicuna)", .want = "release-24.11" },1793        .{ .in = "25.11pre-git", .want = "master" },1794        .{ .in = "25.05pre789012.abcdef (Warbler)", .want = "master" },1795        .{ .in = "nixos-unstable", .want = "master" },1796        .{ .in = "garbage", .want = "master" },1797    };1798    for (cases) |c| {1799        const got = try homeBranchFromVersion(a, c.in);1800        defer a.free(got);1801        try std.testing.expectEqualStrings(c.want, got);1802    }1803}18041805// The home-manager branch matching the running nixpkgs. Falls back to master1806// when nixos-version is unavailable (non-NixOS host). Caller frees.1807fn detectHomeManagerBranch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]const u8 {1808    const r = capture(gpa, io, machine, &.{"nixos-version"}) catch1809        return gpa.dupe(u8, "master");1810    defer gpa.free(r.stdout);1811    defer gpa.free(r.stderr);1812    if (r.exit_code != 0) return gpa.dupe(u8, "master");1813    return homeBranchFromVersion(gpa, r.stdout);1814}18151816// `nix run home-manager/<branch> -- init [--switch] [dir]` — generates1817// flake.nix + home.nix (in dir, or ~/.config/home-manager by default),1818// activating immediately when switch_on_init is set.1819pub fn homeManagerInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, switch_on_init: bool, dir: ?[]const u8) !u8 {1820    const branch = try detectHomeManagerBranch(gpa, io, machine);1821    defer gpa.free(branch);1822    const flake_ref = try std.fmt.allocPrint(gpa, "home-manager/{s}", .{branch});1823    defer gpa.free(flake_ref);18241825    var argv: std.ArrayList([]const u8) = .empty;1826    defer argv.deinit(gpa);1827    try argv.appendSlice(gpa, &.{ "nix", "run", flake_ref, "--", "init" });1828    if (switch_on_init) try argv.append(gpa, "--switch");1829    if (dir) |d| try argv.append(gpa, d);18301831    return stream(io, machine, gpa, argv.items);1832}18331834pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {1835    output.flush();1836    var argv: std.ArrayList([]const u8) = .empty;1837    defer argv.deinit(gpa);1838    try argv.appendSlice(gpa, &.{ "home-manager", "switch" });1839    try argv.appendSlice(gpa, extra_flags);1840    const r = try capture(gpa, io, machine, argv.items);1841    defer gpa.free(r.stdout);1842    defer gpa.free(r.stderr);1843    errors.setBuildStderr(r.stderr);1844    return r.exit_code;1845}18461847// Outcome of a flake-based switch, so the caller can fall back to a less1848// specific attribute on a missing-attribute evaluation error — but never on a1849// genuine build failure.1850pub const SwitchOutcome = enum { ok, attr_missing, failed };18511852pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8, extra_flags: []const []const u8) !SwitchOutcome {1853    output.flush();1854    var argv: std.ArrayList([]const u8) = .empty;1855    defer argv.deinit(gpa);1856    try argv.appendSlice(gpa, &.{ "home-manager", "switch", "--flake", flake_ref });1857    try argv.appendSlice(gpa, extra_flags);1858    const r = try capture(gpa, io, machine, argv.items);1859    defer gpa.free(r.stdout);1860    defer gpa.free(r.stderr);1861    if (r.exit_code == 0) return .ok;1862    // A flake that doesn't define this homeConfiguration fails during evaluation1863    // with "does not provide attribute" — surface that so the caller can retry a1864    // different attr rather than treating it as a build failure.1865    if (std.mem.indexOf(u8, r.stderr, "does not provide attribute") != null)1866        return .attr_missing;1867    errors.setBuildStderr(r.stderr);1868    return .failed;1869}18701871// home-manager has no system-profile rollback; it re-activates the previous1872// generation via `switch --rollback`.1873pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1874    output.flush();1875    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch", "--rollback" });1876    defer gpa.free(r.stdout);1877    defer gpa.free(r.stderr);1878    errors.setBuildStderr(r.stderr);1879    return r.exit_code;1880}18811882// Build (and validate) the home config without activating it — used by `home1883// check` and `home apply --dry`. `home-manager build` drops a ./result symlink1884// in the cwd, so run it in a throwaway temp dir to avoid littering the directory1885// nina was invoked from.1886pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {1887    output.flush();1888    // extra_flags are passed as real argv elements after the literal `--`, picked1889    // up via "$@" — never interpolated into the script text, so an extra flag1890    // can't smuggle shell metacharacters into the command.1891    var argv: std.ArrayList([]const u8) = .empty;1892    defer argv.deinit(gpa);1893    try argv.appendSlice(gpa, &.{ "sh", "-c", "d=$(mktemp -d) && cd \"$d\" && home-manager build \"$@\"", "--" });1894    try argv.appendSlice(gpa, extra_flags);1895    const r = try capture(gpa, io, machine, argv.items);1896    defer gpa.free(r.stdout);1897    defer gpa.free(r.stderr);1898    errors.setBuildStderr(r.stderr);1899    return r.exit_code;1900}19011902pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1903    const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1904    defer gpa.free(r.stderr);1905    if (r.exit_code != 0) {1906        gpa.free(r.stdout);1907        return error.ProcessFailed;1908    }1909    return r.stdout;1910}19111912// Store paths referenced by a home generation — used to list managed packages.1913pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1914    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1915    defer gpa.free(r.stderr);1916    if (r.exit_code != 0) {1917        gpa.free(r.stdout);1918        return error.ProcessFailed;1919    }1920    return r.stdout;1921}19221923// diff-closures between two arbitrary store paths (home generations), mirroring1924// diffClosures' tty/piped color handling.1925pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1926    if (output.colorEnabled()) {1927        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1928    }1929    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1930    defer gpa.free(r.stdout);1931    defer gpa.free(r.stderr);1932    const cleaned = try stripAnsi(gpa, r.stdout);1933    defer gpa.free(cleaned);1934    output.raw(cleaned);1935    return r.exit_code;1936}19371938// --- Log ---19391940pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1941    const home = environ.get("HOME") orelse return error.FileNotFound;1942    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1943    defer gpa.free(path);1944    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1945    if (last == 0) return content;19461947    // Collect non-empty lines, then keep only the final `last`. Slices point into1948    // `content`, so copy them out before freeing it.1949    var lines: std.ArrayList([]const u8) = .empty;1950    defer lines.deinit(gpa);1951    var it = std.mem.splitScalar(u8, content, '\n');1952    while (it.next()) |line| {1953        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1954        try lines.append(gpa, line);1955    }1956    if (lines.items.len <= last) return content;19571958    var out: std.ArrayList(u8) = .empty;1959    errdefer out.deinit(gpa);1960    for (lines.items[lines.items.len - last ..]) |line| {1961        try out.appendSlice(gpa, line);1962        try out.append(gpa, '\n');1963    }1964    gpa.free(content);1965    return out.toOwnedSlice(gpa);1966}19671968// nina is a one-shot process, so "did the last apply fail this session?" can't1969// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1970// other ~/.nina-* state files. This lets a later successful apply earn the1971// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1972pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1973    const home = environ.get("HOME") orelse return;1974    var buf: [512]u8 = undefined;1975    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1976    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1977    file.close(io);1978}19791980pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1981    const home = environ.get("HOME") orelse return false;1982    var buf: [512]u8 = undefined;1983    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1984    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1985        f.close(io);1986        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1987        return true;1988    } else |_| {1989        return false;1990    }1991}19921993pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1994    const home = environ.get("HOME") orelse return;1995    var path_buf: [512]u8 = undefined;1996    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1997    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1998        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1999    defer file.close(io);2000    const size = file.length(io) catch 0;2001    file.writePositionalAll(io, entry, size) catch {};2002}20032004// --- Update helpers ---20052006// Fetch a URL with curl and return the response body. Caller must free.2007// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.2008pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {2009    const argv = [_][]const u8{2010        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,2011    };2012    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;2013    defer gpa.free(result.stderr);20142015    const marker = "\nHTTP_STATUS:";2016    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {2017        gpa.free(result.stdout);2018        return error.NetworkError;2019    };2020    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");2021    const status = std.fmt.parseInt(u16, status_str, 10) catch {2022        gpa.free(result.stdout);2023        return error.NetworkError;2024    };2025    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }2026    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }2027    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {2028        gpa.free(result.stdout);2029        return e;2030    };2031    gpa.free(result.stdout);2032    return body;2033}20342035// Download a URL to a temp file. Returns the temp path (caller must gpa.free2036// the string AND delete the file once done with it — this only reserves the2037// name and writes the content). mktemp's random suffix keeps the path from2038// being guessable, unlike a fixed name that a shared /tmp lets any local user2039// symlink out from under a self-update.2040pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {2041    const tmp_raw = try captureLocal(gpa, io, &.{ "mktemp", "/tmp/nina-update.XXXXXX" });2042    defer gpa.free(tmp_raw);2043    const tmp_path = try gpa.dupe(u8, std.mem.trim(u8, tmp_raw, " \t\r\n"));2044    errdefer gpa.free(tmp_path);20452046    var child = std.process.spawn(io, .{2047        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },2048        .stdin = .close,2049        .stdout = .close,2050        .stderr = .inherit,2051    }) catch return error.NetworkError;2052    const term = child.wait(io) catch return error.NetworkError;2053    switch (term) {2054        .exited => |c| if (c != 0) return error.NetworkError,2055        else => return error.NetworkError,2056    }2057    return tmp_path;2058}20592060test "downloadToTemp uses a distinct random path per call and can be cleaned up (NINA-004)" {2061    const a = std.testing.allocator;2062    const io = std.testing.io;20632064    var tmp = std.testing.tmpDir(.{});2065    defer tmp.cleanup();20662067    const payload = "nina download fixture payload\n";2068    {2069        const f = try tmp.dir.createFile(io, "source.bin", .{});2070        defer f.close(io);2071        try f.writePositionalAll(io, payload, 0);2072    }20732074    // curl supports file:// URLs, so this exercises the real downloadToTemp2075    // implementation (real mktemp + real curl spawn) without any network.2076    var real_path_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;2077    const real_path_len = try tmp.dir.realPathFile(io, "source.bin", &real_path_buf);2078    const url = try std.fmt.allocPrint(a, "file://{s}", .{real_path_buf[0..real_path_len]});2079    defer a.free(url);20802081    const path1 = try downloadToTemp(a, io, url);2082    defer a.free(path1);2083    defer std.Io.Dir.deleteFileAbsolute(io, path1) catch {};20842085    const path2 = try downloadToTemp(a, io, url);2086    defer a.free(path2);2087    defer std.Io.Dir.deleteFileAbsolute(io, path2) catch {};20882089    // mktemp's random suffix must differ per call — a fixed path is2090    // symlink-clobberable and shared across concurrent self-updates.2091    try std.testing.expect(!std.mem.eql(u8, path1, path2));2092    try std.testing.expect(!std.mem.eql(u8, path1, "/tmp/nina-update.bin"));20932094    try std.testing.expect(pathExists(io, path1));2095    const downloaded = try std.Io.Dir.readFileAlloc(.cwd(), io, path1, a, .unlimited);2096    defer a.free(downloaded);2097    try std.testing.expectEqualStrings(payload, downloaded);20982099    // The caller owns cleanup (see the update command's post-install defer) —2100    // confirm the mktemp'd file is actually removable and gone afterward.2101    try std.Io.Dir.deleteFileAbsolute(io, path1);2102    try std.testing.expect(!pathExists(io, path1));2103}21042105// Get the current executable path into buf. Returns slice of buf.2106pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {2107    const len = try std.process.executablePath(io, buf);2108    return buf[0..len];2109}21102111// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then2112// atomically install the binary to install_path. Errors: ChecksumMismatch,2113// AccessDenied (with error_info set), or underlying I/O errors.2114pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {2115    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {2116        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});2117        return error.FileNotFound;2118    };2119    defer gpa.free(bytes);21202121    var hasher = std.crypto.hash.Blake3.init(.{});2122    hasher.update(bytes);2123    var raw: [32]u8 = undefined;2124    hasher.final(&raw);2125    const hex = std.fmt.bytesToHex(raw, .lower);2126    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;21272128    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;2129    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch2130        return error.NameTooLong;21312132    {2133        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {2134            errors.error_info.setMessage("cannot write to {s}", .{install_path});2135            errors.error_info.setSuggestion("try: sudo nina update", .{});2136            return error.AccessDenied;2137        };2138        defer f.close(io);2139        f.writePositionalAll(io, bytes, 0) catch {2140            errors.error_info.setMessage("cannot write to {s}", .{install_path});2141            return error.AccessDenied;2142        };2143        try f.setPermissions(io, .fromMode(0o755));2144    }2145    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};21462147    if (comptime builtin.os.tag == .macos) {2148        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};2149    }21502151    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {2152        error.AccessDenied => {2153            errors.error_info.setMessage("cannot replace {s}", .{install_path});2154            errors.error_info.setSuggestion("try: sudo nina update", .{});2155            return error.AccessDenied;2156        },2157        else => return e,2158    };2159}21602161// --- Nix feature setup ---21622163pub const NixFeatureStatus = struct {2164    nix_command: bool = false,2165    flakes: bool = false,21662167    pub fn allEnabled(self: NixFeatureStatus) bool {2168        return self.nix_command and self.flakes;2169    }2170};21712172fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {2173    var lines = std.mem.splitScalar(u8, conf, '\n');2174    while (lines.next()) |line| {2175        const trimmed = std.mem.trim(u8, line, " \t");2176        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;2177        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;2178        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;2179    }2180}21812182pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {2183    var status = NixFeatureStatus{};21842185    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {2186        defer gpa.free(conf);2187        scanConfFeatures(conf, &status);2188    }21892190    if (environ.get("HOME")) |home| {2191        var buf: [512]u8 = undefined;2192        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;2193        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {2194            defer gpa.free(conf);2195            scanConfFeatures(conf, &status);2196        }2197    }21982199    return status;2200}22012202pub fn isNixOS(io: std.Io) bool {2203    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;2204    file.close(io);2205    return true;2206}22072208// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.2209// Returns the path written (caller must free).2210pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {2211    const home = environ.get("HOME") orelse {2212        errors.error_info.setMessage("HOME not set", .{});2213        return error.ConfigNotFound;2214    };22152216    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});2217    defer gpa.free(dir_path);2218    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});2219    errdefer gpa.free(file_path);22202221    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};22222223    const line = "experimental-features = nix-command flakes\n";2224    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch2225        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {2226        errors.error_info.setMessage("could not write {s}", .{file_path});2227        return error.FileNotFound;2228    });2229    defer file.close(io);22302231    const size = file.length(io) catch 0;2232    file.writePositionalAll(io, line, size) catch {2233        errors.error_info.setMessage("could not write {s}", .{file_path});2234        return error.FileNotFound;2235    };22362237    return file_path;2238}22392240// --- NixOS: declarative experimental-features ---2241//2242// On NixOS the permanent, declarative home for these flags is configuration.nix,2243// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves2244// the `nixos-rebuild switch` to the user.22452246pub const NIXOS_FEATURES_LINE =2247    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";22482249// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns2250// false on any read error so the caller still offers to add the line.2251pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {2252    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;2253    defer gpa.free(conf);2254    return std.mem.indexOf(u8, conf, "experimental-features") != null and2255        std.mem.indexOf(u8, conf, "nix-command") != null and2256        std.mem.indexOf(u8, conf, "flakes") != null;2257}22582259fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {2260    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;2261    return captureLocal(gpa, io, &.{ "sudo", "cat", path });2262}22632264// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix2265// (i.e. inside the top-level attribute set) and write it back via a single2266// `sudo cp`, which prompts for the password on the terminal. Returns an error2267// for the caller to fall back to printed manual instructions.2268pub fn appendFeaturesToNixosConfig(2269    gpa: std.mem.Allocator,2270    io: std.Io,2271    environ: *const std.process.Environ.Map,2272    path: []const u8,2273) !void {2274    const conf = readMaybeSudo(gpa, io, path) catch {2275        errors.error_info.setMessage("could not read {s}", .{path});2276        return error.ConfigNotFound;2277    };2278    defer gpa.free(conf);22792280    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared22812282    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {2283        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});2284        return error.MalformedConfig;2285    };22862287    const home = environ.get("HOME") orelse {2288        errors.error_info.setMessage("HOME not set", .{});2289        return error.ConfigNotFound;2290    };2291    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});2292    defer gpa.free(tmp_path);22932294    var buf: std.ArrayList(u8) = .empty;2295    defer buf.deinit(gpa);2296    try buf.appendSlice(gpa, conf[0..brace]);2297    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');2298    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");2299    try buf.appendSlice(gpa, "  ");2300    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);2301    try buf.append(gpa, '\n');2302    try buf.appendSlice(gpa, conf[brace..]);23032304    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {2305        errors.error_info.setMessage("could not write {s}", .{tmp_path});2306        return error.FileNotFound;2307    };2308    tmp.writePositionalAll(io, buf.items, 0) catch {2309        tmp.close(io);2310        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2311        errors.error_info.setMessage("could not write {s}", .{tmp_path});2312        return error.FileNotFound;2313    };2314    tmp.close(io);23152316    // Back up the existing config, then replace it — in one sudo call so the2317    // password is asked for at most once. Paths travel as positional args ($0,2318    // $1) to sidestep shell quoting.2319    const code = streamLocal(io, &.{2320        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,2321    }) catch {2322        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2323        errors.error_info.setMessage("could not write {s}", .{path});2324        return error.ProcessFailed;2325    };2326    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2327    if (code != 0) {2328        errors.error_info.setMessage("sudo cp into {s} failed", .{path});2329        return error.ProcessFailed;2330    }2331}