exec.zig

33.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// 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    const pi = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "--all", "--json" });365    defer gpa.free(pi.stdout);366    defer gpa.free(pi.stderr);367368    var live: u64 = 0;369    if (pi.exit_code == 0) {370        live = countJsonPaths(pi.stdout);371    }372373    const du = try capture(gpa, io, machine, &.{ "du", "-sh", "/nix/store" });374    defer gpa.free(du.stderr);375    const total = blk: {376        const line = std.mem.trim(u8, du.stdout, " \t\n\r");377        const tab = std.mem.indexOfScalar(u8, line, '\t') orelse break :blk "?";378        break :blk line[0..tab];379    };380    const total_owned = try gpa.dupe(u8, total);381    gpa.free(du.stdout);382383    return .{384        .total_size = total_owned,385        .live_paths = live,386        .reclaimable_paths = 0,387    };388}389390fn countJsonPaths(json_str: []const u8) u64 {391    // quick count: number of top-level keys392    var count: u64 = 0;393    var i: usize = 0;394    while (i < json_str.len) : (i += 1) {395        if (json_str[i] == '"') count += 1;396    }397    return count / 2; // each path has 2 quotes398}399400pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {401    // nixpkgs#<attr>, not .#<attr>: the package lives in nixpkgs (resolved via the402    // flake registry), not a flake in the current directory.403    const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});404    defer gpa.free(expr);405    const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });406    defer gpa.free(r.stderr);407    if (r.exit_code != 0) {408        gpa.free(r.stdout);409        return error.ProcessFailed;410    }411    return r.stdout;412}413414// --- Flake ---415416pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {417    if (input) |inp| {418        return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });419    }420    return stream(io, machine, gpa, &.{ "nix", "flake", "update" });421}422423pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {424    return stream(io, machine, gpa, &.{ "nix", "flake", "check" });425}426427pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {428    return stream(io, machine, gpa, &.{ "nix", "flake", "init" });429}430431pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {432    return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });433}434435pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {436    return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });437}438439pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {440    const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });441    defer gpa.free(r.stderr);442    if (r.exit_code != 0) {443        gpa.free(r.stdout);444        return error.ProcessFailed;445    }446    return r.stdout;447}448449// --- Build / Run / Develop ---450451pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {452    if (attr) |a| {453        const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});454        defer gpa.free(ref);455        return stream(io, machine, gpa, &.{ "nix", "build", ref });456    }457    return stream(io, machine, gpa, &.{ "nix", "build" });458}459460pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {461    // nix run always gets --no-write-lock-file for remote URLs462    const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");463    if (is_url) {464        return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });465    }466    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.467    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {468        return stream(io, machine, gpa, &.{ "nix", "run", pkg });469    }470    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});471    defer gpa.free(ref);472    return stream(io, machine, gpa, &.{ "nix", "run", ref });473}474475pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {476    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});477    defer gpa.free(ref);478    return stream(io, machine, gpa, &.{ "nix", "shell", ref });479}480481pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {482    if (run_cmd) |cmd| {483        // sh -c so a multi-word command isn't treated as a single executable name.484        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });485    }486    return stream(io, machine, gpa, &.{ "nix", "develop" });487}488489pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {490    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });491}492493// --- Format ---494495pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {496    if (check) {497        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });498    }499    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });500}501502// --- Info ---503504pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {505    const r = try capture(gpa, io, machine, &.{"nixos-version"});506    defer gpa.free(r.stderr);507    if (r.exit_code != 0) {508        gpa.free(r.stdout);509        return error.ProcessFailed;510    }511    return r.stdout;512}513514pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {515    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });516    defer gpa.free(r.stderr);517    if (r.exit_code != 0) {518        gpa.free(r.stdout);519        return error.ProcessFailed;520    }521    return r.stdout;522}523524pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {525    const r = try capture(gpa, io, machine, &.{"uptime"});526    defer gpa.free(r.stderr);527    if (r.exit_code != 0) {528        gpa.free(r.stdout);529        return error.ProcessFailed;530    }531    return r.stdout;532}533534// --- Boot ---535536pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {537    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });538    defer gpa.free(r.stderr);539    defer gpa.free(r.stdout);540    if (r.exit_code != 0) return error.ProcessFailed;541    return parseBootEntries(gpa, r.stdout);542}543544fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {545    var entries: std.ArrayList(types.BootEntry) = .empty;546    var lines = std.mem.splitScalar(u8, output_str, '\n');547    while (lines.next()) |line| {548        const trimmed = std.mem.trim(u8, line, " \t\r");549        if (std.mem.startsWith(u8, trimmed, "title:")) {550            const title = std.mem.trim(u8, trimmed[6..], " \t");551            const current = std.mem.indexOf(u8, title, "(current)") != null;552            try entries.append(gpa, .{553                .title = try gpa.dupe(u8, title),554                .current = current,555            });556        }557    }558    return entries.toOwnedSlice(gpa);559}560561// --- Pkg info ---562563pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {564    return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });565}566567pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {568    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });569}570571pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {572    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", pkg });573    defer gpa.free(r.stderr);574    if (r.exit_code != 0) {575        gpa.free(r.stdout);576        return error.ProcessFailed;577    }578    return r.stdout;579}580581pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {582    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });583}584585// --- Hash / Fetch ---586587pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {588    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });589    defer gpa.free(r.stderr);590    if (r.exit_code != 0) {591        gpa.free(r.stdout);592        return error.ProcessFailed;593    }594    return r.stdout;595}596597pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {598    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });599    defer gpa.free(r.stderr);600    if (r.exit_code != 0) {601        gpa.free(r.stdout);602        return error.ProcessFailed;603    }604    return r.stdout;605}606607// --- Pin ---608609pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {610    // Stub: full implementation would parse and edit flake.lock JSON611    // The pin/unpin flow works via nix flake update which regenerates flake.lock612}613614pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {615    if (line) |l| {616        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});617        defer gpa.free(line_arg);618        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });619    }620    return stream(io, &types.Machine{}, gpa, &.{ editor, path });621}622623pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {624    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});625    defer gpa.free(a_str);626    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});627    defer gpa.free(b_str);628    return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });629}630631// --- Doctor checks ---632633pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {634    var checks: std.ArrayList(types.DoctorCheck) = .empty;635636    // Check nix daemon637    {638        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });639        defer gpa.free(r.stdout);640        defer gpa.free(r.stderr);641        const active = std.mem.indexOf(u8, r.stdout, "active") != null;642        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });643    }644645    // Check config syntax646    {647        const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });648        defer gpa.free(r.stdout);649        defer gpa.free(r.stderr);650        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });651    }652653    // Check channel654    {655        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });656        defer gpa.free(r.stdout);657        defer gpa.free(r.stderr);658        const has_channel = r.exit_code == 0 and r.stdout.len > 0;659        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });660    }661662    return checks.toOwnedSlice(gpa);663}664665// --- Log ---666667pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {668    const home = environ.get("HOME") orelse return error.FileNotFound;669    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});670    defer gpa.free(path);671    _ = last;672    return std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;673}674675pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {676    const home = environ.get("HOME") orelse return;677    var path_buf: [512]u8 = undefined;678    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;679    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch680        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);681    defer file.close(io);682    const size = file.length(io) catch 0;683    file.writePositionalAll(io, entry, size) catch {};684}685686// --- Update helpers ---687688// Fetch a URL with curl and return the response body. Caller must free.689// error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response.690pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {691    const argv = [_][]const u8{692        "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,693    };694    const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;695    defer gpa.free(result.stderr);696697    const marker = "\nHTTP_STATUS:";698    const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {699        gpa.free(result.stdout);700        return error.NetworkError;701    };702    const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");703    const status = std.fmt.parseInt(u16, status_str, 10) catch {704        gpa.free(result.stdout);705        return error.NetworkError;706    };707    if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }708    if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }709    const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {710        gpa.free(result.stdout);711        return e;712    };713    gpa.free(result.stdout);714    return body;715}716717// Download a URL to a temp file. Returns the temp path (caller must gpa.free).718// The file is written to /tmp/nina-update-<pid> and left for the caller to use.719pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {720    const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");721    errdefer gpa.free(tmp_path);722723    var child = std.process.spawn(io, .{724        .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },725        .stdin = .close,726        .stdout = .close,727        .stderr = .inherit,728    }) catch return error.NetworkError;729    const term = child.wait(io) catch return error.NetworkError;730    switch (term) {731        .exited => |c| if (c != 0) return error.NetworkError,732        else => return error.NetworkError,733    }734    return tmp_path;735}736737// Get the current executable path into buf. Returns slice of buf.738pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {739    const len = try std.process.executablePath(io, buf);740    return buf[0..len];741}742743// Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then744// atomically install the binary to install_path. Errors: ChecksumMismatch,745// AccessDenied (with error_info set), or underlying I/O errors.746pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {747    const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {748        errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});749        return error.FileNotFound;750    };751    defer gpa.free(bytes);752753    var hasher = std.crypto.hash.Blake3.init(.{});754    hasher.update(bytes);755    var raw: [32]u8 = undefined;756    hasher.final(&raw);757    const hex = std.fmt.bytesToHex(raw, .lower);758    if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;759760    var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;761    const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch762        return error.NameTooLong;763764    {765        const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {766            errors.error_info.setMessage("cannot write to {s}", .{install_path});767            errors.error_info.setSuggestion("try: sudo nina update", .{});768            return error.AccessDenied;769        };770        defer f.close(io);771        f.writePositionalAll(io, bytes, 0) catch {772            errors.error_info.setMessage("cannot write to {s}", .{install_path});773            return error.AccessDenied;774        };775        try f.setPermissions(io, .fromMode(0o755));776    }777    errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};778779    if (comptime builtin.os.tag == .macos) {780        _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};781    }782783    std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {784        error.AccessDenied => {785            errors.error_info.setMessage("cannot replace {s}", .{install_path});786            errors.error_info.setSuggestion("try: sudo nina update", .{});787            return error.AccessDenied;788        },789        else => return e,790    };791}792793// --- Nix feature setup ---794795pub const NixFeatureStatus = struct {796    nix_command: bool = false,797    flakes: bool = false,798799    pub fn allEnabled(self: NixFeatureStatus) bool {800        return self.nix_command and self.flakes;801    }802};803804fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {805    var lines = std.mem.splitScalar(u8, conf, '\n');806    while (lines.next()) |line| {807        const trimmed = std.mem.trim(u8, line, " \t");808        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;809        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;810        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;811    }812}813814pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {815    var status = NixFeatureStatus{};816817    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {818        defer gpa.free(conf);819        scanConfFeatures(conf, &status);820    }821822    if (environ.get("HOME")) |home| {823        var buf: [512]u8 = undefined;824        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;825        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {826            defer gpa.free(conf);827            scanConfFeatures(conf, &status);828        }829    }830831    return status;832}833834pub fn isNixOS(io: std.Io) bool {835    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;836    file.close(io);837    return true;838}839840// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.841// Returns the path written (caller must free).842pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {843    const home = environ.get("HOME") orelse {844        errors.error_info.setMessage("HOME not set", .{});845        return error.ConfigNotFound;846    };847848    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});849    defer gpa.free(dir_path);850    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});851    errdefer gpa.free(file_path);852853    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};854855    const line = "experimental-features = nix-command flakes\n";856    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch857        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {858        errors.error_info.setMessage("could not write {s}", .{file_path});859        return error.FileNotFound;860    });861    defer file.close(io);862863    const size = file.length(io) catch 0;864    file.writePositionalAll(io, line, size) catch {865        errors.error_info.setMessage("could not write {s}", .{file_path});866        return error.FileNotFound;867    };868869    return file_path;870}