exec.zig

85.2 KB · raw

1// exec.zig — all process execution and SSH routing2// Commands call these functions; output is streamed or captured here.3const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const output = @import("output.zig");89// nixos-rebuild manages this profile; generation commands must target it10// explicitly. Bare nix-env defaults to the per-user profile, which is empty.11const SYSTEM_PROFILE = "/nix/var/nix/profiles/system";1213pub const RunResult = struct {14    stdout: []u8,15    stderr: []u8,16    exit_code: u8,17};1819pub const HookResult = enum {20    ok,21    failed,22    not_found,23};2425pub const HookRun = struct {26    result: HookResult,27    exit_code: u8 = 0,28    output: []u8,29};3031// Run a process and capture stdout+stderr (not streaming).32pub fn capture(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, cmd: []const []const u8) !RunResult {33    const argv = try buildArgv(gpa, machine, cmd);34    defer if (!machine.local) gpa.free(argv);3536    const result = std.process.run(gpa, io, .{ .argv = argv }) catch |e| {37        errors.error_info.setMessage("process failed: {s}", .{cmd[0]});38        return e;39    };4041    return .{42        .stdout = result.stdout,43        .stderr = result.stderr,44        .exit_code = switch (result.term) {45            .exited => |c| c,46            else => 1,47        },48    };49}5051// Run a process and stream its output to the terminal (inherit stdio).52pub fn stream(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8) !u8 {53    // The child inherits stdout and writes directly to the fd; flush any buffered54    // nina header first so it isn't reordered after the child's output.55    output.flush();56    const argv = try buildArgv(gpa, machine, cmd);57    defer if (!machine.local) gpa.free(argv);5859    var child = std.process.spawn(io, .{60        .argv = argv,61        .stdin = .inherit,62        .stdout = .inherit,63        .stderr = .inherit,64    }) catch |e| {65        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});66        return e;67    };6869    const term = child.wait(io) catch |e| {70        errors.error_info.setMessage("process wait failed", .{});71        return e;72    };7374    return switch (term) {75        .exited => |c| c,76        else => 1,77    };78}7980// Stream a process with an overridden PS1 in the child environment.81fn streamEnv(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8, base_env: *const std.process.Environ.Map, ps1: []const u8) !u8 {82    output.flush();83    const argv = try buildArgv(gpa, machine, cmd);84    defer if (!machine.local) gpa.free(argv);8586    var env = try base_env.clone(gpa);87    defer env.deinit();88    try env.put("PS1", ps1);89    try env.put("NINA_PS1", ps1);9091    var child = std.process.spawn(io, .{92        .argv = argv,93        .stdin = .inherit,94        .stdout = .inherit,95        .stderr = .inherit,96        .environ_map = &env,97    }) catch |e| {98        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});99        return e;100    };101102    const term = child.wait(io) catch |e| {103        errors.error_info.setMessage("process wait failed", .{});104        return e;105    };106107    return switch (term) {108        .exited => |c| c,109        else => 1,110    };111}112113fn createInteractiveShellRc(gpa: std.mem.Allocator, io: std.Io) ![]u8 {114    const out = try captureLocal(gpa, io, &.{ "mktemp", "/tmp/nina-shell-rc.XXXXXX" });115    defer gpa.free(out);116117    const path = std.mem.trim(u8, out, " \t\r\n");118    if (path.len == 0) return error.FileNotFound;119    const owned_path = try gpa.dupe(u8, path);120    errdefer gpa.free(owned_path);121122    const file = std.Io.Dir.createFile(.cwd(), io, owned_path, .{}) catch {123        errors.error_info.setMessage("could not write shell prompt setup", .{});124        return error.FileNotFound;125    };126    errdefer file.close(io);127128    const content =129        \\PS1="${NINA_PS1:-$PS1}"130        \\trap 'exit 130' INT131        \\132    ;133    file.writePositionalAll(io, content, 0) catch {134        errors.error_info.setMessage("could not write shell prompt setup", .{});135        return error.FileNotFound;136    };137    file.close(io);138139    return owned_path;140}141142// Stream a local process with inherited stdio (no SSH routing — for nix commands).143pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 {144    output.flush();145    var child = std.process.spawn(io, .{146        .argv = cmd,147        .stdin = .inherit,148        .stdout = .inherit,149        .stderr = .inherit,150    }) catch |e| {151        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});152        return e;153    };154    const term = child.wait(io) catch {155        errors.error_info.setMessage("process wait failed", .{});156        return error.ProcessFailed;157    };158    return switch (term) {159        .exited => |c| c,160        else => 1,161    };162}163164// Run a process and capture output as a single string (no SSH routing — for local nix commands).165pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {166    const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;167    defer gpa.free(result.stderr);168    switch (result.term) {169        .exited => |c| if (c != 0) {170            gpa.free(result.stdout);171            return error.ProcessFailed;172        },173        else => {174            gpa.free(result.stdout);175            return error.ProcessFailed;176        },177    }178    return result.stdout;179}180181// Create a directory and its parents, best-effort. Shelling out to `mkdir -p`182// matches how the rest of exec.zig provisions config locations (~/.config/nix).183pub fn ensureDir(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) void {184    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir }) catch {};185}186187// Optional user hooks live in ~/.config/nina/hooks and must be executable.188// They are always local: hooks protect the user's local workflow before nina189// starts state-changing work.190pub fn runHook(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, hook_name: []const u8) !HookRun {191    const home = environ.get("HOME") orelse return .{192        .result = .not_found,193        .output = try gpa.dupe(u8, ""),194    };195196    const hook_dir = try std.fs.path.join(gpa, &.{ home, ".config", "nina", "hooks" });197    defer gpa.free(hook_dir);198    ensureDir(gpa, io, hook_dir);199200    const hook_path = try std.fs.path.join(gpa, &.{ hook_dir, hook_name });201    defer gpa.free(hook_path);202203    const executable = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", "test -x \"$1\"", "nina-hook-check", hook_path } }) catch return .{204        .result = .not_found,205        .output = try gpa.dupe(u8, ""),206    };207    defer gpa.free(executable.stdout);208    defer gpa.free(executable.stderr);209    const is_executable = switch (executable.term) {210        .exited => |code| code == 0,211        else => false,212    };213    if (!is_executable) return .{214        .result = .not_found,215        .output = try gpa.dupe(u8, ""),216    };217218    const tmp_raw = try captureLocal(gpa, io, &.{ "mktemp", "/tmp/nina-hook.XXXXXX" });219    defer gpa.free(tmp_raw);220    const tmp_output = std.mem.trim(u8, tmp_raw, " \t\r\n");221    defer if (std.fs.path.isAbsolute(tmp_output)) std.Io.Dir.deleteFileAbsolute(io, tmp_output) catch {};222223    const result = try std.process.run(gpa, io, .{224        .argv = &.{225            "sh",226            "-c",227            "$1 > \"$2\" 2>&1; code=$?; tail -c 4096 \"$2\"; exit \"$code\"",228            "nina-hook-run",229            hook_path,230            tmp_output,231        },232        .stdout_limit = .limited(4096),233        .stderr_limit = .limited(512),234    });235    defer gpa.free(result.stdout);236    defer gpa.free(result.stderr);237238    const exit_code = switch (result.term) {239        .exited => |code| code,240        else => 1,241    };242    return .{243        .result = if (exit_code == 0) .ok else .failed,244        .exit_code = exit_code,245        .output = try std.fmt.allocPrint(gpa, "{s}{s}", .{ result.stdout, result.stderr }),246    };247}248249test "runHook ignores non-executable hooks and captures failures" {250    const a = std.testing.allocator;251    const io = std.testing.io;252253    var tmp = std.testing.tmpDir(.{});254    defer tmp.cleanup();255256    const home = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{&tmp.sub_path});257    defer a.free(home);258259    var env: std.process.Environ.Map = .init(a);260    defer env.deinit();261    try env.put("HOME", home);262263    var hook_dir = try tmp.dir.createDirPathOpen(io, ".config/nina/hooks", .{});264    defer hook_dir.close(io);265266    const script =267        \\#!/bin/sh268        \\echo hook says no269        \\echo detail >&2270        \\exit 3271        \\272    ;273    {274        const file = try hook_dir.createFile(io, "pre-apply", .{});275        defer file.close(io);276        try file.writePositionalAll(io, script, 0);277        try file.setPermissions(io, .fromMode(0o644));278    }279280    const missing = try runHook(a, io, &env, "pre-apply");281    defer a.free(missing.output);282    try std.testing.expectEqual(HookResult.not_found, missing.result);283284    try hook_dir.setFilePermissions(io, "pre-apply", .fromMode(0o755), .{});285286    const failed = try runHook(a, io, &env, "pre-apply");287    defer a.free(failed.output);288    try std.testing.expectEqual(HookResult.failed, failed.result);289    try std.testing.expectEqual(@as(u8, 3), failed.exit_code);290    try std.testing.expect(std.mem.indexOf(u8, failed.output, "hook says no") != null);291    try std.testing.expect(std.mem.indexOf(u8, failed.output, "detail") != null);292}293294fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {295    if (machine.local) return cmd;296297    const host = machine.host orelse {298        errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});299        return error.SshFailed;300    };301302    var ssh: std.ArrayList([]const u8) = .empty;303    try ssh.append(gpa, "ssh");304    try ssh.append(gpa, "-o");305    try ssh.append(gpa, "BatchMode=yes");306    try ssh.append(gpa, "-o");307    try ssh.append(gpa, "StrictHostKeyChecking=accept-new");308    if (machine.ssh_key) |key| {309        try ssh.append(gpa, "-i");310        try ssh.append(gpa, key);311    }312    const addr = if (machine.user) |u|313        try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })314    else315        try gpa.dupe(u8, host);316    try ssh.append(gpa, addr);317    for (cmd) |arg| try ssh.append(gpa, arg);318    return ssh.toOwnedSlice(gpa);319}320321// --- NixOS rebuild ---322323// True if the machine's config dir holds a flake.nix. Only meaningful for a local324// machine — the file lives on the local filesystem. Remote flake detection would325// need an ssh round-trip; a remote flake at the default /etc/nixos needs no flag326// anyway, so we don't bother.327// True if `dir` contains a flake.nix (local filesystem check).328pub fn dirHasFlake(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) bool {329    const flake_path = std.fs.path.join(gpa, &.{ dir, "flake.nix" }) catch return false;330    defer gpa.free(flake_path);331    return pathExists(io, flake_path);332}333334pub fn configHasFlake(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {335    if (!machine.local) return false;336    return dirHasFlake(gpa, io, machine.config_path);337}338339// nixos-rebuild auto-detects /etc/nixos/flake.nix, so the --flake flag is only340// needed when the flake lives elsewhere. A flake at a non-default path must be341// passed explicitly or nixos-rebuild falls back to channels. Compare with342// trailing slashes trimmed so "/etc/nixos/" is still treated as the default.343fn useFlakeFlag(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {344    if (!configHasFlake(gpa, io, machine)) return false;345    var path = machine.config_path;346    while (path.len > 1 and path[path.len - 1] == '/') path = path[0 .. path.len - 1];347    return !std.mem.eql(u8, path, "/etc/nixos");348}349350// Capture nixos-rebuild stderr for the translation pipeline. Raw nix build351// output is suppressed; on failure, reportError() translates stderr via352// errors.translateError(). The substep line above the call tells the user what353// is running; silence during the build is intentional per the error-wrapping brief.354fn nixosRebuildRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, flake: bool, extra_flags: []const []const u8) !u8 {355    var argv: std.ArrayList([]const u8) = .empty;356    defer argv.deinit(gpa);357    try argv.appendSlice(gpa, &.{ "sudo", "nixos-rebuild", verb });358    if (flake) try argv.appendSlice(gpa, &.{ "--flake", machine.config_path });359    try argv.appendSlice(gpa, extra_flags);360361    output.flush();362    const r = try capture(gpa, io, machine, argv.items);363    defer gpa.free(r.stdout);364    defer gpa.free(r.stderr);365    errors.setBuildStderr(r.stderr);366    return r.exit_code;367}368369pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {370    const flake = useFlakeFlag(gpa, io, machine);371    if (flake) {372        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});373    } else {374        output.printSubstep("nixos-rebuild switch", .{});375    }376    return nixosRebuildRun(io, machine, gpa, "switch", flake, extra_flags);377}378379// Live-streaming variant used by `apply` when stdout is a TTY. Each stderr line380// from nixos-rebuild is fed to the build panel for real-time progress display381// while the full stderr is also accumulated for the error translation pipeline.382// Falls back to the silent capture path when not a TTY.383pub fn nixosRebuildSwitchWithPanel(384    io: std.Io,385    machine: *const types.Machine,386    gpa: std.mem.Allocator,387    panel: *output.BuildPanel,388    extra_flags: []const []const u8,389) !u8 {390    const flake = useFlakeFlag(gpa, io, machine);391    if (flake) {392        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});393    } else {394        output.printSubstep("nixos-rebuild switch", .{});395    }396    if (!output.colorEnabled()) return nixosRebuildRun(io, machine, gpa, "switch", flake, extra_flags);397    return nixosRebuildRunStreamed(io, machine, gpa, "switch", flake, panel, extra_flags);398}399400fn nixosRebuildRunStreamed(401    io: std.Io,402    machine: *const types.Machine,403    gpa: std.mem.Allocator,404    verb: []const u8,405    flake: bool,406    panel: *output.BuildPanel,407    extra_flags: []const []const u8,408) !u8 {409    var argv_list: std.ArrayList([]const u8) = .empty;410    defer argv_list.deinit(gpa);411    try argv_list.appendSlice(gpa, &.{ "sudo", "nixos-rebuild", verb });412    if (flake) try argv_list.appendSlice(gpa, &.{ "--flake", machine.config_path });413    try argv_list.appendSlice(gpa, extra_flags);414    const argv: []const []const u8 = argv_list.items;415416    output.flush();417    const built_argv = try buildArgv(gpa, machine, argv);418    defer if (!machine.local) gpa.free(built_argv);419420    var child = std.process.spawn(io, .{421        .argv = built_argv,422        .stdin = .ignore,423        .stdout = .ignore,424        .stderr = .pipe,425    }) catch |e| {426        errors.error_info.setMessage("failed to spawn nixos-rebuild", .{});427        return e;428    };429430    var accumulated: std.ArrayList(u8) = .empty;431    defer accumulated.deinit(gpa);432433    if (child.stderr) |stderr_file| {434        var reader_buf: [8192]u8 = undefined;435        var fr = std.Io.File.Reader.initStreaming(stderr_file, io, &reader_buf);436        while (true) {437            const maybe = fr.interface.takeDelimiter('\n') catch break;438            const raw = maybe orelse break;439            accumulated.appendSlice(gpa, raw) catch {};440            const line = std.mem.trimEnd(u8, raw, "\r\n");441            panel.update(line);442            panel.render();443        }444    }445446    errors.setBuildStderr(accumulated.items);447448    const term = child.wait(io) catch |e| {449        errors.error_info.setMessage("nixos-rebuild wait failed", .{});450        return e;451    };452    return switch (term) {453        .exited => |code| code,454        else => 1,455    };456}457458pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {459    return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine), extra_flags);460}461462pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {463    return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine), extra_flags);464}465466// --- Generations ---467468// Read system-profile generations WITHOUT root. `nix-env --list-generations -p469// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user470// ("system.lock: Permission denied"). The generation symlinks themselves are471// world-readable, so list them directly: parse `system-N-link` names, take each472// link's own mtime for the date/time, and mark the one the `system` symlink473// points at as current. Output matches the `nix-env --list-generations` columns474// (num date time [current]) so parseGenerations is unchanged.475const GEN_LIST_SCRIPT =476    \\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 }'477;478479pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {480    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });481    defer gpa.free(r.stderr);482    defer gpa.free(r.stdout);483    if (r.exit_code != 0) return error.ProcessFailed;484    return parseGenerations(gpa, r.stdout);485}486487fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {488    var gens: std.ArrayList(types.GenerationInfo) = .empty;489    var lines = std.mem.splitScalar(u8, output_str, '\n');490    while (lines.next()) |line| {491        const trimmed = std.mem.trim(u8, line, " \t");492        if (trimmed.len == 0) continue;493        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");494        const num_str = parts.next() orelse continue;495        const date_str = parts.next() orelse continue;496        const time_str = parts.next() orelse continue;497        const rest = parts.rest();498        const current = std.mem.indexOf(u8, rest, "current") != null;499        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;500        try gens.append(gpa, .{501            .number = num,502            .date = try gpa.dupe(u8, date_str),503            .time = try gpa.dupe(u8, time_str),504            .current = current,505        });506    }507    return gens.toOwnedSlice(gpa);508}509510pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {511    const gens = try getGenerations(gpa, io, machine);512    defer gpa.free(gens);513    for (gens) |g| {514        if (g.current) return g.number;515    }516    return 0;517}518519pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {520    // Switch the system profile to generation n, then activate it (bootloader +521    // services). Without switch-to-configuration the change isn't applied.522    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 });523    defer gpa.free(cmd);524    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });525}526527pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {528    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });529}530531pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {532    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});533    defer gpa.free(n_str);534    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });535}536537pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {538    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });539}540541// --- Garbage collection ---542543pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {544    if (delete_old) {545        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });546    }547    // Keep the `keep` most recent system generations (+N deletes all but N),548    // then collect now-unreferenced store paths. `--delete-older-than` wants a549    // duration (e.g. 14d), not a generation count.550    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });551    defer gpa.free(cmd);552    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });553}554555// --- Channels ---556557pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {558    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });559    defer gpa.free(r.stderr);560    defer gpa.free(r.stdout);561    if (r.exit_code != 0) return error.ProcessFailed;562    return parseChannels(gpa, r.stdout);563}564565fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {566    var channels: std.ArrayList(types.ChannelInfo) = .empty;567    var lines = std.mem.splitScalar(u8, output_str, '\n');568    while (lines.next()) |line| {569        const trimmed = std.mem.trim(u8, line, " \t\r");570        if (trimmed.len == 0) continue;571        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;572        try channels.append(gpa, .{573            .name = try gpa.dupe(u8, trimmed[0..space]),574            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),575        });576    }577    return channels.toOwnedSlice(gpa);578}579580pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {581    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });582}583584pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {585    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });586}587588pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {589    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });590}591592// --- Services ---593594pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {595    const cmd: []const []const u8 = if (user)596        &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }597    else598        &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };599    const r = try capture(gpa, io, machine, cmd);600    defer gpa.free(r.stderr);601    defer gpa.free(r.stdout);602    if (r.exit_code != 0) return error.ProcessFailed;603    return parseServices(gpa, r.stdout);604}605606fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {607    var svcs: std.ArrayList(types.ServiceInfo) = .empty;608    var lines = std.mem.splitScalar(u8, output_str, '\n');609    while (lines.next()) |line| {610        const trimmed = std.mem.trim(u8, line, " \t\r");611        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines612        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");613        const name = parts.next() orelse continue;614        _ = parts.next(); // load615        const active_str = parts.next() orelse continue;616        const sub_str = parts.next() orelse "unknown";617618        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))619            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)620        else if (std.mem.eql(u8, active_str, "failed"))621            .failed622        else623            .inactive;624625        try svcs.append(gpa, .{626            .name = try gpa.dupe(u8, name),627            .state = state,628            .uptime = null,629        });630    }631    return svcs.toOwnedSlice(gpa);632}633634pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {635    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.636    // User services run under the caller's own systemd manager, so no sudo.637    if (user) {638        return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });639    }640    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });641}642643pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {644    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});645    defer gpa.free(n_str);646    if (user) {647        if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });648        return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });649    }650    if (follow) {651        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });652    }653    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });654}655656// --- Profile ---657658// Stream with one extra environment variable injected alongside the inherited env.659// Used for cases like NIXPKGS_ALLOW_UNFREE=1 where we need a single override660// without replacing the full parent environment.661fn 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 {662    output.flush();663    const argv = try buildArgv(gpa, machine, cmd);664    defer if (!machine.local) gpa.free(argv);665666    var env = try base_env.clone(gpa);667    defer env.deinit();668    try env.put(key, val);669670    var child = std.process.spawn(io, .{671        .argv = argv,672        .stdin = .inherit,673        .stdout = .inherit,674        .stderr = .inherit,675        .environ_map = &env,676    }) catch |e| {677        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});678        return e;679    };680681    const term = child.wait(io) catch |e| {682        errors.error_info.setMessage("process wait failed", .{});683        return e;684    };685686    return switch (term) {687        .exited => |c| c,688        else => 1,689    };690}691692pub 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 {693    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});694    defer gpa.free(pkg_ref);695    // `nix profile add` is the current verb; `install` is a deprecated alias that696    // prints a warning on modern nix.697    if (allow_unfree) {698        // The package is unfree and the user's system-wide allowUnfree setting699        // doesn't propagate to imperative nix commands. Pass NIXPKGS_ALLOW_UNFREE=1700        // and --impure so the profile add succeeds: --impure allows builtins.getEnv701        // to read the env var inside the nixpkgs flake's pure evaluation context.702        return streamWithEnvVar(io, machine, gpa, &.{ "nix", "profile", "add", "--impure", pkg_ref }, environ, "NIXPKGS_ALLOW_UNFREE", "1");703    }704    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });705}706707pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {708    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not709    // by flake ref — passing nixpkgs#ripgrep matches nothing.710    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });711}712713pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {714    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });715    defer gpa.free(r.stderr);716    if (r.exit_code != 0) return error.ProcessFailed;717    return r.stdout;718}719720// Machine-readable profile listing — caller parses elements -> name + version.721pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {722    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });723    defer gpa.free(r.stderr);724    if (r.exit_code != 0) {725        gpa.free(r.stdout);726        return error.ProcessFailed;727    }728    return r.stdout;729}730731// Returns the profile element name to pass to `nix profile remove/upgrade`732// (e.g. "nina" or "default"), or null if nina is not found. Caller owns the733// returned slice. A NixOS system-package install also resolves into /nix/store734// so the store path alone can't distinguish it from a profile install — the735// profile list can. A missing/empty profile (or no nix) returns null.736pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {737    const js = profileListJson(gpa, io, machine) catch return null;738    defer gpa.free(js);739    return profileJsonNinaElement(gpa, js);740}741742743pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {744    const name = profileNinaElement(gpa, io, machine) orelse return false;745    gpa.free(name);746    return true;747}748749// True when a nix store path belongs to the nina package. Store paths have the750// form /nix/store/<32-char-hash>-<pname>-<version>[/<subpath>]. We check that751// the 33 chars after /nix/store/ are the hash+dash, and the pname that follows752// is exactly "nina" (followed by "-" or end-of-component).753fn storePathIsNina(path: []const u8) bool {754    const prefix = "/nix/store/";755    if (!std.mem.startsWith(u8, path, prefix)) return false;756    const rel = path[prefix.len..];757    // The store entry name ends at the first "/" (if any sub-path follows).758    const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];759    if (entry.len < 34) return false; // 32-char hash + dash + at least one char760    const pname_ver = entry[33..]; // skip hash + dash761    return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");762}763764// Pure parse of `nix profile list --json` for a nina element, returning its765// element name (the key to pass to `nix profile remove/upgrade`) or null.766// Newer nix (2.18+) keys elements by pname ("nina"). Older nix uses an array767// with an "attrPath" field. Tarball installs via the `default` output may use768// the key "default" instead of "nina"; we detect those via storePaths.769fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {770    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;771    defer parsed.deinit();772    const root = parsed.value;773    if (root != .object) return null;774    const elements = root.object.get("elements") orelse return null;775    switch (elements) {776        .object => |obj| {777            // Fast path: exact "nina" key (nix 2.18+ with nixpkgs#nina install).778            if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;779            // Fallback: scan storePaths. Handles tarball installs where the default780            // output is selected and nix names the element "default" (older nix) or781            // some other key derived from the attrPath rather than the pname.782            var it = obj.iterator();783            while (it.next()) |kv| {784                const val = kv.value_ptr.*;785                if (val != .object) continue;786                const sps = val.object.get("storePaths") orelse continue;787                if (sps != .array) continue;788                for (sps.array.items) |sp| {789                    if (sp == .string and storePathIsNina(sp.string))790                        return gpa.dupe(u8, kv.key_ptr.*) catch null;791                }792            }793            return null;794        },795        .array => |arr| {796            // Older nix array format. Element name is the last component of attrPath.797            for (arr.items) |el| {798                if (el != .object) continue;799                const ap = el.object.get("attrPath") orelse continue;800                if (ap != .string) continue;801                if (std.mem.eql(u8, ap.string, "nina") or802                    std.mem.endsWith(u8, ap.string, ".nina"))803                    return gpa.dupe(u8, "nina") catch null;804                // Tarball default-output install: attrPath ends in ".default" but805                // storePaths point to nina. Return "default" as the element name.806                const sps = el.object.get("storePaths") orelse continue;807                if (sps != .array) continue;808                for (sps.array.items) |sp| {809                    if (sp != .string) continue;810                    if (!storePathIsNina(sp.string)) continue;811                    const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;812                    const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;813                    return gpa.dupe(u8, el_name) catch null;814                }815            }816            return null;817        },818        else => return null,819    }820}821822test "profileJsonNinaElement finds element name from profile JSON" {823    const a = std.testing.allocator;824825    // Newer nix: elements keyed by pname. "nina" key present.826    const named =827        \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},828        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}829    ;830    const r1 = profileJsonNinaElement(a, named);831    defer if (r1) |n| a.free(n);832    try std.testing.expectEqualStrings("nina", r1.?);833834    // Tarball install via default output: element keyed as "default", storePath is nina.835    const default_key =836        \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}837    ;838    const r2 = profileJsonNinaElement(a, default_key);839    defer if (r2) |n| a.free(n);840    try std.testing.expectEqualStrings("default", r2.?);841842    // Decoy: storePath of another package contains "nina" as a substring but is not nina.843    const decoy =844        \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}845    ;846    const r3 = profileJsonNinaElement(a, decoy);847    try std.testing.expectEqual(@as(?[]const u8, null), r3);848849    // Older nix array schema, attrPath ending in ".nina".850    const arr =851        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}852    ;853    const r4 = profileJsonNinaElement(a, arr);854    defer if (r4) |n| a.free(n);855    try std.testing.expectEqualStrings("nina", r4.?);856857    // Older nix array schema, tarball default-output install.858    const arr_default =859        \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}860    ;861    const r5 = profileJsonNinaElement(a, arr_default);862    defer if (r5) |n| a.free(n);863    try std.testing.expectEqualStrings("default", r5.?);864865    // Empty / malformed → null.866    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));867    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));868}869870// The store paths that make up the running system environment. Each reference is871// a <hash>-<name>-<version> path, so the caller can list system packages with872// versions — there is no cleaner per-package list for environment.systemPackages.873pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {874    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });875    defer gpa.free(r.stderr);876    if (r.exit_code != 0) {877        gpa.free(r.stdout);878        return error.ProcessFailed;879    }880    return r.stdout;881}882883pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {884    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });885}886887// --- Store ---888889pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {890    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });891}892893pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {894    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });895}896897// Deduplicate identical store files via hard links — frees space without898// garbage-collecting any paths.899pub fn storeOptimise(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {900    return stream(io, machine, gpa, &.{ "nix", "store", "optimise" });901}902903pub const SystemStatus = struct { size: []u8, age: []u8 };904905// One read-only pass for `nina status`: the current system's closure size (a906// single `path-info -S` of /run/current-system — fast, unlike -S over the whole907// store) and seconds since the system profile was last switched (its symlink908// mtime). Both are world-readable; no root needed.909const STATUS_SCRIPT =910    \\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} ))"911;912913pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {914    const unknown = SystemStatus{915        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },916        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },917    };918    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;919    defer gpa.free(r.stdout);920    defer gpa.free(r.stderr);921    if (r.exit_code != 0) return unknown;922923    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");924    const sz_str = it.next() orelse return unknown;925    const age_str = it.next() orelse return unknown;926    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;927    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;928929    gpa.free(unknown.size);930    gpa.free(unknown.age);931    return .{932        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),933        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),934    };935}936937// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A938// one-word health signal; exits non-zero when degraded, so we read stdout, not939// the code. Caller owns the returned slice.940pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {941    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch942        return gpa.dupe(u8, "unknown");943    defer gpa.free(r.stderr);944    const state = std.mem.trim(u8, r.stdout, " \t\n\r");945    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");946    gpa.free(r.stdout);947    return owned;948}949950fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {951    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});952    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});953    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});954    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});955}956957pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {958    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });959}960961pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {962    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)963    // graph work that takes minutes on a real store (59k+ paths) and hangs the964    // command. We don't need closures: `--all --json` (no -S) carries each path's965    // own narSize, so one fast pass gives the path count and the summed store size.966    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.967    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.968    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });969    defer gpa.free(pi.stdout);970    defer gpa.free(pi.stderr);971972    const scan = scanStoreJson(pi.stdout);973    const total_owned = try humanSize(gpa, scan.total_bytes);974975    return .{976        .total_size = total_owned,977        .live_paths = scan.count,978        .reclaimable_paths = 0,979    };980}981982const StoreScan = struct { count: u64, total_bytes: u64 };983984// One linear pass over `nix path-info --json`: each path object has exactly one985// "narSize": field, so counting them gives the true path count and summing the986// values gives the total store size — no per-path closure walk.987fn scanStoreJson(json_str: []const u8) StoreScan {988    const needle = "\"narSize\":";989    var count: u64 = 0;990    var total: u64 = 0;991    var i: usize = 0;992    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {993        var j = pos + needle.len;994        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}995        var val: u64 = 0;996        var any = false;997        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {998            val = val * 10 + (json_str[j] - '0');999            any = true;1000        }1001        if (any) {1002            count += 1;1003            total += val;1004        }1005        i = j;1006    }1007    return .{ .count = count, .total_bytes = total };1008}10091010fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1011    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };1012    var val: f64 = @floatFromInt(bytes);1013    var unit: usize = 0;1014    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1015    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1016    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1017}10181019pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {1020    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the1021    // flake registry), not a flake in the current directory.1022    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});1023    defer gpa.free(expr);1024    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });1025    defer gpa.free(r.stderr);1026    if (r.exit_code != 0) {1027        gpa.free(r.stdout);1028        return error.ProcessFailed;1029    }1030    return r.stdout;1031}10321033// --- Flake ---10341035pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8, extra_flags: []const []const u8) !u8 {1036    var argv: std.ArrayList([]const u8) = .empty;1037    defer argv.deinit(gpa);1038    try argv.appendSlice(gpa, &.{ "nix", "flake", "update" });1039    if (input) |inp| try argv.append(gpa, inp);1040    try argv.appendSlice(gpa, extra_flags);1041    return stream(io, machine, gpa, argv.items);1042}10431044// Update flake inputs for the flake living in `dir` (the config dir). `nix flake1045// update` operates on the flake in the working directory, so we cd there first.1046// Used by `nina upgrade` on a flake system in place of nix-channel --update.1047pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {1048    return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });1049}10501051pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1052    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });1053}10541055pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1056    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });1057}10581059pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1060    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });1061}10621063pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {1064    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });1065}10661067pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1068    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });1069    defer gpa.free(r.stderr);1070    if (r.exit_code != 0) {1071        gpa.free(r.stdout);1072        return error.ProcessFailed;1073    }1074    return r.stdout;1075}10761077// --- Build / Run / Develop ---10781079pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8, extra_flags: []const []const u8) !u8 {1080    var argv: std.ArrayList([]const u8) = .empty;1081    defer argv.deinit(gpa);1082    try argv.append(gpa, "nix");1083    try argv.append(gpa, "build");1084    var ref_buf: ?[]u8 = null;1085    defer if (ref_buf) |r| gpa.free(r);1086    if (attr) |a| {1087        ref_buf = try std.fmt.allocPrint(gpa, ".#{s}", .{a});1088        try argv.append(gpa, ref_buf.?);1089    }1090    try argv.appendSlice(gpa, extra_flags);1091    return stream(io, machine, gpa, argv.items);1092}10931094pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1095    // nix run always gets --no-write-lock-file for remote URLs1096    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");1097    if (is_url) {1098        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });1099    }1100    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.1101    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {1102        return stream(io, machine, gpa, &.{ "nix", "run", pkg });1103    }1104    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1105    defer gpa.free(ref);1106    return stream(io, machine, gpa, &.{ "nix", "run", ref });1107}11081109pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1110    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1111    defer gpa.free(ref);1112    return stream(io, machine, gpa, &.{ "nix", "shell", ref });1113}11141115pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {1116    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1117    defer gpa.free(ref);1118    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});1119    defer gpa.free(ps1);1120    if (machine.local) {1121        const rc_path = try createInteractiveShellRc(gpa, io);1122        defer {1123            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1124            gpa.free(rc_path);1125        }1126        return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref, "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, ps1);1127    }1128    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);1129}11301131pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8, extra_flags: []const []const u8) !u8 {1132    if (run_cmd) |cmd| {1133        // sh -c so a multi-word command isn't treated as a single executable name.1134        var argv: std.ArrayList([]const u8) = .empty;1135        defer argv.deinit(gpa);1136        try argv.appendSlice(gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1137        try argv.appendSlice(gpa, extra_flags);1138        return stream(io, machine, gpa, argv.items);1139    }1140    var argv: std.ArrayList([]const u8) = .empty;1141    defer argv.deinit(gpa);1142    try argv.append(gpa, "nix");1143    try argv.append(gpa, "develop");1144    try argv.appendSlice(gpa, extra_flags);1145    return stream(io, machine, gpa, argv.items);1146}11471148pub 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 {1149    if (run_cmd) |cmd| {1150        // sh -c so a multi-word command isn't treated as a single executable name.1151        var argv: std.ArrayList([]const u8) = .empty;1152        defer argv.deinit(gpa);1153        try argv.appendSlice(gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1154        try argv.appendSlice(gpa, extra_flags);1155        return stream(io, machine, gpa, argv.items);1156    }1157    if (machine.local) {1158        const rc_path = try createInteractiveShellRc(gpa, io);1159        defer {1160            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1161            gpa.free(rc_path);1162        }1163        var argv: std.ArrayList([]const u8) = .empty;1164        defer argv.deinit(gpa);1165        try argv.append(gpa, "nix");1166        try argv.append(gpa, "develop");1167        try argv.appendSlice(gpa, extra_flags);1168        try argv.appendSlice(gpa, &.{ "--command", "bash", "--rcfile", rc_path, "-i" });1169        return streamEnv(io, machine, gpa, argv.items, base_env, "(nina: dev) -> ");1170    }1171    var argv: std.ArrayList([]const u8) = .empty;1172    defer argv.deinit(gpa);1173    try argv.append(gpa, "nix");1174    try argv.append(gpa, "develop");1175    try argv.appendSlice(gpa, extra_flags);1176    return streamEnv(io, machine, gpa, argv.items, base_env, "(nina: dev) -> ");1177}11781179pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1180    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });1181}11821183// --- Format ---11841185pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {1186    if (check) {1187        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });1188    }1189    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });1190}11911192// --- Info ---11931194pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1195    const r = try capture(gpa, io, machine, &.{"nixos-version"});1196    defer gpa.free(r.stderr);1197    if (r.exit_code != 0) {1198        gpa.free(r.stdout);1199        return error.ProcessFailed;1200    }1201    return r.stdout;1202}12031204pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1205    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });1206    defer gpa.free(r.stderr);1207    if (r.exit_code != 0) {1208        gpa.free(r.stdout);1209        return error.ProcessFailed;1210    }1211    return r.stdout;1212}12131214pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1215    const r = try capture(gpa, io, machine, &.{"uptime"});1216    defer gpa.free(r.stderr);1217    if (r.exit_code != 0) {1218        gpa.free(r.stdout);1219        return error.ProcessFailed;1220    }1221    return r.stdout;1222}12231224// --- Boot ---12251226pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {1227    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });1228    defer gpa.free(r.stderr);1229    defer gpa.free(r.stdout);1230    if (r.exit_code != 0) return error.ProcessFailed;1231    return parseBootEntries(gpa, r.stdout);1232}12331234fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {1235    var entries: std.ArrayList(types.BootEntry) = .empty;1236    var lines = std.mem.splitScalar(u8, output_str, '\n');1237    while (lines.next()) |line| {1238        const trimmed = std.mem.trim(u8, line, " \t\r");1239        if (std.mem.startsWith(u8, trimmed, "title:")) {1240            const title = std.mem.trim(u8, trimmed[6..], " \t");1241            const current = std.mem.indexOf(u8, title, "(current)") != null;1242            try entries.append(gpa, .{1243                .title = try gpa.dupe(u8, title),1244                .current = current,1245            });1246        }1247    }1248    return entries.toOwnedSlice(gpa);1249}12501251// --- Pkg info ---12521253fn pkgInstallable(gpa: std.mem.Allocator, pkg: []const u8) ![]u8 {1254    return std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1255}12561257fn resolvePkgStorePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, installable: []const u8) ![]u8 {1258    const r = try capture(gpa, io, machine, &.{ "nix", "build", "--no-link", "--print-out-paths", installable });1259    defer gpa.free(r.stderr);1260    defer gpa.free(r.stdout);1261    if (r.exit_code != 0) return error.PackageNotFound;12621263    var lines = std.mem.tokenizeAny(u8, r.stdout, "\r\n");1264    const first_path = lines.next() orelse return error.PackageNotFound;1265    const store_path = std.mem.trim(u8, first_path, " \t");1266    if (store_path.len == 0) return error.PackageNotFound;1267    return gpa.dupe(u8, store_path);1268}12691270pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1271    const installable = try pkgInstallable(gpa, pkg);1272    defer gpa.free(installable);1273    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1274    defer gpa.free(store_path);1275    return stream(io, machine, gpa, &.{ "nix", "why-depends", "/run/current-system", store_path });1276}12771278pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1279    const installable = try pkgInstallable(gpa, pkg);1280    defer gpa.free(installable);1281    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1282    defer gpa.free(store_path);1283    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", store_path });1284}12851286pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {1287    const installable = try pkgInstallable(gpa, pkg);1288    defer gpa.free(installable);1289    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", "--json", installable });1290    defer gpa.free(r.stderr);1291    defer gpa.free(r.stdout);1292    if (r.exit_code != 0) return error.ProcessFailed;12931294    const nar_size = try pathInfoNarSize(gpa, r.stdout);1295    return humanPkgSize(gpa, nar_size);1296}12971298pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1299    const installable = try pkgInstallable(gpa, pkg);1300    defer gpa.free(installable);1301    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1302    defer gpa.free(store_path);1303    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", store_path });1304}13051306fn pathInfoNarSize(gpa: std.mem.Allocator, json_str: []const u8) !u64 {1307    var parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.ProcessFailed;1308    defer parsed.deinit();1309    switch (parsed.value) {1310        .object => |obj| {1311            var it = obj.iterator();1312            while (it.next()) |entry| {1313                if (entry.value_ptr.* == .object) {1314                    if (entry.value_ptr.object.get("narSize")) |v| {1315                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1316                    }1317                }1318            }1319        },1320        .array => |arr| {1321            for (arr.items) |item| {1322                if (item == .object) {1323                    if (item.object.get("narSize")) |v| {1324                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1325                    }1326                }1327            }1328        },1329        else => {},1330    }1331    return error.ProcessFailed;1332}13331334fn humanPkgSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1335    const units = [_][]const u8{ "B", "KiB", "MiB", "GiB", "TiB" };1336    var val: f64 = @floatFromInt(bytes);1337    var unit: usize = 0;1338    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1339    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1340    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1341}13421343test "pathInfoNarSize parses object and array shapes" {1344    try std.testing.expectEqual(@as(u64, 1064629862), try pathInfoNarSize(std.testing.allocator,1345        \\{"/nix/store/abc-ffmpeg":{"narSize":1064629862}}1346    ));1347    try std.testing.expectEqual(@as(u64, 2048), try pathInfoNarSize(std.testing.allocator,1348        \\[{"path":"/nix/store/abc-pkg","narSize":2048}]1349    ));1350}13511352// --- Hash / Fetch ---13531354pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {1355    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });1356    defer gpa.free(r.stderr);1357    if (r.exit_code != 0) {1358        gpa.free(r.stdout);1359        return error.ProcessFailed;1360    }1361    return r.stdout;1362}13631364pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {1365    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });1366    defer gpa.free(r.stderr);1367    if (r.exit_code != 0) {1368        gpa.free(r.stdout);1369        return error.ProcessFailed;1370    }1371    return r.stdout;1372}13731374// --- Pin ---13751376pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {1377    // Stub: full implementation would parse and edit flake.lock JSON1378    // The pin/unpin flow works via nix flake update which regenerates flake.lock1379}13801381pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {1382    if (line) |l| {1383        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});1384        defer gpa.free(line_arg);1385        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });1386    }1387    return stream(io, &types.Machine{}, gpa, &.{ editor, path });1388}13891390// Open a config directory as root with `sudo -E <editor> <path>` — `-E`1391// preserves the user's environment (PATH, TERM, EDITOR config) so the editor1392// behaves the same as it does unprivileged. Used by `nina edit --dir`.1393pub fn openEditorSudo(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8) !u8 {1394    return stream(io, &types.Machine{}, gpa, &.{ "sudo", "-E", editor, path });1395}13961397pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {1398    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});1399    defer gpa.free(a_str);1400    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});1401    defer gpa.free(b_str);1402    // On a tty, the child's own color is fine — stream it directly.1403    if (output.colorEnabled()) {1404        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });1405    }1406    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,1407    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.1408    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });1409    defer gpa.free(r.stdout);1410    defer gpa.free(r.stderr);1411    const cleaned = try stripAnsi(gpa, r.stdout);1412    defer gpa.free(cleaned);1413    output.raw(cleaned);1414    return r.exit_code;1415}14161417// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a1418// child process's color when it writes ANSI unconditionally.1419fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1420    var out: std.ArrayList(u8) = .empty;1421    errdefer out.deinit(gpa);1422    var i: usize = 0;1423    while (i < input.len) {1424        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1425            i += 2;1426            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1427            if (i < input.len) i += 1; // consume the final byte1428            continue;1429        }1430        try out.append(gpa, input[i]);1431        i += 1;1432    }1433    return out.toOwnedSlice(gpa);1434}14351436test "stripAnsi removes CSI color sequences" {1437    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1438    defer std.testing.allocator.free(cleaned);1439    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1440}14411442// --- Doctor checks ---14431444pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1445    var checks: std.ArrayList(types.DoctorCheck) = .empty;14461447    // Check nix daemon1448    {1449        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1450        defer gpa.free(r.stdout);1451        defer gpa.free(r.stderr);1452        const active = std.mem.indexOf(u8, r.stdout, "active") != null;1453        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1454    }14551456    // Check config syntax. Flake-aware like apply/upgrade: on a flake system a1457    // plain `nixos-rebuild dry-build` evaluates <nixpkgs/nixos> + <nixos-config>1458    // (channel style) and fails, so pass --flake when the config dir has one.1459    {1460        const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1461            &.{ "sudo", "nixos-rebuild", "dry-build", "--flake", machine.config_path }1462        else1463            &.{ "sudo", "nixos-rebuild", "dry-build" };1464        const r = try capture(gpa, io, machine, argv);1465        defer gpa.free(r.stdout);1466        defer gpa.free(r.stderr);1467        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1468    }14691470    // Check channel1471    {1472        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1473        defer gpa.free(r.stdout);1474        defer gpa.free(r.stderr);1475        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1476        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1477    }14781479    return checks.toOwnedSlice(gpa);1480}14811482// --- Home Manager ---1483//1484// Home Manager has three usage modes. nina detects which one is in play before1485// any `home` command so it can either drive the standalone CLI or redirect the1486// user to `nina apply` (when HM is a NixOS/flake module activated by rebuild).14871488pub const HomeManagerMode = enum {1489    // home-manager binary on PATH — manages the user env on its own.1490    standalone,1491    // No binary, but a home.nix exists — HM is a NixOS/flake module rebuilt by1492    // nixos-rebuild. `nina home apply` redirects to `nina apply`.1493    module,1494    none,1495};14961497fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1498    const home = environ.get("HOME") orelse return null;1499    return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1500}15011502// Path to the standalone home.nix. Caller frees.1503pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1504    const dir = homeConfigDir(gpa, environ) orelse return null;1505    defer gpa.free(dir);1506    return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1507}15081509pub fn pathExists(io: std.Io, path: []const u8) bool {1510    const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1511    f.close(io);1512    return true;1513}15141515// `command -v <name>` — true if the binary resolves on PATH. Silent (captured),1516// unlike streamLocal which would inherit stdio.1517fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1518    var buf: [256]u8 = undefined;1519    const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1520    const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1521    defer gpa.free(r.stdout);1522    defer gpa.free(r.stderr);1523    return switch (r.term) {1524        .exited => |code| code == 0,1525        else => false,1526    };1527}15281529pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1530    if (commandExists(gpa, io, "home-manager")) return .standalone;1531    if (homeNixPath(gpa, environ)) |p| {1532        defer gpa.free(p);1533        if (pathExists(io, p)) return .module;1534    }1535    return .none;1536}15371538// The home-manager config dir when it holds a flake.nix (a flake-based home1539// config that `home-manager switch --flake` drives). null for a channel-based1540// config, which uses a plain `home-manager switch`. Caller frees.1541pub fn homeFlakeDir(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1542    const dir = homeConfigDir(gpa, environ) orelse return null;1543    const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch {1544        gpa.free(dir);1545        return null;1546    };1547    defer gpa.free(flake);1548    if (!pathExists(io, flake)) {1549        gpa.free(dir);1550        return null;1551    }1552    return dir;1553}15541555// Platform-specific home-manager attribute "<user>-<arch>-<os>" (e.g.1556// murazaki-x86_64-linux) — the homeConfigurations key many flakes derive from1557// ${USER}-${system}. arch/os come from uname on the local host (home commands1558// are local-only). Caller frees.1559pub fn homeManagerAttr(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, environ: *const std.process.Environ.Map) ![]const u8 {1560    const user = environ.get("USER") orelse "user";15611562    const arch_r = try capture(gpa, io, machine, &.{ "uname", "-m" });1563    defer gpa.free(arch_r.stdout);1564    defer gpa.free(arch_r.stderr);1565    if (arch_r.exit_code != 0) return error.ProcessFailed;1566    const arch = std.mem.trim(u8, arch_r.stdout, " \t\r\n");15671568    const os_r = try capture(gpa, io, machine, &.{ "uname", "-s" });1569    defer gpa.free(os_r.stdout);1570    defer gpa.free(os_r.stderr);1571    if (os_r.exit_code != 0) return error.ProcessFailed;1572    const os = try gpa.dupe(u8, std.mem.trim(u8, os_r.stdout, " \t\r\n"));1573    defer gpa.free(os);1574    for (os) |*ch| ch.* = std.ascii.toLower(ch.*);15751576    if (arch.len == 0 or os.len == 0) return error.ProcessFailed;1577    return std.fmt.allocPrint(gpa, "{s}-{s}-{s}", .{ user, arch, os });1578}15791580// Map a nixos-version string to the matching home-manager branch: an unstable1581// channel ("…pre…"/"unstable") → master; a stable release like1582// "25.05.20250115.abcdef (Warbler)" → release-25.05. Anything unparseable1583// falls back to master. Caller frees.1584fn homeBranchFromVersion(gpa: std.mem.Allocator, version_raw: []const u8) ![]const u8 {1585    const v = std.mem.trim(u8, version_raw, " \t\r\n");1586    if (std.mem.indexOf(u8, v, "pre") != null or1587        std.mem.indexOf(u8, v, "unstable") != null)1588        return gpa.dupe(u8, "master");15891590    const head = v[0 .. std.mem.indexOfScalar(u8, v, ' ') orelse v.len];1591    var it = std.mem.splitScalar(u8, head, '.');1592    const major = it.next() orelse "";1593    const minor = it.next() orelse "";1594    if (allDigits(major) and allDigits(minor))1595        return std.fmt.allocPrint(gpa, "release-{s}.{s}", .{ major, minor });15961597    return gpa.dupe(u8, "master");1598}15991600fn allDigits(s: []const u8) bool {1601    if (s.len == 0) return false;1602    for (s) |ch| if (!std.ascii.isDigit(ch)) return false;1603    return true;1604}16051606test "homeBranchFromVersion maps channels to HM branches" {1607    const a = std.testing.allocator;1608    const cases = [_]struct { in: []const u8, want: []const u8 }{1609        .{ .in = "25.05.20250115.abcdef (Warbler)", .want = "release-25.05" },1610        .{ .in = "24.11.20241201.deadbee (Vicuna)", .want = "release-24.11" },1611        .{ .in = "25.11pre-git", .want = "master" },1612        .{ .in = "25.05pre789012.abcdef (Warbler)", .want = "master" },1613        .{ .in = "nixos-unstable", .want = "master" },1614        .{ .in = "garbage", .want = "master" },1615    };1616    for (cases) |c| {1617        const got = try homeBranchFromVersion(a, c.in);1618        defer a.free(got);1619        try std.testing.expectEqualStrings(c.want, got);1620    }1621}16221623// The home-manager branch matching the running nixpkgs. Falls back to master1624// when nixos-version is unavailable (non-NixOS host). Caller frees.1625fn detectHomeManagerBranch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]const u8 {1626    const r = capture(gpa, io, machine, &.{"nixos-version"}) catch1627        return gpa.dupe(u8, "master");1628    defer gpa.free(r.stdout);1629    defer gpa.free(r.stderr);1630    if (r.exit_code != 0) return gpa.dupe(u8, "master");1631    return homeBranchFromVersion(gpa, r.stdout);1632}16331634// `nix run home-manager/<branch> -- init [--switch] [dir]` — generates1635// flake.nix + home.nix (in dir, or ~/.config/home-manager by default),1636// activating immediately when switch_on_init is set.1637pub fn homeManagerInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, switch_on_init: bool, dir: ?[]const u8) !u8 {1638    const branch = try detectHomeManagerBranch(gpa, io, machine);1639    defer gpa.free(branch);1640    const flake_ref = try std.fmt.allocPrint(gpa, "home-manager/{s}", .{branch});1641    defer gpa.free(flake_ref);16421643    var argv: std.ArrayList([]const u8) = .empty;1644    defer argv.deinit(gpa);1645    try argv.appendSlice(gpa, &.{ "nix", "run", flake_ref, "--", "init" });1646    if (switch_on_init) try argv.append(gpa, "--switch");1647    if (dir) |d| try argv.append(gpa, d);16481649    return stream(io, machine, gpa, argv.items);1650}16511652pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1653    output.flush();1654    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch" });1655    defer gpa.free(r.stdout);1656    defer gpa.free(r.stderr);1657    errors.setBuildStderr(r.stderr);1658    return r.exit_code;1659}16601661// Outcome of a flake-based switch, so the caller can fall back to a less1662// specific attribute on a missing-attribute evaluation error — but never on a1663// genuine build failure.1664pub const SwitchOutcome = enum { ok, attr_missing, failed };16651666pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8) !SwitchOutcome {1667    output.flush();1668    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch", "--flake", flake_ref });1669    defer gpa.free(r.stdout);1670    defer gpa.free(r.stderr);1671    if (r.exit_code == 0) return .ok;1672    // A flake that doesn't define this homeConfiguration fails during evaluation1673    // with "does not provide attribute" — surface that so the caller can retry a1674    // different attr rather than treating it as a build failure.1675    if (std.mem.indexOf(u8, r.stderr, "does not provide attribute") != null)1676        return .attr_missing;1677    errors.setBuildStderr(r.stderr);1678    return .failed;1679}16801681// home-manager has no system-profile rollback; it re-activates the previous1682// generation via `switch --rollback`.1683pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1684    output.flush();1685    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch", "--rollback" });1686    defer gpa.free(r.stdout);1687    defer gpa.free(r.stderr);1688    errors.setBuildStderr(r.stderr);1689    return r.exit_code;1690}16911692// Build (and validate) the home config without activating it — used by `home1693// check` and `home apply --dry`. `home-manager build` drops a ./result symlink1694// in the cwd, so run it in a throwaway temp dir to avoid littering the directory1695// nina was invoked from.1696pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1697    output.flush();1698    const r = try capture(gpa, io, machine, &.{ "sh", "-c", "d=$(mktemp -d) && cd \"$d\" && home-manager build" });1699    defer gpa.free(r.stdout);1700    defer gpa.free(r.stderr);1701    errors.setBuildStderr(r.stderr);1702    return r.exit_code;1703}17041705pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1706    const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1707    defer gpa.free(r.stderr);1708    if (r.exit_code != 0) {1709        gpa.free(r.stdout);1710        return error.ProcessFailed;1711    }1712    return r.stdout;1713}17141715// Store paths referenced by a home generation — used to list managed packages.1716pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1717    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1718    defer gpa.free(r.stderr);1719    if (r.exit_code != 0) {1720        gpa.free(r.stdout);1721        return error.ProcessFailed;1722    }1723    return r.stdout;1724}17251726// diff-closures between two arbitrary store paths (home generations), mirroring1727// diffClosures' tty/piped color handling.1728pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1729    if (output.colorEnabled()) {1730        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1731    }1732    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1733    defer gpa.free(r.stdout);1734    defer gpa.free(r.stderr);1735    const cleaned = try stripAnsi(gpa, r.stdout);1736    defer gpa.free(cleaned);1737    output.raw(cleaned);1738    return r.exit_code;1739}17401741// --- Log ---17421743pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1744    const home = environ.get("HOME") orelse return error.FileNotFound;1745    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1746    defer gpa.free(path);1747    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1748    if (last == 0) return content;17491750    // Collect non-empty lines, then keep only the final `last`. Slices point into1751    // `content`, so copy them out before freeing it.1752    var lines: std.ArrayList([]const u8) = .empty;1753    defer lines.deinit(gpa);1754    var it = std.mem.splitScalar(u8, content, '\n');1755    while (it.next()) |line| {1756        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1757        try lines.append(gpa, line);1758    }1759    if (lines.items.len <= last) return content;17601761    var out: std.ArrayList(u8) = .empty;1762    errdefer out.deinit(gpa);1763    for (lines.items[lines.items.len - last ..]) |line| {1764        try out.appendSlice(gpa, line);1765        try out.append(gpa, '\n');1766    }1767    gpa.free(content);1768    return out.toOwnedSlice(gpa);1769}17701771// nina is a one-shot process, so "did the last apply fail this session?" can't1772// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1773// other ~/.nina-* state files. This lets a later successful apply earn the1774// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1775pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1776    const home = environ.get("HOME") orelse return;1777    var buf: [512]u8 = undefined;1778    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1779    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1780    file.close(io);1781}17821783pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1784    const home = environ.get("HOME") orelse return false;1785    var buf: [512]u8 = undefined;1786    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1787    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1788        f.close(io);1789        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1790        return true;1791    } else |_| {1792        return false;1793    }1794}17951796pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1797    const home = environ.get("HOME") orelse return;1798    var path_buf: [512]u8 = undefined;1799    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1800    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1801        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1802    defer file.close(io);1803    const size = file.length(io) catch 0;1804    file.writePositionalAll(io, entry, size) catch {};1805}18061807// --- Update helpers ---18081809// Fetch a URL with curl and return the response body. Caller must free.1810// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.1811pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1812    const argv = [_][]const u8{1813        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1814    };1815    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1816    defer gpa.free(result.stderr);18171818    const marker = "\nHTTP_STATUS:";1819    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1820        gpa.free(result.stdout);1821        return error.NetworkError;1822    };1823    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1824    const status = std.fmt.parseInt(u16, status_str, 10) catch {1825        gpa.free(result.stdout);1826        return error.NetworkError;1827    };1828    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1829    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1830    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1831        gpa.free(result.stdout);1832        return e;1833    };1834    gpa.free(result.stdout);1835    return body;1836}18371838// Download a URL to a temp file. Returns the temp path (caller must gpa.free).1839// The file is written to /tmp/nina-update-<pid> and left for the caller to use.1840pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1841    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1842    errdefer gpa.free(tmp_path);18431844    var child = std.process.spawn(io, .{1845        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1846        .stdin = .close,1847        .stdout = .close,1848        .stderr = .inherit,1849    }) catch return error.NetworkError;1850    const term = child.wait(io) catch return error.NetworkError;1851    switch (term) {1852        .exited => |c| if (c != 0) return error.NetworkError,1853        else => return error.NetworkError,1854    }1855    return tmp_path;1856}18571858// Get the current executable path into buf. Returns slice of buf.1859pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1860    const len = try std.process.executablePath(io, buf);1861    return buf[0..len];1862}18631864// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1865// atomically install the binary to install_path. Errors: ChecksumMismatch,1866// AccessDenied (with error_info set), or underlying I/O errors.1867pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1868    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1869        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1870        return error.FileNotFound;1871    };1872    defer gpa.free(bytes);18731874    var hasher = std.crypto.hash.Blake3.init(.{});1875    hasher.update(bytes);1876    var raw: [32]u8 = undefined;1877    hasher.final(&raw);1878    const hex = std.fmt.bytesToHex(raw, .lower);1879    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;18801881    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1882    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1883        return error.NameTooLong;18841885    {1886        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1887            errors.error_info.setMessage("cannot write to {s}", .{install_path});1888            errors.error_info.setSuggestion("try: sudo nina update", .{});1889            return error.AccessDenied;1890        };1891        defer f.close(io);1892        f.writePositionalAll(io, bytes, 0) catch {1893            errors.error_info.setMessage("cannot write to {s}", .{install_path});1894            return error.AccessDenied;1895        };1896        try f.setPermissions(io, .fromMode(0o755));1897    }1898    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};18991900    if (comptime builtin.os.tag == .macos) {1901        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1902    }19031904    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1905        error.AccessDenied => {1906            errors.error_info.setMessage("cannot replace {s}", .{install_path});1907            errors.error_info.setSuggestion("try: sudo nina update", .{});1908            return error.AccessDenied;1909        },1910        else => return e,1911    };1912}19131914// --- Nix feature setup ---19151916pub const NixFeatureStatus = struct {1917    nix_command: bool = false,1918    flakes: bool = false,19191920    pub fn allEnabled(self: NixFeatureStatus) bool {1921        return self.nix_command and self.flakes;1922    }1923};19241925fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1926    var lines = std.mem.splitScalar(u8, conf, '\n');1927    while (lines.next()) |line| {1928        const trimmed = std.mem.trim(u8, line, " \t");1929        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1930        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1931        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1932    }1933}19341935pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1936    var status = NixFeatureStatus{};19371938    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1939        defer gpa.free(conf);1940        scanConfFeatures(conf, &status);1941    }19421943    if (environ.get("HOME")) |home| {1944        var buf: [512]u8 = undefined;1945        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1946        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1947            defer gpa.free(conf);1948            scanConfFeatures(conf, &status);1949        }1950    }19511952    return status;1953}19541955pub fn isNixOS(io: std.Io) bool {1956    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1957    file.close(io);1958    return true;1959}19601961// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.1962// Returns the path written (caller must free).1963pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1964    const home = environ.get("HOME") orelse {1965        errors.error_info.setMessage("HOME not set", .{});1966        return error.ConfigNotFound;1967    };19681969    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1970    defer gpa.free(dir_path);1971    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1972    errdefer gpa.free(file_path);19731974    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};19751976    const line = "experimental-features = nix-command flakes\n";1977    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1978        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1979        errors.error_info.setMessage("could not write {s}", .{file_path});1980        return error.FileNotFound;1981    });1982    defer file.close(io);19831984    const size = file.length(io) catch 0;1985    file.writePositionalAll(io, line, size) catch {1986        errors.error_info.setMessage("could not write {s}", .{file_path});1987        return error.FileNotFound;1988    };19891990    return file_path;1991}19921993// --- NixOS: declarative experimental-features ---1994//1995// On NixOS the permanent, declarative home for these flags is configuration.nix,1996// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves1997// the `nixos-rebuild switch` to the user.19981999pub const NIXOS_FEATURES_LINE =2000    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";20012002// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns2003// false on any read error so the caller still offers to add the line.2004pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {2005    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;2006    defer gpa.free(conf);2007    return std.mem.indexOf(u8, conf, "experimental-features") != null and2008        std.mem.indexOf(u8, conf, "nix-command") != null and2009        std.mem.indexOf(u8, conf, "flakes") != null;2010}20112012fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {2013    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;2014    return captureLocal(gpa, io, &.{ "sudo", "cat", path });2015}20162017// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix2018// (i.e. inside the top-level attribute set) and write it back via a single2019// `sudo cp`, which prompts for the password on the terminal. Returns an error2020// for the caller to fall back to printed manual instructions.2021pub fn appendFeaturesToNixosConfig(2022    gpa: std.mem.Allocator,2023    io: std.Io,2024    environ: *const std.process.Environ.Map,2025    path: []const u8,2026) !void {2027    const conf = readMaybeSudo(gpa, io, path) catch {2028        errors.error_info.setMessage("could not read {s}", .{path});2029        return error.ConfigNotFound;2030    };2031    defer gpa.free(conf);20322033    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared20342035    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {2036        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});2037        return error.MalformedConfig;2038    };20392040    const home = environ.get("HOME") orelse {2041        errors.error_info.setMessage("HOME not set", .{});2042        return error.ConfigNotFound;2043    };2044    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});2045    defer gpa.free(tmp_path);20462047    var buf: std.ArrayList(u8) = .empty;2048    defer buf.deinit(gpa);2049    try buf.appendSlice(gpa, conf[0..brace]);2050    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');2051    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");2052    try buf.appendSlice(gpa, "  ");2053    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);2054    try buf.append(gpa, '\n');2055    try buf.appendSlice(gpa, conf[brace..]);20562057    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {2058        errors.error_info.setMessage("could not write {s}", .{tmp_path});2059        return error.FileNotFound;2060    };2061    tmp.writePositionalAll(io, buf.items, 0) catch {2062        tmp.close(io);2063        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2064        errors.error_info.setMessage("could not write {s}", .{tmp_path});2065        return error.FileNotFound;2066    };2067    tmp.close(io);20682069    // Back up the existing config, then replace it — in one sudo call so the2070    // password is asked for at most once. Paths travel as positional args ($0,2071    // $1) to sidestep shell quoting.2072    const code = streamLocal(io, &.{2073        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,2074    }) catch {2075        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2076        errors.error_info.setMessage("could not write {s}", .{path});2077        return error.ProcessFailed;2078    };2079    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2080    if (code != 0) {2081        errors.error_info.setMessage("sudo cp into {s} failed", .{path});2082        return error.ProcessFailed;2083    }2084}