exec.zig

37.1 KB · raw

1// exec.zig — all process execution and SSH routing2// Commands call these functions; output is streamed or captured here.3const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const output = @import("output.zig");89// nixos-rebuild manages this profile; generation commands must target it10// explicitly. Bare nix-env defaults to the per-user profile, which is empty.11const SYSTEM_PROFILE = "/nix/var/nix/profiles/system";1213pub const RunResult = struct {14    stdout: []u8,15    stderr: []u8,16    exit_code: u8,17};1819// Run a process and capture stdout+stderr (not streaming).20pub fn capture(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, cmd: []const []const u8) !RunResult {21    const argv = try buildArgv(gpa, machine, cmd);22    defer if (!machine.local) gpa.free(argv);2324    const result = std.process.run(gpa, io, .{ .argv = argv }) catch |e| {25        errors.error_info.setMessage("process failed: {s}", .{cmd[0]});26        return e;27    };2829    return .{30        .stdout = result.stdout,31        .stderr = result.stderr,32        .exit_code = switch (result.term) {33            .exited => |c| c,34            else => 1,35        },36    };37}3839// Run a process and stream its output to the terminal (inherit stdio).40pub fn stream(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8) !u8 {41    // The child inherits stdout and writes directly to the fd; flush any buffered42    // nina header first so it isn't reordered after the child's output.43    output.flush();44    const argv = try buildArgv(gpa, machine, cmd);45    defer if (!machine.local) gpa.free(argv);4647    var child = std.process.spawn(io, .{48        .argv = argv,49        .stdin = .inherit,50        .stdout = .inherit,51        .stderr = .inherit,52    }) catch |e| {53        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});54        return e;55    };5657    const term = child.wait(io) catch |e| {58        errors.error_info.setMessage("process wait failed", .{});59        return e;60    };6162    return switch (term) {63        .exited => |c| c,64        else => 1,65    };66}6768// Stream a local process with inherited stdio (no SSH routing — for nix commands).69pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 {70    output.flush();71    var child = std.process.spawn(io, .{72        .argv = cmd,73        .stdin = .inherit,74        .stdout = .inherit,75        .stderr = .inherit,76    }) catch |e| {77        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});78        return e;79    };80    const term = child.wait(io) catch {81        errors.error_info.setMessage("process wait failed", .{});82        return error.ProcessFailed;83    };84    return switch (term) {85        .exited => |c| c,86        else => 1,87    };88}8990// Run a process and capture output as a single string (no SSH routing — for local nix commands).91pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {92    const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;93    defer gpa.free(result.stderr);94    switch (result.term) {95        .exited => |c| if (c != 0) {96            gpa.free(result.stdout);97            return error.ProcessFailed;98        },99        else => {100            gpa.free(result.stdout);101            return error.ProcessFailed;102        },103    }104    return result.stdout;105}106107fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {108    if (machine.local) return cmd;109110    const host = machine.host orelse {111        errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});112        return error.SshFailed;113    };114115    var ssh: std.ArrayList([]const u8) = .empty;116    try ssh.append(gpa, "ssh");117    try ssh.append(gpa, "-o");118    try ssh.append(gpa, "BatchMode=yes");119    try ssh.append(gpa, "-o");120    try ssh.append(gpa, "StrictHostKeyChecking=accept-new");121    if (machine.ssh_key) |key| {122        try ssh.append(gpa, "-i");123        try ssh.append(gpa, key);124    }125    const addr = if (machine.user) |u|126        try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })127    else128        try gpa.dupe(u8, host);129    try ssh.append(gpa, addr);130    for (cmd) |arg| try ssh.append(gpa, arg);131    return ssh.toOwnedSlice(gpa);132}133134// --- NixOS rebuild ---135136pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {137    const cmd = &.{ "sudo", "nixos-rebuild", "switch" };138    output.printSubstep("nixos-rebuild switch", .{});139    return stream(io, machine, gpa, cmd);140}141142pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {143    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "dry-activate" });144}145146pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {147    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "build" });148}149150// --- Generations ---151152// Read system-profile generations WITHOUT root. `nix-env --list-generations -p153// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user154// ("system.lock: Permission denied"). The generation symlinks themselves are155// world-readable, so list them directly: parse `system-N-link` names, take each156// link's own mtime for the date/time, and mark the one the `system` symlink157// points at as current. Output matches the `nix-env --list-generations` columns158// (num date time [current]) so parseGenerations is unchanged.159const GEN_LIST_SCRIPT =160    \\cur=$(readlink /nix/var/nix/profiles/system 2>/dev/null | sed 's/.*system-\([0-9]*\)-link/\1/'); find /nix/var/nix/profiles -maxdepth 1 -name 'system-*-link' -printf '%f %TY-%Tm-%Td %TH:%TM\n' 2>/dev/null | sed 's/system-\([0-9]*\)-link/\1/' | sort -n | awk -v c="$cur" '{ if ($1==c) print $0" current"; else print $0 }'161;162163pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {164    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });165    defer gpa.free(r.stderr);166    defer gpa.free(r.stdout);167    if (r.exit_code != 0) return error.ProcessFailed;168    return parseGenerations(gpa, r.stdout);169}170171fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {172    var gens: std.ArrayList(types.GenerationInfo) = .empty;173    var lines = std.mem.splitScalar(u8, output_str, '\n');174    while (lines.next()) |line| {175        const trimmed = std.mem.trim(u8, line, " \t");176        if (trimmed.len == 0) continue;177        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");178        const num_str = parts.next() orelse continue;179        const date_str = parts.next() orelse continue;180        const time_str = parts.next() orelse continue;181        const rest = parts.rest();182        const current = std.mem.indexOf(u8, rest, "current") != null;183        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;184        try gens.append(gpa, .{185            .number = num,186            .date = try gpa.dupe(u8, date_str),187            .time = try gpa.dupe(u8, time_str),188            .current = current,189        });190    }191    return gens.toOwnedSlice(gpa);192}193194pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {195    const gens = try getGenerations(gpa, io, machine);196    defer gpa.free(gens);197    for (gens) |g| {198        if (g.current) return g.number;199    }200    return 0;201}202203pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {204    // Switch the system profile to generation n, then activate it (bootloader +205    // services). Without switch-to-configuration the change isn't applied.206    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --switch-generation {d} && {s}/bin/switch-to-configuration switch", .{ SYSTEM_PROFILE, n, SYSTEM_PROFILE });207    defer gpa.free(cmd);208    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });209}210211pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {212    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });213}214215pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {216    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});217    defer gpa.free(n_str);218    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });219}220221pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {222    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });223}224225// --- Garbage collection ---226227pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {228    if (delete_old) {229        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });230    }231    // Keep the `keep` most recent system generations (+N deletes all but N),232    // then collect now-unreferenced store paths. `--delete-older-than` wants a233    // duration (e.g. 14d), not a generation count.234    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });235    defer gpa.free(cmd);236    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });237}238239// --- Channels ---240241pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {242    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });243    defer gpa.free(r.stderr);244    defer gpa.free(r.stdout);245    if (r.exit_code != 0) return error.ProcessFailed;246    return parseChannels(gpa, r.stdout);247}248249fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {250    var channels: std.ArrayList(types.ChannelInfo) = .empty;251    var lines = std.mem.splitScalar(u8, output_str, '\n');252    while (lines.next()) |line| {253        const trimmed = std.mem.trim(u8, line, " \t\r");254        if (trimmed.len == 0) continue;255        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;256        try channels.append(gpa, .{257            .name = try gpa.dupe(u8, trimmed[0..space]),258            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),259        });260    }261    return channels.toOwnedSlice(gpa);262}263264pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {265    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });266}267268pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {269    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });270}271272pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {273    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });274}275276// --- Services ---277278pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ServiceInfo {279    const r = try capture(gpa, io, machine, &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" });280    defer gpa.free(r.stderr);281    defer gpa.free(r.stdout);282    if (r.exit_code != 0) return error.ProcessFailed;283    return parseServices(gpa, r.stdout);284}285286fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {287    var svcs: std.ArrayList(types.ServiceInfo) = .empty;288    var lines = std.mem.splitScalar(u8, output_str, '\n');289    while (lines.next()) |line| {290        const trimmed = std.mem.trim(u8, line, " \t\r");291        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines292        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");293        const name = parts.next() orelse continue;294        _ = parts.next(); // load295        const active_str = parts.next() orelse continue;296        const sub_str = parts.next() orelse "unknown";297298        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))299            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)300        else if (std.mem.eql(u8, active_str, "failed"))301            .failed302        else303            .inactive;304305        try svcs.append(gpa, .{306            .name = try gpa.dupe(u8, name),307            .state = state,308            .uptime = null,309        });310    }311    return svcs.toOwnedSlice(gpa);312}313314pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8) !u8 {315    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.316    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });317}318319pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool) !u8 {320    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});321    defer gpa.free(n_str);322    if (follow) {323        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });324    }325    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });326}327328// --- Profile ---329330pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {331    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});332    defer gpa.free(pkg_ref);333    return stream(io, machine, gpa, &.{ "nix", "profile", "install", pkg_ref });334}335336pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {337    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not338    // by flake ref — passing nixpkgs#ripgrep matches nothing.339    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });340}341342pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {343    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });344    defer gpa.free(r.stderr);345    if (r.exit_code != 0) return error.ProcessFailed;346    return r.stdout;347}348349pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {350    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });351}352353// --- Store ---354355pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {356    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });357}358359pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {360    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });361}362363pub const SystemStatus = struct { size: []u8, age: []u8 };364365// One read-only pass for `nina status`: the current system's closure size (a366// single `path-info -S` of /run/current-system — fast, unlike -S over the whole367// store) and seconds since the system profile was last switched (its symlink368// mtime). Both are world-readable; no root needed.369const STATUS_SCRIPT =370    \\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} ))"371;372373pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {374    const unknown = SystemStatus{375        .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },376        .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },377    };378    const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;379    defer gpa.free(r.stdout);380    defer gpa.free(r.stderr);381    if (r.exit_code != 0) return unknown;382383    var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");384    const sz_str = it.next() orelse return unknown;385    const age_str = it.next() orelse return unknown;386    const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;387    const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;388389    gpa.free(unknown.size);390    gpa.free(unknown.age);391    return .{392        .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),393        .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),394    };395}396397fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {398    if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});399    if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});400    if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});401    return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});402}403404pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {405    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });406}407408pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {409    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)410    // graph work that takes minutes on a real store (59k+ paths) and hangs the411    // command. We don't need closures: `--all --json` (no -S) carries each path's412    // own narSize, so one fast pass gives the path count and the summed store size.413    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.414    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.415    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });416    defer gpa.free(pi.stdout);417    defer gpa.free(pi.stderr);418419    const scan = scanStoreJson(pi.stdout);420    const total_owned = try humanSize(gpa, scan.total_bytes);421422    return .{423        .total_size = total_owned,424        .live_paths = scan.count,425        .reclaimable_paths = 0,426    };427}428429const StoreScan = struct { count: u64, total_bytes: u64 };430431// One linear pass over `nix path-info --json`: each path object has exactly one432// "narSize": field, so counting them gives the true path count and summing the433// values gives the total store size — no per-path closure walk.434fn scanStoreJson(json_str: []const u8) StoreScan {435    const needle = "\"narSize\":";436    var count: u64 = 0;437    var total: u64 = 0;438    var i: usize = 0;439    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {440        var j = pos + needle.len;441        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}442        var val: u64 = 0;443        var any = false;444        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {445            val = val * 10 + (json_str[j] - '0');446            any = true;447        }448        if (any) {449            count += 1;450            total += val;451        }452        i = j;453    }454    return .{ .count = count, .total_bytes = total };455}456457fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {458    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };459    var val: f64 = @floatFromInt(bytes);460    var unit: usize = 0;461    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;462    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });463    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });464}465466pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {467    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the468    // flake registry), not a flake in the current directory.469    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});470    defer gpa.free(expr);471    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });472    defer gpa.free(r.stderr);473    if (r.exit_code != 0) {474        gpa.free(r.stdout);475        return error.ProcessFailed;476    }477    return r.stdout;478}479480// --- Flake ---481482pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {483    if (input) |inp| {484        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });485    }486    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });487}488489pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {490    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });491}492493pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {494    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });495}496497pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {498    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });499}500501pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {502    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });503}504505pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {506    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });507    defer gpa.free(r.stderr);508    if (r.exit_code != 0) {509        gpa.free(r.stdout);510        return error.ProcessFailed;511    }512    return r.stdout;513}514515// --- Build / Run / Develop ---516517pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {518    if (attr) |a| {519        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});520        defer gpa.free(ref);521        return stream(io, machine, gpa, &.{ "nix", "build", ref });522    }523    return stream(io, machine, gpa, &.{ "nix", "build" });524}525526pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {527    // nix run always gets --no-write-lock-file for remote URLs528    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");529    if (is_url) {530        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });531    }532    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.533    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {534        return stream(io, machine, gpa, &.{ "nix", "run", pkg });535    }536    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});537    defer gpa.free(ref);538    return stream(io, machine, gpa, &.{ "nix", "run", ref });539}540541pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {542    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});543    defer gpa.free(ref);544    return stream(io, machine, gpa, &.{ "nix", "shell", ref });545}546547pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {548    if (run_cmd) |cmd| {549        // sh -c so a multi-word command isn't treated as a single executable name.550        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });551    }552    return stream(io, machine, gpa, &.{ "nix", "develop" });553}554555pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {556    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });557}558559// --- Format ---560561pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {562    if (check) {563        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });564    }565    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });566}567568// --- Info ---569570pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {571    const r = try capture(gpa, io, machine, &.{"nixos-version"});572    defer gpa.free(r.stderr);573    if (r.exit_code != 0) {574        gpa.free(r.stdout);575        return error.ProcessFailed;576    }577    return r.stdout;578}579580pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {581    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });582    defer gpa.free(r.stderr);583    if (r.exit_code != 0) {584        gpa.free(r.stdout);585        return error.ProcessFailed;586    }587    return r.stdout;588}589590pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {591    const r = try capture(gpa, io, machine, &.{"uptime"});592    defer gpa.free(r.stderr);593    if (r.exit_code != 0) {594        gpa.free(r.stdout);595        return error.ProcessFailed;596    }597    return r.stdout;598}599600// --- Boot ---601602pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {603    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });604    defer gpa.free(r.stderr);605    defer gpa.free(r.stdout);606    if (r.exit_code != 0) return error.ProcessFailed;607    return parseBootEntries(gpa, r.stdout);608}609610fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {611    var entries: std.ArrayList(types.BootEntry) = .empty;612    var lines = std.mem.splitScalar(u8, output_str, '\n');613    while (lines.next()) |line| {614        const trimmed = std.mem.trim(u8, line, " \t\r");615        if (std.mem.startsWith(u8, trimmed, "title:")) {616            const title = std.mem.trim(u8, trimmed[6..], " \t");617            const current = std.mem.indexOf(u8, title, "(current)") != null;618            try entries.append(gpa, .{619                .title = try gpa.dupe(u8, title),620                .current = current,621            });622        }623    }624    return entries.toOwnedSlice(gpa);625}626627// --- Pkg info ---628629pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {630    return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });631}632633pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {634    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });635}636637pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {638    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", pkg });639    defer gpa.free(r.stderr);640    if (r.exit_code != 0) {641        gpa.free(r.stdout);642        return error.ProcessFailed;643    }644    return r.stdout;645}646647pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {648    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });649}650651// --- Hash / Fetch ---652653pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {654    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });655    defer gpa.free(r.stderr);656    if (r.exit_code != 0) {657        gpa.free(r.stdout);658        return error.ProcessFailed;659    }660    return r.stdout;661}662663pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {664    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });665    defer gpa.free(r.stderr);666    if (r.exit_code != 0) {667        gpa.free(r.stdout);668        return error.ProcessFailed;669    }670    return r.stdout;671}672673// --- Pin ---674675pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {676    // Stub: full implementation would parse and edit flake.lock JSON677    // The pin/unpin flow works via nix flake update which regenerates flake.lock678}679680pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {681    if (line) |l| {682        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});683        defer gpa.free(line_arg);684        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });685    }686    return stream(io, &types.Machine{}, gpa, &.{ editor, path });687}688689pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {690    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});691    defer gpa.free(a_str);692    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});693    defer gpa.free(b_str);694    return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });695}696697// --- Doctor checks ---698699pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {700    var checks: std.ArrayList(types.DoctorCheck) = .empty;701702    // Check nix daemon703    {704        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });705        defer gpa.free(r.stdout);706        defer gpa.free(r.stderr);707        const active = std.mem.indexOf(u8, r.stdout, "active") != null;708        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });709    }710711    // Check config syntax712    {713        const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });714        defer gpa.free(r.stdout);715        defer gpa.free(r.stderr);716        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });717    }718719    // Check channel720    {721        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });722        defer gpa.free(r.stdout);723        defer gpa.free(r.stderr);724        const has_channel = r.exit_code == 0 and r.stdout.len > 0;725        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });726    }727728    return checks.toOwnedSlice(gpa);729}730731// --- Log ---732733pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {734    const home = environ.get("HOME") orelse return error.FileNotFound;735    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});736    defer gpa.free(path);737    _ = last;738    return std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;739}740741pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {742    const home = environ.get("HOME") orelse return;743    var path_buf: [512]u8 = undefined;744    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;745    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch746        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);747    defer file.close(io);748    const size = file.length(io) catch 0;749    file.writePositionalAll(io, entry, size) catch {};750}751752// --- Update helpers ---753754// Fetch a URL with curl and return the response body. Caller must free.755// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.756pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {757    const argv = [_][]const u8{758        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,759    };760    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;761    defer gpa.free(result.stderr);762763    const marker = "\nHTTP_STATUS:";764    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {765        gpa.free(result.stdout);766        return error.NetworkError;767    };768    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");769    const status = std.fmt.parseInt(u16, status_str, 10) catch {770        gpa.free(result.stdout);771        return error.NetworkError;772    };773    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }774    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }775    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {776        gpa.free(result.stdout);777        return e;778    };779    gpa.free(result.stdout);780    return body;781}782783// Download a URL to a temp file. Returns the temp path (caller must gpa.free).784// The file is written to /tmp/nina-update-<pid> and left for the caller to use.785pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {786    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");787    errdefer gpa.free(tmp_path);788789    var child = std.process.spawn(io, .{790        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },791        .stdin = .close,792        .stdout = .close,793        .stderr = .inherit,794    }) catch return error.NetworkError;795    const term = child.wait(io) catch return error.NetworkError;796    switch (term) {797        .exited => |c| if (c != 0) return error.NetworkError,798        else => return error.NetworkError,799    }800    return tmp_path;801}802803// Get the current executable path into buf. Returns slice of buf.804pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {805    const len = try std.process.executablePath(io, buf);806    return buf[0..len];807}808809// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then810// atomically install the binary to install_path. Errors: ChecksumMismatch,811// AccessDenied (with error_info set), or underlying I/O errors.812pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {813    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {814        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});815        return error.FileNotFound;816    };817    defer gpa.free(bytes);818819    var hasher = std.crypto.hash.Blake3.init(.{});820    hasher.update(bytes);821    var raw: [32]u8 = undefined;822    hasher.final(&raw);823    const hex = std.fmt.bytesToHex(raw, .lower);824    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;825826    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;827    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch828        return error.NameTooLong;829830    {831        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {832            errors.error_info.setMessage("cannot write to {s}", .{install_path});833            errors.error_info.setSuggestion("try: sudo nina update", .{});834            return error.AccessDenied;835        };836        defer f.close(io);837        f.writePositionalAll(io, bytes, 0) catch {838            errors.error_info.setMessage("cannot write to {s}", .{install_path});839            return error.AccessDenied;840        };841        try f.setPermissions(io, .fromMode(0o755));842    }843    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};844845    if (comptime builtin.os.tag == .macos) {846        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};847    }848849    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {850        error.AccessDenied => {851            errors.error_info.setMessage("cannot replace {s}", .{install_path});852            errors.error_info.setSuggestion("try: sudo nina update", .{});853            return error.AccessDenied;854        },855        else => return e,856    };857}858859// --- Nix feature setup ---860861pub const NixFeatureStatus = struct {862    nix_command: bool = false,863    flakes: bool = false,864865    pub fn allEnabled(self: NixFeatureStatus) bool {866        return self.nix_command and self.flakes;867    }868};869870fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {871    var lines = std.mem.splitScalar(u8, conf, '\n');872    while (lines.next()) |line| {873        const trimmed = std.mem.trim(u8, line, " \t");874        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;875        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;876        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;877    }878}879880pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {881    var status = NixFeatureStatus{};882883    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {884        defer gpa.free(conf);885        scanConfFeatures(conf, &status);886    }887888    if (environ.get("HOME")) |home| {889        var buf: [512]u8 = undefined;890        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;891        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {892            defer gpa.free(conf);893            scanConfFeatures(conf, &status);894        }895    }896897    return status;898}899900pub fn isNixOS(io: std.Io) bool {901    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;902    file.close(io);903    return true;904}905906// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.907// Returns the path written (caller must free).908pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {909    const home = environ.get("HOME") orelse {910        errors.error_info.setMessage("HOME not set", .{});911        return error.ConfigNotFound;912    };913914    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});915    defer gpa.free(dir_path);916    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});917    errdefer gpa.free(file_path);918919    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};920921    const line = "experimental-features = nix-command flakes\n";922    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch923        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {924        errors.error_info.setMessage("could not write {s}", .{file_path});925        return error.FileNotFound;926    });927    defer file.close(io);928929    const size = file.length(io) catch 0;930    file.writePositionalAll(io, line, size) catch {931        errors.error_info.setMessage("could not write {s}", .{file_path});932        return error.FileNotFound;933    };934935    return file_path;936}