// exec.zig — all process execution and SSH routing // Commands call these functions; output is streamed or captured here. const std = @import("std"); const builtin = @import("builtin"); const types = @import("types.zig"); const errors = @import("errors.zig"); const output = @import("output.zig"); // nixos-rebuild manages this profile; generation commands must target it // explicitly. Bare nix-env defaults to the per-user profile, which is empty. const SYSTEM_PROFILE = "/nix/var/nix/profiles/system"; pub const RunResult = struct { stdout: []u8, stderr: []u8, exit_code: u8, }; // Run a process and capture stdout+stderr (not streaming). pub fn capture(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, cmd: []const []const u8) !RunResult { const argv = try buildArgv(gpa, machine, cmd); defer if (!machine.local) gpa.free(argv); const result = std.process.run(gpa, io, .{ .argv = argv }) catch |e| { errors.error_info.setMessage("process failed: {s}", .{cmd[0]}); return e; }; return .{ .stdout = result.stdout, .stderr = result.stderr, .exit_code = switch (result.term) { .exited => |c| c, else => 1, }, }; } // Run a process and stream its output to the terminal (inherit stdio). pub fn stream(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8) !u8 { // The child inherits stdout and writes directly to the fd; flush any buffered // nina header first so it isn't reordered after the child's output. output.flush(); const argv = try buildArgv(gpa, machine, cmd); defer if (!machine.local) gpa.free(argv); var child = std.process.spawn(io, .{ .argv = argv, .stdin = .inherit, .stdout = .inherit, .stderr = .inherit, }) catch |e| { errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]}); return e; }; const term = child.wait(io) catch |e| { errors.error_info.setMessage("process wait failed", .{}); return e; }; return switch (term) { .exited => |c| c, else => 1, }; } // Stream a local process with inherited stdio (no SSH routing — for nix commands). pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 { output.flush(); var child = std.process.spawn(io, .{ .argv = cmd, .stdin = .inherit, .stdout = .inherit, .stderr = .inherit, }) catch |e| { errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]}); return e; }; const term = child.wait(io) catch { errors.error_info.setMessage("process wait failed", .{}); return error.ProcessFailed; }; return switch (term) { .exited => |c| c, else => 1, }; } // Run a process and capture output as a single string (no SSH routing — for local nix commands). pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 { const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed; defer gpa.free(result.stderr); switch (result.term) { .exited => |c| if (c != 0) { gpa.free(result.stdout); return error.ProcessFailed; }, else => { gpa.free(result.stdout); return error.ProcessFailed; }, } return result.stdout; } fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 { if (machine.local) return cmd; const host = machine.host orelse { errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name}); return error.SshFailed; }; var ssh: std.ArrayList([]const u8) = .empty; try ssh.append(gpa, "ssh"); try ssh.append(gpa, "-o"); try ssh.append(gpa, "BatchMode=yes"); try ssh.append(gpa, "-o"); try ssh.append(gpa, "StrictHostKeyChecking=accept-new"); if (machine.ssh_key) |key| { try ssh.append(gpa, "-i"); try ssh.append(gpa, key); } const addr = if (machine.user) |u| try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host }) else try gpa.dupe(u8, host); try ssh.append(gpa, addr); for (cmd) |arg| try ssh.append(gpa, arg); return ssh.toOwnedSlice(gpa); } // --- NixOS rebuild --- pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 { const cmd = &.{ "sudo", "nixos-rebuild", "switch" }; output.printSubstep("nixos-rebuild switch", .{}); return stream(io, machine, gpa, cmd); } pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 { return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "dry-activate" }); } pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 { return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "build" }); } // --- Generations --- // Read system-profile generations WITHOUT root. `nix-env --list-generations -p // /nix/var/nix/profiles/system` takes a profile lock and fails as a normal user // ("system.lock: Permission denied"). The generation symlinks themselves are // world-readable, so list them directly: parse `system-N-link` names, take each // link's own mtime for the date/time, and mark the one the `system` symlink // points at as current. Output matches the `nix-env --list-generations` columns // (num date time [current]) so parseGenerations is unchanged. const GEN_LIST_SCRIPT = \\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 }' ; pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo { const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT }); defer gpa.free(r.stderr); defer gpa.free(r.stdout); if (r.exit_code != 0) return error.ProcessFailed; return parseGenerations(gpa, r.stdout); } fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo { var gens: std.ArrayList(types.GenerationInfo) = .empty; var lines = std.mem.splitScalar(u8, output_str, '\n'); while (lines.next()) |line| { const trimmed = std.mem.trim(u8, line, " \t"); if (trimmed.len == 0) continue; var parts = std.mem.tokenizeAny(u8, trimmed, " \t"); const num_str = parts.next() orelse continue; const date_str = parts.next() orelse continue; const time_str = parts.next() orelse continue; const rest = parts.rest(); const current = std.mem.indexOf(u8, rest, "current") != null; const num = std.fmt.parseInt(u32, num_str, 10) catch continue; try gens.append(gpa, .{ .number = num, .date = try gpa.dupe(u8, date_str), .time = try gpa.dupe(u8, time_str), .current = current, }); } return gens.toOwnedSlice(gpa); } pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 { const gens = try getGenerations(gpa, io, machine); defer gpa.free(gens); for (gens) |g| { if (g.current) return g.number; } return 0; } pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 { // Switch the system profile to generation n, then activate it (bootloader + // services). Without switch-to-configuration the change isn't applied. 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 }); defer gpa.free(cmd); return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd }); } pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 { return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" }); } pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 { const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n}); defer gpa.free(n_str); return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str }); } pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 { return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" }); } // --- Garbage collection --- pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 { if (delete_old) { return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" }); } // Keep the `keep` most recent system generations (+N deletes all but N), // then collect now-unreferenced store paths. `--delete-older-than` wants a // duration (e.g. 14d), not a generation count. const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep }); defer gpa.free(cmd); return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd }); } // --- Channels --- pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo { const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" }); defer gpa.free(r.stderr); defer gpa.free(r.stdout); if (r.exit_code != 0) return error.ProcessFailed; return parseChannels(gpa, r.stdout); } fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo { var channels: std.ArrayList(types.ChannelInfo) = .empty; var lines = std.mem.splitScalar(u8, output_str, '\n'); while (lines.next()) |line| { const trimmed = std.mem.trim(u8, line, " \t\r"); if (trimmed.len == 0) continue; const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue; try channels.append(gpa, .{ .name = try gpa.dupe(u8, trimmed[0..space]), .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")), }); } return channels.toOwnedSlice(gpa); } pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 { return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" }); } pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 { return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name }); } pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 { return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name }); } // --- Services --- pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ServiceInfo { const r = try capture(gpa, io, machine, &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" }); defer gpa.free(r.stderr); defer gpa.free(r.stdout); if (r.exit_code != 0) return error.ProcessFailed; return parseServices(gpa, r.stdout); } fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo { var svcs: std.ArrayList(types.ServiceInfo) = .empty; var lines = std.mem.splitScalar(u8, output_str, '\n'); while (lines.next()) |line| { const trimmed = std.mem.trim(u8, line, " \t\r"); if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; // skip UTF-8 bullet lines var parts = std.mem.tokenizeAny(u8, trimmed, " \t"); const name = parts.next() orelse continue; _ = parts.next(); // load const active_str = parts.next() orelse continue; const sub_str = parts.next() orelse "unknown"; const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active")) (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active) else if (std.mem.eql(u8, active_str, "failed")) .failed else .inactive; try svcs.append(gpa, .{ .name = try gpa.dupe(u8, name), .state = state, .uptime = null, }); } return svcs.toOwnedSlice(gpa); } pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8) !u8 { // --no-pager: `systemctl status` pipes to a pager on a tty and would block. return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name }); } pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool) !u8 { const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last}); defer gpa.free(n_str); if (follow) { return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" }); } return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" }); } // --- Profile --- pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 { const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr}); defer gpa.free(pkg_ref); return stream(io, machine, gpa, &.{ "nix", "profile", "install", pkg_ref }); } pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 { // `nix profile remove` matches by profile element name (e.g. "ripgrep"), not // by flake ref — passing nixpkgs#ripgrep matches nothing. return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr }); } pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 { const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" }); defer gpa.free(r.stderr); if (r.exit_code != 0) return error.ProcessFailed; return r.stdout; } pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 { return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" }); } // --- Store --- pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 { return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" }); } pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 { return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" }); } pub const SystemStatus = struct { size: []u8, age: []u8 }; // One read-only pass for `nina status`: the current system's closure size (a // single `path-info -S` of /run/current-system — fast, unlike -S over the whole // store) and seconds since the system profile was last switched (its symlink // mtime). Both are world-readable; no root needed. const STATUS_SCRIPT = \\sz=$(nix path-info -S /run/current-system 2>/dev/null | awk '{print $NF}'); mt=$(stat -c %Y /nix/var/nix/profiles/system 2>/dev/null); now=$(date +%s); echo "${sz:-0} $(( ${now:-0} - ${mt:-0} ))" ; pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus { const unknown = SystemStatus{ .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" }, .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" }, }; const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown; defer gpa.free(r.stdout); defer gpa.free(r.stderr); if (r.exit_code != 0) return unknown; var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r"); const sz_str = it.next() orelse return unknown; const age_str = it.next() orelse return unknown; const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0; const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0; gpa.free(unknown.size); gpa.free(unknown.age); return .{ .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""), .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""), }; } fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 { if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs}); if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60}); if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600}); return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400}); } pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 { return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" }); } pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo { // `nix path-info -S --all` computes the CLOSURE size of every path — O(paths^2) // graph work that takes minutes on a real store (59k+ paths) and hangs the // command. We don't need closures: `--all --json` (no -S) carries each path's // own narSize, so one fast pass gives the path count and the summed store size. // `du -sh /nix/store` is just as slow on a big store, so it's gone too. // timeout-wrapped so a pathological store degrades to "?" instead of hanging. const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" }); defer gpa.free(pi.stdout); defer gpa.free(pi.stderr); const scan = scanStoreJson(pi.stdout); const total_owned = try humanSize(gpa, scan.total_bytes); return .{ .total_size = total_owned, .live_paths = scan.count, .reclaimable_paths = 0, }; } const StoreScan = struct { count: u64, total_bytes: u64 }; // One linear pass over `nix path-info --json`: each path object has exactly one // "narSize": field, so counting them gives the true path count and summing the // values gives the total store size — no per-path closure walk. fn scanStoreJson(json_str: []const u8) StoreScan { const needle = "\"narSize\":"; var count: u64 = 0; var total: u64 = 0; var i: usize = 0; while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| { var j = pos + needle.len; while (j < json_str.len and json_str[j] == ' ') : (j += 1) {} var val: u64 = 0; var any = false; while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) { val = val * 10 + (json_str[j] - '0'); any = true; } if (any) { count += 1; total += val; } i = j; } return .{ .count = count, .total_bytes = total }; } fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 { const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" }; var val: f64 = @floatFromInt(bytes); var unit: usize = 0; while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0; if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] }); return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] }); } pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 { // nixpkgs#, not .#: the package lives in nixpkgs (resolved via the // flake registry), not a flake in the current directory. const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr}); defer gpa.free(expr); const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr }); defer gpa.free(r.stderr); if (r.exit_code != 0) { gpa.free(r.stdout); return error.ProcessFailed; } return r.stdout; } // --- Flake --- pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 { if (input) |inp| { return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp }); } return stream(io, machine, gpa, &.{ "nix", "flake", "update" }); } pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 { return stream(io, machine, gpa, &.{ "nix", "flake", "check" }); } pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 { return stream(io, machine, gpa, &.{ "nix", "flake", "init" }); } pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 { return stream(io, machine, gpa, &.{ "nix", "flake", "lock" }); } pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 { return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url }); } pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 { const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" }); defer gpa.free(r.stderr); if (r.exit_code != 0) { gpa.free(r.stdout); return error.ProcessFailed; } return r.stdout; } // --- Build / Run / Develop --- pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 { if (attr) |a| { const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a}); defer gpa.free(ref); return stream(io, machine, gpa, &.{ "nix", "build", ref }); } return stream(io, machine, gpa, &.{ "nix", "build" }); } pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 { // nix run always gets --no-write-lock-file for remote URLs const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:"); if (is_url) { return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" }); } // Already a flake ref (contains '#') → use as-is; bare name → default to nixpkgs#. if (std.mem.indexOfScalar(u8, pkg, '#') != null) { return stream(io, machine, gpa, &.{ "nix", "run", pkg }); } const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg}); defer gpa.free(ref); return stream(io, machine, gpa, &.{ "nix", "run", ref }); } pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 { const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg}); defer gpa.free(ref); return stream(io, machine, gpa, &.{ "nix", "shell", ref }); } pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 { if (run_cmd) |cmd| { // sh -c so a multi-word command isn't treated as a single executable name. return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd }); } return stream(io, machine, gpa, &.{ "nix", "develop" }); } pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 { return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import {}" }); } // --- Format --- pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 { if (check) { return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path }); } return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path }); } // --- Info --- pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 { const r = try capture(gpa, io, machine, &.{"nixos-version"}); defer gpa.free(r.stderr); if (r.exit_code != 0) { gpa.free(r.stdout); return error.ProcessFailed; } return r.stdout; } pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 { const r = try capture(gpa, io, machine, &.{ "uname", "-r" }); defer gpa.free(r.stderr); if (r.exit_code != 0) { gpa.free(r.stdout); return error.ProcessFailed; } return r.stdout; } pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 { const r = try capture(gpa, io, machine, &.{"uptime"}); defer gpa.free(r.stderr); if (r.exit_code != 0) { gpa.free(r.stdout); return error.ProcessFailed; } return r.stdout; } // --- Boot --- pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry { const r = try capture(gpa, io, machine, &.{ "bootctl", "list" }); defer gpa.free(r.stderr); defer gpa.free(r.stdout); if (r.exit_code != 0) return error.ProcessFailed; return parseBootEntries(gpa, r.stdout); } fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry { var entries: std.ArrayList(types.BootEntry) = .empty; var lines = std.mem.splitScalar(u8, output_str, '\n'); while (lines.next()) |line| { const trimmed = std.mem.trim(u8, line, " \t\r"); if (std.mem.startsWith(u8, trimmed, "title:")) { const title = std.mem.trim(u8, trimmed[6..], " \t"); const current = std.mem.indexOf(u8, title, "(current)") != null; try entries.append(gpa, .{ .title = try gpa.dupe(u8, title), .current = current, }); } } return entries.toOwnedSlice(gpa); } // --- Pkg info --- pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 { return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg }); } pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 { return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg }); } pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 { // A bare name ("ripgrep") isn't a valid installable; resolve via nixpkgs# like // `pkg path` does. -S -h gives closure size, human-readable. Output is // " "; return just the size. const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg}); defer gpa.free(ref); const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref }); defer gpa.free(r.stderr); defer gpa.free(r.stdout); if (r.exit_code != 0) return error.ProcessFailed; const line = std.mem.trim(u8, r.stdout, " \t\n\r"); var it = std.mem.tokenizeAny(u8, line, " \t"); _ = it.next(); // store path const size = std.mem.trim(u8, it.rest(), " \t"); if (size.len == 0) return error.ProcessFailed; return gpa.dupe(u8, size); } pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 { return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg }); } // --- Hash / Fetch --- pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 { const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path }); defer gpa.free(r.stderr); if (r.exit_code != 0) { gpa.free(r.stdout); return error.ProcessFailed; } return r.stdout; } pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 { const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url }); defer gpa.free(r.stderr); if (r.exit_code != 0) { gpa.free(r.stdout); return error.ProcessFailed; } return r.stdout; } // --- Pin --- pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void { // Stub: full implementation would parse and edit flake.lock JSON // The pin/unpin flow works via nix flake update which regenerates flake.lock } pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 { if (line) |l| { const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l}); defer gpa.free(line_arg); return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg }); } return stream(io, &types.Machine{}, gpa, &.{ editor, path }); } pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 { const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a}); defer gpa.free(a_str); const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b}); defer gpa.free(b_str); return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str }); } // --- Doctor checks --- pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck { var checks: std.ArrayList(types.DoctorCheck) = .empty; // Check nix daemon { const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" }); defer gpa.free(r.stdout); defer gpa.free(r.stderr); const active = std.mem.indexOf(u8, r.stdout, "active") != null; try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail }); } // Check config syntax { const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" }); defer gpa.free(r.stdout); defer gpa.free(r.stderr); try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail }); } // Check channel { const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" }); defer gpa.free(r.stdout); defer gpa.free(r.stderr); const has_channel = r.exit_code == 0 and r.stdout.len > 0; try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn }); } return checks.toOwnedSlice(gpa); } // --- Log --- pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 { const home = environ.get("HOME") orelse return error.FileNotFound; const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home}); defer gpa.free(path); _ = last; return std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound; } pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void { const home = environ.get("HOME") orelse return; var path_buf: [512]u8 = undefined; const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return; const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return); defer file.close(io); const size = file.length(io) catch 0; file.writePositionalAll(io, entry, size) catch {}; } // --- Update helpers --- // Fetch a URL with curl and return the response body. Caller must free. // error.NetworkError = DNS/connect failure; error.HttpError = non-2xx response. pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 { const argv = [_][]const u8{ "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url, }; const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError; defer gpa.free(result.stderr); const marker = "\nHTTP_STATUS:"; const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse { gpa.free(result.stdout); return error.NetworkError; }; const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n"); const status = std.fmt.parseInt(u16, status_str, 10) catch { gpa.free(result.stdout); return error.NetworkError; }; if (status == 0) { gpa.free(result.stdout); return error.NetworkError; } if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; } const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| { gpa.free(result.stdout); return e; }; gpa.free(result.stdout); return body; } // Download a URL to a temp file. Returns the temp path (caller must gpa.free). // The file is written to /tmp/nina-update- and left for the caller to use. pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 { const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin"); errdefer gpa.free(tmp_path); var child = std.process.spawn(io, .{ .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url }, .stdin = .close, .stdout = .close, .stderr = .inherit, }) catch return error.NetworkError; const term = child.wait(io) catch return error.NetworkError; switch (term) { .exited => |c| if (c != 0) return error.NetworkError, else => return error.NetworkError, } return tmp_path; } // Get the current executable path into buf. Returns slice of buf. pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 { const len = try std.process.executablePath(io, buf); return buf[0..len]; } // Verify blake3 of tmp_path against expected_hex (raw hex, no prefix), then // atomically install the binary to install_path. Errors: ChecksumMismatch, // AccessDenied (with error_info set), or underlying I/O errors. pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void { const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch { errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path}); return error.FileNotFound; }; defer gpa.free(bytes); var hasher = std.crypto.hash.Blake3.init(.{}); hasher.update(bytes); var raw: [32]u8 = undefined; hasher.final(&raw); const hex = std.fmt.bytesToHex(raw, .lower); if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch; var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined; const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch return error.NameTooLong; { const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch { errors.error_info.setMessage("cannot write to {s}", .{install_path}); errors.error_info.setSuggestion("try: sudo nina update", .{}); return error.AccessDenied; }; defer f.close(io); f.writePositionalAll(io, bytes, 0) catch { errors.error_info.setMessage("cannot write to {s}", .{install_path}); return error.AccessDenied; }; try f.setPermissions(io, .fromMode(0o755)); } errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {}; if (comptime builtin.os.tag == .macos) { _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {}; } std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) { error.AccessDenied => { errors.error_info.setMessage("cannot replace {s}", .{install_path}); errors.error_info.setSuggestion("try: sudo nina update", .{}); return error.AccessDenied; }, else => return e, }; } // --- Nix feature setup --- pub const NixFeatureStatus = struct { nix_command: bool = false, flakes: bool = false, pub fn allEnabled(self: NixFeatureStatus) bool { return self.nix_command and self.flakes; } }; fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void { var lines = std.mem.splitScalar(u8, conf, '\n'); while (lines.next()) |line| { const trimmed = std.mem.trim(u8, line, " \t"); if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue; if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true; if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true; } } pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus { var status = NixFeatureStatus{}; if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| { defer gpa.free(conf); scanConfFeatures(conf, &status); } if (environ.get("HOME")) |home| { var buf: [512]u8 = undefined; const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status; if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| { defer gpa.free(conf); scanConfFeatures(conf, &status); } } return status; } pub fn isNixOS(io: std.Io) bool { const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false; file.close(io); return true; } // Appends `experimental-features = nix-command flakes` to ~/.config/nix/nix.conf. // Returns the path written (caller must free). pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 { const home = environ.get("HOME") orelse { errors.error_info.setMessage("HOME not set", .{}); return error.ConfigNotFound; }; const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home}); defer gpa.free(dir_path); const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home}); errdefer gpa.free(file_path); _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {}; const line = "experimental-features = nix-command flakes\n"; const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch { errors.error_info.setMessage("could not write {s}", .{file_path}); return error.FileNotFound; }); defer file.close(io); const size = file.length(io) catch 0; file.writePositionalAll(io, line, size) catch { errors.error_info.setMessage("could not write {s}", .{file_path}); return error.FileNotFound; }; return file_path; }