exec.zig

35.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    const argv = try buildArgv(gpa, machine, cmd);42    defer if (!machine.local) gpa.free(argv);4344    var child = std.process.spawn(io, .{45        .argv = argv,46        .stdin = .inherit,47        .stdout = .inherit,48        .stderr = .inherit,49    }) catch |e| {50        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});51        return e;52    };5354    const term = child.wait(io) catch |e| {55        errors.error_info.setMessage("process wait failed", .{});56        return e;57    };5859    return switch (term) {60        .exited => |c| c,61        else => 1,62    };63}6465// Stream a local process with inherited stdio (no SSH routing — for nix commands).66pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 {67    var child = std.process.spawn(io, .{68        .argv = cmd,69        .stdin = .inherit,70        .stdout = .inherit,71        .stderr = .inherit,72    }) catch |e| {73        errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});74        return e;75    };76    const term = child.wait(io) catch {77        errors.error_info.setMessage("process wait failed", .{});78        return error.ProcessFailed;79    };80    return switch (term) {81        .exited => |c| c,82        else => 1,83    };84}8586// Run a process and capture output as a single string (no SSH routing — for local nix commands).87pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {88    const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;89    defer gpa.free(result.stderr);90    switch (result.term) {91        .exited => |c| if (c != 0) {92            gpa.free(result.stdout);93            return error.ProcessFailed;94        },95        else => {96            gpa.free(result.stdout);97            return error.ProcessFailed;98        },99    }100    return result.stdout;101}102103fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {104    if (machine.local) return cmd;105106    const host = machine.host orelse {107        errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});108        return error.SshFailed;109    };110111    var ssh: std.ArrayList([]const u8) = .empty;112    try ssh.append(gpa, "ssh");113    try ssh.append(gpa, "-o");114    try ssh.append(gpa, "BatchMode=yes");115    try ssh.append(gpa, "-o");116    try ssh.append(gpa, "StrictHostKeyChecking=accept-new");117    if (machine.ssh_key) |key| {118        try ssh.append(gpa, "-i");119        try ssh.append(gpa, key);120    }121    const addr = if (machine.user) |u|122        try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })123    else124        try gpa.dupe(u8, host);125    try ssh.append(gpa, addr);126    for (cmd) |arg| try ssh.append(gpa, arg);127    return ssh.toOwnedSlice(gpa);128}129130// --- NixOS rebuild ---131132pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {133    const cmd = &.{ "sudo", "nixos-rebuild", "switch" };134    output.printSubstep("nixos-rebuild switch", .{});135    return stream(io, machine, gpa, cmd);136}137138pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {139    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "dry-activate" });140}141142pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {143    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "build" });144}145146// --- Generations ---147148// Read system-profile generations WITHOUT root. `nix-env --list-generations -p149// /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user150// ("system.lock: Permission denied"). The generation symlinks themselves are151// world-readable, so list them directly: parse `system-N-link` names, take each152// link's own mtime for the date/time, and mark the one the `system` symlink153// points at as current. Output matches the `nix-env --list-generations` columns154// (num date time [current]) so parseGenerations is unchanged.155const GEN_LIST_SCRIPT =156    \\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 }'157;158159pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {160    const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });161    defer gpa.free(r.stderr);162    defer gpa.free(r.stdout);163    if (r.exit_code != 0) return error.ProcessFailed;164    return parseGenerations(gpa, r.stdout);165}166167fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {168    var gens: std.ArrayList(types.GenerationInfo) = .empty;169    var lines = std.mem.splitScalar(u8, output_str, '\n');170    while (lines.next()) |line| {171        const trimmed = std.mem.trim(u8, line, " \t");172        if (trimmed.len == 0) continue;173        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");174        const num_str = parts.next() orelse continue;175        const date_str = parts.next() orelse continue;176        const time_str = parts.next() orelse continue;177        const rest = parts.rest();178        const current = std.mem.indexOf(u8, rest, "current") != null;179        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;180        try gens.append(gpa, .{181            .number = num,182            .date = try gpa.dupe(u8, date_str),183            .time = try gpa.dupe(u8, time_str),184            .current = current,185        });186    }187    return gens.toOwnedSlice(gpa);188}189190pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {191    const gens = try getGenerations(gpa, io, machine);192    defer gpa.free(gens);193    for (gens) |g| {194        if (g.current) return g.number;195    }196    return 0;197}198199pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {200    // Switch the system profile to generation n, then activate it (bootloader +201    // services). Without switch-to-configuration the change isn't applied.202    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 });203    defer gpa.free(cmd);204    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });205}206207pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {208    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });209}210211pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {212    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});213    defer gpa.free(n_str);214    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });215}216217pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {218    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });219}220221// --- Garbage collection ---222223pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {224    if (delete_old) {225        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });226    }227    // Keep the `keep` most recent system generations (+N deletes all but N),228    // then collect now-unreferenced store paths. `--delete-older-than` wants a229    // duration (e.g. 14d), not a generation count.230    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });231    defer gpa.free(cmd);232    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });233}234235// --- Channels ---236237pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {238    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });239    defer gpa.free(r.stderr);240    defer gpa.free(r.stdout);241    if (r.exit_code != 0) return error.ProcessFailed;242    return parseChannels(gpa, r.stdout);243}244245fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {246    var channels: std.ArrayList(types.ChannelInfo) = .empty;247    var lines = std.mem.splitScalar(u8, output_str, '\n');248    while (lines.next()) |line| {249        const trimmed = std.mem.trim(u8, line, " \t\r");250        if (trimmed.len == 0) continue;251        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;252        try channels.append(gpa, .{253            .name = try gpa.dupe(u8, trimmed[0..space]),254            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),255        });256    }257    return channels.toOwnedSlice(gpa);258}259260pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {261    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });262}263264pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {265    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });266}267268pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {269    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });270}271272// --- Services ---273274pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ServiceInfo {275    const r = try capture(gpa, io, machine, &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" });276    defer gpa.free(r.stderr);277    defer gpa.free(r.stdout);278    if (r.exit_code != 0) return error.ProcessFailed;279    return parseServices(gpa, r.stdout);280}281282fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {283    var svcs: std.ArrayList(types.ServiceInfo) = .empty;284    var lines = std.mem.splitScalar(u8, output_str, '\n');285    while (lines.next()) |line| {286        const trimmed = std.mem.trim(u8, line, " \t\r");287        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines288        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");289        const name = parts.next() orelse continue;290        _ = parts.next(); // load291        const active_str = parts.next() orelse continue;292        const sub_str = parts.next() orelse "unknown";293294        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))295            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)296        else if (std.mem.eql(u8, active_str, "failed"))297            .failed298        else299            .inactive;300301        try svcs.append(gpa, .{302            .name = try gpa.dupe(u8, name),303            .state = state,304            .uptime = null,305        });306    }307    return svcs.toOwnedSlice(gpa);308}309310pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8) !u8 {311    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.312    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });313}314315pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool) !u8 {316    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});317    defer gpa.free(n_str);318    if (follow) {319        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });320    }321    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });322}323324// --- Profile ---325326pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {327    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});328    defer gpa.free(pkg_ref);329    return stream(io, machine, gpa, &.{ "nix", "profile", "install", pkg_ref });330}331332pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {333    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not334    // by flake ref — passing nixpkgs#ripgrep matches nothing.335    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });336}337338pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {339    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });340    defer gpa.free(r.stderr);341    if (r.exit_code != 0) return error.ProcessFailed;342    return r.stdout;343}344345pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {346    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });347}348349// --- Store ---350351pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {352    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });353}354355pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {356    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });357}358359pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {360    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });361}362363pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {364    // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2)365    // graph work that takes minutes on a real store (59k+ paths) and hangs the366    // command. We don't need closures: `--all --json` (no -S) carries each path's367    // own narSize, so one fast pass gives the path count and the summed store size.368    // `du -sh /nix/store` is just as slow on a big store, so it's gone too.369    // timeout-wrapped so a pathological store degrades to "?" instead of hanging.370    const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });371    defer gpa.free(pi.stdout);372    defer gpa.free(pi.stderr);373374    const scan = scanStoreJson(pi.stdout);375    const total_owned = try humanSize(gpa, scan.total_bytes);376377    return .{378        .total_size = total_owned,379        .live_paths = scan.count,380        .reclaimable_paths = 0,381    };382}383384const StoreScan = struct { count: u64, total_bytes: u64 };385386// One linear pass over `nix path-info --json`: each path object has exactly one387// "narSize": field, so counting them gives the true path count and summing the388// values gives the total store size — no per-path closure walk.389fn scanStoreJson(json_str: []const u8) StoreScan {390    const needle = "\"narSize\":";391    var count: u64 = 0;392    var total: u64 = 0;393    var i: usize = 0;394    while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {395        var j = pos + needle.len;396        while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}397        var val: u64 = 0;398        var any = false;399        while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {400            val = val * 10 + (json_str[j] - '0');401            any = true;402        }403        if (any) {404            count += 1;405            total += val;406        }407        i = j;408    }409    return .{ .count = count, .total_bytes = total };410}411412fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {413    const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };414    var val: f64 = @floatFromInt(bytes);415    var unit: usize = 0;416    while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;417    if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });418    return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });419}420421pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {422    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the423    // flake registry), not a flake in the current directory.424    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});425    defer gpa.free(expr);426    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });427    defer gpa.free(r.stderr);428    if (r.exit_code != 0) {429        gpa.free(r.stdout);430        return error.ProcessFailed;431    }432    return r.stdout;433}434435// --- Flake ---436437pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {438    if (input) |inp| {439        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });440    }441    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });442}443444pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {445    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });446}447448pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {449    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });450}451452pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {453    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });454}455456pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {457    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });458}459460pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {461    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });462    defer gpa.free(r.stderr);463    if (r.exit_code != 0) {464        gpa.free(r.stdout);465        return error.ProcessFailed;466    }467    return r.stdout;468}469470// --- Build / Run / Develop ---471472pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {473    if (attr) |a| {474        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});475        defer gpa.free(ref);476        return stream(io, machine, gpa, &.{ "nix", "build", ref });477    }478    return stream(io, machine, gpa, &.{ "nix", "build" });479}480481pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {482    // nix run always gets --no-write-lock-file for remote URLs483    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");484    if (is_url) {485        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });486    }487    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.488    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {489        return stream(io, machine, gpa, &.{ "nix", "run", pkg });490    }491    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});492    defer gpa.free(ref);493    return stream(io, machine, gpa, &.{ "nix", "run", ref });494}495496pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {497    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});498    defer gpa.free(ref);499    return stream(io, machine, gpa, &.{ "nix", "shell", ref });500}501502pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {503    if (run_cmd) |cmd| {504        // sh -c so a multi-word command isn't treated as a single executable name.505        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });506    }507    return stream(io, machine, gpa, &.{ "nix", "develop" });508}509510pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {511    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });512}513514// --- Format ---515516pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {517    if (check) {518        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });519    }520    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });521}522523// --- Info ---524525pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {526    const r = try capture(gpa, io, machine, &.{"nixos-version"});527    defer gpa.free(r.stderr);528    if (r.exit_code != 0) {529        gpa.free(r.stdout);530        return error.ProcessFailed;531    }532    return r.stdout;533}534535pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {536    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });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 uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {546    const r = try capture(gpa, io, machine, &.{"uptime"});547    defer gpa.free(r.stderr);548    if (r.exit_code != 0) {549        gpa.free(r.stdout);550        return error.ProcessFailed;551    }552    return r.stdout;553}554555// --- Boot ---556557pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {558    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });559    defer gpa.free(r.stderr);560    defer gpa.free(r.stdout);561    if (r.exit_code != 0) return error.ProcessFailed;562    return parseBootEntries(gpa, r.stdout);563}564565fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {566    var entries: std.ArrayList(types.BootEntry) = .empty;567    var lines = std.mem.splitScalar(u8, output_str, '\n');568    while (lines.next()) |line| {569        const trimmed = std.mem.trim(u8, line, " \t\r");570        if (std.mem.startsWith(u8, trimmed, "title:")) {571            const title = std.mem.trim(u8, trimmed[6..], " \t");572            const current = std.mem.indexOf(u8, title, "(current)") != null;573            try entries.append(gpa, .{574                .title = try gpa.dupe(u8, title),575                .current = current,576            });577        }578    }579    return entries.toOwnedSlice(gpa);580}581582// --- Pkg info ---583584pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {585    return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });586}587588pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {589    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });590}591592pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {593    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", pkg });594    defer gpa.free(r.stderr);595    if (r.exit_code != 0) {596        gpa.free(r.stdout);597        return error.ProcessFailed;598    }599    return r.stdout;600}601602pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {603    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });604}605606// --- Hash / Fetch ---607608pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {609    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });610    defer gpa.free(r.stderr);611    if (r.exit_code != 0) {612        gpa.free(r.stdout);613        return error.ProcessFailed;614    }615    return r.stdout;616}617618pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {619    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });620    defer gpa.free(r.stderr);621    if (r.exit_code != 0) {622        gpa.free(r.stdout);623        return error.ProcessFailed;624    }625    return r.stdout;626}627628// --- Pin ---629630pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {631    // Stub: full implementation would parse and edit flake.lock JSON632    // The pin/unpin flow works via nix flake update which regenerates flake.lock633}634635pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {636    if (line) |l| {637        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});638        defer gpa.free(line_arg);639        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });640    }641    return stream(io, &types.Machine{}, gpa, &.{ editor, path });642}643644pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {645    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});646    defer gpa.free(a_str);647    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});648    defer gpa.free(b_str);649    return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });650}651652// --- Doctor checks ---653654pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {655    var checks: std.ArrayList(types.DoctorCheck) = .empty;656657    // Check nix daemon658    {659        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });660        defer gpa.free(r.stdout);661        defer gpa.free(r.stderr);662        const active = std.mem.indexOf(u8, r.stdout, "active") != null;663        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });664    }665666    // Check config syntax667    {668        const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });669        defer gpa.free(r.stdout);670        defer gpa.free(r.stderr);671        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });672    }673674    // Check channel675    {676        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });677        defer gpa.free(r.stdout);678        defer gpa.free(r.stderr);679        const has_channel = r.exit_code == 0 and r.stdout.len > 0;680        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });681    }682683    return checks.toOwnedSlice(gpa);684}685686// --- Log ---687688pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {689    const home = environ.get("HOME") orelse return error.FileNotFound;690    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});691    defer gpa.free(path);692    _ = last;693    return std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;694}695696pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {697    const home = environ.get("HOME") orelse return;698    var path_buf: [512]u8 = undefined;699    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;700    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch701        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);702    defer file.close(io);703    const size = file.length(io) catch 0;704    file.writePositionalAll(io, entry, size) catch {};705}706707// --- Update helpers ---708709// Fetch a URL with curl and return the response body. Caller must free.710// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.711pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {712    const argv = [_][]const u8{713        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,714    };715    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;716    defer gpa.free(result.stderr);717718    const marker = "\nHTTP_STATUS:";719    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {720        gpa.free(result.stdout);721        return error.NetworkError;722    };723    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");724    const status = std.fmt.parseInt(u16, status_str, 10) catch {725        gpa.free(result.stdout);726        return error.NetworkError;727    };728    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }729    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }730    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {731        gpa.free(result.stdout);732        return e;733    };734    gpa.free(result.stdout);735    return body;736}737738// Download a URL to a temp file. Returns the temp path (caller must gpa.free).739// The file is written to /tmp/nina-update-<pid> and left for the caller to use.740pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {741    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");742    errdefer gpa.free(tmp_path);743744    var child = std.process.spawn(io, .{745        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },746        .stdin = .close,747        .stdout = .close,748        .stderr = .inherit,749    }) catch return error.NetworkError;750    const term = child.wait(io) catch return error.NetworkError;751    switch (term) {752        .exited => |c| if (c != 0) return error.NetworkError,753        else => return error.NetworkError,754    }755    return tmp_path;756}757758// Get the current executable path into buf. Returns slice of buf.759pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {760    const len = try std.process.executablePath(io, buf);761    return buf[0..len];762}763764// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then765// atomically install the binary to install_path. Errors: ChecksumMismatch,766// AccessDenied (with error_info set), or underlying I/O errors.767pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {768    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {769        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});770        return error.FileNotFound;771    };772    defer gpa.free(bytes);773774    var hasher = std.crypto.hash.Blake3.init(.{});775    hasher.update(bytes);776    var raw: [32]u8 = undefined;777    hasher.final(&raw);778    const hex = std.fmt.bytesToHex(raw, .lower);779    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;780781    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;782    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch783        return error.NameTooLong;784785    {786        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {787            errors.error_info.setMessage("cannot write to {s}", .{install_path});788            errors.error_info.setSuggestion("try: sudo nina update", .{});789            return error.AccessDenied;790        };791        defer f.close(io);792        f.writePositionalAll(io, bytes, 0) catch {793            errors.error_info.setMessage("cannot write to {s}", .{install_path});794            return error.AccessDenied;795        };796        try f.setPermissions(io, .fromMode(0o755));797    }798    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};799800    if (comptime builtin.os.tag == .macos) {801        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};802    }803804    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {805        error.AccessDenied => {806            errors.error_info.setMessage("cannot replace {s}", .{install_path});807            errors.error_info.setSuggestion("try: sudo nina update", .{});808            return error.AccessDenied;809        },810        else => return e,811    };812}813814// --- Nix feature setup ---815816pub const NixFeatureStatus = struct {817    nix_command: bool = false,818    flakes: bool = false,819820    pub fn allEnabled(self: NixFeatureStatus) bool {821        return self.nix_command and self.flakes;822    }823};824825fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {826    var lines = std.mem.splitScalar(u8, conf, '\n');827    while (lines.next()) |line| {828        const trimmed = std.mem.trim(u8, line, " \t");829        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;830        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;831        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;832    }833}834835pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {836    var status = NixFeatureStatus{};837838    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {839        defer gpa.free(conf);840        scanConfFeatures(conf, &status);841    }842843    if (environ.get("HOME")) |home| {844        var buf: [512]u8 = undefined;845        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;846        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {847            defer gpa.free(conf);848            scanConfFeatures(conf, &status);849        }850    }851852    return status;853}854855pub fn isNixOS(io: std.Io) bool {856    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;857    file.close(io);858    return true;859}860861// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.862// Returns the path written (caller must free).863pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {864    const home = environ.get("HOME") orelse {865        errors.error_info.setMessage("HOME not set", .{});866        return error.ConfigNotFound;867    };868869    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});870    defer gpa.free(dir_path);871    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});872    errdefer gpa.free(file_path);873874    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};875876    const line = "experimental-features = nix-command flakes\n";877    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch878        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {879        errors.error_info.setMessage("could not write {s}", .{file_path});880        return error.FileNotFound;881    });882    defer file.close(io);883884    const size = file.length(io) catch 0;885    file.writePositionalAll(io, line, size) catch {886        errors.error_info.setMessage("could not write {s}", .{file_path});887        return error.FileNotFound;888    };889890    return file_path;891}