exec.zig

105.6 KB · raw

1// exec.zig — all process execution and SSH routing2// Commands call these functions; output is streamed or captured here.3const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const output = @import("output.zig");89// nixos-rebuild manages this profile; generation commands must target it10// explicitly. Bare nix-env defaults to the per-user profile, which is empty.11const SYSTEM_PROFILE = "/nix/var/nix/profiles/system";1213pub const RunResult = struct {14    stdout: []u8,15    stderr: []u8,16    exit_code: u8,17};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}12271228pub fn flakeLockOverrideInput(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: []const u8, flake_ref: []const u8) !u8 {1229    return stream(io, machine, gpa, &.{ "nix", "flake", "lock", "--override-input", input, flake_ref });1230}12311232pub fn flakeLockOverrideRef(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, input: []const u8, rev: []const u8) ![]u8 {1233    const r = capture(gpa, io, machine, &.{ "cat", "flake.lock" }) catch return error.FileNotFound;1234    defer gpa.free(r.stdout);1235    defer gpa.free(r.stderr);1236    if (r.exit_code != 0) {1237        errors.error_info.setMessage("could not read flake.lock", .{});1238        errors.error_info.setSuggestion("run nina pin from the flake directory", .{});1239        return error.FileNotFound;1240    }1241    return flakeOverrideRefFromLock(gpa, r.stdout, input, rev);1242}12431244fn jsonObject(v: std.json.Value) ?std.json.ObjectMap {1245    return switch (v) {1246        .object => |obj| obj,1247        else => null,1248    };1249}12501251fn jsonString(obj: std.json.ObjectMap, key: []const u8) ?[]const u8 {1252    const v = obj.get(key) orelse return null;1253    return switch (v) {1254        .string => |s| s,1255        else => null,1256    };1257}12581259fn inputNodeName(nodes: std.json.ObjectMap, root_name: []const u8, input: []const u8) ?[]const u8 {1260    const root_v = nodes.get(root_name) orelse return null;1261    const root = jsonObject(root_v) orelse return null;1262    const inputs_v = root.get("inputs") orelse return null;1263    const inputs = jsonObject(inputs_v) orelse return null;1264    const target = inputs.get(input) orelse return null;1265    return switch (target) {1266        .string => |s| s,1267        .array => |arr| {1268            if (arr.items.len == 0) return null;1269            return switch (arr.items[arr.items.len - 1]) {1270                .string => |s| s,1271                else => null,1272            };1273        },1274        else => null,1275    };1276}12771278fn appendQueryString(out: *std.ArrayList(u8), gpa: std.mem.Allocator, first: *bool, key: []const u8, value: []const u8) !void {1279    try out.append(gpa, if (first.*) '?' else '&');1280    first.* = false;1281    try out.appendSlice(gpa, key);1282    try out.append(gpa, '=');1283    try out.appendSlice(gpa, value);1284}12851286fn appendQueryBool(out: *std.ArrayList(u8), gpa: std.mem.Allocator, first: *bool, key: []const u8, obj: std.json.ObjectMap) !void {1287    const v = obj.get(key) orelse return;1288    if (v != .bool) return;1289    try appendQueryString(out, gpa, first, key, if (v.bool) "1" else "0");1290}12911292fn appendSharedFlakeRefQuery(out: *std.ArrayList(u8), gpa: std.mem.Allocator, first: *bool, source: std.json.ObjectMap) !void {1293    if (jsonString(source, "dir")) |dir| try appendQueryString(out, gpa, first, "dir", dir);1294    try appendQueryBool(out, gpa, first, "submodules", source);1295    try appendQueryBool(out, gpa, first, "lfs", source);1296    try appendQueryBool(out, gpa, first, "shallow", source);1297    try appendQueryBool(out, gpa, first, "allRefs", source);1298}12991300fn sourceObject(node: std.json.ObjectMap) ?std.json.ObjectMap {1301    if (node.get("original")) |v| {1302        if (jsonObject(v)) |obj| return obj;1303    }1304    if (node.get("locked")) |v| {1305        if (jsonObject(v)) |obj| return obj;1306    }1307    return null;1308}13091310fn forgeFlakeRef(gpa: std.mem.Allocator, prefix: []const u8, source: std.json.ObjectMap, rev: []const u8) ![]u8 {1311    if (source.get("host") != null) {1312        errors.error_info.setMessage("cannot pin non-default {s} host automatically", .{prefix});1313        errors.error_info.setSuggestion("use nix flake lock --override-input <input> <flake-ref>", .{});1314        return error.Internal;1315    }1316    const owner = jsonString(source, "owner") orelse {1317        errors.error_info.setMessage("flake.lock input is missing owner", .{});1318        return error.Internal;1319    };1320    const repo = jsonString(source, "repo") orelse {1321        errors.error_info.setMessage("flake.lock input is missing repo", .{});1322        return error.Internal;1323    };13241325    var out: std.ArrayList(u8) = .empty;1326    errdefer out.deinit(gpa);1327    try out.appendSlice(gpa, prefix);1328    try out.append(gpa, ':');1329    try out.appendSlice(gpa, owner);1330    try out.append(gpa, '/');1331    try out.appendSlice(gpa, repo);1332    var first_query = true;1333    try appendQueryString(&out, gpa, &first_query, "rev", rev);1334    try appendSharedFlakeRefQuery(&out, gpa, &first_query, source);1335    return out.toOwnedSlice(gpa);1336}13371338fn gitFlakeRef(gpa: std.mem.Allocator, source: std.json.ObjectMap, rev: []const u8) ![]u8 {1339    const url = jsonString(source, "url") orelse {1340        errors.error_info.setMessage("git flake.lock input is missing url", .{});1341        return error.Internal;1342    };1343    var out: std.ArrayList(u8) = .empty;1344    errdefer out.deinit(gpa);1345    if (!std.mem.startsWith(u8, url, "git+")) try out.appendSlice(gpa, "git+");1346    try out.appendSlice(gpa, url);1347    var first_query = std.mem.indexOfScalar(u8, url, '?') == null;1348    try appendQueryString(&out, gpa, &first_query, "rev", rev);1349    try appendSharedFlakeRefQuery(&out, gpa, &first_query, source);1350    return out.toOwnedSlice(gpa);1351}13521353pub fn flakeOverrideRefFromLock(gpa: std.mem.Allocator, lock_json: []const u8, input: []const u8, rev: []const u8) ![]u8 {1354    const parsed = std.json.parseFromSlice(std.json.Value, gpa, lock_json, .{}) catch {1355        errors.error_info.setMessage("could not parse flake.lock", .{});1356        return error.ConfigParseError;1357    };1358    defer parsed.deinit();13591360    const root = jsonObject(parsed.value) orelse {1361        errors.error_info.setMessage("could not parse flake.lock", .{});1362        return error.ConfigParseError;1363    };1364    const nodes_v = root.get("nodes") orelse {1365        errors.error_info.setMessage("flake.lock has no nodes", .{});1366        return error.ConfigParseError;1367    };1368    const nodes = jsonObject(nodes_v) orelse {1369        errors.error_info.setMessage("flake.lock nodes are malformed", .{});1370        return error.ConfigParseError;1371    };1372    const root_name = jsonString(root, "root") orelse "root";1373    const node_name = inputNodeName(nodes, root_name, input) orelse input;1374    const node_v = nodes.get(node_name) orelse {1375        errors.error_info.setMessage("flake input '{s}' not found in flake.lock", .{input});1376        errors.error_info.setSuggestion("run nina flake update first", .{});1377        return error.Internal;1378    };1379    const node = jsonObject(node_v) orelse {1380        errors.error_info.setMessage("flake input '{s}' is malformed", .{input});1381        return error.ConfigParseError;1382    };1383    const source = sourceObject(node) orelse {1384        errors.error_info.setMessage("flake input '{s}' has no source metadata", .{input});1385        return error.Internal;1386    };1387    const typ = jsonString(source, "type") orelse {1388        errors.error_info.setMessage("flake input '{s}' has no source type", .{input});1389        return error.Internal;1390    };13911392    if (std.mem.eql(u8, typ, "github")) return forgeFlakeRef(gpa, "github", source, rev);1393    if (std.mem.eql(u8, typ, "gitlab")) return forgeFlakeRef(gpa, "gitlab", source, rev);1394    if (std.mem.eql(u8, typ, "sourcehut")) return forgeFlakeRef(gpa, "sourcehut", source, rev);1395    if (std.mem.eql(u8, typ, "git")) return gitFlakeRef(gpa, source, rev);13961397    errors.error_info.setMessage("cannot pin flake input '{s}' of type '{s}'", .{ input, typ });1398    errors.error_info.setSuggestion("use nix flake lock --override-input <input> <flake-ref>", .{});1399    return error.Internal;1400}14011402test "flakeOverrideRefFromLock resolves root github input" {1403    const a = std.testing.allocator;1404    const lock =1405        \\{1406        \\  "nodes": {1407        \\    "nixpkgs": {1408        \\      "locked": { "owner": "NixOS", "repo": "nixpkgs", "rev": "old", "type": "github" },1409        \\      "original": { "owner": "NixOS", "ref": "nixos-unstable", "repo": "nixpkgs", "type": "github" }1410        \\    },1411        \\    "root": { "inputs": { "nixpkgs": "nixpkgs" } }1412        \\  },1413        \\  "root": "root",1414        \\  "version": 71415        \\}1416    ;1417    const ref = try flakeOverrideRefFromLock(a, lock, "nixpkgs", "abcdef");1418    defer a.free(ref);1419    try std.testing.expectEqualStrings("github:NixOS/nixpkgs?rev=abcdef", ref);1420}14211422test "flakeOverrideRefFromLock preserves dir and boolean source flags" {1423    const a = std.testing.allocator;1424    const lock =1425        \\{1426        \\  "nodes": {1427        \\    "dep-node": {1428        \\      "original": {1429        \\        "owner": "me",1430        \\        "repo": "mono",1431        \\        "type": "github",1432        \\        "dir": "sub/flake",1433        \\        "submodules": true1434        \\      }1435        \\    },1436        \\    "root": { "inputs": { "dep": "dep-node" } }1437        \\  },1438        \\  "root": "root",1439        \\  "version": 71440        \\}1441    ;1442    const ref = try flakeOverrideRefFromLock(a, lock, "dep", "1234");1443    defer a.free(ref);1444    try std.testing.expectEqualStrings("github:me/mono?rev=1234&dir=sub/flake&submodules=1", ref);1445}14461447test "flakeOverrideRefFromLock resolves generic git inputs" {1448    const a = std.testing.allocator;1449    const lock =1450        \\{1451        \\  "nodes": {1452        \\    "dep": {1453        \\      "original": { "type": "git", "url": "https://example.com/repo.git" }1454        \\    },1455        \\    "root": { "inputs": { "dep": "dep" } }1456        \\  },1457        \\  "root": "root",1458        \\  "version": 71459        \\}1460    ;1461    const ref = try flakeOverrideRefFromLock(a, lock, "dep", "deadbeef");1462    defer a.free(ref);1463    try std.testing.expectEqualStrings("git+https://example.com/repo.git?rev=deadbeef", ref);1464}14651466test "flakeOverrideRefFromLock rejects unsupported source types" {1467    const a = std.testing.allocator;1468    const lock =1469        \\{1470        \\  "nodes": {1471        \\    "local": { "original": { "type": "path", "path": "./dep" } },1472        \\    "root": { "inputs": { "local": "local" } }1473        \\  },1474        \\  "root": "root",1475        \\  "version": 71476        \\}1477    ;1478    try std.testing.expectError(error.Internal, flakeOverrideRefFromLock(a, lock, "local", "deadbeef"));1479}14801481// Update flake inputs for the flake living in `dir` (the config dir). `nix flake1482// update` operates on the flake in the working directory, so we cd there first.1483// Used by `nina upgrade` on a flake system in place of nix-channel --update.1484pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {1485    return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });1486}14871488pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {1489    var argv: std.ArrayList([]const u8) = .empty;1490    defer argv.deinit(gpa);1491    try argv.appendSlice(gpa, &.{ "nix", "flake", "check" });1492    try argv.appendSlice(gpa, extra_flags);1493    return stream(io, machine, gpa, argv.items);1494}14951496pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1497    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });1498}14991500pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1501    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });1502}15031504pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {1505    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });1506}15071508pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1509    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });1510    defer gpa.free(r.stderr);1511    if (r.exit_code != 0) {1512        gpa.free(r.stdout);1513        return error.ProcessFailed;1514    }1515    return r.stdout;1516}15171518// --- Build / Run / Develop ---15191520pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8, extra_flags: []const []const u8) !u8 {1521    var argv: std.ArrayList([]const u8) = .empty;1522    defer argv.deinit(gpa);1523    try argv.append(gpa, "nix");1524    try argv.append(gpa, "build");1525    var ref_buf: ?[]u8 = null;1526    defer if (ref_buf) |r| gpa.free(r);1527    if (attr) |a| {1528        ref_buf = try std.fmt.allocPrint(gpa, ".#{s}", .{a});1529        try argv.append(gpa, ref_buf.?);1530    }1531    try argv.appendSlice(gpa, extra_flags);1532    return stream(io, machine, gpa, argv.items);1533}15341535pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, extra_flags: []const []const u8) !u8 {1536    // nix run always gets --no-write-lock-file for remote URLs1537    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");15381539    var argv: std.ArrayList([]const u8) = .empty;1540    defer argv.deinit(gpa);1541    try argv.append(gpa, "nix");1542    try argv.append(gpa, "run");15431544    var ref_buf: ?[]u8 = null;1545    defer if (ref_buf) |r| gpa.free(r);1546    if (is_url) {1547        try argv.append(gpa, pkg);1548        try argv.append(gpa, "--no-write-lock-file");1549    } else if (std.mem.indexOfScalar(u8, pkg, '#') != null) {1550        // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.1551        try argv.append(gpa, pkg);1552    } else {1553        ref_buf = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1554        try argv.append(gpa, ref_buf.?);1555    }15561557    // extra_flags carries any `-- <program args>` separator verbatim, so this1558    // naturally reconstructs `nix run <ref> -- <args>` — nix's own convention.1559    try argv.appendSlice(gpa, extra_flags);1560    return stream(io, machine, gpa, argv.items);1561}15621563pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1564    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1565    defer gpa.free(ref);1566    return stream(io, machine, gpa, &.{ "nix", "shell", ref });1567}15681569pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {1570    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1571    defer gpa.free(ref);1572    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});1573    defer gpa.free(ps1);1574    if (machine.local) {1575        const rc_path = try createInteractiveShellRc(gpa, io);1576        defer {1577            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1578            gpa.free(rc_path);1579        }1580        return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref, "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, ps1);1581    }1582    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);1583}15841585pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8, extra_flags: []const []const u8) !u8 {1586    if (run_cmd) |cmd| {1587        // sh -c so a multi-word command isn't treated as a single executable name.1588        var argv: std.ArrayList([]const u8) = .empty;1589        defer argv.deinit(gpa);1590        try argv.appendSlice(gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1591        try argv.appendSlice(gpa, extra_flags);1592        return stream(io, machine, gpa, argv.items);1593    }1594    var argv: std.ArrayList([]const u8) = .empty;1595    defer argv.deinit(gpa);1596    try argv.append(gpa, "nix");1597    try argv.append(gpa, "develop");1598    try argv.appendSlice(gpa, extra_flags);1599    return stream(io, machine, gpa, argv.items);1600}16011602pub 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 {1603    if (run_cmd) |cmd| {1604        // sh -c so a multi-word command isn't treated as a single executable name.1605        var argv: std.ArrayList([]const u8) = .empty;1606        defer argv.deinit(gpa);1607        try argv.appendSlice(gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1608        try argv.appendSlice(gpa, extra_flags);1609        return stream(io, machine, gpa, argv.items);1610    }1611    if (machine.local) {1612        const rc_path = try createInteractiveShellRc(gpa, io);1613        defer {1614            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1615            gpa.free(rc_path);1616        }1617        var argv: std.ArrayList([]const u8) = .empty;1618        defer argv.deinit(gpa);1619        try argv.append(gpa, "nix");1620        try argv.append(gpa, "develop");1621        try argv.appendSlice(gpa, extra_flags);1622        try argv.appendSlice(gpa, &.{ "--command", "bash", "--rcfile", rc_path, "-i" });1623        return streamEnv(io, machine, gpa, argv.items, base_env, "(nina: dev) -> ");1624    }1625    var argv: std.ArrayList([]const u8) = .empty;1626    defer argv.deinit(gpa);1627    try argv.append(gpa, "nix");1628    try argv.append(gpa, "develop");1629    try argv.appendSlice(gpa, extra_flags);1630    return streamEnv(io, machine, gpa, argv.items, base_env, "(nina: dev) -> ");1631}16321633pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1634    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });1635}16361637// --- Format ---16381639pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {1640    if (check) {1641        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });1642    }1643    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });1644}16451646// --- Info ---16471648pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1649    const r = try capture(gpa, io, machine, &.{"nixos-version"});1650    defer gpa.free(r.stderr);1651    if (r.exit_code != 0) {1652        gpa.free(r.stdout);1653        return error.ProcessFailed;1654    }1655    return r.stdout;1656}16571658pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1659    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });1660    defer gpa.free(r.stderr);1661    if (r.exit_code != 0) {1662        gpa.free(r.stdout);1663        return error.ProcessFailed;1664    }1665    return r.stdout;1666}16671668pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1669    const r = try capture(gpa, io, machine, &.{"uptime"});1670    defer gpa.free(r.stderr);1671    if (r.exit_code != 0) {1672        gpa.free(r.stdout);1673        return error.ProcessFailed;1674    }1675    return r.stdout;1676}16771678// --- Boot ---16791680pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {1681    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });1682    defer gpa.free(r.stderr);1683    defer gpa.free(r.stdout);1684    if (r.exit_code != 0) return error.ProcessFailed;1685    return parseBootEntries(gpa, r.stdout);1686}16871688fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {1689    var entries: std.ArrayList(types.BootEntry) = .empty;1690    var lines = std.mem.splitScalar(u8, output_str, '\n');1691    while (lines.next()) |line| {1692        const trimmed = std.mem.trim(u8, line, " \t\r");1693        if (std.mem.startsWith(u8, trimmed, "title:")) {1694            const title = std.mem.trim(u8, trimmed[6..], " \t");1695            const current = std.mem.indexOf(u8, title, "(current)") != null;1696            try entries.append(gpa, .{1697                .title = try gpa.dupe(u8, title),1698                .current = current,1699            });1700        }1701    }1702    return entries.toOwnedSlice(gpa);1703}17041705// --- Pkg info ---17061707fn pkgInstallable(gpa: std.mem.Allocator, pkg: []const u8) ![]u8 {1708    return std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1709}17101711fn resolvePkgStorePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, installable: []const u8) ![]u8 {1712    const r = try capture(gpa, io, machine, &.{ "nix", "build", "--no-link", "--print-out-paths", installable });1713    defer gpa.free(r.stderr);1714    defer gpa.free(r.stdout);1715    if (r.exit_code != 0) return error.PackageNotFound;17161717    var lines = std.mem.tokenizeAny(u8, r.stdout, "\r\n");1718    const first_path = lines.next() orelse return error.PackageNotFound;1719    const store_path = std.mem.trim(u8, first_path, " \t");1720    if (store_path.len == 0) return error.PackageNotFound;1721    return gpa.dupe(u8, store_path);1722}17231724pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1725    const installable = try pkgInstallable(gpa, pkg);1726    defer gpa.free(installable);1727    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1728    defer gpa.free(store_path);1729    return stream(io, machine, gpa, &.{ "nix", "why-depends", "/run/current-system", store_path });1730}17311732pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1733    const installable = try pkgInstallable(gpa, pkg);1734    defer gpa.free(installable);1735    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1736    defer gpa.free(store_path);1737    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", store_path });1738}17391740pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {1741    const installable = try pkgInstallable(gpa, pkg);1742    defer gpa.free(installable);1743    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", "--json", installable });1744    defer gpa.free(r.stderr);1745    defer gpa.free(r.stdout);1746    if (r.exit_code != 0) return error.ProcessFailed;17471748    const nar_size = try pathInfoNarSize(gpa, r.stdout);1749    return humanPkgSize(gpa, nar_size);1750}17511752pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1753    const installable = try pkgInstallable(gpa, pkg);1754    defer gpa.free(installable);1755    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1756    defer gpa.free(store_path);1757    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", store_path });1758}17591760fn pathInfoNarSize(gpa: std.mem.Allocator, json_str: []const u8) !u64 {1761    var parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.ProcessFailed;1762    defer parsed.deinit();1763    switch (parsed.value) {1764        .object => |obj| {1765            var it = obj.iterator();1766            while (it.next()) |entry| {1767                if (entry.value_ptr.* == .object) {1768                    if (entry.value_ptr.object.get("narSize")) |v| {1769                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1770                    }1771                }1772            }1773        },1774        .array => |arr| {1775            for (arr.items) |item| {1776                if (item == .object) {1777                    if (item.object.get("narSize")) |v| {1778                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1779                    }1780                }1781            }1782        },1783        else => {},1784    }1785    return error.ProcessFailed;1786}17871788fn humanPkgSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1789    const units = [_][]const u8{ "B", "KiB", "MiB", "GiB", "TiB" };1790    var val: f64 = @floatFromInt(bytes);1791    var unit: usize = 0;1792    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1793    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1794    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1795}17961797test "pathInfoNarSize parses object and array shapes" {1798    try std.testing.expectEqual(@as(u64, 1064629862), try pathInfoNarSize(std.testing.allocator,1799        \\{"/nix/store/abc-ffmpeg":{"narSize":1064629862}}1800    ));1801    try std.testing.expectEqual(@as(u64, 2048), try pathInfoNarSize(std.testing.allocator,1802        \\[{"path":"/nix/store/abc-pkg","narSize":2048}]1803    ));1804}18051806// --- Hash / Fetch ---18071808pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {1809    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });1810    defer gpa.free(r.stderr);1811    if (r.exit_code != 0) {1812        gpa.free(r.stdout);1813        return error.ProcessFailed;1814    }1815    return r.stdout;1816}18171818pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {1819    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });1820    defer gpa.free(r.stderr);1821    if (r.exit_code != 0) {1822        gpa.free(r.stdout);1823        return error.ProcessFailed;1824    }1825    return r.stdout;1826}18271828pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {1829    if (line) |l| {1830        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});1831        defer gpa.free(line_arg);1832        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });1833    }1834    return stream(io, &types.Machine{}, gpa, &.{ editor, path });1835}18361837// Open a config directory as root with `sudo -E <editor> <path>` — `-E`1838// preserves the user's environment (PATH, TERM, EDITOR config) so the editor1839// behaves the same as it does unprivileged. Used by `nina edit --dir`.1840pub fn openEditorSudo(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8) !u8 {1841    return stream(io, &types.Machine{}, gpa, &.{ "sudo", "-E", editor, path });1842}18431844pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {1845    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});1846    defer gpa.free(a_str);1847    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});1848    defer gpa.free(b_str);1849    // On a tty, the child's own color is fine — stream it directly.1850    if (output.colorEnabled()) {1851        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });1852    }1853    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,1854    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.1855    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });1856    defer gpa.free(r.stdout);1857    defer gpa.free(r.stderr);1858    const cleaned = try output.sanitize(gpa, r.stdout);1859    defer gpa.free(cleaned);1860    output.raw(cleaned);1861    return r.exit_code;1862}18631864// --- Doctor checks ---18651866pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1867    var checks: std.ArrayList(types.DoctorCheck) = .empty;18681869    // Check nix daemon1870    {1871        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1872        defer gpa.free(r.stdout);1873        defer gpa.free(r.stderr);1874        const active = std.mem.indexOf(u8, r.stdout, "active") != null;1875        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1876    }18771878    // Check config syntax. Flake-aware like apply/upgrade: on a flake system a1879    // plain `nixos-rebuild dry-build` evaluates <nixpkgs/nixos> + <nixos-config>1880    // (channel style) and fails, so pass --flake when the config dir has one.1881    // No sudo: dry-build only evaluates + builds, it never activates, so it1882    // needs no more privilege than reading the config and talking to the nix1883    // daemon over its (world-writable) socket — unlike switch/activate below.1884    {1885        const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1886            &.{ "nixos-rebuild", "dry-build", "--flake", machine.config_path }1887        else1888            &.{ "nixos-rebuild", "dry-build" };1889        const r = try capture(gpa, io, machine, argv);1890        defer gpa.free(r.stdout);1891        defer gpa.free(r.stderr);1892        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1893    }18941895    // Check channel1896    {1897        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1898        defer gpa.free(r.stdout);1899        defer gpa.free(r.stderr);1900        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1901        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1902    }19031904    return checks.toOwnedSlice(gpa);1905}19061907// --- Home Manager ---1908//1909// Home Manager has three usage modes. nina detects which one is in play before1910// any `home` command so it can either drive the standalone CLI or redirect the1911// user to `nina apply` (when HM is a NixOS/flake module activated by rebuild).19121913pub const HomeManagerMode = enum {1914    // home-manager binary on PATH — manages the user env on its own.1915    standalone,1916    // No binary, but a home.nix exists — HM is a NixOS/flake module rebuilt by1917    // nixos-rebuild. `nina home apply` redirects to `nina apply`.1918    module,1919    none,1920};19211922fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1923    const home = environ.get("HOME") orelse return null;1924    return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1925}19261927// Path to the standalone home.nix. Caller frees.1928pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1929    const dir = homeConfigDir(gpa, environ) orelse return null;1930    defer gpa.free(dir);1931    return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1932}19331934pub fn pathExists(io: std.Io, path: []const u8) bool {1935    const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1936    f.close(io);1937    return true;1938}19391940// `command -v <name>` — true if the binary resolves on PATH. Silent (captured),1941// unlike streamLocal which would inherit stdio.1942// `name` is passed as real argv (positional $1), never interpolated into the1943// script text — only "home-manager" reaches this today, but this is the one1944// place in exec.zig that used to build shell syntax from a parameter.1945fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1946    const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", "command -v \"$1\" >/dev/null 2>&1", "_", name } }) catch return false;1947    defer gpa.free(r.stdout);1948    defer gpa.free(r.stderr);1949    return switch (r.term) {1950        .exited => |code| code == 0,1951        else => false,1952    };1953}19541955pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1956    if (commandExists(gpa, io, "home-manager")) return .standalone;1957    if (homeNixPath(gpa, environ)) |p| {1958        defer gpa.free(p);1959        if (pathExists(io, p)) return .module;1960    }1961    return .none;1962}19631964// The home-manager config dir when it holds a flake.nix (a flake-based home1965// config that `home-manager switch --flake` drives). null for a channel-based1966// config, which uses a plain `home-manager switch`. Caller frees.1967pub fn homeFlakeDir(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1968    const dir = homeConfigDir(gpa, environ) orelse return null;1969    const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch {1970        gpa.free(dir);1971        return null;1972    };1973    defer gpa.free(flake);1974    if (!pathExists(io, flake)) {1975        gpa.free(dir);1976        return null;1977    }1978    return dir;1979}19801981// Platform-specific home-manager attribute "<user>-<arch>-<os>" (e.g.1982// murazaki-x86_64-linux) — the homeConfigurations key many flakes derive from1983// ${USER}-${system}. arch/os come from uname on the local host (home commands1984// are local-only). Caller frees.1985pub fn homeManagerAttr(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, environ: *const std.process.Environ.Map) ![]const u8 {1986    const user = environ.get("USER") orelse "user";19871988    const arch_r = try capture(gpa, io, machine, &.{ "uname", "-m" });1989    defer gpa.free(arch_r.stdout);1990    defer gpa.free(arch_r.stderr);1991    if (arch_r.exit_code != 0) return error.ProcessFailed;1992    const arch = std.mem.trim(u8, arch_r.stdout, " \t\r\n");19931994    const os_r = try capture(gpa, io, machine, &.{ "uname", "-s" });1995    defer gpa.free(os_r.stdout);1996    defer gpa.free(os_r.stderr);1997    if (os_r.exit_code != 0) return error.ProcessFailed;1998    const os = try gpa.dupe(u8, std.mem.trim(u8, os_r.stdout, " \t\r\n"));1999    defer gpa.free(os);2000    for (os) |*ch| ch.* = std.ascii.toLower(ch.*);20012002    if (arch.len == 0 or os.len == 0) return error.ProcessFailed;2003    return std.fmt.allocPrint(gpa, "{s}-{s}-{s}", .{ user, arch, os });2004}20052006// Map a nixos-version string to the matching home-manager branch: an unstable2007// channel ("…pre…"/"unstable") → master; a stable release like2008// "25.05.20250115.abcdef (Warbler)" → release-25.05. Anything unparseable2009// falls back to master. Caller frees.2010fn homeBranchFromVersion(gpa: std.mem.Allocator, version_raw: []const u8) ![]const u8 {2011    const v = std.mem.trim(u8, version_raw, " \t\r\n");2012    if (std.mem.indexOf(u8, v, "pre") != null or2013        std.mem.indexOf(u8, v, "unstable") != null)2014        return gpa.dupe(u8, "master");20152016    const head = v[0 .. std.mem.indexOfScalar(u8, v, ' ') orelse v.len];2017    var it = std.mem.splitScalar(u8, head, '.');2018    const major = it.next() orelse "";2019    const minor = it.next() orelse "";2020    if (allDigits(major) and allDigits(minor))2021        return std.fmt.allocPrint(gpa, "release-{s}.{s}", .{ major, minor });20222023    return gpa.dupe(u8, "master");2024}20252026fn allDigits(s: []const u8) bool {2027    if (s.len == 0) return false;2028    for (s) |ch| if (!std.ascii.isDigit(ch)) return false;2029    return true;2030}20312032test "homeBranchFromVersion maps channels to HM branches" {2033    const a = std.testing.allocator;2034    const cases = [_]struct { in: []const u8, want: []const u8 }{2035        .{ .in = "25.05.20250115.abcdef (Warbler)", .want = "release-25.05" },2036        .{ .in = "24.11.20241201.deadbee (Vicuna)", .want = "release-24.11" },2037        .{ .in = "25.11pre-git", .want = "master" },2038        .{ .in = "25.05pre789012.abcdef (Warbler)", .want = "master" },2039        .{ .in = "nixos-unstable", .want = "master" },2040        .{ .in = "garbage", .want = "master" },2041    };2042    for (cases) |c| {2043        const got = try homeBranchFromVersion(a, c.in);2044        defer a.free(got);2045        try std.testing.expectEqualStrings(c.want, got);2046    }2047}20482049// The home-manager branch matching the running nixpkgs. Falls back to master2050// when nixos-version is unavailable (non-NixOS host). Caller frees.2051fn detectHomeManagerBranch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]const u8 {2052    const r = capture(gpa, io, machine, &.{"nixos-version"}) catch2053        return gpa.dupe(u8, "master");2054    defer gpa.free(r.stdout);2055    defer gpa.free(r.stderr);2056    if (r.exit_code != 0) return gpa.dupe(u8, "master");2057    return homeBranchFromVersion(gpa, r.stdout);2058}20592060// `nix run home-manager/<branch> -- init [--switch] [dir]` — generates2061// flake.nix + home.nix (in dir, or ~/.config/home-manager by default),2062// activating immediately when switch_on_init is set.2063pub fn homeManagerInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, switch_on_init: bool, dir: ?[]const u8) !u8 {2064    const branch = try detectHomeManagerBranch(gpa, io, machine);2065    defer gpa.free(branch);2066    const flake_ref = try std.fmt.allocPrint(gpa, "home-manager/{s}", .{branch});2067    defer gpa.free(flake_ref);20682069    var argv: std.ArrayList([]const u8) = .empty;2070    defer argv.deinit(gpa);2071    try argv.appendSlice(gpa, &.{ "nix", "run", flake_ref, "--", "init" });2072    if (switch_on_init) try argv.append(gpa, "--switch");2073    if (dir) |d| try argv.append(gpa, d);20742075    return stream(io, machine, gpa, argv.items);2076}20772078pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {2079    output.flush();2080    var argv: std.ArrayList([]const u8) = .empty;2081    defer argv.deinit(gpa);2082    try argv.appendSlice(gpa, &.{ "home-manager", "switch" });2083    try argv.appendSlice(gpa, extra_flags);2084    const r = try capture(gpa, io, machine, argv.items);2085    defer gpa.free(r.stdout);2086    defer gpa.free(r.stderr);2087    errors.setBuildStderr(r.stderr);2088    return r.exit_code;2089}20902091// Outcome of a flake-based switch, so the caller can fall back to a less2092// specific attribute on a missing-attribute evaluation error — but never on a2093// genuine build failure.2094pub const SwitchOutcome = enum { ok, attr_missing, failed };20952096pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8, extra_flags: []const []const u8) !SwitchOutcome {2097    output.flush();2098    var argv: std.ArrayList([]const u8) = .empty;2099    defer argv.deinit(gpa);2100    try argv.appendSlice(gpa, &.{ "home-manager", "switch", "--flake", flake_ref });2101    try argv.appendSlice(gpa, extra_flags);2102    const r = try capture(gpa, io, machine, argv.items);2103    defer gpa.free(r.stdout);2104    defer gpa.free(r.stderr);2105    if (r.exit_code == 0) return .ok;2106    // A flake that doesn't define this homeConfiguration fails during evaluation2107    // with "does not provide attribute" — surface that so the caller can retry a2108    // different attr rather than treating it as a build failure.2109    if (std.mem.indexOf(u8, r.stderr, "does not provide attribute") != null)2110        return .attr_missing;2111    errors.setBuildStderr(r.stderr);2112    return .failed;2113}21142115// home-manager has no system-profile rollback; it re-activates the previous2116// generation via `switch --rollback`.2117pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {2118    output.flush();2119    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch", "--rollback" });2120    defer gpa.free(r.stdout);2121    defer gpa.free(r.stderr);2122    errors.setBuildStderr(r.stderr);2123    return r.exit_code;2124}21252126// Build (and validate) the home config without activating it — used by `home2127// check` and `home apply --dry`. `home-manager build` drops a ./result symlink2128// in the cwd, so run it in a throwaway temp dir to avoid littering the directory2129// nina was invoked from.2130pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {2131    output.flush();2132    // extra_flags are passed as real argv elements after the literal `--`, picked2133    // up via "$@" — never interpolated into the script text, so an extra flag2134    // can't smuggle shell metacharacters into the command.2135    var argv: std.ArrayList([]const u8) = .empty;2136    defer argv.deinit(gpa);2137    try argv.appendSlice(gpa, &.{ "sh", "-c", "d=$(mktemp -d) && cd \"$d\" && home-manager build \"$@\"", "--" });2138    try argv.appendSlice(gpa, extra_flags);2139    const r = try capture(gpa, io, machine, argv.items);2140    defer gpa.free(r.stdout);2141    defer gpa.free(r.stderr);2142    errors.setBuildStderr(r.stderr);2143    return r.exit_code;2144}21452146pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {2147    const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });2148    defer gpa.free(r.stderr);2149    if (r.exit_code != 0) {2150        gpa.free(r.stdout);2151        return error.ProcessFailed;2152    }2153    return r.stdout;2154}21552156// Store paths referenced by a home generation — used to list managed packages.2157pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {2158    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });2159    defer gpa.free(r.stderr);2160    if (r.exit_code != 0) {2161        gpa.free(r.stdout);2162        return error.ProcessFailed;2163    }2164    return r.stdout;2165}21662167// diff-closures between two arbitrary store paths (home generations), mirroring2168// diffClosures' tty/piped color handling.2169pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {2170    if (output.colorEnabled()) {2171        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });2172    }2173    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });2174    defer gpa.free(r.stdout);2175    defer gpa.free(r.stderr);2176    const cleaned = try output.sanitize(gpa, r.stdout);2177    defer gpa.free(cleaned);2178    output.raw(cleaned);2179    return r.exit_code;2180}21812182// --- Log ---21832184pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {2185    const home = environ.get("HOME") orelse return error.FileNotFound;2186    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});2187    defer gpa.free(path);2188    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;2189    if (last == 0) return content;21902191    // Collect non-empty lines, then keep only the final `last`. Slices point into2192    // `content`, so copy them out before freeing it.2193    var lines: std.ArrayList([]const u8) = .empty;2194    defer lines.deinit(gpa);2195    var it = std.mem.splitScalar(u8, content, '\n');2196    while (it.next()) |line| {2197        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;2198        try lines.append(gpa, line);2199    }2200    if (lines.items.len <= last) return content;22012202    var out: std.ArrayList(u8) = .empty;2203    errdefer out.deinit(gpa);2204    for (lines.items[lines.items.len - last ..]) |line| {2205        try out.appendSlice(gpa, line);2206        try out.append(gpa, '\n');2207    }2208    gpa.free(content);2209    return out.toOwnedSlice(gpa);2210}22112212// nina is a one-shot process, so "did the last apply fail this session?" can't2213// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the2214// other ~/.nina-* state files. This lets a later successful apply earn the2215// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.2216pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {2217    const home = environ.get("HOME") orelse return;2218    var buf: [512]u8 = undefined;2219    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;2220    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;2221    file.close(io);2222}22232224pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {2225    const home = environ.get("HOME") orelse return false;2226    var buf: [512]u8 = undefined;2227    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;2228    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {2229        f.close(io);2230        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};2231        return true;2232    } else |_| {2233        return false;2234    }2235}22362237pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {2238    const home = environ.get("HOME") orelse return;2239    var path_buf: [512]u8 = undefined;2240    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;2241    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch2242        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);2243    defer file.close(io);2244    const size = file.length(io) catch 0;2245    file.writePositionalAll(io, entry, size) catch {};2246}22472248// --- Update helpers ---22492250// Fetch a URL with curl and return the response body. Caller must free.2251// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.2252pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {2253    const argv = [_][]const u8{2254        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,2255    };2256    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;2257    defer gpa.free(result.stderr);22582259    const marker = "\nHTTP_STATUS:";2260    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {2261        gpa.free(result.stdout);2262        return error.NetworkError;2263    };2264    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");2265    const status = std.fmt.parseInt(u16, status_str, 10) catch {2266        gpa.free(result.stdout);2267        return error.NetworkError;2268    };2269    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }2270    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }2271    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {2272        gpa.free(result.stdout);2273        return e;2274    };2275    gpa.free(result.stdout);2276    return body;2277}22782279// Download a URL to a temp file. Returns the temp path (caller must gpa.free2280// the string AND delete the file once done with it — this only reserves the2281// name and writes the content). mktemp's random suffix keeps the path from2282// being guessable, unlike a fixed name that a shared /tmp lets any local user2283// symlink out from under a self-update.2284pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {2285    const tmp_raw = try captureLocal(gpa, io, &.{ "mktemp", "/tmp/nina-update.XXXXXX" });2286    defer gpa.free(tmp_raw);2287    const tmp_path = try gpa.dupe(u8, std.mem.trim(u8, tmp_raw, " \t\r\n"));2288    errdefer gpa.free(tmp_path);22892290    var child = std.process.spawn(io, .{2291        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },2292        .stdin = .close,2293        .stdout = .close,2294        .stderr = .inherit,2295    }) catch return error.NetworkError;2296    const term = child.wait(io) catch return error.NetworkError;2297    switch (term) {2298        .exited => |c| if (c != 0) return error.NetworkError,2299        else => return error.NetworkError,2300    }2301    return tmp_path;2302}23032304test "downloadToTemp uses a distinct random path per call and can be cleaned up (NINA-004)" {2305    const a = std.testing.allocator;2306    const io = std.testing.io;23072308    var tmp = std.testing.tmpDir(.{});2309    defer tmp.cleanup();23102311    const payload = "nina download fixture payload\n";2312    {2313        const f = try tmp.dir.createFile(io, "source.bin", .{});2314        defer f.close(io);2315        try f.writePositionalAll(io, payload, 0);2316    }23172318    // curl supports file:// URLs, so this exercises the real downloadToTemp2319    // implementation (real mktemp + real curl spawn) without any network.2320    var real_path_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;2321    const real_path_len = try tmp.dir.realPathFile(io, "source.bin", &real_path_buf);2322    const url = try std.fmt.allocPrint(a, "file://{s}", .{real_path_buf[0..real_path_len]});2323    defer a.free(url);23242325    const path1 = try downloadToTemp(a, io, url);2326    defer a.free(path1);2327    defer std.Io.Dir.deleteFileAbsolute(io, path1) catch {};23282329    const path2 = try downloadToTemp(a, io, url);2330    defer a.free(path2);2331    defer std.Io.Dir.deleteFileAbsolute(io, path2) catch {};23322333    // mktemp's random suffix must differ per call — a fixed path is2334    // symlink-clobberable and shared across concurrent self-updates.2335    try std.testing.expect(!std.mem.eql(u8, path1, path2));2336    try std.testing.expect(!std.mem.eql(u8, path1, "/tmp/nina-update.bin"));23372338    try std.testing.expect(pathExists(io, path1));2339    const downloaded = try std.Io.Dir.readFileAlloc(.cwd(), io, path1, a, .unlimited);2340    defer a.free(downloaded);2341    try std.testing.expectEqualStrings(payload, downloaded);23422343    // The caller owns cleanup (see the update command's post-install defer) —2344    // confirm the mktemp'd file is actually removable and gone afterward.2345    try std.Io.Dir.deleteFileAbsolute(io, path1);2346    try std.testing.expect(!pathExists(io, path1));2347}23482349// Get the current executable path into buf. Returns slice of buf.2350pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {2351    const len = try std.process.executablePath(io, buf);2352    return buf[0..len];2353}23542355// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then2356// atomically install the binary to install_path. Errors: ChecksumMismatch,2357// AccessDenied (with error_info set), or underlying I/O errors.2358pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {2359    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {2360        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});2361        return error.FileNotFound;2362    };2363    defer gpa.free(bytes);23642365    var hasher = std.crypto.hash.Blake3.init(.{});2366    hasher.update(bytes);2367    var raw: [32]u8 = undefined;2368    hasher.final(&raw);2369    const hex = std.fmt.bytesToHex(raw, .lower);2370    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;23712372    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;2373    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch2374        return error.NameTooLong;23752376    {2377        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {2378            errors.error_info.setMessage("cannot write to {s}", .{install_path});2379            errors.error_info.setSuggestion("try: sudo nina update", .{});2380            return error.AccessDenied;2381        };2382        defer f.close(io);2383        f.writePositionalAll(io, bytes, 0) catch {2384            errors.error_info.setMessage("cannot write to {s}", .{install_path});2385            return error.AccessDenied;2386        };2387        try f.setPermissions(io, .fromMode(0o755));2388    }2389    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};23902391    if (comptime builtin.os.tag == .macos) {2392        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};2393    }23942395    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {2396        error.AccessDenied => {2397            errors.error_info.setMessage("cannot replace {s}", .{install_path});2398            errors.error_info.setSuggestion("try: sudo nina update", .{});2399            return error.AccessDenied;2400        },2401        else => return e,2402    };2403}24042405// --- Nix feature setup ---24062407pub const NixFeatureStatus = struct {2408    nix_command: bool = false,2409    flakes: bool = false,24102411    pub fn allEnabled(self: NixFeatureStatus) bool {2412        return self.nix_command and self.flakes;2413    }2414};24152416fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {2417    var lines = std.mem.splitScalar(u8, conf, '\n');2418    while (lines.next()) |line| {2419        const trimmed = std.mem.trim(u8, line, " \t");2420        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;2421        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;2422        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;2423    }2424}24252426pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {2427    var status = NixFeatureStatus{};24282429    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {2430        defer gpa.free(conf);2431        scanConfFeatures(conf, &status);2432    }24332434    if (environ.get("HOME")) |home| {2435        var buf: [512]u8 = undefined;2436        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;2437        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {2438            defer gpa.free(conf);2439            scanConfFeatures(conf, &status);2440        }2441    }24422443    return status;2444}24452446pub fn isNixOS(io: std.Io) bool {2447    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;2448    file.close(io);2449    return true;2450}24512452// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.2453// Returns the path written (caller must free).2454pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {2455    const home = environ.get("HOME") orelse {2456        errors.error_info.setMessage("HOME not set", .{});2457        return error.ConfigNotFound;2458    };24592460    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});2461    defer gpa.free(dir_path);2462    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});2463    errdefer gpa.free(file_path);24642465    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};24662467    const line = "experimental-features = nix-command flakes\n";2468    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch2469        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {2470        errors.error_info.setMessage("could not write {s}", .{file_path});2471        return error.FileNotFound;2472    });2473    defer file.close(io);24742475    const size = file.length(io) catch 0;2476    file.writePositionalAll(io, line, size) catch {2477        errors.error_info.setMessage("could not write {s}", .{file_path});2478        return error.FileNotFound;2479    };24802481    return file_path;2482}24832484// --- NixOS: declarative experimental-features ---2485//2486// On NixOS the permanent, declarative home for these flags is configuration.nix,2487// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves2488// the `nixos-rebuild switch` to the user.24892490pub const NIXOS_FEATURES_LINE =2491    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";24922493// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns2494// false on any read error so the caller still offers to add the line.2495pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {2496    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;2497    defer gpa.free(conf);2498    return std.mem.indexOf(u8, conf, "experimental-features") != null and2499        std.mem.indexOf(u8, conf, "nix-command") != null and2500        std.mem.indexOf(u8, conf, "flakes") != null;2501}25022503fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {2504    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;2505    return captureLocal(gpa, io, &.{ "sudo", "cat", path });2506}25072508// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix2509// (i.e. inside the top-level attribute set) and write it back via a single2510// `sudo cp`, which prompts for the password on the terminal. Returns an error2511// for the caller to fall back to printed manual instructions.2512pub fn appendFeaturesToNixosConfig(2513    gpa: std.mem.Allocator,2514    io: std.Io,2515    environ: *const std.process.Environ.Map,2516    path: []const u8,2517) !void {2518    const conf = readMaybeSudo(gpa, io, path) catch {2519        errors.error_info.setMessage("could not read {s}", .{path});2520        return error.ConfigNotFound;2521    };2522    defer gpa.free(conf);25232524    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared25252526    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {2527        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});2528        return error.MalformedConfig;2529    };25302531    const home = environ.get("HOME") orelse {2532        errors.error_info.setMessage("HOME not set", .{});2533        return error.ConfigNotFound;2534    };2535    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});2536    defer gpa.free(tmp_path);25372538    var buf: std.ArrayList(u8) = .empty;2539    defer buf.deinit(gpa);2540    try buf.appendSlice(gpa, conf[0..brace]);2541    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');2542    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");2543    try buf.appendSlice(gpa, "  ");2544    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);2545    try buf.append(gpa, '\n');2546    try buf.appendSlice(gpa, conf[brace..]);25472548    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {2549        errors.error_info.setMessage("could not write {s}", .{tmp_path});2550        return error.FileNotFound;2551    };2552    tmp.writePositionalAll(io, buf.items, 0) catch {2553        tmp.close(io);2554        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2555        errors.error_info.setMessage("could not write {s}", .{tmp_path});2556        return error.FileNotFound;2557    };2558    tmp.close(io);25592560    // Back up the existing config, then replace it — in one sudo call so the2561    // password is asked for at most once. Paths travel as positional args ($0,2562    // $1) to sidestep shell quoting.2563    const code = streamLocal(io, &.{2564        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,2565    }) catch {2566        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2567        errors.error_info.setMessage("could not write {s}", .{path});2568        return error.ProcessFailed;2569    };2570    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2571    if (code != 0) {2572        errors.error_info.setMessage("sudo cp into {s} failed", .{path});2573        return error.ProcessFailed;2574    }2575}