exec.zig

55.4 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}138139fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {140    if (machine.local) return cmd;141142    const host = machine.host orelse {143        errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});144        return error.SshFailed;145    };146147    var ssh: std.ArrayList([]const u8) = .empty;148    try ssh.append(gpa, "ssh");149    try ssh.append(gpa, "-o");150    try ssh.append(gpa, "BatchMode=yes");151    try ssh.append(gpa, "-o");152    try ssh.append(gpa, "StrictHostKeyChecking=accept-new");153    if (machine.ssh_key) |key| {154        try ssh.append(gpa, "-i");155        try ssh.append(gpa, key);156    }157    const addr = if (machine.user) |u|158        try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })159    else160        try gpa.dupe(u8, host);161    try ssh.append(gpa, addr);162    for (cmd) |arg| try ssh.append(gpa, arg);163    return ssh.toOwnedSlice(gpa);164}165166// --- NixOS rebuild ---167168pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {169    const cmd = &.{ "sudo", "nixos-rebuild", "switch" };170    output.printSubstep("nixos-rebuild switch", .{});171    return stream(io, machine, gpa, cmd);172}173174pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {175    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "dry-activate" });176}177178pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {179    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "build" });180}181182// --- Generations ---183184// Read system-profile generations WITHOUT root. `nix-env --list-generations -p185// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user186// ("system.lock: Permission denied"). The generation symlinks themselves are187// world-readable, so list them directly: parse `system-N-link` names, take each188// link's own mtime for the date/time, and mark the one the `system` symlink189// points at as current. Output matches the `nix-env --list-generations` columns190// (num date time [current]) so parseGenerations is unchanged.191const GEN_LIST_SCRIPT =192    \\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 }'193;194195pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {196    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });197    defer gpa.free(r.stderr);198    defer gpa.free(r.stdout);199    if (r.exit_code != 0) return error.ProcessFailed;200    return parseGenerations(gpa, r.stdout);201}202203fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {204    var gens: std.ArrayList(types.GenerationInfo) = .empty;205    var lines = std.mem.splitScalar(u8, output_str, '\n');206    while (lines.next()) |line| {207        const trimmed = std.mem.trim(u8, line, " \t");208        if (trimmed.len == 0) continue;209        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");210        const num_str = parts.next() orelse continue;211        const date_str = parts.next() orelse continue;212        const time_str = parts.next() orelse continue;213        const rest = parts.rest();214        const current = std.mem.indexOf(u8, rest, "current") != null;215        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;216        try gens.append(gpa, .{217            .number = num,218            .date = try gpa.dupe(u8, date_str),219            .time = try gpa.dupe(u8, time_str),220            .current = current,221        });222    }223    return gens.toOwnedSlice(gpa);224}225226pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {227    const gens = try getGenerations(gpa, io, machine);228    defer gpa.free(gens);229    for (gens) |g| {230        if (g.current) return g.number;231    }232    return 0;233}234235pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {236    // Switch the system profile to generation n, then activate it (bootloader +237    // services). Without switch-to-configuration the change isn't applied.238    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 });239    defer gpa.free(cmd);240    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });241}242243pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {244    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });245}246247pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {248    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});249    defer gpa.free(n_str);250    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });251}252253pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {254    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });255}256257// --- Garbage collection ---258259pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {260    if (delete_old) {261        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });262    }263    // Keep the `keep` most recent system generations (+N deletes all but N),264    // then collect now-unreferenced store paths. `--delete-older-than` wants a265    // duration (e.g. 14d), not a generation count.266    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });267    defer gpa.free(cmd);268    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });269}270271// --- Channels ---272273pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {274    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });275    defer gpa.free(r.stderr);276    defer gpa.free(r.stdout);277    if (r.exit_code != 0) return error.ProcessFailed;278    return parseChannels(gpa, r.stdout);279}280281fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {282    var channels: std.ArrayList(types.ChannelInfo) = .empty;283    var lines = std.mem.splitScalar(u8, output_str, '\n');284    while (lines.next()) |line| {285        const trimmed = std.mem.trim(u8, line, " \t\r");286        if (trimmed.len == 0) continue;287        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;288        try channels.append(gpa, .{289            .name = try gpa.dupe(u8, trimmed[0..space]),290            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),291        });292    }293    return channels.toOwnedSlice(gpa);294}295296pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {297    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });298}299300pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {301    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });302}303304pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {305    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });306}307308// --- Services ---309310pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ServiceInfo {311    const r = try capture(gpa, io, machine, &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" });312    defer gpa.free(r.stderr);313    defer gpa.free(r.stdout);314    if (r.exit_code != 0) return error.ProcessFailed;315    return parseServices(gpa, r.stdout);316}317318fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {319    var svcs: std.ArrayList(types.ServiceInfo) = .empty;320    var lines = std.mem.splitScalar(u8, output_str, '\n');321    while (lines.next()) |line| {322        const trimmed = std.mem.trim(u8, line, " \t\r");323        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines324        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");325        const name = parts.next() orelse continue;326        _ = parts.next(); // load327        const active_str = parts.next() orelse continue;328        const sub_str = parts.next() orelse "unknown";329330        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))331            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)332        else if (std.mem.eql(u8, active_str, "failed"))333            .failed334        else335            .inactive;336337        try svcs.append(gpa, .{338            .name = try gpa.dupe(u8, name),339            .state = state,340            .uptime = null,341        });342    }343    return svcs.toOwnedSlice(gpa);344}345346pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8) !u8 {347    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.348    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });349}350351pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool) !u8 {352    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});353    defer gpa.free(n_str);354    if (follow) {355        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });356    }357    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });358}359360// --- Profile ---361362pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {363    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});364    defer gpa.free(pkg_ref);365    // `nix profile add` is the current verb; `install` is a deprecated alias that366    // prints a warning on modern nix.367    return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });368}369370pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {371    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not372    // by flake ref — passing nixpkgs#ripgrep matches nothing.373    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });374}375376pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {377    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });378    defer gpa.free(r.stderr);379    if (r.exit_code != 0) return error.ProcessFailed;380    return r.stdout;381}382383// Machine-readable profile listing — caller parses elements -> name + version.384pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {385    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });386    defer gpa.free(r.stderr);387    if (r.exit_code != 0) {388        gpa.free(r.stdout);389        return error.ProcessFailed;390    }391    return r.stdout;392}393394// Returns the profile element name to pass to `nix profile remove/upgrade`395// (e.g. "nina" or "default"), or null if nina is not found. Caller owns the396// returned slice. A NixOS system-package install also resolves into /nix/store397// so the store path alone can't distinguish it from a profile install — the398// profile list can. A missing/empty profile (or no nix) returns null.399pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {400    const js = profileListJson(gpa, io, machine) catch return null;401    defer gpa.free(js);402    return profileJsonNinaElement(gpa, js);403}404405pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {406    const name = profileNinaElement(gpa, io, machine) orelse return false;407    gpa.free(name);408    return true;409}410411// True when a nix store path belongs to the nina package. Store paths have the412// form /nix/store/<32-char-hash>-<pname>-<version>[/<subpath>]. We check that413// the 33 chars after /nix/store/ are the hash+dash, and the pname that follows414// is exactly "nina" (followed by "-" or end-of-component).415fn storePathIsNina(path: []const u8) bool {416    const prefix = "/nix/store/";417    if (!std.mem.startsWith(u8, path, prefix)) return false;418    const rel = path[prefix.len..];419    // The store entry name ends at the first "/" (if any sub-path follows).420    const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];421    if (entry.len < 34) return false; // 32-char hash + dash + at least one char422    const pname_ver = entry[33..]; // skip hash + dash423    return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");424}425426// Pure parse of `nix profile list --json` for a nina element, returning its427// element name (the key to pass to `nix profile remove/upgrade`) or null.428// Newer nix (2.18+) keys elements by pname ("nina"). Older nix uses an array429// with an "attrPath" field. Tarball installs via the `default` output may use430// the key "default" instead of "nina"; we detect those via storePaths.431fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {432    var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;433    defer parsed.deinit();434    const root = parsed.value;435    if (root != .object) return null;436    const elements = root.object.get("elements") orelse return null;437    switch (elements) {438        .object => |obj| {439            // Fast path: exact "nina" key (nix 2.18+ with nixpkgs#nina install).440            if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;441            // Fallback: scan storePaths. Handles tarball installs where the default442            // output is selected and nix names the element "default" (older nix) or443            // some other key derived from the attrPath rather than the pname.444            var it = obj.iterator();445            while (it.next()) |kv| {446                const val = kv.value_ptr.*;447                if (val != .object) continue;448                const sps = val.object.get("storePaths") orelse continue;449                if (sps != .array) continue;450                for (sps.array.items) |sp| {451                    if (sp == .string and storePathIsNina(sp.string))452                        return gpa.dupe(u8, kv.key_ptr.*) catch null;453                }454            }455            return null;456        },457        .array => |arr| {458            // Older nix array format. Element name is the last component of attrPath.459            for (arr.items) |el| {460                if (el != .object) continue;461                const ap = el.object.get("attrPath") orelse continue;462                if (ap != .string) continue;463                if (std.mem.eql(u8, ap.string, "nina") or464                    std.mem.endsWith(u8, ap.string, ".nina"))465                    return gpa.dupe(u8, "nina") catch null;466                // Tarball default-output install: attrPath ends in ".default" but467                // storePaths point to nina. Return "default" as the element name.468                const sps = el.object.get("storePaths") orelse continue;469                if (sps != .array) continue;470                for (sps.array.items) |sp| {471                    if (sp != .string) continue;472                    if (!storePathIsNina(sp.string)) continue;473                    const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;474                    const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;475                    return gpa.dupe(u8, el_name) catch null;476                }477            }478            return null;479        },480        else => return null,481    }482}483484test "profileJsonNinaElement finds element name from profile JSON" {485    const a = std.testing.allocator;486487    // Newer nix: elements keyed by pname. "nina" key present.488    const named =489        \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},490        \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}491    ;492    const r1 = profileJsonNinaElement(a, named);493    defer if (r1) |n| a.free(n);494    try std.testing.expectEqualStrings("nina", r1.?);495496    // Tarball install via default output: element keyed as "default", storePath is nina.497    const default_key =498        \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}499    ;500    const r2 = profileJsonNinaElement(a, default_key);501    defer if (r2) |n| a.free(n);502    try std.testing.expectEqualStrings("default", r2.?);503504    // Decoy: storePath of another package contains "nina" as a substring but is not nina.505    const decoy =506        \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}507    ;508    const r3 = profileJsonNinaElement(a, decoy);509    try std.testing.expectEqual(@as(?[]const u8, null), r3);510511    // Older nix array schema, attrPath ending in ".nina".512    const arr =513        \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}514    ;515    const r4 = profileJsonNinaElement(a, arr);516    defer if (r4) |n| a.free(n);517    try std.testing.expectEqualStrings("nina", r4.?);518519    // Older nix array schema, tarball default-output install.520    const arr_default =521        \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}522    ;523    const r5 = profileJsonNinaElement(a, arr_default);524    defer if (r5) |n| a.free(n);525    try std.testing.expectEqualStrings("default", r5.?);526527    // Empty / malformed → null.528    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));529    try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));530}531532// The store paths that make up the running system environment. Each reference is533// a <hash>-<name>-<version> path, so the caller can list system packages with534// versions — there is no cleaner per-package list for environment.systemPackages.535pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {536    const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });537    defer gpa.free(r.stderr);538    if (r.exit_code != 0) {539        gpa.free(r.stdout);540        return error.ProcessFailed;541    }542    return r.stdout;543}544545pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {546    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });547}548549// --- Store ---550551pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {552    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });553}554555pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {556    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });557}558559pub const SystemStatus = struct { size: []u8, age: []u8 };560561// One read-only pass for `nina status`: the current system's closure size (a562// single `path-info -S` of /run/current-system — fast, unlike -S over the whole563// store) and seconds since the system profile was last switched (its symlink564// mtime). Both are world-readable; no root needed.565const STATUS_SCRIPT =566    \\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} ))"567;568569pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {570    const unknown = SystemStatus{571        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },572        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },573    };574    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;575    defer gpa.free(r.stdout);576    defer gpa.free(r.stderr);577    if (r.exit_code != 0) return unknown;578579    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");580    const sz_str = it.next() orelse return unknown;581    const age_str = it.next() orelse return unknown;582    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;583    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;584585    gpa.free(unknown.size);586    gpa.free(unknown.age);587    return .{588        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),589        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),590    };591}592593// `systemctl is-system-running` -> "running" / "degraded" / "starting" ... A594// one-word health signal; exits non-zero when degraded, so we read stdout, not595// the code. Caller owns the returned slice.596pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {597    const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch598        return gpa.dupe(u8, "unknown");599    defer gpa.free(r.stderr);600    const state = std.mem.trim(u8, r.stdout, " \t\n\r");601    const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");602    gpa.free(r.stdout);603    return owned;604}605606fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {607    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});608    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});609    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});610    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});611}612613pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {614    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });615}616617pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {618    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)619    // graph work that takes minutes on a real store (59k+ paths) and hangs the620    // command. We don't need closures: `--all --json` (no -S) carries each path's621    // own narSize, so one fast pass gives the path count and the summed store size.622    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.623    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.624    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });625    defer gpa.free(pi.stdout);626    defer gpa.free(pi.stderr);627628    const scan = scanStoreJson(pi.stdout);629    const total_owned = try humanSize(gpa, scan.total_bytes);630631    return .{632        .total_size = total_owned,633        .live_paths = scan.count,634        .reclaimable_paths = 0,635    };636}637638const StoreScan = struct { count: u64, total_bytes: u64 };639640// One linear pass over `nix path-info --json`: each path object has exactly one641// "narSize": field, so counting them gives the true path count and summing the642// values gives the total store size — no per-path closure walk.643fn scanStoreJson(json_str: []const u8) StoreScan {644    const needle = "\"narSize\":";645    var count: u64 = 0;646    var total: u64 = 0;647    var i: usize = 0;648    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {649        var j = pos + needle.len;650        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}651        var val: u64 = 0;652        var any = false;653        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {654            val = val * 10 + (json_str[j] - '0');655            any = true;656        }657        if (any) {658            count += 1;659            total += val;660        }661        i = j;662    }663    return .{ .count = count, .total_bytes = total };664}665666fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {667    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };668    var val: f64 = @floatFromInt(bytes);669    var unit: usize = 0;670    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;671    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });672    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });673}674675pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {676    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the677    // flake registry), not a flake in the current directory.678    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});679    defer gpa.free(expr);680    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });681    defer gpa.free(r.stderr);682    if (r.exit_code != 0) {683        gpa.free(r.stdout);684        return error.ProcessFailed;685    }686    return r.stdout;687}688689// --- Flake ---690691pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {692    if (input) |inp| {693        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });694    }695    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });696}697698pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {699    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });700}701702pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {703    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });704}705706pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {707    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });708}709710pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {711    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });712}713714pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {715    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });716    defer gpa.free(r.stderr);717    if (r.exit_code != 0) {718        gpa.free(r.stdout);719        return error.ProcessFailed;720    }721    return r.stdout;722}723724// --- Build / Run / Develop ---725726pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {727    if (attr) |a| {728        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});729        defer gpa.free(ref);730        return stream(io, machine, gpa, &.{ "nix", "build", ref });731    }732    return stream(io, machine, gpa, &.{ "nix", "build" });733}734735pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {736    // nix run always gets --no-write-lock-file for remote URLs737    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");738    if (is_url) {739        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });740    }741    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.742    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {743        return stream(io, machine, gpa, &.{ "nix", "run", pkg });744    }745    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});746    defer gpa.free(ref);747    return stream(io, machine, gpa, &.{ "nix", "run", ref });748}749750pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {751    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});752    defer gpa.free(ref);753    return stream(io, machine, gpa, &.{ "nix", "shell", ref });754}755756pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {757    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});758    defer gpa.free(ref);759    const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});760    defer gpa.free(ps1);761    return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);762}763764pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {765    if (run_cmd) |cmd| {766        // sh -c so a multi-word command isn't treated as a single executable name.767        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });768    }769    return stream(io, machine, gpa, &.{ "nix", "develop" });770}771772pub 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 {773    if (run_cmd) |cmd| {774        // sh -c so a multi-word command isn't treated as a single executable name.775        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });776    }777    return streamEnv(io, machine, gpa, &.{ "nix", "develop" }, base_env, "(nina: dev) -> ");778}779780pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {781    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });782}783784// --- Format ---785786pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {787    if (check) {788        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });789    }790    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });791}792793// --- Info ---794795pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {796    const r = try capture(gpa, io, machine, &.{"nixos-version"});797    defer gpa.free(r.stderr);798    if (r.exit_code != 0) {799        gpa.free(r.stdout);800        return error.ProcessFailed;801    }802    return r.stdout;803}804805pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {806    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });807    defer gpa.free(r.stderr);808    if (r.exit_code != 0) {809        gpa.free(r.stdout);810        return error.ProcessFailed;811    }812    return r.stdout;813}814815pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {816    const r = try capture(gpa, io, machine, &.{"uptime"});817    defer gpa.free(r.stderr);818    if (r.exit_code != 0) {819        gpa.free(r.stdout);820        return error.ProcessFailed;821    }822    return r.stdout;823}824825// --- Boot ---826827pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {828    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });829    defer gpa.free(r.stderr);830    defer gpa.free(r.stdout);831    if (r.exit_code != 0) return error.ProcessFailed;832    return parseBootEntries(gpa, r.stdout);833}834835fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {836    var entries: std.ArrayList(types.BootEntry) = .empty;837    var lines = std.mem.splitScalar(u8, output_str, '\n');838    while (lines.next()) |line| {839        const trimmed = std.mem.trim(u8, line, " \t\r");840        if (std.mem.startsWith(u8, trimmed, "title:")) {841            const title = std.mem.trim(u8, trimmed[6..], " \t");842            const current = std.mem.indexOf(u8, title, "(current)") != null;843            try entries.append(gpa, .{844                .title = try gpa.dupe(u8, title),845                .current = current,846            });847        }848    }849    return entries.toOwnedSlice(gpa);850}851852// --- Pkg info ---853854pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {855    return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });856}857858pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {859    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });860}861862pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {863    // A bare name ("ripgrep") isn't a valid installable; resolve via nixpkgs# like864    // `pkg path` does. -S -h gives closure size, human-readable. Output is865    // "<store-path>   <size>"; return just the size.866    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});867    defer gpa.free(ref);868    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref });869    defer gpa.free(r.stderr);870    defer gpa.free(r.stdout);871    if (r.exit_code != 0) return error.ProcessFailed;872873    const line = std.mem.trim(u8, r.stdout, " \t\n\r");874    var it = std.mem.tokenizeAny(u8, line, " \t");875    _ = it.next(); // store path876    const size = std.mem.trim(u8, it.rest(), " \t");877    if (size.len == 0) return error.ProcessFailed;878    return gpa.dupe(u8, size);879}880881pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {882    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });883}884885// --- Hash / Fetch ---886887pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {888    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });889    defer gpa.free(r.stderr);890    if (r.exit_code != 0) {891        gpa.free(r.stdout);892        return error.ProcessFailed;893    }894    return r.stdout;895}896897pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {898    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });899    defer gpa.free(r.stderr);900    if (r.exit_code != 0) {901        gpa.free(r.stdout);902        return error.ProcessFailed;903    }904    return r.stdout;905}906907// --- Pin ---908909pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {910    // Stub: full implementation would parse and edit flake.lock JSON911    // The pin/unpin flow works via nix flake update which regenerates flake.lock912}913914pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {915    if (line) |l| {916        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});917        defer gpa.free(line_arg);918        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });919    }920    return stream(io, &types.Machine{}, gpa, &.{ editor, path });921}922923pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {924    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});925    defer gpa.free(a_str);926    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});927    defer gpa.free(b_str);928    // On a tty, the child's own color is fine — stream it directly.929    if (output.colorEnabled()) {930        return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });931    }932    // Piped/redirected: nix store diff-closures colorizes regardless of NO_COLOR,933    // so we can't ask it to stop — capture its output and strip the ANSI ourselves.934    const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });935    defer gpa.free(r.stdout);936    defer gpa.free(r.stderr);937    const cleaned = try stripAnsi(gpa, r.stdout);938    defer gpa.free(cleaned);939    output.raw(cleaned);940    return r.exit_code;941}942943// Strip CSI escape sequences (ESC '[' ... final-byte) from text. Used to clean a944// child process's color when it writes ANSI unconditionally.945fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {946    var out: std.ArrayList(u8) = .empty;947    errdefer out.deinit(gpa);948    var i: usize = 0;949    while (i < input.len) {950        if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {951            i += 2;952            while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}953            if (i < input.len) i += 1; // consume the final byte954            continue;955        }956        try out.append(gpa, input[i]);957        i += 1;958    }959    return out.toOwnedSlice(gpa);960}961962test "stripAnsi removes CSI color sequences" {963    const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");964    defer std.testing.allocator.free(cleaned);965    try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);966}967968// --- Doctor checks ---969970pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {971    var checks: std.ArrayList(types.DoctorCheck) = .empty;972973    // Check nix daemon974    {975        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });976        defer gpa.free(r.stdout);977        defer gpa.free(r.stderr);978        const active = std.mem.indexOf(u8, r.stdout, "active") != null;979        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });980    }981982    // Check config syntax983    {984        const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });985        defer gpa.free(r.stdout);986        defer gpa.free(r.stderr);987        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });988    }989990    // Check channel991    {992        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });993        defer gpa.free(r.stdout);994        defer gpa.free(r.stderr);995        const has_channel = r.exit_code == 0 and r.stdout.len > 0;996        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });997    }998999    return checks.toOwnedSlice(gpa);1000}10011002// --- Log ---10031004pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1005    const home = environ.get("HOME") orelse return error.FileNotFound;1006    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1007    defer gpa.free(path);1008    const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1009    if (last == 0) return content;10101011    // Collect non-empty lines, then keep only the final `last`. Slices point into1012    // `content`, so copy them out before freeing it.1013    var lines: std.ArrayList([]const u8) = .empty;1014    defer lines.deinit(gpa);1015    var it = std.mem.splitScalar(u8, content, '\n');1016    while (it.next()) |line| {1017        if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1018        try lines.append(gpa, line);1019    }1020    if (lines.items.len <= last) return content;10211022    var out: std.ArrayList(u8) = .empty;1023    errdefer out.deinit(gpa);1024    for (lines.items[lines.items.len - last ..]) |line| {1025        try out.appendSlice(gpa, line);1026        try out.append(gpa, '\n');1027    }1028    gpa.free(content);1029    return out.toOwnedSlice(gpa);1030}10311032// nina is a one-shot process, so "did the last apply fail this session?" can't1033// live in memory — it's persisted as a ~/.nina-apply-failed flag, mirroring the1034// other ~/.nina-* state files. This lets a later successful apply earn the1035// excited kaomoji. mark sets it; take reads-and-clears so it fires exactly once.1036pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1037    const home = environ.get("HOME") orelse return;1038    var buf: [512]u8 = undefined;1039    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1040    const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1041    file.close(io);1042}10431044pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1045    const home = environ.get("HOME") orelse return false;1046    var buf: [512]u8 = undefined;1047    const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1048    if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1049        f.close(io);1050        std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1051        return true;1052    } else |_| {1053        return false;1054    }1055}10561057pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1058    const home = environ.get("HOME") orelse return;1059    var path_buf: [512]u8 = undefined;1060    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1061    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1062        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1063    defer file.close(io);1064    const size = file.length(io) catch 0;1065    file.writePositionalAll(io, entry, size) catch {};1066}10671068// --- Update helpers ---10691070// Fetch a URL with curl and return the response body. Caller must free.1071// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.1072pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1073    const argv = [_][]const u8{1074        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1075    };1076    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1077    defer gpa.free(result.stderr);10781079    const marker = "\nHTTP_STATUS:";1080    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1081        gpa.free(result.stdout);1082        return error.NetworkError;1083    };1084    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1085    const status = std.fmt.parseInt(u16, status_str, 10) catch {1086        gpa.free(result.stdout);1087        return error.NetworkError;1088    };1089    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1090    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1091    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1092        gpa.free(result.stdout);1093        return e;1094    };1095    gpa.free(result.stdout);1096    return body;1097}10981099// Download a URL to a temp file. Returns the temp path (caller must gpa.free).1100// The file is written to /tmp/nina-update-<pid> and left for the caller to use.1101pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1102    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1103    errdefer gpa.free(tmp_path);11041105    var child = std.process.spawn(io, .{1106        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1107        .stdin = .close,1108        .stdout = .close,1109        .stderr = .inherit,1110    }) catch return error.NetworkError;1111    const term = child.wait(io) catch return error.NetworkError;1112    switch (term) {1113        .exited => |c| if (c != 0) return error.NetworkError,1114        else => return error.NetworkError,1115    }1116    return tmp_path;1117}11181119// Get the current executable path into buf. Returns slice of buf.1120pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1121    const len = try std.process.executablePath(io, buf);1122    return buf[0..len];1123}11241125// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then1126// atomically install the binary to install_path. Errors: ChecksumMismatch,1127// AccessDenied (with error_info set), or underlying I/O errors.1128pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1129    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1130        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1131        return error.FileNotFound;1132    };1133    defer gpa.free(bytes);11341135    var hasher = std.crypto.hash.Blake3.init(.{});1136    hasher.update(bytes);1137    var raw: [32]u8 = undefined;1138    hasher.final(&raw);1139    const hex = std.fmt.bytesToHex(raw, .lower);1140    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;11411142    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1143    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1144        return error.NameTooLong;11451146    {1147        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1148            errors.error_info.setMessage("cannot write to {s}", .{install_path});1149            errors.error_info.setSuggestion("try: sudo nina update", .{});1150            return error.AccessDenied;1151        };1152        defer f.close(io);1153        f.writePositionalAll(io, bytes, 0) catch {1154            errors.error_info.setMessage("cannot write to {s}", .{install_path});1155            return error.AccessDenied;1156        };1157        try f.setPermissions(io, .fromMode(0o755));1158    }1159    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};11601161    if (comptime builtin.os.tag == .macos) {1162        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1163    }11641165    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1166        error.AccessDenied => {1167            errors.error_info.setMessage("cannot replace {s}", .{install_path});1168            errors.error_info.setSuggestion("try: sudo nina update", .{});1169            return error.AccessDenied;1170        },1171        else => return e,1172    };1173}11741175// --- Nix feature setup ---11761177pub const NixFeatureStatus = struct {1178    nix_command: bool = false,1179    flakes: bool = false,11801181    pub fn allEnabled(self: NixFeatureStatus) bool {1182        return self.nix_command and self.flakes;1183    }1184};11851186fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1187    var lines = std.mem.splitScalar(u8, conf, '\n');1188    while (lines.next()) |line| {1189        const trimmed = std.mem.trim(u8, line, " \t");1190        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1191        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1192        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1193    }1194}11951196pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1197    var status = NixFeatureStatus{};11981199    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1200        defer gpa.free(conf);1201        scanConfFeatures(conf, &status);1202    }12031204    if (environ.get("HOME")) |home| {1205        var buf: [512]u8 = undefined;1206        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1207        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1208            defer gpa.free(conf);1209            scanConfFeatures(conf, &status);1210        }1211    }12121213    return status;1214}12151216pub fn isNixOS(io: std.Io) bool {1217    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1218    file.close(io);1219    return true;1220}12211222// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.1223// Returns the path written (caller must free).1224pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1225    const home = environ.get("HOME") orelse {1226        errors.error_info.setMessage("HOME not set", .{});1227        return error.ConfigNotFound;1228    };12291230    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1231    defer gpa.free(dir_path);1232    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1233    errdefer gpa.free(file_path);12341235    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};12361237    const line = "experimental-features = nix-command flakes\n";1238    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1239        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1240        errors.error_info.setMessage("could not write {s}", .{file_path});1241        return error.FileNotFound;1242    });1243    defer file.close(io);12441245    const size = file.length(io) catch 0;1246    file.writePositionalAll(io, line, size) catch {1247        errors.error_info.setMessage("could not write {s}", .{file_path});1248        return error.FileNotFound;1249    };12501251    return file_path;1252}12531254// --- NixOS: declarative experimental-features ---1255//1256// On NixOS the permanent, declarative home for these flags is configuration.nix,1257// not ~/.config/nix/nix.conf. nina offers to add this one line and then leaves1258// the `nixos-rebuild switch` to the user.12591260pub const NIXOS_FEATURES_LINE =1261    "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";12621263// Best-effort, non-sudo check (configuration.nix is 0644 by default). Returns1264// false on any read error so the caller still offers to add the line.1265pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1266    const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1267    defer gpa.free(conf);1268    return std.mem.indexOf(u8, conf, "experimental-features") != null and1269        std.mem.indexOf(u8, conf, "nix-command") != null and1270        std.mem.indexOf(u8, conf, "flakes") != null;1271}12721273fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1274    if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1275    return captureLocal(gpa, io, &.{ "sudo", "cat", path });1276}12771278// Insert NIXOS_FEATURES_LINE just before the final `}` of configuration.nix1279// (i.e. inside the top-level attribute set) and write it back via a single1280// `sudo cp`, which prompts for the password on the terminal. Returns an error1281// for the caller to fall back to printed manual instructions.1282pub fn appendFeaturesToNixosConfig(1283    gpa: std.mem.Allocator,1284    io: std.Io,1285    environ: *const std.process.Environ.Map,1286    path: []const u8,1287) !void {1288    const conf = readMaybeSudo(gpa, io, path) catch {1289        errors.error_info.setMessage("could not read {s}", .{path});1290        return error.ConfigNotFound;1291    };1292    defer gpa.free(conf);12931294    if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; // already declared12951296    const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1297        errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1298        return error.MalformedConfig;1299    };13001301    const home = environ.get("HOME") orelse {1302        errors.error_info.setMessage("HOME not set", .{});1303        return error.ConfigNotFound;1304    };1305    const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1306    defer gpa.free(tmp_path);13071308    var buf: std.ArrayList(u8) = .empty;1309    defer buf.deinit(gpa);1310    try buf.appendSlice(gpa, conf[0..brace]);1311    if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1312    try buf.appendSlice(gpa, "  # added by nina setup — flakes + the new nix CLI\n");1313    try buf.appendSlice(gpa, "  ");1314    try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1315    try buf.append(gpa, '\n');1316    try buf.appendSlice(gpa, conf[brace..]);13171318    const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1319        errors.error_info.setMessage("could not write {s}", .{tmp_path});1320        return error.FileNotFound;1321    };1322    tmp.writePositionalAll(io, buf.items, 0) catch {1323        tmp.close(io);1324        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1325        errors.error_info.setMessage("could not write {s}", .{tmp_path});1326        return error.FileNotFound;1327    };1328    tmp.close(io);13291330    // Back up the existing config, then replace it — in one sudo call so the1331    // password is asked for at most once. Paths travel as positional args ($0,1332    // $1) to sidestep shell quoting.1333    const code = streamLocal(io, &.{1334        "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1335    }) catch {1336        std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1337        errors.error_info.setMessage("could not write {s}", .{path});1338        return error.ProcessFailed;1339    };1340    std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1341    if (code != 0) {1342        errors.error_info.setMessage("sudo cp into {s} failed", .{path});1343        return error.ProcessFailed;1344    }1345}