exec.zig

49.6 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 local process with inherited stdio (no SSH routing — for nix commands).69pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 {70    output.flush();71    var child = std.process.spawn(io, .{72        .argv = cmd,73        .stdin = .inherit,74        .stdout = .inherit,75        .stderr = .inherit,76    }) catch |e| {77        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});78        return e;79    };80    const term = child.wait(io) catch {81        errors.error_info.setMessage("process wait failed", .{});82        return error.ProcessFailed;83    };84    return switch (term) {85        .exited => |c| c,86        else => 1,87    };88}8990// Run a process and capture output as a single string (no SSH routing — for local nix commands).91pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {92    const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;93    defer gpa.free(result.stderr);94    switch (result.term) {95        .exited => |c| if (c != 0) {96            gpa.free(result.stdout);97            return error.ProcessFailed;98        },99        else => {100            gpa.free(result.stdout);101            return error.ProcessFailed;102        },103    }104    return result.stdout;105}106107fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {108    if (machine.local) return cmd;109110    const host = machine.host orelse {111        errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});112        return error.SshFailed;113    };114115    var ssh: std.ArrayList([]const u8) = .empty;116    try ssh.append(gpa, "ssh");117    try ssh.append(gpa, "-o");118    try ssh.append(gpa, "BatchMode=yes");119    try ssh.append(gpa, "-o");120    try ssh.append(gpa, "StrictHostKeyChecking=accept-new");121    if (machine.ssh_key) |key| {122        try ssh.append(gpa, "-i");123        try ssh.append(gpa, key);124    }125    const addr = if (machine.user) |u|126        try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })127    else128        try gpa.dupe(u8, host);129    try ssh.append(gpa, addr);130    for (cmd) |arg| try ssh.append(gpa, arg);131    return ssh.toOwnedSlice(gpa);132}133134// --- NixOS rebuild ---135136pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {137    const cmd = &.{ "sudo", "nixos-rebuild", "switch" };138    output.printSubstep("nixos-rebuild switch", .{});139    return stream(io, machine, gpa, cmd);140}141142pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {143    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "dry-activate" });144}145146pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {147    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "build" });148}149150// --- Generations ---151152// Read system-profile generations WITHOUT root. `nix-env --list-generations -p153// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user154// ("system.lock: Permission denied"). The generation symlinks themselves are155// world-readable, so list them directly: parse `system-N-link` names, take each156// link's own mtime for the date/time, and mark the one the `system` symlink157// points at as current. Output matches the `nix-env --list-generations` columns158// (num date time [current]) so parseGenerations is unchanged.159const GEN_LIST_SCRIPT =160    \\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 }'161;162163pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {164    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });165    defer gpa.free(r.stderr);166    defer gpa.free(r.stdout);167    if (r.exit_code != 0) return error.ProcessFailed;168    return parseGenerations(gpa, r.stdout);169}170171fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {172    var gens: std.ArrayList(types.GenerationInfo) = .empty;173    var lines = std.mem.splitScalar(u8, output_str, '\n');174    while (lines.next()) |line| {175        const trimmed = std.mem.trim(u8, line, " \t");176        if (trimmed.len == 0) continue;177        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");178        const num_str = parts.next() orelse continue;179        const date_str = parts.next() orelse continue;180        const time_str = parts.next() orelse continue;181        const rest = parts.rest();182        const current = std.mem.indexOf(u8, rest, "current") != null;183        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;184        try gens.append(gpa, .{185            .number = num,186            .date = try gpa.dupe(u8, date_str),187            .time = try gpa.dupe(u8, time_str),188            .current = current,189        });190    }191    return gens.toOwnedSlice(gpa);192}193194pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {195    const gens = try getGenerations(gpa, io, machine);196    defer gpa.free(gens);197    for (gens) |g| {198        if (g.current) return g.number;199    }200    return 0;201}202203pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {204    // Switch the system profile to generation n, then activate it (bootloader +205    // services). Without switch-to-configuration the change isn't applied.206    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 });207    defer gpa.free(cmd);208    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });209}210211pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {212    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });213}214215pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {216    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});217    defer gpa.free(n_str);218    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });219}220221pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {222    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });223}224225// --- Garbage collection ---226227pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {228    if (delete_old) {229        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });230    }231    // Keep the `keep` most recent system generations (+N deletes all but N),232    // then collect now-unreferenced store paths. `--delete-older-than` wants a233    // duration (e.g. 14d), not a generation count.234    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });235    defer gpa.free(cmd);236    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });237}238239// --- Channels ---240241pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {242    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });243    defer gpa.free(r.stderr);244    defer gpa.free(r.stdout);245    if (r.exit_code != 0) return error.ProcessFailed;246    return parseChannels(gpa, r.stdout);247}248249fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {250    var channels: std.ArrayList(types.ChannelInfo) = .empty;251    var lines = std.mem.splitScalar(u8, output_str, '\n');252    while (lines.next()) |line| {253        const trimmed = std.mem.trim(u8, line, " \t\r");254        if (trimmed.len == 0) continue;255        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;256        try channels.append(gpa, .{257            .name = try gpa.dupe(u8, trimmed[0..space]),258            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),259        });260    }261    return channels.toOwnedSlice(gpa);262}263264pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {265    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });266}267268pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {269    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });270}271272pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {273    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });274}275276// --- Services ---277278pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ServiceInfo {279    const r = try capture(gpa, io, machine, &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" });280    defer gpa.free(r.stderr);281    defer gpa.free(r.stdout);282    if (r.exit_code != 0) return error.ProcessFailed;283    return parseServices(gpa, r.stdout);284}285286fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {287    var svcs: std.ArrayList(types.ServiceInfo) = .empty;288    var lines = std.mem.splitScalar(u8, output_str, '\n');289    while (lines.next()) |line| {290        const trimmed = std.mem.trim(u8, line, " \t\r");291        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines292        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");293        const name = parts.next() orelse continue;294        _ = parts.next(); // load295        const active_str = parts.next() orelse continue;296        const sub_str = parts.next() orelse "unknown";297298        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))299            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)300        else if (std.mem.eql(u8, active_str, "failed"))301            .failed302        else303            .inactive;304305        try svcs.append(gpa, .{306            .name = try gpa.dupe(u8, name),307            .state = state,308            .uptime = null,309        });310    }311    return svcs.toOwnedSlice(gpa);312}313314pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8) !u8 {315    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.316    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });317}318319pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool) !u8 {320    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});321    defer gpa.free(n_str);322    if (follow) {323        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });324    }325    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });326}327328// --- Profile ---329330pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {331    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});332    defer gpa.free(pkg_ref);333    // `nix profile add` is the current verb; `install` is a deprecated alias that334    // prints a warning on modern nix.335    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });336}337338pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {339    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not340    // by flake ref — passing nixpkgs#ripgrep matches nothing.341    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });342}343344pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {345    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });346    defer gpa.free(r.stderr);347    if (r.exit_code != 0) return error.ProcessFailed;348    return r.stdout;349}350351// Machine-readable profile listing — caller parses elements -> name + version.352pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {353    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });354    defer gpa.free(r.stderr);355    if (r.exit_code != 0) {356        gpa.free(r.stdout);357        return error.ProcessFailed;358    }359    return r.stdout;360}361362// Whether nina is an element of the nix profile. A NixOS system-package install363// (programs.nina.enable) also resolves the binary into /nix/store, so the store364// path alone can't distinguish it from a `nix profile` install — the profile365// list can. Parses element names rather than substring-matching the raw JSON,366// since another package's store path could contain "nina". A missing/empty367// profile (or no nix) means not-in-profile.368pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {369    const js = profileListJson(gpa, io, machine) catch return false;370    defer gpa.free(js);371    return profileJsonHasNina(gpa, js);372}373374// Pure parse of `nix profile list --json` for a nina element. Element names,375// not a raw substring search — another package's store path could contain376// "nina". Newer nix keys elements by name (e.g. "nina"); older nix uses an377// array of objects with an "attrPath" like "...#nina".378fn profileJsonHasNina(gpa: std.mem.Allocator, js: []const u8) bool {379    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return false;380    defer parsed.deinit();381    const root = parsed.value;382    if (root != .object) return false;383    const elements = root.object.get("elements") orelse return false;384    switch (elements) {385        .object => |obj| return obj.contains("nina"),386        .array => |arr| {387            for (arr.items) |el| {388                if (el != .object) continue;389                const ap = el.object.get("attrPath") orelse continue;390                if (ap == .string and (std.mem.eql(u8, ap.string, "nina") or391                    std.mem.endsWith(u8, ap.string, ".nina"))) return true;392            }393            return false;394        },395        else => return false,396    }397}398399test "profileJsonHasNina matches element name, not store-path substrings" {400    const a = std.testing.allocator;401    // Newer nix schema: elements keyed by name. nina present.402    const has =403        \\{"elements":{"bat":{"storePaths":["/nix/store/h-bat-0.26.1"]},404        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a-nina-3.0.15"]}},"version":3}405    ;406    try std.testing.expect(profileJsonHasNina(a, has));407408    // No nina element, but another package's store path contains "nina" —409    // the old substring check would false-positive here.410    const decoy =411        \\{"elements":{"luminance":{"storePaths":["/nix/store/x-luminance-nina-1.0"]}},"version":3}412    ;413    try std.testing.expect(!profileJsonHasNina(a, decoy));414415    // Older nix array schema.416    const arr =417        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a-nina-3.0.15"]}],"version":2}418    ;419    try std.testing.expect(profileJsonHasNina(a, arr));420421    // Empty / malformed → not present.422    try std.testing.expect(!profileJsonHasNina(a, "{\"elements\":{},\"version\":3}"));423    try std.testing.expect(!profileJsonHasNina(a, "not json"));424}425426// The store paths that make up the running system environment. Each reference is427// a <hash>-<name>-<version> path, so the caller can list system packages with428// versions — there is no cleaner per-package list for environment.systemPackages.429pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {430    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });431    defer gpa.free(r.stderr);432    if (r.exit_code != 0) {433        gpa.free(r.stdout);434        return error.ProcessFailed;435    }436    return r.stdout;437}438439pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {440    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });441}442443// --- Store ---444445pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {446    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });447}448449pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {450    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });451}452453pub const SystemStatus = struct { size: []u8, age: []u8 };454455// One read-only pass for `nina status`: the current system's closure size (a456// single `path-info -S` of /run/current-system — fast, unlike -S over the whole457// store) and seconds since the system profile was last switched (its symlink458// mtime). Both are world-readable; no root needed.459const STATUS_SCRIPT =460    \\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} ))"461;462463pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {464    const unknown = SystemStatus{465        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },466        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },467    };468    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;469    defer gpa.free(r.stdout);470    defer gpa.free(r.stderr);471    if (r.exit_code != 0) return unknown;472473    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");474    const sz_str = it.next() orelse return unknown;475    const age_str = it.next() orelse return unknown;476    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;477    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;478479    gpa.free(unknown.size);480    gpa.free(unknown.age);481    return .{482        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),483        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),484    };485}486487// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A488// one-word health signal; exits non-zero when degraded, so we read stdout, not489// the code. Caller owns the returned slice.490pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {491    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch492        return gpa.dupe(u8, "unknown");493    defer gpa.free(r.stderr);494    const state = std.mem.trim(u8, r.stdout, " \t\n\r");495    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");496    gpa.free(r.stdout);497    return owned;498}499500fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {501    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});502    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});503    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});504    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});505}506507pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {508    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });509}510511pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {512    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)513    // graph work that takes minutes on a real store (59k+ paths) and hangs the514    // command. We don't need closures: `--all --json` (no -S) carries each path's515    // own narSize, so one fast pass gives the path count and the summed store size.516    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.517    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.518    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });519    defer gpa.free(pi.stdout);520    defer gpa.free(pi.stderr);521522    const scan = scanStoreJson(pi.stdout);523    const total_owned = try humanSize(gpa, scan.total_bytes);524525    return .{526        .total_size = total_owned,527        .live_paths = scan.count,528        .reclaimable_paths = 0,529    };530}531532const StoreScan = struct { count: u64, total_bytes: u64 };533534// One linear pass over `nix path-info --json`: each path object has exactly one535// "narSize": field, so counting them gives the true path count and summing the536// values gives the total store size — no per-path closure walk.537fn scanStoreJson(json_str: []const u8) StoreScan {538    const needle = "\"narSize\":";539    var count: u64 = 0;540    var total: u64 = 0;541    var i: usize = 0;542    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {543        var j = pos + needle.len;544        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}545        var val: u64 = 0;546        var any = false;547        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {548            val = val * 10 + (json_str[j] - '0');549            any = true;550        }551        if (any) {552            count += 1;553            total += val;554        }555        i = j;556    }557    return .{ .count = count, .total_bytes = total };558}559560fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {561    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };562    var val: f64 = @floatFromInt(bytes);563    var unit: usize = 0;564    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;565    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });566    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });567}568569pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {570    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the571    // flake registry), not a flake in the current directory.572    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});573    defer gpa.free(expr);574    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });575    defer gpa.free(r.stderr);576    if (r.exit_code != 0) {577        gpa.free(r.stdout);578        return error.ProcessFailed;579    }580    return r.stdout;581}582583// --- Flake ---584585pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {586    if (input) |inp| {587        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });588    }589    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });590}591592pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {593    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });594}595596pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {597    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });598}599600pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {601    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });602}603604pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {605    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });606}607608pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {609    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });610    defer gpa.free(r.stderr);611    if (r.exit_code != 0) {612        gpa.free(r.stdout);613        return error.ProcessFailed;614    }615    return r.stdout;616}617618// --- Build / Run / Develop ---619620pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {621    if (attr) |a| {622        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});623        defer gpa.free(ref);624        return stream(io, machine, gpa, &.{ "nix", "build", ref });625    }626    return stream(io, machine, gpa, &.{ "nix", "build" });627}628629pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {630    // nix run always gets --no-write-lock-file for remote URLs631    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");632    if (is_url) {633        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });634    }635    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.636    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {637        return stream(io, machine, gpa, &.{ "nix", "run", pkg });638    }639    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});640    defer gpa.free(ref);641    return stream(io, machine, gpa, &.{ "nix", "run", ref });642}643644pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {645    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});646    defer gpa.free(ref);647    return stream(io, machine, gpa, &.{ "nix", "shell", ref });648}649650pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {651    if (run_cmd) |cmd| {652        // sh -c so a multi-word command isn't treated as a single executable name.653        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });654    }655    return stream(io, machine, gpa, &.{ "nix", "develop" });656}657658pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {659    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });660}661662// --- Format ---663664pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {665    if (check) {666        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });667    }668    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });669}670671// --- Info ---672673pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {674    const r = try capture(gpa, io, machine, &.{"nixos-version"});675    defer gpa.free(r.stderr);676    if (r.exit_code != 0) {677        gpa.free(r.stdout);678        return error.ProcessFailed;679    }680    return r.stdout;681}682683pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {684    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });685    defer gpa.free(r.stderr);686    if (r.exit_code != 0) {687        gpa.free(r.stdout);688        return error.ProcessFailed;689    }690    return r.stdout;691}692693pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {694    const r = try capture(gpa, io, machine, &.{"uptime"});695    defer gpa.free(r.stderr);696    if (r.exit_code != 0) {697        gpa.free(r.stdout);698        return error.ProcessFailed;699    }700    return r.stdout;701}702703// --- Boot ---704705pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {706    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });707    defer gpa.free(r.stderr);708    defer gpa.free(r.stdout);709    if (r.exit_code != 0) return error.ProcessFailed;710    return parseBootEntries(gpa, r.stdout);711}712713fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {714    var entries: std.ArrayList(types.BootEntry) = .empty;715    var lines = std.mem.splitScalar(u8, output_str, '\n');716    while (lines.next()) |line| {717        const trimmed = std.mem.trim(u8, line, " \t\r");718        if (std.mem.startsWith(u8, trimmed, "title:")) {719            const title = std.mem.trim(u8, trimmed[6..], " \t");720            const current = std.mem.indexOf(u8, title, "(current)") != null;721            try entries.append(gpa, .{722                .title = try gpa.dupe(u8, title),723                .current = current,724            });725        }726    }727    return entries.toOwnedSlice(gpa);728}729730// --- Pkg info ---731732pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {733    return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });734}735736pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {737    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });738}739740pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {741    // A bare name ("ripgrep") isn't a valid installable; resolve via nixpkgs# like742    // `pkg path` does. -S -h gives closure size, human-readable. Output is743    // "<store-path>   <size>"; return just the size.744    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});745    defer gpa.free(ref);746    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref });747    defer gpa.free(r.stderr);748    defer gpa.free(r.stdout);749    if (r.exit_code != 0) return error.ProcessFailed;750751    const line = std.mem.trim(u8, r.stdout, " \t\n\r");752    var it = std.mem.tokenizeAny(u8, line, " \t");753    _ = it.next(); // store path754    const size = std.mem.trim(u8, it.rest(), " \t");755    if (size.len == 0) return error.ProcessFailed;756    return gpa.dupe(u8, size);757}758759pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {760    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });761}762763// --- Hash / Fetch ---764765pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {766    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });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}774775pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {776    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });777    defer gpa.free(r.stderr);778    if (r.exit_code != 0) {779        gpa.free(r.stdout);780        return error.ProcessFailed;781    }782    return r.stdout;783}784785// --- Pin ---786787pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {788    // Stub: full implementation would parse and edit flake.lock JSON789    // The pin/unpin flow works via nix flake update which regenerates flake.lock790}791792pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {793    if (line) |l| {794        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});795        defer gpa.free(line_arg);796        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });797    }798    return stream(io, &types.Machine{}, gpa, &.{ editor, path });799}800801pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {802    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});803    defer gpa.free(a_str);804    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});805    defer gpa.free(b_str);806    // On a tty, the child's own color is fine — stream it directly.807    if (output.colorEnabled()) {808        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });809    }810    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,811    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.812    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });813    defer gpa.free(r.stdout);814    defer gpa.free(r.stderr);815    const cleaned = try stripAnsi(gpa, r.stdout);816    defer gpa.free(cleaned);817    output.raw(cleaned);818    return r.exit_code;819}820821// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a822// child process's color when it writes ANSI unconditionally.823fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {824    var out: std.ArrayList(u8) = .empty;825    errdefer out.deinit(gpa);826    var i: usize = 0;827    while (i < input.len) {828        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {829            i += 2;830            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}831            if (i < input.len) i += 1; // consume the final byte832            continue;833        }834        try out.append(gpa, input[i]);835        i += 1;836    }837    return out.toOwnedSlice(gpa);838}839840test "stripAnsi removes CSI color sequences" {841    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");842    defer std.testing.allocator.free(cleaned);843    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);844}845846// --- Doctor checks ---847848pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {849    var checks: std.ArrayList(types.DoctorCheck) = .empty;850851    // Check nix daemon852    {853        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });854        defer gpa.free(r.stdout);855        defer gpa.free(r.stderr);856        const active = std.mem.indexOf(u8, r.stdout, "active") != null;857        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });858    }859860    // Check config syntax861    {862        const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });863        defer gpa.free(r.stdout);864        defer gpa.free(r.stderr);865        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });866    }867868    // Check channel869    {870        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });871        defer gpa.free(r.stdout);872        defer gpa.free(r.stderr);873        const has_channel = r.exit_code == 0 and r.stdout.len > 0;874        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });875    }876877    return checks.toOwnedSlice(gpa);878}879880// --- Log ---881882pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {883    const home = environ.get("HOME") orelse return error.FileNotFound;884    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});885    defer gpa.free(path);886    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;887    if (last == 0) return content;888889    // Collect non-empty lines, then keep only the final `last`. Slices point into890    // `content`, so copy them out before freeing it.891    var lines: std.ArrayList([]const u8) = .empty;892    defer lines.deinit(gpa);893    var it = std.mem.splitScalar(u8, content, '\n');894    while (it.next()) |line| {895        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;896        try lines.append(gpa, line);897    }898    if (lines.items.len <= last) return content;899900    var out: std.ArrayList(u8) = .empty;901    errdefer out.deinit(gpa);902    for (lines.items[lines.items.len - last ..]) |line| {903        try out.appendSlice(gpa, line);904        try out.append(gpa, '\n');905    }906    gpa.free(content);907    return out.toOwnedSlice(gpa);908}909910// nina is a one-shot process, so "did the last apply fail this session?" can't911// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the912// other ~/.nina-* state files. This lets a later successful apply earn the913// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.914pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {915    const home = environ.get("HOME") orelse return;916    var buf: [512]u8 = undefined;917    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;918    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;919    file.close(io);920}921922pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {923    const home = environ.get("HOME") orelse return false;924    var buf: [512]u8 = undefined;925    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;926    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {927        f.close(io);928        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};929        return true;930    } else |_| {931        return false;932    }933}934935pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {936    const home = environ.get("HOME") orelse return;937    var path_buf: [512]u8 = undefined;938    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;939    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch940        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);941    defer file.close(io);942    const size = file.length(io) catch 0;943    file.writePositionalAll(io, entry, size) catch {};944}945946// --- Update helpers ---947948// Fetch a URL with curl and return the response body. Caller must free.949// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.950pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {951    const argv = [_][]const u8{952        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,953    };954    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;955    defer gpa.free(result.stderr);956957    const marker = "\nHTTP_STATUS:";958    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {959        gpa.free(result.stdout);960        return error.NetworkError;961    };962    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");963    const status = std.fmt.parseInt(u16, status_str, 10) catch {964        gpa.free(result.stdout);965        return error.NetworkError;966    };967    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }968    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }969    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {970        gpa.free(result.stdout);971        return e;972    };973    gpa.free(result.stdout);974    return body;975}976977// Download a URL to a temp file. Returns the temp path (caller must gpa.free).978// The file is written to /tmp/nina-update-<pid> and left for the caller to use.979pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {980    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");981    errdefer gpa.free(tmp_path);982983    var child = std.process.spawn(io, .{984        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },985        .stdin = .close,986        .stdout = .close,987        .stderr = .inherit,988    }) catch return error.NetworkError;989    const term = child.wait(io) catch return error.NetworkError;990    switch (term) {991        .exited => |c| if (c != 0) return error.NetworkError,992        else => return error.NetworkError,993    }994    return tmp_path;995}996997// Get the current executable path into buf. Returns slice of buf.998pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {999    const len = try std.process.executablePath(io, buf);1000    return buf[0..len];1001}10021003// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1004// atomically install the binary to install_path. Errors: ChecksumMismatch,1005// AccessDenied (with error_info set), or underlying I/O errors.1006pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1007    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1008        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1009        return error.FileNotFound;1010    };1011    defer gpa.free(bytes);10121013    var hasher = std.crypto.hash.Blake3.init(.{});1014    hasher.update(bytes);1015    var raw: [32]u8 = undefined;1016    hasher.final(&raw);1017    const hex = std.fmt.bytesToHex(raw, .lower);1018    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;10191020    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1021    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1022        return error.NameTooLong;10231024    {1025        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1026            errors.error_info.setMessage("cannot write to {s}", .{install_path});1027            errors.error_info.setSuggestion("try: sudo nina update", .{});1028            return error.AccessDenied;1029        };1030        defer f.close(io);1031        f.writePositionalAll(io, bytes, 0) catch {1032            errors.error_info.setMessage("cannot write to {s}", .{install_path});1033            return error.AccessDenied;1034        };1035        try f.setPermissions(io, .fromMode(0o755));1036    }1037    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};10381039    if (comptime builtin.os.tag == .macos) {1040        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1041    }10421043    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1044        error.AccessDenied => {1045            errors.error_info.setMessage("cannot replace {s}", .{install_path});1046            errors.error_info.setSuggestion("try: sudo nina update", .{});1047            return error.AccessDenied;1048        },1049        else => return e,1050    };1051}10521053// --- Nix feature setup ---10541055pub const NixFeatureStatus = struct {1056    nix_command: bool = false,1057    flakes: bool = false,10581059    pub fn allEnabled(self: NixFeatureStatus) bool {1060        return self.nix_command and self.flakes;1061    }1062};10631064fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1065    var lines = std.mem.splitScalar(u8, conf, '\n');1066    while (lines.next()) |line| {1067        const trimmed = std.mem.trim(u8, line, " \t");1068        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1069        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1070        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1071    }1072}10731074pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1075    var status = NixFeatureStatus{};10761077    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1078        defer gpa.free(conf);1079        scanConfFeatures(conf, &status);1080    }10811082    if (environ.get("HOME")) |home| {1083        var buf: [512]u8 = undefined;1084        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1085        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1086            defer gpa.free(conf);1087            scanConfFeatures(conf, &status);1088        }1089    }10901091    return status;1092}10931094pub fn isNixOS(io: std.Io) bool {1095    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1096    file.close(io);1097    return true;1098}10991100// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.1101// Returns the path written (caller must free).1102pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1103    const home = environ.get("HOME") orelse {1104        errors.error_info.setMessage("HOME not set", .{});1105        return error.ConfigNotFound;1106    };11071108    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1109    defer gpa.free(dir_path);1110    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1111    errdefer gpa.free(file_path);11121113    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};11141115    const line = "experimental-features = nix-command flakes\n";1116    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1117        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1118        errors.error_info.setMessage("could not write {s}", .{file_path});1119        return error.FileNotFound;1120    });1121    defer file.close(io);11221123    const size = file.length(io) catch 0;1124    file.writePositionalAll(io, line, size) catch {1125        errors.error_info.setMessage("could not write {s}", .{file_path});1126        return error.FileNotFound;1127    };11281129    return file_path;1130}11311132// --- NixOS: declarative experimental-features ---1133//1134// On NixOS the permanent, declarative home for these flags is configuration.nix,1135// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves1136// the `nixos-rebuild switch` to the user.11371138pub const NIXOS_FEATURES_LINE =1139    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";11401141// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns1142// false on any read error so the caller still offers to add the line.1143pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1144    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1145    defer gpa.free(conf);1146    return std.mem.indexOf(u8, conf, "experimental-features") != null and1147        std.mem.indexOf(u8, conf, "nix-command") != null and1148        std.mem.indexOf(u8, conf, "flakes") != null;1149}11501151fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1152    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1153    return captureLocal(gpa, io, &.{ "sudo", "cat", path });1154}11551156// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix1157// (i.e. inside the top-level attribute set) and write it back via a single1158// `sudo cp`, which prompts for the password on the terminal. Returns an error1159// for the caller to fall back to printed manual instructions.1160pub fn appendFeaturesToNixosConfig(1161    gpa: std.mem.Allocator,1162    io: std.Io,1163    environ: *const std.process.Environ.Map,1164    path: []const u8,1165) !void {1166    const conf = readMaybeSudo(gpa, io, path) catch {1167        errors.error_info.setMessage("could not read {s}", .{path});1168        return error.ConfigNotFound;1169    };1170    defer gpa.free(conf);11711172    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared11731174    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1175        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1176        return error.MalformedConfig;1177    };11781179    const home = environ.get("HOME") orelse {1180        errors.error_info.setMessage("HOME not set", .{});1181        return error.ConfigNotFound;1182    };1183    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1184    defer gpa.free(tmp_path);11851186    var buf: std.ArrayList(u8) = .empty;1187    defer buf.deinit(gpa);1188    try buf.appendSlice(gpa, conf[0..brace]);1189    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1190    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");1191    try buf.appendSlice(gpa, "  ");1192    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1193    try buf.append(gpa, '\n');1194    try buf.appendSlice(gpa, conf[brace..]);11951196    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1197        errors.error_info.setMessage("could not write {s}", .{tmp_path});1198        return error.FileNotFound;1199    };1200    tmp.writePositionalAll(io, buf.items, 0) catch {1201        tmp.close(io);1202        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1203        errors.error_info.setMessage("could not write {s}", .{tmp_path});1204        return error.FileNotFound;1205    };1206    tmp.close(io);12071208    // Back up the existing config, then replace it — in one sudo call so the1209    // password is asked for at most once. Paths travel as positional args ($0,1210    // $1) to sidestep shell quoting.1211    const code = streamLocal(io, &.{1212        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1213    }) catch {1214        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1215        errors.error_info.setMessage("could not write {s}", .{path});1216        return error.ProcessFailed;1217    };1218    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1219    if (code != 0) {1220        errors.error_info.setMessage("sudo cp into {s} failed", .{path});1221        return error.ProcessFailed;1222    }1223}