exec.zig

55.7 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) ![]types.ServiceInfo {317    const r = try capture(gpa, io, machine, &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" });318    defer gpa.free(r.stderr);319    defer gpa.free(r.stdout);320    if (r.exit_code != 0) return error.ProcessFailed;321    return parseServices(gpa, r.stdout);322}323324fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {325    var svcs: std.ArrayList(types.ServiceInfo) = .empty;326    var lines = std.mem.splitScalar(u8, output_str, '\n');327    while (lines.next()) |line| {328        const trimmed = std.mem.trim(u8, line, " \t\r");329        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines330        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");331        const name = parts.next() orelse continue;332        _ = parts.next(); // load333        const active_str = parts.next() orelse continue;334        const sub_str = parts.next() orelse "unknown";335336        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))337            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)338        else if (std.mem.eql(u8, active_str, "failed"))339            .failed340        else341            .inactive;342343        try svcs.append(gpa, .{344            .name = try gpa.dupe(u8, name),345            .state = state,346            .uptime = null,347        });348    }349    return svcs.toOwnedSlice(gpa);350}351352pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8) !u8 {353    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.354    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });355}356357pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool) !u8 {358    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});359    defer gpa.free(n_str);360    if (follow) {361        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });362    }363    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });364}365366// --- Profile ---367368pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {369    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});370    defer gpa.free(pkg_ref);371    // `nix profile add` is the current verb; `install` is a deprecated alias that372    // prints a warning on modern nix.373    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });374}375376pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {377    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not378    // by flake ref — passing nixpkgs#ripgrep matches nothing.379    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });380}381382pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {383    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });384    defer gpa.free(r.stderr);385    if (r.exit_code != 0) return error.ProcessFailed;386    return r.stdout;387}388389// Machine-readable profile listing — caller parses elements -> name + version.390pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {391    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });392    defer gpa.free(r.stderr);393    if (r.exit_code != 0) {394        gpa.free(r.stdout);395        return error.ProcessFailed;396    }397    return r.stdout;398}399400// Returns the profile element name to pass to `nix profile remove/upgrade`401// (e.g. "nina" or "default"), or null if nina is not found. Caller owns the402// returned slice. A NixOS system-package install also resolves into /nix/store403// so the store path alone can't distinguish it from a profile install — the404// profile list can. A missing/empty profile (or no nix) returns null.405pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {406    const js = profileListJson(gpa, io, machine) catch return null;407    defer gpa.free(js);408    return profileJsonNinaElement(gpa, js);409}410411pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {412    const name = profileNinaElement(gpa, io, machine) orelse return false;413    gpa.free(name);414    return true;415}416417// True when a nix store path belongs to the nina package. Store paths have the418// form /nix/store/<32-char-hash>-<pname>-<version>[/<subpath>]. We check that419// the 33 chars after /nix/store/ are the hash+dash, and the pname that follows420// is exactly "nina" (followed by "-" or end-of-component).421fn storePathIsNina(path: []const u8) bool {422    const prefix = "/nix/store/";423    if (!std.mem.startsWith(u8, path, prefix)) return false;424    const rel = path[prefix.len..];425    // The store entry name ends at the first "/" (if any sub-path follows).426    const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];427    if (entry.len < 34) return false; // 32-char hash + dash + at least one char428    const pname_ver = entry[33..]; // skip hash + dash429    return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");430}431432// Pure parse of `nix profile list --json` for a nina element, returning its433// element name (the key to pass to `nix profile remove/upgrade`) or null.434// Newer nix (2.18+) keys elements by pname ("nina"). Older nix uses an array435// with an "attrPath" field. Tarball installs via the `default` output may use436// the key "default" instead of "nina"; we detect those via storePaths.437fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {438    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;439    defer parsed.deinit();440    const root = parsed.value;441    if (root != .object) return null;442    const elements = root.object.get("elements") orelse return null;443    switch (elements) {444        .object => |obj| {445            // Fast path: exact "nina" key (nix 2.18+ with nixpkgs#nina install).446            if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;447            // Fallback: scan storePaths. Handles tarball installs where the default448            // output is selected and nix names the element "default" (older nix) or449            // some other key derived from the attrPath rather than the pname.450            var it = obj.iterator();451            while (it.next()) |kv| {452                const val = kv.value_ptr.*;453                if (val != .object) continue;454                const sps = val.object.get("storePaths") orelse continue;455                if (sps != .array) continue;456                for (sps.array.items) |sp| {457                    if (sp == .string and storePathIsNina(sp.string))458                        return gpa.dupe(u8, kv.key_ptr.*) catch null;459                }460            }461            return null;462        },463        .array => |arr| {464            // Older nix array format. Element name is the last component of attrPath.465            for (arr.items) |el| {466                if (el != .object) continue;467                const ap = el.object.get("attrPath") orelse continue;468                if (ap != .string) continue;469                if (std.mem.eql(u8, ap.string, "nina") or470                    std.mem.endsWith(u8, ap.string, ".nina"))471                    return gpa.dupe(u8, "nina") catch null;472                // Tarball default-output install: attrPath ends in ".default" but473                // storePaths point to nina. Return "default" as the element name.474                const sps = el.object.get("storePaths") orelse continue;475                if (sps != .array) continue;476                for (sps.array.items) |sp| {477                    if (sp != .string) continue;478                    if (!storePathIsNina(sp.string)) continue;479                    const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;480                    const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;481                    return gpa.dupe(u8, el_name) catch null;482                }483            }484            return null;485        },486        else => return null,487    }488}489490test "profileJsonNinaElement finds element name from profile JSON" {491    const a = std.testing.allocator;492493    // Newer nix: elements keyed by pname. "nina" key present.494    const named =495        \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},496        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}497    ;498    const r1 = profileJsonNinaElement(a, named);499    defer if (r1) |n| a.free(n);500    try std.testing.expectEqualStrings("nina", r1.?);501502    // Tarball install via default output: element keyed as "default", storePath is nina.503    const default_key =504        \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}505    ;506    const r2 = profileJsonNinaElement(a, default_key);507    defer if (r2) |n| a.free(n);508    try std.testing.expectEqualStrings("default", r2.?);509510    // Decoy: storePath of another package contains "nina" as a substring but is not nina.511    const decoy =512        \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}513    ;514    const r3 = profileJsonNinaElement(a, decoy);515    try std.testing.expectEqual(@as(?[]const u8, null), r3);516517    // Older nix array schema, attrPath ending in ".nina".518    const arr =519        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}520    ;521    const r4 = profileJsonNinaElement(a, arr);522    defer if (r4) |n| a.free(n);523    try std.testing.expectEqualStrings("nina", r4.?);524525    // Older nix array schema, tarball default-output install.526    const arr_default =527        \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}528    ;529    const r5 = profileJsonNinaElement(a, arr_default);530    defer if (r5) |n| a.free(n);531    try std.testing.expectEqualStrings("default", r5.?);532533    // Empty / malformed → null.534    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));535    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));536}537538// The store paths that make up the running system environment. Each reference is539// a <hash>-<name>-<version> path, so the caller can list system packages with540// versions — there is no cleaner per-package list for environment.systemPackages.541pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {542    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });543    defer gpa.free(r.stderr);544    if (r.exit_code != 0) {545        gpa.free(r.stdout);546        return error.ProcessFailed;547    }548    return r.stdout;549}550551pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {552    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });553}554555// --- Store ---556557pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {558    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });559}560561pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {562    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });563}564565pub const SystemStatus = struct { size: []u8, age: []u8 };566567// One read-only pass for `nina status`: the current system's closure size (a568// single `path-info -S` of /run/current-system — fast, unlike -S over the whole569// store) and seconds since the system profile was last switched (its symlink570// mtime). Both are world-readable; no root needed.571const STATUS_SCRIPT =572    \\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} ))"573;574575pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {576    const unknown = SystemStatus{577        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },578        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },579    };580    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;581    defer gpa.free(r.stdout);582    defer gpa.free(r.stderr);583    if (r.exit_code != 0) return unknown;584585    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");586    const sz_str = it.next() orelse return unknown;587    const age_str = it.next() orelse return unknown;588    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;589    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;590591    gpa.free(unknown.size);592    gpa.free(unknown.age);593    return .{594        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),595        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),596    };597}598599// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A600// one-word health signal; exits non-zero when degraded, so we read stdout, not601// the code. Caller owns the returned slice.602pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {603    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch604        return gpa.dupe(u8, "unknown");605    defer gpa.free(r.stderr);606    const state = std.mem.trim(u8, r.stdout, " \t\n\r");607    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");608    gpa.free(r.stdout);609    return owned;610}611612fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {613    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});614    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});615    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});616    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});617}618619pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {620    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });621}622623pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {624    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)625    // graph work that takes minutes on a real store (59k+ paths) and hangs the626    // command. We don't need closures: `--all --json` (no -S) carries each path's627    // own narSize, so one fast pass gives the path count and the summed store size.628    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.629    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.630    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });631    defer gpa.free(pi.stdout);632    defer gpa.free(pi.stderr);633634    const scan = scanStoreJson(pi.stdout);635    const total_owned = try humanSize(gpa, scan.total_bytes);636637    return .{638        .total_size = total_owned,639        .live_paths = scan.count,640        .reclaimable_paths = 0,641    };642}643644const StoreScan = struct { count: u64, total_bytes: u64 };645646// One linear pass over `nix path-info --json`: each path object has exactly one647// "narSize": field, so counting them gives the true path count and summing the648// values gives the total store size — no per-path closure walk.649fn scanStoreJson(json_str: []const u8) StoreScan {650    const needle = "\"narSize\":";651    var count: u64 = 0;652    var total: u64 = 0;653    var i: usize = 0;654    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {655        var j = pos + needle.len;656        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}657        var val: u64 = 0;658        var any = false;659        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {660            val = val * 10 + (json_str[j] - '0');661            any = true;662        }663        if (any) {664            count += 1;665            total += val;666        }667        i = j;668    }669    return .{ .count = count, .total_bytes = total };670}671672fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {673    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };674    var val: f64 = @floatFromInt(bytes);675    var unit: usize = 0;676    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;677    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });678    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });679}680681pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {682    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the683    // flake registry), not a flake in the current directory.684    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});685    defer gpa.free(expr);686    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });687    defer gpa.free(r.stderr);688    if (r.exit_code != 0) {689        gpa.free(r.stdout);690        return error.ProcessFailed;691    }692    return r.stdout;693}694695// --- Flake ---696697pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {698    if (input) |inp| {699        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });700    }701    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });702}703704pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {705    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });706}707708pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {709    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });710}711712pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {713    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });714}715716pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {717    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });718}719720pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {721    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });722    defer gpa.free(r.stderr);723    if (r.exit_code != 0) {724        gpa.free(r.stdout);725        return error.ProcessFailed;726    }727    return r.stdout;728}729730// --- Build / Run / Develop ---731732pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {733    if (attr) |a| {734        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});735        defer gpa.free(ref);736        return stream(io, machine, gpa, &.{ "nix", "build", ref });737    }738    return stream(io, machine, gpa, &.{ "nix", "build" });739}740741pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {742    // nix run always gets --no-write-lock-file for remote URLs743    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");744    if (is_url) {745        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });746    }747    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.748    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {749        return stream(io, machine, gpa, &.{ "nix", "run", pkg });750    }751    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});752    defer gpa.free(ref);753    return stream(io, machine, gpa, &.{ "nix", "run", ref });754}755756pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {757    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});758    defer gpa.free(ref);759    return stream(io, machine, gpa, &.{ "nix", "shell", ref });760}761762pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {763    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});764    defer gpa.free(ref);765    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});766    defer gpa.free(ps1);767    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);768}769770pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {771    if (run_cmd) |cmd| {772        // sh -c so a multi-word command isn't treated as a single executable name.773        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });774    }775    return stream(io, machine, gpa, &.{ "nix", "develop" });776}777778pub 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 {779    if (run_cmd) |cmd| {780        // sh -c so a multi-word command isn't treated as a single executable name.781        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });782    }783    return streamEnv(io, machine, gpa, &.{ "nix", "develop" }, base_env, "(nina: dev) -> ");784}785786pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {787    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });788}789790// --- Format ---791792pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {793    if (check) {794        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });795    }796    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });797}798799// --- Info ---800801pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {802    const r = try capture(gpa, io, machine, &.{"nixos-version"});803    defer gpa.free(r.stderr);804    if (r.exit_code != 0) {805        gpa.free(r.stdout);806        return error.ProcessFailed;807    }808    return r.stdout;809}810811pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {812    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });813    defer gpa.free(r.stderr);814    if (r.exit_code != 0) {815        gpa.free(r.stdout);816        return error.ProcessFailed;817    }818    return r.stdout;819}820821pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {822    const r = try capture(gpa, io, machine, &.{"uptime"});823    defer gpa.free(r.stderr);824    if (r.exit_code != 0) {825        gpa.free(r.stdout);826        return error.ProcessFailed;827    }828    return r.stdout;829}830831// --- Boot ---832833pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {834    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });835    defer gpa.free(r.stderr);836    defer gpa.free(r.stdout);837    if (r.exit_code != 0) return error.ProcessFailed;838    return parseBootEntries(gpa, r.stdout);839}840841fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {842    var entries: std.ArrayList(types.BootEntry) = .empty;843    var lines = std.mem.splitScalar(u8, output_str, '\n');844    while (lines.next()) |line| {845        const trimmed = std.mem.trim(u8, line, " \t\r");846        if (std.mem.startsWith(u8, trimmed, "title:")) {847            const title = std.mem.trim(u8, trimmed[6..], " \t");848            const current = std.mem.indexOf(u8, title, "(current)") != null;849            try entries.append(gpa, .{850                .title = try gpa.dupe(u8, title),851                .current = current,852            });853        }854    }855    return entries.toOwnedSlice(gpa);856}857858// --- Pkg info ---859860pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {861    return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });862}863864pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {865    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });866}867868pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {869    // A bare name ("ripgrep") isn't a valid installable; resolve via nixpkgs# like870    // `pkg path` does. -S -h gives closure size, human-readable. Output is871    // "<store-path>   <size>"; return just the size.872    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});873    defer gpa.free(ref);874    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref });875    defer gpa.free(r.stderr);876    defer gpa.free(r.stdout);877    if (r.exit_code != 0) return error.ProcessFailed;878879    const line = std.mem.trim(u8, r.stdout, " \t\n\r");880    var it = std.mem.tokenizeAny(u8, line, " \t");881    _ = it.next(); // store path882    const size = std.mem.trim(u8, it.rest(), " \t");883    if (size.len == 0) return error.ProcessFailed;884    return gpa.dupe(u8, size);885}886887pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {888    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });889}890891// --- Hash / Fetch ---892893pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {894    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });895    defer gpa.free(r.stderr);896    if (r.exit_code != 0) {897        gpa.free(r.stdout);898        return error.ProcessFailed;899    }900    return r.stdout;901}902903pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {904    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });905    defer gpa.free(r.stderr);906    if (r.exit_code != 0) {907        gpa.free(r.stdout);908        return error.ProcessFailed;909    }910    return r.stdout;911}912913// --- Pin ---914915pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {916    // Stub: full implementation would parse and edit flake.lock JSON917    // The pin/unpin flow works via nix flake update which regenerates flake.lock918}919920pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {921    if (line) |l| {922        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});923        defer gpa.free(line_arg);924        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });925    }926    return stream(io, &types.Machine{}, gpa, &.{ editor, path });927}928929pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {930    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});931    defer gpa.free(a_str);932    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});933    defer gpa.free(b_str);934    // On a tty, the child's own color is fine — stream it directly.935    if (output.colorEnabled()) {936        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });937    }938    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,939    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.940    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });941    defer gpa.free(r.stdout);942    defer gpa.free(r.stderr);943    const cleaned = try stripAnsi(gpa, r.stdout);944    defer gpa.free(cleaned);945    output.raw(cleaned);946    return r.exit_code;947}948949// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a950// child process's color when it writes ANSI unconditionally.951fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {952    var out: std.ArrayList(u8) = .empty;953    errdefer out.deinit(gpa);954    var i: usize = 0;955    while (i < input.len) {956        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {957            i += 2;958            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}959            if (i < input.len) i += 1; // consume the final byte960            continue;961        }962        try out.append(gpa, input[i]);963        i += 1;964    }965    return out.toOwnedSlice(gpa);966}967968test "stripAnsi removes CSI color sequences" {969    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");970    defer std.testing.allocator.free(cleaned);971    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);972}973974// --- Doctor checks ---975976pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {977    var checks: std.ArrayList(types.DoctorCheck) = .empty;978979    // Check nix daemon980    {981        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });982        defer gpa.free(r.stdout);983        defer gpa.free(r.stderr);984        const active = std.mem.indexOf(u8, r.stdout, "active") != null;985        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });986    }987988    // Check config syntax989    {990        const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });991        defer gpa.free(r.stdout);992        defer gpa.free(r.stderr);993        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });994    }995996    // Check channel997    {998        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });999        defer gpa.free(r.stdout);1000        defer gpa.free(r.stderr);1001        const has_channel = r.exit_code == 0 and r.stdout.len > 0;1002        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1003    }10041005    return checks.toOwnedSlice(gpa);1006}10071008// --- Log ---10091010pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1011    const home = environ.get("HOME") orelse return error.FileNotFound;1012    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1013    defer gpa.free(path);1014    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1015    if (last == 0) return content;10161017    // Collect non-empty lines, then keep only the final `last`. Slices point into1018    // `content`, so copy them out before freeing it.1019    var lines: std.ArrayList([]const u8) = .empty;1020    defer lines.deinit(gpa);1021    var it = std.mem.splitScalar(u8, content, '\n');1022    while (it.next()) |line| {1023        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1024        try lines.append(gpa, line);1025    }1026    if (lines.items.len <= last) return content;10271028    var out: std.ArrayList(u8) = .empty;1029    errdefer out.deinit(gpa);1030    for (lines.items[lines.items.len - last ..]) |line| {1031        try out.appendSlice(gpa, line);1032        try out.append(gpa, '\n');1033    }1034    gpa.free(content);1035    return out.toOwnedSlice(gpa);1036}10371038// nina is a one-shot process, so "did the last apply fail this session?" can't1039// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1040// other ~/.nina-* state files. This lets a later successful apply earn the1041// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1042pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1043    const home = environ.get("HOME") orelse return;1044    var buf: [512]u8 = undefined;1045    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1046    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1047    file.close(io);1048}10491050pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1051    const home = environ.get("HOME") orelse return false;1052    var buf: [512]u8 = undefined;1053    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1054    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1055        f.close(io);1056        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1057        return true;1058    } else |_| {1059        return false;1060    }1061}10621063pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1064    const home = environ.get("HOME") orelse return;1065    var path_buf: [512]u8 = undefined;1066    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1067    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1068        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1069    defer file.close(io);1070    const size = file.length(io) catch 0;1071    file.writePositionalAll(io, entry, size) catch {};1072}10731074// --- Update helpers ---10751076// Fetch a URL with curl and return the response body. Caller must free.1077// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.1078pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1079    const argv = [_][]const u8{1080        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1081    };1082    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1083    defer gpa.free(result.stderr);10841085    const marker = "\nHTTP_STATUS:";1086    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1087        gpa.free(result.stdout);1088        return error.NetworkError;1089    };1090    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1091    const status = std.fmt.parseInt(u16, status_str, 10) catch {1092        gpa.free(result.stdout);1093        return error.NetworkError;1094    };1095    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1096    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1097    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1098        gpa.free(result.stdout);1099        return e;1100    };1101    gpa.free(result.stdout);1102    return body;1103}11041105// Download a URL to a temp file. Returns the temp path (caller must gpa.free).1106// The file is written to /tmp/nina-update-<pid> and left for the caller to use.1107pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1108    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1109    errdefer gpa.free(tmp_path);11101111    var child = std.process.spawn(io, .{1112        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1113        .stdin = .close,1114        .stdout = .close,1115        .stderr = .inherit,1116    }) catch return error.NetworkError;1117    const term = child.wait(io) catch return error.NetworkError;1118    switch (term) {1119        .exited => |c| if (c != 0) return error.NetworkError,1120        else => return error.NetworkError,1121    }1122    return tmp_path;1123}11241125// Get the current executable path into buf. Returns slice of buf.1126pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1127    const len = try std.process.executablePath(io, buf);1128    return buf[0..len];1129}11301131// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1132// atomically install the binary to install_path. Errors: ChecksumMismatch,1133// AccessDenied (with error_info set), or underlying I/O errors.1134pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1135    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1136        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1137        return error.FileNotFound;1138    };1139    defer gpa.free(bytes);11401141    var hasher = std.crypto.hash.Blake3.init(.{});1142    hasher.update(bytes);1143    var raw: [32]u8 = undefined;1144    hasher.final(&raw);1145    const hex = std.fmt.bytesToHex(raw, .lower);1146    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;11471148    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1149    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1150        return error.NameTooLong;11511152    {1153        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1154            errors.error_info.setMessage("cannot write to {s}", .{install_path});1155            errors.error_info.setSuggestion("try: sudo nina update", .{});1156            return error.AccessDenied;1157        };1158        defer f.close(io);1159        f.writePositionalAll(io, bytes, 0) catch {1160            errors.error_info.setMessage("cannot write to {s}", .{install_path});1161            return error.AccessDenied;1162        };1163        try f.setPermissions(io, .fromMode(0o755));1164    }1165    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};11661167    if (comptime builtin.os.tag == .macos) {1168        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1169    }11701171    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1172        error.AccessDenied => {1173            errors.error_info.setMessage("cannot replace {s}", .{install_path});1174            errors.error_info.setSuggestion("try: sudo nina update", .{});1175            return error.AccessDenied;1176        },1177        else => return e,1178    };1179}11801181// --- Nix feature setup ---11821183pub const NixFeatureStatus = struct {1184    nix_command: bool = false,1185    flakes: bool = false,11861187    pub fn allEnabled(self: NixFeatureStatus) bool {1188        return self.nix_command and self.flakes;1189    }1190};11911192fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1193    var lines = std.mem.splitScalar(u8, conf, '\n');1194    while (lines.next()) |line| {1195        const trimmed = std.mem.trim(u8, line, " \t");1196        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1197        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1198        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1199    }1200}12011202pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1203    var status = NixFeatureStatus{};12041205    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1206        defer gpa.free(conf);1207        scanConfFeatures(conf, &status);1208    }12091210    if (environ.get("HOME")) |home| {1211        var buf: [512]u8 = undefined;1212        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1213        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1214            defer gpa.free(conf);1215            scanConfFeatures(conf, &status);1216        }1217    }12181219    return status;1220}12211222pub fn isNixOS(io: std.Io) bool {1223    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1224    file.close(io);1225    return true;1226}12271228// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.1229// Returns the path written (caller must free).1230pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1231    const home = environ.get("HOME") orelse {1232        errors.error_info.setMessage("HOME not set", .{});1233        return error.ConfigNotFound;1234    };12351236    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1237    defer gpa.free(dir_path);1238    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1239    errdefer gpa.free(file_path);12401241    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};12421243    const line = "experimental-features = nix-command flakes\n";1244    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1245        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1246        errors.error_info.setMessage("could not write {s}", .{file_path});1247        return error.FileNotFound;1248    });1249    defer file.close(io);12501251    const size = file.length(io) catch 0;1252    file.writePositionalAll(io, line, size) catch {1253        errors.error_info.setMessage("could not write {s}", .{file_path});1254        return error.FileNotFound;1255    };12561257    return file_path;1258}12591260// --- NixOS: declarative experimental-features ---1261//1262// On NixOS the permanent, declarative home for these flags is configuration.nix,1263// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves1264// the `nixos-rebuild switch` to the user.12651266pub const NIXOS_FEATURES_LINE =1267    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";12681269// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns1270// false on any read error so the caller still offers to add the line.1271pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1272    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1273    defer gpa.free(conf);1274    return std.mem.indexOf(u8, conf, "experimental-features") != null and1275        std.mem.indexOf(u8, conf, "nix-command") != null and1276        std.mem.indexOf(u8, conf, "flakes") != null;1277}12781279fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1280    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1281    return captureLocal(gpa, io, &.{ "sudo", "cat", path });1282}12831284// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix1285// (i.e. inside the top-level attribute set) and write it back via a single1286// `sudo cp`, which prompts for the password on the terminal. Returns an error1287// for the caller to fall back to printed manual instructions.1288pub fn appendFeaturesToNixosConfig(1289    gpa: std.mem.Allocator,1290    io: std.Io,1291    environ: *const std.process.Environ.Map,1292    path: []const u8,1293) !void {1294    const conf = readMaybeSudo(gpa, io, path) catch {1295        errors.error_info.setMessage("could not read {s}", .{path});1296        return error.ConfigNotFound;1297    };1298    defer gpa.free(conf);12991300    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared13011302    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1303        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1304        return error.MalformedConfig;1305    };13061307    const home = environ.get("HOME") orelse {1308        errors.error_info.setMessage("HOME not set", .{});1309        return error.ConfigNotFound;1310    };1311    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1312    defer gpa.free(tmp_path);13131314    var buf: std.ArrayList(u8) = .empty;1315    defer buf.deinit(gpa);1316    try buf.appendSlice(gpa, conf[0..brace]);1317    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1318    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");1319    try buf.appendSlice(gpa, "  ");1320    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1321    try buf.append(gpa, '\n');1322    try buf.appendSlice(gpa, conf[brace..]);13231324    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1325        errors.error_info.setMessage("could not write {s}", .{tmp_path});1326        return error.FileNotFound;1327    };1328    tmp.writePositionalAll(io, buf.items, 0) catch {1329        tmp.close(io);1330        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1331        errors.error_info.setMessage("could not write {s}", .{tmp_path});1332        return error.FileNotFound;1333    };1334    tmp.close(io);13351336    // Back up the existing config, then replace it — in one sudo call so the1337    // password is asked for at most once. Paths travel as positional args ($0,1338    // $1) to sidestep shell quoting.1339    const code = streamLocal(io, &.{1340        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1341    }) catch {1342        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1343        errors.error_info.setMessage("could not write {s}", .{path});1344        return error.ProcessFailed;1345    };1346    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1347    if (code != 0) {1348        errors.error_info.setMessage("sudo cp into {s} failed", .{path});1349        return error.ProcessFailed;1350    }1351}