exec.zig

97.0 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);292293    // NINA-010: the runner script's `$1` (the hook path) must be quoted — a294    // hook whose path contains a space used to word-split and fail to run.295    const spaced_script =296        \\#!/bin/sh297        \\echo spaced hook ran298        \\exit 0299        \\300    ;301    {302        const file = try hook_dir.createFile(io, "post apply", .{});303        defer file.close(io);304        try file.writePositionalAll(io, spaced_script, 0);305        try file.setPermissions(io, .fromMode(0o755));306    }307    const spaced = try runHook(a, io, &env, "post apply");308    defer a.free(spaced.output);309    try std.testing.expectEqual(HookResult.ok, spaced.result);310    try std.testing.expect(std.mem.indexOf(u8, spaced.output, "spaced hook ran") != null);311}312313// Single-quote-wrap `arg` for a POSIX shell, escaping embedded single quotes as314// '\''. ssh joins its trailing command arguments with spaces and hands the315// result to the remote login shell for re-parsing, so passing nina's argv316// through unquoted lets a package name, config path, or channel URL containing317// shell metacharacters or spaces be word-split or executed on the remote host.318fn shellQuote(gpa: std.mem.Allocator, arg: []const u8) ![]u8 {319    var out: std.ArrayList(u8) = .empty;320    try out.append(gpa, '\'');321    for (arg) |ch| {322        if (ch == '\'') {323            try out.appendSlice(gpa, "'\\''");324        } else {325            try out.append(gpa, ch);326        }327    }328    try out.append(gpa, '\'');329    return out.toOwnedSlice(gpa);330}331332fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {333    if (machine.local) return cmd;334335    const host = machine.host orelse {336        errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});337        return error.SshFailed;338    };339340    var ssh: std.ArrayList([]const u8) = .empty;341    try ssh.append(gpa, "ssh");342    try ssh.append(gpa, "-o");343    try ssh.append(gpa, "BatchMode=yes");344    try ssh.append(gpa, "-o");345    try ssh.append(gpa, "StrictHostKeyChecking=accept-new");346    if (machine.ssh_key) |key| {347        try ssh.append(gpa, "-i");348        try ssh.append(gpa, key);349    }350    const addr = if (machine.user) |u|351        try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })352    else353        try gpa.dupe(u8, host);354    try ssh.append(gpa, addr);355356    // Quote every word and join into one ssh argument, so ssh has nothing left357    // to re-join with spaces — the remote shell receives exactly our argv.358    var quoted_cmd: std.ArrayList(u8) = .empty;359    for (cmd, 0..) |arg, i| {360        if (i > 0) try quoted_cmd.append(gpa, ' ');361        const q = try shellQuote(gpa, arg);362        defer gpa.free(q);363        try quoted_cmd.appendSlice(gpa, q);364    }365    try ssh.append(gpa, try quoted_cmd.toOwnedSlice(gpa));366    return ssh.toOwnedSlice(gpa);367}368369test "shellQuote round-trips metacharacters through a real shell" {370    const a = std.testing.allocator;371    const io = std.testing.io;372373    const dangerous = [_][]const u8{374        "foo;reboot",375        "foo && rm -rf /",376        "has space",377        "quo'te",378        "$(whoami)",379        "`whoami`",380        "a|b>c<d",381    };382383    for (dangerous) |arg| {384        const quoted = try shellQuote(a, arg);385        defer a.free(quoted);386387        // A shell asked to print out the quoted word verbatim must reproduce388        // exactly the original string, byte for byte — proving the metacharacters389        // stayed inert instead of being word-split or executed.390        const script = try std.fmt.allocPrint(a, "printf '%s' {s}", .{quoted});391        defer a.free(script);392393        const r = try std.process.run(a, io, .{ .argv = &.{ "sh", "-c", script } });394        defer a.free(r.stdout);395        defer a.free(r.stderr);396397        try std.testing.expectEqual(@as(u8, 0), switch (r.term) {398            .exited => |c| c,399            else => 1,400        });401        try std.testing.expectEqualStrings(arg, r.stdout);402    }403}404405test "buildArgv joins a remote command into a single quoted ssh argument" {406    const a = std.testing.allocator;407408    const machine: types.Machine = .{409        .name = "box",410        .local = false,411        .host = "example.com",412        .user = "june",413    };414415    const argv = try buildArgv(a, &machine, &.{ "nix-env", "-iA", "foo;reboot" });416    defer {417        // Indices 5 (addr) and 6 (the joined quoted command) are the only418        // gpa-owned strings; the rest are literals baked into buildArgv.419        a.free(@constCast(argv[5]));420        a.free(@constCast(argv[6]));421        a.free(argv);422    }423424    // Everything after the ssh destination must collapse into exactly one425    // argument — if ssh received the dangerous word as its own separate426    // argument, it would rejoin it with spaces for the remote shell to427    // re-parse, defeating the quoting.428    try std.testing.expectEqualStrings("ssh", argv[0]);429    try std.testing.expectEqualStrings("[email protected]", argv[5]);430    try std.testing.expectEqual(@as(usize, 7), argv.len);431    try std.testing.expectEqualStrings("'nix-env' '-iA' 'foo;reboot'", argv[6]);432}433434// --- NixOS rebuild ---435436// True if the machine's config dir holds a flake.nix. Only meaningful for a local437// machine — the file lives on the local filesystem. Remote flake detection would438// need an ssh round-trip; a remote flake at the default /etc/nixos needs no flag439// anyway, so we don't bother.440// True if `dir` contains a flake.nix (local filesystem check).441pub fn dirHasFlake(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) bool {442    const flake_path = std.fs.path.join(gpa, &.{ dir, "flake.nix" }) catch return false;443    defer gpa.free(flake_path);444    return pathExists(io, flake_path);445}446447pub fn configHasFlake(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {448    if (!machine.local) return false;449    return dirHasFlake(gpa, io, machine.config_path);450}451452// nixos-rebuild auto-detects /etc/nixos/flake.nix, so the --flake flag is only453// needed when the flake lives elsewhere. A flake at a non-default path must be454// passed explicitly or nixos-rebuild falls back to channels. Compare with455// trailing slashes trimmed so "/etc/nixos/" is still treated as the default.456fn useFlakeFlag(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {457    if (!configHasFlake(gpa, io, machine)) return false;458    var path = machine.config_path;459    while (path.len > 1 and path[path.len - 1] == '/') path = path[0 .. path.len - 1];460    return !std.mem.eql(u8, path, "/etc/nixos");461}462463// Capture nixos-rebuild stderr for the translation pipeline. Raw nix build464// output is suppressed; on failure, reportError() translates stderr via465// errors.translateError(). The substep line above the call tells the user what466// is running; silence during the build is intentional per the error-wrapping brief.467fn nixosRebuildRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, flake: bool, extra_flags: []const []const u8) !u8 {468    var argv: std.ArrayList([]const u8) = .empty;469    defer argv.deinit(gpa);470    try argv.appendSlice(gpa, &.{ "sudo", "nixos-rebuild", verb });471    if (flake) try argv.appendSlice(gpa, &.{ "--flake", machine.config_path });472    try argv.appendSlice(gpa, extra_flags);473474    output.flush();475    const r = try capture(gpa, io, machine, argv.items);476    defer gpa.free(r.stdout);477    defer gpa.free(r.stderr);478    errors.setBuildStderr(r.stderr);479    return r.exit_code;480}481482pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {483    const flake = useFlakeFlag(gpa, io, machine);484    if (flake) {485        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});486    } else {487        output.printSubstep("nixos-rebuild switch", .{});488    }489    return nixosRebuildRun(io, machine, gpa, "switch", flake, extra_flags);490}491492// Live-streaming variant used by `apply` when stdout is a TTY. Each stderr line493// from nixos-rebuild is fed to the build panel for real-time progress display494// while the full stderr is also accumulated for the error translation pipeline.495// Falls back to the silent capture path when not a TTY.496pub fn nixosRebuildSwitchWithPanel(497    io: std.Io,498    machine: *const types.Machine,499    gpa: std.mem.Allocator,500    panel: *output.BuildPanel,501    extra_flags: []const []const u8,502) !u8 {503    const flake = useFlakeFlag(gpa, io, machine);504    if (flake) {505        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});506    } else {507        output.printSubstep("nixos-rebuild switch", .{});508    }509    if (!output.colorEnabled()) return nixosRebuildRun(io, machine, gpa, "switch", flake, extra_flags);510    return nixosRebuildRunStreamed(io, machine, gpa, "switch", flake, panel, extra_flags);511}512513// Spawn argv with stderr piped, feed each line to the build panel for live progress,514// and accumulate the full stderr (newlines preserved) for errors.translateError.515// Factored out of nixosRebuildRunStreamed so the read loop is testable without a516// real nixos-rebuild binary.517fn runStreamedCapture(io: std.Io, gpa: std.mem.Allocator, argv: []const []const u8, panel: *output.BuildPanel) !u8 {518    var child = std.process.spawn(io, .{519        .argv = argv,520        .stdin = .ignore,521        .stdout = .ignore,522        .stderr = .pipe,523    }) catch |e| {524        errors.error_info.setMessage("failed to spawn nixos-rebuild", .{});525        return e;526    };527528    var accumulated: std.ArrayList(u8) = .empty;529    defer accumulated.deinit(gpa);530531    if (child.stderr) |stderr_file| {532        var reader_buf: [8192]u8 = undefined;533        var fr = std.Io.File.Reader.initStreaming(stderr_file, io, &reader_buf);534        while (true) {535            const raw = fr.interface.takeDelimiter('\n') catch |err| switch (err) {536                // A single line exceeded the reader's buffer — routine for nix eval537                // traces/derivation lists. Discard the oversized remainder instead of538                // abandoning the pipe: breaking here would leave stderr undrained, and539                // once the kernel pipe buffer filled the child would block on write()540                // forever, hanging child.wait() below.541                error.StreamTooLong => {542                    _ = fr.interface.discardDelimiterInclusive('\n') catch break;543                    continue;544                },545                error.ReadFailed => break,546            } orelse break;547            // takeDelimiter excludes the delimiter, so re-add it or every downstream548            // line-oriented consumer in errors.zig sees one giant concatenated line.549            accumulated.appendSlice(gpa, raw) catch {};550            accumulated.append(gpa, '\n') catch {};551            const line = std.mem.trimEnd(u8, raw, "\r");552            panel.update(line);553            panel.render();554        }555    }556557    errors.setBuildStderr(accumulated.items);558559    const term = child.wait(io) catch |e| {560        errors.error_info.setMessage("nixos-rebuild wait failed", .{});561        return e;562    };563    return switch (term) {564        .exited => |code| code,565        else => 1,566    };567}568569fn nixosRebuildRunStreamed(570    io: std.Io,571    machine: *const types.Machine,572    gpa: std.mem.Allocator,573    verb: []const u8,574    flake: bool,575    panel: *output.BuildPanel,576    extra_flags: []const []const u8,577) !u8 {578    var argv_list: std.ArrayList([]const u8) = .empty;579    defer argv_list.deinit(gpa);580    try argv_list.appendSlice(gpa, &.{ "sudo", "nixos-rebuild", verb });581    if (flake) try argv_list.appendSlice(gpa, &.{ "--flake", machine.config_path });582    try argv_list.appendSlice(gpa, extra_flags);583584    output.flush();585    const built_argv = try buildArgv(gpa, machine, argv_list.items);586    defer if (!machine.local) gpa.free(built_argv);587588    return runStreamedCapture(io, gpa, built_argv, panel);589}590591test "runStreamedCapture preserves newlines and survives an oversized stderr line (NINA-001/002)" {592    const a = std.testing.allocator;593    const io = std.testing.io;594595    // panel.render() writes through output's global writer, which only main.zig596    // initializes in real runs. Point it at a discard sink with color off so the597    // test exercises the real render() call path without a live terminal.598    var discard_buf: [256]u8 = undefined;599    var discarding: std.Io.Writer.Discarding = .init(&discard_buf);600    var env: std.process.Environ.Map = .init(a);601    defer env.deinit();602    output.init(&discarding.writer, io, &env, false);603604    var panel: output.BuildPanel = .{};605606    // A single stderr line over 8192 bytes (the reader's fixed buffer size) used to607    // trip error.StreamTooLong and abandon the pipe (NINA-002); it must now be608    // discarded and draining must continue for the lines that follow.609    var oversized: [9000]u8 = undefined;610    @memset(&oversized, 'x');611612    const script = try std.fmt.allocPrint(a,613        \\exec >&2614        \\printf 'these 3 paths will be fetched (12.3 MiB download, 45.6 MiB unpacked)\n'615        \\printf '%s\n' "{s}"616        \\printf 'error: nina test canary xyz-explanation\n'617        \\printf 'For full logs, run some-command\n'618        \\exit 1619    , .{oversized});620    defer a.free(script);621622    const exit_code = try runStreamedCapture(io, a, &.{ "sh", "-c", script }, &panel);623    try std.testing.expectEqual(@as(u8, 1), exit_code);624625    const stderr = errors.getBuildStderr();626    // Newlines must survive accumulation (NINA-001) — without them, every627    // line-oriented consumer downstream (innermostError, extractLocation,628    // extractWarnings) sees one giant concatenated line instead of real lines.629    try std.testing.expect(std.mem.indexOf(u8, stderr, "error: nina test canary xyz-explanation\n") != null);630631    // translateError's returned strings are a mix of literals and heap allocations632    // depending which layer matched; an arena sidesteps the ownership ambiguity.633    var arena = std.heap.ArenaAllocator.init(a);634    defer arena.deinit();635    const translated = errors.translateError(arena.allocator(), stderr);636    // Must reach Layer 2's structured extraction (innermostError needs a trimmed637    // line starting with "error:") rather than falling through to the generic638    // Layer-3 fallback, which is only reachable when line structure is lost.639    try std.testing.expect(!std.mem.eql(u8, translated.body, "something went wrong that nina couldn't translate."));640}641642pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {643    return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine), extra_flags);644}645646pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {647    return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine), extra_flags);648}649650// --- Generations ---651652// Read system-profile generations WITHOUT root. `nix-env --list-generations -p653// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user654// ("system.lock: Permission denied"). The generation symlinks themselves are655// world-readable, so list them directly: parse `system-N-link` names, take each656// link's own mtime for the date/time, and mark the one the `system` symlink657// points at as current. Output matches the `nix-env --list-generations` columns658// (num date time [current]) so parseGenerations is unchanged.659const GEN_LIST_SCRIPT =660    \\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 }'661;662663pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {664    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });665    defer gpa.free(r.stderr);666    defer gpa.free(r.stdout);667    if (r.exit_code != 0) return error.ProcessFailed;668    return parseGenerations(gpa, r.stdout);669}670671fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {672    var gens: std.ArrayList(types.GenerationInfo) = .empty;673    var lines = std.mem.splitScalar(u8, output_str, '\n');674    while (lines.next()) |line| {675        const trimmed = std.mem.trim(u8, line, " \t");676        if (trimmed.len == 0) continue;677        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");678        const num_str = parts.next() orelse continue;679        const date_str = parts.next() orelse continue;680        const time_str = parts.next() orelse continue;681        const rest = parts.rest();682        const current = std.mem.indexOf(u8, rest, "current") != null;683        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;684        try gens.append(gpa, .{685            .number = num,686            .date = try gpa.dupe(u8, date_str),687            .time = try gpa.dupe(u8, time_str),688            .current = current,689        });690    }691    return gens.toOwnedSlice(gpa);692}693694pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {695    const gens = try getGenerations(gpa, io, machine);696    defer gpa.free(gens);697    for (gens) |g| {698        if (g.current) return g.number;699    }700    return 0;701}702703pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {704    // Switch the system profile to generation n, then activate it (bootloader +705    // services). Without switch-to-configuration the change isn't applied.706    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 });707    defer gpa.free(cmd);708    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });709}710711pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {712    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });713}714715pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {716    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});717    defer gpa.free(n_str);718    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });719}720721pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {722    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });723}724725// --- Garbage collection ---726727pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {728    if (delete_old) {729        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });730    }731    // Keep the `keep` most recent system generations (+N deletes all but N),732    // then collect now-unreferenced store paths. `--delete-older-than` wants a733    // duration (e.g. 14d), not a generation count.734    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });735    defer gpa.free(cmd);736    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });737}738739// --- Channels ---740741pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {742    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });743    defer gpa.free(r.stderr);744    defer gpa.free(r.stdout);745    if (r.exit_code != 0) return error.ProcessFailed;746    return parseChannels(gpa, r.stdout);747}748749fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {750    var channels: std.ArrayList(types.ChannelInfo) = .empty;751    var lines = std.mem.splitScalar(u8, output_str, '\n');752    while (lines.next()) |line| {753        const trimmed = std.mem.trim(u8, line, " \t\r");754        if (trimmed.len == 0) continue;755        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;756        try channels.append(gpa, .{757            .name = try gpa.dupe(u8, trimmed[0..space]),758            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),759        });760    }761    return channels.toOwnedSlice(gpa);762}763764pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {765    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });766}767768pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {769    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });770}771772pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {773    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });774}775776// --- Services ---777778pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {779    const cmd: []const []const u8 = if (user)780        &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }781    else782        &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };783    const r = try capture(gpa, io, machine, cmd);784    defer gpa.free(r.stderr);785    defer gpa.free(r.stdout);786    if (r.exit_code != 0) return error.ProcessFailed;787    return parseServices(gpa, r.stdout);788}789790fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {791    var svcs: std.ArrayList(types.ServiceInfo) = .empty;792    var lines = std.mem.splitScalar(u8, output_str, '\n');793    while (lines.next()) |line| {794        const trimmed = std.mem.trim(u8, line, " \t\r");795        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines796        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");797        const name = parts.next() orelse continue;798        _ = parts.next(); // load799        const active_str = parts.next() orelse continue;800        const sub_str = parts.next() orelse "unknown";801802        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))803            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)804        else if (std.mem.eql(u8, active_str, "failed"))805            .failed806        else807            .inactive;808809        try svcs.append(gpa, .{810            .name = try gpa.dupe(u8, name),811            .state = state,812            .uptime = null,813        });814    }815    return svcs.toOwnedSlice(gpa);816}817818pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {819    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.820    // User services run under the caller's own systemd manager, so no sudo.821    if (user) {822        return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });823    }824    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });825}826827pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {828    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});829    defer gpa.free(n_str);830    if (user) {831        if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });832        return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });833    }834    if (follow) {835        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });836    }837    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });838}839840// --- Profile ---841842// Stream with one extra environment variable injected alongside the inherited env.843// Used for cases like NIXPKGS_ALLOW_UNFREE=1 where we need a single override844// without replacing the full parent environment.845fn 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 {846    output.flush();847    const argv = try buildArgv(gpa, machine, cmd);848    defer if (!machine.local) gpa.free(argv);849850    var env = try base_env.clone(gpa);851    defer env.deinit();852    try env.put(key, val);853854    var child = std.process.spawn(io, .{855        .argv = argv,856        .stdin = .inherit,857        .stdout = .inherit,858        .stderr = .inherit,859        .environ_map = &env,860    }) catch |e| {861        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});862        return e;863    };864865    const term = child.wait(io) catch |e| {866        errors.error_info.setMessage("process wait failed", .{});867        return e;868    };869870    return switch (term) {871        .exited => |c| c,872        else => 1,873    };874}875876pub 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 {877    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});878    defer gpa.free(pkg_ref);879    // `nix profile add` is the current verb; `install` is a deprecated alias that880    // prints a warning on modern nix.881    if (allow_unfree) {882        // The package is unfree and the user's system-wide allowUnfree setting883        // doesn't propagate to imperative nix commands. Pass NIXPKGS_ALLOW_UNFREE=1884        // and --impure so the profile add succeeds: --impure allows builtins.getEnv885        // to read the env var inside the nixpkgs flake's pure evaluation context.886        return streamWithEnvVar(io, machine, gpa, &.{ "nix", "profile", "add", "--impure", pkg_ref }, environ, "NIXPKGS_ALLOW_UNFREE", "1");887    }888    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });889}890891pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {892    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not893    // by flake ref — passing nixpkgs#ripgrep matches nothing.894    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });895}896897pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {898    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });899    defer gpa.free(r.stderr);900    if (r.exit_code != 0) return error.ProcessFailed;901    return r.stdout;902}903904// Machine-readable profile listing — caller parses elements -> name + version.905pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {906    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });907    defer gpa.free(r.stderr);908    if (r.exit_code != 0) {909        gpa.free(r.stdout);910        return error.ProcessFailed;911    }912    return r.stdout;913}914915// Returns the profile element name to pass to `nix profile remove/upgrade`916// (e.g. "nina" or "default"), or null if nina is not found. Caller owns the917// returned slice. A NixOS system-package install also resolves into /nix/store918// so the store path alone can't distinguish it from a profile install — the919// profile list can. A missing/empty profile (or no nix) returns null.920pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {921    const js = profileListJson(gpa, io, machine) catch return null;922    defer gpa.free(js);923    return profileJsonNinaElement(gpa, js);924}925926927pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {928    const name = profileNinaElement(gpa, io, machine) orelse return false;929    gpa.free(name);930    return true;931}932933// True when a nix store path belongs to the nina package. Store paths have the934// form /nix/store/<32-char-hash>-<pname>-<version>[/<subpath>]. We check that935// the 33 chars after /nix/store/ are the hash+dash, and the pname that follows936// is exactly "nina" (followed by "-" or end-of-component).937fn storePathIsNina(path: []const u8) bool {938    const prefix = "/nix/store/";939    if (!std.mem.startsWith(u8, path, prefix)) return false;940    const rel = path[prefix.len..];941    // The store entry name ends at the first "/" (if any sub-path follows).942    const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];943    if (entry.len < 34) return false; // 32-char hash + dash + at least one char944    const pname_ver = entry[33..]; // skip hash + dash945    return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");946}947948// Pure parse of `nix profile list --json` for a nina element, returning its949// element name (the key to pass to `nix profile remove/upgrade`) or null.950// Newer nix (2.18+) keys elements by pname ("nina"). Older nix uses an array951// with an "attrPath" field. Tarball installs via the `default` output may use952// the key "default" instead of "nina"; we detect those via storePaths.953fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {954    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;955    defer parsed.deinit();956    const root = parsed.value;957    if (root != .object) return null;958    const elements = root.object.get("elements") orelse return null;959    switch (elements) {960        .object => |obj| {961            // Fast path: exact "nina" key (nix 2.18+ with nixpkgs#nina install).962            if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;963            // Fallback: scan storePaths. Handles tarball installs where the default964            // output is selected and nix names the element "default" (older nix) or965            // some other key derived from the attrPath rather than the pname.966            var it = obj.iterator();967            while (it.next()) |kv| {968                const val = kv.value_ptr.*;969                if (val != .object) continue;970                const sps = val.object.get("storePaths") orelse continue;971                if (sps != .array) continue;972                for (sps.array.items) |sp| {973                    if (sp == .string and storePathIsNina(sp.string))974                        return gpa.dupe(u8, kv.key_ptr.*) catch null;975                }976            }977            return null;978        },979        .array => |arr| {980            // Older nix array format. Element name is the last component of attrPath.981            for (arr.items) |el| {982                if (el != .object) continue;983                const ap = el.object.get("attrPath") orelse continue;984                if (ap != .string) continue;985                if (std.mem.eql(u8, ap.string, "nina") or986                    std.mem.endsWith(u8, ap.string, ".nina"))987                    return gpa.dupe(u8, "nina") catch null;988                // Tarball default-output install: attrPath ends in ".default" but989                // storePaths point to nina. Return "default" as the element name.990                const sps = el.object.get("storePaths") orelse continue;991                if (sps != .array) continue;992                for (sps.array.items) |sp| {993                    if (sp != .string) continue;994                    if (!storePathIsNina(sp.string)) continue;995                    const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;996                    const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;997                    return gpa.dupe(u8, el_name) catch null;998                }999            }1000            return null;1001        },1002        else => return null,1003    }1004}10051006test "profileJsonNinaElement finds element name from profile JSON" {1007    const a = std.testing.allocator;10081009    // Newer nix: elements keyed by pname. "nina" key present.1010    const named =1011        \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},1012        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}1013    ;1014    const r1 = profileJsonNinaElement(a, named);1015    defer if (r1) |n| a.free(n);1016    try std.testing.expectEqualStrings("nina", r1.?);10171018    // Tarball install via default output: element keyed as "default", storePath is nina.1019    const default_key =1020        \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}1021    ;1022    const r2 = profileJsonNinaElement(a, default_key);1023    defer if (r2) |n| a.free(n);1024    try std.testing.expectEqualStrings("default", r2.?);10251026    // Decoy: storePath of another package contains "nina" as a substring but is not nina.1027    const decoy =1028        \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}1029    ;1030    const r3 = profileJsonNinaElement(a, decoy);1031    try std.testing.expectEqual(@as(?[]const u8, null), r3);10321033    // Older nix array schema, attrPath ending in ".nina".1034    const arr =1035        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}1036    ;1037    const r4 = profileJsonNinaElement(a, arr);1038    defer if (r4) |n| a.free(n);1039    try std.testing.expectEqualStrings("nina", r4.?);10401041    // Older nix array schema, tarball default-output install.1042    const arr_default =1043        \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}1044    ;1045    const r5 = profileJsonNinaElement(a, arr_default);1046    defer if (r5) |n| a.free(n);1047    try std.testing.expectEqualStrings("default", r5.?);10481049    // Empty / malformed → null.1050    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));1051    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));1052}10531054// The store paths that make up the running system environment. Each reference is1055// a <hash>-<name>-<version> path, so the caller can list system packages with1056// versions — there is no cleaner per-package list for environment.systemPackages.1057pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1058    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });1059    defer gpa.free(r.stderr);1060    if (r.exit_code != 0) {1061        gpa.free(r.stdout);1062        return error.ProcessFailed;1063    }1064    return r.stdout;1065}10661067pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1068    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });1069}10701071// --- Store ---10721073pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1074    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });1075}10761077pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1078    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });1079}10801081// Deduplicate identical store files via hard links — frees space without1082// garbage-collecting any paths.1083pub fn storeOptimise(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1084    return stream(io, machine, gpa, &.{ "nix", "store", "optimise" });1085}10861087pub const SystemStatus = struct { size: []u8, age: []u8 };10881089// One read-only pass for `nina status`: the current system's closure size (a1090// single `path-info -S` of /run/current-system — fast, unlike -S over the whole1091// store) and seconds since the system profile was last switched (its symlink1092// mtime). Both are world-readable; no root needed.1093const STATUS_SCRIPT =1094    \\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} ))"1095;10961097pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {1098    const unknown = SystemStatus{1099        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },1100        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },1101    };1102    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;1103    defer gpa.free(r.stdout);1104    defer gpa.free(r.stderr);1105    if (r.exit_code != 0) return unknown;11061107    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");1108    const sz_str = it.next() orelse return unknown;1109    const age_str = it.next() orelse return unknown;1110    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;1111    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;11121113    gpa.free(unknown.size);1114    gpa.free(unknown.age);1115    return .{1116        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),1117        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),1118    };1119}11201121// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A1122// one-word health signal; exits non-zero when degraded, so we read stdout, not1123// the code. Caller owns the returned slice.1124pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1125    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch1126        return gpa.dupe(u8, "unknown");1127    defer gpa.free(r.stderr);1128    const state = std.mem.trim(u8, r.stdout, " \t\n\r");1129    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");1130    gpa.free(r.stdout);1131    return owned;1132}11331134fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {1135    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});1136    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});1137    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});1138    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});1139}11401141pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1142    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });1143}11441145pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {1146    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)1147    // graph work that takes minutes on a real store (59k+ paths) and hangs the1148    // command. We don't need closures: `--all --json` (no -S) carries each path's1149    // own narSize, so one fast pass gives the path count and the summed store size.1150    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.1151    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.1152    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });1153    defer gpa.free(pi.stdout);1154    defer gpa.free(pi.stderr);11551156    const scan = scanStoreJson(pi.stdout);1157    const total_owned = try humanSize(gpa, scan.total_bytes);11581159    return .{1160        .total_size = total_owned,1161        .live_paths = scan.count,1162        .reclaimable_paths = 0,1163    };1164}11651166const StoreScan = struct { count: u64, total_bytes: u64 };11671168// One linear pass over `nix path-info --json`: each path object has exactly one1169// "narSize": field, so counting them gives the true path count and summing the1170// values gives the total store size — no per-path closure walk.1171fn scanStoreJson(json_str: []const u8) StoreScan {1172    const needle = "\"narSize\":";1173    var count: u64 = 0;1174    var total: u64 = 0;1175    var i: usize = 0;1176    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {1177        var j = pos + needle.len;1178        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}1179        var val: u64 = 0;1180        var any = false;1181        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {1182            val = val * 10 + (json_str[j] - '0');1183            any = true;1184        }1185        if (any) {1186            count += 1;1187            total += val;1188        }1189        i = j;1190    }1191    return .{ .count = count, .total_bytes = total };1192}11931194fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1195    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };1196    var val: f64 = @floatFromInt(bytes);1197    var unit: usize = 0;1198    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1199    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1200    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1201}12021203pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {1204    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the1205    // flake registry), not a flake in the current directory.1206    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});1207    defer gpa.free(expr);1208    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });1209    defer gpa.free(r.stderr);1210    if (r.exit_code != 0) {1211        gpa.free(r.stdout);1212        return error.ProcessFailed;1213    }1214    return r.stdout;1215}12161217// --- Flake ---12181219pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8, extra_flags: []const []const u8) !u8 {1220    var argv: std.ArrayList([]const u8) = .empty;1221    defer argv.deinit(gpa);1222    try argv.appendSlice(gpa, &.{ "nix", "flake", "update" });1223    if (input) |inp| try argv.append(gpa, inp);1224    try argv.appendSlice(gpa, extra_flags);1225    return stream(io, machine, gpa, argv.items);1226}12271228// Update flake inputs for the flake living in `dir` (the config dir). `nix flake1229// update` operates on the flake in the working directory, so we cd there first.1230// Used by `nina upgrade` on a flake system in place of nix-channel --update.1231pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {1232    return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });1233}12341235pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {1236    var argv: std.ArrayList([]const u8) = .empty;1237    defer argv.deinit(gpa);1238    try argv.appendSlice(gpa, &.{ "nix", "flake", "check" });1239    try argv.appendSlice(gpa, extra_flags);1240    return stream(io, machine, gpa, argv.items);1241}12421243pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1244    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });1245}12461247pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1248    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });1249}12501251pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {1252    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });1253}12541255pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1256    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });1257    defer gpa.free(r.stderr);1258    if (r.exit_code != 0) {1259        gpa.free(r.stdout);1260        return error.ProcessFailed;1261    }1262    return r.stdout;1263}12641265// --- Build / Run / Develop ---12661267pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8, extra_flags: []const []const u8) !u8 {1268    var argv: std.ArrayList([]const u8) = .empty;1269    defer argv.deinit(gpa);1270    try argv.append(gpa, "nix");1271    try argv.append(gpa, "build");1272    var ref_buf: ?[]u8 = null;1273    defer if (ref_buf) |r| gpa.free(r);1274    if (attr) |a| {1275        ref_buf = try std.fmt.allocPrint(gpa, ".#{s}", .{a});1276        try argv.append(gpa, ref_buf.?);1277    }1278    try argv.appendSlice(gpa, extra_flags);1279    return stream(io, machine, gpa, argv.items);1280}12811282pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, extra_flags: []const []const u8) !u8 {1283    // nix run always gets --no-write-lock-file for remote URLs1284    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");12851286    var argv: std.ArrayList([]const u8) = .empty;1287    defer argv.deinit(gpa);1288    try argv.append(gpa, "nix");1289    try argv.append(gpa, "run");12901291    var ref_buf: ?[]u8 = null;1292    defer if (ref_buf) |r| gpa.free(r);1293    if (is_url) {1294        try argv.append(gpa, pkg);1295        try argv.append(gpa, "--no-write-lock-file");1296    } else if (std.mem.indexOfScalar(u8, pkg, '#') != null) {1297        // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.1298        try argv.append(gpa, pkg);1299    } else {1300        ref_buf = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1301        try argv.append(gpa, ref_buf.?);1302    }13031304    // extra_flags carries any `-- <program args>` separator verbatim, so this1305    // naturally reconstructs `nix run <ref> -- <args>` — nix's own convention.1306    try argv.appendSlice(gpa, extra_flags);1307    return stream(io, machine, gpa, argv.items);1308}13091310pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1311    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1312    defer gpa.free(ref);1313    return stream(io, machine, gpa, &.{ "nix", "shell", ref });1314}13151316pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {1317    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1318    defer gpa.free(ref);1319    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});1320    defer gpa.free(ps1);1321    if (machine.local) {1322        const rc_path = try createInteractiveShellRc(gpa, io);1323        defer {1324            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1325            gpa.free(rc_path);1326        }1327        return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref, "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, ps1);1328    }1329    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);1330}13311332pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8, extra_flags: []const []const u8) !u8 {1333    if (run_cmd) |cmd| {1334        // sh -c so a multi-word command isn't treated as a single executable name.1335        var argv: std.ArrayList([]const u8) = .empty;1336        defer argv.deinit(gpa);1337        try argv.appendSlice(gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1338        try argv.appendSlice(gpa, extra_flags);1339        return stream(io, machine, gpa, argv.items);1340    }1341    var argv: std.ArrayList([]const u8) = .empty;1342    defer argv.deinit(gpa);1343    try argv.append(gpa, "nix");1344    try argv.append(gpa, "develop");1345    try argv.appendSlice(gpa, extra_flags);1346    return stream(io, machine, gpa, argv.items);1347}13481349pub 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 {1350    if (run_cmd) |cmd| {1351        // sh -c so a multi-word command isn't treated as a single executable name.1352        var argv: std.ArrayList([]const u8) = .empty;1353        defer argv.deinit(gpa);1354        try argv.appendSlice(gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1355        try argv.appendSlice(gpa, extra_flags);1356        return stream(io, machine, gpa, argv.items);1357    }1358    if (machine.local) {1359        const rc_path = try createInteractiveShellRc(gpa, io);1360        defer {1361            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1362            gpa.free(rc_path);1363        }1364        var argv: std.ArrayList([]const u8) = .empty;1365        defer argv.deinit(gpa);1366        try argv.append(gpa, "nix");1367        try argv.append(gpa, "develop");1368        try argv.appendSlice(gpa, extra_flags);1369        try argv.appendSlice(gpa, &.{ "--command", "bash", "--rcfile", rc_path, "-i" });1370        return streamEnv(io, machine, gpa, argv.items, base_env, "(nina: dev) -> ");1371    }1372    var argv: std.ArrayList([]const u8) = .empty;1373    defer argv.deinit(gpa);1374    try argv.append(gpa, "nix");1375    try argv.append(gpa, "develop");1376    try argv.appendSlice(gpa, extra_flags);1377    return streamEnv(io, machine, gpa, argv.items, base_env, "(nina: dev) -> ");1378}13791380pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1381    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });1382}13831384// --- Format ---13851386pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {1387    if (check) {1388        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });1389    }1390    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });1391}13921393// --- Info ---13941395pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1396    const r = try capture(gpa, io, machine, &.{"nixos-version"});1397    defer gpa.free(r.stderr);1398    if (r.exit_code != 0) {1399        gpa.free(r.stdout);1400        return error.ProcessFailed;1401    }1402    return r.stdout;1403}14041405pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1406    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });1407    defer gpa.free(r.stderr);1408    if (r.exit_code != 0) {1409        gpa.free(r.stdout);1410        return error.ProcessFailed;1411    }1412    return r.stdout;1413}14141415pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1416    const r = try capture(gpa, io, machine, &.{"uptime"});1417    defer gpa.free(r.stderr);1418    if (r.exit_code != 0) {1419        gpa.free(r.stdout);1420        return error.ProcessFailed;1421    }1422    return r.stdout;1423}14241425// --- Boot ---14261427pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {1428    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });1429    defer gpa.free(r.stderr);1430    defer gpa.free(r.stdout);1431    if (r.exit_code != 0) return error.ProcessFailed;1432    return parseBootEntries(gpa, r.stdout);1433}14341435fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {1436    var entries: std.ArrayList(types.BootEntry) = .empty;1437    var lines = std.mem.splitScalar(u8, output_str, '\n');1438    while (lines.next()) |line| {1439        const trimmed = std.mem.trim(u8, line, " \t\r");1440        if (std.mem.startsWith(u8, trimmed, "title:")) {1441            const title = std.mem.trim(u8, trimmed[6..], " \t");1442            const current = std.mem.indexOf(u8, title, "(current)") != null;1443            try entries.append(gpa, .{1444                .title = try gpa.dupe(u8, title),1445                .current = current,1446            });1447        }1448    }1449    return entries.toOwnedSlice(gpa);1450}14511452// --- Pkg info ---14531454fn pkgInstallable(gpa: std.mem.Allocator, pkg: []const u8) ![]u8 {1455    return std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1456}14571458fn resolvePkgStorePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, installable: []const u8) ![]u8 {1459    const r = try capture(gpa, io, machine, &.{ "nix", "build", "--no-link", "--print-out-paths", installable });1460    defer gpa.free(r.stderr);1461    defer gpa.free(r.stdout);1462    if (r.exit_code != 0) return error.PackageNotFound;14631464    var lines = std.mem.tokenizeAny(u8, r.stdout, "\r\n");1465    const first_path = lines.next() orelse return error.PackageNotFound;1466    const store_path = std.mem.trim(u8, first_path, " \t");1467    if (store_path.len == 0) return error.PackageNotFound;1468    return gpa.dupe(u8, store_path);1469}14701471pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1472    const installable = try pkgInstallable(gpa, pkg);1473    defer gpa.free(installable);1474    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1475    defer gpa.free(store_path);1476    return stream(io, machine, gpa, &.{ "nix", "why-depends", "/run/current-system", store_path });1477}14781479pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1480    const installable = try pkgInstallable(gpa, pkg);1481    defer gpa.free(installable);1482    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1483    defer gpa.free(store_path);1484    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", store_path });1485}14861487pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {1488    const installable = try pkgInstallable(gpa, pkg);1489    defer gpa.free(installable);1490    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", "--json", installable });1491    defer gpa.free(r.stderr);1492    defer gpa.free(r.stdout);1493    if (r.exit_code != 0) return error.ProcessFailed;14941495    const nar_size = try pathInfoNarSize(gpa, r.stdout);1496    return humanPkgSize(gpa, nar_size);1497}14981499pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1500    const installable = try pkgInstallable(gpa, pkg);1501    defer gpa.free(installable);1502    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1503    defer gpa.free(store_path);1504    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", store_path });1505}15061507fn pathInfoNarSize(gpa: std.mem.Allocator, json_str: []const u8) !u64 {1508    var parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.ProcessFailed;1509    defer parsed.deinit();1510    switch (parsed.value) {1511        .object => |obj| {1512            var it = obj.iterator();1513            while (it.next()) |entry| {1514                if (entry.value_ptr.* == .object) {1515                    if (entry.value_ptr.object.get("narSize")) |v| {1516                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1517                    }1518                }1519            }1520        },1521        .array => |arr| {1522            for (arr.items) |item| {1523                if (item == .object) {1524                    if (item.object.get("narSize")) |v| {1525                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1526                    }1527                }1528            }1529        },1530        else => {},1531    }1532    return error.ProcessFailed;1533}15341535fn humanPkgSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1536    const units = [_][]const u8{ "B", "KiB", "MiB", "GiB", "TiB" };1537    var val: f64 = @floatFromInt(bytes);1538    var unit: usize = 0;1539    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1540    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1541    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1542}15431544test "pathInfoNarSize parses object and array shapes" {1545    try std.testing.expectEqual(@as(u64, 1064629862), try pathInfoNarSize(std.testing.allocator,1546        \\{"/nix/store/abc-ffmpeg":{"narSize":1064629862}}1547    ));1548    try std.testing.expectEqual(@as(u64, 2048), try pathInfoNarSize(std.testing.allocator,1549        \\[{"path":"/nix/store/abc-pkg","narSize":2048}]1550    ));1551}15521553// --- Hash / Fetch ---15541555pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {1556    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });1557    defer gpa.free(r.stderr);1558    if (r.exit_code != 0) {1559        gpa.free(r.stdout);1560        return error.ProcessFailed;1561    }1562    return r.stdout;1563}15641565pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {1566    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });1567    defer gpa.free(r.stderr);1568    if (r.exit_code != 0) {1569        gpa.free(r.stdout);1570        return error.ProcessFailed;1571    }1572    return r.stdout;1573}15741575// --- Pin ---15761577pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {1578    // Stub: full implementation would parse and edit flake.lock JSON1579    // The pin/unpin flow works via nix flake update which regenerates flake.lock1580}15811582pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {1583    if (line) |l| {1584        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});1585        defer gpa.free(line_arg);1586        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });1587    }1588    return stream(io, &types.Machine{}, gpa, &.{ editor, path });1589}15901591// Open a config directory as root with `sudo -E <editor> <path>` — `-E`1592// preserves the user's environment (PATH, TERM, EDITOR config) so the editor1593// behaves the same as it does unprivileged. Used by `nina edit --dir`.1594pub fn openEditorSudo(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8) !u8 {1595    return stream(io, &types.Machine{}, gpa, &.{ "sudo", "-E", editor, path });1596}15971598pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {1599    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});1600    defer gpa.free(a_str);1601    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});1602    defer gpa.free(b_str);1603    // On a tty, the child's own color is fine — stream it directly.1604    if (output.colorEnabled()) {1605        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });1606    }1607    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,1608    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.1609    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });1610    defer gpa.free(r.stdout);1611    defer gpa.free(r.stderr);1612    const cleaned = try stripAnsi(gpa, r.stdout);1613    defer gpa.free(cleaned);1614    output.raw(cleaned);1615    return r.exit_code;1616}16171618// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a1619// child process's color when it writes ANSI unconditionally.1620fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1621    var out: std.ArrayList(u8) = .empty;1622    errdefer out.deinit(gpa);1623    var i: usize = 0;1624    while (i < input.len) {1625        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1626            i += 2;1627            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1628            if (i < input.len) i += 1; // consume the final byte1629            continue;1630        }1631        try out.append(gpa, input[i]);1632        i += 1;1633    }1634    return out.toOwnedSlice(gpa);1635}16361637test "stripAnsi removes CSI color sequences" {1638    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1639    defer std.testing.allocator.free(cleaned);1640    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1641}16421643// --- Doctor checks ---16441645pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1646    var checks: std.ArrayList(types.DoctorCheck) = .empty;16471648    // Check nix daemon1649    {1650        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1651        defer gpa.free(r.stdout);1652        defer gpa.free(r.stderr);1653        const active = std.mem.indexOf(u8, r.stdout, "active") != null;1654        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1655    }16561657    // Check config syntax. Flake-aware like apply/upgrade: on a flake system a1658    // plain `nixos-rebuild dry-build` evaluates <nixpkgs/nixos> + <nixos-config>1659    // (channel style) and fails, so pass --flake when the config dir has one.1660    // No sudo: dry-build only evaluates + builds, it never activates, so it1661    // needs no more privilege than reading the config and talking to the nix1662    // daemon over its (world-writable) socket — unlike switch/activate below.1663    {1664        const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1665            &.{ "nixos-rebuild", "dry-build", "--flake", machine.config_path }1666        else1667            &.{ "nixos-rebuild", "dry-build" };1668        const r = try capture(gpa, io, machine, argv);1669        defer gpa.free(r.stdout);1670        defer gpa.free(r.stderr);1671        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1672    }16731674    // Check channel1675    {1676        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1677        defer gpa.free(r.stdout);1678        defer gpa.free(r.stderr);1679        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1680        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1681    }16821683    return checks.toOwnedSlice(gpa);1684}16851686// --- Home Manager ---1687//1688// Home Manager has three usage modes. nina detects which one is in play before1689// any `home` command so it can either drive the standalone CLI or redirect the1690// user to `nina apply` (when HM is a NixOS/flake module activated by rebuild).16911692pub const HomeManagerMode = enum {1693    // home-manager binary on PATH — manages the user env on its own.1694    standalone,1695    // No binary, but a home.nix exists — HM is a NixOS/flake module rebuilt by1696    // nixos-rebuild. `nina home apply` redirects to `nina apply`.1697    module,1698    none,1699};17001701fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1702    const home = environ.get("HOME") orelse return null;1703    return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1704}17051706// Path to the standalone home.nix. Caller frees.1707pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1708    const dir = homeConfigDir(gpa, environ) orelse return null;1709    defer gpa.free(dir);1710    return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1711}17121713pub fn pathExists(io: std.Io, path: []const u8) bool {1714    const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1715    f.close(io);1716    return true;1717}17181719// `command -v <name>` — true if the binary resolves on PATH. Silent (captured),1720// unlike streamLocal which would inherit stdio.1721// `name` is passed as real argv (positional $1), never interpolated into the1722// script text — only "home-manager" reaches this today, but this is the one1723// place in exec.zig that used to build shell syntax from a parameter.1724fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1725    const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", "command -v \"$1\" >/dev/null 2>&1", "_", name } }) catch return false;1726    defer gpa.free(r.stdout);1727    defer gpa.free(r.stderr);1728    return switch (r.term) {1729        .exited => |code| code == 0,1730        else => false,1731    };1732}17331734pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1735    if (commandExists(gpa, io, "home-manager")) return .standalone;1736    if (homeNixPath(gpa, environ)) |p| {1737        defer gpa.free(p);1738        if (pathExists(io, p)) return .module;1739    }1740    return .none;1741}17421743// The home-manager config dir when it holds a flake.nix (a flake-based home1744// config that `home-manager switch --flake` drives). null for a channel-based1745// config, which uses a plain `home-manager switch`. Caller frees.1746pub fn homeFlakeDir(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1747    const dir = homeConfigDir(gpa, environ) orelse return null;1748    const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch {1749        gpa.free(dir);1750        return null;1751    };1752    defer gpa.free(flake);1753    if (!pathExists(io, flake)) {1754        gpa.free(dir);1755        return null;1756    }1757    return dir;1758}17591760// Platform-specific home-manager attribute "<user>-<arch>-<os>" (e.g.1761// murazaki-x86_64-linux) — the homeConfigurations key many flakes derive from1762// ${USER}-${system}. arch/os come from uname on the local host (home commands1763// are local-only). Caller frees.1764pub fn homeManagerAttr(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, environ: *const std.process.Environ.Map) ![]const u8 {1765    const user = environ.get("USER") orelse "user";17661767    const arch_r = try capture(gpa, io, machine, &.{ "uname", "-m" });1768    defer gpa.free(arch_r.stdout);1769    defer gpa.free(arch_r.stderr);1770    if (arch_r.exit_code != 0) return error.ProcessFailed;1771    const arch = std.mem.trim(u8, arch_r.stdout, " \t\r\n");17721773    const os_r = try capture(gpa, io, machine, &.{ "uname", "-s" });1774    defer gpa.free(os_r.stdout);1775    defer gpa.free(os_r.stderr);1776    if (os_r.exit_code != 0) return error.ProcessFailed;1777    const os = try gpa.dupe(u8, std.mem.trim(u8, os_r.stdout, " \t\r\n"));1778    defer gpa.free(os);1779    for (os) |*ch| ch.* = std.ascii.toLower(ch.*);17801781    if (arch.len == 0 or os.len == 0) return error.ProcessFailed;1782    return std.fmt.allocPrint(gpa, "{s}-{s}-{s}", .{ user, arch, os });1783}17841785// Map a nixos-version string to the matching home-manager branch: an unstable1786// channel ("…pre…"/"unstable") → master; a stable release like1787// "25.05.20250115.abcdef (Warbler)" → release-25.05. Anything unparseable1788// falls back to master. Caller frees.1789fn homeBranchFromVersion(gpa: std.mem.Allocator, version_raw: []const u8) ![]const u8 {1790    const v = std.mem.trim(u8, version_raw, " \t\r\n");1791    if (std.mem.indexOf(u8, v, "pre") != null or1792        std.mem.indexOf(u8, v, "unstable") != null)1793        return gpa.dupe(u8, "master");17941795    const head = v[0 .. std.mem.indexOfScalar(u8, v, ' ') orelse v.len];1796    var it = std.mem.splitScalar(u8, head, '.');1797    const major = it.next() orelse "";1798    const minor = it.next() orelse "";1799    if (allDigits(major) and allDigits(minor))1800        return std.fmt.allocPrint(gpa, "release-{s}.{s}", .{ major, minor });18011802    return gpa.dupe(u8, "master");1803}18041805fn allDigits(s: []const u8) bool {1806    if (s.len == 0) return false;1807    for (s) |ch| if (!std.ascii.isDigit(ch)) return false;1808    return true;1809}18101811test "homeBranchFromVersion maps channels to HM branches" {1812    const a = std.testing.allocator;1813    const cases = [_]struct { in: []const u8, want: []const u8 }{1814        .{ .in = "25.05.20250115.abcdef (Warbler)", .want = "release-25.05" },1815        .{ .in = "24.11.20241201.deadbee (Vicuna)", .want = "release-24.11" },1816        .{ .in = "25.11pre-git", .want = "master" },1817        .{ .in = "25.05pre789012.abcdef (Warbler)", .want = "master" },1818        .{ .in = "nixos-unstable", .want = "master" },1819        .{ .in = "garbage", .want = "master" },1820    };1821    for (cases) |c| {1822        const got = try homeBranchFromVersion(a, c.in);1823        defer a.free(got);1824        try std.testing.expectEqualStrings(c.want, got);1825    }1826}18271828// The home-manager branch matching the running nixpkgs. Falls back to master1829// when nixos-version is unavailable (non-NixOS host). Caller frees.1830fn detectHomeManagerBranch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]const u8 {1831    const r = capture(gpa, io, machine, &.{"nixos-version"}) catch1832        return gpa.dupe(u8, "master");1833    defer gpa.free(r.stdout);1834    defer gpa.free(r.stderr);1835    if (r.exit_code != 0) return gpa.dupe(u8, "master");1836    return homeBranchFromVersion(gpa, r.stdout);1837}18381839// `nix run home-manager/<branch> -- init [--switch] [dir]` — generates1840// flake.nix + home.nix (in dir, or ~/.config/home-manager by default),1841// activating immediately when switch_on_init is set.1842pub fn homeManagerInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, switch_on_init: bool, dir: ?[]const u8) !u8 {1843    const branch = try detectHomeManagerBranch(gpa, io, machine);1844    defer gpa.free(branch);1845    const flake_ref = try std.fmt.allocPrint(gpa, "home-manager/{s}", .{branch});1846    defer gpa.free(flake_ref);18471848    var argv: std.ArrayList([]const u8) = .empty;1849    defer argv.deinit(gpa);1850    try argv.appendSlice(gpa, &.{ "nix", "run", flake_ref, "--", "init" });1851    if (switch_on_init) try argv.append(gpa, "--switch");1852    if (dir) |d| try argv.append(gpa, d);18531854    return stream(io, machine, gpa, argv.items);1855}18561857pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {1858    output.flush();1859    var argv: std.ArrayList([]const u8) = .empty;1860    defer argv.deinit(gpa);1861    try argv.appendSlice(gpa, &.{ "home-manager", "switch" });1862    try argv.appendSlice(gpa, extra_flags);1863    const r = try capture(gpa, io, machine, argv.items);1864    defer gpa.free(r.stdout);1865    defer gpa.free(r.stderr);1866    errors.setBuildStderr(r.stderr);1867    return r.exit_code;1868}18691870// Outcome of a flake-based switch, so the caller can fall back to a less1871// specific attribute on a missing-attribute evaluation error — but never on a1872// genuine build failure.1873pub const SwitchOutcome = enum { ok, attr_missing, failed };18741875pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8, extra_flags: []const []const u8) !SwitchOutcome {1876    output.flush();1877    var argv: std.ArrayList([]const u8) = .empty;1878    defer argv.deinit(gpa);1879    try argv.appendSlice(gpa, &.{ "home-manager", "switch", "--flake", flake_ref });1880    try argv.appendSlice(gpa, extra_flags);1881    const r = try capture(gpa, io, machine, argv.items);1882    defer gpa.free(r.stdout);1883    defer gpa.free(r.stderr);1884    if (r.exit_code == 0) return .ok;1885    // A flake that doesn't define this homeConfiguration fails during evaluation1886    // with "does not provide attribute" — surface that so the caller can retry a1887    // different attr rather than treating it as a build failure.1888    if (std.mem.indexOf(u8, r.stderr, "does not provide attribute") != null)1889        return .attr_missing;1890    errors.setBuildStderr(r.stderr);1891    return .failed;1892}18931894// home-manager has no system-profile rollback; it re-activates the previous1895// generation via `switch --rollback`.1896pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1897    output.flush();1898    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch", "--rollback" });1899    defer gpa.free(r.stdout);1900    defer gpa.free(r.stderr);1901    errors.setBuildStderr(r.stderr);1902    return r.exit_code;1903}19041905// Build (and validate) the home config without activating it — used by `home1906// check` and `home apply --dry`. `home-manager build` drops a ./result symlink1907// in the cwd, so run it in a throwaway temp dir to avoid littering the directory1908// nina was invoked from.1909pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {1910    output.flush();1911    // extra_flags are passed as real argv elements after the literal `--`, picked1912    // up via "$@" — never interpolated into the script text, so an extra flag1913    // can't smuggle shell metacharacters into the command.1914    var argv: std.ArrayList([]const u8) = .empty;1915    defer argv.deinit(gpa);1916    try argv.appendSlice(gpa, &.{ "sh", "-c", "d=$(mktemp -d) && cd \"$d\" && home-manager build \"$@\"", "--" });1917    try argv.appendSlice(gpa, extra_flags);1918    const r = try capture(gpa, io, machine, argv.items);1919    defer gpa.free(r.stdout);1920    defer gpa.free(r.stderr);1921    errors.setBuildStderr(r.stderr);1922    return r.exit_code;1923}19241925pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1926    const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1927    defer gpa.free(r.stderr);1928    if (r.exit_code != 0) {1929        gpa.free(r.stdout);1930        return error.ProcessFailed;1931    }1932    return r.stdout;1933}19341935// Store paths referenced by a home generation — used to list managed packages.1936pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1937    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1938    defer gpa.free(r.stderr);1939    if (r.exit_code != 0) {1940        gpa.free(r.stdout);1941        return error.ProcessFailed;1942    }1943    return r.stdout;1944}19451946// diff-closures between two arbitrary store paths (home generations), mirroring1947// diffClosures' tty/piped color handling.1948pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1949    if (output.colorEnabled()) {1950        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1951    }1952    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1953    defer gpa.free(r.stdout);1954    defer gpa.free(r.stderr);1955    const cleaned = try stripAnsi(gpa, r.stdout);1956    defer gpa.free(cleaned);1957    output.raw(cleaned);1958    return r.exit_code;1959}19601961// --- Log ---19621963pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1964    const home = environ.get("HOME") orelse return error.FileNotFound;1965    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1966    defer gpa.free(path);1967    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1968    if (last == 0) return content;19691970    // Collect non-empty lines, then keep only the final `last`. Slices point into1971    // `content`, so copy them out before freeing it.1972    var lines: std.ArrayList([]const u8) = .empty;1973    defer lines.deinit(gpa);1974    var it = std.mem.splitScalar(u8, content, '\n');1975    while (it.next()) |line| {1976        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1977        try lines.append(gpa, line);1978    }1979    if (lines.items.len <= last) return content;19801981    var out: std.ArrayList(u8) = .empty;1982    errdefer out.deinit(gpa);1983    for (lines.items[lines.items.len - last ..]) |line| {1984        try out.appendSlice(gpa, line);1985        try out.append(gpa, '\n');1986    }1987    gpa.free(content);1988    return out.toOwnedSlice(gpa);1989}19901991// nina is a one-shot process, so "did the last apply fail this session?" can't1992// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1993// other ~/.nina-* state files. This lets a later successful apply earn the1994// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1995pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1996    const home = environ.get("HOME") orelse return;1997    var buf: [512]u8 = undefined;1998    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1999    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;2000    file.close(io);2001}20022003pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {2004    const home = environ.get("HOME") orelse return false;2005    var buf: [512]u8 = undefined;2006    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;2007    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {2008        f.close(io);2009        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};2010        return true;2011    } else |_| {2012        return false;2013    }2014}20152016pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {2017    const home = environ.get("HOME") orelse return;2018    var path_buf: [512]u8 = undefined;2019    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;2020    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch2021        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);2022    defer file.close(io);2023    const size = file.length(io) catch 0;2024    file.writePositionalAll(io, entry, size) catch {};2025}20262027// --- Update helpers ---20282029// Fetch a URL with curl and return the response body. Caller must free.2030// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.2031pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {2032    const argv = [_][]const u8{2033        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,2034    };2035    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;2036    defer gpa.free(result.stderr);20372038    const marker = "\nHTTP_STATUS:";2039    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {2040        gpa.free(result.stdout);2041        return error.NetworkError;2042    };2043    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");2044    const status = std.fmt.parseInt(u16, status_str, 10) catch {2045        gpa.free(result.stdout);2046        return error.NetworkError;2047    };2048    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }2049    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }2050    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {2051        gpa.free(result.stdout);2052        return e;2053    };2054    gpa.free(result.stdout);2055    return body;2056}20572058// Download a URL to a temp file. Returns the temp path (caller must gpa.free2059// the string AND delete the file once done with it — this only reserves the2060// name and writes the content). mktemp's random suffix keeps the path from2061// being guessable, unlike a fixed name that a shared /tmp lets any local user2062// symlink out from under a self-update.2063pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {2064    const tmp_raw = try captureLocal(gpa, io, &.{ "mktemp", "/tmp/nina-update.XXXXXX" });2065    defer gpa.free(tmp_raw);2066    const tmp_path = try gpa.dupe(u8, std.mem.trim(u8, tmp_raw, " \t\r\n"));2067    errdefer gpa.free(tmp_path);20682069    var child = std.process.spawn(io, .{2070        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },2071        .stdin = .close,2072        .stdout = .close,2073        .stderr = .inherit,2074    }) catch return error.NetworkError;2075    const term = child.wait(io) catch return error.NetworkError;2076    switch (term) {2077        .exited => |c| if (c != 0) return error.NetworkError,2078        else => return error.NetworkError,2079    }2080    return tmp_path;2081}20822083test "downloadToTemp uses a distinct random path per call and can be cleaned up (NINA-004)" {2084    const a = std.testing.allocator;2085    const io = std.testing.io;20862087    var tmp = std.testing.tmpDir(.{});2088    defer tmp.cleanup();20892090    const payload = "nina download fixture payload\n";2091    {2092        const f = try tmp.dir.createFile(io, "source.bin", .{});2093        defer f.close(io);2094        try f.writePositionalAll(io, payload, 0);2095    }20962097    // curl supports file:// URLs, so this exercises the real downloadToTemp2098    // implementation (real mktemp + real curl spawn) without any network.2099    var real_path_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;2100    const real_path_len = try tmp.dir.realPathFile(io, "source.bin", &real_path_buf);2101    const url = try std.fmt.allocPrint(a, "file://{s}", .{real_path_buf[0..real_path_len]});2102    defer a.free(url);21032104    const path1 = try downloadToTemp(a, io, url);2105    defer a.free(path1);2106    defer std.Io.Dir.deleteFileAbsolute(io, path1) catch {};21072108    const path2 = try downloadToTemp(a, io, url);2109    defer a.free(path2);2110    defer std.Io.Dir.deleteFileAbsolute(io, path2) catch {};21112112    // mktemp's random suffix must differ per call — a fixed path is2113    // symlink-clobberable and shared across concurrent self-updates.2114    try std.testing.expect(!std.mem.eql(u8, path1, path2));2115    try std.testing.expect(!std.mem.eql(u8, path1, "/tmp/nina-update.bin"));21162117    try std.testing.expect(pathExists(io, path1));2118    const downloaded = try std.Io.Dir.readFileAlloc(.cwd(), io, path1, a, .unlimited);2119    defer a.free(downloaded);2120    try std.testing.expectEqualStrings(payload, downloaded);21212122    // The caller owns cleanup (see the update command's post-install defer) —2123    // confirm the mktemp'd file is actually removable and gone afterward.2124    try std.Io.Dir.deleteFileAbsolute(io, path1);2125    try std.testing.expect(!pathExists(io, path1));2126}21272128// Get the current executable path into buf. Returns slice of buf.2129pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {2130    const len = try std.process.executablePath(io, buf);2131    return buf[0..len];2132}21332134// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then2135// atomically install the binary to install_path. Errors: ChecksumMismatch,2136// AccessDenied (with error_info set), or underlying I/O errors.2137pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {2138    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {2139        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});2140        return error.FileNotFound;2141    };2142    defer gpa.free(bytes);21432144    var hasher = std.crypto.hash.Blake3.init(.{});2145    hasher.update(bytes);2146    var raw: [32]u8 = undefined;2147    hasher.final(&raw);2148    const hex = std.fmt.bytesToHex(raw, .lower);2149    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;21502151    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;2152    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch2153        return error.NameTooLong;21542155    {2156        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {2157            errors.error_info.setMessage("cannot write to {s}", .{install_path});2158            errors.error_info.setSuggestion("try: sudo nina update", .{});2159            return error.AccessDenied;2160        };2161        defer f.close(io);2162        f.writePositionalAll(io, bytes, 0) catch {2163            errors.error_info.setMessage("cannot write to {s}", .{install_path});2164            return error.AccessDenied;2165        };2166        try f.setPermissions(io, .fromMode(0o755));2167    }2168    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};21692170    if (comptime builtin.os.tag == .macos) {2171        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};2172    }21732174    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {2175        error.AccessDenied => {2176            errors.error_info.setMessage("cannot replace {s}", .{install_path});2177            errors.error_info.setSuggestion("try: sudo nina update", .{});2178            return error.AccessDenied;2179        },2180        else => return e,2181    };2182}21832184// --- Nix feature setup ---21852186pub const NixFeatureStatus = struct {2187    nix_command: bool = false,2188    flakes: bool = false,21892190    pub fn allEnabled(self: NixFeatureStatus) bool {2191        return self.nix_command and self.flakes;2192    }2193};21942195fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {2196    var lines = std.mem.splitScalar(u8, conf, '\n');2197    while (lines.next()) |line| {2198        const trimmed = std.mem.trim(u8, line, " \t");2199        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;2200        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;2201        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;2202    }2203}22042205pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {2206    var status = NixFeatureStatus{};22072208    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {2209        defer gpa.free(conf);2210        scanConfFeatures(conf, &status);2211    }22122213    if (environ.get("HOME")) |home| {2214        var buf: [512]u8 = undefined;2215        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;2216        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {2217            defer gpa.free(conf);2218            scanConfFeatures(conf, &status);2219        }2220    }22212222    return status;2223}22242225pub fn isNixOS(io: std.Io) bool {2226    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;2227    file.close(io);2228    return true;2229}22302231// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.2232// Returns the path written (caller must free).2233pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {2234    const home = environ.get("HOME") orelse {2235        errors.error_info.setMessage("HOME not set", .{});2236        return error.ConfigNotFound;2237    };22382239    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});2240    defer gpa.free(dir_path);2241    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});2242    errdefer gpa.free(file_path);22432244    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};22452246    const line = "experimental-features = nix-command flakes\n";2247    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch2248        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {2249        errors.error_info.setMessage("could not write {s}", .{file_path});2250        return error.FileNotFound;2251    });2252    defer file.close(io);22532254    const size = file.length(io) catch 0;2255    file.writePositionalAll(io, line, size) catch {2256        errors.error_info.setMessage("could not write {s}", .{file_path});2257        return error.FileNotFound;2258    };22592260    return file_path;2261}22622263// --- NixOS: declarative experimental-features ---2264//2265// On NixOS the permanent, declarative home for these flags is configuration.nix,2266// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves2267// the `nixos-rebuild switch` to the user.22682269pub const NIXOS_FEATURES_LINE =2270    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";22712272// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns2273// false on any read error so the caller still offers to add the line.2274pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {2275    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;2276    defer gpa.free(conf);2277    return std.mem.indexOf(u8, conf, "experimental-features") != null and2278        std.mem.indexOf(u8, conf, "nix-command") != null and2279        std.mem.indexOf(u8, conf, "flakes") != null;2280}22812282fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {2283    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;2284    return captureLocal(gpa, io, &.{ "sudo", "cat", path });2285}22862287// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix2288// (i.e. inside the top-level attribute set) and write it back via a single2289// `sudo cp`, which prompts for the password on the terminal. Returns an error2290// for the caller to fall back to printed manual instructions.2291pub fn appendFeaturesToNixosConfig(2292    gpa: std.mem.Allocator,2293    io: std.Io,2294    environ: *const std.process.Environ.Map,2295    path: []const u8,2296) !void {2297    const conf = readMaybeSudo(gpa, io, path) catch {2298        errors.error_info.setMessage("could not read {s}", .{path});2299        return error.ConfigNotFound;2300    };2301    defer gpa.free(conf);23022303    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared23042305    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {2306        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});2307        return error.MalformedConfig;2308    };23092310    const home = environ.get("HOME") orelse {2311        errors.error_info.setMessage("HOME not set", .{});2312        return error.ConfigNotFound;2313    };2314    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});2315    defer gpa.free(tmp_path);23162317    var buf: std.ArrayList(u8) = .empty;2318    defer buf.deinit(gpa);2319    try buf.appendSlice(gpa, conf[0..brace]);2320    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');2321    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");2322    try buf.appendSlice(gpa, "  ");2323    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);2324    try buf.append(gpa, '\n');2325    try buf.appendSlice(gpa, conf[brace..]);23262327    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {2328        errors.error_info.setMessage("could not write {s}", .{tmp_path});2329        return error.FileNotFound;2330    };2331    tmp.writePositionalAll(io, buf.items, 0) catch {2332        tmp.close(io);2333        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2334        errors.error_info.setMessage("could not write {s}", .{tmp_path});2335        return error.FileNotFound;2336    };2337    tmp.close(io);23382339    // Back up the existing config, then replace it — in one sudo call so the2340    // password is asked for at most once. Paths travel as positional args ($0,2341    // $1) to sidestep shell quoting.2342    const code = streamLocal(io, &.{2343        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,2344    }) catch {2345        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2346        errors.error_info.setMessage("could not write {s}", .{path});2347        return error.ProcessFailed;2348    };2349    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2350    if (code != 0) {2351        errors.error_info.setMessage("sudo cp into {s} failed", .{path});2352        return error.ProcessFailed;2353    }2354}