exec.zig

85.7 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, extra_flags: []const []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:");10971098    var argv: std.ArrayList([]const u8) = .empty;1099    defer argv.deinit(gpa);1100    try argv.append(gpa, "nix");1101    try argv.append(gpa, "run");11021103    var ref_buf: ?[]u8 = null;1104    defer if (ref_buf) |r| gpa.free(r);1105    if (is_url) {1106        try argv.append(gpa, pkg);1107        try argv.append(gpa, "--no-write-lock-file");1108    } else if (std.mem.indexOfScalar(u8, pkg, '#') != null) {1109        // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.1110        try argv.append(gpa, pkg);1111    } else {1112        ref_buf = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1113        try argv.append(gpa, ref_buf.?);1114    }11151116    // extra_flags carries any `-- <program args>` separator verbatim, so this1117    // naturally reconstructs `nix run <ref> -- <args>` — nix's own convention.1118    try argv.appendSlice(gpa, extra_flags);1119    return stream(io, machine, gpa, argv.items);1120}11211122pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1123    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1124    defer gpa.free(ref);1125    return stream(io, machine, gpa, &.{ "nix", "shell", ref });1126}11271128pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {1129    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1130    defer gpa.free(ref);1131    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});1132    defer gpa.free(ps1);1133    if (machine.local) {1134        const rc_path = try createInteractiveShellRc(gpa, io);1135        defer {1136            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1137            gpa.free(rc_path);1138        }1139        return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref, "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, ps1);1140    }1141    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);1142}11431144pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8, extra_flags: []const []const u8) !u8 {1145    if (run_cmd) |cmd| {1146        // sh -c so a multi-word command isn't treated as a single executable name.1147        var argv: std.ArrayList([]const u8) = .empty;1148        defer argv.deinit(gpa);1149        try argv.appendSlice(gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1150        try argv.appendSlice(gpa, extra_flags);1151        return stream(io, machine, gpa, argv.items);1152    }1153    var argv: std.ArrayList([]const u8) = .empty;1154    defer argv.deinit(gpa);1155    try argv.append(gpa, "nix");1156    try argv.append(gpa, "develop");1157    try argv.appendSlice(gpa, extra_flags);1158    return stream(io, machine, gpa, argv.items);1159}11601161pub 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 {1162    if (run_cmd) |cmd| {1163        // sh -c so a multi-word command isn't treated as a single executable name.1164        var argv: std.ArrayList([]const u8) = .empty;1165        defer argv.deinit(gpa);1166        try argv.appendSlice(gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1167        try argv.appendSlice(gpa, extra_flags);1168        return stream(io, machine, gpa, argv.items);1169    }1170    if (machine.local) {1171        const rc_path = try createInteractiveShellRc(gpa, io);1172        defer {1173            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1174            gpa.free(rc_path);1175        }1176        var argv: std.ArrayList([]const u8) = .empty;1177        defer argv.deinit(gpa);1178        try argv.append(gpa, "nix");1179        try argv.append(gpa, "develop");1180        try argv.appendSlice(gpa, extra_flags);1181        try argv.appendSlice(gpa, &.{ "--command", "bash", "--rcfile", rc_path, "-i" });1182        return streamEnv(io, machine, gpa, argv.items, base_env, "(nina: dev) -> ");1183    }1184    var argv: std.ArrayList([]const u8) = .empty;1185    defer argv.deinit(gpa);1186    try argv.append(gpa, "nix");1187    try argv.append(gpa, "develop");1188    try argv.appendSlice(gpa, extra_flags);1189    return streamEnv(io, machine, gpa, argv.items, base_env, "(nina: dev) -> ");1190}11911192pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1193    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });1194}11951196// --- Format ---11971198pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {1199    if (check) {1200        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });1201    }1202    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });1203}12041205// --- Info ---12061207pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1208    const r = try capture(gpa, io, machine, &.{"nixos-version"});1209    defer gpa.free(r.stderr);1210    if (r.exit_code != 0) {1211        gpa.free(r.stdout);1212        return error.ProcessFailed;1213    }1214    return r.stdout;1215}12161217pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1218    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });1219    defer gpa.free(r.stderr);1220    if (r.exit_code != 0) {1221        gpa.free(r.stdout);1222        return error.ProcessFailed;1223    }1224    return r.stdout;1225}12261227pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1228    const r = try capture(gpa, io, machine, &.{"uptime"});1229    defer gpa.free(r.stderr);1230    if (r.exit_code != 0) {1231        gpa.free(r.stdout);1232        return error.ProcessFailed;1233    }1234    return r.stdout;1235}12361237// --- Boot ---12381239pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {1240    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });1241    defer gpa.free(r.stderr);1242    defer gpa.free(r.stdout);1243    if (r.exit_code != 0) return error.ProcessFailed;1244    return parseBootEntries(gpa, r.stdout);1245}12461247fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {1248    var entries: std.ArrayList(types.BootEntry) = .empty;1249    var lines = std.mem.splitScalar(u8, output_str, '\n');1250    while (lines.next()) |line| {1251        const trimmed = std.mem.trim(u8, line, " \t\r");1252        if (std.mem.startsWith(u8, trimmed, "title:")) {1253            const title = std.mem.trim(u8, trimmed[6..], " \t");1254            const current = std.mem.indexOf(u8, title, "(current)") != null;1255            try entries.append(gpa, .{1256                .title = try gpa.dupe(u8, title),1257                .current = current,1258            });1259        }1260    }1261    return entries.toOwnedSlice(gpa);1262}12631264// --- Pkg info ---12651266fn pkgInstallable(gpa: std.mem.Allocator, pkg: []const u8) ![]u8 {1267    return std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1268}12691270fn resolvePkgStorePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, installable: []const u8) ![]u8 {1271    const r = try capture(gpa, io, machine, &.{ "nix", "build", "--no-link", "--print-out-paths", installable });1272    defer gpa.free(r.stderr);1273    defer gpa.free(r.stdout);1274    if (r.exit_code != 0) return error.PackageNotFound;12751276    var lines = std.mem.tokenizeAny(u8, r.stdout, "\r\n");1277    const first_path = lines.next() orelse return error.PackageNotFound;1278    const store_path = std.mem.trim(u8, first_path, " \t");1279    if (store_path.len == 0) return error.PackageNotFound;1280    return gpa.dupe(u8, store_path);1281}12821283pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1284    const installable = try pkgInstallable(gpa, pkg);1285    defer gpa.free(installable);1286    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1287    defer gpa.free(store_path);1288    return stream(io, machine, gpa, &.{ "nix", "why-depends", "/run/current-system", store_path });1289}12901291pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1292    const installable = try pkgInstallable(gpa, pkg);1293    defer gpa.free(installable);1294    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1295    defer gpa.free(store_path);1296    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", store_path });1297}12981299pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {1300    const installable = try pkgInstallable(gpa, pkg);1301    defer gpa.free(installable);1302    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", "--json", installable });1303    defer gpa.free(r.stderr);1304    defer gpa.free(r.stdout);1305    if (r.exit_code != 0) return error.ProcessFailed;13061307    const nar_size = try pathInfoNarSize(gpa, r.stdout);1308    return humanPkgSize(gpa, nar_size);1309}13101311pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1312    const installable = try pkgInstallable(gpa, pkg);1313    defer gpa.free(installable);1314    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1315    defer gpa.free(store_path);1316    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", store_path });1317}13181319fn pathInfoNarSize(gpa: std.mem.Allocator, json_str: []const u8) !u64 {1320    var parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.ProcessFailed;1321    defer parsed.deinit();1322    switch (parsed.value) {1323        .object => |obj| {1324            var it = obj.iterator();1325            while (it.next()) |entry| {1326                if (entry.value_ptr.* == .object) {1327                    if (entry.value_ptr.object.get("narSize")) |v| {1328                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1329                    }1330                }1331            }1332        },1333        .array => |arr| {1334            for (arr.items) |item| {1335                if (item == .object) {1336                    if (item.object.get("narSize")) |v| {1337                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1338                    }1339                }1340            }1341        },1342        else => {},1343    }1344    return error.ProcessFailed;1345}13461347fn humanPkgSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1348    const units = [_][]const u8{ "B", "KiB", "MiB", "GiB", "TiB" };1349    var val: f64 = @floatFromInt(bytes);1350    var unit: usize = 0;1351    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1352    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1353    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1354}13551356test "pathInfoNarSize parses object and array shapes" {1357    try std.testing.expectEqual(@as(u64, 1064629862), try pathInfoNarSize(std.testing.allocator,1358        \\{"/nix/store/abc-ffmpeg":{"narSize":1064629862}}1359    ));1360    try std.testing.expectEqual(@as(u64, 2048), try pathInfoNarSize(std.testing.allocator,1361        \\[{"path":"/nix/store/abc-pkg","narSize":2048}]1362    ));1363}13641365// --- Hash / Fetch ---13661367pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {1368    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });1369    defer gpa.free(r.stderr);1370    if (r.exit_code != 0) {1371        gpa.free(r.stdout);1372        return error.ProcessFailed;1373    }1374    return r.stdout;1375}13761377pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {1378    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });1379    defer gpa.free(r.stderr);1380    if (r.exit_code != 0) {1381        gpa.free(r.stdout);1382        return error.ProcessFailed;1383    }1384    return r.stdout;1385}13861387// --- Pin ---13881389pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {1390    // Stub: full implementation would parse and edit flake.lock JSON1391    // The pin/unpin flow works via nix flake update which regenerates flake.lock1392}13931394pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {1395    if (line) |l| {1396        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});1397        defer gpa.free(line_arg);1398        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });1399    }1400    return stream(io, &types.Machine{}, gpa, &.{ editor, path });1401}14021403// Open a config directory as root with `sudo -E <editor> <path>` — `-E`1404// preserves the user's environment (PATH, TERM, EDITOR config) so the editor1405// behaves the same as it does unprivileged. Used by `nina edit --dir`.1406pub fn openEditorSudo(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8) !u8 {1407    return stream(io, &types.Machine{}, gpa, &.{ "sudo", "-E", editor, path });1408}14091410pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {1411    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});1412    defer gpa.free(a_str);1413    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});1414    defer gpa.free(b_str);1415    // On a tty, the child's own color is fine — stream it directly.1416    if (output.colorEnabled()) {1417        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });1418    }1419    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,1420    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.1421    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });1422    defer gpa.free(r.stdout);1423    defer gpa.free(r.stderr);1424    const cleaned = try stripAnsi(gpa, r.stdout);1425    defer gpa.free(cleaned);1426    output.raw(cleaned);1427    return r.exit_code;1428}14291430// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a1431// child process's color when it writes ANSI unconditionally.1432fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1433    var out: std.ArrayList(u8) = .empty;1434    errdefer out.deinit(gpa);1435    var i: usize = 0;1436    while (i < input.len) {1437        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1438            i += 2;1439            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1440            if (i < input.len) i += 1; // consume the final byte1441            continue;1442        }1443        try out.append(gpa, input[i]);1444        i += 1;1445    }1446    return out.toOwnedSlice(gpa);1447}14481449test "stripAnsi removes CSI color sequences" {1450    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1451    defer std.testing.allocator.free(cleaned);1452    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1453}14541455// --- Doctor checks ---14561457pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1458    var checks: std.ArrayList(types.DoctorCheck) = .empty;14591460    // Check nix daemon1461    {1462        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1463        defer gpa.free(r.stdout);1464        defer gpa.free(r.stderr);1465        const active = std.mem.indexOf(u8, r.stdout, "active") != null;1466        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1467    }14681469    // Check config syntax. Flake-aware like apply/upgrade: on a flake system a1470    // plain `nixos-rebuild dry-build` evaluates <nixpkgs/nixos> + <nixos-config>1471    // (channel style) and fails, so pass --flake when the config dir has one.1472    {1473        const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1474            &.{ "sudo", "nixos-rebuild", "dry-build", "--flake", machine.config_path }1475        else1476            &.{ "sudo", "nixos-rebuild", "dry-build" };1477        const r = try capture(gpa, io, machine, argv);1478        defer gpa.free(r.stdout);1479        defer gpa.free(r.stderr);1480        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1481    }14821483    // Check channel1484    {1485        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1486        defer gpa.free(r.stdout);1487        defer gpa.free(r.stderr);1488        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1489        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1490    }14911492    return checks.toOwnedSlice(gpa);1493}14941495// --- Home Manager ---1496//1497// Home Manager has three usage modes. nina detects which one is in play before1498// any `home` command so it can either drive the standalone CLI or redirect the1499// user to `nina apply` (when HM is a NixOS/flake module activated by rebuild).15001501pub const HomeManagerMode = enum {1502    // home-manager binary on PATH — manages the user env on its own.1503    standalone,1504    // No binary, but a home.nix exists — HM is a NixOS/flake module rebuilt by1505    // nixos-rebuild. `nina home apply` redirects to `nina apply`.1506    module,1507    none,1508};15091510fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1511    const home = environ.get("HOME") orelse return null;1512    return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1513}15141515// Path to the standalone home.nix. Caller frees.1516pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1517    const dir = homeConfigDir(gpa, environ) orelse return null;1518    defer gpa.free(dir);1519    return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1520}15211522pub fn pathExists(io: std.Io, path: []const u8) bool {1523    const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1524    f.close(io);1525    return true;1526}15271528// `command -v <name>` — true if the binary resolves on PATH. Silent (captured),1529// unlike streamLocal which would inherit stdio.1530fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1531    var buf: [256]u8 = undefined;1532    const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1533    const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1534    defer gpa.free(r.stdout);1535    defer gpa.free(r.stderr);1536    return switch (r.term) {1537        .exited => |code| code == 0,1538        else => false,1539    };1540}15411542pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1543    if (commandExists(gpa, io, "home-manager")) return .standalone;1544    if (homeNixPath(gpa, environ)) |p| {1545        defer gpa.free(p);1546        if (pathExists(io, p)) return .module;1547    }1548    return .none;1549}15501551// The home-manager config dir when it holds a flake.nix (a flake-based home1552// config that `home-manager switch --flake` drives). null for a channel-based1553// config, which uses a plain `home-manager switch`. Caller frees.1554pub fn homeFlakeDir(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1555    const dir = homeConfigDir(gpa, environ) orelse return null;1556    const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch {1557        gpa.free(dir);1558        return null;1559    };1560    defer gpa.free(flake);1561    if (!pathExists(io, flake)) {1562        gpa.free(dir);1563        return null;1564    }1565    return dir;1566}15671568// Platform-specific home-manager attribute "<user>-<arch>-<os>" (e.g.1569// murazaki-x86_64-linux) — the homeConfigurations key many flakes derive from1570// ${USER}-${system}. arch/os come from uname on the local host (home commands1571// are local-only). Caller frees.1572pub fn homeManagerAttr(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, environ: *const std.process.Environ.Map) ![]const u8 {1573    const user = environ.get("USER") orelse "user";15741575    const arch_r = try capture(gpa, io, machine, &.{ "uname", "-m" });1576    defer gpa.free(arch_r.stdout);1577    defer gpa.free(arch_r.stderr);1578    if (arch_r.exit_code != 0) return error.ProcessFailed;1579    const arch = std.mem.trim(u8, arch_r.stdout, " \t\r\n");15801581    const os_r = try capture(gpa, io, machine, &.{ "uname", "-s" });1582    defer gpa.free(os_r.stdout);1583    defer gpa.free(os_r.stderr);1584    if (os_r.exit_code != 0) return error.ProcessFailed;1585    const os = try gpa.dupe(u8, std.mem.trim(u8, os_r.stdout, " \t\r\n"));1586    defer gpa.free(os);1587    for (os) |*ch| ch.* = std.ascii.toLower(ch.*);15881589    if (arch.len == 0 or os.len == 0) return error.ProcessFailed;1590    return std.fmt.allocPrint(gpa, "{s}-{s}-{s}", .{ user, arch, os });1591}15921593// Map a nixos-version string to the matching home-manager branch: an unstable1594// channel ("…pre…"/"unstable") → master; a stable release like1595// "25.05.20250115.abcdef (Warbler)" → release-25.05. Anything unparseable1596// falls back to master. Caller frees.1597fn homeBranchFromVersion(gpa: std.mem.Allocator, version_raw: []const u8) ![]const u8 {1598    const v = std.mem.trim(u8, version_raw, " \t\r\n");1599    if (std.mem.indexOf(u8, v, "pre") != null or1600        std.mem.indexOf(u8, v, "unstable") != null)1601        return gpa.dupe(u8, "master");16021603    const head = v[0 .. std.mem.indexOfScalar(u8, v, ' ') orelse v.len];1604    var it = std.mem.splitScalar(u8, head, '.');1605    const major = it.next() orelse "";1606    const minor = it.next() orelse "";1607    if (allDigits(major) and allDigits(minor))1608        return std.fmt.allocPrint(gpa, "release-{s}.{s}", .{ major, minor });16091610    return gpa.dupe(u8, "master");1611}16121613fn allDigits(s: []const u8) bool {1614    if (s.len == 0) return false;1615    for (s) |ch| if (!std.ascii.isDigit(ch)) return false;1616    return true;1617}16181619test "homeBranchFromVersion maps channels to HM branches" {1620    const a = std.testing.allocator;1621    const cases = [_]struct { in: []const u8, want: []const u8 }{1622        .{ .in = "25.05.20250115.abcdef (Warbler)", .want = "release-25.05" },1623        .{ .in = "24.11.20241201.deadbee (Vicuna)", .want = "release-24.11" },1624        .{ .in = "25.11pre-git", .want = "master" },1625        .{ .in = "25.05pre789012.abcdef (Warbler)", .want = "master" },1626        .{ .in = "nixos-unstable", .want = "master" },1627        .{ .in = "garbage", .want = "master" },1628    };1629    for (cases) |c| {1630        const got = try homeBranchFromVersion(a, c.in);1631        defer a.free(got);1632        try std.testing.expectEqualStrings(c.want, got);1633    }1634}16351636// The home-manager branch matching the running nixpkgs. Falls back to master1637// when nixos-version is unavailable (non-NixOS host). Caller frees.1638fn detectHomeManagerBranch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]const u8 {1639    const r = capture(gpa, io, machine, &.{"nixos-version"}) catch1640        return gpa.dupe(u8, "master");1641    defer gpa.free(r.stdout);1642    defer gpa.free(r.stderr);1643    if (r.exit_code != 0) return gpa.dupe(u8, "master");1644    return homeBranchFromVersion(gpa, r.stdout);1645}16461647// `nix run home-manager/<branch> -- init [--switch] [dir]` — generates1648// flake.nix + home.nix (in dir, or ~/.config/home-manager by default),1649// activating immediately when switch_on_init is set.1650pub fn homeManagerInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, switch_on_init: bool, dir: ?[]const u8) !u8 {1651    const branch = try detectHomeManagerBranch(gpa, io, machine);1652    defer gpa.free(branch);1653    const flake_ref = try std.fmt.allocPrint(gpa, "home-manager/{s}", .{branch});1654    defer gpa.free(flake_ref);16551656    var argv: std.ArrayList([]const u8) = .empty;1657    defer argv.deinit(gpa);1658    try argv.appendSlice(gpa, &.{ "nix", "run", flake_ref, "--", "init" });1659    if (switch_on_init) try argv.append(gpa, "--switch");1660    if (dir) |d| try argv.append(gpa, d);16611662    return stream(io, machine, gpa, argv.items);1663}16641665pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1666    output.flush();1667    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch" });1668    defer gpa.free(r.stdout);1669    defer gpa.free(r.stderr);1670    errors.setBuildStderr(r.stderr);1671    return r.exit_code;1672}16731674// Outcome of a flake-based switch, so the caller can fall back to a less1675// specific attribute on a missing-attribute evaluation error — but never on a1676// genuine build failure.1677pub const SwitchOutcome = enum { ok, attr_missing, failed };16781679pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8) !SwitchOutcome {1680    output.flush();1681    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch", "--flake", flake_ref });1682    defer gpa.free(r.stdout);1683    defer gpa.free(r.stderr);1684    if (r.exit_code == 0) return .ok;1685    // A flake that doesn't define this homeConfiguration fails during evaluation1686    // with "does not provide attribute" — surface that so the caller can retry a1687    // different attr rather than treating it as a build failure.1688    if (std.mem.indexOf(u8, r.stderr, "does not provide attribute") != null)1689        return .attr_missing;1690    errors.setBuildStderr(r.stderr);1691    return .failed;1692}16931694// home-manager has no system-profile rollback; it re-activates the previous1695// generation via `switch --rollback`.1696pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1697    output.flush();1698    const r = try capture(gpa, io, machine, &.{ "home-manager", "switch", "--rollback" });1699    defer gpa.free(r.stdout);1700    defer gpa.free(r.stderr);1701    errors.setBuildStderr(r.stderr);1702    return r.exit_code;1703}17041705// Build (and validate) the home config without activating it — used by `home1706// check` and `home apply --dry`. `home-manager build` drops a ./result symlink1707// in the cwd, so run it in a throwaway temp dir to avoid littering the directory1708// nina was invoked from.1709pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1710    output.flush();1711    const r = try capture(gpa, io, machine, &.{ "sh", "-c", "d=$(mktemp -d) && cd \"$d\" && home-manager build" });1712    defer gpa.free(r.stdout);1713    defer gpa.free(r.stderr);1714    errors.setBuildStderr(r.stderr);1715    return r.exit_code;1716}17171718pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1719    const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1720    defer gpa.free(r.stderr);1721    if (r.exit_code != 0) {1722        gpa.free(r.stdout);1723        return error.ProcessFailed;1724    }1725    return r.stdout;1726}17271728// Store paths referenced by a home generation — used to list managed packages.1729pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1730    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1731    defer gpa.free(r.stderr);1732    if (r.exit_code != 0) {1733        gpa.free(r.stdout);1734        return error.ProcessFailed;1735    }1736    return r.stdout;1737}17381739// diff-closures between two arbitrary store paths (home generations), mirroring1740// diffClosures' tty/piped color handling.1741pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1742    if (output.colorEnabled()) {1743        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1744    }1745    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1746    defer gpa.free(r.stdout);1747    defer gpa.free(r.stderr);1748    const cleaned = try stripAnsi(gpa, r.stdout);1749    defer gpa.free(cleaned);1750    output.raw(cleaned);1751    return r.exit_code;1752}17531754// --- Log ---17551756pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1757    const home = environ.get("HOME") orelse return error.FileNotFound;1758    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1759    defer gpa.free(path);1760    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1761    if (last == 0) return content;17621763    // Collect non-empty lines, then keep only the final `last`. Slices point into1764    // `content`, so copy them out before freeing it.1765    var lines: std.ArrayList([]const u8) = .empty;1766    defer lines.deinit(gpa);1767    var it = std.mem.splitScalar(u8, content, '\n');1768    while (it.next()) |line| {1769        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1770        try lines.append(gpa, line);1771    }1772    if (lines.items.len <= last) return content;17731774    var out: std.ArrayList(u8) = .empty;1775    errdefer out.deinit(gpa);1776    for (lines.items[lines.items.len - last ..]) |line| {1777        try out.appendSlice(gpa, line);1778        try out.append(gpa, '\n');1779    }1780    gpa.free(content);1781    return out.toOwnedSlice(gpa);1782}17831784// nina is a one-shot process, so "did the last apply fail this session?" can't1785// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1786// other ~/.nina-* state files. This lets a later successful apply earn the1787// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1788pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1789    const home = environ.get("HOME") orelse return;1790    var buf: [512]u8 = undefined;1791    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1792    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1793    file.close(io);1794}17951796pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1797    const home = environ.get("HOME") orelse return false;1798    var buf: [512]u8 = undefined;1799    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1800    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1801        f.close(io);1802        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1803        return true;1804    } else |_| {1805        return false;1806    }1807}18081809pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1810    const home = environ.get("HOME") orelse return;1811    var path_buf: [512]u8 = undefined;1812    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1813    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1814        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1815    defer file.close(io);1816    const size = file.length(io) catch 0;1817    file.writePositionalAll(io, entry, size) catch {};1818}18191820// --- Update helpers ---18211822// Fetch a URL with curl and return the response body. Caller must free.1823// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.1824pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1825    const argv = [_][]const u8{1826        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1827    };1828    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1829    defer gpa.free(result.stderr);18301831    const marker = "\nHTTP_STATUS:";1832    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1833        gpa.free(result.stdout);1834        return error.NetworkError;1835    };1836    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1837    const status = std.fmt.parseInt(u16, status_str, 10) catch {1838        gpa.free(result.stdout);1839        return error.NetworkError;1840    };1841    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1842    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1843    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1844        gpa.free(result.stdout);1845        return e;1846    };1847    gpa.free(result.stdout);1848    return body;1849}18501851// Download a URL to a temp file. Returns the temp path (caller must gpa.free).1852// The file is written to /tmp/nina-update-<pid> and left for the caller to use.1853pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1854    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1855    errdefer gpa.free(tmp_path);18561857    var child = std.process.spawn(io, .{1858        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1859        .stdin = .close,1860        .stdout = .close,1861        .stderr = .inherit,1862    }) catch return error.NetworkError;1863    const term = child.wait(io) catch return error.NetworkError;1864    switch (term) {1865        .exited => |c| if (c != 0) return error.NetworkError,1866        else => return error.NetworkError,1867    }1868    return tmp_path;1869}18701871// Get the current executable path into buf. Returns slice of buf.1872pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1873    const len = try std.process.executablePath(io, buf);1874    return buf[0..len];1875}18761877// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1878// atomically install the binary to install_path. Errors: ChecksumMismatch,1879// AccessDenied (with error_info set), or underlying I/O errors.1880pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1881    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1882        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1883        return error.FileNotFound;1884    };1885    defer gpa.free(bytes);18861887    var hasher = std.crypto.hash.Blake3.init(.{});1888    hasher.update(bytes);1889    var raw: [32]u8 = undefined;1890    hasher.final(&raw);1891    const hex = std.fmt.bytesToHex(raw, .lower);1892    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;18931894    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1895    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1896        return error.NameTooLong;18971898    {1899        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1900            errors.error_info.setMessage("cannot write to {s}", .{install_path});1901            errors.error_info.setSuggestion("try: sudo nina update", .{});1902            return error.AccessDenied;1903        };1904        defer f.close(io);1905        f.writePositionalAll(io, bytes, 0) catch {1906            errors.error_info.setMessage("cannot write to {s}", .{install_path});1907            return error.AccessDenied;1908        };1909        try f.setPermissions(io, .fromMode(0o755));1910    }1911    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};19121913    if (comptime builtin.os.tag == .macos) {1914        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1915    }19161917    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1918        error.AccessDenied => {1919            errors.error_info.setMessage("cannot replace {s}", .{install_path});1920            errors.error_info.setSuggestion("try: sudo nina update", .{});1921            return error.AccessDenied;1922        },1923        else => return e,1924    };1925}19261927// --- Nix feature setup ---19281929pub const NixFeatureStatus = struct {1930    nix_command: bool = false,1931    flakes: bool = false,19321933    pub fn allEnabled(self: NixFeatureStatus) bool {1934        return self.nix_command and self.flakes;1935    }1936};19371938fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1939    var lines = std.mem.splitScalar(u8, conf, '\n');1940    while (lines.next()) |line| {1941        const trimmed = std.mem.trim(u8, line, " \t");1942        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1943        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1944        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1945    }1946}19471948pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1949    var status = NixFeatureStatus{};19501951    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1952        defer gpa.free(conf);1953        scanConfFeatures(conf, &status);1954    }19551956    if (environ.get("HOME")) |home| {1957        var buf: [512]u8 = undefined;1958        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1959        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1960            defer gpa.free(conf);1961            scanConfFeatures(conf, &status);1962        }1963    }19641965    return status;1966}19671968pub fn isNixOS(io: std.Io) bool {1969    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1970    file.close(io);1971    return true;1972}19731974// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.1975// Returns the path written (caller must free).1976pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1977    const home = environ.get("HOME") orelse {1978        errors.error_info.setMessage("HOME not set", .{});1979        return error.ConfigNotFound;1980    };19811982    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1983    defer gpa.free(dir_path);1984    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1985    errdefer gpa.free(file_path);19861987    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};19881989    const line = "experimental-features = nix-command flakes\n";1990    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1991        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1992        errors.error_info.setMessage("could not write {s}", .{file_path});1993        return error.FileNotFound;1994    });1995    defer file.close(io);19961997    const size = file.length(io) catch 0;1998    file.writePositionalAll(io, line, size) catch {1999        errors.error_info.setMessage("could not write {s}", .{file_path});2000        return error.FileNotFound;2001    };20022003    return file_path;2004}20052006// --- NixOS: declarative experimental-features ---2007//2008// On NixOS the permanent, declarative home for these flags is configuration.nix,2009// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves2010// the `nixos-rebuild switch` to the user.20112012pub const NIXOS_FEATURES_LINE =2013    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";20142015// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns2016// false on any read error so the caller still offers to add the line.2017pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {2018    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;2019    defer gpa.free(conf);2020    return std.mem.indexOf(u8, conf, "experimental-features") != null and2021        std.mem.indexOf(u8, conf, "nix-command") != null and2022        std.mem.indexOf(u8, conf, "flakes") != null;2023}20242025fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {2026    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;2027    return captureLocal(gpa, io, &.{ "sudo", "cat", path });2028}20292030// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix2031// (i.e. inside the top-level attribute set) and write it back via a single2032// `sudo cp`, which prompts for the password on the terminal. Returns an error2033// for the caller to fall back to printed manual instructions.2034pub fn appendFeaturesToNixosConfig(2035    gpa: std.mem.Allocator,2036    io: std.Io,2037    environ: *const std.process.Environ.Map,2038    path: []const u8,2039) !void {2040    const conf = readMaybeSudo(gpa, io, path) catch {2041        errors.error_info.setMessage("could not read {s}", .{path});2042        return error.ConfigNotFound;2043    };2044    defer gpa.free(conf);20452046    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared20472048    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {2049        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});2050        return error.MalformedConfig;2051    };20522053    const home = environ.get("HOME") orelse {2054        errors.error_info.setMessage("HOME not set", .{});2055        return error.ConfigNotFound;2056    };2057    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});2058    defer gpa.free(tmp_path);20592060    var buf: std.ArrayList(u8) = .empty;2061    defer buf.deinit(gpa);2062    try buf.appendSlice(gpa, conf[0..brace]);2063    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');2064    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");2065    try buf.appendSlice(gpa, "  ");2066    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);2067    try buf.append(gpa, '\n');2068    try buf.appendSlice(gpa, conf[brace..]);20692070    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {2071        errors.error_info.setMessage("could not write {s}", .{tmp_path});2072        return error.FileNotFound;2073    };2074    tmp.writePositionalAll(io, buf.items, 0) catch {2075        tmp.close(io);2076        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2077        errors.error_info.setMessage("could not write {s}", .{tmp_path});2078        return error.FileNotFound;2079    };2080    tmp.close(io);20812082    // Back up the existing config, then replace it — in one sudo call so the2083    // password is asked for at most once. Paths travel as positional args ($0,2084    // $1) to sidestep shell quoting.2085    const code = streamLocal(io, &.{2086        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,2087    }) catch {2088        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2089        errors.error_info.setMessage("could not write {s}", .{path});2090        return error.ProcessFailed;2091    };2092    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2093    if (code != 0) {2094        errors.error_info.setMessage("sudo cp into {s} failed", .{path});2095        return error.ProcessFailed;2096    }2097}