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}396397fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {398 if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});399 if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});400 if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});401 return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});402}403404pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {405 return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });406}407408pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {409 410 411 412 413 414 415 const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });416 defer gpa.free(pi.stdout);417 defer gpa.free(pi.stderr);418419 const scan = scanStoreJson(pi.stdout);420 const total_owned = try humanSize(gpa, scan.total_bytes);421422 return .{423 .total_size = total_owned,424 .live_paths = scan.count,425 .reclaimable_paths = 0,426 };427}428429const StoreScan = struct { count: u64, total_bytes: u64 };430431432433434fn scanStoreJson(json_str: []const u8) StoreScan {435 const needle = "\"narSize\":";436 var count: u64 = 0;437 var total: u64 = 0;438 var i: usize = 0;439 while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {440 var j = pos + needle.len;441 while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}442 var val: u64 = 0;443 var any = false;444 while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {445 val = val * 10 + (json_str[j] - '0');446 any = true;447 }448 if (any) {449 count += 1;450 total += val;451 }452 i = j;453 }454 return .{ .count = count, .total_bytes = total };455}456457fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {458 const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };459 var val: f64 = @floatFromInt(bytes);460 var unit: usize = 0;461 while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;462 if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });463 return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });464}465466pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {467 468 469 const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});470 defer gpa.free(expr);471 const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });472 defer gpa.free(r.stderr);473 if (r.exit_code != 0) {474 gpa.free(r.stdout);475 return error.ProcessFailed;476 }477 return r.stdout;478}479480481482pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {483 if (input) |inp| {484 return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });485 }486 return stream(io, machine, gpa, &.{ "nix", "flake", "update" });487}488489pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {490 return stream(io, machine, gpa, &.{ "nix", "flake", "check" });491}492493pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {494 return stream(io, machine, gpa, &.{ "nix", "flake", "init" });495}496497pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {498 return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });499}500501pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {502 return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });503}504505pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {506 const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });507 defer gpa.free(r.stderr);508 if (r.exit_code != 0) {509 gpa.free(r.stdout);510 return error.ProcessFailed;511 }512 return r.stdout;513}514515516517pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {518 if (attr) |a| {519 const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});520 defer gpa.free(ref);521 return stream(io, machine, gpa, &.{ "nix", "build", ref });522 }523 return stream(io, machine, gpa, &.{ "nix", "build" });524}525526pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {527 528 const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");529 if (is_url) {530 return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });531 }532 533 if (std.mem.indexOfScalar(u8, pkg, '#') != null) {534 return stream(io, machine, gpa, &.{ "nix", "run", pkg });535 }536 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});537 defer gpa.free(ref);538 return stream(io, machine, gpa, &.{ "nix", "run", ref });539}540541pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {542 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});543 defer gpa.free(ref);544 return stream(io, machine, gpa, &.{ "nix", "shell", ref });545}546547pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {548 if (run_cmd) |cmd| {549 550 return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });551 }552 return stream(io, machine, gpa, &.{ "nix", "develop" });553}554555pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {556 return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });557}558559560561pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {562 if (check) {563 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });564 }565 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });566}567568569570pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {571 const r = try capture(gpa, io, machine, &.{"nixos-version"});572 defer gpa.free(r.stderr);573 if (r.exit_code != 0) {574 gpa.free(r.stdout);575 return error.ProcessFailed;576 }577 return r.stdout;578}579580pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {581 const r = try capture(gpa, io, machine, &.{ "uname", "-r" });582 defer gpa.free(r.stderr);583 if (r.exit_code != 0) {584 gpa.free(r.stdout);585 return error.ProcessFailed;586 }587 return r.stdout;588}589590pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {591 const r = try capture(gpa, io, machine, &.{"uptime"});592 defer gpa.free(r.stderr);593 if (r.exit_code != 0) {594 gpa.free(r.stdout);595 return error.ProcessFailed;596 }597 return r.stdout;598}599600601602pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {603 const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });604 defer gpa.free(r.stderr);605 defer gpa.free(r.stdout);606 if (r.exit_code != 0) return error.ProcessFailed;607 return parseBootEntries(gpa, r.stdout);608}609610fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {611 var entries: std.ArrayList(types.BootEntry) = .empty;612 var lines = std.mem.splitScalar(u8, output_str, '\n');613 while (lines.next()) |line| {614 const trimmed = std.mem.trim(u8, line, " \t\r");615 if (std.mem.startsWith(u8, trimmed, "title:")) {616 const title = std.mem.trim(u8, trimmed[6..], " \t");617 const current = std.mem.indexOf(u8, title, "(current)") != null;618 try entries.append(gpa, .{619 .title = try gpa.dupe(u8, title),620 .current = current,621 });622 }623 }624 return entries.toOwnedSlice(gpa);625}626627628629pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {630 return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });631}632633pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {634 return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });635}636637pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {638 639 640 641 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});642 defer gpa.free(ref);643 const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref });644 defer gpa.free(r.stderr);645 defer gpa.free(r.stdout);646 if (r.exit_code != 0) return error.ProcessFailed;647648 const line = std.mem.trim(u8, r.stdout, " \t\n\r");649 var it = std.mem.tokenizeAny(u8, line, " \t");650 _ = it.next(); 651 const size = std.mem.trim(u8, it.rest(), " \t");652 if (size.len == 0) return error.ProcessFailed;653 return gpa.dupe(u8, size);654}655656pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {657 return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });658}659660661662pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {663 const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });664 defer gpa.free(r.stderr);665 if (r.exit_code != 0) {666 gpa.free(r.stdout);667 return error.ProcessFailed;668 }669 return r.stdout;670}671672pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {673 const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });674 defer gpa.free(r.stderr);675 if (r.exit_code != 0) {676 gpa.free(r.stdout);677 return error.ProcessFailed;678 }679 return r.stdout;680}681682683684pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {685 686 687}688689pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {690 if (line) |l| {691 const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});692 defer gpa.free(line_arg);693 return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });694 }695 return stream(io, &types.Machine{}, gpa, &.{ editor, path });696}697698pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {699 const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});700 defer gpa.free(a_str);701 const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});702 defer gpa.free(b_str);703 return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });704}705706707708pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {709 var checks: std.ArrayList(types.DoctorCheck) = .empty;710711 712 {713 const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });714 defer gpa.free(r.stdout);715 defer gpa.free(r.stderr);716 const active = std.mem.indexOf(u8, r.stdout, "active") != null;717 try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });718 }719720 721 {722 const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });723 defer gpa.free(r.stdout);724 defer gpa.free(r.stderr);725 try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });726 }727728 729 {730 const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });731 defer gpa.free(r.stdout);732 defer gpa.free(r.stderr);733 const has_channel = r.exit_code == 0 and r.stdout.len > 0;734 try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });735 }736737 return checks.toOwnedSlice(gpa);738}739740741742pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {743 const home = environ.get("HOME") orelse return error.FileNotFound;744 const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});745 defer gpa.free(path);746 _ = last;747 return std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;748}749750pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {751 const home = environ.get("HOME") orelse return;752 var path_buf: [512]u8 = undefined;753 const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;754 const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch755 (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);756 defer file.close(io);757 const size = file.length(io) catch 0;758 file.writePositionalAll(io, entry, size) catch {};759}760761762763764765pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {766 const argv = [_][]const u8{767 "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,768 };769 const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;770 defer gpa.free(result.stderr);771772 const marker = "\nHTTP_STATUS:";773 const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {774 gpa.free(result.stdout);775 return error.NetworkError;776 };777 const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");778 const status = std.fmt.parseInt(u16, status_str, 10) catch {779 gpa.free(result.stdout);780 return error.NetworkError;781 };782 if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }783 if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }784 const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {785 gpa.free(result.stdout);786 return e;787 };788 gpa.free(result.stdout);789 return body;790}791792793794pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {795 const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");796 errdefer gpa.free(tmp_path);797798 var child = std.process.spawn(io, .{799 .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },800 .stdin = .close,801 .stdout = .close,802 .stderr = .inherit,803 }) catch return error.NetworkError;804 const term = child.wait(io) catch return error.NetworkError;805 switch (term) {806 .exited => |c| if (c != 0) return error.NetworkError,807 else => return error.NetworkError,808 }809 return tmp_path;810}811812813pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {814 const len = try std.process.executablePath(io, buf);815 return buf[0..len];816}817818819820821pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {822 const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {823 errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});824 return error.FileNotFound;825 };826 defer gpa.free(bytes);827828 var hasher = std.crypto.hash.Blake3.init(.{});829 hasher.update(bytes);830 var raw: [32]u8 = undefined;831 hasher.final(&raw);832 const hex = std.fmt.bytesToHex(raw, .lower);833 if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;834835 var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;836 const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch837 return error.NameTooLong;838839 {840 const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {841 errors.error_info.setMessage("cannot write to {s}", .{install_path});842 errors.error_info.setSuggestion("try: sudo nina update", .{});843 return error.AccessDenied;844 };845 defer f.close(io);846 f.writePositionalAll(io, bytes, 0) catch {847 errors.error_info.setMessage("cannot write to {s}", .{install_path});848 return error.AccessDenied;849 };850 try f.setPermissions(io, .fromMode(0o755));851 }852 errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};853854 if (comptime builtin.os.tag == .macos) {855 _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};856 }857858 std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {859 error.AccessDenied => {860 errors.error_info.setMessage("cannot replace {s}", .{install_path});861 errors.error_info.setSuggestion("try: sudo nina update", .{});862 return error.AccessDenied;863 },864 else => return e,865 };866}867868869870pub const NixFeatureStatus = struct {871 nix_command: bool = false,872 flakes: bool = false,873874 pub fn allEnabled(self: NixFeatureStatus) bool {875 return self.nix_command and self.flakes;876 }877};878879fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {880 var lines = std.mem.splitScalar(u8, conf, '\n');881 while (lines.next()) |line| {882 const trimmed = std.mem.trim(u8, line, " \t");883 if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;884 if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;885 if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;886 }887}888889pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {890 var status = NixFeatureStatus{};891892 if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {893 defer gpa.free(conf);894 scanConfFeatures(conf, &status);895 }896897 if (environ.get("HOME")) |home| {898 var buf: [512]u8 = undefined;899 const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;900 if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {901 defer gpa.free(conf);902 scanConfFeatures(conf, &status);903 }904 }905906 return status;907}908909pub fn isNixOS(io: std.Io) bool {910 const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;911 file.close(io);912 return true;913}914915916917pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {918 const home = environ.get("HOME") orelse {919 errors.error_info.setMessage("HOME not set", .{});920 return error.ConfigNotFound;921 };922923 const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});924 defer gpa.free(dir_path);925 const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});926 errdefer gpa.free(file_path);927928 _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};929930 const line = "experimental-features = nix-command flakes\n";931 const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch932 (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {933 errors.error_info.setMessage("could not write {s}", .{file_path});934 return error.FileNotFound;935 });936 defer file.close(io);937938 const size = file.length(io) catch 0;939 file.writePositionalAll(io, line, size) catch {940 errors.error_info.setMessage("could not write {s}", .{file_path});941 return error.FileNotFound;942 };943944 return file_path;945}