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}676869fn streamEnv(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8, base_env: *const std.process.Environ.Map, ps1: []const u8) !u8 {70 output.flush();71 const argv = try buildArgv(gpa, machine, cmd);72 defer if (!machine.local) gpa.free(argv);7374 var env = try base_env.clone(gpa);75 defer env.deinit();76 try env.put("PS1", ps1);7778 var child = std.process.spawn(io, .{79 .argv = argv,80 .stdin = .inherit,81 .stdout = .inherit,82 .stderr = .inherit,83 .environ_map = &env,84 }) catch |e| {85 errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});86 return e;87 };8889 const term = child.wait(io) catch |e| {90 errors.error_info.setMessage("process wait failed", .{});91 return e;92 };9394 return switch (term) {95 .exited => |c| c,96 else => 1,97 };98}99100101pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 {102 output.flush();103 var child = std.process.spawn(io, .{104 .argv = cmd,105 .stdin = .inherit,106 .stdout = .inherit,107 .stderr = .inherit,108 }) catch |e| {109 errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});110 return e;111 };112 const term = child.wait(io) catch {113 errors.error_info.setMessage("process wait failed", .{});114 return error.ProcessFailed;115 };116 return switch (term) {117 .exited => |c| c,118 else => 1,119 };120}121122123pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {124 const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;125 defer gpa.free(result.stderr);126 switch (result.term) {127 .exited => |c| if (c != 0) {128 gpa.free(result.stdout);129 return error.ProcessFailed;130 },131 else => {132 gpa.free(result.stdout);133 return error.ProcessFailed;134 },135 }136 return result.stdout;137}138139140141pub fn ensureDir(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) void {142 _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir }) catch {};143}144145fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {146 if (machine.local) return cmd;147148 const host = machine.host orelse {149 errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});150 return error.SshFailed;151 };152153 var ssh: std.ArrayList([]const u8) = .empty;154 try ssh.append(gpa, "ssh");155 try ssh.append(gpa, "-o");156 try ssh.append(gpa, "BatchMode=yes");157 try ssh.append(gpa, "-o");158 try ssh.append(gpa, "StrictHostKeyChecking=accept-new");159 if (machine.ssh_key) |key| {160 try ssh.append(gpa, "-i");161 try ssh.append(gpa, key);162 }163 const addr = if (machine.user) |u|164 try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })165 else166 try gpa.dupe(u8, host);167 try ssh.append(gpa, addr);168 for (cmd) |arg| try ssh.append(gpa, arg);169 return ssh.toOwnedSlice(gpa);170}171172173174175176177178pub fn configHasFlake(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {179 if (!machine.local) return false;180 const flake_path = std.fs.path.join(gpa, &.{ machine.config_path, "flake.nix" }) catch return false;181 defer gpa.free(flake_path);182 const f = std.Io.Dir.openFile(.cwd(), io, flake_path, .{}) catch return false;183 f.close(io);184 return true;185}186187188189190fn useFlakeFlag(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {191 return configHasFlake(gpa, io, machine) and !std.mem.eql(u8, machine.config_path, "/etc/nixos");192}193194fn nixosRebuildRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, flake: bool) !u8 {195 if (flake) {196 return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb, "--flake", machine.config_path });197 }198 return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb });199}200201pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {202 const flake = useFlakeFlag(gpa, io, machine);203 if (flake) {204 output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});205 } else {206 output.printSubstep("nixos-rebuild switch", .{});207 }208 return nixosRebuildRun(io, machine, gpa, "switch", flake);209}210211pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {212 return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine));213}214215pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {216 return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine));217}218219220221222223224225226227228const GEN_LIST_SCRIPT =229 \\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 }'230;231232pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {233 const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });234 defer gpa.free(r.stderr);235 defer gpa.free(r.stdout);236 if (r.exit_code != 0) return error.ProcessFailed;237 return parseGenerations(gpa, r.stdout);238}239240fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {241 var gens: std.ArrayList(types.GenerationInfo) = .empty;242 var lines = std.mem.splitScalar(u8, output_str, '\n');243 while (lines.next()) |line| {244 const trimmed = std.mem.trim(u8, line, " \t");245 if (trimmed.len == 0) continue;246 var parts = std.mem.tokenizeAny(u8, trimmed, " \t");247 const num_str = parts.next() orelse continue;248 const date_str = parts.next() orelse continue;249 const time_str = parts.next() orelse continue;250 const rest = parts.rest();251 const current = std.mem.indexOf(u8, rest, "current") != null;252 const num = std.fmt.parseInt(u32, num_str, 10) catch continue;253 try gens.append(gpa, .{254 .number = num,255 .date = try gpa.dupe(u8, date_str),256 .time = try gpa.dupe(u8, time_str),257 .current = current,258 });259 }260 return gens.toOwnedSlice(gpa);261}262263pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {264 const gens = try getGenerations(gpa, io, machine);265 defer gpa.free(gens);266 for (gens) |g| {267 if (g.current) return g.number;268 }269 return 0;270}271272pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {273 274 275 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 });276 defer gpa.free(cmd);277 return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });278}279280pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {281 return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });282}283284pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {285 const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});286 defer gpa.free(n_str);287 return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });288}289290pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {291 return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });292}293294295296pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {297 if (delete_old) {298 return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });299 }300 301 302 303 const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });304 defer gpa.free(cmd);305 return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });306}307308309310pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {311 const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });312 defer gpa.free(r.stderr);313 defer gpa.free(r.stdout);314 if (r.exit_code != 0) return error.ProcessFailed;315 return parseChannels(gpa, r.stdout);316}317318fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {319 var channels: std.ArrayList(types.ChannelInfo) = .empty;320 var lines = std.mem.splitScalar(u8, output_str, '\n');321 while (lines.next()) |line| {322 const trimmed = std.mem.trim(u8, line, " \t\r");323 if (trimmed.len == 0) continue;324 const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;325 try channels.append(gpa, .{326 .name = try gpa.dupe(u8, trimmed[0..space]),327 .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),328 });329 }330 return channels.toOwnedSlice(gpa);331}332333pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {334 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });335}336337pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {338 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });339}340341pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {342 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });343}344345346347pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {348 const cmd: []const []const u8 = if (user)349 &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }350 else351 &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };352 const r = try capture(gpa, io, machine, cmd);353 defer gpa.free(r.stderr);354 defer gpa.free(r.stdout);355 if (r.exit_code != 0) return error.ProcessFailed;356 return parseServices(gpa, r.stdout);357}358359fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {360 var svcs: std.ArrayList(types.ServiceInfo) = .empty;361 var lines = std.mem.splitScalar(u8, output_str, '\n');362 while (lines.next()) |line| {363 const trimmed = std.mem.trim(u8, line, " \t\r");364 if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; 365 var parts = std.mem.tokenizeAny(u8, trimmed, " \t");366 const name = parts.next() orelse continue;367 _ = parts.next(); 368 const active_str = parts.next() orelse continue;369 const sub_str = parts.next() orelse "unknown";370371 const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))372 (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)373 else if (std.mem.eql(u8, active_str, "failed"))374 .failed375 else376 .inactive;377378 try svcs.append(gpa, .{379 .name = try gpa.dupe(u8, name),380 .state = state,381 .uptime = null,382 });383 }384 return svcs.toOwnedSlice(gpa);385}386387pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {388 389 390 if (user) {391 return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });392 }393 return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });394}395396pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {397 const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});398 defer gpa.free(n_str);399 if (user) {400 if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });401 return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });402 }403 if (follow) {404 return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });405 }406 return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });407}408409410411pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {412 const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});413 defer gpa.free(pkg_ref);414 415 416 return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });417}418419pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {420 421 422 return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });423}424425pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {426 const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });427 defer gpa.free(r.stderr);428 if (r.exit_code != 0) return error.ProcessFailed;429 return r.stdout;430}431432433pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {434 const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });435 defer gpa.free(r.stderr);436 if (r.exit_code != 0) {437 gpa.free(r.stdout);438 return error.ProcessFailed;439 }440 return r.stdout;441}442443444445446447448pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {449 const js = profileListJson(gpa, io, machine) catch return null;450 defer gpa.free(js);451 return profileJsonNinaElement(gpa, js);452}453454pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {455 const name = profileNinaElement(gpa, io, machine) orelse return false;456 gpa.free(name);457 return true;458}459460461462463464fn storePathIsNina(path: []const u8) bool {465 const prefix = "/nix/store/";466 if (!std.mem.startsWith(u8, path, prefix)) return false;467 const rel = path[prefix.len..];468 469 const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];470 if (entry.len < 34) return false; 471 const pname_ver = entry[33..]; 472 return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");473}474475476477478479480fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {481 var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;482 defer parsed.deinit();483 const root = parsed.value;484 if (root != .object) return null;485 const elements = root.object.get("elements") orelse return null;486 switch (elements) {487 .object => |obj| {488 489 if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;490 491 492 493 var it = obj.iterator();494 while (it.next()) |kv| {495 const val = kv.value_ptr.*;496 if (val != .object) continue;497 const sps = val.object.get("storePaths") orelse continue;498 if (sps != .array) continue;499 for (sps.array.items) |sp| {500 if (sp == .string and storePathIsNina(sp.string))501 return gpa.dupe(u8, kv.key_ptr.*) catch null;502 }503 }504 return null;505 },506 .array => |arr| {507 508 for (arr.items) |el| {509 if (el != .object) continue;510 const ap = el.object.get("attrPath") orelse continue;511 if (ap != .string) continue;512 if (std.mem.eql(u8, ap.string, "nina") or513 std.mem.endsWith(u8, ap.string, ".nina"))514 return gpa.dupe(u8, "nina") catch null;515 516 517 const sps = el.object.get("storePaths") orelse continue;518 if (sps != .array) continue;519 for (sps.array.items) |sp| {520 if (sp != .string) continue;521 if (!storePathIsNina(sp.string)) continue;522 const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;523 const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;524 return gpa.dupe(u8, el_name) catch null;525 }526 }527 return null;528 },529 else => return null,530 }531}532533test "profileJsonNinaElement finds element name from profile JSON" {534 const a = std.testing.allocator;535536 537 const named =538 \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},539 \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}540 ;541 const r1 = profileJsonNinaElement(a, named);542 defer if (r1) |n| a.free(n);543 try std.testing.expectEqualStrings("nina", r1.?);544545 546 const default_key =547 \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}548 ;549 const r2 = profileJsonNinaElement(a, default_key);550 defer if (r2) |n| a.free(n);551 try std.testing.expectEqualStrings("default", r2.?);552553 554 const decoy =555 \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}556 ;557 const r3 = profileJsonNinaElement(a, decoy);558 try std.testing.expectEqual(@as(?[]const u8, null), r3);559560 561 const arr =562 \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}563 ;564 const r4 = profileJsonNinaElement(a, arr);565 defer if (r4) |n| a.free(n);566 try std.testing.expectEqualStrings("nina", r4.?);567568 569 const arr_default =570 \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}571 ;572 const r5 = profileJsonNinaElement(a, arr_default);573 defer if (r5) |n| a.free(n);574 try std.testing.expectEqualStrings("default", r5.?);575576 577 try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));578 try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));579}580581582583584pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {585 const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });586 defer gpa.free(r.stderr);587 if (r.exit_code != 0) {588 gpa.free(r.stdout);589 return error.ProcessFailed;590 }591 return r.stdout;592}593594pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {595 return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });596}597598599600pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {601 return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });602}603604pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {605 return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });606}607608pub const SystemStatus = struct { size: []u8, age: []u8 };609610611612613614const STATUS_SCRIPT =615 \\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} ))"616;617618pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {619 const unknown = SystemStatus{620 .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },621 .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },622 };623 const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;624 defer gpa.free(r.stdout);625 defer gpa.free(r.stderr);626 if (r.exit_code != 0) return unknown;627628 var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");629 const sz_str = it.next() orelse return unknown;630 const age_str = it.next() orelse return unknown;631 const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;632 const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;633634 gpa.free(unknown.size);635 gpa.free(unknown.age);636 return .{637 .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),638 .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),639 };640}641642643644645pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {646 const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch647 return gpa.dupe(u8, "unknown");648 defer gpa.free(r.stderr);649 const state = std.mem.trim(u8, r.stdout, " \t\n\r");650 const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");651 gpa.free(r.stdout);652 return owned;653}654655fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {656 if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});657 if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});658 if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});659 return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});660}661662pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {663 return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });664}665666pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {667 668 669 670 671 672 673 const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });674 defer gpa.free(pi.stdout);675 defer gpa.free(pi.stderr);676677 const scan = scanStoreJson(pi.stdout);678 const total_owned = try humanSize(gpa, scan.total_bytes);679680 return .{681 .total_size = total_owned,682 .live_paths = scan.count,683 .reclaimable_paths = 0,684 };685}686687const StoreScan = struct { count: u64, total_bytes: u64 };688689690691692fn scanStoreJson(json_str: []const u8) StoreScan {693 const needle = "\"narSize\":";694 var count: u64 = 0;695 var total: u64 = 0;696 var i: usize = 0;697 while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {698 var j = pos + needle.len;699 while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}700 var val: u64 = 0;701 var any = false;702 while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {703 val = val * 10 + (json_str[j] - '0');704 any = true;705 }706 if (any) {707 count += 1;708 total += val;709 }710 i = j;711 }712 return .{ .count = count, .total_bytes = total };713}714715fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {716 const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };717 var val: f64 = @floatFromInt(bytes);718 var unit: usize = 0;719 while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;720 if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });721 return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });722}723724pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {725 726 727 const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});728 defer gpa.free(expr);729 const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });730 defer gpa.free(r.stderr);731 if (r.exit_code != 0) {732 gpa.free(r.stdout);733 return error.ProcessFailed;734 }735 return r.stdout;736}737738739740pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {741 if (input) |inp| {742 return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });743 }744 return stream(io, machine, gpa, &.{ "nix", "flake", "update" });745}746747748749750pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {751 return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });752}753754pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {755 return stream(io, machine, gpa, &.{ "nix", "flake", "check" });756}757758pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {759 return stream(io, machine, gpa, &.{ "nix", "flake", "init" });760}761762pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {763 return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });764}765766pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {767 return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });768}769770pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {771 const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });772 defer gpa.free(r.stderr);773 if (r.exit_code != 0) {774 gpa.free(r.stdout);775 return error.ProcessFailed;776 }777 return r.stdout;778}779780781782pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {783 if (attr) |a| {784 const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});785 defer gpa.free(ref);786 return stream(io, machine, gpa, &.{ "nix", "build", ref });787 }788 return stream(io, machine, gpa, &.{ "nix", "build" });789}790791pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {792 793 const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");794 if (is_url) {795 return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });796 }797 798 if (std.mem.indexOfScalar(u8, pkg, '#') != null) {799 return stream(io, machine, gpa, &.{ "nix", "run", pkg });800 }801 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});802 defer gpa.free(ref);803 return stream(io, machine, gpa, &.{ "nix", "run", ref });804}805806pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {807 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});808 defer gpa.free(ref);809 return stream(io, machine, gpa, &.{ "nix", "shell", ref });810}811812pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {813 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});814 defer gpa.free(ref);815 const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});816 defer gpa.free(ps1);817 return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);818}819820pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {821 if (run_cmd) |cmd| {822 823 return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });824 }825 return stream(io, machine, gpa, &.{ "nix", "develop" });826}827828pub fn nixDevelopPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8, base_env: *const std.process.Environ.Map) !u8 {829 if (run_cmd) |cmd| {830 831 return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });832 }833 return streamEnv(io, machine, gpa, &.{ "nix", "develop" }, base_env, "(nina: dev) -> ");834}835836pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {837 return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });838}839840841842pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {843 if (check) {844 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });845 }846 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });847}848849850851pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {852 const r = try capture(gpa, io, machine, &.{"nixos-version"});853 defer gpa.free(r.stderr);854 if (r.exit_code != 0) {855 gpa.free(r.stdout);856 return error.ProcessFailed;857 }858 return r.stdout;859}860861pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {862 const r = try capture(gpa, io, machine, &.{ "uname", "-r" });863 defer gpa.free(r.stderr);864 if (r.exit_code != 0) {865 gpa.free(r.stdout);866 return error.ProcessFailed;867 }868 return r.stdout;869}870871pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {872 const r = try capture(gpa, io, machine, &.{"uptime"});873 defer gpa.free(r.stderr);874 if (r.exit_code != 0) {875 gpa.free(r.stdout);876 return error.ProcessFailed;877 }878 return r.stdout;879}880881882883pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {884 const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });885 defer gpa.free(r.stderr);886 defer gpa.free(r.stdout);887 if (r.exit_code != 0) return error.ProcessFailed;888 return parseBootEntries(gpa, r.stdout);889}890891fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {892 var entries: std.ArrayList(types.BootEntry) = .empty;893 var lines = std.mem.splitScalar(u8, output_str, '\n');894 while (lines.next()) |line| {895 const trimmed = std.mem.trim(u8, line, " \t\r");896 if (std.mem.startsWith(u8, trimmed, "title:")) {897 const title = std.mem.trim(u8, trimmed[6..], " \t");898 const current = std.mem.indexOf(u8, title, "(current)") != null;899 try entries.append(gpa, .{900 .title = try gpa.dupe(u8, title),901 .current = current,902 });903 }904 }905 return entries.toOwnedSlice(gpa);906}907908909910pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {911 return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });912}913914pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {915 return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });916}917918pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {919 920 921 922 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});923 defer gpa.free(ref);924 const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref });925 defer gpa.free(r.stderr);926 defer gpa.free(r.stdout);927 if (r.exit_code != 0) return error.ProcessFailed;928929 const line = std.mem.trim(u8, r.stdout, " \t\n\r");930 var it = std.mem.tokenizeAny(u8, line, " \t");931 _ = it.next(); 932 const size = std.mem.trim(u8, it.rest(), " \t");933 if (size.len == 0) return error.ProcessFailed;934 return gpa.dupe(u8, size);935}936937pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {938 return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });939}940941942943pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {944 const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });945 defer gpa.free(r.stderr);946 if (r.exit_code != 0) {947 gpa.free(r.stdout);948 return error.ProcessFailed;949 }950 return r.stdout;951}952953pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {954 const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });955 defer gpa.free(r.stderr);956 if (r.exit_code != 0) {957 gpa.free(r.stdout);958 return error.ProcessFailed;959 }960 return r.stdout;961}962963964965pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {966 967 968}969970pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {971 if (line) |l| {972 const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});973 defer gpa.free(line_arg);974 return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });975 }976 return stream(io, &types.Machine{}, gpa, &.{ editor, path });977}978979pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {980 const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});981 defer gpa.free(a_str);982 const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});983 defer gpa.free(b_str);984 985 if (output.colorEnabled()) {986 return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });987 }988 989 990 const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });991 defer gpa.free(r.stdout);992 defer gpa.free(r.stderr);993 const cleaned = try stripAnsi(gpa, r.stdout);994 defer gpa.free(cleaned);995 output.raw(cleaned);996 return r.exit_code;997}99899910001001fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1002 var out: std.ArrayList(u8) = .empty;1003 errdefer out.deinit(gpa);1004 var i: usize = 0;1005 while (i < input.len) {1006 if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1007 i += 2;1008 while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1009 if (i < input.len) i += 1; 1010 continue;1011 }1012 try out.append(gpa, input[i]);1013 i += 1;1014 }1015 return out.toOwnedSlice(gpa);1016}10171018test "stripAnsi removes CSI color sequences" {1019 const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1020 defer std.testing.allocator.free(cleaned);1021 try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1022}1023102410251026pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1027 var checks: std.ArrayList(types.DoctorCheck) = .empty;10281029 1030 {1031 const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1032 defer gpa.free(r.stdout);1033 defer gpa.free(r.stderr);1034 const active = std.mem.indexOf(u8, r.stdout, "active") != null;1035 try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1036 }10371038 1039 {1040 const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });1041 defer gpa.free(r.stdout);1042 defer gpa.free(r.stderr);1043 try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1044 }10451046 1047 {1048 const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1049 defer gpa.free(r.stdout);1050 defer gpa.free(r.stderr);1051 const has_channel = r.exit_code == 0 and r.stdout.len > 0;1052 try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1053 }10541055 return checks.toOwnedSlice(gpa);1056}10571058105910601061106210631064pub const HomeManagerMode = enum {1065 1066 standalone,1067 1068 1069 module,1070 none,1071};10721073fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1074 const home = environ.get("HOME") orelse return null;1075 return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1076}107710781079pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1080 const dir = homeConfigDir(gpa, environ) orelse return null;1081 defer gpa.free(dir);1082 return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1083}10841085fn pathExists(io: std.Io, path: []const u8) bool {1086 const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1087 f.close(io);1088 return true;1089}1090109110921093fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1094 var buf: [256]u8 = undefined;1095 const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1096 const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1097 defer gpa.free(r.stdout);1098 defer gpa.free(r.stderr);1099 return switch (r.term) {1100 .exited => |code| code == 0,1101 else => false,1102 };1103}11041105pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1106 if (commandExists(gpa, io, "home-manager")) return .standalone;1107 if (homeNixPath(gpa, environ)) |p| {1108 defer gpa.free(p);1109 if (pathExists(io, p)) return .module;1110 }1111 return .none;1112}11131114111511161117pub fn homeFlakeRef(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1118 const dir = homeConfigDir(gpa, environ) orelse return null;1119 defer gpa.free(dir);1120 const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch return null;1121 defer gpa.free(flake);1122 if (!pathExists(io, flake)) return null;1123 const user = environ.get("USER") orelse "default";1124 return std.fmt.allocPrint(gpa, "{s}#{s}", .{ dir, user }) catch null;1125}11261127pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1128 return stream(io, machine, gpa, &.{ "home-manager", "switch" });1129}11301131pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8) !u8 {1132 return stream(io, machine, gpa, &.{ "home-manager", "switch", "--flake", flake_ref });1133}1134113511361137pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1138 return stream(io, machine, gpa, &.{ "home-manager", "switch", "--rollback" });1139}1140114111421143pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1144 return stream(io, machine, gpa, &.{ "home-manager", "build" });1145}11461147pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1148 const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1149 defer gpa.free(r.stderr);1150 if (r.exit_code != 0) {1151 gpa.free(r.stdout);1152 return error.ProcessFailed;1153 }1154 return r.stdout;1155}115611571158pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1159 const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1160 defer gpa.free(r.stderr);1161 if (r.exit_code != 0) {1162 gpa.free(r.stdout);1163 return error.ProcessFailed;1164 }1165 return r.stdout;1166}1167116811691170pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1171 if (output.colorEnabled()) {1172 return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1173 }1174 const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1175 defer gpa.free(r.stdout);1176 defer gpa.free(r.stderr);1177 const cleaned = try stripAnsi(gpa, r.stdout);1178 defer gpa.free(cleaned);1179 output.raw(cleaned);1180 return r.exit_code;1181}1182118311841185pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1186 const home = environ.get("HOME") orelse return error.FileNotFound;1187 const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1188 defer gpa.free(path);1189 const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1190 if (last == 0) return content;11911192 1193 1194 var lines: std.ArrayList([]const u8) = .empty;1195 defer lines.deinit(gpa);1196 var it = std.mem.splitScalar(u8, content, '\n');1197 while (it.next()) |line| {1198 if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1199 try lines.append(gpa, line);1200 }1201 if (lines.items.len <= last) return content;12021203 var out: std.ArrayList(u8) = .empty;1204 errdefer out.deinit(gpa);1205 for (lines.items[lines.items.len - last ..]) |line| {1206 try out.appendSlice(gpa, line);1207 try out.append(gpa, '\n');1208 }1209 gpa.free(content);1210 return out.toOwnedSlice(gpa);1211}121212131214121512161217pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1218 const home = environ.get("HOME") orelse return;1219 var buf: [512]u8 = undefined;1220 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1221 const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1222 file.close(io);1223}12241225pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1226 const home = environ.get("HOME") orelse return false;1227 var buf: [512]u8 = undefined;1228 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1229 if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1230 f.close(io);1231 std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1232 return true;1233 } else |_| {1234 return false;1235 }1236}12371238pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1239 const home = environ.get("HOME") orelse return;1240 var path_buf: [512]u8 = undefined;1241 const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1242 const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1243 (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1244 defer file.close(io);1245 const size = file.length(io) catch 0;1246 file.writePositionalAll(io, entry, size) catch {};1247}124812491250125112521253pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1254 const argv = [_][]const u8{1255 "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1256 };1257 const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1258 defer gpa.free(result.stderr);12591260 const marker = "\nHTTP_STATUS:";1261 const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1262 gpa.free(result.stdout);1263 return error.NetworkError;1264 };1265 const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1266 const status = std.fmt.parseInt(u16, status_str, 10) catch {1267 gpa.free(result.stdout);1268 return error.NetworkError;1269 };1270 if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1271 if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1272 const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1273 gpa.free(result.stdout);1274 return e;1275 };1276 gpa.free(result.stdout);1277 return body;1278}1279128012811282pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1283 const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1284 errdefer gpa.free(tmp_path);12851286 var child = std.process.spawn(io, .{1287 .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1288 .stdin = .close,1289 .stdout = .close,1290 .stderr = .inherit,1291 }) catch return error.NetworkError;1292 const term = child.wait(io) catch return error.NetworkError;1293 switch (term) {1294 .exited => |c| if (c != 0) return error.NetworkError,1295 else => return error.NetworkError,1296 }1297 return tmp_path;1298}129913001301pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1302 const len = try std.process.executablePath(io, buf);1303 return buf[0..len];1304}13051306130713081309pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1310 const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1311 errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1312 return error.FileNotFound;1313 };1314 defer gpa.free(bytes);13151316 var hasher = std.crypto.hash.Blake3.init(.{});1317 hasher.update(bytes);1318 var raw: [32]u8 = undefined;1319 hasher.final(&raw);1320 const hex = std.fmt.bytesToHex(raw, .lower);1321 if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;13221323 var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1324 const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1325 return error.NameTooLong;13261327 {1328 const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1329 errors.error_info.setMessage("cannot write to {s}", .{install_path});1330 errors.error_info.setSuggestion("try: sudo nina update", .{});1331 return error.AccessDenied;1332 };1333 defer f.close(io);1334 f.writePositionalAll(io, bytes, 0) catch {1335 errors.error_info.setMessage("cannot write to {s}", .{install_path});1336 return error.AccessDenied;1337 };1338 try f.setPermissions(io, .fromMode(0o755));1339 }1340 errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};13411342 if (comptime builtin.os.tag == .macos) {1343 _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1344 }13451346 std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1347 error.AccessDenied => {1348 errors.error_info.setMessage("cannot replace {s}", .{install_path});1349 errors.error_info.setSuggestion("try: sudo nina update", .{});1350 return error.AccessDenied;1351 },1352 else => return e,1353 };1354}1355135613571358pub const NixFeatureStatus = struct {1359 nix_command: bool = false,1360 flakes: bool = false,13611362 pub fn allEnabled(self: NixFeatureStatus) bool {1363 return self.nix_command and self.flakes;1364 }1365};13661367fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1368 var lines = std.mem.splitScalar(u8, conf, '\n');1369 while (lines.next()) |line| {1370 const trimmed = std.mem.trim(u8, line, " \t");1371 if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1372 if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1373 if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1374 }1375}13761377pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1378 var status = NixFeatureStatus{};13791380 if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1381 defer gpa.free(conf);1382 scanConfFeatures(conf, &status);1383 }13841385 if (environ.get("HOME")) |home| {1386 var buf: [512]u8 = undefined;1387 const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1388 if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1389 defer gpa.free(conf);1390 scanConfFeatures(conf, &status);1391 }1392 }13931394 return status;1395}13961397pub fn isNixOS(io: std.Io) bool {1398 const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1399 file.close(io);1400 return true;1401}1402140314041405pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1406 const home = environ.get("HOME") orelse {1407 errors.error_info.setMessage("HOME not set", .{});1408 return error.ConfigNotFound;1409 };14101411 const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1412 defer gpa.free(dir_path);1413 const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1414 errdefer gpa.free(file_path);14151416 _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};14171418 const line = "experimental-features = nix-command flakes\n";1419 const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1420 (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1421 errors.error_info.setMessage("could not write {s}", .{file_path});1422 return error.FileNotFound;1423 });1424 defer file.close(io);14251426 const size = file.length(io) catch 0;1427 file.writePositionalAll(io, line, size) catch {1428 errors.error_info.setMessage("could not write {s}", .{file_path});1429 return error.FileNotFound;1430 };14311432 return file_path;1433}14341435143614371438143914401441pub const NIXOS_FEATURES_LINE =1442 "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";1443144414451446pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1447 const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1448 defer gpa.free(conf);1449 return std.mem.indexOf(u8, conf, "experimental-features") != null and1450 std.mem.indexOf(u8, conf, "nix-command") != null and1451 std.mem.indexOf(u8, conf, "flakes") != null;1452}14531454fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1455 if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1456 return captureLocal(gpa, io, &.{ "sudo", "cat", path });1457}145814591460146114621463pub fn appendFeaturesToNixosConfig(1464 gpa: std.mem.Allocator,1465 io: std.Io,1466 environ: *const std.process.Environ.Map,1467 path: []const u8,1468) !void {1469 const conf = readMaybeSudo(gpa, io, path) catch {1470 errors.error_info.setMessage("could not read {s}", .{path});1471 return error.ConfigNotFound;1472 };1473 defer gpa.free(conf);14741475 if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; 14761477 const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1478 errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1479 return error.MalformedConfig;1480 };14811482 const home = environ.get("HOME") orelse {1483 errors.error_info.setMessage("HOME not set", .{});1484 return error.ConfigNotFound;1485 };1486 const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1487 defer gpa.free(tmp_path);14881489 var buf: std.ArrayList(u8) = .empty;1490 defer buf.deinit(gpa);1491 try buf.appendSlice(gpa, conf[0..brace]);1492 if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1493 try buf.appendSlice(gpa, " # added by nina setup — flakes + the new nix CLI\n");1494 try buf.appendSlice(gpa, " ");1495 try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1496 try buf.append(gpa, '\n');1497 try buf.appendSlice(gpa, conf[brace..]);14981499 const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1500 errors.error_info.setMessage("could not write {s}", .{tmp_path});1501 return error.FileNotFound;1502 };1503 tmp.writePositionalAll(io, buf.items, 0) catch {1504 tmp.close(io);1505 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1506 errors.error_info.setMessage("could not write {s}", .{tmp_path});1507 return error.FileNotFound;1508 };1509 tmp.close(io);15101511 1512 1513 1514 const code = streamLocal(io, &.{1515 "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1516 }) catch {1517 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1518 errors.error_info.setMessage("could not write {s}", .{path});1519 return error.ProcessFailed;1520 };1521 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1522 if (code != 0) {1523 errors.error_info.setMessage("sudo cp into {s} failed", .{path});1524 return error.ProcessFailed;1525 }1526}