exec.zig

73.8 KB · raw

1// exec.zig — all process execution and SSH routing2// Commands call these functions; output is streamed or captured here.3const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const output = @import("output.zig");89// nixos-rebuild manages this profile; generation commands must target it10// explicitly. Bare nix-env defaults to the per-user profile, which is empty.11const SYSTEM_PROFILE = "/nix/var/nix/profiles/system";1213pub const RunResult = struct {14    stdout: []u8,15    stderr: []u8,16    exit_code: u8,17};1819pub const HookResult = enum {20    ok,21    failed,22    not_found,23};2425pub const HookRun = struct {26    result: HookResult,27    exit_code: u8 = 0,28    output: []u8,29};3031// Run a process and capture stdout+stderr (not streaming).32pub fn capture(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, cmd: []const []const u8) !RunResult {33    const argv = try buildArgv(gpa, machine, cmd);34    defer if (!machine.local) gpa.free(argv);3536    const result = std.process.run(gpa, io, .{ .argv = argv }) catch |e| {37        errors.error_info.setMessage("process failed: {s}", .{cmd[0]});38        return e;39    };4041    return .{42        .stdout = result.stdout,43        .stderr = result.stderr,44        .exit_code = switch (result.term) {45            .exited => |c| c,46            else => 1,47        },48    };49}5051// Run a process and stream its output to the terminal (inherit stdio).52pub fn stream(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8) !u8 {53    // The child inherits stdout and writes directly to the fd; flush any buffered54    // nina header first so it isn't reordered after the child's output.55    output.flush();56    const argv = try buildArgv(gpa, machine, cmd);57    defer if (!machine.local) gpa.free(argv);5859    var child = std.process.spawn(io, .{60        .argv = argv,61        .stdin = .inherit,62        .stdout = .inherit,63        .stderr = .inherit,64    }) catch |e| {65        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});66        return e;67    };6869    const term = child.wait(io) catch |e| {70        errors.error_info.setMessage("process wait failed", .{});71        return e;72    };7374    return switch (term) {75        .exited => |c| c,76        else => 1,77    };78}7980// Stream a process with an overridden PS1 in the child environment.81fn streamEnv(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8, base_env: *const std.process.Environ.Map, ps1: []const u8) !u8 {82    output.flush();83    const argv = try buildArgv(gpa, machine, cmd);84    defer if (!machine.local) gpa.free(argv);8586    var env = try base_env.clone(gpa);87    defer env.deinit();88    try env.put("PS1", ps1);89    try env.put("NINA_PS1", ps1);9091    var child = std.process.spawn(io, .{92        .argv = argv,93        .stdin = .inherit,94        .stdout = .inherit,95        .stderr = .inherit,96        .environ_map = &env,97    }) catch |e| {98        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});99        return e;100    };101102    const term = child.wait(io) catch |e| {103        errors.error_info.setMessage("process wait failed", .{});104        return e;105    };106107    return switch (term) {108        .exited => |c| c,109        else => 1,110    };111}112113fn createInteractiveShellRc(gpa: std.mem.Allocator, io: std.Io) ![]u8 {114    const out = try captureLocal(gpa, io, &.{ "mktemp", "/tmp/nina-shell-rc.XXXXXX" });115    defer gpa.free(out);116117    const path = std.mem.trim(u8, out, " \t\r\n");118    if (path.len == 0) return error.FileNotFound;119    const owned_path = try gpa.dupe(u8, path);120    errdefer gpa.free(owned_path);121122    const file = std.Io.Dir.createFile(.cwd(), io, owned_path, .{}) catch {123        errors.error_info.setMessage("could not write shell prompt setup", .{});124        return error.FileNotFound;125    };126    errdefer file.close(io);127128    const content =129        \\PS1="${NINA_PS1:-$PS1}"130        \\trap 'exit 130' INT131        \\132    ;133    file.writePositionalAll(io, content, 0) catch {134        errors.error_info.setMessage("could not write shell prompt setup", .{});135        return error.FileNotFound;136    };137    file.close(io);138139    return owned_path;140}141142// Stream a local process with inherited stdio (no SSH routing — for nix commands).143pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 {144    output.flush();145    var child = std.process.spawn(io, .{146        .argv = cmd,147        .stdin = .inherit,148        .stdout = .inherit,149        .stderr = .inherit,150    }) catch |e| {151        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});152        return e;153    };154    const term = child.wait(io) catch {155        errors.error_info.setMessage("process wait failed", .{});156        return error.ProcessFailed;157    };158    return switch (term) {159        .exited => |c| c,160        else => 1,161    };162}163164// Run a process and capture output as a single string (no SSH routing — for local nix commands).165pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {166    const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;167    defer gpa.free(result.stderr);168    switch (result.term) {169        .exited => |c| if (c != 0) {170            gpa.free(result.stdout);171            return error.ProcessFailed;172        },173        else => {174            gpa.free(result.stdout);175            return error.ProcessFailed;176        },177    }178    return result.stdout;179}180181// Create a directory and its parents, best-effort. Shelling out to `mkdir -p`182// matches how the rest of exec.zig provisions config locations (~/.config/nix).183pub fn ensureDir(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) void {184    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir }) catch {};185}186187// Optional user hooks live in ~/.config/nina/hooks and must be executable.188// They are always local: hooks protect the user's local workflow before nina189// starts state-changing work.190pub fn runHook(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, hook_name: []const u8) !HookRun {191    const home = environ.get("HOME") orelse return .{192        .result = .not_found,193        .output = try gpa.dupe(u8, ""),194    };195196    const hook_dir = try std.fs.path.join(gpa, &.{ home, ".config", "nina", "hooks" });197    defer gpa.free(hook_dir);198    ensureDir(gpa, io, hook_dir);199200    const hook_path = try std.fs.path.join(gpa, &.{ hook_dir, hook_name });201    defer gpa.free(hook_path);202203    const executable = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", "test -x \"$1\"", "nina-hook-check", hook_path } }) catch return .{204        .result = .not_found,205        .output = try gpa.dupe(u8, ""),206    };207    defer gpa.free(executable.stdout);208    defer gpa.free(executable.stderr);209    const is_executable = switch (executable.term) {210        .exited => |code| code == 0,211        else => false,212    };213    if (!is_executable) return .{214        .result = .not_found,215        .output = try gpa.dupe(u8, ""),216    };217218    const tmp_raw = try captureLocal(gpa, io, &.{ "mktemp", "/tmp/nina-hook.XXXXXX" });219    defer gpa.free(tmp_raw);220    const tmp_output = std.mem.trim(u8, tmp_raw, " \t\r\n");221    defer if (std.fs.path.isAbsolute(tmp_output)) std.Io.Dir.deleteFileAbsolute(io, tmp_output) catch {};222223    const result = try std.process.run(gpa, io, .{224        .argv = &.{225            "sh",226            "-c",227            "$1 > \"$2\" 2>&1; code=$?; tail -c 4096 \"$2\"; exit \"$code\"",228            "nina-hook-run",229            hook_path,230            tmp_output,231        },232        .stdout_limit = .limited(4096),233        .stderr_limit = .limited(512),234    });235    defer gpa.free(result.stdout);236    defer gpa.free(result.stderr);237238    const exit_code = switch (result.term) {239        .exited => |code| code,240        else => 1,241    };242    return .{243        .result = if (exit_code == 0) .ok else .failed,244        .exit_code = exit_code,245        .output = try std.fmt.allocPrint(gpa, "{s}{s}", .{ result.stdout, result.stderr }),246    };247}248249test "runHook ignores non-executable hooks and captures failures" {250    const a = std.testing.allocator;251    const io = std.testing.io;252253    var tmp = std.testing.tmpDir(.{});254    defer tmp.cleanup();255256    const home = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{&tmp.sub_path});257    defer a.free(home);258259    var env: std.process.Environ.Map = .init(a);260    defer env.deinit();261    try env.put("HOME", home);262263    var hook_dir = try tmp.dir.createDirPathOpen(io, ".config/nina/hooks", .{});264    defer hook_dir.close(io);265266    const script =267        \\#!/bin/sh268        \\echo hook says no269        \\echo detail >&2270        \\exit 3271        \\272    ;273    {274        const file = try hook_dir.createFile(io, "pre-apply", .{});275        defer file.close(io);276        try file.writePositionalAll(io, script, 0);277        try file.setPermissions(io, .fromMode(0o644));278    }279280    const missing = try runHook(a, io, &env, "pre-apply");281    defer a.free(missing.output);282    try std.testing.expectEqual(HookResult.not_found, missing.result);283284    try hook_dir.setFilePermissions(io, "pre-apply", .fromMode(0o755), .{});285286    const failed = try runHook(a, io, &env, "pre-apply");287    defer a.free(failed.output);288    try std.testing.expectEqual(HookResult.failed, failed.result);289    try std.testing.expectEqual(@as(u8, 3), failed.exit_code);290    try std.testing.expect(std.mem.indexOf(u8, failed.output, "hook says no") != null);291    try std.testing.expect(std.mem.indexOf(u8, failed.output, "detail") != null);292}293294fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {295    if (machine.local) return cmd;296297    const host = machine.host orelse {298        errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});299        return error.SshFailed;300    };301302    var ssh: std.ArrayList([]const u8) = .empty;303    try ssh.append(gpa, "ssh");304    try ssh.append(gpa, "-o");305    try ssh.append(gpa, "BatchMode=yes");306    try ssh.append(gpa, "-o");307    try ssh.append(gpa, "StrictHostKeyChecking=accept-new");308    if (machine.ssh_key) |key| {309        try ssh.append(gpa, "-i");310        try ssh.append(gpa, key);311    }312    const addr = if (machine.user) |u|313        try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })314    else315        try gpa.dupe(u8, host);316    try ssh.append(gpa, addr);317    for (cmd) |arg| try ssh.append(gpa, arg);318    return ssh.toOwnedSlice(gpa);319}320321// --- NixOS rebuild ---322323// True if the machine's config dir holds a flake.nix. Only meaningful for a local324// machine — the file lives on the local filesystem. Remote flake detection would325// need an ssh round-trip; a remote flake at the default /etc/nixos needs no flag326// anyway, so we don't bother.327// True if `dir` contains a flake.nix (local filesystem check).328pub fn dirHasFlake(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) bool {329    const flake_path = std.fs.path.join(gpa, &.{ dir, "flake.nix" }) catch return false;330    defer gpa.free(flake_path);331    return pathExists(io, flake_path);332}333334pub fn configHasFlake(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {335    if (!machine.local) return false;336    return dirHasFlake(gpa, io, machine.config_path);337}338339// nixos-rebuild auto-detects /etc/nixos/flake.nix, so the --flake flag is only340// needed when the flake lives elsewhere. A flake at a non-default path must be341// passed explicitly or nixos-rebuild falls back to channels. Compare with342// trailing slashes trimmed so "/etc/nixos/" is still treated as the default.343fn useFlakeFlag(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {344    if (!configHasFlake(gpa, io, machine)) return false;345    var path = machine.config_path;346    while (path.len > 1 and path[path.len - 1] == '/') path = path[0 .. path.len - 1];347    return !std.mem.eql(u8, path, "/etc/nixos");348}349350// Capture nixos-rebuild stderr for the translation pipeline. Raw nix build351// output is suppressed; on failure, reportError() translates stderr via352// errors.translateError(). The substep line above the call tells the user what353// is running; silence during the build is intentional per the error-wrapping brief.354fn nixosRebuildRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, flake: bool) !u8 {355    const argv: []const []const u8 = if (flake)356        &.{ "sudo", "nixos-rebuild", verb, "--flake", machine.config_path }357    else358        &.{ "sudo", "nixos-rebuild", verb };359    output.flush();360    const r = try capture(gpa, io, machine, argv);361    defer gpa.free(r.stdout);362    defer gpa.free(r.stderr);363    errors.setBuildStderr(r.stderr);364    return r.exit_code;365}366367pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {368    const flake = useFlakeFlag(gpa, io, machine);369    if (flake) {370        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});371    } else {372        output.printSubstep("nixos-rebuild switch", .{});373    }374    return nixosRebuildRun(io, machine, gpa, "switch", flake);375}376377pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {378    return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine));379}380381pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {382    return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine));383}384385// --- Generations ---386387// Read system-profile generations WITHOUT root. `nix-env --list-generations -p388// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user389// ("system.lock: Permission denied"). The generation symlinks themselves are390// world-readable, so list them directly: parse `system-N-link` names, take each391// link's own mtime for the date/time, and mark the one the `system` symlink392// points at as current. Output matches the `nix-env --list-generations` columns393// (num date time [current]) so parseGenerations is unchanged.394const GEN_LIST_SCRIPT =395    \\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 }'396;397398pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {399    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });400    defer gpa.free(r.stderr);401    defer gpa.free(r.stdout);402    if (r.exit_code != 0) return error.ProcessFailed;403    return parseGenerations(gpa, r.stdout);404}405406fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {407    var gens: std.ArrayList(types.GenerationInfo) = .empty;408    var lines = std.mem.splitScalar(u8, output_str, '\n');409    while (lines.next()) |line| {410        const trimmed = std.mem.trim(u8, line, " \t");411        if (trimmed.len == 0) continue;412        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");413        const num_str = parts.next() orelse continue;414        const date_str = parts.next() orelse continue;415        const time_str = parts.next() orelse continue;416        const rest = parts.rest();417        const current = std.mem.indexOf(u8, rest, "current") != null;418        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;419        try gens.append(gpa, .{420            .number = num,421            .date = try gpa.dupe(u8, date_str),422            .time = try gpa.dupe(u8, time_str),423            .current = current,424        });425    }426    return gens.toOwnedSlice(gpa);427}428429pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {430    const gens = try getGenerations(gpa, io, machine);431    defer gpa.free(gens);432    for (gens) |g| {433        if (g.current) return g.number;434    }435    return 0;436}437438pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {439    // Switch the system profile to generation n, then activate it (bootloader +440    // services). Without switch-to-configuration the change isn't applied.441    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 });442    defer gpa.free(cmd);443    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });444}445446pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {447    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });448}449450pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {451    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});452    defer gpa.free(n_str);453    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });454}455456pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {457    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });458}459460// --- Garbage collection ---461462pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {463    if (delete_old) {464        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });465    }466    // Keep the `keep` most recent system generations (+N deletes all but N),467    // then collect now-unreferenced store paths. `--delete-older-than` wants a468    // duration (e.g. 14d), not a generation count.469    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });470    defer gpa.free(cmd);471    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });472}473474// --- Channels ---475476pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {477    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });478    defer gpa.free(r.stderr);479    defer gpa.free(r.stdout);480    if (r.exit_code != 0) return error.ProcessFailed;481    return parseChannels(gpa, r.stdout);482}483484fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {485    var channels: std.ArrayList(types.ChannelInfo) = .empty;486    var lines = std.mem.splitScalar(u8, output_str, '\n');487    while (lines.next()) |line| {488        const trimmed = std.mem.trim(u8, line, " \t\r");489        if (trimmed.len == 0) continue;490        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;491        try channels.append(gpa, .{492            .name = try gpa.dupe(u8, trimmed[0..space]),493            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),494        });495    }496    return channels.toOwnedSlice(gpa);497}498499pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {500    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });501}502503pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {504    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });505}506507pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {508    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });509}510511// --- Services ---512513pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {514    const cmd: []const []const u8 = if (user)515        &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }516    else517        &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };518    const r = try capture(gpa, io, machine, cmd);519    defer gpa.free(r.stderr);520    defer gpa.free(r.stdout);521    if (r.exit_code != 0) return error.ProcessFailed;522    return parseServices(gpa, r.stdout);523}524525fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {526    var svcs: std.ArrayList(types.ServiceInfo) = .empty;527    var lines = std.mem.splitScalar(u8, output_str, '\n');528    while (lines.next()) |line| {529        const trimmed = std.mem.trim(u8, line, " \t\r");530        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines531        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");532        const name = parts.next() orelse continue;533        _ = parts.next(); // load534        const active_str = parts.next() orelse continue;535        const sub_str = parts.next() orelse "unknown";536537        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))538            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)539        else if (std.mem.eql(u8, active_str, "failed"))540            .failed541        else542            .inactive;543544        try svcs.append(gpa, .{545            .name = try gpa.dupe(u8, name),546            .state = state,547            .uptime = null,548        });549    }550    return svcs.toOwnedSlice(gpa);551}552553pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {554    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.555    // User services run under the caller's own systemd manager, so no sudo.556    if (user) {557        return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });558    }559    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });560}561562pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {563    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});564    defer gpa.free(n_str);565    if (user) {566        if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });567        return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });568    }569    if (follow) {570        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });571    }572    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });573}574575// --- Profile ---576577pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {578    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});579    defer gpa.free(pkg_ref);580    // `nix profile add` is the current verb; `install` is a deprecated alias that581    // prints a warning on modern nix.582    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });583}584585pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {586    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not587    // by flake ref — passing nixpkgs#ripgrep matches nothing.588    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });589}590591pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {592    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });593    defer gpa.free(r.stderr);594    if (r.exit_code != 0) return error.ProcessFailed;595    return r.stdout;596}597598// Machine-readable profile listing — caller parses elements -> name + version.599pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {600    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });601    defer gpa.free(r.stderr);602    if (r.exit_code != 0) {603        gpa.free(r.stdout);604        return error.ProcessFailed;605    }606    return r.stdout;607}608609// Returns the profile element name to pass to `nix profile remove/upgrade`610// (e.g. "nina" or "default"), or null if nina is not found. Caller owns the611// returned slice. A NixOS system-package install also resolves into /nix/store612// so the store path alone can't distinguish it from a profile install — the613// profile list can. A missing/empty profile (or no nix) returns null.614pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {615    const js = profileListJson(gpa, io, machine) catch return null;616    defer gpa.free(js);617    return profileJsonNinaElement(gpa, js);618}619620pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {621    const name = profileNinaElement(gpa, io, machine) orelse return false;622    gpa.free(name);623    return true;624}625626// True when a nix store path belongs to the nina package. Store paths have the627// form /nix/store/<32-char-hash>-<pname>-<version>[/<subpath>]. We check that628// the 33 chars after /nix/store/ are the hash+dash, and the pname that follows629// is exactly "nina" (followed by "-" or end-of-component).630fn storePathIsNina(path: []const u8) bool {631    const prefix = "/nix/store/";632    if (!std.mem.startsWith(u8, path, prefix)) return false;633    const rel = path[prefix.len..];634    // The store entry name ends at the first "/" (if any sub-path follows).635    const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];636    if (entry.len < 34) return false; // 32-char hash + dash + at least one char637    const pname_ver = entry[33..]; // skip hash + dash638    return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");639}640641// Pure parse of `nix profile list --json` for a nina element, returning its642// element name (the key to pass to `nix profile remove/upgrade`) or null.643// Newer nix (2.18+) keys elements by pname ("nina"). Older nix uses an array644// with an "attrPath" field. Tarball installs via the `default` output may use645// the key "default" instead of "nina"; we detect those via storePaths.646fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {647    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;648    defer parsed.deinit();649    const root = parsed.value;650    if (root != .object) return null;651    const elements = root.object.get("elements") orelse return null;652    switch (elements) {653        .object => |obj| {654            // Fast path: exact "nina" key (nix 2.18+ with nixpkgs#nina install).655            if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;656            // Fallback: scan storePaths. Handles tarball installs where the default657            // output is selected and nix names the element "default" (older nix) or658            // some other key derived from the attrPath rather than the pname.659            var it = obj.iterator();660            while (it.next()) |kv| {661                const val = kv.value_ptr.*;662                if (val != .object) continue;663                const sps = val.object.get("storePaths") orelse continue;664                if (sps != .array) continue;665                for (sps.array.items) |sp| {666                    if (sp == .string and storePathIsNina(sp.string))667                        return gpa.dupe(u8, kv.key_ptr.*) catch null;668                }669            }670            return null;671        },672        .array => |arr| {673            // Older nix array format. Element name is the last component of attrPath.674            for (arr.items) |el| {675                if (el != .object) continue;676                const ap = el.object.get("attrPath") orelse continue;677                if (ap != .string) continue;678                if (std.mem.eql(u8, ap.string, "nina") or679                    std.mem.endsWith(u8, ap.string, ".nina"))680                    return gpa.dupe(u8, "nina") catch null;681                // Tarball default-output install: attrPath ends in ".default" but682                // storePaths point to nina. Return "default" as the element name.683                const sps = el.object.get("storePaths") orelse continue;684                if (sps != .array) continue;685                for (sps.array.items) |sp| {686                    if (sp != .string) continue;687                    if (!storePathIsNina(sp.string)) continue;688                    const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;689                    const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;690                    return gpa.dupe(u8, el_name) catch null;691                }692            }693            return null;694        },695        else => return null,696    }697}698699test "profileJsonNinaElement finds element name from profile JSON" {700    const a = std.testing.allocator;701702    // Newer nix: elements keyed by pname. "nina" key present.703    const named =704        \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},705        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}706    ;707    const r1 = profileJsonNinaElement(a, named);708    defer if (r1) |n| a.free(n);709    try std.testing.expectEqualStrings("nina", r1.?);710711    // Tarball install via default output: element keyed as "default", storePath is nina.712    const default_key =713        \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}714    ;715    const r2 = profileJsonNinaElement(a, default_key);716    defer if (r2) |n| a.free(n);717    try std.testing.expectEqualStrings("default", r2.?);718719    // Decoy: storePath of another package contains "nina" as a substring but is not nina.720    const decoy =721        \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}722    ;723    const r3 = profileJsonNinaElement(a, decoy);724    try std.testing.expectEqual(@as(?[]const u8, null), r3);725726    // Older nix array schema, attrPath ending in ".nina".727    const arr =728        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}729    ;730    const r4 = profileJsonNinaElement(a, arr);731    defer if (r4) |n| a.free(n);732    try std.testing.expectEqualStrings("nina", r4.?);733734    // Older nix array schema, tarball default-output install.735    const arr_default =736        \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}737    ;738    const r5 = profileJsonNinaElement(a, arr_default);739    defer if (r5) |n| a.free(n);740    try std.testing.expectEqualStrings("default", r5.?);741742    // Empty / malformed → null.743    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));744    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));745}746747// The store paths that make up the running system environment. Each reference is748// a <hash>-<name>-<version> path, so the caller can list system packages with749// versions — there is no cleaner per-package list for environment.systemPackages.750pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {751    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });752    defer gpa.free(r.stderr);753    if (r.exit_code != 0) {754        gpa.free(r.stdout);755        return error.ProcessFailed;756    }757    return r.stdout;758}759760pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {761    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });762}763764// --- Store ---765766pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {767    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });768}769770pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {771    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });772}773774pub const SystemStatus = struct { size: []u8, age: []u8 };775776// One read-only pass for `nina status`: the current system's closure size (a777// single `path-info -S` of /run/current-system — fast, unlike -S over the whole778// store) and seconds since the system profile was last switched (its symlink779// mtime). Both are world-readable; no root needed.780const STATUS_SCRIPT =781    \\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} ))"782;783784pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {785    const unknown = SystemStatus{786        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },787        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },788    };789    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;790    defer gpa.free(r.stdout);791    defer gpa.free(r.stderr);792    if (r.exit_code != 0) return unknown;793794    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");795    const sz_str = it.next() orelse return unknown;796    const age_str = it.next() orelse return unknown;797    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;798    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;799800    gpa.free(unknown.size);801    gpa.free(unknown.age);802    return .{803        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),804        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),805    };806}807808// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A809// one-word health signal; exits non-zero when degraded, so we read stdout, not810// the code. Caller owns the returned slice.811pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {812    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch813        return gpa.dupe(u8, "unknown");814    defer gpa.free(r.stderr);815    const state = std.mem.trim(u8, r.stdout, " \t\n\r");816    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");817    gpa.free(r.stdout);818    return owned;819}820821fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {822    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});823    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});824    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});825    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});826}827828pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {829    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });830}831832pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {833    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)834    // graph work that takes minutes on a real store (59k+ paths) and hangs the835    // command. We don't need closures: `--all --json` (no -S) carries each path's836    // own narSize, so one fast pass gives the path count and the summed store size.837    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.838    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.839    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });840    defer gpa.free(pi.stdout);841    defer gpa.free(pi.stderr);842843    const scan = scanStoreJson(pi.stdout);844    const total_owned = try humanSize(gpa, scan.total_bytes);845846    return .{847        .total_size = total_owned,848        .live_paths = scan.count,849        .reclaimable_paths = 0,850    };851}852853const StoreScan = struct { count: u64, total_bytes: u64 };854855// One linear pass over `nix path-info --json`: each path object has exactly one856// "narSize": field, so counting them gives the true path count and summing the857// values gives the total store size — no per-path closure walk.858fn scanStoreJson(json_str: []const u8) StoreScan {859    const needle = "\"narSize\":";860    var count: u64 = 0;861    var total: u64 = 0;862    var i: usize = 0;863    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {864        var j = pos + needle.len;865        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}866        var val: u64 = 0;867        var any = false;868        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {869            val = val * 10 + (json_str[j] - '0');870            any = true;871        }872        if (any) {873            count += 1;874            total += val;875        }876        i = j;877    }878    return .{ .count = count, .total_bytes = total };879}880881fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {882    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };883    var val: f64 = @floatFromInt(bytes);884    var unit: usize = 0;885    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;886    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });887    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });888}889890pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {891    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the892    // flake registry), not a flake in the current directory.893    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});894    defer gpa.free(expr);895    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });896    defer gpa.free(r.stderr);897    if (r.exit_code != 0) {898        gpa.free(r.stdout);899        return error.ProcessFailed;900    }901    return r.stdout;902}903904// --- Flake ---905906pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {907    if (input) |inp| {908        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });909    }910    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });911}912913// Update flake inputs for the flake living in `dir` (the config dir). `nix flake914// update` operates on the flake in the working directory, so we cd there first.915// Used by `nina upgrade` on a flake system in place of nix-channel --update.916pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {917    return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });918}919920pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {921    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });922}923924pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {925    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });926}927928pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {929    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });930}931932pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {933    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });934}935936pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {937    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });938    defer gpa.free(r.stderr);939    if (r.exit_code != 0) {940        gpa.free(r.stdout);941        return error.ProcessFailed;942    }943    return r.stdout;944}945946// --- Build / Run / Develop ---947948pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {949    if (attr) |a| {950        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});951        defer gpa.free(ref);952        return stream(io, machine, gpa, &.{ "nix", "build", ref });953    }954    return stream(io, machine, gpa, &.{ "nix", "build" });955}956957pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {958    // nix run always gets --no-write-lock-file for remote URLs959    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");960    if (is_url) {961        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });962    }963    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.964    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {965        return stream(io, machine, gpa, &.{ "nix", "run", pkg });966    }967    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});968    defer gpa.free(ref);969    return stream(io, machine, gpa, &.{ "nix", "run", ref });970}971972pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {973    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});974    defer gpa.free(ref);975    return stream(io, machine, gpa, &.{ "nix", "shell", ref });976}977978pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {979    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});980    defer gpa.free(ref);981    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});982    defer gpa.free(ps1);983    if (machine.local) {984        const rc_path = try createInteractiveShellRc(gpa, io);985        defer {986            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};987            gpa.free(rc_path);988        }989        return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref, "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, ps1);990    }991    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);992}993994pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {995    if (run_cmd) |cmd| {996        // sh -c so a multi-word command isn't treated as a single executable name.997        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });998    }999    return stream(io, machine, gpa, &.{ "nix", "develop" });1000}10011002pub fn nixDevelopPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8, base_env: *const std.process.Environ.Map) !u8 {1003    if (run_cmd) |cmd| {1004        // sh -c so a multi-word command isn't treated as a single executable name.1005        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1006    }1007    if (machine.local) {1008        const rc_path = try createInteractiveShellRc(gpa, io);1009        defer {1010            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1011            gpa.free(rc_path);1012        }1013        return streamEnv(io, machine, gpa, &.{ "nix", "develop", "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, "(nina: dev) -> ");1014    }1015    return streamEnv(io, machine, gpa, &.{ "nix", "develop" }, base_env, "(nina: dev) -> ");1016}10171018pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1019    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });1020}10211022// --- Format ---10231024pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {1025    if (check) {1026        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });1027    }1028    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });1029}10301031// --- Info ---10321033pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1034    const r = try capture(gpa, io, machine, &.{"nixos-version"});1035    defer gpa.free(r.stderr);1036    if (r.exit_code != 0) {1037        gpa.free(r.stdout);1038        return error.ProcessFailed;1039    }1040    return r.stdout;1041}10421043pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1044    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });1045    defer gpa.free(r.stderr);1046    if (r.exit_code != 0) {1047        gpa.free(r.stdout);1048        return error.ProcessFailed;1049    }1050    return r.stdout;1051}10521053pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1054    const r = try capture(gpa, io, machine, &.{"uptime"});1055    defer gpa.free(r.stderr);1056    if (r.exit_code != 0) {1057        gpa.free(r.stdout);1058        return error.ProcessFailed;1059    }1060    return r.stdout;1061}10621063// --- Boot ---10641065pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {1066    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });1067    defer gpa.free(r.stderr);1068    defer gpa.free(r.stdout);1069    if (r.exit_code != 0) return error.ProcessFailed;1070    return parseBootEntries(gpa, r.stdout);1071}10721073fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {1074    var entries: std.ArrayList(types.BootEntry) = .empty;1075    var lines = std.mem.splitScalar(u8, output_str, '\n');1076    while (lines.next()) |line| {1077        const trimmed = std.mem.trim(u8, line, " \t\r");1078        if (std.mem.startsWith(u8, trimmed, "title:")) {1079            const title = std.mem.trim(u8, trimmed[6..], " \t");1080            const current = std.mem.indexOf(u8, title, "(current)") != null;1081            try entries.append(gpa, .{1082                .title = try gpa.dupe(u8, title),1083                .current = current,1084            });1085        }1086    }1087    return entries.toOwnedSlice(gpa);1088}10891090// --- Pkg info ---10911092fn pkgInstallable(gpa: std.mem.Allocator, pkg: []const u8) ![]u8 {1093    return std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1094}10951096fn resolvePkgStorePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, installable: []const u8) ![]u8 {1097    const r = try capture(gpa, io, machine, &.{ "nix", "build", "--no-link", "--print-out-paths", installable });1098    defer gpa.free(r.stderr);1099    defer gpa.free(r.stdout);1100    if (r.exit_code != 0) return error.PackageNotFound;11011102    var lines = std.mem.tokenizeAny(u8, r.stdout, "\r\n");1103    const first_path = lines.next() orelse return error.PackageNotFound;1104    const store_path = std.mem.trim(u8, first_path, " \t");1105    if (store_path.len == 0) return error.PackageNotFound;1106    return gpa.dupe(u8, store_path);1107}11081109pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1110    const installable = try pkgInstallable(gpa, pkg);1111    defer gpa.free(installable);1112    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1113    defer gpa.free(store_path);1114    return stream(io, machine, gpa, &.{ "nix", "why-depends", "/run/current-system", store_path });1115}11161117pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1118    const installable = try pkgInstallable(gpa, pkg);1119    defer gpa.free(installable);1120    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1121    defer gpa.free(store_path);1122    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", store_path });1123}11241125pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {1126    const installable = try pkgInstallable(gpa, pkg);1127    defer gpa.free(installable);1128    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", "--json", installable });1129    defer gpa.free(r.stderr);1130    defer gpa.free(r.stdout);1131    if (r.exit_code != 0) return error.ProcessFailed;11321133    const nar_size = try pathInfoNarSize(gpa, r.stdout);1134    return humanPkgSize(gpa, nar_size);1135}11361137pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1138    const installable = try pkgInstallable(gpa, pkg);1139    defer gpa.free(installable);1140    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1141    defer gpa.free(store_path);1142    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", store_path });1143}11441145fn pathInfoNarSize(gpa: std.mem.Allocator, json_str: []const u8) !u64 {1146    var parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.ProcessFailed;1147    defer parsed.deinit();1148    switch (parsed.value) {1149        .object => |obj| {1150            var it = obj.iterator();1151            while (it.next()) |entry| {1152                if (entry.value_ptr.* == .object) {1153                    if (entry.value_ptr.object.get("narSize")) |v| {1154                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1155                    }1156                }1157            }1158        },1159        .array => |arr| {1160            for (arr.items) |item| {1161                if (item == .object) {1162                    if (item.object.get("narSize")) |v| {1163                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1164                    }1165                }1166            }1167        },1168        else => {},1169    }1170    return error.ProcessFailed;1171}11721173fn humanPkgSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1174    const units = [_][]const u8{ "B", "KiB", "MiB", "GiB", "TiB" };1175    var val: f64 = @floatFromInt(bytes);1176    var unit: usize = 0;1177    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1178    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1179    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1180}11811182test "pathInfoNarSize parses object and array shapes" {1183    try std.testing.expectEqual(@as(u64, 1064629862), try pathInfoNarSize(std.testing.allocator,1184        \\{"/nix/store/abc-ffmpeg":{"narSize":1064629862}}1185    ));1186    try std.testing.expectEqual(@as(u64, 2048), try pathInfoNarSize(std.testing.allocator,1187        \\[{"path":"/nix/store/abc-pkg","narSize":2048}]1188    ));1189}11901191// --- Hash / Fetch ---11921193pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {1194    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });1195    defer gpa.free(r.stderr);1196    if (r.exit_code != 0) {1197        gpa.free(r.stdout);1198        return error.ProcessFailed;1199    }1200    return r.stdout;1201}12021203pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {1204    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });1205    defer gpa.free(r.stderr);1206    if (r.exit_code != 0) {1207        gpa.free(r.stdout);1208        return error.ProcessFailed;1209    }1210    return r.stdout;1211}12121213// --- Pin ---12141215pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {1216    // Stub: full implementation would parse and edit flake.lock JSON1217    // The pin/unpin flow works via nix flake update which regenerates flake.lock1218}12191220pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {1221    if (line) |l| {1222        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});1223        defer gpa.free(line_arg);1224        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });1225    }1226    return stream(io, &types.Machine{}, gpa, &.{ editor, path });1227}12281229pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {1230    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});1231    defer gpa.free(a_str);1232    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});1233    defer gpa.free(b_str);1234    // On a tty, the child's own color is fine — stream it directly.1235    if (output.colorEnabled()) {1236        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });1237    }1238    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,1239    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.1240    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });1241    defer gpa.free(r.stdout);1242    defer gpa.free(r.stderr);1243    const cleaned = try stripAnsi(gpa, r.stdout);1244    defer gpa.free(cleaned);1245    output.raw(cleaned);1246    return r.exit_code;1247}12481249// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a1250// child process's color when it writes ANSI unconditionally.1251fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1252    var out: std.ArrayList(u8) = .empty;1253    errdefer out.deinit(gpa);1254    var i: usize = 0;1255    while (i < input.len) {1256        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1257            i += 2;1258            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1259            if (i < input.len) i += 1; // consume the final byte1260            continue;1261        }1262        try out.append(gpa, input[i]);1263        i += 1;1264    }1265    return out.toOwnedSlice(gpa);1266}12671268test "stripAnsi removes CSI color sequences" {1269    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1270    defer std.testing.allocator.free(cleaned);1271    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1272}12731274// --- Doctor checks ---12751276pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1277    var checks: std.ArrayList(types.DoctorCheck) = .empty;12781279    // Check nix daemon1280    {1281        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1282        defer gpa.free(r.stdout);1283        defer gpa.free(r.stderr);1284        const active = std.mem.indexOf(u8, r.stdout, "active") != null;1285        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1286    }12871288    // Check config syntax. Flake-aware like apply/upgrade: on a flake system a1289    // plain `nixos-rebuild dry-build` evaluates <nixpkgs/nixos> + <nixos-config>1290    // (channel style) and fails, so pass --flake when the config dir has one.1291    {1292        const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1293            &.{ "sudo", "nixos-rebuild", "dry-build", "--flake", machine.config_path }1294        else1295            &.{ "sudo", "nixos-rebuild", "dry-build" };1296        const r = try capture(gpa, io, machine, argv);1297        defer gpa.free(r.stdout);1298        defer gpa.free(r.stderr);1299        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1300    }13011302    // Check channel1303    {1304        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1305        defer gpa.free(r.stdout);1306        defer gpa.free(r.stderr);1307        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1308        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1309    }13101311    return checks.toOwnedSlice(gpa);1312}13131314// --- Home Manager ---1315//1316// Home Manager has three usage modes. nina detects which one is in play before1317// any `home` command so it can either drive the standalone CLI or redirect the1318// user to `nina apply` (when HM is a NixOS/flake module activated by rebuild).13191320pub const HomeManagerMode = enum {1321    // home-manager binary on PATH — manages the user env on its own.1322    standalone,1323    // No binary, but a home.nix exists — HM is a NixOS/flake module rebuilt by1324    // nixos-rebuild. `nina home apply` redirects to `nina apply`.1325    module,1326    none,1327};13281329fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1330    const home = environ.get("HOME") orelse return null;1331    return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1332}13331334// Path to the standalone home.nix. Caller frees.1335pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1336    const dir = homeConfigDir(gpa, environ) orelse return null;1337    defer gpa.free(dir);1338    return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1339}13401341pub fn pathExists(io: std.Io, path: []const u8) bool {1342    const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1343    f.close(io);1344    return true;1345}13461347// `command -v <name>` — true if the binary resolves on PATH. Silent (captured),1348// unlike streamLocal which would inherit stdio.1349fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1350    var buf: [256]u8 = undefined;1351    const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1352    const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1353    defer gpa.free(r.stdout);1354    defer gpa.free(r.stderr);1355    return switch (r.term) {1356        .exited => |code| code == 0,1357        else => false,1358    };1359}13601361pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1362    if (commandExists(gpa, io, "home-manager")) return .standalone;1363    if (homeNixPath(gpa, environ)) |p| {1364        defer gpa.free(p);1365        if (pathExists(io, p)) return .module;1366    }1367    return .none;1368}13691370// If the home-manager config dir holds a flake.nix, returns the flake ref1371// "<dir>#<user>" for `home-manager switch --flake`. Username comes from $USER.1372// Caller frees. null when there's no flake.nix (channel-based home config).1373pub fn homeFlakeRef(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1374    const dir = homeConfigDir(gpa, environ) orelse return null;1375    defer gpa.free(dir);1376    const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch return null;1377    defer gpa.free(flake);1378    if (!pathExists(io, flake)) return null;1379    const user = environ.get("USER") orelse "default";1380    return std.fmt.allocPrint(gpa, "{s}#{s}", .{ dir, user }) catch null;1381}13821383pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1384    output.flush();1385    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch" });1386    defer gpa.free(r.stdout);1387    defer gpa.free(r.stderr);1388    errors.setBuildStderr(r.stderr);1389    return r.exit_code;1390}13911392pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8) !u8 {1393    output.flush();1394    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch", "--flake", flake_ref });1395    defer gpa.free(r.stdout);1396    defer gpa.free(r.stderr);1397    errors.setBuildStderr(r.stderr);1398    return r.exit_code;1399}14001401// home-manager has no system-profile rollback; it re-activates the previous1402// generation via `switch --rollback`.1403pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1404    output.flush();1405    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch", "--rollback" });1406    defer gpa.free(r.stdout);1407    defer gpa.free(r.stderr);1408    errors.setBuildStderr(r.stderr);1409    return r.exit_code;1410}14111412// Build (and validate) the home config without activating it — used by `home1413// check` and `home apply --dry`. `home-manager build` drops a ./result symlink1414// in the cwd, so run it in a throwaway temp dir to avoid littering the directory1415// nina was invoked from.1416pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1417    output.flush();1418    const r = try capture(gpa, io, machine, &.{ "sh", "-c", "d=$(mktemp -d) && cd \"$d\" && home-manager build" });1419    defer gpa.free(r.stdout);1420    defer gpa.free(r.stderr);1421    errors.setBuildStderr(r.stderr);1422    return r.exit_code;1423}14241425pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1426    const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1427    defer gpa.free(r.stderr);1428    if (r.exit_code != 0) {1429        gpa.free(r.stdout);1430        return error.ProcessFailed;1431    }1432    return r.stdout;1433}14341435// Store paths referenced by a home generation — used to list managed packages.1436pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1437    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1438    defer gpa.free(r.stderr);1439    if (r.exit_code != 0) {1440        gpa.free(r.stdout);1441        return error.ProcessFailed;1442    }1443    return r.stdout;1444}14451446// diff-closures between two arbitrary store paths (home generations), mirroring1447// diffClosures' tty/piped color handling.1448pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1449    if (output.colorEnabled()) {1450        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1451    }1452    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1453    defer gpa.free(r.stdout);1454    defer gpa.free(r.stderr);1455    const cleaned = try stripAnsi(gpa, r.stdout);1456    defer gpa.free(cleaned);1457    output.raw(cleaned);1458    return r.exit_code;1459}14601461// --- Log ---14621463pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1464    const home = environ.get("HOME") orelse return error.FileNotFound;1465    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1466    defer gpa.free(path);1467    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1468    if (last == 0) return content;14691470    // Collect non-empty lines, then keep only the final `last`. Slices point into1471    // `content`, so copy them out before freeing it.1472    var lines: std.ArrayList([]const u8) = .empty;1473    defer lines.deinit(gpa);1474    var it = std.mem.splitScalar(u8, content, '\n');1475    while (it.next()) |line| {1476        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1477        try lines.append(gpa, line);1478    }1479    if (lines.items.len <= last) return content;14801481    var out: std.ArrayList(u8) = .empty;1482    errdefer out.deinit(gpa);1483    for (lines.items[lines.items.len - last ..]) |line| {1484        try out.appendSlice(gpa, line);1485        try out.append(gpa, '\n');1486    }1487    gpa.free(content);1488    return out.toOwnedSlice(gpa);1489}14901491// nina is a one-shot process, so "did the last apply fail this session?" can't1492// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1493// other ~/.nina-* state files. This lets a later successful apply earn the1494// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1495pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1496    const home = environ.get("HOME") orelse return;1497    var buf: [512]u8 = undefined;1498    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1499    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1500    file.close(io);1501}15021503pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1504    const home = environ.get("HOME") orelse return false;1505    var buf: [512]u8 = undefined;1506    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1507    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1508        f.close(io);1509        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1510        return true;1511    } else |_| {1512        return false;1513    }1514}15151516pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1517    const home = environ.get("HOME") orelse return;1518    var path_buf: [512]u8 = undefined;1519    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1520    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1521        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1522    defer file.close(io);1523    const size = file.length(io) catch 0;1524    file.writePositionalAll(io, entry, size) catch {};1525}15261527// --- Update helpers ---15281529// Fetch a URL with curl and return the response body. Caller must free.1530// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.1531pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1532    const argv = [_][]const u8{1533        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1534    };1535    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1536    defer gpa.free(result.stderr);15371538    const marker = "\nHTTP_STATUS:";1539    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1540        gpa.free(result.stdout);1541        return error.NetworkError;1542    };1543    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1544    const status = std.fmt.parseInt(u16, status_str, 10) catch {1545        gpa.free(result.stdout);1546        return error.NetworkError;1547    };1548    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1549    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1550    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1551        gpa.free(result.stdout);1552        return e;1553    };1554    gpa.free(result.stdout);1555    return body;1556}15571558// Download a URL to a temp file. Returns the temp path (caller must gpa.free).1559// The file is written to /tmp/nina-update-<pid> and left for the caller to use.1560pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1561    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1562    errdefer gpa.free(tmp_path);15631564    var child = std.process.spawn(io, .{1565        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1566        .stdin = .close,1567        .stdout = .close,1568        .stderr = .inherit,1569    }) catch return error.NetworkError;1570    const term = child.wait(io) catch return error.NetworkError;1571    switch (term) {1572        .exited => |c| if (c != 0) return error.NetworkError,1573        else => return error.NetworkError,1574    }1575    return tmp_path;1576}15771578// Get the current executable path into buf. Returns slice of buf.1579pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1580    const len = try std.process.executablePath(io, buf);1581    return buf[0..len];1582}15831584// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1585// atomically install the binary to install_path. Errors: ChecksumMismatch,1586// AccessDenied (with error_info set), or underlying I/O errors.1587pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1588    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1589        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1590        return error.FileNotFound;1591    };1592    defer gpa.free(bytes);15931594    var hasher = std.crypto.hash.Blake3.init(.{});1595    hasher.update(bytes);1596    var raw: [32]u8 = undefined;1597    hasher.final(&raw);1598    const hex = std.fmt.bytesToHex(raw, .lower);1599    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;16001601    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1602    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1603        return error.NameTooLong;16041605    {1606        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1607            errors.error_info.setMessage("cannot write to {s}", .{install_path});1608            errors.error_info.setSuggestion("try: sudo nina update", .{});1609            return error.AccessDenied;1610        };1611        defer f.close(io);1612        f.writePositionalAll(io, bytes, 0) catch {1613            errors.error_info.setMessage("cannot write to {s}", .{install_path});1614            return error.AccessDenied;1615        };1616        try f.setPermissions(io, .fromMode(0o755));1617    }1618    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};16191620    if (comptime builtin.os.tag == .macos) {1621        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1622    }16231624    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1625        error.AccessDenied => {1626            errors.error_info.setMessage("cannot replace {s}", .{install_path});1627            errors.error_info.setSuggestion("try: sudo nina update", .{});1628            return error.AccessDenied;1629        },1630        else => return e,1631    };1632}16331634// --- Nix feature setup ---16351636pub const NixFeatureStatus = struct {1637    nix_command: bool = false,1638    flakes: bool = false,16391640    pub fn allEnabled(self: NixFeatureStatus) bool {1641        return self.nix_command and self.flakes;1642    }1643};16441645fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1646    var lines = std.mem.splitScalar(u8, conf, '\n');1647    while (lines.next()) |line| {1648        const trimmed = std.mem.trim(u8, line, " \t");1649        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1650        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1651        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1652    }1653}16541655pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1656    var status = NixFeatureStatus{};16571658    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1659        defer gpa.free(conf);1660        scanConfFeatures(conf, &status);1661    }16621663    if (environ.get("HOME")) |home| {1664        var buf: [512]u8 = undefined;1665        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1666        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1667            defer gpa.free(conf);1668            scanConfFeatures(conf, &status);1669        }1670    }16711672    return status;1673}16741675pub fn isNixOS(io: std.Io) bool {1676    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1677    file.close(io);1678    return true;1679}16801681// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.1682// Returns the path written (caller must free).1683pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1684    const home = environ.get("HOME") orelse {1685        errors.error_info.setMessage("HOME not set", .{});1686        return error.ConfigNotFound;1687    };16881689    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1690    defer gpa.free(dir_path);1691    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1692    errdefer gpa.free(file_path);16931694    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};16951696    const line = "experimental-features = nix-command flakes\n";1697    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1698        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1699        errors.error_info.setMessage("could not write {s}", .{file_path});1700        return error.FileNotFound;1701    });1702    defer file.close(io);17031704    const size = file.length(io) catch 0;1705    file.writePositionalAll(io, line, size) catch {1706        errors.error_info.setMessage("could not write {s}", .{file_path});1707        return error.FileNotFound;1708    };17091710    return file_path;1711}17121713// --- NixOS: declarative experimental-features ---1714//1715// On NixOS the permanent, declarative home for these flags is configuration.nix,1716// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves1717// the `nixos-rebuild switch` to the user.17181719pub const NIXOS_FEATURES_LINE =1720    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";17211722// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns1723// false on any read error so the caller still offers to add the line.1724pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1725    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1726    defer gpa.free(conf);1727    return std.mem.indexOf(u8, conf, "experimental-features") != null and1728        std.mem.indexOf(u8, conf, "nix-command") != null and1729        std.mem.indexOf(u8, conf, "flakes") != null;1730}17311732fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1733    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1734    return captureLocal(gpa, io, &.{ "sudo", "cat", path });1735}17361737// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix1738// (i.e. inside the top-level attribute set) and write it back via a single1739// `sudo cp`, which prompts for the password on the terminal. Returns an error1740// for the caller to fall back to printed manual instructions.1741pub fn appendFeaturesToNixosConfig(1742    gpa: std.mem.Allocator,1743    io: std.Io,1744    environ: *const std.process.Environ.Map,1745    path: []const u8,1746) !void {1747    const conf = readMaybeSudo(gpa, io, path) catch {1748        errors.error_info.setMessage("could not read {s}", .{path});1749        return error.ConfigNotFound;1750    };1751    defer gpa.free(conf);17521753    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared17541755    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1756        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1757        return error.MalformedConfig;1758    };17591760    const home = environ.get("HOME") orelse {1761        errors.error_info.setMessage("HOME not set", .{});1762        return error.ConfigNotFound;1763    };1764    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1765    defer gpa.free(tmp_path);17661767    var buf: std.ArrayList(u8) = .empty;1768    defer buf.deinit(gpa);1769    try buf.appendSlice(gpa, conf[0..brace]);1770    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1771    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");1772    try buf.appendSlice(gpa, "  ");1773    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1774    try buf.append(gpa, '\n');1775    try buf.appendSlice(gpa, conf[brace..]);17761777    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1778        errors.error_info.setMessage("could not write {s}", .{tmp_path});1779        return error.FileNotFound;1780    };1781    tmp.writePositionalAll(io, buf.items, 0) catch {1782        tmp.close(io);1783        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1784        errors.error_info.setMessage("could not write {s}", .{tmp_path});1785        return error.FileNotFound;1786    };1787    tmp.close(io);17881789    // Back up the existing config, then replace it — in one sudo call so the1790    // password is asked for at most once. Paths travel as positional args ($0,1791    // $1) to sidestep shell quoting.1792    const code = streamLocal(io, &.{1793        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1794    }) catch {1795        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1796        errors.error_info.setMessage("could not write {s}", .{path});1797        return error.ProcessFailed;1798    };1799    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1800    if (code != 0) {1801        errors.error_info.setMessage("sudo cp into {s} failed", .{path});1802        return error.ProcessFailed;1803    }1804}