exec.zig

64.1 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);7778    var child = std.process.spawn(io, .{79        .argv = argv,80        .stdin = .inherit,81        .stdout = .inherit,82        .stderr = .inherit,83        .environ_map = &env,84    }) catch |e| {85        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});86        return e;87    };8889    const term = child.wait(io) catch |e| {90        errors.error_info.setMessage("process wait failed", .{});91        return e;92    };9394    return switch (term) {95        .exited => |c| c,96        else => 1,97    };98}99100// Stream a local process with inherited stdio (no SSH routing — for nix commands).101pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 {102    output.flush();103    var child = std.process.spawn(io, .{104        .argv = cmd,105        .stdin = .inherit,106        .stdout = .inherit,107        .stderr = .inherit,108    }) catch |e| {109        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});110        return e;111    };112    const term = child.wait(io) catch {113        errors.error_info.setMessage("process wait failed", .{});114        return error.ProcessFailed;115    };116    return switch (term) {117        .exited => |c| c,118        else => 1,119    };120}121122// Run a process and capture output as a single string (no SSH routing — for local nix commands).123pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {124    const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;125    defer gpa.free(result.stderr);126    switch (result.term) {127        .exited => |c| if (c != 0) {128            gpa.free(result.stdout);129            return error.ProcessFailed;130        },131        else => {132            gpa.free(result.stdout);133            return error.ProcessFailed;134        },135    }136    return result.stdout;137}138139// Create a directory and its parents, best-effort. Shelling out to `mkdir -p`140// matches how the rest of exec.zig provisions config locations (~/.config/nix).141pub fn ensureDir(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) void {142    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir }) catch {};143}144145fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {146    if (machine.local) return cmd;147148    const host = machine.host orelse {149        errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});150        return error.SshFailed;151    };152153    var ssh: std.ArrayList([]const u8) = .empty;154    try ssh.append(gpa, "ssh");155    try ssh.append(gpa, "-o");156    try ssh.append(gpa, "BatchMode=yes");157    try ssh.append(gpa, "-o");158    try ssh.append(gpa, "StrictHostKeyChecking=accept-new");159    if (machine.ssh_key) |key| {160        try ssh.append(gpa, "-i");161        try ssh.append(gpa, key);162    }163    const addr = if (machine.user) |u|164        try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })165    else166        try gpa.dupe(u8, host);167    try ssh.append(gpa, addr);168    for (cmd) |arg| try ssh.append(gpa, arg);169    return ssh.toOwnedSlice(gpa);170}171172// --- NixOS rebuild ---173174// True if the machine's config dir holds a flake.nix. Only meaningful for a local175// machine — the file lives on the local filesystem. Remote flake detection would176// need an ssh round-trip; a remote flake at the default /etc/nixos needs no flag177// anyway, so we don't bother.178// True if `dir` contains a flake.nix (local filesystem check).179pub fn dirHasFlake(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) bool {180    const flake_path = std.fs.path.join(gpa, &.{ dir, "flake.nix" }) catch return false;181    defer gpa.free(flake_path);182    return pathExists(io, flake_path);183}184185pub fn configHasFlake(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {186    if (!machine.local) return false;187    return dirHasFlake(gpa, io, machine.config_path);188}189190// nixos-rebuild auto-detects /etc/nixos/flake.nix, so the --flake flag is only191// needed when the flake lives elsewhere. A flake at a non-default path must be192// passed explicitly or nixos-rebuild falls back to channels.193fn useFlakeFlag(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {194    return configHasFlake(gpa, io, machine) and !std.mem.eql(u8, machine.config_path, "/etc/nixos");195}196197fn nixosRebuildRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, flake: bool) !u8 {198    if (flake) {199        return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb, "--flake", machine.config_path });200    }201    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb });202}203204pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {205    const flake = useFlakeFlag(gpa, io, machine);206    if (flake) {207        output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});208    } else {209        output.printSubstep("nixos-rebuild switch", .{});210    }211    return nixosRebuildRun(io, machine, gpa, "switch", flake);212}213214pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {215    return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine));216}217218pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {219    return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine));220}221222// --- Generations ---223224// Read system-profile generations WITHOUT root. `nix-env --list-generations -p225// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user226// ("system.lock: Permission denied"). The generation symlinks themselves are227// world-readable, so list them directly: parse `system-N-link` names, take each228// link's own mtime for the date/time, and mark the one the `system` symlink229// points at as current. Output matches the `nix-env --list-generations` columns230// (num date time [current]) so parseGenerations is unchanged.231const GEN_LIST_SCRIPT =232    \\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 }'233;234235pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {236    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });237    defer gpa.free(r.stderr);238    defer gpa.free(r.stdout);239    if (r.exit_code != 0) return error.ProcessFailed;240    return parseGenerations(gpa, r.stdout);241}242243fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {244    var gens: std.ArrayList(types.GenerationInfo) = .empty;245    var lines = std.mem.splitScalar(u8, output_str, '\n');246    while (lines.next()) |line| {247        const trimmed = std.mem.trim(u8, line, " \t");248        if (trimmed.len == 0) continue;249        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");250        const num_str = parts.next() orelse continue;251        const date_str = parts.next() orelse continue;252        const time_str = parts.next() orelse continue;253        const rest = parts.rest();254        const current = std.mem.indexOf(u8, rest, "current") != null;255        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;256        try gens.append(gpa, .{257            .number = num,258            .date = try gpa.dupe(u8, date_str),259            .time = try gpa.dupe(u8, time_str),260            .current = current,261        });262    }263    return gens.toOwnedSlice(gpa);264}265266pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {267    const gens = try getGenerations(gpa, io, machine);268    defer gpa.free(gens);269    for (gens) |g| {270        if (g.current) return g.number;271    }272    return 0;273}274275pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {276    // Switch the system profile to generation n, then activate it (bootloader +277    // services). Without switch-to-configuration the change isn't applied.278    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 });279    defer gpa.free(cmd);280    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });281}282283pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {284    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });285}286287pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {288    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});289    defer gpa.free(n_str);290    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });291}292293pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {294    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });295}296297// --- Garbage collection ---298299pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {300    if (delete_old) {301        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });302    }303    // Keep the `keep` most recent system generations (+N deletes all but N),304    // then collect now-unreferenced store paths. `--delete-older-than` wants a305    // duration (e.g. 14d), not a generation count.306    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });307    defer gpa.free(cmd);308    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });309}310311// --- Channels ---312313pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {314    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });315    defer gpa.free(r.stderr);316    defer gpa.free(r.stdout);317    if (r.exit_code != 0) return error.ProcessFailed;318    return parseChannels(gpa, r.stdout);319}320321fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {322    var channels: std.ArrayList(types.ChannelInfo) = .empty;323    var lines = std.mem.splitScalar(u8, output_str, '\n');324    while (lines.next()) |line| {325        const trimmed = std.mem.trim(u8, line, " \t\r");326        if (trimmed.len == 0) continue;327        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;328        try channels.append(gpa, .{329            .name = try gpa.dupe(u8, trimmed[0..space]),330            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),331        });332    }333    return channels.toOwnedSlice(gpa);334}335336pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {337    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });338}339340pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {341    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });342}343344pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {345    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });346}347348// --- Services ---349350pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {351    const cmd: []const []const u8 = if (user)352        &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }353    else354        &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };355    const r = try capture(gpa, io, machine, cmd);356    defer gpa.free(r.stderr);357    defer gpa.free(r.stdout);358    if (r.exit_code != 0) return error.ProcessFailed;359    return parseServices(gpa, r.stdout);360}361362fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {363    var svcs: std.ArrayList(types.ServiceInfo) = .empty;364    var lines = std.mem.splitScalar(u8, output_str, '\n');365    while (lines.next()) |line| {366        const trimmed = std.mem.trim(u8, line, " \t\r");367        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines368        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");369        const name = parts.next() orelse continue;370        _ = parts.next(); // load371        const active_str = parts.next() orelse continue;372        const sub_str = parts.next() orelse "unknown";373374        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))375            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)376        else if (std.mem.eql(u8, active_str, "failed"))377            .failed378        else379            .inactive;380381        try svcs.append(gpa, .{382            .name = try gpa.dupe(u8, name),383            .state = state,384            .uptime = null,385        });386    }387    return svcs.toOwnedSlice(gpa);388}389390pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {391    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.392    // User services run under the caller's own systemd manager, so no sudo.393    if (user) {394        return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });395    }396    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });397}398399pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {400    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});401    defer gpa.free(n_str);402    if (user) {403        if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });404        return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });405    }406    if (follow) {407        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });408    }409    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });410}411412// --- Profile ---413414pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {415    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});416    defer gpa.free(pkg_ref);417    // `nix profile add` is the current verb; `install` is a deprecated alias that418    // prints a warning on modern nix.419    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });420}421422pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {423    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not424    // by flake ref — passing nixpkgs#ripgrep matches nothing.425    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });426}427428pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {429    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });430    defer gpa.free(r.stderr);431    if (r.exit_code != 0) return error.ProcessFailed;432    return r.stdout;433}434435// Machine-readable profile listing — caller parses elements -> name + version.436pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {437    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });438    defer gpa.free(r.stderr);439    if (r.exit_code != 0) {440        gpa.free(r.stdout);441        return error.ProcessFailed;442    }443    return r.stdout;444}445446// Returns the profile element name to pass to `nix profile remove/upgrade`447// (e.g. "nina" or "default"), or null if nina is not found. Caller owns the448// returned slice. A NixOS system-package install also resolves into /nix/store449// so the store path alone can't distinguish it from a profile install — the450// profile list can. A missing/empty profile (or no nix) returns null.451pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {452    const js = profileListJson(gpa, io, machine) catch return null;453    defer gpa.free(js);454    return profileJsonNinaElement(gpa, js);455}456457pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {458    const name = profileNinaElement(gpa, io, machine) orelse return false;459    gpa.free(name);460    return true;461}462463// True when a nix store path belongs to the nina package. Store paths have the464// form /nix/store/<32-char-hash>-<pname>-<version>[/<subpath>]. We check that465// the 33 chars after /nix/store/ are the hash+dash, and the pname that follows466// is exactly "nina" (followed by "-" or end-of-component).467fn storePathIsNina(path: []const u8) bool {468    const prefix = "/nix/store/";469    if (!std.mem.startsWith(u8, path, prefix)) return false;470    const rel = path[prefix.len..];471    // The store entry name ends at the first "/" (if any sub-path follows).472    const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];473    if (entry.len < 34) return false; // 32-char hash + dash + at least one char474    const pname_ver = entry[33..]; // skip hash + dash475    return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");476}477478// Pure parse of `nix profile list --json` for a nina element, returning its479// element name (the key to pass to `nix profile remove/upgrade`) or null.480// Newer nix (2.18+) keys elements by pname ("nina"). Older nix uses an array481// with an "attrPath" field. Tarball installs via the `default` output may use482// the key "default" instead of "nina"; we detect those via storePaths.483fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {484    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;485    defer parsed.deinit();486    const root = parsed.value;487    if (root != .object) return null;488    const elements = root.object.get("elements") orelse return null;489    switch (elements) {490        .object => |obj| {491            // Fast path: exact "nina" key (nix 2.18+ with nixpkgs#nina install).492            if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;493            // Fallback: scan storePaths. Handles tarball installs where the default494            // output is selected and nix names the element "default" (older nix) or495            // some other key derived from the attrPath rather than the pname.496            var it = obj.iterator();497            while (it.next()) |kv| {498                const val = kv.value_ptr.*;499                if (val != .object) continue;500                const sps = val.object.get("storePaths") orelse continue;501                if (sps != .array) continue;502                for (sps.array.items) |sp| {503                    if (sp == .string and storePathIsNina(sp.string))504                        return gpa.dupe(u8, kv.key_ptr.*) catch null;505                }506            }507            return null;508        },509        .array => |arr| {510            // Older nix array format. Element name is the last component of attrPath.511            for (arr.items) |el| {512                if (el != .object) continue;513                const ap = el.object.get("attrPath") orelse continue;514                if (ap != .string) continue;515                if (std.mem.eql(u8, ap.string, "nina") or516                    std.mem.endsWith(u8, ap.string, ".nina"))517                    return gpa.dupe(u8, "nina") catch null;518                // Tarball default-output install: attrPath ends in ".default" but519                // storePaths point to nina. Return "default" as the element name.520                const sps = el.object.get("storePaths") orelse continue;521                if (sps != .array) continue;522                for (sps.array.items) |sp| {523                    if (sp != .string) continue;524                    if (!storePathIsNina(sp.string)) continue;525                    const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;526                    const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;527                    return gpa.dupe(u8, el_name) catch null;528                }529            }530            return null;531        },532        else => return null,533    }534}535536test "profileJsonNinaElement finds element name from profile JSON" {537    const a = std.testing.allocator;538539    // Newer nix: elements keyed by pname. "nina" key present.540    const named =541        \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},542        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}543    ;544    const r1 = profileJsonNinaElement(a, named);545    defer if (r1) |n| a.free(n);546    try std.testing.expectEqualStrings("nina", r1.?);547548    // Tarball install via default output: element keyed as "default", storePath is nina.549    const default_key =550        \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}551    ;552    const r2 = profileJsonNinaElement(a, default_key);553    defer if (r2) |n| a.free(n);554    try std.testing.expectEqualStrings("default", r2.?);555556    // Decoy: storePath of another package contains "nina" as a substring but is not nina.557    const decoy =558        \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}559    ;560    const r3 = profileJsonNinaElement(a, decoy);561    try std.testing.expectEqual(@as(?[]const u8, null), r3);562563    // Older nix array schema, attrPath ending in ".nina".564    const arr =565        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}566    ;567    const r4 = profileJsonNinaElement(a, arr);568    defer if (r4) |n| a.free(n);569    try std.testing.expectEqualStrings("nina", r4.?);570571    // Older nix array schema, tarball default-output install.572    const arr_default =573        \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}574    ;575    const r5 = profileJsonNinaElement(a, arr_default);576    defer if (r5) |n| a.free(n);577    try std.testing.expectEqualStrings("default", r5.?);578579    // Empty / malformed → null.580    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));581    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));582}583584// The store paths that make up the running system environment. Each reference is585// a <hash>-<name>-<version> path, so the caller can list system packages with586// versions — there is no cleaner per-package list for environment.systemPackages.587pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {588    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });589    defer gpa.free(r.stderr);590    if (r.exit_code != 0) {591        gpa.free(r.stdout);592        return error.ProcessFailed;593    }594    return r.stdout;595}596597pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {598    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });599}600601// --- Store ---602603pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {604    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });605}606607pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {608    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });609}610611pub const SystemStatus = struct { size: []u8, age: []u8 };612613// One read-only pass for `nina status`: the current system's closure size (a614// single `path-info -S` of /run/current-system — fast, unlike -S over the whole615// store) and seconds since the system profile was last switched (its symlink616// mtime). Both are world-readable; no root needed.617const STATUS_SCRIPT =618    \\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} ))"619;620621pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {622    const unknown = SystemStatus{623        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },624        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },625    };626    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;627    defer gpa.free(r.stdout);628    defer gpa.free(r.stderr);629    if (r.exit_code != 0) return unknown;630631    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");632    const sz_str = it.next() orelse return unknown;633    const age_str = it.next() orelse return unknown;634    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;635    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;636637    gpa.free(unknown.size);638    gpa.free(unknown.age);639    return .{640        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),641        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),642    };643}644645// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A646// one-word health signal; exits non-zero when degraded, so we read stdout, not647// the code. Caller owns the returned slice.648pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {649    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch650        return gpa.dupe(u8, "unknown");651    defer gpa.free(r.stderr);652    const state = std.mem.trim(u8, r.stdout, " \t\n\r");653    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");654    gpa.free(r.stdout);655    return owned;656}657658fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {659    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});660    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});661    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});662    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});663}664665pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {666    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });667}668669pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {670    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)671    // graph work that takes minutes on a real store (59k+ paths) and hangs the672    // command. We don't need closures: `--all --json` (no -S) carries each path's673    // own narSize, so one fast pass gives the path count and the summed store size.674    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.675    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.676    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });677    defer gpa.free(pi.stdout);678    defer gpa.free(pi.stderr);679680    const scan = scanStoreJson(pi.stdout);681    const total_owned = try humanSize(gpa, scan.total_bytes);682683    return .{684        .total_size = total_owned,685        .live_paths = scan.count,686        .reclaimable_paths = 0,687    };688}689690const StoreScan = struct { count: u64, total_bytes: u64 };691692// One linear pass over `nix path-info --json`: each path object has exactly one693// "narSize": field, so counting them gives the true path count and summing the694// values gives the total store size — no per-path closure walk.695fn scanStoreJson(json_str: []const u8) StoreScan {696    const needle = "\"narSize\":";697    var count: u64 = 0;698    var total: u64 = 0;699    var i: usize = 0;700    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {701        var j = pos + needle.len;702        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}703        var val: u64 = 0;704        var any = false;705        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {706            val = val * 10 + (json_str[j] - '0');707            any = true;708        }709        if (any) {710            count += 1;711            total += val;712        }713        i = j;714    }715    return .{ .count = count, .total_bytes = total };716}717718fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {719    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };720    var val: f64 = @floatFromInt(bytes);721    var unit: usize = 0;722    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;723    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });724    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });725}726727pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {728    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the729    // flake registry), not a flake in the current directory.730    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});731    defer gpa.free(expr);732    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });733    defer gpa.free(r.stderr);734    if (r.exit_code != 0) {735        gpa.free(r.stdout);736        return error.ProcessFailed;737    }738    return r.stdout;739}740741// --- Flake ---742743pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {744    if (input) |inp| {745        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });746    }747    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });748}749750// Update flake inputs for the flake living in `dir` (the config dir). `nix flake751// update` operates on the flake in the working directory, so we cd there first.752// Used by `nina upgrade` on a flake system in place of nix-channel --update.753pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {754    return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });755}756757pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {758    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });759}760761pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {762    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });763}764765pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {766    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });767}768769pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {770    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });771}772773pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {774    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });775    defer gpa.free(r.stderr);776    if (r.exit_code != 0) {777        gpa.free(r.stdout);778        return error.ProcessFailed;779    }780    return r.stdout;781}782783// --- Build / Run / Develop ---784785pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {786    if (attr) |a| {787        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});788        defer gpa.free(ref);789        return stream(io, machine, gpa, &.{ "nix", "build", ref });790    }791    return stream(io, machine, gpa, &.{ "nix", "build" });792}793794pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {795    // nix run always gets --no-write-lock-file for remote URLs796    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");797    if (is_url) {798        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });799    }800    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.801    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {802        return stream(io, machine, gpa, &.{ "nix", "run", pkg });803    }804    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});805    defer gpa.free(ref);806    return stream(io, machine, gpa, &.{ "nix", "run", ref });807}808809pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {810    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});811    defer gpa.free(ref);812    return stream(io, machine, gpa, &.{ "nix", "shell", ref });813}814815pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {816    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});817    defer gpa.free(ref);818    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});819    defer gpa.free(ps1);820    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);821}822823pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {824    if (run_cmd) |cmd| {825        // sh -c so a multi-word command isn't treated as a single executable name.826        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });827    }828    return stream(io, machine, gpa, &.{ "nix", "develop" });829}830831pub 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 {832    if (run_cmd) |cmd| {833        // sh -c so a multi-word command isn't treated as a single executable name.834        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });835    }836    return streamEnv(io, machine, gpa, &.{ "nix", "develop" }, base_env, "(nina: dev) -> ");837}838839pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {840    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });841}842843// --- Format ---844845pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {846    if (check) {847        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });848    }849    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });850}851852// --- Info ---853854pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {855    const r = try capture(gpa, io, machine, &.{"nixos-version"});856    defer gpa.free(r.stderr);857    if (r.exit_code != 0) {858        gpa.free(r.stdout);859        return error.ProcessFailed;860    }861    return r.stdout;862}863864pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {865    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });866    defer gpa.free(r.stderr);867    if (r.exit_code != 0) {868        gpa.free(r.stdout);869        return error.ProcessFailed;870    }871    return r.stdout;872}873874pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {875    const r = try capture(gpa, io, machine, &.{"uptime"});876    defer gpa.free(r.stderr);877    if (r.exit_code != 0) {878        gpa.free(r.stdout);879        return error.ProcessFailed;880    }881    return r.stdout;882}883884// --- Boot ---885886pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {887    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });888    defer gpa.free(r.stderr);889    defer gpa.free(r.stdout);890    if (r.exit_code != 0) return error.ProcessFailed;891    return parseBootEntries(gpa, r.stdout);892}893894fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {895    var entries: std.ArrayList(types.BootEntry) = .empty;896    var lines = std.mem.splitScalar(u8, output_str, '\n');897    while (lines.next()) |line| {898        const trimmed = std.mem.trim(u8, line, " \t\r");899        if (std.mem.startsWith(u8, trimmed, "title:")) {900            const title = std.mem.trim(u8, trimmed[6..], " \t");901            const current = std.mem.indexOf(u8, title, "(current)") != null;902            try entries.append(gpa, .{903                .title = try gpa.dupe(u8, title),904                .current = current,905            });906        }907    }908    return entries.toOwnedSlice(gpa);909}910911// --- Pkg info ---912913pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {914    return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });915}916917pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {918    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });919}920921pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {922    // A bare name ("ripgrep") isn't a valid installable; resolve via nixpkgs# like923    // `pkg path` does. -S -h gives closure size, human-readable. Output is924    // "<store-path>   <size>"; return just the size.925    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});926    defer gpa.free(ref);927    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref });928    defer gpa.free(r.stderr);929    defer gpa.free(r.stdout);930    if (r.exit_code != 0) return error.ProcessFailed;931932    const line = std.mem.trim(u8, r.stdout, " \t\n\r");933    var it = std.mem.tokenizeAny(u8, line, " \t");934    _ = it.next(); // store path935    const size = std.mem.trim(u8, it.rest(), " \t");936    if (size.len == 0) return error.ProcessFailed;937    return gpa.dupe(u8, size);938}939940pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {941    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });942}943944// --- Hash / Fetch ---945946pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {947    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });948    defer gpa.free(r.stderr);949    if (r.exit_code != 0) {950        gpa.free(r.stdout);951        return error.ProcessFailed;952    }953    return r.stdout;954}955956pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {957    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });958    defer gpa.free(r.stderr);959    if (r.exit_code != 0) {960        gpa.free(r.stdout);961        return error.ProcessFailed;962    }963    return r.stdout;964}965966// --- Pin ---967968pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {969    // Stub: full implementation would parse and edit flake.lock JSON970    // The pin/unpin flow works via nix flake update which regenerates flake.lock971}972973pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {974    if (line) |l| {975        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});976        defer gpa.free(line_arg);977        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });978    }979    return stream(io, &types.Machine{}, gpa, &.{ editor, path });980}981982pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {983    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});984    defer gpa.free(a_str);985    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});986    defer gpa.free(b_str);987    // On a tty, the child's own color is fine — stream it directly.988    if (output.colorEnabled()) {989        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });990    }991    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,992    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.993    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });994    defer gpa.free(r.stdout);995    defer gpa.free(r.stderr);996    const cleaned = try stripAnsi(gpa, r.stdout);997    defer gpa.free(cleaned);998    output.raw(cleaned);999    return r.exit_code;1000}10011002// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a1003// child process's color when it writes ANSI unconditionally.1004fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1005    var out: std.ArrayList(u8) = .empty;1006    errdefer out.deinit(gpa);1007    var i: usize = 0;1008    while (i < input.len) {1009        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1010            i += 2;1011            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1012            if (i < input.len) i += 1; // consume the final byte1013            continue;1014        }1015        try out.append(gpa, input[i]);1016        i += 1;1017    }1018    return out.toOwnedSlice(gpa);1019}10201021test "stripAnsi removes CSI color sequences" {1022    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1023    defer std.testing.allocator.free(cleaned);1024    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1025}10261027// --- Doctor checks ---10281029pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1030    var checks: std.ArrayList(types.DoctorCheck) = .empty;10311032    // Check nix daemon1033    {1034        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1035        defer gpa.free(r.stdout);1036        defer gpa.free(r.stderr);1037        const active = std.mem.indexOf(u8, r.stdout, "active") != null;1038        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1039    }10401041    // Check config syntax. Flake-aware like apply/upgrade: on a flake system a1042    // plain `nixos-rebuild dry-build` evaluates <nixpkgs/nixos> + <nixos-config>1043    // (channel style) and fails, so pass --flake when the config dir has one.1044    {1045        const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1046            &.{ "sudo", "nixos-rebuild", "dry-build", "--flake", machine.config_path }1047        else1048            &.{ "sudo", "nixos-rebuild", "dry-build" };1049        const r = try capture(gpa, io, machine, argv);1050        defer gpa.free(r.stdout);1051        defer gpa.free(r.stderr);1052        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1053    }10541055    // Check channel1056    {1057        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1058        defer gpa.free(r.stdout);1059        defer gpa.free(r.stderr);1060        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1061        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1062    }10631064    return checks.toOwnedSlice(gpa);1065}10661067// --- Home Manager ---1068//1069// Home Manager has three usage modes. nina detects which one is in play before1070// any `home` command so it can either drive the standalone CLI or redirect the1071// user to `nina apply` (when HM is a NixOS/flake module activated by rebuild).10721073pub const HomeManagerMode = enum {1074    // home-manager binary on PATH — manages the user env on its own.1075    standalone,1076    // No binary, but a home.nix exists — HM is a NixOS/flake module rebuilt by1077    // nixos-rebuild. `nina home apply` redirects to `nina apply`.1078    module,1079    none,1080};10811082fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1083    const home = environ.get("HOME") orelse return null;1084    return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1085}10861087// Path to the standalone home.nix. Caller frees.1088pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1089    const dir = homeConfigDir(gpa, environ) orelse return null;1090    defer gpa.free(dir);1091    return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1092}10931094pub fn pathExists(io: std.Io, path: []const u8) bool {1095    const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1096    f.close(io);1097    return true;1098}10991100// `command -v <name>` — true if the binary resolves on PATH. Silent (captured),1101// unlike streamLocal which would inherit stdio.1102fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1103    var buf: [256]u8 = undefined;1104    const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1105    const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1106    defer gpa.free(r.stdout);1107    defer gpa.free(r.stderr);1108    return switch (r.term) {1109        .exited => |code| code == 0,1110        else => false,1111    };1112}11131114pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1115    if (commandExists(gpa, io, "home-manager")) return .standalone;1116    if (homeNixPath(gpa, environ)) |p| {1117        defer gpa.free(p);1118        if (pathExists(io, p)) return .module;1119    }1120    return .none;1121}11221123// If the home-manager config dir holds a flake.nix, returns the flake ref1124// "<dir>#<user>" for `home-manager switch --flake`. Username comes from $USER.1125// Caller frees. null when there's no flake.nix (channel-based home config).1126pub fn homeFlakeRef(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1127    const dir = homeConfigDir(gpa, environ) orelse return null;1128    defer gpa.free(dir);1129    const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch return null;1130    defer gpa.free(flake);1131    if (!pathExists(io, flake)) return null;1132    const user = environ.get("USER") orelse "default";1133    return std.fmt.allocPrint(gpa, "{s}#{s}", .{ dir, user }) catch null;1134}11351136pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1137    return stream(io, machine, gpa, &.{ "home-manager", "switch" });1138}11391140pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8) !u8 {1141    return stream(io, machine, gpa, &.{ "home-manager", "switch", "--flake", flake_ref });1142}11431144// home-manager has no system-profile rollback; it re-activates the previous1145// generation via `switch --rollback`.1146pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1147    return stream(io, machine, gpa, &.{ "home-manager", "switch", "--rollback" });1148}11491150// Build (and validate) the home config without activating it — used by `home1151// check` and `home apply --dry`.1152pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1153    return stream(io, machine, gpa, &.{ "home-manager", "build" });1154}11551156pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1157    const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1158    defer gpa.free(r.stderr);1159    if (r.exit_code != 0) {1160        gpa.free(r.stdout);1161        return error.ProcessFailed;1162    }1163    return r.stdout;1164}11651166// Store paths referenced by a home generation — used to list managed packages.1167pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1168    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1169    defer gpa.free(r.stderr);1170    if (r.exit_code != 0) {1171        gpa.free(r.stdout);1172        return error.ProcessFailed;1173    }1174    return r.stdout;1175}11761177// diff-closures between two arbitrary store paths (home generations), mirroring1178// diffClosures' tty/piped color handling.1179pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1180    if (output.colorEnabled()) {1181        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1182    }1183    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1184    defer gpa.free(r.stdout);1185    defer gpa.free(r.stderr);1186    const cleaned = try stripAnsi(gpa, r.stdout);1187    defer gpa.free(cleaned);1188    output.raw(cleaned);1189    return r.exit_code;1190}11911192// --- Log ---11931194pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1195    const home = environ.get("HOME") orelse return error.FileNotFound;1196    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1197    defer gpa.free(path);1198    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1199    if (last == 0) return content;12001201    // Collect non-empty lines, then keep only the final `last`. Slices point into1202    // `content`, so copy them out before freeing it.1203    var lines: std.ArrayList([]const u8) = .empty;1204    defer lines.deinit(gpa);1205    var it = std.mem.splitScalar(u8, content, '\n');1206    while (it.next()) |line| {1207        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1208        try lines.append(gpa, line);1209    }1210    if (lines.items.len <= last) return content;12111212    var out: std.ArrayList(u8) = .empty;1213    errdefer out.deinit(gpa);1214    for (lines.items[lines.items.len - last ..]) |line| {1215        try out.appendSlice(gpa, line);1216        try out.append(gpa, '\n');1217    }1218    gpa.free(content);1219    return out.toOwnedSlice(gpa);1220}12211222// nina is a one-shot process, so "did the last apply fail this session?" can't1223// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1224// other ~/.nina-* state files. This lets a later successful apply earn the1225// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1226pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1227    const home = environ.get("HOME") orelse return;1228    var buf: [512]u8 = undefined;1229    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1230    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1231    file.close(io);1232}12331234pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1235    const home = environ.get("HOME") orelse return false;1236    var buf: [512]u8 = undefined;1237    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1238    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1239        f.close(io);1240        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1241        return true;1242    } else |_| {1243        return false;1244    }1245}12461247pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1248    const home = environ.get("HOME") orelse return;1249    var path_buf: [512]u8 = undefined;1250    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1251    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1252        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1253    defer file.close(io);1254    const size = file.length(io) catch 0;1255    file.writePositionalAll(io, entry, size) catch {};1256}12571258// --- Update helpers ---12591260// Fetch a URL with curl and return the response body. Caller must free.1261// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.1262pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1263    const argv = [_][]const u8{1264        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1265    };1266    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1267    defer gpa.free(result.stderr);12681269    const marker = "\nHTTP_STATUS:";1270    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1271        gpa.free(result.stdout);1272        return error.NetworkError;1273    };1274    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1275    const status = std.fmt.parseInt(u16, status_str, 10) catch {1276        gpa.free(result.stdout);1277        return error.NetworkError;1278    };1279    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1280    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1281    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1282        gpa.free(result.stdout);1283        return e;1284    };1285    gpa.free(result.stdout);1286    return body;1287}12881289// Download a URL to a temp file. Returns the temp path (caller must gpa.free).1290// The file is written to /tmp/nina-update-<pid> and left for the caller to use.1291pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1292    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1293    errdefer gpa.free(tmp_path);12941295    var child = std.process.spawn(io, .{1296        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1297        .stdin = .close,1298        .stdout = .close,1299        .stderr = .inherit,1300    }) catch return error.NetworkError;1301    const term = child.wait(io) catch return error.NetworkError;1302    switch (term) {1303        .exited => |c| if (c != 0) return error.NetworkError,1304        else => return error.NetworkError,1305    }1306    return tmp_path;1307}13081309// Get the current executable path into buf. Returns slice of buf.1310pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1311    const len = try std.process.executablePath(io, buf);1312    return buf[0..len];1313}13141315// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1316// atomically install the binary to install_path. Errors: ChecksumMismatch,1317// AccessDenied (with error_info set), or underlying I/O errors.1318pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1319    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1320        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1321        return error.FileNotFound;1322    };1323    defer gpa.free(bytes);13241325    var hasher = std.crypto.hash.Blake3.init(.{});1326    hasher.update(bytes);1327    var raw: [32]u8 = undefined;1328    hasher.final(&raw);1329    const hex = std.fmt.bytesToHex(raw, .lower);1330    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;13311332    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1333    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1334        return error.NameTooLong;13351336    {1337        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1338            errors.error_info.setMessage("cannot write to {s}", .{install_path});1339            errors.error_info.setSuggestion("try: sudo nina update", .{});1340            return error.AccessDenied;1341        };1342        defer f.close(io);1343        f.writePositionalAll(io, bytes, 0) catch {1344            errors.error_info.setMessage("cannot write to {s}", .{install_path});1345            return error.AccessDenied;1346        };1347        try f.setPermissions(io, .fromMode(0o755));1348    }1349    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};13501351    if (comptime builtin.os.tag == .macos) {1352        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1353    }13541355    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1356        error.AccessDenied => {1357            errors.error_info.setMessage("cannot replace {s}", .{install_path});1358            errors.error_info.setSuggestion("try: sudo nina update", .{});1359            return error.AccessDenied;1360        },1361        else => return e,1362    };1363}13641365// --- Nix feature setup ---13661367pub const NixFeatureStatus = struct {1368    nix_command: bool = false,1369    flakes: bool = false,13701371    pub fn allEnabled(self: NixFeatureStatus) bool {1372        return self.nix_command and self.flakes;1373    }1374};13751376fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1377    var lines = std.mem.splitScalar(u8, conf, '\n');1378    while (lines.next()) |line| {1379        const trimmed = std.mem.trim(u8, line, " \t");1380        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1381        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1382        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1383    }1384}13851386pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1387    var status = NixFeatureStatus{};13881389    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1390        defer gpa.free(conf);1391        scanConfFeatures(conf, &status);1392    }13931394    if (environ.get("HOME")) |home| {1395        var buf: [512]u8 = undefined;1396        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1397        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1398            defer gpa.free(conf);1399            scanConfFeatures(conf, &status);1400        }1401    }14021403    return status;1404}14051406pub fn isNixOS(io: std.Io) bool {1407    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1408    file.close(io);1409    return true;1410}14111412// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.1413// Returns the path written (caller must free).1414pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1415    const home = environ.get("HOME") orelse {1416        errors.error_info.setMessage("HOME not set", .{});1417        return error.ConfigNotFound;1418    };14191420    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1421    defer gpa.free(dir_path);1422    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1423    errdefer gpa.free(file_path);14241425    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};14261427    const line = "experimental-features = nix-command flakes\n";1428    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1429        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1430        errors.error_info.setMessage("could not write {s}", .{file_path});1431        return error.FileNotFound;1432    });1433    defer file.close(io);14341435    const size = file.length(io) catch 0;1436    file.writePositionalAll(io, line, size) catch {1437        errors.error_info.setMessage("could not write {s}", .{file_path});1438        return error.FileNotFound;1439    };14401441    return file_path;1442}14431444// --- NixOS: declarative experimental-features ---1445//1446// On NixOS the permanent, declarative home for these flags is configuration.nix,1447// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves1448// the `nixos-rebuild switch` to the user.14491450pub const NIXOS_FEATURES_LINE =1451    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";14521453// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns1454// false on any read error so the caller still offers to add the line.1455pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1456    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1457    defer gpa.free(conf);1458    return std.mem.indexOf(u8, conf, "experimental-features") != null and1459        std.mem.indexOf(u8, conf, "nix-command") != null and1460        std.mem.indexOf(u8, conf, "flakes") != null;1461}14621463fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1464    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1465    return captureLocal(gpa, io, &.{ "sudo", "cat", path });1466}14671468// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix1469// (i.e. inside the top-level attribute set) and write it back via a single1470// `sudo cp`, which prompts for the password on the terminal. Returns an error1471// for the caller to fall back to printed manual instructions.1472pub fn appendFeaturesToNixosConfig(1473    gpa: std.mem.Allocator,1474    io: std.Io,1475    environ: *const std.process.Environ.Map,1476    path: []const u8,1477) !void {1478    const conf = readMaybeSudo(gpa, io, path) catch {1479        errors.error_info.setMessage("could not read {s}", .{path});1480        return error.ConfigNotFound;1481    };1482    defer gpa.free(conf);14831484    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared14851486    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1487        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1488        return error.MalformedConfig;1489    };14901491    const home = environ.get("HOME") orelse {1492        errors.error_info.setMessage("HOME not set", .{});1493        return error.ConfigNotFound;1494    };1495    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1496    defer gpa.free(tmp_path);14971498    var buf: std.ArrayList(u8) = .empty;1499    defer buf.deinit(gpa);1500    try buf.appendSlice(gpa, conf[0..brace]);1501    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1502    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");1503    try buf.appendSlice(gpa, "  ");1504    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1505    try buf.append(gpa, '\n');1506    try buf.appendSlice(gpa, conf[brace..]);15071508    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1509        errors.error_info.setMessage("could not write {s}", .{tmp_path});1510        return error.FileNotFound;1511    };1512    tmp.writePositionalAll(io, buf.items, 0) catch {1513        tmp.close(io);1514        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1515        errors.error_info.setMessage("could not write {s}", .{tmp_path});1516        return error.FileNotFound;1517    };1518    tmp.close(io);15191520    // Back up the existing config, then replace it — in one sudo call so the1521    // password is asked for at most once. Paths travel as positional args ($0,1522    // $1) to sidestep shell quoting.1523    const code = streamLocal(io, &.{1524        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1525    }) catch {1526        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1527        errors.error_info.setMessage("could not write {s}", .{path});1528        return error.ProcessFailed;1529    };1530    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1531    if (code != 0) {1532        errors.error_info.setMessage("sudo cp into {s} failed", .{path});1533        return error.ProcessFailed;1534    }1535}