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}171172173174175176177178179pub fn dirHasFlake(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) bool {180 const flake_path = std.fs.path.join(gpa, &.{ dir, "flake.nix" }) catch return false;181 defer gpa.free(flake_path);182 return pathExists(io, flake_path);183}184185pub fn configHasFlake(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {186 if (!machine.local) return false;187 return dirHasFlake(gpa, io, machine.config_path);188}189190191192193fn useFlakeFlag(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {194 return configHasFlake(gpa, io, machine) and !std.mem.eql(u8, machine.config_path, "/etc/nixos");195}196197fn nixosRebuildRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, flake: bool) !u8 {198 if (flake) {199 return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb, "--flake", machine.config_path });200 }201 return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", verb });202}203204pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {205 const flake = useFlakeFlag(gpa, io, machine);206 if (flake) {207 output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});208 } else {209 output.printSubstep("nixos-rebuild switch", .{});210 }211 return nixosRebuildRun(io, machine, gpa, "switch", flake);212}213214pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {215 return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine));216}217218pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {219 return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine));220}221222223224225226227228229230231const GEN_LIST_SCRIPT =232 \\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 }'233;234235pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {236 const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });237 defer gpa.free(r.stderr);238 defer gpa.free(r.stdout);239 if (r.exit_code != 0) return error.ProcessFailed;240 return parseGenerations(gpa, r.stdout);241}242243fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {244 var gens: std.ArrayList(types.GenerationInfo) = .empty;245 var lines = std.mem.splitScalar(u8, output_str, '\n');246 while (lines.next()) |line| {247 const trimmed = std.mem.trim(u8, line, " \t");248 if (trimmed.len == 0) continue;249 var parts = std.mem.tokenizeAny(u8, trimmed, " \t");250 const num_str = parts.next() orelse continue;251 const date_str = parts.next() orelse continue;252 const time_str = parts.next() orelse continue;253 const rest = parts.rest();254 const current = std.mem.indexOf(u8, rest, "current") != null;255 const num = std.fmt.parseInt(u32, num_str, 10) catch continue;256 try gens.append(gpa, .{257 .number = num,258 .date = try gpa.dupe(u8, date_str),259 .time = try gpa.dupe(u8, time_str),260 .current = current,261 });262 }263 return gens.toOwnedSlice(gpa);264}265266pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {267 const gens = try getGenerations(gpa, io, machine);268 defer gpa.free(gens);269 for (gens) |g| {270 if (g.current) return g.number;271 }272 return 0;273}274275pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {276 277 278 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 });279 defer gpa.free(cmd);280 return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });281}282283pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {284 return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });285}286287pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {288 const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});289 defer gpa.free(n_str);290 return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });291}292293pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {294 return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });295}296297298299pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {300 if (delete_old) {301 return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });302 }303 304 305 306 const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });307 defer gpa.free(cmd);308 return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });309}310311312313pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {314 const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });315 defer gpa.free(r.stderr);316 defer gpa.free(r.stdout);317 if (r.exit_code != 0) return error.ProcessFailed;318 return parseChannels(gpa, r.stdout);319}320321fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {322 var channels: std.ArrayList(types.ChannelInfo) = .empty;323 var lines = std.mem.splitScalar(u8, output_str, '\n');324 while (lines.next()) |line| {325 const trimmed = std.mem.trim(u8, line, " \t\r");326 if (trimmed.len == 0) continue;327 const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;328 try channels.append(gpa, .{329 .name = try gpa.dupe(u8, trimmed[0..space]),330 .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),331 });332 }333 return channels.toOwnedSlice(gpa);334}335336pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {337 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });338}339340pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {341 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });342}343344pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {345 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });346}347348349350pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {351 const cmd: []const []const u8 = if (user)352 &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }353 else354 &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };355 const r = try capture(gpa, io, machine, cmd);356 defer gpa.free(r.stderr);357 defer gpa.free(r.stdout);358 if (r.exit_code != 0) return error.ProcessFailed;359 return parseServices(gpa, r.stdout);360}361362fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {363 var svcs: std.ArrayList(types.ServiceInfo) = .empty;364 var lines = std.mem.splitScalar(u8, output_str, '\n');365 while (lines.next()) |line| {366 const trimmed = std.mem.trim(u8, line, " \t\r");367 if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; 368 var parts = std.mem.tokenizeAny(u8, trimmed, " \t");369 const name = parts.next() orelse continue;370 _ = parts.next(); 371 const active_str = parts.next() orelse continue;372 const sub_str = parts.next() orelse "unknown";373374 const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))375 (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)376 else if (std.mem.eql(u8, active_str, "failed"))377 .failed378 else379 .inactive;380381 try svcs.append(gpa, .{382 .name = try gpa.dupe(u8, name),383 .state = state,384 .uptime = null,385 });386 }387 return svcs.toOwnedSlice(gpa);388}389390pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {391 392 393 if (user) {394 return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });395 }396 return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });397}398399pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {400 const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});401 defer gpa.free(n_str);402 if (user) {403 if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });404 return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });405 }406 if (follow) {407 return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });408 }409 return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });410}411412413414pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {415 const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});416 defer gpa.free(pkg_ref);417 418 419 return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });420}421422pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {423 424 425 return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });426}427428pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {429 const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });430 defer gpa.free(r.stderr);431 if (r.exit_code != 0) return error.ProcessFailed;432 return r.stdout;433}434435436pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {437 const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });438 defer gpa.free(r.stderr);439 if (r.exit_code != 0) {440 gpa.free(r.stdout);441 return error.ProcessFailed;442 }443 return r.stdout;444}445446447448449450451pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {452 const js = profileListJson(gpa, io, machine) catch return null;453 defer gpa.free(js);454 return profileJsonNinaElement(gpa, js);455}456457pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {458 const name = profileNinaElement(gpa, io, machine) orelse return false;459 gpa.free(name);460 return true;461}462463464465466467fn storePathIsNina(path: []const u8) bool {468 const prefix = "/nix/store/";469 if (!std.mem.startsWith(u8, path, prefix)) return false;470 const rel = path[prefix.len..];471 472 const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];473 if (entry.len < 34) return false; 474 const pname_ver = entry[33..]; 475 return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");476}477478479480481482483fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {484 var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;485 defer parsed.deinit();486 const root = parsed.value;487 if (root != .object) return null;488 const elements = root.object.get("elements") orelse return null;489 switch (elements) {490 .object => |obj| {491 492 if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;493 494 495 496 var it = obj.iterator();497 while (it.next()) |kv| {498 const val = kv.value_ptr.*;499 if (val != .object) continue;500 const sps = val.object.get("storePaths") orelse continue;501 if (sps != .array) continue;502 for (sps.array.items) |sp| {503 if (sp == .string and storePathIsNina(sp.string))504 return gpa.dupe(u8, kv.key_ptr.*) catch null;505 }506 }507 return null;508 },509 .array => |arr| {510 511 for (arr.items) |el| {512 if (el != .object) continue;513 const ap = el.object.get("attrPath") orelse continue;514 if (ap != .string) continue;515 if (std.mem.eql(u8, ap.string, "nina") or516 std.mem.endsWith(u8, ap.string, ".nina"))517 return gpa.dupe(u8, "nina") catch null;518 519 520 const sps = el.object.get("storePaths") orelse continue;521 if (sps != .array) continue;522 for (sps.array.items) |sp| {523 if (sp != .string) continue;524 if (!storePathIsNina(sp.string)) continue;525 const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;526 const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;527 return gpa.dupe(u8, el_name) catch null;528 }529 }530 return null;531 },532 else => return null,533 }534}535536test "profileJsonNinaElement finds element name from profile JSON" {537 const a = std.testing.allocator;538539 540 const named =541 \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},542 \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}543 ;544 const r1 = profileJsonNinaElement(a, named);545 defer if (r1) |n| a.free(n);546 try std.testing.expectEqualStrings("nina", r1.?);547548 549 const default_key =550 \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}551 ;552 const r2 = profileJsonNinaElement(a, default_key);553 defer if (r2) |n| a.free(n);554 try std.testing.expectEqualStrings("default", r2.?);555556 557 const decoy =558 \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}559 ;560 const r3 = profileJsonNinaElement(a, decoy);561 try std.testing.expectEqual(@as(?[]const u8, null), r3);562563 564 const arr =565 \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}566 ;567 const r4 = profileJsonNinaElement(a, arr);568 defer if (r4) |n| a.free(n);569 try std.testing.expectEqualStrings("nina", r4.?);570571 572 const arr_default =573 \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}574 ;575 const r5 = profileJsonNinaElement(a, arr_default);576 defer if (r5) |n| a.free(n);577 try std.testing.expectEqualStrings("default", r5.?);578579 580 try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));581 try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));582}583584585586587pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {588 const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });589 defer gpa.free(r.stderr);590 if (r.exit_code != 0) {591 gpa.free(r.stdout);592 return error.ProcessFailed;593 }594 return r.stdout;595}596597pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {598 return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });599}600601602603pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {604 return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });605}606607pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {608 return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });609}610611pub const SystemStatus = struct { size: []u8, age: []u8 };612613614615616617const STATUS_SCRIPT =618 \\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} ))"619;620621pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {622 const unknown = SystemStatus{623 .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },624 .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },625 };626 const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;627 defer gpa.free(r.stdout);628 defer gpa.free(r.stderr);629 if (r.exit_code != 0) return unknown;630631 var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");632 const sz_str = it.next() orelse return unknown;633 const age_str = it.next() orelse return unknown;634 const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;635 const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;636637 gpa.free(unknown.size);638 gpa.free(unknown.age);639 return .{640 .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),641 .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),642 };643}644645646647648pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {649 const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch650 return gpa.dupe(u8, "unknown");651 defer gpa.free(r.stderr);652 const state = std.mem.trim(u8, r.stdout, " \t\n\r");653 const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");654 gpa.free(r.stdout);655 return owned;656}657658fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {659 if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});660 if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});661 if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});662 return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});663}664665pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {666 return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });667}668669pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {670 671 672 673 674 675 676 const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });677 defer gpa.free(pi.stdout);678 defer gpa.free(pi.stderr);679680 const scan = scanStoreJson(pi.stdout);681 const total_owned = try humanSize(gpa, scan.total_bytes);682683 return .{684 .total_size = total_owned,685 .live_paths = scan.count,686 .reclaimable_paths = 0,687 };688}689690const StoreScan = struct { count: u64, total_bytes: u64 };691692693694695fn scanStoreJson(json_str: []const u8) StoreScan {696 const needle = "\"narSize\":";697 var count: u64 = 0;698 var total: u64 = 0;699 var i: usize = 0;700 while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {701 var j = pos + needle.len;702 while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}703 var val: u64 = 0;704 var any = false;705 while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {706 val = val * 10 + (json_str[j] - '0');707 any = true;708 }709 if (any) {710 count += 1;711 total += val;712 }713 i = j;714 }715 return .{ .count = count, .total_bytes = total };716}717718fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {719 const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };720 var val: f64 = @floatFromInt(bytes);721 var unit: usize = 0;722 while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;723 if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });724 return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });725}726727pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {728 729 730 const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});731 defer gpa.free(expr);732 const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });733 defer gpa.free(r.stderr);734 if (r.exit_code != 0) {735 gpa.free(r.stdout);736 return error.ProcessFailed;737 }738 return r.stdout;739}740741742743pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {744 if (input) |inp| {745 return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });746 }747 return stream(io, machine, gpa, &.{ "nix", "flake", "update" });748}749750751752753pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {754 return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });755}756757pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {758 return stream(io, machine, gpa, &.{ "nix", "flake", "check" });759}760761pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {762 return stream(io, machine, gpa, &.{ "nix", "flake", "init" });763}764765pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {766 return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });767}768769pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {770 return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });771}772773pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {774 const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });775 defer gpa.free(r.stderr);776 if (r.exit_code != 0) {777 gpa.free(r.stdout);778 return error.ProcessFailed;779 }780 return r.stdout;781}782783784785pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {786 if (attr) |a| {787 const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});788 defer gpa.free(ref);789 return stream(io, machine, gpa, &.{ "nix", "build", ref });790 }791 return stream(io, machine, gpa, &.{ "nix", "build" });792}793794pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {795 796 const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");797 if (is_url) {798 return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });799 }800 801 if (std.mem.indexOfScalar(u8, pkg, '#') != null) {802 return stream(io, machine, gpa, &.{ "nix", "run", pkg });803 }804 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});805 defer gpa.free(ref);806 return stream(io, machine, gpa, &.{ "nix", "run", ref });807}808809pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {810 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});811 defer gpa.free(ref);812 return stream(io, machine, gpa, &.{ "nix", "shell", ref });813}814815pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {816 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});817 defer gpa.free(ref);818 const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});819 defer gpa.free(ps1);820 return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);821}822823pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {824 if (run_cmd) |cmd| {825 826 return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });827 }828 return stream(io, machine, gpa, &.{ "nix", "develop" });829}830831pub 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 {832 if (run_cmd) |cmd| {833 834 return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });835 }836 return streamEnv(io, machine, gpa, &.{ "nix", "develop" }, base_env, "(nina: dev) -> ");837}838839pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {840 return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });841}842843844845pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {846 if (check) {847 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });848 }849 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });850}851852853854pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {855 const r = try capture(gpa, io, machine, &.{"nixos-version"});856 defer gpa.free(r.stderr);857 if (r.exit_code != 0) {858 gpa.free(r.stdout);859 return error.ProcessFailed;860 }861 return r.stdout;862}863864pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {865 const r = try capture(gpa, io, machine, &.{ "uname", "-r" });866 defer gpa.free(r.stderr);867 if (r.exit_code != 0) {868 gpa.free(r.stdout);869 return error.ProcessFailed;870 }871 return r.stdout;872}873874pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {875 const r = try capture(gpa, io, machine, &.{"uptime"});876 defer gpa.free(r.stderr);877 if (r.exit_code != 0) {878 gpa.free(r.stdout);879 return error.ProcessFailed;880 }881 return r.stdout;882}883884885886pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {887 const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });888 defer gpa.free(r.stderr);889 defer gpa.free(r.stdout);890 if (r.exit_code != 0) return error.ProcessFailed;891 return parseBootEntries(gpa, r.stdout);892}893894fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {895 var entries: std.ArrayList(types.BootEntry) = .empty;896 var lines = std.mem.splitScalar(u8, output_str, '\n');897 while (lines.next()) |line| {898 const trimmed = std.mem.trim(u8, line, " \t\r");899 if (std.mem.startsWith(u8, trimmed, "title:")) {900 const title = std.mem.trim(u8, trimmed[6..], " \t");901 const current = std.mem.indexOf(u8, title, "(current)") != null;902 try entries.append(gpa, .{903 .title = try gpa.dupe(u8, title),904 .current = current,905 });906 }907 }908 return entries.toOwnedSlice(gpa);909}910911912913pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {914 return stream(io, machine, gpa, &.{ "nix", "why-depends", ".#", pkg });915}916917pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {918 return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", pkg });919}920921pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {922 923 924 925 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});926 defer gpa.free(ref);927 const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-S", "-h", ref });928 defer gpa.free(r.stderr);929 defer gpa.free(r.stdout);930 if (r.exit_code != 0) return error.ProcessFailed;931932 const line = std.mem.trim(u8, r.stdout, " \t\n\r");933 var it = std.mem.tokenizeAny(u8, line, " \t");934 _ = it.next(); 935 const size = std.mem.trim(u8, it.rest(), " \t");936 if (size.len == 0) return error.ProcessFailed;937 return gpa.dupe(u8, size);938}939940pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {941 return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", pkg });942}943944945946pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {947 const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });948 defer gpa.free(r.stderr);949 if (r.exit_code != 0) {950 gpa.free(r.stdout);951 return error.ProcessFailed;952 }953 return r.stdout;954}955956pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {957 const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });958 defer gpa.free(r.stderr);959 if (r.exit_code != 0) {960 gpa.free(r.stdout);961 return error.ProcessFailed;962 }963 return r.stdout;964}965966967968pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {969 970 971}972973pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {974 if (line) |l| {975 const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});976 defer gpa.free(line_arg);977 return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });978 }979 return stream(io, &types.Machine{}, gpa, &.{ editor, path });980}981982pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {983 const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});984 defer gpa.free(a_str);985 const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});986 defer gpa.free(b_str);987 988 if (output.colorEnabled()) {989 return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });990 }991 992 993 const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });994 defer gpa.free(r.stdout);995 defer gpa.free(r.stderr);996 const cleaned = try stripAnsi(gpa, r.stdout);997 defer gpa.free(cleaned);998 output.raw(cleaned);999 return r.exit_code;1000}1001100210031004fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1005 var out: std.ArrayList(u8) = .empty;1006 errdefer out.deinit(gpa);1007 var i: usize = 0;1008 while (i < input.len) {1009 if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1010 i += 2;1011 while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1012 if (i < input.len) i += 1; 1013 continue;1014 }1015 try out.append(gpa, input[i]);1016 i += 1;1017 }1018 return out.toOwnedSlice(gpa);1019}10201021test "stripAnsi removes CSI color sequences" {1022 const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1023 defer std.testing.allocator.free(cleaned);1024 try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1025}1026102710281029pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1030 var checks: std.ArrayList(types.DoctorCheck) = .empty;10311032 1033 {1034 const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1035 defer gpa.free(r.stdout);1036 defer gpa.free(r.stderr);1037 const active = std.mem.indexOf(u8, r.stdout, "active") != null;1038 try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1039 }10401041 1042 {1043 const r = try capture(gpa, io, machine, &.{ "sudo", "nixos-rebuild", "dry-build" });1044 defer gpa.free(r.stdout);1045 defer gpa.free(r.stderr);1046 try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1047 }10481049 1050 {1051 const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1052 defer gpa.free(r.stdout);1053 defer gpa.free(r.stderr);1054 const has_channel = r.exit_code == 0 and r.stdout.len > 0;1055 try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1056 }10571058 return checks.toOwnedSlice(gpa);1059}10601061106210631064106510661067pub const HomeManagerMode = enum {1068 1069 standalone,1070 1071 1072 module,1073 none,1074};10751076fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1077 const home = environ.get("HOME") orelse return null;1078 return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1079}108010811082pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1083 const dir = homeConfigDir(gpa, environ) orelse return null;1084 defer gpa.free(dir);1085 return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1086}10871088pub fn pathExists(io: std.Io, path: []const u8) bool {1089 const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1090 f.close(io);1091 return true;1092}1093109410951096fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1097 var buf: [256]u8 = undefined;1098 const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1099 const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1100 defer gpa.free(r.stdout);1101 defer gpa.free(r.stderr);1102 return switch (r.term) {1103 .exited => |code| code == 0,1104 else => false,1105 };1106}11071108pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1109 if (commandExists(gpa, io, "home-manager")) return .standalone;1110 if (homeNixPath(gpa, environ)) |p| {1111 defer gpa.free(p);1112 if (pathExists(io, p)) return .module;1113 }1114 return .none;1115}11161117111811191120pub fn homeFlakeRef(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1121 const dir = homeConfigDir(gpa, environ) orelse return null;1122 defer gpa.free(dir);1123 const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch return null;1124 defer gpa.free(flake);1125 if (!pathExists(io, flake)) return null;1126 const user = environ.get("USER") orelse "default";1127 return std.fmt.allocPrint(gpa, "{s}#{s}", .{ dir, user }) catch null;1128}11291130pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1131 return stream(io, machine, gpa, &.{ "home-manager", "switch" });1132}11331134pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8) !u8 {1135 return stream(io, machine, gpa, &.{ "home-manager", "switch", "--flake", flake_ref });1136}1137113811391140pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1141 return stream(io, machine, gpa, &.{ "home-manager", "switch", "--rollback" });1142}1143114411451146pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1147 return stream(io, machine, gpa, &.{ "home-manager", "build" });1148}11491150pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1151 const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1152 defer gpa.free(r.stderr);1153 if (r.exit_code != 0) {1154 gpa.free(r.stdout);1155 return error.ProcessFailed;1156 }1157 return r.stdout;1158}115911601161pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1162 const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1163 defer gpa.free(r.stderr);1164 if (r.exit_code != 0) {1165 gpa.free(r.stdout);1166 return error.ProcessFailed;1167 }1168 return r.stdout;1169}1170117111721173pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1174 if (output.colorEnabled()) {1175 return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1176 }1177 const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1178 defer gpa.free(r.stdout);1179 defer gpa.free(r.stderr);1180 const cleaned = try stripAnsi(gpa, r.stdout);1181 defer gpa.free(cleaned);1182 output.raw(cleaned);1183 return r.exit_code;1184}1185118611871188pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1189 const home = environ.get("HOME") orelse return error.FileNotFound;1190 const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1191 defer gpa.free(path);1192 const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1193 if (last == 0) return content;11941195 1196 1197 var lines: std.ArrayList([]const u8) = .empty;1198 defer lines.deinit(gpa);1199 var it = std.mem.splitScalar(u8, content, '\n');1200 while (it.next()) |line| {1201 if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1202 try lines.append(gpa, line);1203 }1204 if (lines.items.len <= last) return content;12051206 var out: std.ArrayList(u8) = .empty;1207 errdefer out.deinit(gpa);1208 for (lines.items[lines.items.len - last ..]) |line| {1209 try out.appendSlice(gpa, line);1210 try out.append(gpa, '\n');1211 }1212 gpa.free(content);1213 return out.toOwnedSlice(gpa);1214}121512161217121812191220pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1221 const home = environ.get("HOME") orelse return;1222 var buf: [512]u8 = undefined;1223 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1224 const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1225 file.close(io);1226}12271228pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1229 const home = environ.get("HOME") orelse return false;1230 var buf: [512]u8 = undefined;1231 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1232 if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1233 f.close(io);1234 std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1235 return true;1236 } else |_| {1237 return false;1238 }1239}12401241pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1242 const home = environ.get("HOME") orelse return;1243 var path_buf: [512]u8 = undefined;1244 const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1245 const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1246 (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1247 defer file.close(io);1248 const size = file.length(io) catch 0;1249 file.writePositionalAll(io, entry, size) catch {};1250}125112521253125412551256pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1257 const argv = [_][]const u8{1258 "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1259 };1260 const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1261 defer gpa.free(result.stderr);12621263 const marker = "\nHTTP_STATUS:";1264 const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1265 gpa.free(result.stdout);1266 return error.NetworkError;1267 };1268 const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1269 const status = std.fmt.parseInt(u16, status_str, 10) catch {1270 gpa.free(result.stdout);1271 return error.NetworkError;1272 };1273 if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1274 if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1275 const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1276 gpa.free(result.stdout);1277 return e;1278 };1279 gpa.free(result.stdout);1280 return body;1281}1282128312841285pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1286 const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1287 errdefer gpa.free(tmp_path);12881289 var child = std.process.spawn(io, .{1290 .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1291 .stdin = .close,1292 .stdout = .close,1293 .stderr = .inherit,1294 }) catch return error.NetworkError;1295 const term = child.wait(io) catch return error.NetworkError;1296 switch (term) {1297 .exited => |c| if (c != 0) return error.NetworkError,1298 else => return error.NetworkError,1299 }1300 return tmp_path;1301}130213031304pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1305 const len = try std.process.executablePath(io, buf);1306 return buf[0..len];1307}13081309131013111312pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1313 const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1314 errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1315 return error.FileNotFound;1316 };1317 defer gpa.free(bytes);13181319 var hasher = std.crypto.hash.Blake3.init(.{});1320 hasher.update(bytes);1321 var raw: [32]u8 = undefined;1322 hasher.final(&raw);1323 const hex = std.fmt.bytesToHex(raw, .lower);1324 if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;13251326 var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1327 const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1328 return error.NameTooLong;13291330 {1331 const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1332 errors.error_info.setMessage("cannot write to {s}", .{install_path});1333 errors.error_info.setSuggestion("try: sudo nina update", .{});1334 return error.AccessDenied;1335 };1336 defer f.close(io);1337 f.writePositionalAll(io, bytes, 0) catch {1338 errors.error_info.setMessage("cannot write to {s}", .{install_path});1339 return error.AccessDenied;1340 };1341 try f.setPermissions(io, .fromMode(0o755));1342 }1343 errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};13441345 if (comptime builtin.os.tag == .macos) {1346 _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1347 }13481349 std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1350 error.AccessDenied => {1351 errors.error_info.setMessage("cannot replace {s}", .{install_path});1352 errors.error_info.setSuggestion("try: sudo nina update", .{});1353 return error.AccessDenied;1354 },1355 else => return e,1356 };1357}1358135913601361pub const NixFeatureStatus = struct {1362 nix_command: bool = false,1363 flakes: bool = false,13641365 pub fn allEnabled(self: NixFeatureStatus) bool {1366 return self.nix_command and self.flakes;1367 }1368};13691370fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1371 var lines = std.mem.splitScalar(u8, conf, '\n');1372 while (lines.next()) |line| {1373 const trimmed = std.mem.trim(u8, line, " \t");1374 if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1375 if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1376 if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1377 }1378}13791380pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1381 var status = NixFeatureStatus{};13821383 if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1384 defer gpa.free(conf);1385 scanConfFeatures(conf, &status);1386 }13871388 if (environ.get("HOME")) |home| {1389 var buf: [512]u8 = undefined;1390 const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1391 if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1392 defer gpa.free(conf);1393 scanConfFeatures(conf, &status);1394 }1395 }13961397 return status;1398}13991400pub fn isNixOS(io: std.Io) bool {1401 const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1402 file.close(io);1403 return true;1404}1405140614071408pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1409 const home = environ.get("HOME") orelse {1410 errors.error_info.setMessage("HOME not set", .{});1411 return error.ConfigNotFound;1412 };14131414 const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1415 defer gpa.free(dir_path);1416 const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1417 errdefer gpa.free(file_path);14181419 _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};14201421 const line = "experimental-features = nix-command flakes\n";1422 const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1423 (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1424 errors.error_info.setMessage("could not write {s}", .{file_path});1425 return error.FileNotFound;1426 });1427 defer file.close(io);14281429 const size = file.length(io) catch 0;1430 file.writePositionalAll(io, line, size) catch {1431 errors.error_info.setMessage("could not write {s}", .{file_path});1432 return error.FileNotFound;1433 };14341435 return file_path;1436}14371438143914401441144214431444pub const NIXOS_FEATURES_LINE =1445 "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";1446144714481449pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1450 const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1451 defer gpa.free(conf);1452 return std.mem.indexOf(u8, conf, "experimental-features") != null and1453 std.mem.indexOf(u8, conf, "nix-command") != null and1454 std.mem.indexOf(u8, conf, "flakes") != null;1455}14561457fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1458 if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1459 return captureLocal(gpa, io, &.{ "sudo", "cat", path });1460}146114621463146414651466pub fn appendFeaturesToNixosConfig(1467 gpa: std.mem.Allocator,1468 io: std.Io,1469 environ: *const std.process.Environ.Map,1470 path: []const u8,1471) !void {1472 const conf = readMaybeSudo(gpa, io, path) catch {1473 errors.error_info.setMessage("could not read {s}", .{path});1474 return error.ConfigNotFound;1475 };1476 defer gpa.free(conf);14771478 if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; 14791480 const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1481 errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1482 return error.MalformedConfig;1483 };14841485 const home = environ.get("HOME") orelse {1486 errors.error_info.setMessage("HOME not set", .{});1487 return error.ConfigNotFound;1488 };1489 const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1490 defer gpa.free(tmp_path);14911492 var buf: std.ArrayList(u8) = .empty;1493 defer buf.deinit(gpa);1494 try buf.appendSlice(gpa, conf[0..brace]);1495 if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1496 try buf.appendSlice(gpa, " # added by nina setup — flakes + the new nix CLI\n");1497 try buf.appendSlice(gpa, " ");1498 try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1499 try buf.append(gpa, '\n');1500 try buf.appendSlice(gpa, conf[brace..]);15011502 const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1503 errors.error_info.setMessage("could not write {s}", .{tmp_path});1504 return error.FileNotFound;1505 };1506 tmp.writePositionalAll(io, buf.items, 0) catch {1507 tmp.close(io);1508 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1509 errors.error_info.setMessage("could not write {s}", .{tmp_path});1510 return error.FileNotFound;1511 };1512 tmp.close(io);15131514 1515 1516 1517 const code = streamLocal(io, &.{1518 "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1519 }) catch {1520 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1521 errors.error_info.setMessage("could not write {s}", .{path});1522 return error.ProcessFailed;1523 };1524 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1525 if (code != 0) {1526 errors.error_info.setMessage("sudo cp into {s} failed", .{path});1527 return error.ProcessFailed;1528 }1529}