exec.zig

53.6 KB · raw

1// exec.zig — all process execution and SSH routing2// Commands call these functions; output is streamed or captured here.3const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const output = @import("output.zig");89// nixos-rebuild manages this profile; generation commands must target it10// explicitly. Bare nix-env defaults to the per-user profile, which is empty.11const SYSTEM_PROFILE = "/nix/var/nix/profiles/system";1213pub const RunResult = struct {14    stdout: []u8,15    stderr: []u8,16    exit_code: u8,17};1819// Run a process and capture stdout+stderr (not streaming).20pub fn capture(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, cmd: []const []const u8) !RunResult {21    const argv = try buildArgv(gpa, machine, cmd);22    defer if (!machine.local) gpa.free(argv);2324    const result = std.process.run(gpa, io, .{ .argv = argv }) catch |e| {25        errors.error_info.setMessage("process failed: {s}", .{cmd[0]});26        return e;27    };2829    return .{30        .stdout = result.stdout,31        .stderr = result.stderr,32        .exit_code = switch (result.term) {33            .exited => |c| c,34            else => 1,35        },36    };37}3839// Run a process and stream its output to the terminal (inherit stdio).40pub fn stream(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8) !u8 {41    // The child inherits stdout and writes directly to the fd; flush any buffered42    // nina header first so it isn't reordered after the child's output.43    output.flush();44    const argv = try buildArgv(gpa, machine, cmd);45    defer if (!machine.local) gpa.free(argv);4647    var child = std.process.spawn(io, .{48        .argv = argv,49        .stdin = .inherit,50        .stdout = .inherit,51        .stderr = .inherit,52    }) catch |e| {53        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});54        return e;55    };5657    const term = child.wait(io) catch |e| {58        errors.error_info.setMessage("process wait failed", .{});59        return e;60    };6162    return switch (term) {63        .exited => |c| c,64        else => 1,65    };66}6768// Stream a local process with inherited stdio (no SSH routing — for nix commands).69pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 {70    output.flush();71    var child = std.process.spawn(io, .{72        .argv = cmd,73        .stdin = .inherit,74        .stdout = .inherit,75        .stderr = .inherit,76    }) catch |e| {77        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});78        return e;79    };80    const term = child.wait(io) catch {81        errors.error_info.setMessage("process wait failed", .{});82        return error.ProcessFailed;83    };84    return switch (term) {85        .exited => |c| c,86        else => 1,87    };88}8990// Run a process and capture output as a single string (no SSH routing — for local nix commands).91pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {92    const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;93    defer gpa.free(result.stderr);94    switch (result.term) {95        .exited => |c| if (c != 0) {96            gpa.free(result.stdout);97            return error.ProcessFailed;98        },99        else => {100            gpa.free(result.stdout);101            return error.ProcessFailed;102        },103    }104    return result.stdout;105}106107fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {108    if (machine.local) return cmd;109110    const host = machine.host orelse {111        errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});112        return error.SshFailed;113    };114115    var ssh: std.ArrayList([]const u8) = .empty;116    try ssh.append(gpa, "ssh");117    try ssh.append(gpa, "-o");118    try ssh.append(gpa, "BatchMode=yes");119    try ssh.append(gpa, "-o");120    try ssh.append(gpa, "StrictHostKeyChecking=accept-new");121    if (machine.ssh_key) |key| {122        try ssh.append(gpa, "-i");123        try ssh.append(gpa, key);124    }125    const addr = if (machine.user) |u|126        try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })127    else128        try gpa.dupe(u8, host);129    try ssh.append(gpa, addr);130    for (cmd) |arg| try ssh.append(gpa, arg);131    return ssh.toOwnedSlice(gpa);132}133134// --- NixOS rebuild ---135136pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {137    const cmd = &.{ "sudo", "nixos-rebuild", "switch" };138    output.printSubstep("nixos-rebuild switch", .{});139    return stream(io, machine, gpa, cmd);140}141142pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {143    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "dry-activate" });144}145146pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {147    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "build" });148}149150// --- Generations ---151152// Read system-profile generations WITHOUT root. `nix-env --list-generations -p153// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user154// ("system.lock: Permission denied"). The generation symlinks themselves are155// world-readable, so list them directly: parse `system-N-link` names, take each156// link's own mtime for the date/time, and mark the one the `system` symlink157// points at as current. Output matches the `nix-env --list-generations` columns158// (num date time [current]) so parseGenerations is unchanged.159const GEN_LIST_SCRIPT =160    \\cur=$(readlink /nix/var/nix/profiles/system 2>/dev/null | sed 's/.*system-\([0-9]*\)-link/\1/'); find /nix/var/nix/profiles -maxdepth 1 -name 'system-*-link' -printf '%f %TY-%Tm-%Td %TH:%TM\n' 2>/dev/null | sed 's/system-\([0-9]*\)-link/\1/' | sort -n | awk -v c="$cur" '{ if ($1==c) print $0" current"; else print $0 }'161;162163pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {164    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });165    defer gpa.free(r.stderr);166    defer gpa.free(r.stdout);167    if (r.exit_code != 0) return error.ProcessFailed;168    return parseGenerations(gpa, r.stdout);169}170171fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {172    var gens: std.ArrayList(types.GenerationInfo) = .empty;173    var lines = std.mem.splitScalar(u8, output_str, '\n');174    while (lines.next()) |line| {175        const trimmed = std.mem.trim(u8, line, " \t");176        if (trimmed.len == 0) continue;177        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");178        const num_str = parts.next() orelse continue;179        const date_str = parts.next() orelse continue;180        const time_str = parts.next() orelse continue;181        const rest = parts.rest();182        const current = std.mem.indexOf(u8, rest, "current") != null;183        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;184        try gens.append(gpa, .{185            .number = num,186            .date = try gpa.dupe(u8, date_str),187            .time = try gpa.dupe(u8, time_str),188            .current = current,189        });190    }191    return gens.toOwnedSlice(gpa);192}193194pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {195    const gens = try getGenerations(gpa, io, machine);196    defer gpa.free(gens);197    for (gens) |g| {198        if (g.current) return g.number;199    }200    return 0;201}202203pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {204    // Switch the system profile to generation n, then activate it (bootloader +205    // services). Without switch-to-configuration the change isn't applied.206    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --switch-generation {d} && {s}/bin/switch-to-configuration switch", .{ SYSTEM_PROFILE, n, SYSTEM_PROFILE });207    defer gpa.free(cmd);208    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });209}210211pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {212    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });213}214215pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {216    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});217    defer gpa.free(n_str);218    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });219}220221pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {222    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });223}224225// --- Garbage collection ---226227pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {228    if (delete_old) {229        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });230    }231    // Keep the `keep` most recent system generations (+N deletes all but N),232    // then collect now-unreferenced store paths. `--delete-older-than` wants a233    // duration (e.g. 14d), not a generation count.234    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });235    defer gpa.free(cmd);236    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });237}238239// --- Channels ---240241pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {242    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });243    defer gpa.free(r.stderr);244    defer gpa.free(r.stdout);245    if (r.exit_code != 0) return error.ProcessFailed;246    return parseChannels(gpa, r.stdout);247}248249fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {250    var channels: std.ArrayList(types.ChannelInfo) = .empty;251    var lines = std.mem.splitScalar(u8, output_str, '\n');252    while (lines.next()) |line| {253        const trimmed = std.mem.trim(u8, line, " \t\r");254        if (trimmed.len == 0) continue;255        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;256        try channels.append(gpa, .{257            .name = try gpa.dupe(u8, trimmed[0..space]),258            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),259        });260    }261    return channels.toOwnedSlice(gpa);262}263264pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {265    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });266}267268pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {269    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });270}271272pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {273    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });274}275276// --- Services ---277278pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ServiceInfo {279    const r = try capture(gpa, io, machine, &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" });280    defer gpa.free(r.stderr);281    defer gpa.free(r.stdout);282    if (r.exit_code != 0) return error.ProcessFailed;283    return parseServices(gpa, r.stdout);284}285286fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {287    var svcs: std.ArrayList(types.ServiceInfo) = .empty;288    var lines = std.mem.splitScalar(u8, output_str, '\n');289    while (lines.next()) |line| {290        const trimmed = std.mem.trim(u8, line, " \t\r");291        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines292        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");293        const name = parts.next() orelse continue;294        _ = parts.next(); // load295        const active_str = parts.next() orelse continue;296        const sub_str = parts.next() orelse "unknown";297298        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))299            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)300        else if (std.mem.eql(u8, active_str, "failed"))301            .failed302        else303            .inactive;304305        try svcs.append(gpa, .{306            .name = try gpa.dupe(u8, name),307            .state = state,308            .uptime = null,309        });310    }311    return svcs.toOwnedSlice(gpa);312}313314pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8) !u8 {315    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.316    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });317}318319pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool) !u8 {320    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});321    defer gpa.free(n_str);322    if (follow) {323        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });324    }325    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });326}327328// --- Profile ---329330pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {331    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});332    defer gpa.free(pkg_ref);333    // `nix profile add` is the current verb; `install` is a deprecated alias that334    // prints a warning on modern nix.335    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });336}337338pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {339    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not340    // by flake ref — passing nixpkgs#ripgrep matches nothing.341    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });342}343344pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {345    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });346    defer gpa.free(r.stderr);347    if (r.exit_code != 0) return error.ProcessFailed;348    return r.stdout;349}350351// Machine-readable profile listing — caller parses elements -> name + version.352pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {353    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });354    defer gpa.free(r.stderr);355    if (r.exit_code != 0) {356        gpa.free(r.stdout);357        return error.ProcessFailed;358    }359    return r.stdout;360}361362// Returns the profile element name to pass to `nix profile remove/upgrade`363// (e.g. "nina" or "default"), or null if nina is not found. Caller owns the364// returned slice. A NixOS system-package install also resolves into /nix/store365// so the store path alone can't distinguish it from a profile install — the366// profile list can. A missing/empty profile (or no nix) returns null.367pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {368    const js = profileListJson(gpa, io, machine) catch return null;369    defer gpa.free(js);370    return profileJsonNinaElement(gpa, js);371}372373pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {374    const name = profileNinaElement(gpa, io, machine) orelse return false;375    gpa.free(name);376    return true;377}378379// True when a nix store path belongs to the nina package. Store paths have the380// form /nix/store/<32-char-hash>-<pname>-<version>[/<subpath>]. We check that381// the 33 chars after /nix/store/ are the hash+dash, and the pname that follows382// is exactly "nina" (followed by "-" or end-of-component).383fn storePathIsNina(path: []const u8) bool {384    const prefix = "/nix/store/";385    if (!std.mem.startsWith(u8, path, prefix)) return false;386    const rel = path[prefix.len..];387    // The store entry name ends at the first "/" (if any sub-path follows).388    const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];389    if (entry.len < 34) return false; // 32-char hash + dash + at least one char390    const pname_ver = entry[33..]; // skip hash + dash391    return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");392}393394// Pure parse of `nix profile list --json` for a nina element, returning its395// element name (the key to pass to `nix profile remove/upgrade`) or null.396// Newer nix (2.18+) keys elements by pname ("nina"). Older nix uses an array397// with an "attrPath" field. Tarball installs via the `default` output may use398// the key "default" instead of "nina"; we detect those via storePaths.399fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {400    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;401    defer parsed.deinit();402    const root = parsed.value;403    if (root != .object) return null;404    const elements = root.object.get("elements") orelse return null;405    switch (elements) {406        .object => |obj| {407            // Fast path: exact "nina" key (nix 2.18+ with nixpkgs#nina install).408            if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;409            // Fallback: scan storePaths. Handles tarball installs where the default410            // output is selected and nix names the element "default" (older nix) or411            // some other key derived from the attrPath rather than the pname.412            var it = obj.iterator();413            while (it.next()) |kv| {414                const val = kv.value_ptr.*;415                if (val != .object) continue;416                const sps = val.object.get("storePaths") orelse continue;417                if (sps != .array) continue;418                for (sps.array.items) |sp| {419                    if (sp == .string and storePathIsNina(sp.string))420                        return gpa.dupe(u8, kv.key_ptr.*) catch null;421                }422            }423            return null;424        },425        .array => |arr| {426            // Older nix array format. Element name is the last component of attrPath.427            for (arr.items) |el| {428                if (el != .object) continue;429                const ap = el.object.get("attrPath") orelse continue;430                if (ap != .string) continue;431                if (std.mem.eql(u8, ap.string, "nina") or432                    std.mem.endsWith(u8, ap.string, ".nina"))433                    return gpa.dupe(u8, "nina") catch null;434                // Tarball default-output install: attrPath ends in ".default" but435                // storePaths point to nina. Return "default" as the element name.436                const sps = el.object.get("storePaths") orelse continue;437                if (sps != .array) continue;438                for (sps.array.items) |sp| {439                    if (sp != .string) continue;440                    if (!storePathIsNina(sp.string)) continue;441                    const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;442                    const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;443                    return gpa.dupe(u8, el_name) catch null;444                }445            }446            return null;447        },448        else => return null,449    }450}451452test "profileJsonNinaElement finds element name from profile JSON" {453    const a = std.testing.allocator;454455    // Newer nix: elements keyed by pname. "nina" key present.456    const named =457        \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},458        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}459    ;460    const r1 = profileJsonNinaElement(a, named);461    defer if (r1) |n| a.free(n);462    try std.testing.expectEqualStrings("nina", r1.?);463464    // Tarball install via default output: element keyed as "default", storePath is nina.465    const default_key =466        \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}467    ;468    const r2 = profileJsonNinaElement(a, default_key);469    defer if (r2) |n| a.free(n);470    try std.testing.expectEqualStrings("default", r2.?);471472    // Decoy: storePath of another package contains "nina" as a substring but is not nina.473    const decoy =474        \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}475    ;476    const r3 = profileJsonNinaElement(a, decoy);477    try std.testing.expectEqual(@as(?[]const u8, null), r3);478479    // Older nix array schema, attrPath ending in ".nina".480    const arr =481        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}482    ;483    const r4 = profileJsonNinaElement(a, arr);484    defer if (r4) |n| a.free(n);485    try std.testing.expectEqualStrings("nina", r4.?);486487    // Older nix array schema, tarball default-output install.488    const arr_default =489        \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}490    ;491    const r5 = profileJsonNinaElement(a, arr_default);492    defer if (r5) |n| a.free(n);493    try std.testing.expectEqualStrings("default", r5.?);494495    // Empty / malformed → null.496    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));497    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));498}499500// The store paths that make up the running system environment. Each reference is501// a <hash>-<name>-<version> path, so the caller can list system packages with502// versions — there is no cleaner per-package list for environment.systemPackages.503pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {504    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });505    defer gpa.free(r.stderr);506    if (r.exit_code != 0) {507        gpa.free(r.stdout);508        return error.ProcessFailed;509    }510    return r.stdout;511}512513pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {514    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });515}516517// --- Store ---518519pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {520    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });521}522523pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {524    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });525}526527pub const SystemStatus = struct { size: []u8, age: []u8 };528529// One read-only pass for `nina status`: the current system's closure size (a530// single `path-info -S` of /run/current-system — fast, unlike -S over the whole531// store) and seconds since the system profile was last switched (its symlink532// mtime). Both are world-readable; no root needed.533const STATUS_SCRIPT =534    \\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} ))"535;536537pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {538    const unknown = SystemStatus{539        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },540        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },541    };542    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;543    defer gpa.free(r.stdout);544    defer gpa.free(r.stderr);545    if (r.exit_code != 0) return unknown;546547    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");548    const sz_str = it.next() orelse return unknown;549    const age_str = it.next() orelse return unknown;550    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;551    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;552553    gpa.free(unknown.size);554    gpa.free(unknown.age);555    return .{556        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),557        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),558    };559}560561// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A562// one-word health signal; exits non-zero when degraded, so we read stdout, not563// the code. Caller owns the returned slice.564pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {565    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch566        return gpa.dupe(u8, "unknown");567    defer gpa.free(r.stderr);568    const state = std.mem.trim(u8, r.stdout, " \t\n\r");569    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");570    gpa.free(r.stdout);571    return owned;572}573574fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {575    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});576    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});577    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});578    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});579}580581pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {582    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });583}584585pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {586    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)587    // graph work that takes minutes on a real store (59k+ paths) and hangs the588    // command. We don't need closures: `--all --json` (no -S) carries each path's589    // own narSize, so one fast pass gives the path count and the summed store size.590    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.591    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.592    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });593    defer gpa.free(pi.stdout);594    defer gpa.free(pi.stderr);595596    const scan = scanStoreJson(pi.stdout);597    const total_owned = try humanSize(gpa, scan.total_bytes);598599    return .{600        .total_size = total_owned,601        .live_paths = scan.count,602        .reclaimable_paths = 0,603    };604}605606const StoreScan = struct { count: u64, total_bytes: u64 };607608// One linear pass over `nix path-info --json`: each path object has exactly one609// "narSize": field, so counting them gives the true path count and summing the610// values gives the total store size — no per-path closure walk.611fn scanStoreJson(json_str: []const u8) StoreScan {612    const needle = "\"narSize\":";613    var count: u64 = 0;614    var total: u64 = 0;615    var i: usize = 0;616    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {617        var j = pos + needle.len;618        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}619        var val: u64 = 0;620        var any = false;621        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {622            val = val * 10 + (json_str[j] - '0');623            any = true;624        }625        if (any) {626            count += 1;627            total += val;628        }629        i = j;630    }631    return .{ .count = count, .total_bytes = total };632}633634fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {635    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };636    var val: f64 = @floatFromInt(bytes);637    var unit: usize = 0;638    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;639    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });640    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });641}642643pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {644    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the645    // flake registry), not a flake in the current directory.646    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});647    defer gpa.free(expr);648    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });649    defer gpa.free(r.stderr);650    if (r.exit_code != 0) {651        gpa.free(r.stdout);652        return error.ProcessFailed;653    }654    return r.stdout;655}656657// --- Flake ---658659pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {660    if (input) |inp| {661        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });662    }663    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });664}665666pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {667    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });668}669670pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {671    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });672}673674pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {675    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });676}677678pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {679    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });680}681682pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {683    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });684    defer gpa.free(r.stderr);685    if (r.exit_code != 0) {686        gpa.free(r.stdout);687        return error.ProcessFailed;688    }689    return r.stdout;690}691692// --- Build / Run / Develop ---693694pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {695    if (attr) |a| {696        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});697        defer gpa.free(ref);698        return stream(io, machine, gpa, &.{ "nix", "build", ref });699    }700    return stream(io, machine, gpa, &.{ "nix", "build" });701}702703pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {704    // nix run always gets --no-write-lock-file for remote URLs705    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");706    if (is_url) {707        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });708    }709    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.710    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {711        return stream(io, machine, gpa, &.{ "nix", "run", pkg });712    }713    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});714    defer gpa.free(ref);715    return stream(io, machine, gpa, &.{ "nix", "run", ref });716}717718pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {719    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});720    defer gpa.free(ref);721    return stream(io, machine, gpa, &.{ "nix", "shell", ref });722}723724pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {725    if (run_cmd) |cmd| {726        // sh -c so a multi-word command isn't treated as a single executable name.727        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });728    }729    return stream(io, machine, gpa, &.{ "nix", "develop" });730}731732pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {733    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });734}735736// --- Format ---737738pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {739    if (check) {740        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });741    }742    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });743}744745// --- Info ---746747pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {748    const r = try capture(gpa, io, machine, &.{"nixos-version"});749    defer gpa.free(r.stderr);750    if (r.exit_code != 0) {751        gpa.free(r.stdout);752        return error.ProcessFailed;753    }754    return r.stdout;755}756757pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {758    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });759    defer gpa.free(r.stderr);760    if (r.exit_code != 0) {761        gpa.free(r.stdout);762        return error.ProcessFailed;763    }764    return r.stdout;765}766767pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {768    const r = try capture(gpa, io, machine, &.{"uptime"});769    defer gpa.free(r.stderr);770    if (r.exit_code != 0) {771        gpa.free(r.stdout);772        return error.ProcessFailed;773    }774    return r.stdout;775}776777// --- Boot ---778779pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {780    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });781    defer gpa.free(r.stderr);782    defer gpa.free(r.stdout);783    if (r.exit_code != 0) return error.ProcessFailed;784    return parseBootEntries(gpa, r.stdout);785}786787fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {788    var entries: std.ArrayList(types.BootEntry) = .empty;789    var lines = std.mem.splitScalar(u8, output_str, '\n');790    while (lines.next()) |line| {791        const trimmed = std.mem.trim(u8, line, " \t\r");792        if (std.mem.startsWith(u8, trimmed, "title:")) {793            const title = std.mem.trim(u8, trimmed[6..], " \t");794            const current = std.mem.indexOf(u8, title, "(current)") != null;795            try entries.append(gpa, .{796                .title = try gpa.dupe(u8, title),797                .current = current,798            });799        }800    }801    return entries.toOwnedSlice(gpa);802}803804// --- Pkg info ---805806pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {807    return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });808}809810pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {811    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });812}813814pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {815    // A bare name ("ripgrep") isn't a valid installable; resolve via nixpkgs# like816    // `pkg path` does. -S -h gives closure size, human-readable. Output is817    // "<store-path>   <size>"; return just the size.818    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});819    defer gpa.free(ref);820    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref });821    defer gpa.free(r.stderr);822    defer gpa.free(r.stdout);823    if (r.exit_code != 0) return error.ProcessFailed;824825    const line = std.mem.trim(u8, r.stdout, " \t\n\r");826    var it = std.mem.tokenizeAny(u8, line, " \t");827    _ = it.next(); // store path828    const size = std.mem.trim(u8, it.rest(), " \t");829    if (size.len == 0) return error.ProcessFailed;830    return gpa.dupe(u8, size);831}832833pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {834    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });835}836837// --- Hash / Fetch ---838839pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {840    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });841    defer gpa.free(r.stderr);842    if (r.exit_code != 0) {843        gpa.free(r.stdout);844        return error.ProcessFailed;845    }846    return r.stdout;847}848849pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {850    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });851    defer gpa.free(r.stderr);852    if (r.exit_code != 0) {853        gpa.free(r.stdout);854        return error.ProcessFailed;855    }856    return r.stdout;857}858859// --- Pin ---860861pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {862    // Stub: full implementation would parse and edit flake.lock JSON863    // The pin/unpin flow works via nix flake update which regenerates flake.lock864}865866pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {867    if (line) |l| {868        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});869        defer gpa.free(line_arg);870        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });871    }872    return stream(io, &types.Machine{}, gpa, &.{ editor, path });873}874875pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {876    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});877    defer gpa.free(a_str);878    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});879    defer gpa.free(b_str);880    // On a tty, the child's own color is fine — stream it directly.881    if (output.colorEnabled()) {882        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });883    }884    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,885    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.886    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });887    defer gpa.free(r.stdout);888    defer gpa.free(r.stderr);889    const cleaned = try stripAnsi(gpa, r.stdout);890    defer gpa.free(cleaned);891    output.raw(cleaned);892    return r.exit_code;893}894895// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a896// child process's color when it writes ANSI unconditionally.897fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {898    var out: std.ArrayList(u8) = .empty;899    errdefer out.deinit(gpa);900    var i: usize = 0;901    while (i < input.len) {902        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {903            i += 2;904            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}905            if (i < input.len) i += 1; // consume the final byte906            continue;907        }908        try out.append(gpa, input[i]);909        i += 1;910    }911    return out.toOwnedSlice(gpa);912}913914test "stripAnsi removes CSI color sequences" {915    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");916    defer std.testing.allocator.free(cleaned);917    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);918}919920// --- Doctor checks ---921922pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {923    var checks: std.ArrayList(types.DoctorCheck) = .empty;924925    // Check nix daemon926    {927        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });928        defer gpa.free(r.stdout);929        defer gpa.free(r.stderr);930        const active = std.mem.indexOf(u8, r.stdout, "active") != null;931        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });932    }933934    // Check config syntax935    {936        const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });937        defer gpa.free(r.stdout);938        defer gpa.free(r.stderr);939        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });940    }941942    // Check channel943    {944        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });945        defer gpa.free(r.stdout);946        defer gpa.free(r.stderr);947        const has_channel = r.exit_code == 0 and r.stdout.len > 0;948        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });949    }950951    return checks.toOwnedSlice(gpa);952}953954// --- Log ---955956pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {957    const home = environ.get("HOME") orelse return error.FileNotFound;958    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});959    defer gpa.free(path);960    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;961    if (last == 0) return content;962963    // Collect non-empty lines, then keep only the final `last`. Slices point into964    // `content`, so copy them out before freeing it.965    var lines: std.ArrayList([]const u8) = .empty;966    defer lines.deinit(gpa);967    var it = std.mem.splitScalar(u8, content, '\n');968    while (it.next()) |line| {969        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;970        try lines.append(gpa, line);971    }972    if (lines.items.len <= last) return content;973974    var out: std.ArrayList(u8) = .empty;975    errdefer out.deinit(gpa);976    for (lines.items[lines.items.len - last ..]) |line| {977        try out.appendSlice(gpa, line);978        try out.append(gpa, '\n');979    }980    gpa.free(content);981    return out.toOwnedSlice(gpa);982}983984// nina is a one-shot process, so "did the last apply fail this session?" can't985// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the986// other ~/.nina-* state files. This lets a later successful apply earn the987// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.988pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {989    const home = environ.get("HOME") orelse return;990    var buf: [512]u8 = undefined;991    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;992    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;993    file.close(io);994}995996pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {997    const home = environ.get("HOME") orelse return false;998    var buf: [512]u8 = undefined;999    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1000    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1001        f.close(io);1002        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1003        return true;1004    } else |_| {1005        return false;1006    }1007}10081009pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1010    const home = environ.get("HOME") orelse return;1011    var path_buf: [512]u8 = undefined;1012    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1013    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1014        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1015    defer file.close(io);1016    const size = file.length(io) catch 0;1017    file.writePositionalAll(io, entry, size) catch {};1018}10191020// --- Update helpers ---10211022// Fetch a URL with curl and return the response body. Caller must free.1023// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.1024pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1025    const argv = [_][]const u8{1026        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1027    };1028    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1029    defer gpa.free(result.stderr);10301031    const marker = "\nHTTP_STATUS:";1032    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1033        gpa.free(result.stdout);1034        return error.NetworkError;1035    };1036    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1037    const status = std.fmt.parseInt(u16, status_str, 10) catch {1038        gpa.free(result.stdout);1039        return error.NetworkError;1040    };1041    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1042    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1043    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1044        gpa.free(result.stdout);1045        return e;1046    };1047    gpa.free(result.stdout);1048    return body;1049}10501051// Download a URL to a temp file. Returns the temp path (caller must gpa.free).1052// The file is written to /tmp/nina-update-<pid> and left for the caller to use.1053pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1054    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1055    errdefer gpa.free(tmp_path);10561057    var child = std.process.spawn(io, .{1058        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1059        .stdin = .close,1060        .stdout = .close,1061        .stderr = .inherit,1062    }) catch return error.NetworkError;1063    const term = child.wait(io) catch return error.NetworkError;1064    switch (term) {1065        .exited => |c| if (c != 0) return error.NetworkError,1066        else => return error.NetworkError,1067    }1068    return tmp_path;1069}10701071// Get the current executable path into buf. Returns slice of buf.1072pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1073    const len = try std.process.executablePath(io, buf);1074    return buf[0..len];1075}10761077// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1078// atomically install the binary to install_path. Errors: ChecksumMismatch,1079// AccessDenied (with error_info set), or underlying I/O errors.1080pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1081    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1082        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1083        return error.FileNotFound;1084    };1085    defer gpa.free(bytes);10861087    var hasher = std.crypto.hash.Blake3.init(.{});1088    hasher.update(bytes);1089    var raw: [32]u8 = undefined;1090    hasher.final(&raw);1091    const hex = std.fmt.bytesToHex(raw, .lower);1092    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;10931094    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1095    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1096        return error.NameTooLong;10971098    {1099        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1100            errors.error_info.setMessage("cannot write to {s}", .{install_path});1101            errors.error_info.setSuggestion("try: sudo nina update", .{});1102            return error.AccessDenied;1103        };1104        defer f.close(io);1105        f.writePositionalAll(io, bytes, 0) catch {1106            errors.error_info.setMessage("cannot write to {s}", .{install_path});1107            return error.AccessDenied;1108        };1109        try f.setPermissions(io, .fromMode(0o755));1110    }1111    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};11121113    if (comptime builtin.os.tag == .macos) {1114        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1115    }11161117    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1118        error.AccessDenied => {1119            errors.error_info.setMessage("cannot replace {s}", .{install_path});1120            errors.error_info.setSuggestion("try: sudo nina update", .{});1121            return error.AccessDenied;1122        },1123        else => return e,1124    };1125}11261127// --- Nix feature setup ---11281129pub const NixFeatureStatus = struct {1130    nix_command: bool = false,1131    flakes: bool = false,11321133    pub fn allEnabled(self: NixFeatureStatus) bool {1134        return self.nix_command and self.flakes;1135    }1136};11371138fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1139    var lines = std.mem.splitScalar(u8, conf, '\n');1140    while (lines.next()) |line| {1141        const trimmed = std.mem.trim(u8, line, " \t");1142        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1143        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1144        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1145    }1146}11471148pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1149    var status = NixFeatureStatus{};11501151    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1152        defer gpa.free(conf);1153        scanConfFeatures(conf, &status);1154    }11551156    if (environ.get("HOME")) |home| {1157        var buf: [512]u8 = undefined;1158        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1159        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1160            defer gpa.free(conf);1161            scanConfFeatures(conf, &status);1162        }1163    }11641165    return status;1166}11671168pub fn isNixOS(io: std.Io) bool {1169    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1170    file.close(io);1171    return true;1172}11731174// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.1175// Returns the path written (caller must free).1176pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1177    const home = environ.get("HOME") orelse {1178        errors.error_info.setMessage("HOME not set", .{});1179        return error.ConfigNotFound;1180    };11811182    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1183    defer gpa.free(dir_path);1184    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1185    errdefer gpa.free(file_path);11861187    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};11881189    const line = "experimental-features = nix-command flakes\n";1190    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1191        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1192        errors.error_info.setMessage("could not write {s}", .{file_path});1193        return error.FileNotFound;1194    });1195    defer file.close(io);11961197    const size = file.length(io) catch 0;1198    file.writePositionalAll(io, line, size) catch {1199        errors.error_info.setMessage("could not write {s}", .{file_path});1200        return error.FileNotFound;1201    };12021203    return file_path;1204}12051206// --- NixOS: declarative experimental-features ---1207//1208// On NixOS the permanent, declarative home for these flags is configuration.nix,1209// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves1210// the `nixos-rebuild switch` to the user.12111212pub const NIXOS_FEATURES_LINE =1213    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";12141215// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns1216// false on any read error so the caller still offers to add the line.1217pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1218    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1219    defer gpa.free(conf);1220    return std.mem.indexOf(u8, conf, "experimental-features") != null and1221        std.mem.indexOf(u8, conf, "nix-command") != null and1222        std.mem.indexOf(u8, conf, "flakes") != null;1223}12241225fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1226    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1227    return captureLocal(gpa, io, &.{ "sudo", "cat", path });1228}12291230// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix1231// (i.e. inside the top-level attribute set) and write it back via a single1232// `sudo cp`, which prompts for the password on the terminal. Returns an error1233// for the caller to fall back to printed manual instructions.1234pub fn appendFeaturesToNixosConfig(1235    gpa: std.mem.Allocator,1236    io: std.Io,1237    environ: *const std.process.Environ.Map,1238    path: []const u8,1239) !void {1240    const conf = readMaybeSudo(gpa, io, path) catch {1241        errors.error_info.setMessage("could not read {s}", .{path});1242        return error.ConfigNotFound;1243    };1244    defer gpa.free(conf);12451246    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared12471248    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1249        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1250        return error.MalformedConfig;1251    };12521253    const home = environ.get("HOME") orelse {1254        errors.error_info.setMessage("HOME not set", .{});1255        return error.ConfigNotFound;1256    };1257    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1258    defer gpa.free(tmp_path);12591260    var buf: std.ArrayList(u8) = .empty;1261    defer buf.deinit(gpa);1262    try buf.appendSlice(gpa, conf[0..brace]);1263    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1264    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");1265    try buf.appendSlice(gpa, "  ");1266    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1267    try buf.append(gpa, '\n');1268    try buf.appendSlice(gpa, conf[brace..]);12691270    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1271        errors.error_info.setMessage("could not write {s}", .{tmp_path});1272        return error.FileNotFound;1273    };1274    tmp.writePositionalAll(io, buf.items, 0) catch {1275        tmp.close(io);1276        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1277        errors.error_info.setMessage("could not write {s}", .{tmp_path});1278        return error.FileNotFound;1279    };1280    tmp.close(io);12811282    // Back up the existing config, then replace it — in one sudo call so the1283    // password is asked for at most once. Paths travel as positional args ($0,1284    // $1) to sidestep shell quoting.1285    const code = streamLocal(io, &.{1286        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1287    }) catch {1288        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1289        errors.error_info.setMessage("could not write {s}", .{path});1290        return error.ProcessFailed;1291    };1292    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1293    if (code != 0) {1294        errors.error_info.setMessage("sudo cp into {s} failed", .{path});1295        return error.ProcessFailed;1296    }1297}