exec.zig

72.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}349350fn nixosRebuildRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, flake: bool) !u8 {351    if (flake) {352        return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb, "--flake", machine.config_path });353    }354    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb });355}356357pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {358    const flake = useFlakeFlag(gpa, io, machine);359    if (flake) {360        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});361    } else {362        output.printSubstep("nixos-rebuild switch", .{});363    }364    return nixosRebuildRun(io, machine, gpa, "switch", flake);365}366367pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {368    return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine));369}370371pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {372    return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine));373}374375// --- Generations ---376377// Read system-profile generations WITHOUT root. `nix-env --list-generations -p378// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user379// ("system.lock: Permission denied"). The generation symlinks themselves are380// world-readable, so list them directly: parse `system-N-link` names, take each381// link's own mtime for the date/time, and mark the one the `system` symlink382// points at as current. Output matches the `nix-env --list-generations` columns383// (num date time [current]) so parseGenerations is unchanged.384const GEN_LIST_SCRIPT =385    \\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 }'386;387388pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {389    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });390    defer gpa.free(r.stderr);391    defer gpa.free(r.stdout);392    if (r.exit_code != 0) return error.ProcessFailed;393    return parseGenerations(gpa, r.stdout);394}395396fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {397    var gens: std.ArrayList(types.GenerationInfo) = .empty;398    var lines = std.mem.splitScalar(u8, output_str, '\n');399    while (lines.next()) |line| {400        const trimmed = std.mem.trim(u8, line, " \t");401        if (trimmed.len == 0) continue;402        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");403        const num_str = parts.next() orelse continue;404        const date_str = parts.next() orelse continue;405        const time_str = parts.next() orelse continue;406        const rest = parts.rest();407        const current = std.mem.indexOf(u8, rest, "current") != null;408        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;409        try gens.append(gpa, .{410            .number = num,411            .date = try gpa.dupe(u8, date_str),412            .time = try gpa.dupe(u8, time_str),413            .current = current,414        });415    }416    return gens.toOwnedSlice(gpa);417}418419pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {420    const gens = try getGenerations(gpa, io, machine);421    defer gpa.free(gens);422    for (gens) |g| {423        if (g.current) return g.number;424    }425    return 0;426}427428pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {429    // Switch the system profile to generation n, then activate it (bootloader +430    // services). Without switch-to-configuration the change isn't applied.431    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 });432    defer gpa.free(cmd);433    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });434}435436pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {437    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });438}439440pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {441    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});442    defer gpa.free(n_str);443    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });444}445446pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {447    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });448}449450// --- Garbage collection ---451452pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {453    if (delete_old) {454        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });455    }456    // Keep the `keep` most recent system generations (+N deletes all but N),457    // then collect now-unreferenced store paths. `--delete-older-than` wants a458    // duration (e.g. 14d), not a generation count.459    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });460    defer gpa.free(cmd);461    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });462}463464// --- Channels ---465466pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {467    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });468    defer gpa.free(r.stderr);469    defer gpa.free(r.stdout);470    if (r.exit_code != 0) return error.ProcessFailed;471    return parseChannels(gpa, r.stdout);472}473474fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {475    var channels: std.ArrayList(types.ChannelInfo) = .empty;476    var lines = std.mem.splitScalar(u8, output_str, '\n');477    while (lines.next()) |line| {478        const trimmed = std.mem.trim(u8, line, " \t\r");479        if (trimmed.len == 0) continue;480        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;481        try channels.append(gpa, .{482            .name = try gpa.dupe(u8, trimmed[0..space]),483            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),484        });485    }486    return channels.toOwnedSlice(gpa);487}488489pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {490    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });491}492493pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {494    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });495}496497pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {498    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });499}500501// --- Services ---502503pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {504    const cmd: []const []const u8 = if (user)505        &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }506    else507        &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };508    const r = try capture(gpa, io, machine, cmd);509    defer gpa.free(r.stderr);510    defer gpa.free(r.stdout);511    if (r.exit_code != 0) return error.ProcessFailed;512    return parseServices(gpa, r.stdout);513}514515fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {516    var svcs: std.ArrayList(types.ServiceInfo) = .empty;517    var lines = std.mem.splitScalar(u8, output_str, '\n');518    while (lines.next()) |line| {519        const trimmed = std.mem.trim(u8, line, " \t\r");520        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines521        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");522        const name = parts.next() orelse continue;523        _ = parts.next(); // load524        const active_str = parts.next() orelse continue;525        const sub_str = parts.next() orelse "unknown";526527        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))528            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)529        else if (std.mem.eql(u8, active_str, "failed"))530            .failed531        else532            .inactive;533534        try svcs.append(gpa, .{535            .name = try gpa.dupe(u8, name),536            .state = state,537            .uptime = null,538        });539    }540    return svcs.toOwnedSlice(gpa);541}542543pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {544    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.545    // User services run under the caller's own systemd manager, so no sudo.546    if (user) {547        return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });548    }549    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });550}551552pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {553    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});554    defer gpa.free(n_str);555    if (user) {556        if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });557        return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });558    }559    if (follow) {560        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });561    }562    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });563}564565// --- Profile ---566567pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {568    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});569    defer gpa.free(pkg_ref);570    // `nix profile add` is the current verb; `install` is a deprecated alias that571    // prints a warning on modern nix.572    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });573}574575pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {576    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not577    // by flake ref — passing nixpkgs#ripgrep matches nothing.578    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });579}580581pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {582    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });583    defer gpa.free(r.stderr);584    if (r.exit_code != 0) return error.ProcessFailed;585    return r.stdout;586}587588// Machine-readable profile listing — caller parses elements -> name + version.589pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {590    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });591    defer gpa.free(r.stderr);592    if (r.exit_code != 0) {593        gpa.free(r.stdout);594        return error.ProcessFailed;595    }596    return r.stdout;597}598599// Returns the profile element name to pass to `nix profile remove/upgrade`600// (e.g. "nina" or "default"), or null if nina is not found. Caller owns the601// returned slice. A NixOS system-package install also resolves into /nix/store602// so the store path alone can't distinguish it from a profile install — the603// profile list can. A missing/empty profile (or no nix) returns null.604pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {605    const js = profileListJson(gpa, io, machine) catch return null;606    defer gpa.free(js);607    return profileJsonNinaElement(gpa, js);608}609610pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {611    const name = profileNinaElement(gpa, io, machine) orelse return false;612    gpa.free(name);613    return true;614}615616// True when a nix store path belongs to the nina package. Store paths have the617// form /nix/store/<32-char-hash>-<pname>-<version>[/<subpath>]. We check that618// the 33 chars after /nix/store/ are the hash+dash, and the pname that follows619// is exactly "nina" (followed by "-" or end-of-component).620fn storePathIsNina(path: []const u8) bool {621    const prefix = "/nix/store/";622    if (!std.mem.startsWith(u8, path, prefix)) return false;623    const rel = path[prefix.len..];624    // The store entry name ends at the first "/" (if any sub-path follows).625    const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];626    if (entry.len < 34) return false; // 32-char hash + dash + at least one char627    const pname_ver = entry[33..]; // skip hash + dash628    return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");629}630631// Pure parse of `nix profile list --json` for a nina element, returning its632// element name (the key to pass to `nix profile remove/upgrade`) or null.633// Newer nix (2.18+) keys elements by pname ("nina"). Older nix uses an array634// with an "attrPath" field. Tarball installs via the `default` output may use635// the key "default" instead of "nina"; we detect those via storePaths.636fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {637    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;638    defer parsed.deinit();639    const root = parsed.value;640    if (root != .object) return null;641    const elements = root.object.get("elements") orelse return null;642    switch (elements) {643        .object => |obj| {644            // Fast path: exact "nina" key (nix 2.18+ with nixpkgs#nina install).645            if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;646            // Fallback: scan storePaths. Handles tarball installs where the default647            // output is selected and nix names the element "default" (older nix) or648            // some other key derived from the attrPath rather than the pname.649            var it = obj.iterator();650            while (it.next()) |kv| {651                const val = kv.value_ptr.*;652                if (val != .object) continue;653                const sps = val.object.get("storePaths") orelse continue;654                if (sps != .array) continue;655                for (sps.array.items) |sp| {656                    if (sp == .string and storePathIsNina(sp.string))657                        return gpa.dupe(u8, kv.key_ptr.*) catch null;658                }659            }660            return null;661        },662        .array => |arr| {663            // Older nix array format. Element name is the last component of attrPath.664            for (arr.items) |el| {665                if (el != .object) continue;666                const ap = el.object.get("attrPath") orelse continue;667                if (ap != .string) continue;668                if (std.mem.eql(u8, ap.string, "nina") or669                    std.mem.endsWith(u8, ap.string, ".nina"))670                    return gpa.dupe(u8, "nina") catch null;671                // Tarball default-output install: attrPath ends in ".default" but672                // storePaths point to nina. Return "default" as the element name.673                const sps = el.object.get("storePaths") orelse continue;674                if (sps != .array) continue;675                for (sps.array.items) |sp| {676                    if (sp != .string) continue;677                    if (!storePathIsNina(sp.string)) continue;678                    const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;679                    const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;680                    return gpa.dupe(u8, el_name) catch null;681                }682            }683            return null;684        },685        else => return null,686    }687}688689test "profileJsonNinaElement finds element name from profile JSON" {690    const a = std.testing.allocator;691692    // Newer nix: elements keyed by pname. "nina" key present.693    const named =694        \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},695        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}696    ;697    const r1 = profileJsonNinaElement(a, named);698    defer if (r1) |n| a.free(n);699    try std.testing.expectEqualStrings("nina", r1.?);700701    // Tarball install via default output: element keyed as "default", storePath is nina.702    const default_key =703        \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}704    ;705    const r2 = profileJsonNinaElement(a, default_key);706    defer if (r2) |n| a.free(n);707    try std.testing.expectEqualStrings("default", r2.?);708709    // Decoy: storePath of another package contains "nina" as a substring but is not nina.710    const decoy =711        \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}712    ;713    const r3 = profileJsonNinaElement(a, decoy);714    try std.testing.expectEqual(@as(?[]const u8, null), r3);715716    // Older nix array schema, attrPath ending in ".nina".717    const arr =718        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}719    ;720    const r4 = profileJsonNinaElement(a, arr);721    defer if (r4) |n| a.free(n);722    try std.testing.expectEqualStrings("nina", r4.?);723724    // Older nix array schema, tarball default-output install.725    const arr_default =726        \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}727    ;728    const r5 = profileJsonNinaElement(a, arr_default);729    defer if (r5) |n| a.free(n);730    try std.testing.expectEqualStrings("default", r5.?);731732    // Empty / malformed → null.733    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));734    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));735}736737// The store paths that make up the running system environment. Each reference is738// a <hash>-<name>-<version> path, so the caller can list system packages with739// versions — there is no cleaner per-package list for environment.systemPackages.740pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {741    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });742    defer gpa.free(r.stderr);743    if (r.exit_code != 0) {744        gpa.free(r.stdout);745        return error.ProcessFailed;746    }747    return r.stdout;748}749750pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {751    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });752}753754// --- Store ---755756pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {757    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });758}759760pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {761    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });762}763764pub const SystemStatus = struct { size: []u8, age: []u8 };765766// One read-only pass for `nina status`: the current system's closure size (a767// single `path-info -S` of /run/current-system — fast, unlike -S over the whole768// store) and seconds since the system profile was last switched (its symlink769// mtime). Both are world-readable; no root needed.770const STATUS_SCRIPT =771    \\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} ))"772;773774pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {775    const unknown = SystemStatus{776        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },777        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },778    };779    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;780    defer gpa.free(r.stdout);781    defer gpa.free(r.stderr);782    if (r.exit_code != 0) return unknown;783784    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");785    const sz_str = it.next() orelse return unknown;786    const age_str = it.next() orelse return unknown;787    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;788    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;789790    gpa.free(unknown.size);791    gpa.free(unknown.age);792    return .{793        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),794        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),795    };796}797798// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A799// one-word health signal; exits non-zero when degraded, so we read stdout, not800// the code. Caller owns the returned slice.801pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {802    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch803        return gpa.dupe(u8, "unknown");804    defer gpa.free(r.stderr);805    const state = std.mem.trim(u8, r.stdout, " \t\n\r");806    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");807    gpa.free(r.stdout);808    return owned;809}810811fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {812    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});813    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});814    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});815    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});816}817818pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {819    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });820}821822pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {823    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)824    // graph work that takes minutes on a real store (59k+ paths) and hangs the825    // command. We don't need closures: `--all --json` (no -S) carries each path's826    // own narSize, so one fast pass gives the path count and the summed store size.827    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.828    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.829    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });830    defer gpa.free(pi.stdout);831    defer gpa.free(pi.stderr);832833    const scan = scanStoreJson(pi.stdout);834    const total_owned = try humanSize(gpa, scan.total_bytes);835836    return .{837        .total_size = total_owned,838        .live_paths = scan.count,839        .reclaimable_paths = 0,840    };841}842843const StoreScan = struct { count: u64, total_bytes: u64 };844845// One linear pass over `nix path-info --json`: each path object has exactly one846// "narSize": field, so counting them gives the true path count and summing the847// values gives the total store size — no per-path closure walk.848fn scanStoreJson(json_str: []const u8) StoreScan {849    const needle = "\"narSize\":";850    var count: u64 = 0;851    var total: u64 = 0;852    var i: usize = 0;853    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {854        var j = pos + needle.len;855        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}856        var val: u64 = 0;857        var any = false;858        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {859            val = val * 10 + (json_str[j] - '0');860            any = true;861        }862        if (any) {863            count += 1;864            total += val;865        }866        i = j;867    }868    return .{ .count = count, .total_bytes = total };869}870871fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {872    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };873    var val: f64 = @floatFromInt(bytes);874    var unit: usize = 0;875    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;876    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });877    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });878}879880pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {881    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the882    // flake registry), not a flake in the current directory.883    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});884    defer gpa.free(expr);885    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });886    defer gpa.free(r.stderr);887    if (r.exit_code != 0) {888        gpa.free(r.stdout);889        return error.ProcessFailed;890    }891    return r.stdout;892}893894// --- Flake ---895896pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {897    if (input) |inp| {898        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });899    }900    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });901}902903// Update flake inputs for the flake living in `dir` (the config dir). `nix flake904// update` operates on the flake in the working directory, so we cd there first.905// Used by `nina upgrade` on a flake system in place of nix-channel --update.906pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {907    return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });908}909910pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {911    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });912}913914pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {915    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });916}917918pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {919    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });920}921922pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {923    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });924}925926pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {927    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });928    defer gpa.free(r.stderr);929    if (r.exit_code != 0) {930        gpa.free(r.stdout);931        return error.ProcessFailed;932    }933    return r.stdout;934}935936// --- Build / Run / Develop ---937938pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {939    if (attr) |a| {940        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});941        defer gpa.free(ref);942        return stream(io, machine, gpa, &.{ "nix", "build", ref });943    }944    return stream(io, machine, gpa, &.{ "nix", "build" });945}946947pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {948    // nix run always gets --no-write-lock-file for remote URLs949    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");950    if (is_url) {951        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });952    }953    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.954    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {955        return stream(io, machine, gpa, &.{ "nix", "run", pkg });956    }957    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});958    defer gpa.free(ref);959    return stream(io, machine, gpa, &.{ "nix", "run", ref });960}961962pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {963    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});964    defer gpa.free(ref);965    return stream(io, machine, gpa, &.{ "nix", "shell", ref });966}967968pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {969    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});970    defer gpa.free(ref);971    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});972    defer gpa.free(ps1);973    if (machine.local) {974        const rc_path = try createInteractiveShellRc(gpa, io);975        defer {976            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};977            gpa.free(rc_path);978        }979        return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref, "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, ps1);980    }981    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);982}983984pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {985    if (run_cmd) |cmd| {986        // sh -c so a multi-word command isn't treated as a single executable name.987        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });988    }989    return stream(io, machine, gpa, &.{ "nix", "develop" });990}991992pub fn nixDevelopPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8, base_env: *const std.process.Environ.Map) !u8 {993    if (run_cmd) |cmd| {994        // sh -c so a multi-word command isn't treated as a single executable name.995        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });996    }997    if (machine.local) {998        const rc_path = try createInteractiveShellRc(gpa, io);999        defer {1000            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1001            gpa.free(rc_path);1002        }1003        return streamEnv(io, machine, gpa, &.{ "nix", "develop", "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, "(nina: dev) -> ");1004    }1005    return streamEnv(io, machine, gpa, &.{ "nix", "develop" }, base_env, "(nina: dev) -> ");1006}10071008pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1009    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });1010}10111012// --- Format ---10131014pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {1015    if (check) {1016        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });1017    }1018    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });1019}10201021// --- Info ---10221023pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1024    const r = try capture(gpa, io, machine, &.{"nixos-version"});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}10321033pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1034    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });1035    defer gpa.free(r.stderr);1036    if (r.exit_code != 0) {1037        gpa.free(r.stdout);1038        return error.ProcessFailed;1039    }1040    return r.stdout;1041}10421043pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1044    const r = try capture(gpa, io, machine, &.{"uptime"});1045    defer gpa.free(r.stderr);1046    if (r.exit_code != 0) {1047        gpa.free(r.stdout);1048        return error.ProcessFailed;1049    }1050    return r.stdout;1051}10521053// --- Boot ---10541055pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {1056    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });1057    defer gpa.free(r.stderr);1058    defer gpa.free(r.stdout);1059    if (r.exit_code != 0) return error.ProcessFailed;1060    return parseBootEntries(gpa, r.stdout);1061}10621063fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {1064    var entries: std.ArrayList(types.BootEntry) = .empty;1065    var lines = std.mem.splitScalar(u8, output_str, '\n');1066    while (lines.next()) |line| {1067        const trimmed = std.mem.trim(u8, line, " \t\r");1068        if (std.mem.startsWith(u8, trimmed, "title:")) {1069            const title = std.mem.trim(u8, trimmed[6..], " \t");1070            const current = std.mem.indexOf(u8, title, "(current)") != null;1071            try entries.append(gpa, .{1072                .title = try gpa.dupe(u8, title),1073                .current = current,1074            });1075        }1076    }1077    return entries.toOwnedSlice(gpa);1078}10791080// --- Pkg info ---10811082fn pkgInstallable(gpa: std.mem.Allocator, pkg: []const u8) ![]u8 {1083    return std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1084}10851086fn resolvePkgStorePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, installable: []const u8) ![]u8 {1087    const r = try capture(gpa, io, machine, &.{ "nix", "build", "--no-link", "--print-out-paths", installable });1088    defer gpa.free(r.stderr);1089    defer gpa.free(r.stdout);1090    if (r.exit_code != 0) return error.PackageNotFound;10911092    var lines = std.mem.tokenizeAny(u8, r.stdout, "\r\n");1093    const first_path = lines.next() orelse return error.PackageNotFound;1094    const store_path = std.mem.trim(u8, first_path, " \t");1095    if (store_path.len == 0) return error.PackageNotFound;1096    return gpa.dupe(u8, store_path);1097}10981099pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1100    const installable = try pkgInstallable(gpa, pkg);1101    defer gpa.free(installable);1102    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1103    defer gpa.free(store_path);1104    return stream(io, machine, gpa, &.{ "nix", "why-depends", "/run/current-system", store_path });1105}11061107pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1108    const installable = try pkgInstallable(gpa, pkg);1109    defer gpa.free(installable);1110    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1111    defer gpa.free(store_path);1112    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", store_path });1113}11141115pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {1116    const installable = try pkgInstallable(gpa, pkg);1117    defer gpa.free(installable);1118    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", "--json", installable });1119    defer gpa.free(r.stderr);1120    defer gpa.free(r.stdout);1121    if (r.exit_code != 0) return error.ProcessFailed;11221123    const nar_size = try pathInfoNarSize(gpa, r.stdout);1124    return humanPkgSize(gpa, nar_size);1125}11261127pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1128    const installable = try pkgInstallable(gpa, pkg);1129    defer gpa.free(installable);1130    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1131    defer gpa.free(store_path);1132    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", store_path });1133}11341135fn pathInfoNarSize(gpa: std.mem.Allocator, json_str: []const u8) !u64 {1136    var parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.ProcessFailed;1137    defer parsed.deinit();1138    switch (parsed.value) {1139        .object => |obj| {1140            var it = obj.iterator();1141            while (it.next()) |entry| {1142                if (entry.value_ptr.* == .object) {1143                    if (entry.value_ptr.object.get("narSize")) |v| {1144                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1145                    }1146                }1147            }1148        },1149        .array => |arr| {1150            for (arr.items) |item| {1151                if (item == .object) {1152                    if (item.object.get("narSize")) |v| {1153                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1154                    }1155                }1156            }1157        },1158        else => {},1159    }1160    return error.ProcessFailed;1161}11621163fn humanPkgSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1164    const units = [_][]const u8{ "B", "KiB", "MiB", "GiB", "TiB" };1165    var val: f64 = @floatFromInt(bytes);1166    var unit: usize = 0;1167    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1168    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1169    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1170}11711172test "pathInfoNarSize parses object and array shapes" {1173    try std.testing.expectEqual(@as(u64, 1064629862), try pathInfoNarSize(std.testing.allocator,1174        \\{"/nix/store/abc-ffmpeg":{"narSize":1064629862}}1175    ));1176    try std.testing.expectEqual(@as(u64, 2048), try pathInfoNarSize(std.testing.allocator,1177        \\[{"path":"/nix/store/abc-pkg","narSize":2048}]1178    ));1179}11801181// --- Hash / Fetch ---11821183pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {1184    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });1185    defer gpa.free(r.stderr);1186    if (r.exit_code != 0) {1187        gpa.free(r.stdout);1188        return error.ProcessFailed;1189    }1190    return r.stdout;1191}11921193pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {1194    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });1195    defer gpa.free(r.stderr);1196    if (r.exit_code != 0) {1197        gpa.free(r.stdout);1198        return error.ProcessFailed;1199    }1200    return r.stdout;1201}12021203// --- Pin ---12041205pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {1206    // Stub: full implementation would parse and edit flake.lock JSON1207    // The pin/unpin flow works via nix flake update which regenerates flake.lock1208}12091210pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {1211    if (line) |l| {1212        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});1213        defer gpa.free(line_arg);1214        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });1215    }1216    return stream(io, &types.Machine{}, gpa, &.{ editor, path });1217}12181219pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {1220    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});1221    defer gpa.free(a_str);1222    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});1223    defer gpa.free(b_str);1224    // On a tty, the child's own color is fine — stream it directly.1225    if (output.colorEnabled()) {1226        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });1227    }1228    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,1229    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.1230    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });1231    defer gpa.free(r.stdout);1232    defer gpa.free(r.stderr);1233    const cleaned = try stripAnsi(gpa, r.stdout);1234    defer gpa.free(cleaned);1235    output.raw(cleaned);1236    return r.exit_code;1237}12381239// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a1240// child process's color when it writes ANSI unconditionally.1241fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1242    var out: std.ArrayList(u8) = .empty;1243    errdefer out.deinit(gpa);1244    var i: usize = 0;1245    while (i < input.len) {1246        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1247            i += 2;1248            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1249            if (i < input.len) i += 1; // consume the final byte1250            continue;1251        }1252        try out.append(gpa, input[i]);1253        i += 1;1254    }1255    return out.toOwnedSlice(gpa);1256}12571258test "stripAnsi removes CSI color sequences" {1259    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1260    defer std.testing.allocator.free(cleaned);1261    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1262}12631264// --- Doctor checks ---12651266pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1267    var checks: std.ArrayList(types.DoctorCheck) = .empty;12681269    // Check nix daemon1270    {1271        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1272        defer gpa.free(r.stdout);1273        defer gpa.free(r.stderr);1274        const active = std.mem.indexOf(u8, r.stdout, "active") != null;1275        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1276    }12771278    // Check config syntax. Flake-aware like apply/upgrade: on a flake system a1279    // plain `nixos-rebuild dry-build` evaluates <nixpkgs/nixos> + <nixos-config>1280    // (channel style) and fails, so pass --flake when the config dir has one.1281    {1282        const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1283            &.{ "sudo", "nixos-rebuild", "dry-build", "--flake", machine.config_path }1284        else1285            &.{ "sudo", "nixos-rebuild", "dry-build" };1286        const r = try capture(gpa, io, machine, argv);1287        defer gpa.free(r.stdout);1288        defer gpa.free(r.stderr);1289        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1290    }12911292    // Check channel1293    {1294        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1295        defer gpa.free(r.stdout);1296        defer gpa.free(r.stderr);1297        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1298        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1299    }13001301    return checks.toOwnedSlice(gpa);1302}13031304// --- Home Manager ---1305//1306// Home Manager has three usage modes. nina detects which one is in play before1307// any `home` command so it can either drive the standalone CLI or redirect the1308// user to `nina apply` (when HM is a NixOS/flake module activated by rebuild).13091310pub const HomeManagerMode = enum {1311    // home-manager binary on PATH — manages the user env on its own.1312    standalone,1313    // No binary, but a home.nix exists — HM is a NixOS/flake module rebuilt by1314    // nixos-rebuild. `nina home apply` redirects to `nina apply`.1315    module,1316    none,1317};13181319fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1320    const home = environ.get("HOME") orelse return null;1321    return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1322}13231324// Path to the standalone home.nix. Caller frees.1325pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1326    const dir = homeConfigDir(gpa, environ) orelse return null;1327    defer gpa.free(dir);1328    return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1329}13301331pub fn pathExists(io: std.Io, path: []const u8) bool {1332    const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1333    f.close(io);1334    return true;1335}13361337// `command -v <name>` — true if the binary resolves on PATH. Silent (captured),1338// unlike streamLocal which would inherit stdio.1339fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1340    var buf: [256]u8 = undefined;1341    const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1342    const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1343    defer gpa.free(r.stdout);1344    defer gpa.free(r.stderr);1345    return switch (r.term) {1346        .exited => |code| code == 0,1347        else => false,1348    };1349}13501351pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1352    if (commandExists(gpa, io, "home-manager")) return .standalone;1353    if (homeNixPath(gpa, environ)) |p| {1354        defer gpa.free(p);1355        if (pathExists(io, p)) return .module;1356    }1357    return .none;1358}13591360// If the home-manager config dir holds a flake.nix, returns the flake ref1361// "<dir>#<user>" for `home-manager switch --flake`. Username comes from $USER.1362// Caller frees. null when there's no flake.nix (channel-based home config).1363pub fn homeFlakeRef(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1364    const dir = homeConfigDir(gpa, environ) orelse return null;1365    defer gpa.free(dir);1366    const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch return null;1367    defer gpa.free(flake);1368    if (!pathExists(io, flake)) return null;1369    const user = environ.get("USER") orelse "default";1370    return std.fmt.allocPrint(gpa, "{s}#{s}", .{ dir, user }) catch null;1371}13721373pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1374    return stream(io, machine, gpa, &.{ "home-manager", "switch" });1375}13761377pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8) !u8 {1378    return stream(io, machine, gpa, &.{ "home-manager", "switch", "--flake", flake_ref });1379}13801381// home-manager has no system-profile rollback; it re-activates the previous1382// generation via `switch --rollback`.1383pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1384    return stream(io, machine, gpa, &.{ "home-manager", "switch", "--rollback" });1385}13861387// Build (and validate) the home config without activating it — used by `home1388// check` and `home apply --dry`. `home-manager build` drops a ./result symlink1389// in the cwd, so run it in a throwaway temp dir to avoid littering the directory1390// nina was invoked from.1391pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1392    return stream(io, machine, gpa, &.{ "sh", "-c", "d=$(mktemp -d) && cd \"$d\" && home-manager build" });1393}13941395pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1396    const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1397    defer gpa.free(r.stderr);1398    if (r.exit_code != 0) {1399        gpa.free(r.stdout);1400        return error.ProcessFailed;1401    }1402    return r.stdout;1403}14041405// Store paths referenced by a home generation — used to list managed packages.1406pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1407    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1408    defer gpa.free(r.stderr);1409    if (r.exit_code != 0) {1410        gpa.free(r.stdout);1411        return error.ProcessFailed;1412    }1413    return r.stdout;1414}14151416// diff-closures between two arbitrary store paths (home generations), mirroring1417// diffClosures' tty/piped color handling.1418pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1419    if (output.colorEnabled()) {1420        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1421    }1422    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1423    defer gpa.free(r.stdout);1424    defer gpa.free(r.stderr);1425    const cleaned = try stripAnsi(gpa, r.stdout);1426    defer gpa.free(cleaned);1427    output.raw(cleaned);1428    return r.exit_code;1429}14301431// --- Log ---14321433pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1434    const home = environ.get("HOME") orelse return error.FileNotFound;1435    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1436    defer gpa.free(path);1437    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1438    if (last == 0) return content;14391440    // Collect non-empty lines, then keep only the final `last`. Slices point into1441    // `content`, so copy them out before freeing it.1442    var lines: std.ArrayList([]const u8) = .empty;1443    defer lines.deinit(gpa);1444    var it = std.mem.splitScalar(u8, content, '\n');1445    while (it.next()) |line| {1446        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1447        try lines.append(gpa, line);1448    }1449    if (lines.items.len <= last) return content;14501451    var out: std.ArrayList(u8) = .empty;1452    errdefer out.deinit(gpa);1453    for (lines.items[lines.items.len - last ..]) |line| {1454        try out.appendSlice(gpa, line);1455        try out.append(gpa, '\n');1456    }1457    gpa.free(content);1458    return out.toOwnedSlice(gpa);1459}14601461// nina is a one-shot process, so "did the last apply fail this session?" can't1462// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1463// other ~/.nina-* state files. This lets a later successful apply earn the1464// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1465pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1466    const home = environ.get("HOME") orelse return;1467    var buf: [512]u8 = undefined;1468    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1469    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1470    file.close(io);1471}14721473pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1474    const home = environ.get("HOME") orelse return false;1475    var buf: [512]u8 = undefined;1476    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1477    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1478        f.close(io);1479        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1480        return true;1481    } else |_| {1482        return false;1483    }1484}14851486pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1487    const home = environ.get("HOME") orelse return;1488    var path_buf: [512]u8 = undefined;1489    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1490    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1491        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1492    defer file.close(io);1493    const size = file.length(io) catch 0;1494    file.writePositionalAll(io, entry, size) catch {};1495}14961497// --- Update helpers ---14981499// Fetch a URL with curl and return the response body. Caller must free.1500// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.1501pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1502    const argv = [_][]const u8{1503        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1504    };1505    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1506    defer gpa.free(result.stderr);15071508    const marker = "\nHTTP_STATUS:";1509    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1510        gpa.free(result.stdout);1511        return error.NetworkError;1512    };1513    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1514    const status = std.fmt.parseInt(u16, status_str, 10) catch {1515        gpa.free(result.stdout);1516        return error.NetworkError;1517    };1518    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1519    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1520    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1521        gpa.free(result.stdout);1522        return e;1523    };1524    gpa.free(result.stdout);1525    return body;1526}15271528// Download a URL to a temp file. Returns the temp path (caller must gpa.free).1529// The file is written to /tmp/nina-update-<pid> and left for the caller to use.1530pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1531    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1532    errdefer gpa.free(tmp_path);15331534    var child = std.process.spawn(io, .{1535        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1536        .stdin = .close,1537        .stdout = .close,1538        .stderr = .inherit,1539    }) catch return error.NetworkError;1540    const term = child.wait(io) catch return error.NetworkError;1541    switch (term) {1542        .exited => |c| if (c != 0) return error.NetworkError,1543        else => return error.NetworkError,1544    }1545    return tmp_path;1546}15471548// Get the current executable path into buf. Returns slice of buf.1549pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1550    const len = try std.process.executablePath(io, buf);1551    return buf[0..len];1552}15531554// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1555// atomically install the binary to install_path. Errors: ChecksumMismatch,1556// AccessDenied (with error_info set), or underlying I/O errors.1557pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1558    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1559        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1560        return error.FileNotFound;1561    };1562    defer gpa.free(bytes);15631564    var hasher = std.crypto.hash.Blake3.init(.{});1565    hasher.update(bytes);1566    var raw: [32]u8 = undefined;1567    hasher.final(&raw);1568    const hex = std.fmt.bytesToHex(raw, .lower);1569    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;15701571    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1572    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1573        return error.NameTooLong;15741575    {1576        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1577            errors.error_info.setMessage("cannot write to {s}", .{install_path});1578            errors.error_info.setSuggestion("try: sudo nina update", .{});1579            return error.AccessDenied;1580        };1581        defer f.close(io);1582        f.writePositionalAll(io, bytes, 0) catch {1583            errors.error_info.setMessage("cannot write to {s}", .{install_path});1584            return error.AccessDenied;1585        };1586        try f.setPermissions(io, .fromMode(0o755));1587    }1588    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};15891590    if (comptime builtin.os.tag == .macos) {1591        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1592    }15931594    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1595        error.AccessDenied => {1596            errors.error_info.setMessage("cannot replace {s}", .{install_path});1597            errors.error_info.setSuggestion("try: sudo nina update", .{});1598            return error.AccessDenied;1599        },1600        else => return e,1601    };1602}16031604// --- Nix feature setup ---16051606pub const NixFeatureStatus = struct {1607    nix_command: bool = false,1608    flakes: bool = false,16091610    pub fn allEnabled(self: NixFeatureStatus) bool {1611        return self.nix_command and self.flakes;1612    }1613};16141615fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1616    var lines = std.mem.splitScalar(u8, conf, '\n');1617    while (lines.next()) |line| {1618        const trimmed = std.mem.trim(u8, line, " \t");1619        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1620        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1621        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1622    }1623}16241625pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1626    var status = NixFeatureStatus{};16271628    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1629        defer gpa.free(conf);1630        scanConfFeatures(conf, &status);1631    }16321633    if (environ.get("HOME")) |home| {1634        var buf: [512]u8 = undefined;1635        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1636        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1637            defer gpa.free(conf);1638            scanConfFeatures(conf, &status);1639        }1640    }16411642    return status;1643}16441645pub fn isNixOS(io: std.Io) bool {1646    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1647    file.close(io);1648    return true;1649}16501651// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.1652// Returns the path written (caller must free).1653pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1654    const home = environ.get("HOME") orelse {1655        errors.error_info.setMessage("HOME not set", .{});1656        return error.ConfigNotFound;1657    };16581659    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1660    defer gpa.free(dir_path);1661    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1662    errdefer gpa.free(file_path);16631664    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};16651666    const line = "experimental-features = nix-command flakes\n";1667    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1668        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1669        errors.error_info.setMessage("could not write {s}", .{file_path});1670        return error.FileNotFound;1671    });1672    defer file.close(io);16731674    const size = file.length(io) catch 0;1675    file.writePositionalAll(io, line, size) catch {1676        errors.error_info.setMessage("could not write {s}", .{file_path});1677        return error.FileNotFound;1678    };16791680    return file_path;1681}16821683// --- NixOS: declarative experimental-features ---1684//1685// On NixOS the permanent, declarative home for these flags is configuration.nix,1686// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves1687// the `nixos-rebuild switch` to the user.16881689pub const NIXOS_FEATURES_LINE =1690    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";16911692// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns1693// false on any read error so the caller still offers to add the line.1694pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1695    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1696    defer gpa.free(conf);1697    return std.mem.indexOf(u8, conf, "experimental-features") != null and1698        std.mem.indexOf(u8, conf, "nix-command") != null and1699        std.mem.indexOf(u8, conf, "flakes") != null;1700}17011702fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1703    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1704    return captureLocal(gpa, io, &.{ "sudo", "cat", path });1705}17061707// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix1708// (i.e. inside the top-level attribute set) and write it back via a single1709// `sudo cp`, which prompts for the password on the terminal. Returns an error1710// for the caller to fall back to printed manual instructions.1711pub fn appendFeaturesToNixosConfig(1712    gpa: std.mem.Allocator,1713    io: std.Io,1714    environ: *const std.process.Environ.Map,1715    path: []const u8,1716) !void {1717    const conf = readMaybeSudo(gpa, io, path) catch {1718        errors.error_info.setMessage("could not read {s}", .{path});1719        return error.ConfigNotFound;1720    };1721    defer gpa.free(conf);17221723    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared17241725    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1726        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1727        return error.MalformedConfig;1728    };17291730    const home = environ.get("HOME") orelse {1731        errors.error_info.setMessage("HOME not set", .{});1732        return error.ConfigNotFound;1733    };1734    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1735    defer gpa.free(tmp_path);17361737    var buf: std.ArrayList(u8) = .empty;1738    defer buf.deinit(gpa);1739    try buf.appendSlice(gpa, conf[0..brace]);1740    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1741    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");1742    try buf.appendSlice(gpa, "  ");1743    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1744    try buf.append(gpa, '\n');1745    try buf.appendSlice(gpa, conf[brace..]);17461747    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1748        errors.error_info.setMessage("could not write {s}", .{tmp_path});1749        return error.FileNotFound;1750    };1751    tmp.writePositionalAll(io, buf.items, 0) catch {1752        tmp.close(io);1753        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1754        errors.error_info.setMessage("could not write {s}", .{tmp_path});1755        return error.FileNotFound;1756    };1757    tmp.close(io);17581759    // Back up the existing config, then replace it — in one sudo call so the1760    // password is asked for at most once. Paths travel as positional args ($0,1761    // $1) to sidestep shell quoting.1762    const code = streamLocal(io, &.{1763        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1764    }) catch {1765        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1766        errors.error_info.setMessage("could not write {s}", .{path});1767        return error.ProcessFailed;1768    };1769    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1770    if (code != 0) {1771        errors.error_info.setMessage("sudo cp into {s} failed", .{path});1772        return error.ProcessFailed;1773    }1774}