exec.zig

27.9 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    // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#.435    if (std.mem.indexOfScalar(u8, pkg, '#') != null) {436        return stream(io, machine, gpa, &.{ "nix", "run", pkg });437    }438    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});439    defer gpa.free(ref);440    return stream(io, machine, gpa, &.{ "nix", "run", ref });441}442443pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {444    const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});445    defer gpa.free(ref);446    return stream(io, machine, gpa, &.{ "nix", "shell", ref });447}448449pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {450    if (run_cmd) |cmd| {451        // sh -c so a multi-word command isn't treated as a single executable name.452        return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });453    }454    return stream(io, machine, gpa, &.{ "nix", "develop" });455}456457pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {458    return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });459}460461// --- Format ---462463pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {464    if (check) {465        return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });466    }467    return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });468}469470// --- Info ---471472pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {473    const r = try capture(gpa, io, machine, &.{"nixos-version"});474    defer gpa.free(r.stderr);475    if (r.exit_code != 0) {476        gpa.free(r.stdout);477        return error.ProcessFailed;478    }479    return r.stdout;480}481482pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {483    const r = try capture(gpa, io, machine, &.{ "uname", "-r" });484    defer gpa.free(r.stderr);485    if (r.exit_code != 0) {486        gpa.free(r.stdout);487        return error.ProcessFailed;488    }489    return r.stdout;490}491492pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {493    const r = try capture(gpa, io, machine, &.{"uptime"});494    defer gpa.free(r.stderr);495    if (r.exit_code != 0) {496        gpa.free(r.stdout);497        return error.ProcessFailed;498    }499    return r.stdout;500}501502// --- Boot ---503504pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {505    const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });506    defer gpa.free(r.stderr);507    defer gpa.free(r.stdout);508    if (r.exit_code != 0) return error.ProcessFailed;509    return parseBootEntries(gpa, r.stdout);510}511512fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {513    var entries: std.ArrayList(types.BootEntry) = .empty;514    var lines = std.mem.splitScalar(u8, output_str, '\n');515    while (lines.next()) |line| {516        const trimmed = std.mem.trim(u8, line, " \t\r");517        if (std.mem.startsWith(u8, trimmed, "title:")) {518            const title = std.mem.trim(u8, trimmed[6..], " \t");519            const current = std.mem.indexOf(u8, title, "(current)") != null;520            try entries.append(gpa, .{521                .title = try gpa.dupe(u8, title),522                .current = current,523            });524        }525    }526    return entries.toOwnedSlice(gpa);527}528529// --- Pkg info ---530531pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {532    return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });533}534535pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {536    return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });537}538539pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {540    const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", pkg });541    defer gpa.free(r.stderr);542    if (r.exit_code != 0) {543        gpa.free(r.stdout);544        return error.ProcessFailed;545    }546    return r.stdout;547}548549pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {550    return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });551}552553// --- Hash / Fetch ---554555pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {556    const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });557    defer gpa.free(r.stderr);558    if (r.exit_code != 0) {559        gpa.free(r.stdout);560        return error.ProcessFailed;561    }562    return r.stdout;563}564565pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {566    const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });567    defer gpa.free(r.stderr);568    if (r.exit_code != 0) {569        gpa.free(r.stdout);570        return error.ProcessFailed;571    }572    return r.stdout;573}574575// --- Pin ---576577pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {578    // Stub: full implementation would parse and edit flake.lock JSON579    // The pin/unpin flow works via nix flake update which regenerates flake.lock580}581582pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {583    if (line) |l| {584        const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});585        defer gpa.free(line_arg);586        return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });587    }588    return stream(io, &types.Machine{}, gpa, &.{ editor, path });589}590591pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {592    const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});593    defer gpa.free(a_str);594    const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});595    defer gpa.free(b_str);596    return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });597}598599// --- Doctor checks ---600601pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {602    var checks: std.ArrayList(types.DoctorCheck) = .empty;603604    // Check nix daemon605    {606        const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });607        defer gpa.free(r.stdout);608        defer gpa.free(r.stderr);609        const active = std.mem.indexOf(u8, r.stdout, "active") != null;610        try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });611    }612613    // Check config syntax614    {615        const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });616        defer gpa.free(r.stdout);617        defer gpa.free(r.stderr);618        try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });619    }620621    // Check channel622    {623        const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });624        defer gpa.free(r.stdout);625        defer gpa.free(r.stderr);626        const has_channel = r.exit_code == 0 and r.stdout.len > 0;627        try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });628    }629630    return checks.toOwnedSlice(gpa);631}632633// --- Log ---634635pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {636    const home = environ.get("HOME") orelse return error.FileNotFound;637    const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});638    defer gpa.free(path);639    _ = last;640    return std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;641}642643pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {644    const home = environ.get("HOME") orelse return;645    var path_buf: [512]u8 = undefined;646    const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;647    const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch648        (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);649    defer file.close(io);650    const size = file.length(io) catch 0;651    file.writePositionalAll(io, entry, size) catch {};652}653654// --- Nix feature setup ---655656pub const NixFeatureStatus = struct {657    nix_command: bool = false,658    flakes: bool = false,659660    pub fn allEnabled(self: NixFeatureStatus) bool {661        return self.nix_command and self.flakes;662    }663};664665fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {666    var lines = std.mem.splitScalar(u8, conf, '\n');667    while (lines.next()) |line| {668        const trimmed = std.mem.trim(u8, line, " \t");669        if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;670        if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;671        if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;672    }673}674675pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {676    var status = NixFeatureStatus{};677678    if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {679        defer gpa.free(conf);680        scanConfFeatures(conf, &status);681    }682683    if (environ.get("HOME")) |home| {684        var buf: [512]u8 = undefined;685        const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;686        if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {687            defer gpa.free(conf);688            scanConfFeatures(conf, &status);689        }690    }691692    return status;693}694695pub fn isNixOS(io: std.Io) bool {696    const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;697    file.close(io);698    return true;699}700701// Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf.702// Returns the path written (caller must free).703pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {704    const home = environ.get("HOME") orelse {705        errors.error_info.setMessage("HOME not set", .{});706        return error.ConfigNotFound;707    };708709    const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});710    defer gpa.free(dir_path);711    const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});712    errdefer gpa.free(file_path);713714    _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};715716    const line = "experimental-features = nix-command flakes\n";717    const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch718        (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {719        errors.error_info.setMessage("could not write {s}", .{file_path});720        return error.FileNotFound;721    });722    defer file.close(io);723724    const size = file.length(io) catch 0;725    file.writePositionalAll(io, line, size) catch {726        errors.error_info.setMessage("could not write {s}", .{file_path});727        return error.FileNotFound;728    };729730    return file_path;731}