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 1044 {1045 const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1046 &.{ "sudo", "nixos-rebuild", "dry-build", "--flake", machine.config_path }1047 else1048 &.{ "sudo", "nixos-rebuild", "dry-build" };1049 const r = try capture(gpa, io, machine, argv);1050 defer gpa.free(r.stdout);1051 defer gpa.free(r.stderr);1052 try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1053 }10541055 1056 {1057 const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1058 defer gpa.free(r.stdout);1059 defer gpa.free(r.stderr);1060 const has_channel = r.exit_code == 0 and r.stdout.len > 0;1061 try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1062 }10631064 return checks.toOwnedSlice(gpa);1065}10661067106810691070107110721073pub const HomeManagerMode = enum {1074 1075 standalone,1076 1077 1078 module,1079 none,1080};10811082fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1083 const home = environ.get("HOME") orelse return null;1084 return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1085}108610871088pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1089 const dir = homeConfigDir(gpa, environ) orelse return null;1090 defer gpa.free(dir);1091 return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1092}10931094pub fn pathExists(io: std.Io, path: []const u8) bool {1095 const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1096 f.close(io);1097 return true;1098}1099110011011102fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1103 var buf: [256]u8 = undefined;1104 const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1105 const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1106 defer gpa.free(r.stdout);1107 defer gpa.free(r.stderr);1108 return switch (r.term) {1109 .exited => |code| code == 0,1110 else => false,1111 };1112}11131114pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1115 if (commandExists(gpa, io, "home-manager")) return .standalone;1116 if (homeNixPath(gpa, environ)) |p| {1117 defer gpa.free(p);1118 if (pathExists(io, p)) return .module;1119 }1120 return .none;1121}11221123112411251126pub fn homeFlakeRef(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1127 const dir = homeConfigDir(gpa, environ) orelse return null;1128 defer gpa.free(dir);1129 const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch return null;1130 defer gpa.free(flake);1131 if (!pathExists(io, flake)) return null;1132 const user = environ.get("USER") orelse "default";1133 return std.fmt.allocPrint(gpa, "{s}#{s}", .{ dir, user }) catch null;1134}11351136pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1137 return stream(io, machine, gpa, &.{ "home-manager", "switch" });1138}11391140pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8) !u8 {1141 return stream(io, machine, gpa, &.{ "home-manager", "switch", "--flake", flake_ref });1142}1143114411451146pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1147 return stream(io, machine, gpa, &.{ "home-manager", "switch", "--rollback" });1148}1149115011511152pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1153 return stream(io, machine, gpa, &.{ "home-manager", "build" });1154}11551156pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1157 const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1158 defer gpa.free(r.stderr);1159 if (r.exit_code != 0) {1160 gpa.free(r.stdout);1161 return error.ProcessFailed;1162 }1163 return r.stdout;1164}116511661167pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1168 const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1169 defer gpa.free(r.stderr);1170 if (r.exit_code != 0) {1171 gpa.free(r.stdout);1172 return error.ProcessFailed;1173 }1174 return r.stdout;1175}1176117711781179pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1180 if (output.colorEnabled()) {1181 return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1182 }1183 const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1184 defer gpa.free(r.stdout);1185 defer gpa.free(r.stderr);1186 const cleaned = try stripAnsi(gpa, r.stdout);1187 defer gpa.free(cleaned);1188 output.raw(cleaned);1189 return r.exit_code;1190}1191119211931194pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1195 const home = environ.get("HOME") orelse return error.FileNotFound;1196 const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1197 defer gpa.free(path);1198 const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1199 if (last == 0) return content;12001201 1202 1203 var lines: std.ArrayList([]const u8) = .empty;1204 defer lines.deinit(gpa);1205 var it = std.mem.splitScalar(u8, content, '\n');1206 while (it.next()) |line| {1207 if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1208 try lines.append(gpa, line);1209 }1210 if (lines.items.len <= last) return content;12111212 var out: std.ArrayList(u8) = .empty;1213 errdefer out.deinit(gpa);1214 for (lines.items[lines.items.len - last ..]) |line| {1215 try out.appendSlice(gpa, line);1216 try out.append(gpa, '\n');1217 }1218 gpa.free(content);1219 return out.toOwnedSlice(gpa);1220}122112221223122412251226pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1227 const home = environ.get("HOME") orelse return;1228 var buf: [512]u8 = undefined;1229 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1230 const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1231 file.close(io);1232}12331234pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1235 const home = environ.get("HOME") orelse return false;1236 var buf: [512]u8 = undefined;1237 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1238 if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1239 f.close(io);1240 std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1241 return true;1242 } else |_| {1243 return false;1244 }1245}12461247pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1248 const home = environ.get("HOME") orelse return;1249 var path_buf: [512]u8 = undefined;1250 const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1251 const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1252 (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1253 defer file.close(io);1254 const size = file.length(io) catch 0;1255 file.writePositionalAll(io, entry, size) catch {};1256}125712581259126012611262pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1263 const argv = [_][]const u8{1264 "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1265 };1266 const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1267 defer gpa.free(result.stderr);12681269 const marker = "\nHTTP_STATUS:";1270 const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1271 gpa.free(result.stdout);1272 return error.NetworkError;1273 };1274 const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1275 const status = std.fmt.parseInt(u16, status_str, 10) catch {1276 gpa.free(result.stdout);1277 return error.NetworkError;1278 };1279 if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1280 if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1281 const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1282 gpa.free(result.stdout);1283 return e;1284 };1285 gpa.free(result.stdout);1286 return body;1287}1288128912901291pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1292 const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1293 errdefer gpa.free(tmp_path);12941295 var child = std.process.spawn(io, .{1296 .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1297 .stdin = .close,1298 .stdout = .close,1299 .stderr = .inherit,1300 }) catch return error.NetworkError;1301 const term = child.wait(io) catch return error.NetworkError;1302 switch (term) {1303 .exited => |c| if (c != 0) return error.NetworkError,1304 else => return error.NetworkError,1305 }1306 return tmp_path;1307}130813091310pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1311 const len = try std.process.executablePath(io, buf);1312 return buf[0..len];1313}13141315131613171318pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1319 const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1320 errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1321 return error.FileNotFound;1322 };1323 defer gpa.free(bytes);13241325 var hasher = std.crypto.hash.Blake3.init(.{});1326 hasher.update(bytes);1327 var raw: [32]u8 = undefined;1328 hasher.final(&raw);1329 const hex = std.fmt.bytesToHex(raw, .lower);1330 if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;13311332 var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1333 const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1334 return error.NameTooLong;13351336 {1337 const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1338 errors.error_info.setMessage("cannot write to {s}", .{install_path});1339 errors.error_info.setSuggestion("try: sudo nina update", .{});1340 return error.AccessDenied;1341 };1342 defer f.close(io);1343 f.writePositionalAll(io, bytes, 0) catch {1344 errors.error_info.setMessage("cannot write to {s}", .{install_path});1345 return error.AccessDenied;1346 };1347 try f.setPermissions(io, .fromMode(0o755));1348 }1349 errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};13501351 if (comptime builtin.os.tag == .macos) {1352 _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1353 }13541355 std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1356 error.AccessDenied => {1357 errors.error_info.setMessage("cannot replace {s}", .{install_path});1358 errors.error_info.setSuggestion("try: sudo nina update", .{});1359 return error.AccessDenied;1360 },1361 else => return e,1362 };1363}1364136513661367pub const NixFeatureStatus = struct {1368 nix_command: bool = false,1369 flakes: bool = false,13701371 pub fn allEnabled(self: NixFeatureStatus) bool {1372 return self.nix_command and self.flakes;1373 }1374};13751376fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1377 var lines = std.mem.splitScalar(u8, conf, '\n');1378 while (lines.next()) |line| {1379 const trimmed = std.mem.trim(u8, line, " \t");1380 if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1381 if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1382 if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1383 }1384}13851386pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1387 var status = NixFeatureStatus{};13881389 if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1390 defer gpa.free(conf);1391 scanConfFeatures(conf, &status);1392 }13931394 if (environ.get("HOME")) |home| {1395 var buf: [512]u8 = undefined;1396 const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1397 if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1398 defer gpa.free(conf);1399 scanConfFeatures(conf, &status);1400 }1401 }14021403 return status;1404}14051406pub fn isNixOS(io: std.Io) bool {1407 const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1408 file.close(io);1409 return true;1410}1411141214131414pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1415 const home = environ.get("HOME") orelse {1416 errors.error_info.setMessage("HOME not set", .{});1417 return error.ConfigNotFound;1418 };14191420 const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1421 defer gpa.free(dir_path);1422 const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1423 errdefer gpa.free(file_path);14241425 _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};14261427 const line = "experimental-features = nix-command flakes\n";1428 const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1429 (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1430 errors.error_info.setMessage("could not write {s}", .{file_path});1431 return error.FileNotFound;1432 });1433 defer file.close(io);14341435 const size = file.length(io) catch 0;1436 file.writePositionalAll(io, line, size) catch {1437 errors.error_info.setMessage("could not write {s}", .{file_path});1438 return error.FileNotFound;1439 };14401441 return file_path;1442}14431444144514461447144814491450pub const NIXOS_FEATURES_LINE =1451 "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";1452145314541455pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1456 const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1457 defer gpa.free(conf);1458 return std.mem.indexOf(u8, conf, "experimental-features") != null and1459 std.mem.indexOf(u8, conf, "nix-command") != null and1460 std.mem.indexOf(u8, conf, "flakes") != null;1461}14621463fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1464 if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1465 return captureLocal(gpa, io, &.{ "sudo", "cat", path });1466}146714681469147014711472pub fn appendFeaturesToNixosConfig(1473 gpa: std.mem.Allocator,1474 io: std.Io,1475 environ: *const std.process.Environ.Map,1476 path: []const u8,1477) !void {1478 const conf = readMaybeSudo(gpa, io, path) catch {1479 errors.error_info.setMessage("could not read {s}", .{path});1480 return error.ConfigNotFound;1481 };1482 defer gpa.free(conf);14831484 if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; 14851486 const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1487 errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1488 return error.MalformedConfig;1489 };14901491 const home = environ.get("HOME") orelse {1492 errors.error_info.setMessage("HOME not set", .{});1493 return error.ConfigNotFound;1494 };1495 const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1496 defer gpa.free(tmp_path);14971498 var buf: std.ArrayList(u8) = .empty;1499 defer buf.deinit(gpa);1500 try buf.appendSlice(gpa, conf[0..brace]);1501 if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1502 try buf.appendSlice(gpa, " # added by nina setup — flakes + the new nix CLI\n");1503 try buf.appendSlice(gpa, " ");1504 try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1505 try buf.append(gpa, '\n');1506 try buf.appendSlice(gpa, conf[brace..]);15071508 const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1509 errors.error_info.setMessage("could not write {s}", .{tmp_path});1510 return error.FileNotFound;1511 };1512 tmp.writePositionalAll(io, buf.items, 0) catch {1513 tmp.close(io);1514 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1515 errors.error_info.setMessage("could not write {s}", .{tmp_path});1516 return error.FileNotFound;1517 };1518 tmp.close(io);15191520 1521 1522 1523 const code = streamLocal(io, &.{1524 "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1525 }) catch {1526 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1527 errors.error_info.setMessage("could not write {s}", .{path});1528 return error.ProcessFailed;1529 };1530 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1531 if (code != 0) {1532 errors.error_info.setMessage("sudo cp into {s} failed", .{path});1533 return error.ProcessFailed;1534 }1535}