exec.zig

56.3 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 ---173174pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {175    const cmd = &.{ "sudo", "nixos-rebuild", "switch" };176    output.printSubstep("nixos-rebuild switch", .{});177    return stream(io, machine, gpa, cmd);178}179180pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {181    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "dry-activate" });182}183184pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {185    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "build" });186}187188// --- Generations ---189190// Read system-profile generations WITHOUT root. `nix-env --list-generations -p191// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user192// ("system.lock: Permission denied"). The generation symlinks themselves are193// world-readable, so list them directly: parse `system-N-link` names, take each194// link's own mtime for the date/time, and mark the one the `system` symlink195// points at as current. Output matches the `nix-env --list-generations` columns196// (num date time [current]) so parseGenerations is unchanged.197const GEN_LIST_SCRIPT =198    \\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 }'199;200201pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {202    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });203    defer gpa.free(r.stderr);204    defer gpa.free(r.stdout);205    if (r.exit_code != 0) return error.ProcessFailed;206    return parseGenerations(gpa, r.stdout);207}208209fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {210    var gens: std.ArrayList(types.GenerationInfo) = .empty;211    var lines = std.mem.splitScalar(u8, output_str, '\n');212    while (lines.next()) |line| {213        const trimmed = std.mem.trim(u8, line, " \t");214        if (trimmed.len == 0) continue;215        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");216        const num_str = parts.next() orelse continue;217        const date_str = parts.next() orelse continue;218        const time_str = parts.next() orelse continue;219        const rest = parts.rest();220        const current = std.mem.indexOf(u8, rest, "current") != null;221        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;222        try gens.append(gpa, .{223            .number = num,224            .date = try gpa.dupe(u8, date_str),225            .time = try gpa.dupe(u8, time_str),226            .current = current,227        });228    }229    return gens.toOwnedSlice(gpa);230}231232pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {233    const gens = try getGenerations(gpa, io, machine);234    defer gpa.free(gens);235    for (gens) |g| {236        if (g.current) return g.number;237    }238    return 0;239}240241pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {242    // Switch the system profile to generation n, then activate it (bootloader +243    // services). Without switch-to-configuration the change isn't applied.244    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 });245    defer gpa.free(cmd);246    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });247}248249pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {250    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });251}252253pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {254    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});255    defer gpa.free(n_str);256    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });257}258259pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {260    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });261}262263// --- Garbage collection ---264265pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {266    if (delete_old) {267        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });268    }269    // Keep the `keep` most recent system generations (+N deletes all but N),270    // then collect now-unreferenced store paths. `--delete-older-than` wants a271    // duration (e.g. 14d), not a generation count.272    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });273    defer gpa.free(cmd);274    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });275}276277// --- Channels ---278279pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {280    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });281    defer gpa.free(r.stderr);282    defer gpa.free(r.stdout);283    if (r.exit_code != 0) return error.ProcessFailed;284    return parseChannels(gpa, r.stdout);285}286287fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {288    var channels: std.ArrayList(types.ChannelInfo) = .empty;289    var lines = std.mem.splitScalar(u8, output_str, '\n');290    while (lines.next()) |line| {291        const trimmed = std.mem.trim(u8, line, " \t\r");292        if (trimmed.len == 0) continue;293        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;294        try channels.append(gpa, .{295            .name = try gpa.dupe(u8, trimmed[0..space]),296            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),297        });298    }299    return channels.toOwnedSlice(gpa);300}301302pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {303    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });304}305306pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {307    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });308}309310pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {311    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });312}313314// --- Services ---315316pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {317    const cmd: []const []const u8 = if (user)318        &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }319    else320        &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };321    const r = try capture(gpa, io, machine, cmd);322    defer gpa.free(r.stderr);323    defer gpa.free(r.stdout);324    if (r.exit_code != 0) return error.ProcessFailed;325    return parseServices(gpa, r.stdout);326}327328fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {329    var svcs: std.ArrayList(types.ServiceInfo) = .empty;330    var lines = std.mem.splitScalar(u8, output_str, '\n');331    while (lines.next()) |line| {332        const trimmed = std.mem.trim(u8, line, " \t\r");333        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines334        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");335        const name = parts.next() orelse continue;336        _ = parts.next(); // load337        const active_str = parts.next() orelse continue;338        const sub_str = parts.next() orelse "unknown";339340        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))341            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)342        else if (std.mem.eql(u8, active_str, "failed"))343            .failed344        else345            .inactive;346347        try svcs.append(gpa, .{348            .name = try gpa.dupe(u8, name),349            .state = state,350            .uptime = null,351        });352    }353    return svcs.toOwnedSlice(gpa);354}355356pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {357    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.358    // User services run under the caller's own systemd manager, so no sudo.359    if (user) {360        return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });361    }362    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });363}364365pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {366    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});367    defer gpa.free(n_str);368    if (user) {369        if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });370        return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });371    }372    if (follow) {373        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });374    }375    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });376}377378// --- Profile ---379380pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {381    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});382    defer gpa.free(pkg_ref);383    // `nix profile add` is the current verb; `install` is a deprecated alias that384    // prints a warning on modern nix.385    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });386}387388pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {389    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not390    // by flake ref — passing nixpkgs#ripgrep matches nothing.391    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });392}393394pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {395    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });396    defer gpa.free(r.stderr);397    if (r.exit_code != 0) return error.ProcessFailed;398    return r.stdout;399}400401// Machine-readable profile listing — caller parses elements -> name + version.402pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {403    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });404    defer gpa.free(r.stderr);405    if (r.exit_code != 0) {406        gpa.free(r.stdout);407        return error.ProcessFailed;408    }409    return r.stdout;410}411412// Returns the profile element name to pass to `nix profile remove/upgrade`413// (e.g. "nina" or "default"), or null if nina is not found. Caller owns the414// returned slice. A NixOS system-package install also resolves into /nix/store415// so the store path alone can't distinguish it from a profile install — the416// profile list can. A missing/empty profile (or no nix) returns null.417pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {418    const js = profileListJson(gpa, io, machine) catch return null;419    defer gpa.free(js);420    return profileJsonNinaElement(gpa, js);421}422423pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {424    const name = profileNinaElement(gpa, io, machine) orelse return false;425    gpa.free(name);426    return true;427}428429// True when a nix store path belongs to the nina package. Store paths have the430// form /nix/store/<32-char-hash>-<pname>-<version>[/<subpath>]. We check that431// the 33 chars after /nix/store/ are the hash+dash, and the pname that follows432// is exactly "nina" (followed by "-" or end-of-component).433fn storePathIsNina(path: []const u8) bool {434    const prefix = "/nix/store/";435    if (!std.mem.startsWith(u8, path, prefix)) return false;436    const rel = path[prefix.len..];437    // The store entry name ends at the first "/" (if any sub-path follows).438    const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];439    if (entry.len < 34) return false; // 32-char hash + dash + at least one char440    const pname_ver = entry[33..]; // skip hash + dash441    return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");442}443444// Pure parse of `nix profile list --json` for a nina element, returning its445// element name (the key to pass to `nix profile remove/upgrade`) or null.446// Newer nix (2.18+) keys elements by pname ("nina"). Older nix uses an array447// with an "attrPath" field. Tarball installs via the `default` output may use448// the key "default" instead of "nina"; we detect those via storePaths.449fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {450    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;451    defer parsed.deinit();452    const root = parsed.value;453    if (root != .object) return null;454    const elements = root.object.get("elements") orelse return null;455    switch (elements) {456        .object => |obj| {457            // Fast path: exact "nina" key (nix 2.18+ with nixpkgs#nina install).458            if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;459            // Fallback: scan storePaths. Handles tarball installs where the default460            // output is selected and nix names the element "default" (older nix) or461            // some other key derived from the attrPath rather than the pname.462            var it = obj.iterator();463            while (it.next()) |kv| {464                const val = kv.value_ptr.*;465                if (val != .object) continue;466                const sps = val.object.get("storePaths") orelse continue;467                if (sps != .array) continue;468                for (sps.array.items) |sp| {469                    if (sp == .string and storePathIsNina(sp.string))470                        return gpa.dupe(u8, kv.key_ptr.*) catch null;471                }472            }473            return null;474        },475        .array => |arr| {476            // Older nix array format. Element name is the last component of attrPath.477            for (arr.items) |el| {478                if (el != .object) continue;479                const ap = el.object.get("attrPath") orelse continue;480                if (ap != .string) continue;481                if (std.mem.eql(u8, ap.string, "nina") or482                    std.mem.endsWith(u8, ap.string, ".nina"))483                    return gpa.dupe(u8, "nina") catch null;484                // Tarball default-output install: attrPath ends in ".default" but485                // storePaths point to nina. Return "default" as the element name.486                const sps = el.object.get("storePaths") orelse continue;487                if (sps != .array) continue;488                for (sps.array.items) |sp| {489                    if (sp != .string) continue;490                    if (!storePathIsNina(sp.string)) continue;491                    const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;492                    const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;493                    return gpa.dupe(u8, el_name) catch null;494                }495            }496            return null;497        },498        else => return null,499    }500}501502test "profileJsonNinaElement finds element name from profile JSON" {503    const a = std.testing.allocator;504505    // Newer nix: elements keyed by pname. "nina" key present.506    const named =507        \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},508        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}509    ;510    const r1 = profileJsonNinaElement(a, named);511    defer if (r1) |n| a.free(n);512    try std.testing.expectEqualStrings("nina", r1.?);513514    // Tarball install via default output: element keyed as "default", storePath is nina.515    const default_key =516        \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}517    ;518    const r2 = profileJsonNinaElement(a, default_key);519    defer if (r2) |n| a.free(n);520    try std.testing.expectEqualStrings("default", r2.?);521522    // Decoy: storePath of another package contains "nina" as a substring but is not nina.523    const decoy =524        \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}525    ;526    const r3 = profileJsonNinaElement(a, decoy);527    try std.testing.expectEqual(@as(?[]const u8, null), r3);528529    // Older nix array schema, attrPath ending in ".nina".530    const arr =531        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}532    ;533    const r4 = profileJsonNinaElement(a, arr);534    defer if (r4) |n| a.free(n);535    try std.testing.expectEqualStrings("nina", r4.?);536537    // Older nix array schema, tarball default-output install.538    const arr_default =539        \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}540    ;541    const r5 = profileJsonNinaElement(a, arr_default);542    defer if (r5) |n| a.free(n);543    try std.testing.expectEqualStrings("default", r5.?);544545    // Empty / malformed → null.546    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));547    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));548}549550// The store paths that make up the running system environment. Each reference is551// a <hash>-<name>-<version> path, so the caller can list system packages with552// versions — there is no cleaner per-package list for environment.systemPackages.553pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {554    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });555    defer gpa.free(r.stderr);556    if (r.exit_code != 0) {557        gpa.free(r.stdout);558        return error.ProcessFailed;559    }560    return r.stdout;561}562563pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {564    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });565}566567// --- Store ---568569pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {570    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });571}572573pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {574    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });575}576577pub const SystemStatus = struct { size: []u8, age: []u8 };578579// One read-only pass for `nina status`: the current system's closure size (a580// single `path-info -S` of /run/current-system — fast, unlike -S over the whole581// store) and seconds since the system profile was last switched (its symlink582// mtime). Both are world-readable; no root needed.583const STATUS_SCRIPT =584    \\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} ))"585;586587pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {588    const unknown = SystemStatus{589        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },590        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },591    };592    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;593    defer gpa.free(r.stdout);594    defer gpa.free(r.stderr);595    if (r.exit_code != 0) return unknown;596597    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");598    const sz_str = it.next() orelse return unknown;599    const age_str = it.next() orelse return unknown;600    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;601    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;602603    gpa.free(unknown.size);604    gpa.free(unknown.age);605    return .{606        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),607        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),608    };609}610611// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A612// one-word health signal; exits non-zero when degraded, so we read stdout, not613// the code. Caller owns the returned slice.614pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {615    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch616        return gpa.dupe(u8, "unknown");617    defer gpa.free(r.stderr);618    const state = std.mem.trim(u8, r.stdout, " \t\n\r");619    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");620    gpa.free(r.stdout);621    return owned;622}623624fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {625    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});626    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});627    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});628    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});629}630631pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {632    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });633}634635pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {636    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)637    // graph work that takes minutes on a real store (59k+ paths) and hangs the638    // command. We don't need closures: `--all --json` (no -S) carries each path's639    // own narSize, so one fast pass gives the path count and the summed store size.640    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.641    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.642    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });643    defer gpa.free(pi.stdout);644    defer gpa.free(pi.stderr);645646    const scan = scanStoreJson(pi.stdout);647    const total_owned = try humanSize(gpa, scan.total_bytes);648649    return .{650        .total_size = total_owned,651        .live_paths = scan.count,652        .reclaimable_paths = 0,653    };654}655656const StoreScan = struct { count: u64, total_bytes: u64 };657658// One linear pass over `nix path-info --json`: each path object has exactly one659// "narSize": field, so counting them gives the true path count and summing the660// values gives the total store size — no per-path closure walk.661fn scanStoreJson(json_str: []const u8) StoreScan {662    const needle = "\"narSize\":";663    var count: u64 = 0;664    var total: u64 = 0;665    var i: usize = 0;666    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {667        var j = pos + needle.len;668        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}669        var val: u64 = 0;670        var any = false;671        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {672            val = val * 10 + (json_str[j] - '0');673            any = true;674        }675        if (any) {676            count += 1;677            total += val;678        }679        i = j;680    }681    return .{ .count = count, .total_bytes = total };682}683684fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {685    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };686    var val: f64 = @floatFromInt(bytes);687    var unit: usize = 0;688    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;689    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });690    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });691}692693pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {694    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the695    // flake registry), not a flake in the current directory.696    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});697    defer gpa.free(expr);698    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });699    defer gpa.free(r.stderr);700    if (r.exit_code != 0) {701        gpa.free(r.stdout);702        return error.ProcessFailed;703    }704    return r.stdout;705}706707// --- Flake ---708709pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {710    if (input) |inp| {711        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });712    }713    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });714}715716pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {717    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });718}719720pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {721    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });722}723724pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {725    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });726}727728pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {729    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });730}731732pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {733    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });734    defer gpa.free(r.stderr);735    if (r.exit_code != 0) {736        gpa.free(r.stdout);737        return error.ProcessFailed;738    }739    return r.stdout;740}741742// --- Build / Run / Develop ---743744pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {745    if (attr) |a| {746        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});747        defer gpa.free(ref);748        return stream(io, machine, gpa, &.{ "nix", "build", ref });749    }750    return stream(io, machine, gpa, &.{ "nix", "build" });751}752753pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {754    // nix run always gets --no-write-lock-file for remote URLs755    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");756    if (is_url) {757        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });758    }759    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.760    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {761        return stream(io, machine, gpa, &.{ "nix", "run", pkg });762    }763    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});764    defer gpa.free(ref);765    return stream(io, machine, gpa, &.{ "nix", "run", ref });766}767768pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {769    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});770    defer gpa.free(ref);771    return stream(io, machine, gpa, &.{ "nix", "shell", ref });772}773774pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {775    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});776    defer gpa.free(ref);777    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});778    defer gpa.free(ps1);779    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);780}781782pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {783    if (run_cmd) |cmd| {784        // sh -c so a multi-word command isn't treated as a single executable name.785        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });786    }787    return stream(io, machine, gpa, &.{ "nix", "develop" });788}789790pub 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 {791    if (run_cmd) |cmd| {792        // sh -c so a multi-word command isn't treated as a single executable name.793        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });794    }795    return streamEnv(io, machine, gpa, &.{ "nix", "develop" }, base_env, "(nina: dev) -> ");796}797798pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {799    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });800}801802// --- Format ---803804pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {805    if (check) {806        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });807    }808    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });809}810811// --- Info ---812813pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {814    const r = try capture(gpa, io, machine, &.{"nixos-version"});815    defer gpa.free(r.stderr);816    if (r.exit_code != 0) {817        gpa.free(r.stdout);818        return error.ProcessFailed;819    }820    return r.stdout;821}822823pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {824    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });825    defer gpa.free(r.stderr);826    if (r.exit_code != 0) {827        gpa.free(r.stdout);828        return error.ProcessFailed;829    }830    return r.stdout;831}832833pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {834    const r = try capture(gpa, io, machine, &.{"uptime"});835    defer gpa.free(r.stderr);836    if (r.exit_code != 0) {837        gpa.free(r.stdout);838        return error.ProcessFailed;839    }840    return r.stdout;841}842843// --- Boot ---844845pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {846    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });847    defer gpa.free(r.stderr);848    defer gpa.free(r.stdout);849    if (r.exit_code != 0) return error.ProcessFailed;850    return parseBootEntries(gpa, r.stdout);851}852853fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {854    var entries: std.ArrayList(types.BootEntry) = .empty;855    var lines = std.mem.splitScalar(u8, output_str, '\n');856    while (lines.next()) |line| {857        const trimmed = std.mem.trim(u8, line, " \t\r");858        if (std.mem.startsWith(u8, trimmed, "title:")) {859            const title = std.mem.trim(u8, trimmed[6..], " \t");860            const current = std.mem.indexOf(u8, title, "(current)") != null;861            try entries.append(gpa, .{862                .title = try gpa.dupe(u8, title),863                .current = current,864            });865        }866    }867    return entries.toOwnedSlice(gpa);868}869870// --- Pkg info ---871872pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {873    return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });874}875876pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {877    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });878}879880pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {881    // A bare name ("ripgrep") isn't a valid installable; resolve via nixpkgs# like882    // `pkg path` does. -S -h gives closure size, human-readable. Output is883    // "<store-path>   <size>"; return just the size.884    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});885    defer gpa.free(ref);886    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref });887    defer gpa.free(r.stderr);888    defer gpa.free(r.stdout);889    if (r.exit_code != 0) return error.ProcessFailed;890891    const line = std.mem.trim(u8, r.stdout, " \t\n\r");892    var it = std.mem.tokenizeAny(u8, line, " \t");893    _ = it.next(); // store path894    const size = std.mem.trim(u8, it.rest(), " \t");895    if (size.len == 0) return error.ProcessFailed;896    return gpa.dupe(u8, size);897}898899pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {900    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });901}902903// --- Hash / Fetch ---904905pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {906    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });907    defer gpa.free(r.stderr);908    if (r.exit_code != 0) {909        gpa.free(r.stdout);910        return error.ProcessFailed;911    }912    return r.stdout;913}914915pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {916    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });917    defer gpa.free(r.stderr);918    if (r.exit_code != 0) {919        gpa.free(r.stdout);920        return error.ProcessFailed;921    }922    return r.stdout;923}924925// --- Pin ---926927pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {928    // Stub: full implementation would parse and edit flake.lock JSON929    // The pin/unpin flow works via nix flake update which regenerates flake.lock930}931932pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {933    if (line) |l| {934        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});935        defer gpa.free(line_arg);936        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });937    }938    return stream(io, &types.Machine{}, gpa, &.{ editor, path });939}940941pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {942    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});943    defer gpa.free(a_str);944    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});945    defer gpa.free(b_str);946    // On a tty, the child's own color is fine — stream it directly.947    if (output.colorEnabled()) {948        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });949    }950    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,951    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.952    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });953    defer gpa.free(r.stdout);954    defer gpa.free(r.stderr);955    const cleaned = try stripAnsi(gpa, r.stdout);956    defer gpa.free(cleaned);957    output.raw(cleaned);958    return r.exit_code;959}960961// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a962// child process's color when it writes ANSI unconditionally.963fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {964    var out: std.ArrayList(u8) = .empty;965    errdefer out.deinit(gpa);966    var i: usize = 0;967    while (i < input.len) {968        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {969            i += 2;970            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}971            if (i < input.len) i += 1; // consume the final byte972            continue;973        }974        try out.append(gpa, input[i]);975        i += 1;976    }977    return out.toOwnedSlice(gpa);978}979980test "stripAnsi removes CSI color sequences" {981    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");982    defer std.testing.allocator.free(cleaned);983    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);984}985986// --- Doctor checks ---987988pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {989    var checks: std.ArrayList(types.DoctorCheck) = .empty;990991    // Check nix daemon992    {993        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });994        defer gpa.free(r.stdout);995        defer gpa.free(r.stderr);996        const active = std.mem.indexOf(u8, r.stdout, "active") != null;997        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });998    }9991000    // Check config syntax1001    {1002        const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });1003        defer gpa.free(r.stdout);1004        defer gpa.free(r.stderr);1005        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1006    }10071008    // Check channel1009    {1010        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1011        defer gpa.free(r.stdout);1012        defer gpa.free(r.stderr);1013        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1014        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1015    }10161017    return checks.toOwnedSlice(gpa);1018}10191020// --- Log ---10211022pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1023    const home = environ.get("HOME") orelse return error.FileNotFound;1024    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1025    defer gpa.free(path);1026    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1027    if (last == 0) return content;10281029    // Collect non-empty lines, then keep only the final `last`. Slices point into1030    // `content`, so copy them out before freeing it.1031    var lines: std.ArrayList([]const u8) = .empty;1032    defer lines.deinit(gpa);1033    var it = std.mem.splitScalar(u8, content, '\n');1034    while (it.next()) |line| {1035        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1036        try lines.append(gpa, line);1037    }1038    if (lines.items.len <= last) return content;10391040    var out: std.ArrayList(u8) = .empty;1041    errdefer out.deinit(gpa);1042    for (lines.items[lines.items.len - last ..]) |line| {1043        try out.appendSlice(gpa, line);1044        try out.append(gpa, '\n');1045    }1046    gpa.free(content);1047    return out.toOwnedSlice(gpa);1048}10491050// nina is a one-shot process, so "did the last apply fail this session?" can't1051// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1052// other ~/.nina-* state files. This lets a later successful apply earn the1053// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1054pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1055    const home = environ.get("HOME") orelse return;1056    var buf: [512]u8 = undefined;1057    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1058    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1059    file.close(io);1060}10611062pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1063    const home = environ.get("HOME") orelse return false;1064    var buf: [512]u8 = undefined;1065    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1066    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1067        f.close(io);1068        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1069        return true;1070    } else |_| {1071        return false;1072    }1073}10741075pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1076    const home = environ.get("HOME") orelse return;1077    var path_buf: [512]u8 = undefined;1078    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1079    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1080        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1081    defer file.close(io);1082    const size = file.length(io) catch 0;1083    file.writePositionalAll(io, entry, size) catch {};1084}10851086// --- Update helpers ---10871088// Fetch a URL with curl and return the response body. Caller must free.1089// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.1090pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1091    const argv = [_][]const u8{1092        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1093    };1094    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1095    defer gpa.free(result.stderr);10961097    const marker = "\nHTTP_STATUS:";1098    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1099        gpa.free(result.stdout);1100        return error.NetworkError;1101    };1102    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1103    const status = std.fmt.parseInt(u16, status_str, 10) catch {1104        gpa.free(result.stdout);1105        return error.NetworkError;1106    };1107    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1108    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1109    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1110        gpa.free(result.stdout);1111        return e;1112    };1113    gpa.free(result.stdout);1114    return body;1115}11161117// Download a URL to a temp file. Returns the temp path (caller must gpa.free).1118// The file is written to /tmp/nina-update-<pid> and left for the caller to use.1119pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1120    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1121    errdefer gpa.free(tmp_path);11221123    var child = std.process.spawn(io, .{1124        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1125        .stdin = .close,1126        .stdout = .close,1127        .stderr = .inherit,1128    }) catch return error.NetworkError;1129    const term = child.wait(io) catch return error.NetworkError;1130    switch (term) {1131        .exited => |c| if (c != 0) return error.NetworkError,1132        else => return error.NetworkError,1133    }1134    return tmp_path;1135}11361137// Get the current executable path into buf. Returns slice of buf.1138pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1139    const len = try std.process.executablePath(io, buf);1140    return buf[0..len];1141}11421143// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1144// atomically install the binary to install_path. Errors: ChecksumMismatch,1145// AccessDenied (with error_info set), or underlying I/O errors.1146pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1147    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1148        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1149        return error.FileNotFound;1150    };1151    defer gpa.free(bytes);11521153    var hasher = std.crypto.hash.Blake3.init(.{});1154    hasher.update(bytes);1155    var raw: [32]u8 = undefined;1156    hasher.final(&raw);1157    const hex = std.fmt.bytesToHex(raw, .lower);1158    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;11591160    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1161    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1162        return error.NameTooLong;11631164    {1165        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1166            errors.error_info.setMessage("cannot write to {s}", .{install_path});1167            errors.error_info.setSuggestion("try: sudo nina update", .{});1168            return error.AccessDenied;1169        };1170        defer f.close(io);1171        f.writePositionalAll(io, bytes, 0) catch {1172            errors.error_info.setMessage("cannot write to {s}", .{install_path});1173            return error.AccessDenied;1174        };1175        try f.setPermissions(io, .fromMode(0o755));1176    }1177    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};11781179    if (comptime builtin.os.tag == .macos) {1180        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1181    }11821183    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1184        error.AccessDenied => {1185            errors.error_info.setMessage("cannot replace {s}", .{install_path});1186            errors.error_info.setSuggestion("try: sudo nina update", .{});1187            return error.AccessDenied;1188        },1189        else => return e,1190    };1191}11921193// --- Nix feature setup ---11941195pub const NixFeatureStatus = struct {1196    nix_command: bool = false,1197    flakes: bool = false,11981199    pub fn allEnabled(self: NixFeatureStatus) bool {1200        return self.nix_command and self.flakes;1201    }1202};12031204fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1205    var lines = std.mem.splitScalar(u8, conf, '\n');1206    while (lines.next()) |line| {1207        const trimmed = std.mem.trim(u8, line, " \t");1208        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1209        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1210        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1211    }1212}12131214pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1215    var status = NixFeatureStatus{};12161217    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1218        defer gpa.free(conf);1219        scanConfFeatures(conf, &status);1220    }12211222    if (environ.get("HOME")) |home| {1223        var buf: [512]u8 = undefined;1224        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1225        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1226            defer gpa.free(conf);1227            scanConfFeatures(conf, &status);1228        }1229    }12301231    return status;1232}12331234pub fn isNixOS(io: std.Io) bool {1235    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1236    file.close(io);1237    return true;1238}12391240// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.1241// Returns the path written (caller must free).1242pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1243    const home = environ.get("HOME") orelse {1244        errors.error_info.setMessage("HOME not set", .{});1245        return error.ConfigNotFound;1246    };12471248    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1249    defer gpa.free(dir_path);1250    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1251    errdefer gpa.free(file_path);12521253    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};12541255    const line = "experimental-features = nix-command flakes\n";1256    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1257        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1258        errors.error_info.setMessage("could not write {s}", .{file_path});1259        return error.FileNotFound;1260    });1261    defer file.close(io);12621263    const size = file.length(io) catch 0;1264    file.writePositionalAll(io, line, size) catch {1265        errors.error_info.setMessage("could not write {s}", .{file_path});1266        return error.FileNotFound;1267    };12681269    return file_path;1270}12711272// --- NixOS: declarative experimental-features ---1273//1274// On NixOS the permanent, declarative home for these flags is configuration.nix,1275// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves1276// the `nixos-rebuild switch` to the user.12771278pub const NIXOS_FEATURES_LINE =1279    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";12801281// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns1282// false on any read error so the caller still offers to add the line.1283pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1284    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1285    defer gpa.free(conf);1286    return std.mem.indexOf(u8, conf, "experimental-features") != null and1287        std.mem.indexOf(u8, conf, "nix-command") != null and1288        std.mem.indexOf(u8, conf, "flakes") != null;1289}12901291fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1292    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1293    return captureLocal(gpa, io, &.{ "sudo", "cat", path });1294}12951296// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix1297// (i.e. inside the top-level attribute set) and write it back via a single1298// `sudo cp`, which prompts for the password on the terminal. Returns an error1299// for the caller to fall back to printed manual instructions.1300pub fn appendFeaturesToNixosConfig(1301    gpa: std.mem.Allocator,1302    io: std.Io,1303    environ: *const std.process.Environ.Map,1304    path: []const u8,1305) !void {1306    const conf = readMaybeSudo(gpa, io, path) catch {1307        errors.error_info.setMessage("could not read {s}", .{path});1308        return error.ConfigNotFound;1309    };1310    defer gpa.free(conf);13111312    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared13131314    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1315        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1316        return error.MalformedConfig;1317    };13181319    const home = environ.get("HOME") orelse {1320        errors.error_info.setMessage("HOME not set", .{});1321        return error.ConfigNotFound;1322    };1323    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1324    defer gpa.free(tmp_path);13251326    var buf: std.ArrayList(u8) = .empty;1327    defer buf.deinit(gpa);1328    try buf.appendSlice(gpa, conf[0..brace]);1329    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1330    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");1331    try buf.appendSlice(gpa, "  ");1332    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1333    try buf.append(gpa, '\n');1334    try buf.appendSlice(gpa, conf[brace..]);13351336    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1337        errors.error_info.setMessage("could not write {s}", .{tmp_path});1338        return error.FileNotFound;1339    };1340    tmp.writePositionalAll(io, buf.items, 0) catch {1341        tmp.close(io);1342        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1343        errors.error_info.setMessage("could not write {s}", .{tmp_path});1344        return error.FileNotFound;1345    };1346    tmp.close(io);13471348    // Back up the existing config, then replace it — in one sudo call so the1349    // password is asked for at most once. Paths travel as positional args ($0,1350    // $1) to sidestep shell quoting.1351    const code = streamLocal(io, &.{1352        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1353    }) catch {1354        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1355        errors.error_info.setMessage("could not write {s}", .{path});1356        return error.ProcessFailed;1357    };1358    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1359    if (code != 0) {1360        errors.error_info.setMessage("sudo cp into {s} failed", .{path});1361        return error.ProcessFailed;1362    }1363}