exec.zig

33.0 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 ---147148pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {149    const r = try capture(gpa, io, machine, &.{ "nix-env", "-p", SYSTEM_PROFILE, "--list-generations" });150    defer gpa.free(r.stderr);151    defer gpa.free(r.stdout);152    if (r.exit_code != 0) return error.ProcessFailed;153    return parseGenerations(gpa, r.stdout);154}155156fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {157    var gens: std.ArrayList(types.GenerationInfo) = .empty;158    var lines = std.mem.splitScalar(u8, output_str, '\n');159    while (lines.next()) |line| {160        const trimmed = std.mem.trim(u8, line, " \t");161        if (trimmed.len == 0) continue;162        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");163        const num_str = parts.next() orelse continue;164        const date_str = parts.next() orelse continue;165        const time_str = parts.next() orelse continue;166        const rest = parts.rest();167        const current = std.mem.indexOf(u8, rest, "current") != null;168        const num = std.fmt.parseInt(u32, num_str, 10) catch continue;169        try gens.append(gpa, .{170            .number = num,171            .date = try gpa.dupe(u8, date_str),172            .time = try gpa.dupe(u8, time_str),173            .current = current,174        });175    }176    return gens.toOwnedSlice(gpa);177}178179pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {180    const gens = try getGenerations(gpa, io, machine);181    defer gpa.free(gens);182    for (gens) |g| {183        if (g.current) return g.number;184    }185    return 0;186}187188pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {189    // Switch the system profile to generation n, then activate it (bootloader +190    // services). Without switch-to-configuration the change isn't applied.191    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 });192    defer gpa.free(cmd);193    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });194}195196pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {197    return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });198}199200pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {201    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});202    defer gpa.free(n_str);203    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });204}205206pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {207    return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });208}209210// --- Garbage collection ---211212pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {213    if (delete_old) {214        return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });215    }216    // Keep the `keep` most recent system generations (+N deletes all but N),217    // then collect now-unreferenced store paths. `--delete-older-than` wants a218    // duration (e.g. 14d), not a generation count.219    const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });220    defer gpa.free(cmd);221    return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });222}223224// --- Channels ---225226pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {227    const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });228    defer gpa.free(r.stderr);229    defer gpa.free(r.stdout);230    if (r.exit_code != 0) return error.ProcessFailed;231    return parseChannels(gpa, r.stdout);232}233234fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {235    var channels: std.ArrayList(types.ChannelInfo) = .empty;236    var lines = std.mem.splitScalar(u8, output_str, '\n');237    while (lines.next()) |line| {238        const trimmed = std.mem.trim(u8, line, " \t\r");239        if (trimmed.len == 0) continue;240        const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;241        try channels.append(gpa, .{242            .name = try gpa.dupe(u8, trimmed[0..space]),243            .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),244        });245    }246    return channels.toOwnedSlice(gpa);247}248249pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {250    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });251}252253pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {254    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });255}256257pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {258    return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });259}260261// --- Services ---262263pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ServiceInfo {264    const r = try capture(gpa, io, machine, &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" });265    defer gpa.free(r.stderr);266    defer gpa.free(r.stdout);267    if (r.exit_code != 0) return error.ProcessFailed;268    return parseServices(gpa, r.stdout);269}270271fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {272    var svcs: std.ArrayList(types.ServiceInfo) = .empty;273    var lines = std.mem.splitScalar(u8, output_str, '\n');274    while (lines.next()) |line| {275        const trimmed = std.mem.trim(u8, line, " \t\r");276        if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines277        var parts = std.mem.tokenizeAny(u8, trimmed, " \t");278        const name = parts.next() orelse continue;279        _ = parts.next(); // load280        const active_str = parts.next() orelse continue;281        const sub_str = parts.next() orelse "unknown";282283        const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))284            (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)285        else if (std.mem.eql(u8, active_str, "failed"))286            .failed287        else288            .inactive;289290        try svcs.append(gpa, .{291            .name = try gpa.dupe(u8, name),292            .state = state,293            .uptime = null,294        });295    }296    return svcs.toOwnedSlice(gpa);297}298299pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8) !u8 {300    // --no-pager: `systemctl status` pipes to a pager on a tty and would block.301    return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });302}303304pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool) !u8 {305    const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});306    defer gpa.free(n_str);307    if (follow) {308        return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });309    }310    return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });311}312313// --- Profile ---314315pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {316    const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});317    defer gpa.free(pkg_ref);318    return stream(io, machine, gpa, &.{ "nix", "profile", "install", pkg_ref });319}320321pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {322    // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not323    // by flake ref — passing nixpkgs#ripgrep matches nothing.324    return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });325}326327pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {328    const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });329    defer gpa.free(r.stderr);330    if (r.exit_code != 0) return error.ProcessFailed;331    return r.stdout;332}333334pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {335    return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });336}337338// --- Store ---339340pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {341    return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });342}343344pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {345    return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });346}347348pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {349    return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });350}351352pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {353    const pi = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "--all", "--json" });354    defer gpa.free(pi.stdout);355    defer gpa.free(pi.stderr);356357    var live: u64 = 0;358    if (pi.exit_code == 0) {359        live = countJsonPaths(pi.stdout);360    }361362    const du = try capture(gpa, io, machine, &.{ "du", "-sh", "/nix/store" });363    defer gpa.free(du.stderr);364    const total = blk: {365        const line = std.mem.trim(u8, du.stdout, " \t\n\r");366        const tab = std.mem.indexOfScalar(u8, line, '\t') orelse break :blk "?";367        break :blk line[0..tab];368    };369    const total_owned = try gpa.dupe(u8, total);370    gpa.free(du.stdout);371372    return .{373        .total_size = total_owned,374        .live_paths = live,375        .reclaimable_paths = 0,376    };377}378379fn countJsonPaths(json_str: []const u8) u64 {380    // quick count: number of top-level keys381    var count: u64 = 0;382    var i: usize = 0;383    while (i < json_str.len) : (i += 1) {384        if (json_str[i] == '"') count += 1;385    }386    return count / 2; // each path has 2 quotes387}388389pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {390    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the391    // flake registry), not a flake in the current directory.392    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});393    defer gpa.free(expr);394    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });395    defer gpa.free(r.stderr);396    if (r.exit_code != 0) {397        gpa.free(r.stdout);398        return error.ProcessFailed;399    }400    return r.stdout;401}402403// --- Flake ---404405pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {406    if (input) |inp| {407        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });408    }409    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });410}411412pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {413    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });414}415416pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {417    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });418}419420pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {421    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });422}423424pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {425    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });426}427428pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {429    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });430    defer gpa.free(r.stderr);431    if (r.exit_code != 0) {432        gpa.free(r.stdout);433        return error.ProcessFailed;434    }435    return r.stdout;436}437438// --- Build / Run / Develop ---439440pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {441    if (attr) |a| {442        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});443        defer gpa.free(ref);444        return stream(io, machine, gpa, &.{ "nix", "build", ref });445    }446    return stream(io, machine, gpa, &.{ "nix", "build" });447}448449pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {450    // nix run always gets --no-write-lock-file for remote URLs451    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");452    if (is_url) {453        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });454    }455    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.456    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {457        return stream(io, machine, gpa, &.{ "nix", "run", pkg });458    }459    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});460    defer gpa.free(ref);461    return stream(io, machine, gpa, &.{ "nix", "run", ref });462}463464pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {465    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});466    defer gpa.free(ref);467    return stream(io, machine, gpa, &.{ "nix", "shell", ref });468}469470pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {471    if (run_cmd) |cmd| {472        // sh -c so a multi-word command isn't treated as a single executable name.473        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });474    }475    return stream(io, machine, gpa, &.{ "nix", "develop" });476}477478pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {479    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });480}481482// --- Format ---483484pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {485    if (check) {486        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });487    }488    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });489}490491// --- Info ---492493pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {494    const r = try capture(gpa, io, machine, &.{"nixos-version"});495    defer gpa.free(r.stderr);496    if (r.exit_code != 0) {497        gpa.free(r.stdout);498        return error.ProcessFailed;499    }500    return r.stdout;501}502503pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {504    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });505    defer gpa.free(r.stderr);506    if (r.exit_code != 0) {507        gpa.free(r.stdout);508        return error.ProcessFailed;509    }510    return r.stdout;511}512513pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {514    const r = try capture(gpa, io, machine, &.{"uptime"});515    defer gpa.free(r.stderr);516    if (r.exit_code != 0) {517        gpa.free(r.stdout);518        return error.ProcessFailed;519    }520    return r.stdout;521}522523// --- Boot ---524525pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {526    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });527    defer gpa.free(r.stderr);528    defer gpa.free(r.stdout);529    if (r.exit_code != 0) return error.ProcessFailed;530    return parseBootEntries(gpa, r.stdout);531}532533fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {534    var entries: std.ArrayList(types.BootEntry) = .empty;535    var lines = std.mem.splitScalar(u8, output_str, '\n');536    while (lines.next()) |line| {537        const trimmed = std.mem.trim(u8, line, " \t\r");538        if (std.mem.startsWith(u8, trimmed, "title:")) {539            const title = std.mem.trim(u8, trimmed[6..], " \t");540            const current = std.mem.indexOf(u8, title, "(current)") != null;541            try entries.append(gpa, .{542                .title = try gpa.dupe(u8, title),543                .current = current,544            });545        }546    }547    return entries.toOwnedSlice(gpa);548}549550// --- Pkg info ---551552pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {553    return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });554}555556pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {557    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });558}559560pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {561    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", pkg });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}569570pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {571    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });572}573574// --- Hash / Fetch ---575576pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {577    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });578    defer gpa.free(r.stderr);579    if (r.exit_code != 0) {580        gpa.free(r.stdout);581        return error.ProcessFailed;582    }583    return r.stdout;584}585586pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {587    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });588    defer gpa.free(r.stderr);589    if (r.exit_code != 0) {590        gpa.free(r.stdout);591        return error.ProcessFailed;592    }593    return r.stdout;594}595596// --- Pin ---597598pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {599    // Stub: full implementation would parse and edit flake.lock JSON600    // The pin/unpin flow works via nix flake update which regenerates flake.lock601}602603pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {604    if (line) |l| {605        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});606        defer gpa.free(line_arg);607        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });608    }609    return stream(io, &types.Machine{}, gpa, &.{ editor, path });610}611612pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {613    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});614    defer gpa.free(a_str);615    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});616    defer gpa.free(b_str);617    return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });618}619620// --- Doctor checks ---621622pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {623    var checks: std.ArrayList(types.DoctorCheck) = .empty;624625    // Check nix daemon626    {627        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });628        defer gpa.free(r.stdout);629        defer gpa.free(r.stderr);630        const active = std.mem.indexOf(u8, r.stdout, "active") != null;631        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });632    }633634    // Check config syntax635    {636        const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });637        defer gpa.free(r.stdout);638        defer gpa.free(r.stderr);639        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });640    }641642    // Check channel643    {644        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });645        defer gpa.free(r.stdout);646        defer gpa.free(r.stderr);647        const has_channel = r.exit_code == 0 and r.stdout.len > 0;648        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });649    }650651    return checks.toOwnedSlice(gpa);652}653654// --- Log ---655656pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {657    const home = environ.get("HOME") orelse return error.FileNotFound;658    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});659    defer gpa.free(path);660    _ = last;661    return std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;662}663664pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {665    const home = environ.get("HOME") orelse return;666    var path_buf: [512]u8 = undefined;667    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;668    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch669        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);670    defer file.close(io);671    const size = file.length(io) catch 0;672    file.writePositionalAll(io, entry, size) catch {};673}674675// --- Update helpers ---676677// Fetch a URL with curl and return the response body. Caller must free.678// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.679pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {680    const argv = [_][]const u8{681        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,682    };683    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;684    defer gpa.free(result.stderr);685686    const marker = "\nHTTP_STATUS:";687    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {688        gpa.free(result.stdout);689        return error.NetworkError;690    };691    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");692    const status = std.fmt.parseInt(u16, status_str, 10) catch {693        gpa.free(result.stdout);694        return error.NetworkError;695    };696    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }697    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }698    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {699        gpa.free(result.stdout);700        return e;701    };702    gpa.free(result.stdout);703    return body;704}705706// Download a URL to a temp file. Returns the temp path (caller must gpa.free).707// The file is written to /tmp/nina-update-<pid> and left for the caller to use.708pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {709    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");710    errdefer gpa.free(tmp_path);711712    var child = std.process.spawn(io, .{713        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },714        .stdin = .close,715        .stdout = .close,716        .stderr = .inherit,717    }) catch return error.NetworkError;718    const term = child.wait(io) catch return error.NetworkError;719    switch (term) {720        .exited => |c| if (c != 0) return error.NetworkError,721        else => return error.NetworkError,722    }723    return tmp_path;724}725726// Get the current executable path into buf. Returns slice of buf.727pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {728    const len = try std.process.executablePath(io, buf);729    return buf[0..len];730}731732// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then733// atomically install the binary to install_path. Errors: ChecksumMismatch,734// AccessDenied (with error_info set), or underlying I/O errors.735pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {736    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {737        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});738        return error.FileNotFound;739    };740    defer gpa.free(bytes);741742    var hasher = std.crypto.hash.Blake3.init(.{});743    hasher.update(bytes);744    var raw: [32]u8 = undefined;745    hasher.final(&raw);746    const hex = std.fmt.bytesToHex(raw, .lower);747    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;748749    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;750    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch751        return error.NameTooLong;752753    {754        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {755            errors.error_info.setMessage("cannot write to {s}", .{install_path});756            errors.error_info.setSuggestion("try: sudo nina update", .{});757            return error.AccessDenied;758        };759        defer f.close(io);760        f.writePositionalAll(io, bytes, 0) catch {761            errors.error_info.setMessage("cannot write to {s}", .{install_path});762            return error.AccessDenied;763        };764        try f.setPermissions(io, .fromMode(0o755));765    }766    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};767768    if (comptime builtin.os.tag == .macos) {769        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};770    }771772    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {773        error.AccessDenied => {774            errors.error_info.setMessage("cannot replace {s}", .{install_path});775            errors.error_info.setSuggestion("try: sudo nina update", .{});776            return error.AccessDenied;777        },778        else => return e,779    };780}781782// --- Nix feature setup ---783784pub const NixFeatureStatus = struct {785    nix_command: bool = false,786    flakes: bool = false,787788    pub fn allEnabled(self: NixFeatureStatus) bool {789        return self.nix_command and self.flakes;790    }791};792793fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {794    var lines = std.mem.splitScalar(u8, conf, '\n');795    while (lines.next()) |line| {796        const trimmed = std.mem.trim(u8, line, " \t");797        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;798        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;799        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;800    }801}802803pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {804    var status = NixFeatureStatus{};805806    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {807        defer gpa.free(conf);808        scanConfFeatures(conf, &status);809    }810811    if (environ.get("HOME")) |home| {812        var buf: [512]u8 = undefined;813        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;814        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {815            defer gpa.free(conf);816            scanConfFeatures(conf, &status);817        }818    }819820    return status;821}822823pub fn isNixOS(io: std.Io) bool {824    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;825    file.close(io);826    return true;827}828829// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.830// Returns the path written (caller must free).831pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {832    const home = environ.get("HOME") orelse {833        errors.error_info.setMessage("HOME not set", .{});834        return error.ConfigNotFound;835    };836837    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});838    defer gpa.free(dir_path);839    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});840    errdefer gpa.free(file_path);841842    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};843844    const line = "experimental-features = nix-command flakes\n";845    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch846        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {847        errors.error_info.setMessage("could not write {s}", .{file_path});848        return error.FileNotFound;849    });850    defer file.close(io);851852    const size = file.length(io) catch 0;853    file.writePositionalAll(io, line, size) catch {854        errors.error_info.setMessage("could not write {s}", .{file_path});855        return error.FileNotFound;856    };857858    return file_path;859}