exec.zig

24.8 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// Run a process and capture output as a single string (no SSH routing — for local nix commands).66pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {67    const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;68    defer gpa.free(result.stderr);69    switch (result.term) {70        .exited => |c| if (c != 0) {71            gpa.free(result.stdout);72            return error.ProcessFailed;73        },74        else => {75            gpa.free(result.stdout);76            return error.ProcessFailed;77        },78    }79    return result.stdout;80}8182fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {83    if (machine.local) return cmd;8485    const host = machine.host orelse {86        errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});87        return error.SshFailed;88    };8990    var ssh: std.ArrayList([]const u8) = .empty;91    try ssh.append(gpa, "ssh");92    try ssh.append(gpa, "-o");93    try ssh.append(gpa, "BatchMode=yes");94    try ssh.append(gpa, "-o");95    try ssh.append(gpa, "StrictHostKeyChecking=accept-new");96    if (machine.ssh_key) |key| {97        try ssh.append(gpa, "-i");98        try ssh.append(gpa, key);99    }100    const addr = if (machine.user) |u|101        try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })102    else103        try gpa.dupe(u8, host);104    try ssh.append(gpa, addr);105    for (cmd) |arg| try ssh.append(gpa, arg);106    return ssh.toOwnedSlice(gpa);107}108109// --- NixOS rebuild ---110111pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {112    const cmd = &.{ "sudo", "nixos-rebuild", "switch" };113    output.printSubstep("nixos-rebuild switch", .{});114    return stream(io, machine, gpa, cmd);115}116117pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {118    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "dry-activate" });119}120121pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {122    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "build" });123}124125// --- Generations ---126127pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {128    const r = try capture(gpa, io, machine, &.{ "nix-env", "-p", SYSTEM_PROFILE, "--list-generations" });129    defer gpa.free(r.stderr);130    defer gpa.free(r.stdout);131    if (r.exit_code != 0) return error.ProcessFailed;132    return parseGenerations(gpa, r.stdout);133}134135fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {136    var gens: std.ArrayList(types.GenerationInfo) = .empty;137    var lines = std.mem.splitScalar(u8, output_str, '\n');138    while (lines.next()) |line| {139        const trimmed = std.mem.trim(u8, line, " \t");140        if (trimmed.len == 0) continue;141        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");142        const num_str = parts.next() orelse continue;143        const date_str = parts.next() orelse continue;144        const time_str = parts.next() orelse continue;145        const rest = parts.rest();146        const current = std.mem.indexOf(u8, rest, "current") != null;147        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;148        try gens.append(gpa, .{149            .number = num,150            .date = try gpa.dupe(u8, date_str),151            .time = try gpa.dupe(u8, time_str),152            .current = current,153        });154    }155    return gens.toOwnedSlice(gpa);156}157158pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {159    const gens = try getGenerations(gpa, io, machine);160    defer gpa.free(gens);161    for (gens) |g| {162        if (g.current) return g.number;163    }164    return 0;165}166167pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {168    // Switch the system profile to generation n, then activate it (bootloader +169    // services). Without switch-to-configuration the change isn't applied.170    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 });171    defer gpa.free(cmd);172    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });173}174175pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {176    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });177}178179pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {180    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});181    defer gpa.free(n_str);182    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });183}184185pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {186    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });187}188189// --- Garbage collection ---190191pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {192    if (delete_old) {193        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });194    }195    // Keep the `keep` most recent system generations (+N deletes all but N),196    // then collect now-unreferenced store paths. `--delete-older-than` wants a197    // duration (e.g. 14d), not a generation count.198    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });199    defer gpa.free(cmd);200    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });201}202203// --- Channels ---204205pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {206    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });207    defer gpa.free(r.stderr);208    defer gpa.free(r.stdout);209    if (r.exit_code != 0) return error.ProcessFailed;210    return parseChannels(gpa, r.stdout);211}212213fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {214    var channels: std.ArrayList(types.ChannelInfo) = .empty;215    var lines = std.mem.splitScalar(u8, output_str, '\n');216    while (lines.next()) |line| {217        const trimmed = std.mem.trim(u8, line, " \t\r");218        if (trimmed.len == 0) continue;219        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;220        try channels.append(gpa, .{221            .name = try gpa.dupe(u8, trimmed[0..space]),222            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),223        });224    }225    return channels.toOwnedSlice(gpa);226}227228pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {229    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });230}231232pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {233    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });234}235236pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {237    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });238}239240// --- Services ---241242pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ServiceInfo {243    const r = try capture(gpa, io, machine, &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" });244    defer gpa.free(r.stderr);245    defer gpa.free(r.stdout);246    if (r.exit_code != 0) return error.ProcessFailed;247    return parseServices(gpa, r.stdout);248}249250fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {251    var svcs: std.ArrayList(types.ServiceInfo) = .empty;252    var lines = std.mem.splitScalar(u8, output_str, '\n');253    while (lines.next()) |line| {254        const trimmed = std.mem.trim(u8, line, " \t\r");255        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines256        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");257        const name = parts.next() orelse continue;258        _ = parts.next(); // load259        const active_str = parts.next() orelse continue;260        const sub_str = parts.next() orelse "unknown";261262        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))263            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)264        else if (std.mem.eql(u8, active_str, "failed"))265            .failed266        else267            .inactive;268269        try svcs.append(gpa, .{270            .name = try gpa.dupe(u8, name),271            .state = state,272            .uptime = null,273        });274    }275    return svcs.toOwnedSlice(gpa);276}277278pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8) !u8 {279    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.280    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });281}282283pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool) !u8 {284    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});285    defer gpa.free(n_str);286    if (follow) {287        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });288    }289    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });290}291292// --- Profile ---293294pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {295    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});296    defer gpa.free(pkg_ref);297    return stream(io, machine, gpa, &.{ "nix", "profile", "install", pkg_ref });298}299300pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {301    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not302    // by flake ref — passing nixpkgs#ripgrep matches nothing.303    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });304}305306pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {307    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });308    defer gpa.free(r.stderr);309    if (r.exit_code != 0) return error.ProcessFailed;310    return r.stdout;311}312313pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {314    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });315}316317// --- Store ---318319pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {320    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });321}322323pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {324    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });325}326327pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {328    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });329}330331pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {332    const pi = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "--all", "--json" });333    defer gpa.free(pi.stdout);334    defer gpa.free(pi.stderr);335336    var live: u64 = 0;337    if (pi.exit_code == 0) {338        live = countJsonPaths(pi.stdout);339    }340341    const du = try capture(gpa, io, machine, &.{ "du", "-sh", "/nix/store" });342    defer gpa.free(du.stderr);343    const total = blk: {344        const line = std.mem.trim(u8, du.stdout, " \t\n\r");345        const tab = std.mem.indexOfScalar(u8, line, '\t') orelse break :blk "?";346        break :blk line[0..tab];347    };348    const total_owned = try gpa.dupe(u8, total);349    gpa.free(du.stdout);350351    return .{352        .total_size = total_owned,353        .live_paths = live,354        .reclaimable_paths = 0,355    };356}357358fn countJsonPaths(json_str: []const u8) u64 {359    // quick count: number of top-level keys360    var count: u64 = 0;361    var i: usize = 0;362    while (i < json_str.len) : (i += 1) {363        if (json_str[i] == '"') count += 1;364    }365    return count / 2; // each path has 2 quotes366}367368pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {369    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the370    // flake registry), not a flake in the current directory.371    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});372    defer gpa.free(expr);373    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });374    defer gpa.free(r.stderr);375    if (r.exit_code != 0) {376        gpa.free(r.stdout);377        return error.ProcessFailed;378    }379    return r.stdout;380}381382// --- Flake ---383384pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {385    if (input) |inp| {386        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });387    }388    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });389}390391pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {392    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });393}394395pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {396    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });397}398399pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {400    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });401}402403pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {404    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });405}406407pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {408    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });409    defer gpa.free(r.stderr);410    if (r.exit_code != 0) {411        gpa.free(r.stdout);412        return error.ProcessFailed;413    }414    return r.stdout;415}416417// --- Build / Run / Develop ---418419pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {420    if (attr) |a| {421        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});422        defer gpa.free(ref);423        return stream(io, machine, gpa, &.{ "nix", "build", ref });424    }425    return stream(io, machine, gpa, &.{ "nix", "build" });426}427428pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {429    // nix run always gets --no-write-lock-file for remote URLs430    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");431    if (is_url) {432        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });433    }434    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});435    defer gpa.free(ref);436    return stream(io, machine, gpa, &.{ "nix", "run", ref });437}438439pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {440    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});441    defer gpa.free(ref);442    return stream(io, machine, gpa, &.{ "nix", "shell", ref });443}444445pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {446    if (run_cmd) |cmd| {447        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", cmd });448    }449    return stream(io, machine, gpa, &.{ "nix", "develop" });450}451452pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {453    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });454}455456// --- Format ---457458pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {459    if (check) {460        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });461    }462    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });463}464465// --- Info ---466467pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {468    const r = try capture(gpa, io, machine, &.{"nixos-version"});469    defer gpa.free(r.stderr);470    if (r.exit_code != 0) {471        gpa.free(r.stdout);472        return error.ProcessFailed;473    }474    return r.stdout;475}476477pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {478    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });479    defer gpa.free(r.stderr);480    if (r.exit_code != 0) {481        gpa.free(r.stdout);482        return error.ProcessFailed;483    }484    return r.stdout;485}486487pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {488    const r = try capture(gpa, io, machine, &.{"uptime"});489    defer gpa.free(r.stderr);490    if (r.exit_code != 0) {491        gpa.free(r.stdout);492        return error.ProcessFailed;493    }494    return r.stdout;495}496497// --- Boot ---498499pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {500    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });501    defer gpa.free(r.stderr);502    defer gpa.free(r.stdout);503    if (r.exit_code != 0) return error.ProcessFailed;504    return parseBootEntries(gpa, r.stdout);505}506507fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {508    var entries: std.ArrayList(types.BootEntry) = .empty;509    var lines = std.mem.splitScalar(u8, output_str, '\n');510    while (lines.next()) |line| {511        const trimmed = std.mem.trim(u8, line, " \t\r");512        if (std.mem.startsWith(u8, trimmed, "title:")) {513            const title = std.mem.trim(u8, trimmed[6..], " \t");514            const current = std.mem.indexOf(u8, title, "(current)") != null;515            try entries.append(gpa, .{516                .title = try gpa.dupe(u8, title),517                .current = current,518            });519        }520    }521    return entries.toOwnedSlice(gpa);522}523524// --- Pkg info ---525526pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {527    return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });528}529530pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {531    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });532}533534pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {535    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", pkg });536    defer gpa.free(r.stderr);537    if (r.exit_code != 0) {538        gpa.free(r.stdout);539        return error.ProcessFailed;540    }541    return r.stdout;542}543544pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {545    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });546}547548// --- Hash / Fetch ---549550pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {551    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });552    defer gpa.free(r.stderr);553    if (r.exit_code != 0) {554        gpa.free(r.stdout);555        return error.ProcessFailed;556    }557    return r.stdout;558}559560pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {561    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });562    defer gpa.free(r.stderr);563    if (r.exit_code != 0) {564        gpa.free(r.stdout);565        return error.ProcessFailed;566    }567    return r.stdout;568}569570// --- Pin ---571572pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {573    // Stub: full implementation would parse and edit flake.lock JSON574    // The pin/unpin flow works via nix flake update which regenerates flake.lock575}576577pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {578    if (line) |l| {579        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});580        defer gpa.free(line_arg);581        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });582    }583    return stream(io, &types.Machine{}, gpa, &.{ editor, path });584}585586pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {587    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});588    defer gpa.free(a_str);589    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});590    defer gpa.free(b_str);591    return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });592}593594// --- Doctor checks ---595596pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {597    var checks: std.ArrayList(types.DoctorCheck) = .empty;598599    // Check nix daemon600    {601        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });602        defer gpa.free(r.stdout);603        defer gpa.free(r.stderr);604        const active = std.mem.indexOf(u8, r.stdout, "active") != null;605        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });606    }607608    // Check config syntax609    {610        const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });611        defer gpa.free(r.stdout);612        defer gpa.free(r.stderr);613        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });614    }615616    // Check channel617    {618        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });619        defer gpa.free(r.stdout);620        defer gpa.free(r.stderr);621        const has_channel = r.exit_code == 0 and r.stdout.len > 0;622        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });623    }624625    return checks.toOwnedSlice(gpa);626}627628// --- Log ---629630pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {631    const home = environ.get("HOME") orelse return error.FileNotFound;632    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});633    defer gpa.free(path);634    _ = last;635    return std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;636}637638pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {639    const home = environ.get("HOME") orelse return;640    var path_buf: [512]u8 = undefined;641    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;642    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch643        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);644    defer file.close(io);645    const size = file.length(io) catch 0;646    file.writePositionalAll(io, entry, size) catch {};647}