123const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const output = @import("output.zig");891011const SYSTEM_PROFILE = "/nix/var/nix/profiles/system";1213pub const RunResult = struct {14 stdout: []u8,15 stderr: []u8,16 exit_code: u8,17};181920pub 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}383940pub fn stream(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8) !u8 {41 42 43 output.flush();44 const argv = try buildArgv(gpa, machine, cmd);45 defer if (!machine.local) gpa.free(argv);4647 var child = std.process.spawn(io, .{48 .argv = argv,49 .stdin = .inherit,50 .stdout = .inherit,51 .stderr = .inherit,52 }) catch |e| {53 errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});54 return e;55 };5657 const term = child.wait(io) catch |e| {58 errors.error_info.setMessage("process wait failed", .{});59 return e;60 };6162 return switch (term) {63 .exited => |c| c,64 else => 1,65 };66}676869pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 {70 output.flush();71 var child = std.process.spawn(io, .{72 .argv = cmd,73 .stdin = .inherit,74 .stdout = .inherit,75 .stderr = .inherit,76 }) catch |e| {77 errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});78 return e;79 };80 const term = child.wait(io) catch {81 errors.error_info.setMessage("process wait failed", .{});82 return error.ProcessFailed;83 };84 return switch (term) {85 .exited => |c| c,86 else => 1,87 };88}899091pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {92 const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;93 defer gpa.free(result.stderr);94 switch (result.term) {95 .exited => |c| if (c != 0) {96 gpa.free(result.stdout);97 return error.ProcessFailed;98 },99 else => {100 gpa.free(result.stdout);101 return error.ProcessFailed;102 },103 }104 return result.stdout;105}106107fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {108 if (machine.local) return cmd;109110 const host = machine.host orelse {111 errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});112 return error.SshFailed;113 };114115 var ssh: std.ArrayList([]const u8) = .empty;116 try ssh.append(gpa, "ssh");117 try ssh.append(gpa, "-o");118 try ssh.append(gpa, "BatchMode=yes");119 try ssh.append(gpa, "-o");120 try ssh.append(gpa, "StrictHostKeyChecking=accept-new");121 if (machine.ssh_key) |key| {122 try ssh.append(gpa, "-i");123 try ssh.append(gpa, key);124 }125 const addr = if (machine.user) |u|126 try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })127 else128 try gpa.dupe(u8, host);129 try ssh.append(gpa, addr);130 for (cmd) |arg| try ssh.append(gpa, arg);131 return ssh.toOwnedSlice(gpa);132}133134135136pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {137 const cmd = &.{ "sudo", "nixos-rebuild", "switch" };138 output.printSubstep("nixos-rebuild switch", .{});139 return stream(io, machine, gpa, cmd);140}141142pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {143 return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "dry-activate" });144}145146pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {147 return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "build" });148}149150151152153154155156157158159const GEN_LIST_SCRIPT =160 \\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 }'161;162163pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {164 const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });165 defer gpa.free(r.stderr);166 defer gpa.free(r.stdout);167 if (r.exit_code != 0) return error.ProcessFailed;168 return parseGenerations(gpa, r.stdout);169}170171fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {172 var gens: std.ArrayList(types.GenerationInfo) = .empty;173 var lines = std.mem.splitScalar(u8, output_str, '\n');174 while (lines.next()) |line| {175 const trimmed = std.mem.trim(u8, line, " \t");176 if (trimmed.len == 0) continue;177 var parts = std.mem.tokenizeAny(u8, trimmed, " \t");178 const num_str = parts.next() orelse continue;179 const date_str = parts.next() orelse continue;180 const time_str = parts.next() orelse continue;181 const rest = parts.rest();182 const current = std.mem.indexOf(u8, rest, "current") != null;183 const num = std.fmt.parseInt(u32, num_str, 10) catch continue;184 try gens.append(gpa, .{185 .number = num,186 .date = try gpa.dupe(u8, date_str),187 .time = try gpa.dupe(u8, time_str),188 .current = current,189 });190 }191 return gens.toOwnedSlice(gpa);192}193194pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {195 const gens = try getGenerations(gpa, io, machine);196 defer gpa.free(gens);197 for (gens) |g| {198 if (g.current) return g.number;199 }200 return 0;201}202203pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {204 205 206 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 });207 defer gpa.free(cmd);208 return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });209}210211pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {212 return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });213}214215pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {216 const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});217 defer gpa.free(n_str);218 return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });219}220221pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {222 return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });223}224225226227pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {228 if (delete_old) {229 return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });230 }231 232 233 234 const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });235 defer gpa.free(cmd);236 return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });237}238239240241pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {242 const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });243 defer gpa.free(r.stderr);244 defer gpa.free(r.stdout);245 if (r.exit_code != 0) return error.ProcessFailed;246 return parseChannels(gpa, r.stdout);247}248249fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {250 var channels: std.ArrayList(types.ChannelInfo) = .empty;251 var lines = std.mem.splitScalar(u8, output_str, '\n');252 while (lines.next()) |line| {253 const trimmed = std.mem.trim(u8, line, " \t\r");254 if (trimmed.len == 0) continue;255 const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;256 try channels.append(gpa, .{257 .name = try gpa.dupe(u8, trimmed[0..space]),258 .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),259 });260 }261 return channels.toOwnedSlice(gpa);262}263264pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {265 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });266}267268pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {269 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });270}271272pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {273 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });274}275276277278pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ServiceInfo {279 const r = try capture(gpa, io, machine, &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" });280 defer gpa.free(r.stderr);281 defer gpa.free(r.stdout);282 if (r.exit_code != 0) return error.ProcessFailed;283 return parseServices(gpa, r.stdout);284}285286fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {287 var svcs: std.ArrayList(types.ServiceInfo) = .empty;288 var lines = std.mem.splitScalar(u8, output_str, '\n');289 while (lines.next()) |line| {290 const trimmed = std.mem.trim(u8, line, " \t\r");291 if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; 292 var parts = std.mem.tokenizeAny(u8, trimmed, " \t");293 const name = parts.next() orelse continue;294 _ = parts.next(); 295 const active_str = parts.next() orelse continue;296 const sub_str = parts.next() orelse "unknown";297298 const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))299 (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)300 else if (std.mem.eql(u8, active_str, "failed"))301 .failed302 else303 .inactive;304305 try svcs.append(gpa, .{306 .name = try gpa.dupe(u8, name),307 .state = state,308 .uptime = null,309 });310 }311 return svcs.toOwnedSlice(gpa);312}313314pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8) !u8 {315 316 return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });317}318319pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool) !u8 {320 const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});321 defer gpa.free(n_str);322 if (follow) {323 return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });324 }325 return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });326}327328329330pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {331 const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});332 defer gpa.free(pkg_ref);333 return stream(io, machine, gpa, &.{ "nix", "profile", "install", pkg_ref });334}335336pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {337 338 339 return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });340}341342pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {343 const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });344 defer gpa.free(r.stderr);345 if (r.exit_code != 0) return error.ProcessFailed;346 return r.stdout;347}348349pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {350 return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });351}352353354355pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {356 return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });357}358359pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {360 return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });361}362363pub const SystemStatus = struct { size: []u8, age: []u8 };364365366367368369const STATUS_SCRIPT =370 \\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} ))"371;372373pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {374 const unknown = SystemStatus{375 .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },376 .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },377 };378 const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;379 defer gpa.free(r.stdout);380 defer gpa.free(r.stderr);381 if (r.exit_code != 0) return unknown;382383 var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");384 const sz_str = it.next() orelse return unknown;385 const age_str = it.next() orelse return unknown;386 const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;387 const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;388389 gpa.free(unknown.size);390 gpa.free(unknown.age);391 return .{392 .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),393 .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),394 };395}396397398399400pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {401 const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch402 return gpa.dupe(u8, "unknown");403 defer gpa.free(r.stderr);404 const state = std.mem.trim(u8, r.stdout, " \t\n\r");405 const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");406 gpa.free(r.stdout);407 return owned;408}409410fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {411 if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});412 if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});413 if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});414 return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});415}416417pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {418 return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });419}420421pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {422 423 424 425 426 427 428 const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });429 defer gpa.free(pi.stdout);430 defer gpa.free(pi.stderr);431432 const scan = scanStoreJson(pi.stdout);433 const total_owned = try humanSize(gpa, scan.total_bytes);434435 return .{436 .total_size = total_owned,437 .live_paths = scan.count,438 .reclaimable_paths = 0,439 };440}441442const StoreScan = struct { count: u64, total_bytes: u64 };443444445446447fn scanStoreJson(json_str: []const u8) StoreScan {448 const needle = "\"narSize\":";449 var count: u64 = 0;450 var total: u64 = 0;451 var i: usize = 0;452 while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {453 var j = pos + needle.len;454 while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}455 var val: u64 = 0;456 var any = false;457 while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {458 val = val * 10 + (json_str[j] - '0');459 any = true;460 }461 if (any) {462 count += 1;463 total += val;464 }465 i = j;466 }467 return .{ .count = count, .total_bytes = total };468}469470fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {471 const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };472 var val: f64 = @floatFromInt(bytes);473 var unit: usize = 0;474 while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;475 if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });476 return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });477}478479pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {480 481 482 const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});483 defer gpa.free(expr);484 const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });485 defer gpa.free(r.stderr);486 if (r.exit_code != 0) {487 gpa.free(r.stdout);488 return error.ProcessFailed;489 }490 return r.stdout;491}492493494495pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {496 if (input) |inp| {497 return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });498 }499 return stream(io, machine, gpa, &.{ "nix", "flake", "update" });500}501502pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {503 return stream(io, machine, gpa, &.{ "nix", "flake", "check" });504}505506pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {507 return stream(io, machine, gpa, &.{ "nix", "flake", "init" });508}509510pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {511 return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });512}513514pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {515 return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });516}517518pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {519 const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });520 defer gpa.free(r.stderr);521 if (r.exit_code != 0) {522 gpa.free(r.stdout);523 return error.ProcessFailed;524 }525 return r.stdout;526}527528529530pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {531 if (attr) |a| {532 const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});533 defer gpa.free(ref);534 return stream(io, machine, gpa, &.{ "nix", "build", ref });535 }536 return stream(io, machine, gpa, &.{ "nix", "build" });537}538539pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {540 541 const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");542 if (is_url) {543 return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });544 }545 546 if (std.mem.indexOfScalar(u8, pkg, '#') != null) {547 return stream(io, machine, gpa, &.{ "nix", "run", pkg });548 }549 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});550 defer gpa.free(ref);551 return stream(io, machine, gpa, &.{ "nix", "run", ref });552}553554pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {555 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});556 defer gpa.free(ref);557 return stream(io, machine, gpa, &.{ "nix", "shell", ref });558}559560pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {561 if (run_cmd) |cmd| {562 563 return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });564 }565 return stream(io, machine, gpa, &.{ "nix", "develop" });566}567568pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {569 return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });570}571572573574pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {575 if (check) {576 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });577 }578 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });579}580581582583pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {584 const r = try capture(gpa, io, machine, &.{"nixos-version"});585 defer gpa.free(r.stderr);586 if (r.exit_code != 0) {587 gpa.free(r.stdout);588 return error.ProcessFailed;589 }590 return r.stdout;591}592593pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {594 const r = try capture(gpa, io, machine, &.{ "uname", "-r" });595 defer gpa.free(r.stderr);596 if (r.exit_code != 0) {597 gpa.free(r.stdout);598 return error.ProcessFailed;599 }600 return r.stdout;601}602603pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {604 const r = try capture(gpa, io, machine, &.{"uptime"});605 defer gpa.free(r.stderr);606 if (r.exit_code != 0) {607 gpa.free(r.stdout);608 return error.ProcessFailed;609 }610 return r.stdout;611}612613614615pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {616 const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });617 defer gpa.free(r.stderr);618 defer gpa.free(r.stdout);619 if (r.exit_code != 0) return error.ProcessFailed;620 return parseBootEntries(gpa, r.stdout);621}622623fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {624 var entries: std.ArrayList(types.BootEntry) = .empty;625 var lines = std.mem.splitScalar(u8, output_str, '\n');626 while (lines.next()) |line| {627 const trimmed = std.mem.trim(u8, line, " \t\r");628 if (std.mem.startsWith(u8, trimmed, "title:")) {629 const title = std.mem.trim(u8, trimmed[6..], " \t");630 const current = std.mem.indexOf(u8, title, "(current)") != null;631 try entries.append(gpa, .{632 .title = try gpa.dupe(u8, title),633 .current = current,634 });635 }636 }637 return entries.toOwnedSlice(gpa);638}639640641642pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {643 return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });644}645646pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {647 return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });648}649650pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {651 652 653 654 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});655 defer gpa.free(ref);656 const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref });657 defer gpa.free(r.stderr);658 defer gpa.free(r.stdout);659 if (r.exit_code != 0) return error.ProcessFailed;660661 const line = std.mem.trim(u8, r.stdout, " \t\n\r");662 var it = std.mem.tokenizeAny(u8, line, " \t");663 _ = it.next(); 664 const size = std.mem.trim(u8, it.rest(), " \t");665 if (size.len == 0) return error.ProcessFailed;666 return gpa.dupe(u8, size);667}668669pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {670 return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });671}672673674675pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {676 const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });677 defer gpa.free(r.stderr);678 if (r.exit_code != 0) {679 gpa.free(r.stdout);680 return error.ProcessFailed;681 }682 return r.stdout;683}684685pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {686 const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });687 defer gpa.free(r.stderr);688 if (r.exit_code != 0) {689 gpa.free(r.stdout);690 return error.ProcessFailed;691 }692 return r.stdout;693}694695696697pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {698 699 700}701702pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {703 if (line) |l| {704 const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});705 defer gpa.free(line_arg);706 return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });707 }708 return stream(io, &types.Machine{}, gpa, &.{ editor, path });709}710711pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {712 const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});713 defer gpa.free(a_str);714 const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});715 defer gpa.free(b_str);716 717 718 719 if (!output.colorEnabled()) {720 return stream(io, machine, gpa, &.{ "env", "NO_COLOR=1", "nix", "store", "diff-closures", a_str, b_str });721 }722 return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });723}724725726727pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {728 var checks: std.ArrayList(types.DoctorCheck) = .empty;729730 731 {732 const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });733 defer gpa.free(r.stdout);734 defer gpa.free(r.stderr);735 const active = std.mem.indexOf(u8, r.stdout, "active") != null;736 try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });737 }738739 740 {741 const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });742 defer gpa.free(r.stdout);743 defer gpa.free(r.stderr);744 try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });745 }746747 748 {749 const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });750 defer gpa.free(r.stdout);751 defer gpa.free(r.stderr);752 const has_channel = r.exit_code == 0 and r.stdout.len > 0;753 try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });754 }755756 return checks.toOwnedSlice(gpa);757}758759760761pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {762 const home = environ.get("HOME") orelse return error.FileNotFound;763 const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});764 defer gpa.free(path);765 _ = last;766 return std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;767}768769770771772773pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {774 const home = environ.get("HOME") orelse return;775 var buf: [512]u8 = undefined;776 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;777 const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;778 file.close(io);779}780781pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {782 const home = environ.get("HOME") orelse return false;783 var buf: [512]u8 = undefined;784 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;785 if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {786 f.close(io);787 std.Io.Dir.deleteFile(.cwd(), io, path) catch {};788 return true;789 } else |_| {790 return false;791 }792}793794pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {795 const home = environ.get("HOME") orelse return;796 var path_buf: [512]u8 = undefined;797 const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;798 const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch799 (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);800 defer file.close(io);801 const size = file.length(io) catch 0;802 file.writePositionalAll(io, entry, size) catch {};803}804805806807808809pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {810 const argv = [_][]const u8{811 "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,812 };813 const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;814 defer gpa.free(result.stderr);815816 const marker = "\nHTTP_STATUS:";817 const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {818 gpa.free(result.stdout);819 return error.NetworkError;820 };821 const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");822 const status = std.fmt.parseInt(u16, status_str, 10) catch {823 gpa.free(result.stdout);824 return error.NetworkError;825 };826 if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }827 if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }828 const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {829 gpa.free(result.stdout);830 return e;831 };832 gpa.free(result.stdout);833 return body;834}835836837838pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {839 const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");840 errdefer gpa.free(tmp_path);841842 var child = std.process.spawn(io, .{843 .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },844 .stdin = .close,845 .stdout = .close,846 .stderr = .inherit,847 }) catch return error.NetworkError;848 const term = child.wait(io) catch return error.NetworkError;849 switch (term) {850 .exited => |c| if (c != 0) return error.NetworkError,851 else => return error.NetworkError,852 }853 return tmp_path;854}855856857pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {858 const len = try std.process.executablePath(io, buf);859 return buf[0..len];860}861862863864865pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {866 const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {867 errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});868 return error.FileNotFound;869 };870 defer gpa.free(bytes);871872 var hasher = std.crypto.hash.Blake3.init(.{});873 hasher.update(bytes);874 var raw: [32]u8 = undefined;875 hasher.final(&raw);876 const hex = std.fmt.bytesToHex(raw, .lower);877 if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;878879 var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;880 const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch881 return error.NameTooLong;882883 {884 const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {885 errors.error_info.setMessage("cannot write to {s}", .{install_path});886 errors.error_info.setSuggestion("try: sudo nina update", .{});887 return error.AccessDenied;888 };889 defer f.close(io);890 f.writePositionalAll(io, bytes, 0) catch {891 errors.error_info.setMessage("cannot write to {s}", .{install_path});892 return error.AccessDenied;893 };894 try f.setPermissions(io, .fromMode(0o755));895 }896 errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};897898 if (comptime builtin.os.tag == .macos) {899 _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};900 }901902 std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {903 error.AccessDenied => {904 errors.error_info.setMessage("cannot replace {s}", .{install_path});905 errors.error_info.setSuggestion("try: sudo nina update", .{});906 return error.AccessDenied;907 },908 else => return e,909 };910}911912913914pub const NixFeatureStatus = struct {915 nix_command: bool = false,916 flakes: bool = false,917918 pub fn allEnabled(self: NixFeatureStatus) bool {919 return self.nix_command and self.flakes;920 }921};922923fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {924 var lines = std.mem.splitScalar(u8, conf, '\n');925 while (lines.next()) |line| {926 const trimmed = std.mem.trim(u8, line, " \t");927 if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;928 if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;929 if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;930 }931}932933pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {934 var status = NixFeatureStatus{};935936 if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {937 defer gpa.free(conf);938 scanConfFeatures(conf, &status);939 }940941 if (environ.get("HOME")) |home| {942 var buf: [512]u8 = undefined;943 const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;944 if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {945 defer gpa.free(conf);946 scanConfFeatures(conf, &status);947 }948 }949950 return status;951}952953pub fn isNixOS(io: std.Io) bool {954 const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;955 file.close(io);956 return true;957}958959960961pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {962 const home = environ.get("HOME") orelse {963 errors.error_info.setMessage("HOME not set", .{});964 return error.ConfigNotFound;965 };966967 const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});968 defer gpa.free(dir_path);969 const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});970 errdefer gpa.free(file_path);971972 _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};973974 const line = "experimental-features = nix-command flakes\n";975 const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch976 (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {977 errors.error_info.setMessage("could not write {s}", .{file_path});978 return error.FileNotFound;979 });980 defer file.close(io);981982 const size = file.length(io) catch 0;983 file.writePositionalAll(io, line, size) catch {984 errors.error_info.setMessage("could not write {s}", .{file_path});985 return error.FileNotFound;986 };987988 return file_path;989}