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);77 try env.put("NINA_PS1", ps1);7879 var child = std.process.spawn(io, .{80 .argv = argv,81 .stdin = .inherit,82 .stdout = .inherit,83 .stderr = .inherit,84 .environ_map = &env,85 }) catch |e| {86 errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});87 return e;88 };8990 const term = child.wait(io) catch |e| {91 errors.error_info.setMessage("process wait failed", .{});92 return e;93 };9495 return switch (term) {96 .exited => |c| c,97 else => 1,98 };99}100101fn createInteractiveShellRc(gpa: std.mem.Allocator, io: std.Io) ![]u8 {102 const out = try captureLocal(gpa, io, &.{ "mktemp", "/tmp/nina-shell-rc.XXXXXX" });103 defer gpa.free(out);104105 const path = std.mem.trim(u8, out, " \t\r\n");106 if (path.len == 0) return error.FileNotFound;107 const owned_path = try gpa.dupe(u8, path);108 errdefer gpa.free(owned_path);109110 const file = std.Io.Dir.createFile(.cwd(), io, owned_path, .{}) catch {111 errors.error_info.setMessage("could not write shell prompt setup", .{});112 return error.FileNotFound;113 };114 errdefer file.close(io);115116 const content =117 \\PS1="${NINA_PS1:-$PS1}"118 \\trap 'exit 130' INT119 \\120 ;121 file.writePositionalAll(io, content, 0) catch {122 errors.error_info.setMessage("could not write shell prompt setup", .{});123 return error.FileNotFound;124 };125 file.close(io);126127 return owned_path;128}129130131pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 {132 output.flush();133 var child = std.process.spawn(io, .{134 .argv = cmd,135 .stdin = .inherit,136 .stdout = .inherit,137 .stderr = .inherit,138 }) catch |e| {139 errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});140 return e;141 };142 const term = child.wait(io) catch {143 errors.error_info.setMessage("process wait failed", .{});144 return error.ProcessFailed;145 };146 return switch (term) {147 .exited => |c| c,148 else => 1,149 };150}151152153pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {154 const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;155 defer gpa.free(result.stderr);156 switch (result.term) {157 .exited => |c| if (c != 0) {158 gpa.free(result.stdout);159 return error.ProcessFailed;160 },161 else => {162 gpa.free(result.stdout);163 return error.ProcessFailed;164 },165 }166 return result.stdout;167}168169170171pub fn ensureDir(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) void {172 _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir }) catch {};173}174175fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {176 if (machine.local) return cmd;177178 const host = machine.host orelse {179 errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});180 return error.SshFailed;181 };182183 var ssh: std.ArrayList([]const u8) = .empty;184 try ssh.append(gpa, "ssh");185 try ssh.append(gpa, "-o");186 try ssh.append(gpa, "BatchMode=yes");187 try ssh.append(gpa, "-o");188 try ssh.append(gpa, "StrictHostKeyChecking=accept-new");189 if (machine.ssh_key) |key| {190 try ssh.append(gpa, "-i");191 try ssh.append(gpa, key);192 }193 const addr = if (machine.user) |u|194 try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })195 else196 try gpa.dupe(u8, host);197 try ssh.append(gpa, addr);198 for (cmd) |arg| try ssh.append(gpa, arg);199 return ssh.toOwnedSlice(gpa);200}201202203204205206207208209pub fn dirHasFlake(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) bool {210 const flake_path = std.fs.path.join(gpa, &.{ dir, "flake.nix" }) catch return false;211 defer gpa.free(flake_path);212 return pathExists(io, flake_path);213}214215pub fn configHasFlake(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {216 if (!machine.local) return false;217 return dirHasFlake(gpa, io, machine.config_path);218}219220221222223224fn useFlakeFlag(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {225 if (!configHasFlake(gpa, io, machine)) return false;226 var path = machine.config_path;227 while (path.len > 1 and path[path.len - 1] == '/') path = path[0 .. path.len - 1];228 return !std.mem.eql(u8, path, "/etc/nixos");229}230231fn nixosRebuildRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, flake: bool) !u8 {232 if (flake) {233 return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb, "--flake", machine.config_path });234 }235 return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb });236}237238pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {239 const flake = useFlakeFlag(gpa, io, machine);240 if (flake) {241 output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});242 } else {243 output.printSubstep("nixos-rebuild switch", .{});244 }245 return nixosRebuildRun(io, machine, gpa, "switch", flake);246}247248pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {249 return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine));250}251252pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {253 return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine));254}255256257258259260261262263264265const GEN_LIST_SCRIPT =266 \\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 }'267;268269pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {270 const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });271 defer gpa.free(r.stderr);272 defer gpa.free(r.stdout);273 if (r.exit_code != 0) return error.ProcessFailed;274 return parseGenerations(gpa, r.stdout);275}276277fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {278 var gens: std.ArrayList(types.GenerationInfo) = .empty;279 var lines = std.mem.splitScalar(u8, output_str, '\n');280 while (lines.next()) |line| {281 const trimmed = std.mem.trim(u8, line, " \t");282 if (trimmed.len == 0) continue;283 var parts = std.mem.tokenizeAny(u8, trimmed, " \t");284 const num_str = parts.next() orelse continue;285 const date_str = parts.next() orelse continue;286 const time_str = parts.next() orelse continue;287 const rest = parts.rest();288 const current = std.mem.indexOf(u8, rest, "current") != null;289 const num = std.fmt.parseInt(u32, num_str, 10) catch continue;290 try gens.append(gpa, .{291 .number = num,292 .date = try gpa.dupe(u8, date_str),293 .time = try gpa.dupe(u8, time_str),294 .current = current,295 });296 }297 return gens.toOwnedSlice(gpa);298}299300pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {301 const gens = try getGenerations(gpa, io, machine);302 defer gpa.free(gens);303 for (gens) |g| {304 if (g.current) return g.number;305 }306 return 0;307}308309pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {310 311 312 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 });313 defer gpa.free(cmd);314 return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });315}316317pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {318 return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });319}320321pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {322 const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});323 defer gpa.free(n_str);324 return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });325}326327pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {328 return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });329}330331332333pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {334 if (delete_old) {335 return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });336 }337 338 339 340 const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });341 defer gpa.free(cmd);342 return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });343}344345346347pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {348 const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });349 defer gpa.free(r.stderr);350 defer gpa.free(r.stdout);351 if (r.exit_code != 0) return error.ProcessFailed;352 return parseChannels(gpa, r.stdout);353}354355fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {356 var channels: std.ArrayList(types.ChannelInfo) = .empty;357 var lines = std.mem.splitScalar(u8, output_str, '\n');358 while (lines.next()) |line| {359 const trimmed = std.mem.trim(u8, line, " \t\r");360 if (trimmed.len == 0) continue;361 const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;362 try channels.append(gpa, .{363 .name = try gpa.dupe(u8, trimmed[0..space]),364 .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),365 });366 }367 return channels.toOwnedSlice(gpa);368}369370pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {371 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });372}373374pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {375 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });376}377378pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {379 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });380}381382383384pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {385 const cmd: []const []const u8 = if (user)386 &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }387 else388 &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };389 const r = try capture(gpa, io, machine, cmd);390 defer gpa.free(r.stderr);391 defer gpa.free(r.stdout);392 if (r.exit_code != 0) return error.ProcessFailed;393 return parseServices(gpa, r.stdout);394}395396fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {397 var svcs: std.ArrayList(types.ServiceInfo) = .empty;398 var lines = std.mem.splitScalar(u8, output_str, '\n');399 while (lines.next()) |line| {400 const trimmed = std.mem.trim(u8, line, " \t\r");401 if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; 402 var parts = std.mem.tokenizeAny(u8, trimmed, " \t");403 const name = parts.next() orelse continue;404 _ = parts.next(); 405 const active_str = parts.next() orelse continue;406 const sub_str = parts.next() orelse "unknown";407408 const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))409 (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)410 else if (std.mem.eql(u8, active_str, "failed"))411 .failed412 else413 .inactive;414415 try svcs.append(gpa, .{416 .name = try gpa.dupe(u8, name),417 .state = state,418 .uptime = null,419 });420 }421 return svcs.toOwnedSlice(gpa);422}423424pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {425 426 427 if (user) {428 return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });429 }430 return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });431}432433pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {434 const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});435 defer gpa.free(n_str);436 if (user) {437 if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });438 return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });439 }440 if (follow) {441 return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });442 }443 return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });444}445446447448pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {449 const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});450 defer gpa.free(pkg_ref);451 452 453 return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });454}455456pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {457 458 459 return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });460}461462pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {463 const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });464 defer gpa.free(r.stderr);465 if (r.exit_code != 0) return error.ProcessFailed;466 return r.stdout;467}468469470pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {471 const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });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}479480481482483484485pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {486 const js = profileListJson(gpa, io, machine) catch return null;487 defer gpa.free(js);488 return profileJsonNinaElement(gpa, js);489}490491pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {492 const name = profileNinaElement(gpa, io, machine) orelse return false;493 gpa.free(name);494 return true;495}496497498499500501fn storePathIsNina(path: []const u8) bool {502 const prefix = "/nix/store/";503 if (!std.mem.startsWith(u8, path, prefix)) return false;504 const rel = path[prefix.len..];505 506 const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];507 if (entry.len < 34) return false; 508 const pname_ver = entry[33..]; 509 return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");510}511512513514515516517fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {518 var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;519 defer parsed.deinit();520 const root = parsed.value;521 if (root != .object) return null;522 const elements = root.object.get("elements") orelse return null;523 switch (elements) {524 .object => |obj| {525 526 if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;527 528 529 530 var it = obj.iterator();531 while (it.next()) |kv| {532 const val = kv.value_ptr.*;533 if (val != .object) continue;534 const sps = val.object.get("storePaths") orelse continue;535 if (sps != .array) continue;536 for (sps.array.items) |sp| {537 if (sp == .string and storePathIsNina(sp.string))538 return gpa.dupe(u8, kv.key_ptr.*) catch null;539 }540 }541 return null;542 },543 .array => |arr| {544 545 for (arr.items) |el| {546 if (el != .object) continue;547 const ap = el.object.get("attrPath") orelse continue;548 if (ap != .string) continue;549 if (std.mem.eql(u8, ap.string, "nina") or550 std.mem.endsWith(u8, ap.string, ".nina"))551 return gpa.dupe(u8, "nina") catch null;552 553 554 const sps = el.object.get("storePaths") orelse continue;555 if (sps != .array) continue;556 for (sps.array.items) |sp| {557 if (sp != .string) continue;558 if (!storePathIsNina(sp.string)) continue;559 const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;560 const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;561 return gpa.dupe(u8, el_name) catch null;562 }563 }564 return null;565 },566 else => return null,567 }568}569570test "profileJsonNinaElement finds element name from profile JSON" {571 const a = std.testing.allocator;572573 574 const named =575 \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},576 \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}577 ;578 const r1 = profileJsonNinaElement(a, named);579 defer if (r1) |n| a.free(n);580 try std.testing.expectEqualStrings("nina", r1.?);581582 583 const default_key =584 \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}585 ;586 const r2 = profileJsonNinaElement(a, default_key);587 defer if (r2) |n| a.free(n);588 try std.testing.expectEqualStrings("default", r2.?);589590 591 const decoy =592 \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}593 ;594 const r3 = profileJsonNinaElement(a, decoy);595 try std.testing.expectEqual(@as(?[]const u8, null), r3);596597 598 const arr =599 \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}600 ;601 const r4 = profileJsonNinaElement(a, arr);602 defer if (r4) |n| a.free(n);603 try std.testing.expectEqualStrings("nina", r4.?);604605 606 const arr_default =607 \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}608 ;609 const r5 = profileJsonNinaElement(a, arr_default);610 defer if (r5) |n| a.free(n);611 try std.testing.expectEqualStrings("default", r5.?);612613 614 try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));615 try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));616}617618619620621pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {622 const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });623 defer gpa.free(r.stderr);624 if (r.exit_code != 0) {625 gpa.free(r.stdout);626 return error.ProcessFailed;627 }628 return r.stdout;629}630631pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {632 return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });633}634635636637pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {638 return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });639}640641pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {642 return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });643}644645pub const SystemStatus = struct { size: []u8, age: []u8 };646647648649650651const STATUS_SCRIPT =652 \\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} ))"653;654655pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {656 const unknown = SystemStatus{657 .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },658 .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },659 };660 const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;661 defer gpa.free(r.stdout);662 defer gpa.free(r.stderr);663 if (r.exit_code != 0) return unknown;664665 var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");666 const sz_str = it.next() orelse return unknown;667 const age_str = it.next() orelse return unknown;668 const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;669 const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;670671 gpa.free(unknown.size);672 gpa.free(unknown.age);673 return .{674 .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),675 .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),676 };677}678679680681682pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {683 const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch684 return gpa.dupe(u8, "unknown");685 defer gpa.free(r.stderr);686 const state = std.mem.trim(u8, r.stdout, " \t\n\r");687 const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");688 gpa.free(r.stdout);689 return owned;690}691692fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {693 if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});694 if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});695 if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});696 return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});697}698699pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {700 return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });701}702703pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {704 705 706 707 708 709 710 const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });711 defer gpa.free(pi.stdout);712 defer gpa.free(pi.stderr);713714 const scan = scanStoreJson(pi.stdout);715 const total_owned = try humanSize(gpa, scan.total_bytes);716717 return .{718 .total_size = total_owned,719 .live_paths = scan.count,720 .reclaimable_paths = 0,721 };722}723724const StoreScan = struct { count: u64, total_bytes: u64 };725726727728729fn scanStoreJson(json_str: []const u8) StoreScan {730 const needle = "\"narSize\":";731 var count: u64 = 0;732 var total: u64 = 0;733 var i: usize = 0;734 while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {735 var j = pos + needle.len;736 while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}737 var val: u64 = 0;738 var any = false;739 while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {740 val = val * 10 + (json_str[j] - '0');741 any = true;742 }743 if (any) {744 count += 1;745 total += val;746 }747 i = j;748 }749 return .{ .count = count, .total_bytes = total };750}751752fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {753 const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };754 var val: f64 = @floatFromInt(bytes);755 var unit: usize = 0;756 while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;757 if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });758 return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });759}760761pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {762 763 764 const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});765 defer gpa.free(expr);766 const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });767 defer gpa.free(r.stderr);768 if (r.exit_code != 0) {769 gpa.free(r.stdout);770 return error.ProcessFailed;771 }772 return r.stdout;773}774775776777pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {778 if (input) |inp| {779 return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });780 }781 return stream(io, machine, gpa, &.{ "nix", "flake", "update" });782}783784785786787pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {788 return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });789}790791pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {792 return stream(io, machine, gpa, &.{ "nix", "flake", "check" });793}794795pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {796 return stream(io, machine, gpa, &.{ "nix", "flake", "init" });797}798799pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {800 return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });801}802803pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {804 return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });805}806807pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {808 const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });809 defer gpa.free(r.stderr);810 if (r.exit_code != 0) {811 gpa.free(r.stdout);812 return error.ProcessFailed;813 }814 return r.stdout;815}816817818819pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {820 if (attr) |a| {821 const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});822 defer gpa.free(ref);823 return stream(io, machine, gpa, &.{ "nix", "build", ref });824 }825 return stream(io, machine, gpa, &.{ "nix", "build" });826}827828pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {829 830 const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");831 if (is_url) {832 return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });833 }834 835 if (std.mem.indexOfScalar(u8, pkg, '#') != null) {836 return stream(io, machine, gpa, &.{ "nix", "run", pkg });837 }838 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});839 defer gpa.free(ref);840 return stream(io, machine, gpa, &.{ "nix", "run", ref });841}842843pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {844 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});845 defer gpa.free(ref);846 return stream(io, machine, gpa, &.{ "nix", "shell", ref });847}848849pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {850 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});851 defer gpa.free(ref);852 const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});853 defer gpa.free(ps1);854 if (machine.local) {855 const rc_path = try createInteractiveShellRc(gpa, io);856 defer {857 std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};858 gpa.free(rc_path);859 }860 return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref, "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, ps1);861 }862 return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);863}864865pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {866 if (run_cmd) |cmd| {867 868 return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });869 }870 return stream(io, machine, gpa, &.{ "nix", "develop" });871}872873pub 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 {874 if (run_cmd) |cmd| {875 876 return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });877 }878 if (machine.local) {879 const rc_path = try createInteractiveShellRc(gpa, io);880 defer {881 std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};882 gpa.free(rc_path);883 }884 return streamEnv(io, machine, gpa, &.{ "nix", "develop", "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, "(nina: dev) -> ");885 }886 return streamEnv(io, machine, gpa, &.{ "nix", "develop" }, base_env, "(nina: dev) -> ");887}888889pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {890 return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });891}892893894895pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {896 if (check) {897 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });898 }899 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });900}901902903904pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {905 const r = try capture(gpa, io, machine, &.{"nixos-version"});906 defer gpa.free(r.stderr);907 if (r.exit_code != 0) {908 gpa.free(r.stdout);909 return error.ProcessFailed;910 }911 return r.stdout;912}913914pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {915 const r = try capture(gpa, io, machine, &.{ "uname", "-r" });916 defer gpa.free(r.stderr);917 if (r.exit_code != 0) {918 gpa.free(r.stdout);919 return error.ProcessFailed;920 }921 return r.stdout;922}923924pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {925 const r = try capture(gpa, io, machine, &.{"uptime"});926 defer gpa.free(r.stderr);927 if (r.exit_code != 0) {928 gpa.free(r.stdout);929 return error.ProcessFailed;930 }931 return r.stdout;932}933934935936pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {937 const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });938 defer gpa.free(r.stderr);939 defer gpa.free(r.stdout);940 if (r.exit_code != 0) return error.ProcessFailed;941 return parseBootEntries(gpa, r.stdout);942}943944fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {945 var entries: std.ArrayList(types.BootEntry) = .empty;946 var lines = std.mem.splitScalar(u8, output_str, '\n');947 while (lines.next()) |line| {948 const trimmed = std.mem.trim(u8, line, " \t\r");949 if (std.mem.startsWith(u8, trimmed, "title:")) {950 const title = std.mem.trim(u8, trimmed[6..], " \t");951 const current = std.mem.indexOf(u8, title, "(current)") != null;952 try entries.append(gpa, .{953 .title = try gpa.dupe(u8, title),954 .current = current,955 });956 }957 }958 return entries.toOwnedSlice(gpa);959}960961962963pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {964 return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });965}966967pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {968 return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });969}970971pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {972 973 974 975 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});976 defer gpa.free(ref);977 const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref });978 defer gpa.free(r.stderr);979 defer gpa.free(r.stdout);980 if (r.exit_code != 0) return error.ProcessFailed;981982 const line = std.mem.trim(u8, r.stdout, " \t\n\r");983 var it = std.mem.tokenizeAny(u8, line, " \t");984 _ = it.next(); 985 const size = std.mem.trim(u8, it.rest(), " \t");986 if (size.len == 0) return error.ProcessFailed;987 return gpa.dupe(u8, size);988}989990pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {991 return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });992}993994995996pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {997 const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });998 defer gpa.free(r.stderr);999 if (r.exit_code != 0) {1000 gpa.free(r.stdout);1001 return error.ProcessFailed;1002 }1003 return r.stdout;1004}10051006pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {1007 const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });1008 defer gpa.free(r.stderr);1009 if (r.exit_code != 0) {1010 gpa.free(r.stdout);1011 return error.ProcessFailed;1012 }1013 return r.stdout;1014}1015101610171018pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {1019 1020 1021}10221023pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {1024 if (line) |l| {1025 const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});1026 defer gpa.free(line_arg);1027 return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });1028 }1029 return stream(io, &types.Machine{}, gpa, &.{ editor, path });1030}10311032pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {1033 const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});1034 defer gpa.free(a_str);1035 const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});1036 defer gpa.free(b_str);1037 1038 if (output.colorEnabled()) {1039 return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });1040 }1041 1042 1043 const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });1044 defer gpa.free(r.stdout);1045 defer gpa.free(r.stderr);1046 const cleaned = try stripAnsi(gpa, r.stdout);1047 defer gpa.free(cleaned);1048 output.raw(cleaned);1049 return r.exit_code;1050}1051105210531054fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1055 var out: std.ArrayList(u8) = .empty;1056 errdefer out.deinit(gpa);1057 var i: usize = 0;1058 while (i < input.len) {1059 if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1060 i += 2;1061 while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1062 if (i < input.len) i += 1; 1063 continue;1064 }1065 try out.append(gpa, input[i]);1066 i += 1;1067 }1068 return out.toOwnedSlice(gpa);1069}10701071test "stripAnsi removes CSI color sequences" {1072 const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1073 defer std.testing.allocator.free(cleaned);1074 try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1075}1076107710781079pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1080 var checks: std.ArrayList(types.DoctorCheck) = .empty;10811082 1083 {1084 const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1085 defer gpa.free(r.stdout);1086 defer gpa.free(r.stderr);1087 const active = std.mem.indexOf(u8, r.stdout, "active") != null;1088 try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1089 }10901091 1092 1093 1094 {1095 const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1096 &.{ "sudo", "nixos-rebuild", "dry-build", "--flake", machine.config_path }1097 else1098 &.{ "sudo", "nixos-rebuild", "dry-build" };1099 const r = try capture(gpa, io, machine, argv);1100 defer gpa.free(r.stdout);1101 defer gpa.free(r.stderr);1102 try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1103 }11041105 1106 {1107 const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1108 defer gpa.free(r.stdout);1109 defer gpa.free(r.stderr);1110 const has_channel = r.exit_code == 0 and r.stdout.len > 0;1111 try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1112 }11131114 return checks.toOwnedSlice(gpa);1115}11161117111811191120112111221123pub const HomeManagerMode = enum {1124 1125 standalone,1126 1127 1128 module,1129 none,1130};11311132fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1133 const home = environ.get("HOME") orelse return null;1134 return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1135}113611371138pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1139 const dir = homeConfigDir(gpa, environ) orelse return null;1140 defer gpa.free(dir);1141 return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1142}11431144pub fn pathExists(io: std.Io, path: []const u8) bool {1145 const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1146 f.close(io);1147 return true;1148}1149115011511152fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1153 var buf: [256]u8 = undefined;1154 const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1155 const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1156 defer gpa.free(r.stdout);1157 defer gpa.free(r.stderr);1158 return switch (r.term) {1159 .exited => |code| code == 0,1160 else => false,1161 };1162}11631164pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1165 if (commandExists(gpa, io, "home-manager")) return .standalone;1166 if (homeNixPath(gpa, environ)) |p| {1167 defer gpa.free(p);1168 if (pathExists(io, p)) return .module;1169 }1170 return .none;1171}11721173117411751176pub fn homeFlakeRef(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1177 const dir = homeConfigDir(gpa, environ) orelse return null;1178 defer gpa.free(dir);1179 const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch return null;1180 defer gpa.free(flake);1181 if (!pathExists(io, flake)) return null;1182 const user = environ.get("USER") orelse "default";1183 return std.fmt.allocPrint(gpa, "{s}#{s}", .{ dir, user }) catch null;1184}11851186pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1187 return stream(io, machine, gpa, &.{ "home-manager", "switch" });1188}11891190pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8) !u8 {1191 return stream(io, machine, gpa, &.{ "home-manager", "switch", "--flake", flake_ref });1192}1193119411951196pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1197 return stream(io, machine, gpa, &.{ "home-manager", "switch", "--rollback" });1198}119912001201120212031204pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1205 return stream(io, machine, gpa, &.{ "sh", "-c", "d=$(mktemp -d) && cd \"$d\" && home-manager build" });1206}12071208pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1209 const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1210 defer gpa.free(r.stderr);1211 if (r.exit_code != 0) {1212 gpa.free(r.stdout);1213 return error.ProcessFailed;1214 }1215 return r.stdout;1216}121712181219pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1220 const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1221 defer gpa.free(r.stderr);1222 if (r.exit_code != 0) {1223 gpa.free(r.stdout);1224 return error.ProcessFailed;1225 }1226 return r.stdout;1227}1228122912301231pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1232 if (output.colorEnabled()) {1233 return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1234 }1235 const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1236 defer gpa.free(r.stdout);1237 defer gpa.free(r.stderr);1238 const cleaned = try stripAnsi(gpa, r.stdout);1239 defer gpa.free(cleaned);1240 output.raw(cleaned);1241 return r.exit_code;1242}1243124412451246pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1247 const home = environ.get("HOME") orelse return error.FileNotFound;1248 const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1249 defer gpa.free(path);1250 const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1251 if (last == 0) return content;12521253 1254 1255 var lines: std.ArrayList([]const u8) = .empty;1256 defer lines.deinit(gpa);1257 var it = std.mem.splitScalar(u8, content, '\n');1258 while (it.next()) |line| {1259 if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1260 try lines.append(gpa, line);1261 }1262 if (lines.items.len <= last) return content;12631264 var out: std.ArrayList(u8) = .empty;1265 errdefer out.deinit(gpa);1266 for (lines.items[lines.items.len - last ..]) |line| {1267 try out.appendSlice(gpa, line);1268 try out.append(gpa, '\n');1269 }1270 gpa.free(content);1271 return out.toOwnedSlice(gpa);1272}127312741275127612771278pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1279 const home = environ.get("HOME") orelse return;1280 var buf: [512]u8 = undefined;1281 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1282 const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1283 file.close(io);1284}12851286pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1287 const home = environ.get("HOME") orelse return false;1288 var buf: [512]u8 = undefined;1289 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1290 if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1291 f.close(io);1292 std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1293 return true;1294 } else |_| {1295 return false;1296 }1297}12981299pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1300 const home = environ.get("HOME") orelse return;1301 var path_buf: [512]u8 = undefined;1302 const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1303 const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1304 (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1305 defer file.close(io);1306 const size = file.length(io) catch 0;1307 file.writePositionalAll(io, entry, size) catch {};1308}130913101311131213131314pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1315 const argv = [_][]const u8{1316 "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1317 };1318 const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1319 defer gpa.free(result.stderr);13201321 const marker = "\nHTTP_STATUS:";1322 const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1323 gpa.free(result.stdout);1324 return error.NetworkError;1325 };1326 const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1327 const status = std.fmt.parseInt(u16, status_str, 10) catch {1328 gpa.free(result.stdout);1329 return error.NetworkError;1330 };1331 if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1332 if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1333 const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1334 gpa.free(result.stdout);1335 return e;1336 };1337 gpa.free(result.stdout);1338 return body;1339}1340134113421343pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1344 const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1345 errdefer gpa.free(tmp_path);13461347 var child = std.process.spawn(io, .{1348 .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1349 .stdin = .close,1350 .stdout = .close,1351 .stderr = .inherit,1352 }) catch return error.NetworkError;1353 const term = child.wait(io) catch return error.NetworkError;1354 switch (term) {1355 .exited => |c| if (c != 0) return error.NetworkError,1356 else => return error.NetworkError,1357 }1358 return tmp_path;1359}136013611362pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1363 const len = try std.process.executablePath(io, buf);1364 return buf[0..len];1365}13661367136813691370pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1371 const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1372 errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1373 return error.FileNotFound;1374 };1375 defer gpa.free(bytes);13761377 var hasher = std.crypto.hash.Blake3.init(.{});1378 hasher.update(bytes);1379 var raw: [32]u8 = undefined;1380 hasher.final(&raw);1381 const hex = std.fmt.bytesToHex(raw, .lower);1382 if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;13831384 var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1385 const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1386 return error.NameTooLong;13871388 {1389 const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1390 errors.error_info.setMessage("cannot write to {s}", .{install_path});1391 errors.error_info.setSuggestion("try: sudo nina update", .{});1392 return error.AccessDenied;1393 };1394 defer f.close(io);1395 f.writePositionalAll(io, bytes, 0) catch {1396 errors.error_info.setMessage("cannot write to {s}", .{install_path});1397 return error.AccessDenied;1398 };1399 try f.setPermissions(io, .fromMode(0o755));1400 }1401 errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};14021403 if (comptime builtin.os.tag == .macos) {1404 _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1405 }14061407 std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1408 error.AccessDenied => {1409 errors.error_info.setMessage("cannot replace {s}", .{install_path});1410 errors.error_info.setSuggestion("try: sudo nina update", .{});1411 return error.AccessDenied;1412 },1413 else => return e,1414 };1415}1416141714181419pub const NixFeatureStatus = struct {1420 nix_command: bool = false,1421 flakes: bool = false,14221423 pub fn allEnabled(self: NixFeatureStatus) bool {1424 return self.nix_command and self.flakes;1425 }1426};14271428fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1429 var lines = std.mem.splitScalar(u8, conf, '\n');1430 while (lines.next()) |line| {1431 const trimmed = std.mem.trim(u8, line, " \t");1432 if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1433 if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1434 if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1435 }1436}14371438pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1439 var status = NixFeatureStatus{};14401441 if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1442 defer gpa.free(conf);1443 scanConfFeatures(conf, &status);1444 }14451446 if (environ.get("HOME")) |home| {1447 var buf: [512]u8 = undefined;1448 const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1449 if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1450 defer gpa.free(conf);1451 scanConfFeatures(conf, &status);1452 }1453 }14541455 return status;1456}14571458pub fn isNixOS(io: std.Io) bool {1459 const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1460 file.close(io);1461 return true;1462}1463146414651466pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1467 const home = environ.get("HOME") orelse {1468 errors.error_info.setMessage("HOME not set", .{});1469 return error.ConfigNotFound;1470 };14711472 const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1473 defer gpa.free(dir_path);1474 const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1475 errdefer gpa.free(file_path);14761477 _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};14781479 const line = "experimental-features = nix-command flakes\n";1480 const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1481 (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1482 errors.error_info.setMessage("could not write {s}", .{file_path});1483 return error.FileNotFound;1484 });1485 defer file.close(io);14861487 const size = file.length(io) catch 0;1488 file.writePositionalAll(io, line, size) catch {1489 errors.error_info.setMessage("could not write {s}", .{file_path});1490 return error.FileNotFound;1491 };14921493 return file_path;1494}14951496149714981499150015011502pub const NIXOS_FEATURES_LINE =1503 "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";1504150515061507pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1508 const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1509 defer gpa.free(conf);1510 return std.mem.indexOf(u8, conf, "experimental-features") != null and1511 std.mem.indexOf(u8, conf, "nix-command") != null and1512 std.mem.indexOf(u8, conf, "flakes") != null;1513}15141515fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1516 if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1517 return captureLocal(gpa, io, &.{ "sudo", "cat", path });1518}151915201521152215231524pub fn appendFeaturesToNixosConfig(1525 gpa: std.mem.Allocator,1526 io: std.Io,1527 environ: *const std.process.Environ.Map,1528 path: []const u8,1529) !void {1530 const conf = readMaybeSudo(gpa, io, path) catch {1531 errors.error_info.setMessage("could not read {s}", .{path});1532 return error.ConfigNotFound;1533 };1534 defer gpa.free(conf);15351536 if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; 15371538 const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1539 errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1540 return error.MalformedConfig;1541 };15421543 const home = environ.get("HOME") orelse {1544 errors.error_info.setMessage("HOME not set", .{});1545 return error.ConfigNotFound;1546 };1547 const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1548 defer gpa.free(tmp_path);15491550 var buf: std.ArrayList(u8) = .empty;1551 defer buf.deinit(gpa);1552 try buf.appendSlice(gpa, conf[0..brace]);1553 if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1554 try buf.appendSlice(gpa, " # added by nina setup — flakes + the new nix CLI\n");1555 try buf.appendSlice(gpa, " ");1556 try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1557 try buf.append(gpa, '\n');1558 try buf.appendSlice(gpa, conf[brace..]);15591560 const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1561 errors.error_info.setMessage("could not write {s}", .{tmp_path});1562 return error.FileNotFound;1563 };1564 tmp.writePositionalAll(io, buf.items, 0) catch {1565 tmp.close(io);1566 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1567 errors.error_info.setMessage("could not write {s}", .{tmp_path});1568 return error.FileNotFound;1569 };1570 tmp.close(io);15711572 1573 1574 1575 const code = streamLocal(io, &.{1576 "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1577 }) catch {1578 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1579 errors.error_info.setMessage("could not write {s}", .{path});1580 return error.ProcessFailed;1581 };1582 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1583 if (code != 0) {1584 errors.error_info.setMessage("sudo cp into {s} failed", .{path});1585 return error.ProcessFailed;1586 }1587}