exec.zig

68.9 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};1819// Run a process and capture stdout+stderr (not streaming).20pub fn capture(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, cmd: []const []const u8) !RunResult {21    const argv = try buildArgv(gpa, machine, cmd);22    defer if (!machine.local) gpa.free(argv);2324    const result = std.process.run(gpa, io, .{ .argv = argv }) catch |e| {25        errors.error_info.setMessage("process failed: {s}", .{cmd[0]});26        return e;27    };2829    return .{30        .stdout = result.stdout,31        .stderr = result.stderr,32        .exit_code = switch (result.term) {33            .exited => |c| c,34            else => 1,35        },36    };37}3839// Run a process and stream its output to the terminal (inherit stdio).40pub fn stream(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8) !u8 {41    // The child inherits stdout and writes directly to the fd; flush any buffered42    // nina header first so it isn't reordered after the child's output.43    output.flush();44    const argv = try buildArgv(gpa, machine, cmd);45    defer if (!machine.local) gpa.free(argv);4647    var child = std.process.spawn(io, .{48        .argv = argv,49        .stdin = .inherit,50        .stdout = .inherit,51        .stderr = .inherit,52    }) catch |e| {53        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});54        return e;55    };5657    const term = child.wait(io) catch |e| {58        errors.error_info.setMessage("process wait failed", .{});59        return e;60    };6162    return switch (term) {63        .exited => |c| c,64        else => 1,65    };66}6768// Stream a process with an overridden PS1 in the child environment.69fn 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 {70    output.flush();71    const argv = try buildArgv(gpa, machine, cmd);72    defer if (!machine.local) gpa.free(argv);7374    var env = try base_env.clone(gpa);75    defer env.deinit();76    try env.put("PS1", ps1);77    try env.put("NINA_PS1", ps1);7879    var child = std.process.spawn(io, .{80        .argv = argv,81        .stdin = .inherit,82        .stdout = .inherit,83        .stderr = .inherit,84        .environ_map = &env,85    }) catch |e| {86        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});87        return e;88    };8990    const term = child.wait(io) catch |e| {91        errors.error_info.setMessage("process wait failed", .{});92        return e;93    };9495    return switch (term) {96        .exited => |c| c,97        else => 1,98    };99}100101fn createInteractiveShellRc(gpa: std.mem.Allocator, io: std.Io) ![]u8 {102    const out = try captureLocal(gpa, io, &.{ "mktemp", "/tmp/nina-shell-rc.XXXXXX" });103    defer gpa.free(out);104105    const path = std.mem.trim(u8, out, " \t\r\n");106    if (path.len == 0) return error.FileNotFound;107    const owned_path = try gpa.dupe(u8, path);108    errdefer gpa.free(owned_path);109110    const file = std.Io.Dir.createFile(.cwd(), io, owned_path, .{}) catch {111        errors.error_info.setMessage("could not write shell prompt setup", .{});112        return error.FileNotFound;113    };114    errdefer file.close(io);115116    const content =117        \\PS1="${NINA_PS1:-$PS1}"118        \\trap 'exit 130' INT119        \\120    ;121    file.writePositionalAll(io, content, 0) catch {122        errors.error_info.setMessage("could not write shell prompt setup", .{});123        return error.FileNotFound;124    };125    file.close(io);126127    return owned_path;128}129130// Stream a local process with inherited stdio (no SSH routing — for nix commands).131pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 {132    output.flush();133    var child = std.process.spawn(io, .{134        .argv = cmd,135        .stdin = .inherit,136        .stdout = .inherit,137        .stderr = .inherit,138    }) catch |e| {139        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});140        return e;141    };142    const term = child.wait(io) catch {143        errors.error_info.setMessage("process wait failed", .{});144        return error.ProcessFailed;145    };146    return switch (term) {147        .exited => |c| c,148        else => 1,149    };150}151152// Run a process and capture output as a single string (no SSH routing — for local nix commands).153pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {154    const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;155    defer gpa.free(result.stderr);156    switch (result.term) {157        .exited => |c| if (c != 0) {158            gpa.free(result.stdout);159            return error.ProcessFailed;160        },161        else => {162            gpa.free(result.stdout);163            return error.ProcessFailed;164        },165    }166    return result.stdout;167}168169// Create a directory and its parents, best-effort. Shelling out to `mkdir -p`170// matches how the rest of exec.zig provisions config locations (~/.config/nix).171pub fn ensureDir(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) void {172    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir }) catch {};173}174175fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {176    if (machine.local) return cmd;177178    const host = machine.host orelse {179        errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});180        return error.SshFailed;181    };182183    var ssh: std.ArrayList([]const u8) = .empty;184    try ssh.append(gpa, "ssh");185    try ssh.append(gpa, "-o");186    try ssh.append(gpa, "BatchMode=yes");187    try ssh.append(gpa, "-o");188    try ssh.append(gpa, "StrictHostKeyChecking=accept-new");189    if (machine.ssh_key) |key| {190        try ssh.append(gpa, "-i");191        try ssh.append(gpa, key);192    }193    const addr = if (machine.user) |u|194        try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })195    else196        try gpa.dupe(u8, host);197    try ssh.append(gpa, addr);198    for (cmd) |arg| try ssh.append(gpa, arg);199    return ssh.toOwnedSlice(gpa);200}201202// --- NixOS rebuild ---203204// True if the machine's config dir holds a flake.nix. Only meaningful for a local205// machine — the file lives on the local filesystem. Remote flake detection would206// need an ssh round-trip; a remote flake at the default /etc/nixos needs no flag207// anyway, so we don't bother.208// True if `dir` contains a flake.nix (local filesystem check).209pub fn dirHasFlake(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) bool {210    const flake_path = std.fs.path.join(gpa, &.{ dir, "flake.nix" }) catch return false;211    defer gpa.free(flake_path);212    return pathExists(io, flake_path);213}214215pub fn configHasFlake(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {216    if (!machine.local) return false;217    return dirHasFlake(gpa, io, machine.config_path);218}219220// nixos-rebuild auto-detects /etc/nixos/flake.nix, so the --flake flag is only221// needed when the flake lives elsewhere. A flake at a non-default path must be222// passed explicitly or nixos-rebuild falls back to channels. Compare with223// trailing slashes trimmed so "/etc/nixos/" is still treated as the default.224fn useFlakeFlag(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {225    if (!configHasFlake(gpa, io, machine)) return false;226    var path = machine.config_path;227    while (path.len > 1 and path[path.len - 1] == '/') path = path[0 .. path.len - 1];228    return !std.mem.eql(u8, path, "/etc/nixos");229}230231fn nixosRebuildRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, flake: bool) !u8 {232    if (flake) {233        return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb, "--flake", machine.config_path });234    }235    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb });236}237238pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {239    const flake = useFlakeFlag(gpa, io, machine);240    if (flake) {241        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});242    } else {243        output.printSubstep("nixos-rebuild switch", .{});244    }245    return nixosRebuildRun(io, machine, gpa, "switch", flake);246}247248pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {249    return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine));250}251252pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {253    return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine));254}255256// --- Generations ---257258// Read system-profile generations WITHOUT root. `nix-env --list-generations -p259// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user260// ("system.lock: Permission denied"). The generation symlinks themselves are261// world-readable, so list them directly: parse `system-N-link` names, take each262// link's own mtime for the date/time, and mark the one the `system` symlink263// points at as current. Output matches the `nix-env --list-generations` columns264// (num date time [current]) so parseGenerations is unchanged.265const GEN_LIST_SCRIPT =266    \\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 }'267;268269pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {270    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });271    defer gpa.free(r.stderr);272    defer gpa.free(r.stdout);273    if (r.exit_code != 0) return error.ProcessFailed;274    return parseGenerations(gpa, r.stdout);275}276277fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {278    var gens: std.ArrayList(types.GenerationInfo) = .empty;279    var lines = std.mem.splitScalar(u8, output_str, '\n');280    while (lines.next()) |line| {281        const trimmed = std.mem.trim(u8, line, " \t");282        if (trimmed.len == 0) continue;283        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");284        const num_str = parts.next() orelse continue;285        const date_str = parts.next() orelse continue;286        const time_str = parts.next() orelse continue;287        const rest = parts.rest();288        const current = std.mem.indexOf(u8, rest, "current") != null;289        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;290        try gens.append(gpa, .{291            .number = num,292            .date = try gpa.dupe(u8, date_str),293            .time = try gpa.dupe(u8, time_str),294            .current = current,295        });296    }297    return gens.toOwnedSlice(gpa);298}299300pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {301    const gens = try getGenerations(gpa, io, machine);302    defer gpa.free(gens);303    for (gens) |g| {304        if (g.current) return g.number;305    }306    return 0;307}308309pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {310    // Switch the system profile to generation n, then activate it (bootloader +311    // services). Without switch-to-configuration the change isn't applied.312    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 });313    defer gpa.free(cmd);314    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });315}316317pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {318    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });319}320321pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {322    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});323    defer gpa.free(n_str);324    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });325}326327pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {328    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });329}330331// --- Garbage collection ---332333pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {334    if (delete_old) {335        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });336    }337    // Keep the `keep` most recent system generations (+N deletes all but N),338    // then collect now-unreferenced store paths. `--delete-older-than` wants a339    // duration (e.g. 14d), not a generation count.340    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });341    defer gpa.free(cmd);342    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });343}344345// --- Channels ---346347pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {348    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });349    defer gpa.free(r.stderr);350    defer gpa.free(r.stdout);351    if (r.exit_code != 0) return error.ProcessFailed;352    return parseChannels(gpa, r.stdout);353}354355fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {356    var channels: std.ArrayList(types.ChannelInfo) = .empty;357    var lines = std.mem.splitScalar(u8, output_str, '\n');358    while (lines.next()) |line| {359        const trimmed = std.mem.trim(u8, line, " \t\r");360        if (trimmed.len == 0) continue;361        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;362        try channels.append(gpa, .{363            .name = try gpa.dupe(u8, trimmed[0..space]),364            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),365        });366    }367    return channels.toOwnedSlice(gpa);368}369370pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {371    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });372}373374pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {375    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });376}377378pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {379    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });380}381382// --- Services ---383384pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {385    const cmd: []const []const u8 = if (user)386        &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }387    else388        &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };389    const r = try capture(gpa, io, machine, cmd);390    defer gpa.free(r.stderr);391    defer gpa.free(r.stdout);392    if (r.exit_code != 0) return error.ProcessFailed;393    return parseServices(gpa, r.stdout);394}395396fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {397    var svcs: std.ArrayList(types.ServiceInfo) = .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\r");401        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines402        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");403        const name = parts.next() orelse continue;404        _ = parts.next(); // load405        const active_str = parts.next() orelse continue;406        const sub_str = parts.next() orelse "unknown";407408        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))409            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)410        else if (std.mem.eql(u8, active_str, "failed"))411            .failed412        else413            .inactive;414415        try svcs.append(gpa, .{416            .name = try gpa.dupe(u8, name),417            .state = state,418            .uptime = null,419        });420    }421    return svcs.toOwnedSlice(gpa);422}423424pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {425    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.426    // User services run under the caller's own systemd manager, so no sudo.427    if (user) {428        return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });429    }430    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });431}432433pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {434    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});435    defer gpa.free(n_str);436    if (user) {437        if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });438        return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });439    }440    if (follow) {441        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });442    }443    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });444}445446// --- Profile ---447448pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {449    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});450    defer gpa.free(pkg_ref);451    // `nix profile add` is the current verb; `install` is a deprecated alias that452    // prints a warning on modern nix.453    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });454}455456pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {457    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not458    // by flake ref — passing nixpkgs#ripgrep matches nothing.459    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });460}461462pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {463    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });464    defer gpa.free(r.stderr);465    if (r.exit_code != 0) return error.ProcessFailed;466    return r.stdout;467}468469// Machine-readable profile listing — caller parses elements -> name + version.470pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {471    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });472    defer gpa.free(r.stderr);473    if (r.exit_code != 0) {474        gpa.free(r.stdout);475        return error.ProcessFailed;476    }477    return r.stdout;478}479480// Returns the profile element name to pass to `nix profile remove/upgrade`481// (e.g. "nina" or "default"), or null if nina is not found. Caller owns the482// returned slice. A NixOS system-package install also resolves into /nix/store483// so the store path alone can't distinguish it from a profile install — the484// profile list can. A missing/empty profile (or no nix) returns null.485pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {486    const js = profileListJson(gpa, io, machine) catch return null;487    defer gpa.free(js);488    return profileJsonNinaElement(gpa, js);489}490491pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {492    const name = profileNinaElement(gpa, io, machine) orelse return false;493    gpa.free(name);494    return true;495}496497// True when a nix store path belongs to the nina package. Store paths have the498// form /nix/store/<32-char-hash>-<pname>-<version>[/<subpath>]. We check that499// the 33 chars after /nix/store/ are the hash+dash, and the pname that follows500// is exactly "nina" (followed by "-" or end-of-component).501fn storePathIsNina(path: []const u8) bool {502    const prefix = "/nix/store/";503    if (!std.mem.startsWith(u8, path, prefix)) return false;504    const rel = path[prefix.len..];505    // The store entry name ends at the first "/" (if any sub-path follows).506    const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];507    if (entry.len < 34) return false; // 32-char hash + dash + at least one char508    const pname_ver = entry[33..]; // skip hash + dash509    return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");510}511512// Pure parse of `nix profile list --json` for a nina element, returning its513// element name (the key to pass to `nix profile remove/upgrade`) or null.514// Newer nix (2.18+) keys elements by pname ("nina"). Older nix uses an array515// with an "attrPath" field. Tarball installs via the `default` output may use516// the key "default" instead of "nina"; we detect those via storePaths.517fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {518    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;519    defer parsed.deinit();520    const root = parsed.value;521    if (root != .object) return null;522    const elements = root.object.get("elements") orelse return null;523    switch (elements) {524        .object => |obj| {525            // Fast path: exact "nina" key (nix 2.18+ with nixpkgs#nina install).526            if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;527            // Fallback: scan storePaths. Handles tarball installs where the default528            // output is selected and nix names the element "default" (older nix) or529            // some other key derived from the attrPath rather than the pname.530            var it = obj.iterator();531            while (it.next()) |kv| {532                const val = kv.value_ptr.*;533                if (val != .object) continue;534                const sps = val.object.get("storePaths") orelse continue;535                if (sps != .array) continue;536                for (sps.array.items) |sp| {537                    if (sp == .string and storePathIsNina(sp.string))538                        return gpa.dupe(u8, kv.key_ptr.*) catch null;539                }540            }541            return null;542        },543        .array => |arr| {544            // Older nix array format. Element name is the last component of attrPath.545            for (arr.items) |el| {546                if (el != .object) continue;547                const ap = el.object.get("attrPath") orelse continue;548                if (ap != .string) continue;549                if (std.mem.eql(u8, ap.string, "nina") or550                    std.mem.endsWith(u8, ap.string, ".nina"))551                    return gpa.dupe(u8, "nina") catch null;552                // Tarball default-output install: attrPath ends in ".default" but553                // storePaths point to nina. Return "default" as the element name.554                const sps = el.object.get("storePaths") orelse continue;555                if (sps != .array) continue;556                for (sps.array.items) |sp| {557                    if (sp != .string) continue;558                    if (!storePathIsNina(sp.string)) continue;559                    const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;560                    const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;561                    return gpa.dupe(u8, el_name) catch null;562                }563            }564            return null;565        },566        else => return null,567    }568}569570test "profileJsonNinaElement finds element name from profile JSON" {571    const a = std.testing.allocator;572573    // Newer nix: elements keyed by pname. "nina" key present.574    const named =575        \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},576        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}577    ;578    const r1 = profileJsonNinaElement(a, named);579    defer if (r1) |n| a.free(n);580    try std.testing.expectEqualStrings("nina", r1.?);581582    // Tarball install via default output: element keyed as "default", storePath is nina.583    const default_key =584        \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}585    ;586    const r2 = profileJsonNinaElement(a, default_key);587    defer if (r2) |n| a.free(n);588    try std.testing.expectEqualStrings("default", r2.?);589590    // Decoy: storePath of another package contains "nina" as a substring but is not nina.591    const decoy =592        \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}593    ;594    const r3 = profileJsonNinaElement(a, decoy);595    try std.testing.expectEqual(@as(?[]const u8, null), r3);596597    // Older nix array schema, attrPath ending in ".nina".598    const arr =599        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}600    ;601    const r4 = profileJsonNinaElement(a, arr);602    defer if (r4) |n| a.free(n);603    try std.testing.expectEqualStrings("nina", r4.?);604605    // Older nix array schema, tarball default-output install.606    const arr_default =607        \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}608    ;609    const r5 = profileJsonNinaElement(a, arr_default);610    defer if (r5) |n| a.free(n);611    try std.testing.expectEqualStrings("default", r5.?);612613    // Empty / malformed → null.614    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));615    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));616}617618// The store paths that make up the running system environment. Each reference is619// a <hash>-<name>-<version> path, so the caller can list system packages with620// versions — there is no cleaner per-package list for environment.systemPackages.621pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {622    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });623    defer gpa.free(r.stderr);624    if (r.exit_code != 0) {625        gpa.free(r.stdout);626        return error.ProcessFailed;627    }628    return r.stdout;629}630631pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {632    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });633}634635// --- Store ---636637pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {638    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });639}640641pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {642    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });643}644645pub const SystemStatus = struct { size: []u8, age: []u8 };646647// One read-only pass for `nina status`: the current system's closure size (a648// single `path-info -S` of /run/current-system — fast, unlike -S over the whole649// store) and seconds since the system profile was last switched (its symlink650// mtime). Both are world-readable; no root needed.651const STATUS_SCRIPT =652    \\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} ))"653;654655pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {656    const unknown = SystemStatus{657        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },658        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },659    };660    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;661    defer gpa.free(r.stdout);662    defer gpa.free(r.stderr);663    if (r.exit_code != 0) return unknown;664665    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");666    const sz_str = it.next() orelse return unknown;667    const age_str = it.next() orelse return unknown;668    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;669    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;670671    gpa.free(unknown.size);672    gpa.free(unknown.age);673    return .{674        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),675        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),676    };677}678679// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A680// one-word health signal; exits non-zero when degraded, so we read stdout, not681// the code. Caller owns the returned slice.682pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {683    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch684        return gpa.dupe(u8, "unknown");685    defer gpa.free(r.stderr);686    const state = std.mem.trim(u8, r.stdout, " \t\n\r");687    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");688    gpa.free(r.stdout);689    return owned;690}691692fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {693    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});694    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});695    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});696    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});697}698699pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {700    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });701}702703pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {704    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)705    // graph work that takes minutes on a real store (59k+ paths) and hangs the706    // command. We don't need closures: `--all --json` (no -S) carries each path's707    // own narSize, so one fast pass gives the path count and the summed store size.708    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.709    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.710    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });711    defer gpa.free(pi.stdout);712    defer gpa.free(pi.stderr);713714    const scan = scanStoreJson(pi.stdout);715    const total_owned = try humanSize(gpa, scan.total_bytes);716717    return .{718        .total_size = total_owned,719        .live_paths = scan.count,720        .reclaimable_paths = 0,721    };722}723724const StoreScan = struct { count: u64, total_bytes: u64 };725726// One linear pass over `nix path-info --json`: each path object has exactly one727// "narSize": field, so counting them gives the true path count and summing the728// values gives the total store size — no per-path closure walk.729fn scanStoreJson(json_str: []const u8) StoreScan {730    const needle = "\"narSize\":";731    var count: u64 = 0;732    var total: u64 = 0;733    var i: usize = 0;734    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {735        var j = pos + needle.len;736        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}737        var val: u64 = 0;738        var any = false;739        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {740            val = val * 10 + (json_str[j] - '0');741            any = true;742        }743        if (any) {744            count += 1;745            total += val;746        }747        i = j;748    }749    return .{ .count = count, .total_bytes = total };750}751752fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {753    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };754    var val: f64 = @floatFromInt(bytes);755    var unit: usize = 0;756    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;757    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });758    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });759}760761pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {762    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the763    // flake registry), not a flake in the current directory.764    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});765    defer gpa.free(expr);766    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });767    defer gpa.free(r.stderr);768    if (r.exit_code != 0) {769        gpa.free(r.stdout);770        return error.ProcessFailed;771    }772    return r.stdout;773}774775// --- Flake ---776777pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {778    if (input) |inp| {779        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });780    }781    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });782}783784// Update flake inputs for the flake living in `dir` (the config dir). `nix flake785// update` operates on the flake in the working directory, so we cd there first.786// Used by `nina upgrade` on a flake system in place of nix-channel --update.787pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {788    return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });789}790791pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {792    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });793}794795pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {796    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });797}798799pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {800    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });801}802803pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {804    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });805}806807pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {808    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });809    defer gpa.free(r.stderr);810    if (r.exit_code != 0) {811        gpa.free(r.stdout);812        return error.ProcessFailed;813    }814    return r.stdout;815}816817// --- Build / Run / Develop ---818819pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {820    if (attr) |a| {821        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});822        defer gpa.free(ref);823        return stream(io, machine, gpa, &.{ "nix", "build", ref });824    }825    return stream(io, machine, gpa, &.{ "nix", "build" });826}827828pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {829    // nix run always gets --no-write-lock-file for remote URLs830    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");831    if (is_url) {832        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });833    }834    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.835    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {836        return stream(io, machine, gpa, &.{ "nix", "run", pkg });837    }838    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});839    defer gpa.free(ref);840    return stream(io, machine, gpa, &.{ "nix", "run", ref });841}842843pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {844    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});845    defer gpa.free(ref);846    return stream(io, machine, gpa, &.{ "nix", "shell", ref });847}848849pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {850    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});851    defer gpa.free(ref);852    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});853    defer gpa.free(ps1);854    if (machine.local) {855        const rc_path = try createInteractiveShellRc(gpa, io);856        defer {857            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};858            gpa.free(rc_path);859        }860        return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref, "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, ps1);861    }862    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);863}864865pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {866    if (run_cmd) |cmd| {867        // sh -c so a multi-word command isn't treated as a single executable name.868        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });869    }870    return stream(io, machine, gpa, &.{ "nix", "develop" });871}872873pub 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 {874    if (run_cmd) |cmd| {875        // sh -c so a multi-word command isn't treated as a single executable name.876        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });877    }878    if (machine.local) {879        const rc_path = try createInteractiveShellRc(gpa, io);880        defer {881            std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};882            gpa.free(rc_path);883        }884        return streamEnv(io, machine, gpa, &.{ "nix", "develop", "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, "(nina: dev) -> ");885    }886    return streamEnv(io, machine, gpa, &.{ "nix", "develop" }, base_env, "(nina: dev) -> ");887}888889pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {890    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });891}892893// --- Format ---894895pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {896    if (check) {897        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });898    }899    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });900}901902// --- Info ---903904pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {905    const r = try capture(gpa, io, machine, &.{"nixos-version"});906    defer gpa.free(r.stderr);907    if (r.exit_code != 0) {908        gpa.free(r.stdout);909        return error.ProcessFailed;910    }911    return r.stdout;912}913914pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {915    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });916    defer gpa.free(r.stderr);917    if (r.exit_code != 0) {918        gpa.free(r.stdout);919        return error.ProcessFailed;920    }921    return r.stdout;922}923924pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {925    const r = try capture(gpa, io, machine, &.{"uptime"});926    defer gpa.free(r.stderr);927    if (r.exit_code != 0) {928        gpa.free(r.stdout);929        return error.ProcessFailed;930    }931    return r.stdout;932}933934// --- Boot ---935936pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {937    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });938    defer gpa.free(r.stderr);939    defer gpa.free(r.stdout);940    if (r.exit_code != 0) return error.ProcessFailed;941    return parseBootEntries(gpa, r.stdout);942}943944fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {945    var entries: std.ArrayList(types.BootEntry) = .empty;946    var lines = std.mem.splitScalar(u8, output_str, '\n');947    while (lines.next()) |line| {948        const trimmed = std.mem.trim(u8, line, " \t\r");949        if (std.mem.startsWith(u8, trimmed, "title:")) {950            const title = std.mem.trim(u8, trimmed[6..], " \t");951            const current = std.mem.indexOf(u8, title, "(current)") != null;952            try entries.append(gpa, .{953                .title = try gpa.dupe(u8, title),954                .current = current,955            });956        }957    }958    return entries.toOwnedSlice(gpa);959}960961// --- Pkg info ---962963fn pkgInstallable(gpa: std.mem.Allocator, pkg: []const u8) ![]u8 {964    return std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});965}966967fn resolvePkgStorePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, installable: []const u8) ![]u8 {968    const r = try capture(gpa, io, machine, &.{ "nix", "build", "--no-link", "--print-out-paths", installable });969    defer gpa.free(r.stderr);970    defer gpa.free(r.stdout);971    if (r.exit_code != 0) return error.PackageNotFound;972973    var lines = std.mem.tokenizeAny(u8, r.stdout, "\r\n");974    const first_path = lines.next() orelse return error.PackageNotFound;975    const store_path = std.mem.trim(u8, first_path, " \t");976    if (store_path.len == 0) return error.PackageNotFound;977    return gpa.dupe(u8, store_path);978}979980pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {981    const installable = try pkgInstallable(gpa, pkg);982    defer gpa.free(installable);983    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);984    defer gpa.free(store_path);985    return stream(io, machine, gpa, &.{ "nix", "why-depends", "/run/current-system", store_path });986}987988pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {989    const installable = try pkgInstallable(gpa, pkg);990    defer gpa.free(installable);991    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);992    defer gpa.free(store_path);993    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", store_path });994}995996pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {997    const installable = try pkgInstallable(gpa, pkg);998    defer gpa.free(installable);999    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", "--json", installable });1000    defer gpa.free(r.stderr);1001    defer gpa.free(r.stdout);1002    if (r.exit_code != 0) return error.ProcessFailed;10031004    const nar_size = try pathInfoNarSize(gpa, r.stdout);1005    return humanPkgSize(gpa, nar_size);1006}10071008pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1009    const installable = try pkgInstallable(gpa, pkg);1010    defer gpa.free(installable);1011    const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1012    defer gpa.free(store_path);1013    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", store_path });1014}10151016fn pathInfoNarSize(gpa: std.mem.Allocator, json_str: []const u8) !u64 {1017    var parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.ProcessFailed;1018    defer parsed.deinit();1019    switch (parsed.value) {1020        .object => |obj| {1021            var it = obj.iterator();1022            while (it.next()) |entry| {1023                if (entry.value_ptr.* == .object) {1024                    if (entry.value_ptr.object.get("narSize")) |v| {1025                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1026                    }1027                }1028            }1029        },1030        .array => |arr| {1031            for (arr.items) |item| {1032                if (item == .object) {1033                    if (item.object.get("narSize")) |v| {1034                        if (v == .integer and v.integer >= 0) return @intCast(v.integer);1035                    }1036                }1037            }1038        },1039        else => {},1040    }1041    return error.ProcessFailed;1042}10431044fn humanPkgSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1045    const units = [_][]const u8{ "B", "KiB", "MiB", "GiB", "TiB" };1046    var val: f64 = @floatFromInt(bytes);1047    var unit: usize = 0;1048    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1049    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1050    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1051}10521053test "pathInfoNarSize parses object and array shapes" {1054    try std.testing.expectEqual(@as(u64, 1064629862), try pathInfoNarSize(std.testing.allocator,1055        \\{"/nix/store/abc-ffmpeg":{"narSize":1064629862}}1056    ));1057    try std.testing.expectEqual(@as(u64, 2048), try pathInfoNarSize(std.testing.allocator,1058        \\[{"path":"/nix/store/abc-pkg","narSize":2048}]1059    ));1060}10611062// --- Hash / Fetch ---10631064pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {1065    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });1066    defer gpa.free(r.stderr);1067    if (r.exit_code != 0) {1068        gpa.free(r.stdout);1069        return error.ProcessFailed;1070    }1071    return r.stdout;1072}10731074pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {1075    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });1076    defer gpa.free(r.stderr);1077    if (r.exit_code != 0) {1078        gpa.free(r.stdout);1079        return error.ProcessFailed;1080    }1081    return r.stdout;1082}10831084// --- Pin ---10851086pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {1087    // Stub: full implementation would parse and edit flake.lock JSON1088    // The pin/unpin flow works via nix flake update which regenerates flake.lock1089}10901091pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {1092    if (line) |l| {1093        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});1094        defer gpa.free(line_arg);1095        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });1096    }1097    return stream(io, &types.Machine{}, gpa, &.{ editor, path });1098}10991100pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {1101    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});1102    defer gpa.free(a_str);1103    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});1104    defer gpa.free(b_str);1105    // On a tty, the child's own color is fine — stream it directly.1106    if (output.colorEnabled()) {1107        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });1108    }1109    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,1110    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.1111    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });1112    defer gpa.free(r.stdout);1113    defer gpa.free(r.stderr);1114    const cleaned = try stripAnsi(gpa, r.stdout);1115    defer gpa.free(cleaned);1116    output.raw(cleaned);1117    return r.exit_code;1118}11191120// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a1121// child process's color when it writes ANSI unconditionally.1122fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1123    var out: std.ArrayList(u8) = .empty;1124    errdefer out.deinit(gpa);1125    var i: usize = 0;1126    while (i < input.len) {1127        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1128            i += 2;1129            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1130            if (i < input.len) i += 1; // consume the final byte1131            continue;1132        }1133        try out.append(gpa, input[i]);1134        i += 1;1135    }1136    return out.toOwnedSlice(gpa);1137}11381139test "stripAnsi removes CSI color sequences" {1140    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1141    defer std.testing.allocator.free(cleaned);1142    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1143}11441145// --- Doctor checks ---11461147pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1148    var checks: std.ArrayList(types.DoctorCheck) = .empty;11491150    // Check nix daemon1151    {1152        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1153        defer gpa.free(r.stdout);1154        defer gpa.free(r.stderr);1155        const active = std.mem.indexOf(u8, r.stdout, "active") != null;1156        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1157    }11581159    // Check config syntax. Flake-aware like apply/upgrade: on a flake system a1160    // plain `nixos-rebuild dry-build` evaluates <nixpkgs/nixos> + <nixos-config>1161    // (channel style) and fails, so pass --flake when the config dir has one.1162    {1163        const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1164            &.{ "sudo", "nixos-rebuild", "dry-build", "--flake", machine.config_path }1165        else1166            &.{ "sudo", "nixos-rebuild", "dry-build" };1167        const r = try capture(gpa, io, machine, argv);1168        defer gpa.free(r.stdout);1169        defer gpa.free(r.stderr);1170        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1171    }11721173    // Check channel1174    {1175        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1176        defer gpa.free(r.stdout);1177        defer gpa.free(r.stderr);1178        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1179        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1180    }11811182    return checks.toOwnedSlice(gpa);1183}11841185// --- Home Manager ---1186//1187// Home Manager has three usage modes. nina detects which one is in play before1188// any `home` command so it can either drive the standalone CLI or redirect the1189// user to `nina apply` (when HM is a NixOS/flake module activated by rebuild).11901191pub const HomeManagerMode = enum {1192    // home-manager binary on PATH — manages the user env on its own.1193    standalone,1194    // No binary, but a home.nix exists — HM is a NixOS/flake module rebuilt by1195    // nixos-rebuild. `nina home apply` redirects to `nina apply`.1196    module,1197    none,1198};11991200fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1201    const home = environ.get("HOME") orelse return null;1202    return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1203}12041205// Path to the standalone home.nix. Caller frees.1206pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1207    const dir = homeConfigDir(gpa, environ) orelse return null;1208    defer gpa.free(dir);1209    return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1210}12111212pub fn pathExists(io: std.Io, path: []const u8) bool {1213    const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1214    f.close(io);1215    return true;1216}12171218// `command -v <name>` — true if the binary resolves on PATH. Silent (captured),1219// unlike streamLocal which would inherit stdio.1220fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1221    var buf: [256]u8 = undefined;1222    const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1223    const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1224    defer gpa.free(r.stdout);1225    defer gpa.free(r.stderr);1226    return switch (r.term) {1227        .exited => |code| code == 0,1228        else => false,1229    };1230}12311232pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1233    if (commandExists(gpa, io, "home-manager")) return .standalone;1234    if (homeNixPath(gpa, environ)) |p| {1235        defer gpa.free(p);1236        if (pathExists(io, p)) return .module;1237    }1238    return .none;1239}12401241// If the home-manager config dir holds a flake.nix, returns the flake ref1242// "<dir>#<user>" for `home-manager switch --flake`. Username comes from $USER.1243// Caller frees. null when there's no flake.nix (channel-based home config).1244pub fn homeFlakeRef(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1245    const dir = homeConfigDir(gpa, environ) orelse return null;1246    defer gpa.free(dir);1247    const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch return null;1248    defer gpa.free(flake);1249    if (!pathExists(io, flake)) return null;1250    const user = environ.get("USER") orelse "default";1251    return std.fmt.allocPrint(gpa, "{s}#{s}", .{ dir, user }) catch null;1252}12531254pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1255    return stream(io, machine, gpa, &.{ "home-manager", "switch" });1256}12571258pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8) !u8 {1259    return stream(io, machine, gpa, &.{ "home-manager", "switch", "--flake", flake_ref });1260}12611262// home-manager has no system-profile rollback; it re-activates the previous1263// generation via `switch --rollback`.1264pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1265    return stream(io, machine, gpa, &.{ "home-manager", "switch", "--rollback" });1266}12671268// Build (and validate) the home config without activating it — used by `home1269// check` and `home apply --dry`. `home-manager build` drops a ./result symlink1270// in the cwd, so run it in a throwaway temp dir to avoid littering the directory1271// nina was invoked from.1272pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1273    return stream(io, machine, gpa, &.{ "sh", "-c", "d=$(mktemp -d) && cd \"$d\" && home-manager build" });1274}12751276pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1277    const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1278    defer gpa.free(r.stderr);1279    if (r.exit_code != 0) {1280        gpa.free(r.stdout);1281        return error.ProcessFailed;1282    }1283    return r.stdout;1284}12851286// Store paths referenced by a home generation — used to list managed packages.1287pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1288    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1289    defer gpa.free(r.stderr);1290    if (r.exit_code != 0) {1291        gpa.free(r.stdout);1292        return error.ProcessFailed;1293    }1294    return r.stdout;1295}12961297// diff-closures between two arbitrary store paths (home generations), mirroring1298// diffClosures' tty/piped color handling.1299pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1300    if (output.colorEnabled()) {1301        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1302    }1303    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1304    defer gpa.free(r.stdout);1305    defer gpa.free(r.stderr);1306    const cleaned = try stripAnsi(gpa, r.stdout);1307    defer gpa.free(cleaned);1308    output.raw(cleaned);1309    return r.exit_code;1310}13111312// --- Log ---13131314pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1315    const home = environ.get("HOME") orelse return error.FileNotFound;1316    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1317    defer gpa.free(path);1318    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1319    if (last == 0) return content;13201321    // Collect non-empty lines, then keep only the final `last`. Slices point into1322    // `content`, so copy them out before freeing it.1323    var lines: std.ArrayList([]const u8) = .empty;1324    defer lines.deinit(gpa);1325    var it = std.mem.splitScalar(u8, content, '\n');1326    while (it.next()) |line| {1327        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1328        try lines.append(gpa, line);1329    }1330    if (lines.items.len <= last) return content;13311332    var out: std.ArrayList(u8) = .empty;1333    errdefer out.deinit(gpa);1334    for (lines.items[lines.items.len - last ..]) |line| {1335        try out.appendSlice(gpa, line);1336        try out.append(gpa, '\n');1337    }1338    gpa.free(content);1339    return out.toOwnedSlice(gpa);1340}13411342// nina is a one-shot process, so "did the last apply fail this session?" can't1343// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1344// other ~/.nina-* state files. This lets a later successful apply earn the1345// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1346pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1347    const home = environ.get("HOME") orelse return;1348    var buf: [512]u8 = undefined;1349    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1350    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1351    file.close(io);1352}13531354pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1355    const home = environ.get("HOME") orelse return false;1356    var buf: [512]u8 = undefined;1357    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1358    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1359        f.close(io);1360        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1361        return true;1362    } else |_| {1363        return false;1364    }1365}13661367pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1368    const home = environ.get("HOME") orelse return;1369    var path_buf: [512]u8 = undefined;1370    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1371    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1372        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1373    defer file.close(io);1374    const size = file.length(io) catch 0;1375    file.writePositionalAll(io, entry, size) catch {};1376}13771378// --- Update helpers ---13791380// Fetch a URL with curl and return the response body. Caller must free.1381// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.1382pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1383    const argv = [_][]const u8{1384        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1385    };1386    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1387    defer gpa.free(result.stderr);13881389    const marker = "\nHTTP_STATUS:";1390    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1391        gpa.free(result.stdout);1392        return error.NetworkError;1393    };1394    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1395    const status = std.fmt.parseInt(u16, status_str, 10) catch {1396        gpa.free(result.stdout);1397        return error.NetworkError;1398    };1399    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1400    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1401    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1402        gpa.free(result.stdout);1403        return e;1404    };1405    gpa.free(result.stdout);1406    return body;1407}14081409// Download a URL to a temp file. Returns the temp path (caller must gpa.free).1410// The file is written to /tmp/nina-update-<pid> and left for the caller to use.1411pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1412    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1413    errdefer gpa.free(tmp_path);14141415    var child = std.process.spawn(io, .{1416        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1417        .stdin = .close,1418        .stdout = .close,1419        .stderr = .inherit,1420    }) catch return error.NetworkError;1421    const term = child.wait(io) catch return error.NetworkError;1422    switch (term) {1423        .exited => |c| if (c != 0) return error.NetworkError,1424        else => return error.NetworkError,1425    }1426    return tmp_path;1427}14281429// Get the current executable path into buf. Returns slice of buf.1430pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1431    const len = try std.process.executablePath(io, buf);1432    return buf[0..len];1433}14341435// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1436// atomically install the binary to install_path. Errors: ChecksumMismatch,1437// AccessDenied (with error_info set), or underlying I/O errors.1438pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1439    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1440        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1441        return error.FileNotFound;1442    };1443    defer gpa.free(bytes);14441445    var hasher = std.crypto.hash.Blake3.init(.{});1446    hasher.update(bytes);1447    var raw: [32]u8 = undefined;1448    hasher.final(&raw);1449    const hex = std.fmt.bytesToHex(raw, .lower);1450    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;14511452    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1453    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1454        return error.NameTooLong;14551456    {1457        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1458            errors.error_info.setMessage("cannot write to {s}", .{install_path});1459            errors.error_info.setSuggestion("try: sudo nina update", .{});1460            return error.AccessDenied;1461        };1462        defer f.close(io);1463        f.writePositionalAll(io, bytes, 0) catch {1464            errors.error_info.setMessage("cannot write to {s}", .{install_path});1465            return error.AccessDenied;1466        };1467        try f.setPermissions(io, .fromMode(0o755));1468    }1469    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};14701471    if (comptime builtin.os.tag == .macos) {1472        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1473    }14741475    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1476        error.AccessDenied => {1477            errors.error_info.setMessage("cannot replace {s}", .{install_path});1478            errors.error_info.setSuggestion("try: sudo nina update", .{});1479            return error.AccessDenied;1480        },1481        else => return e,1482    };1483}14841485// --- Nix feature setup ---14861487pub const NixFeatureStatus = struct {1488    nix_command: bool = false,1489    flakes: bool = false,14901491    pub fn allEnabled(self: NixFeatureStatus) bool {1492        return self.nix_command and self.flakes;1493    }1494};14951496fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1497    var lines = std.mem.splitScalar(u8, conf, '\n');1498    while (lines.next()) |line| {1499        const trimmed = std.mem.trim(u8, line, " \t");1500        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1501        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1502        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1503    }1504}15051506pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1507    var status = NixFeatureStatus{};15081509    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1510        defer gpa.free(conf);1511        scanConfFeatures(conf, &status);1512    }15131514    if (environ.get("HOME")) |home| {1515        var buf: [512]u8 = undefined;1516        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1517        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1518            defer gpa.free(conf);1519            scanConfFeatures(conf, &status);1520        }1521    }15221523    return status;1524}15251526pub fn isNixOS(io: std.Io) bool {1527    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1528    file.close(io);1529    return true;1530}15311532// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.1533// Returns the path written (caller must free).1534pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1535    const home = environ.get("HOME") orelse {1536        errors.error_info.setMessage("HOME not set", .{});1537        return error.ConfigNotFound;1538    };15391540    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1541    defer gpa.free(dir_path);1542    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1543    errdefer gpa.free(file_path);15441545    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};15461547    const line = "experimental-features = nix-command flakes\n";1548    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1549        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1550        errors.error_info.setMessage("could not write {s}", .{file_path});1551        return error.FileNotFound;1552    });1553    defer file.close(io);15541555    const size = file.length(io) catch 0;1556    file.writePositionalAll(io, line, size) catch {1557        errors.error_info.setMessage("could not write {s}", .{file_path});1558        return error.FileNotFound;1559    };15601561    return file_path;1562}15631564// --- NixOS: declarative experimental-features ---1565//1566// On NixOS the permanent, declarative home for these flags is configuration.nix,1567// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves1568// the `nixos-rebuild switch` to the user.15691570pub const NIXOS_FEATURES_LINE =1571    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";15721573// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns1574// false on any read error so the caller still offers to add the line.1575pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1576    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1577    defer gpa.free(conf);1578    return std.mem.indexOf(u8, conf, "experimental-features") != null and1579        std.mem.indexOf(u8, conf, "nix-command") != null and1580        std.mem.indexOf(u8, conf, "flakes") != null;1581}15821583fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1584    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1585    return captureLocal(gpa, io, &.{ "sudo", "cat", path });1586}15871588// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix1589// (i.e. inside the top-level attribute set) and write it back via a single1590// `sudo cp`, which prompts for the password on the terminal. Returns an error1591// for the caller to fall back to printed manual instructions.1592pub fn appendFeaturesToNixosConfig(1593    gpa: std.mem.Allocator,1594    io: std.Io,1595    environ: *const std.process.Environ.Map,1596    path: []const u8,1597) !void {1598    const conf = readMaybeSudo(gpa, io, path) catch {1599        errors.error_info.setMessage("could not read {s}", .{path});1600        return error.ConfigNotFound;1601    };1602    defer gpa.free(conf);16031604    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared16051606    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1607        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1608        return error.MalformedConfig;1609    };16101611    const home = environ.get("HOME") orelse {1612        errors.error_info.setMessage("HOME not set", .{});1613        return error.ConfigNotFound;1614    };1615    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1616    defer gpa.free(tmp_path);16171618    var buf: std.ArrayList(u8) = .empty;1619    defer buf.deinit(gpa);1620    try buf.appendSlice(gpa, conf[0..brace]);1621    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1622    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");1623    try buf.appendSlice(gpa, "  ");1624    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1625    try buf.append(gpa, '\n');1626    try buf.appendSlice(gpa, conf[brace..]);16271628    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1629        errors.error_info.setMessage("could not write {s}", .{tmp_path});1630        return error.FileNotFound;1631    };1632    tmp.writePositionalAll(io, buf.items, 0) catch {1633        tmp.close(io);1634        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1635        errors.error_info.setMessage("could not write {s}", .{tmp_path});1636        return error.FileNotFound;1637    };1638    tmp.close(io);16391640    // Back up the existing config, then replace it — in one sudo call so the1641    // password is asked for at most once. Paths travel as positional args ($0,1642    // $1) to sidestep shell quoting.1643    const code = streamLocal(io, &.{1644        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1645    }) catch {1646        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1647        errors.error_info.setMessage("could not write {s}", .{path});1648        return error.ProcessFailed;1649    };1650    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1651    if (code != 0) {1652        errors.error_info.setMessage("sudo cp into {s} failed", .{path});1653        return error.ProcessFailed;1654    }1655}