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}348349350pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {351 const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });352 defer gpa.free(r.stderr);353 if (r.exit_code != 0) {354 gpa.free(r.stdout);355 return error.ProcessFailed;356 }357 return r.stdout;358}359360361362363pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {364 const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });365 defer gpa.free(r.stderr);366 if (r.exit_code != 0) {367 gpa.free(r.stdout);368 return error.ProcessFailed;369 }370 return r.stdout;371}372373pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {374 return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });375}376377378379pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {380 return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });381}382383pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {384 return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });385}386387pub const SystemStatus = struct { size: []u8, age: []u8 };388389390391392393const STATUS_SCRIPT =394 \\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} ))"395;396397pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {398 const unknown = SystemStatus{399 .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },400 .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },401 };402 const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;403 defer gpa.free(r.stdout);404 defer gpa.free(r.stderr);405 if (r.exit_code != 0) return unknown;406407 var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");408 const sz_str = it.next() orelse return unknown;409 const age_str = it.next() orelse return unknown;410 const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;411 const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;412413 gpa.free(unknown.size);414 gpa.free(unknown.age);415 return .{416 .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),417 .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),418 };419}420421422423424pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {425 const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch426 return gpa.dupe(u8, "unknown");427 defer gpa.free(r.stderr);428 const state = std.mem.trim(u8, r.stdout, " \t\n\r");429 const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");430 gpa.free(r.stdout);431 return owned;432}433434fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {435 if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});436 if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});437 if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});438 return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});439}440441pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {442 return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });443}444445pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {446 447 448 449 450 451 452 const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });453 defer gpa.free(pi.stdout);454 defer gpa.free(pi.stderr);455456 const scan = scanStoreJson(pi.stdout);457 const total_owned = try humanSize(gpa, scan.total_bytes);458459 return .{460 .total_size = total_owned,461 .live_paths = scan.count,462 .reclaimable_paths = 0,463 };464}465466const StoreScan = struct { count: u64, total_bytes: u64 };467468469470471fn scanStoreJson(json_str: []const u8) StoreScan {472 const needle = "\"narSize\":";473 var count: u64 = 0;474 var total: u64 = 0;475 var i: usize = 0;476 while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {477 var j = pos + needle.len;478 while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}479 var val: u64 = 0;480 var any = false;481 while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {482 val = val * 10 + (json_str[j] - '0');483 any = true;484 }485 if (any) {486 count += 1;487 total += val;488 }489 i = j;490 }491 return .{ .count = count, .total_bytes = total };492}493494fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {495 const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };496 var val: f64 = @floatFromInt(bytes);497 var unit: usize = 0;498 while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;499 if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });500 return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });501}502503pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {504 505 506 const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});507 defer gpa.free(expr);508 const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });509 defer gpa.free(r.stderr);510 if (r.exit_code != 0) {511 gpa.free(r.stdout);512 return error.ProcessFailed;513 }514 return r.stdout;515}516517518519pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {520 if (input) |inp| {521 return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });522 }523 return stream(io, machine, gpa, &.{ "nix", "flake", "update" });524}525526pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {527 return stream(io, machine, gpa, &.{ "nix", "flake", "check" });528}529530pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {531 return stream(io, machine, gpa, &.{ "nix", "flake", "init" });532}533534pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {535 return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });536}537538pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {539 return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });540}541542pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {543 const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });544 defer gpa.free(r.stderr);545 if (r.exit_code != 0) {546 gpa.free(r.stdout);547 return error.ProcessFailed;548 }549 return r.stdout;550}551552553554pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {555 if (attr) |a| {556 const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});557 defer gpa.free(ref);558 return stream(io, machine, gpa, &.{ "nix", "build", ref });559 }560 return stream(io, machine, gpa, &.{ "nix", "build" });561}562563pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {564 565 const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");566 if (is_url) {567 return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });568 }569 570 if (std.mem.indexOfScalar(u8, pkg, '#') != null) {571 return stream(io, machine, gpa, &.{ "nix", "run", pkg });572 }573 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});574 defer gpa.free(ref);575 return stream(io, machine, gpa, &.{ "nix", "run", ref });576}577578pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {579 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});580 defer gpa.free(ref);581 return stream(io, machine, gpa, &.{ "nix", "shell", ref });582}583584pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {585 if (run_cmd) |cmd| {586 587 return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });588 }589 return stream(io, machine, gpa, &.{ "nix", "develop" });590}591592pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {593 return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });594}595596597598pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {599 if (check) {600 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });601 }602 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });603}604605606607pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {608 const r = try capture(gpa, io, machine, &.{"nixos-version"});609 defer gpa.free(r.stderr);610 if (r.exit_code != 0) {611 gpa.free(r.stdout);612 return error.ProcessFailed;613 }614 return r.stdout;615}616617pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {618 const r = try capture(gpa, io, machine, &.{ "uname", "-r" });619 defer gpa.free(r.stderr);620 if (r.exit_code != 0) {621 gpa.free(r.stdout);622 return error.ProcessFailed;623 }624 return r.stdout;625}626627pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {628 const r = try capture(gpa, io, machine, &.{"uptime"});629 defer gpa.free(r.stderr);630 if (r.exit_code != 0) {631 gpa.free(r.stdout);632 return error.ProcessFailed;633 }634 return r.stdout;635}636637638639pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {640 const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });641 defer gpa.free(r.stderr);642 defer gpa.free(r.stdout);643 if (r.exit_code != 0) return error.ProcessFailed;644 return parseBootEntries(gpa, r.stdout);645}646647fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {648 var entries: std.ArrayList(types.BootEntry) = .empty;649 var lines = std.mem.splitScalar(u8, output_str, '\n');650 while (lines.next()) |line| {651 const trimmed = std.mem.trim(u8, line, " \t\r");652 if (std.mem.startsWith(u8, trimmed, "title:")) {653 const title = std.mem.trim(u8, trimmed[6..], " \t");654 const current = std.mem.indexOf(u8, title, "(current)") != null;655 try entries.append(gpa, .{656 .title = try gpa.dupe(u8, title),657 .current = current,658 });659 }660 }661 return entries.toOwnedSlice(gpa);662}663664665666pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {667 return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });668}669670pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {671 return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });672}673674pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {675 676 677 678 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});679 defer gpa.free(ref);680 const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref });681 defer gpa.free(r.stderr);682 defer gpa.free(r.stdout);683 if (r.exit_code != 0) return error.ProcessFailed;684685 const line = std.mem.trim(u8, r.stdout, " \t\n\r");686 var it = std.mem.tokenizeAny(u8, line, " \t");687 _ = it.next(); 688 const size = std.mem.trim(u8, it.rest(), " \t");689 if (size.len == 0) return error.ProcessFailed;690 return gpa.dupe(u8, size);691}692693pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {694 return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });695}696697698699pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {700 const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });701 defer gpa.free(r.stderr);702 if (r.exit_code != 0) {703 gpa.free(r.stdout);704 return error.ProcessFailed;705 }706 return r.stdout;707}708709pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {710 const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });711 defer gpa.free(r.stderr);712 if (r.exit_code != 0) {713 gpa.free(r.stdout);714 return error.ProcessFailed;715 }716 return r.stdout;717}718719720721pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {722 723 724}725726pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {727 if (line) |l| {728 const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});729 defer gpa.free(line_arg);730 return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });731 }732 return stream(io, &types.Machine{}, gpa, &.{ editor, path });733}734735pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {736 const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});737 defer gpa.free(a_str);738 const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});739 defer gpa.free(b_str);740 741 if (output.colorEnabled()) {742 return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });743 }744 745 746 const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });747 defer gpa.free(r.stdout);748 defer gpa.free(r.stderr);749 const cleaned = try stripAnsi(gpa, r.stdout);750 defer gpa.free(cleaned);751 output.raw(cleaned);752 return r.exit_code;753}754755756757fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {758 var out: std.ArrayList(u8) = .empty;759 errdefer out.deinit(gpa);760 var i: usize = 0;761 while (i < input.len) {762 if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {763 i += 2;764 while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}765 if (i < input.len) i += 1; 766 continue;767 }768 try out.append(gpa, input[i]);769 i += 1;770 }771 return out.toOwnedSlice(gpa);772}773774test "stripAnsi removes CSI color sequences" {775 const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");776 defer std.testing.allocator.free(cleaned);777 try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);778}779780781782pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {783 var checks: std.ArrayList(types.DoctorCheck) = .empty;784785 786 {787 const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });788 defer gpa.free(r.stdout);789 defer gpa.free(r.stderr);790 const active = std.mem.indexOf(u8, r.stdout, "active") != null;791 try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });792 }793794 795 {796 const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });797 defer gpa.free(r.stdout);798 defer gpa.free(r.stderr);799 try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });800 }801802 803 {804 const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });805 defer gpa.free(r.stdout);806 defer gpa.free(r.stderr);807 const has_channel = r.exit_code == 0 and r.stdout.len > 0;808 try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });809 }810811 return checks.toOwnedSlice(gpa);812}813814815816pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {817 const home = environ.get("HOME") orelse return error.FileNotFound;818 const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});819 defer gpa.free(path);820 const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;821 if (last == 0) return content;822823 824 825 var lines: std.ArrayList([]const u8) = .empty;826 defer lines.deinit(gpa);827 var it = std.mem.splitScalar(u8, content, '\n');828 while (it.next()) |line| {829 if (std.mem.trim(u8, line, " \t\r").len == 0) continue;830 try lines.append(gpa, line);831 }832 if (lines.items.len <= last) return content;833834 var out: std.ArrayList(u8) = .empty;835 errdefer out.deinit(gpa);836 for (lines.items[lines.items.len - last ..]) |line| {837 try out.appendSlice(gpa, line);838 try out.append(gpa, '\n');839 }840 gpa.free(content);841 return out.toOwnedSlice(gpa);842}843844845846847848pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {849 const home = environ.get("HOME") orelse return;850 var buf: [512]u8 = undefined;851 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;852 const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;853 file.close(io);854}855856pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {857 const home = environ.get("HOME") orelse return false;858 var buf: [512]u8 = undefined;859 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;860 if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {861 f.close(io);862 std.Io.Dir.deleteFile(.cwd(), io, path) catch {};863 return true;864 } else |_| {865 return false;866 }867}868869pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {870 const home = environ.get("HOME") orelse return;871 var path_buf: [512]u8 = undefined;872 const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;873 const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch874 (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);875 defer file.close(io);876 const size = file.length(io) catch 0;877 file.writePositionalAll(io, entry, size) catch {};878}879880881882883884pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {885 const argv = [_][]const u8{886 "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,887 };888 const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;889 defer gpa.free(result.stderr);890891 const marker = "\nHTTP_STATUS:";892 const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {893 gpa.free(result.stdout);894 return error.NetworkError;895 };896 const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");897 const status = std.fmt.parseInt(u16, status_str, 10) catch {898 gpa.free(result.stdout);899 return error.NetworkError;900 };901 if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }902 if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }903 const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {904 gpa.free(result.stdout);905 return e;906 };907 gpa.free(result.stdout);908 return body;909}910911912913pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {914 const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");915 errdefer gpa.free(tmp_path);916917 var child = std.process.spawn(io, .{918 .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },919 .stdin = .close,920 .stdout = .close,921 .stderr = .inherit,922 }) catch return error.NetworkError;923 const term = child.wait(io) catch return error.NetworkError;924 switch (term) {925 .exited => |c| if (c != 0) return error.NetworkError,926 else => return error.NetworkError,927 }928 return tmp_path;929}930931932pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {933 const len = try std.process.executablePath(io, buf);934 return buf[0..len];935}936937938939940pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {941 const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {942 errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});943 return error.FileNotFound;944 };945 defer gpa.free(bytes);946947 var hasher = std.crypto.hash.Blake3.init(.{});948 hasher.update(bytes);949 var raw: [32]u8 = undefined;950 hasher.final(&raw);951 const hex = std.fmt.bytesToHex(raw, .lower);952 if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;953954 var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;955 const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch956 return error.NameTooLong;957958 {959 const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {960 errors.error_info.setMessage("cannot write to {s}", .{install_path});961 errors.error_info.setSuggestion("try: sudo nina update", .{});962 return error.AccessDenied;963 };964 defer f.close(io);965 f.writePositionalAll(io, bytes, 0) catch {966 errors.error_info.setMessage("cannot write to {s}", .{install_path});967 return error.AccessDenied;968 };969 try f.setPermissions(io, .fromMode(0o755));970 }971 errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};972973 if (comptime builtin.os.tag == .macos) {974 _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};975 }976977 std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {978 error.AccessDenied => {979 errors.error_info.setMessage("cannot replace {s}", .{install_path});980 errors.error_info.setSuggestion("try: sudo nina update", .{});981 return error.AccessDenied;982 },983 else => return e,984 };985}986987988989pub const NixFeatureStatus = struct {990 nix_command: bool = false,991 flakes: bool = false,992993 pub fn allEnabled(self: NixFeatureStatus) bool {994 return self.nix_command and self.flakes;995 }996};997998fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {999 var lines = std.mem.splitScalar(u8, conf, '\n');1000 while (lines.next()) |line| {1001 const trimmed = std.mem.trim(u8, line, " \t");1002 if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1003 if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1004 if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1005 }1006}10071008pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1009 var status = NixFeatureStatus{};10101011 if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1012 defer gpa.free(conf);1013 scanConfFeatures(conf, &status);1014 }10151016 if (environ.get("HOME")) |home| {1017 var buf: [512]u8 = undefined;1018 const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1019 if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1020 defer gpa.free(conf);1021 scanConfFeatures(conf, &status);1022 }1023 }10241025 return status;1026}10271028pub fn isNixOS(io: std.Io) bool {1029 const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1030 file.close(io);1031 return true;1032}1033103410351036pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1037 const home = environ.get("HOME") orelse {1038 errors.error_info.setMessage("HOME not set", .{});1039 return error.ConfigNotFound;1040 };10411042 const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1043 defer gpa.free(dir_path);1044 const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1045 errdefer gpa.free(file_path);10461047 _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};10481049 const line = "experimental-features = nix-command flakes\n";1050 const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1051 (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1052 errors.error_info.setMessage("could not write {s}", .{file_path});1053 return error.FileNotFound;1054 });1055 defer file.close(io);10561057 const size = file.length(io) catch 0;1058 file.writePositionalAll(io, line, size) catch {1059 errors.error_info.setMessage("could not write {s}", .{file_path});1060 return error.FileNotFound;1061 };10621063 return file_path;1064}