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};1819pub const HookResult = enum {20 ok,21 failed,22 not_found,23};2425pub const HookRun = struct {26 result: HookResult,27 exit_code: u8 = 0,28 output: []u8,29};303132pub fn capture(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, cmd: []const []const u8) !RunResult {33 const argv = try buildArgv(gpa, machine, cmd);34 defer if (!machine.local) gpa.free(argv);3536 const result = std.process.run(gpa, io, .{ .argv = argv }) catch |e| {37 errors.error_info.setMessage("process failed: {s}", .{cmd[0]});38 return e;39 };4041 return .{42 .stdout = result.stdout,43 .stderr = result.stderr,44 .exit_code = switch (result.term) {45 .exited => |c| c,46 else => 1,47 },48 };49}505152pub fn stream(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8) !u8 {53 54 55 output.flush();56 const argv = try buildArgv(gpa, machine, cmd);57 defer if (!machine.local) gpa.free(argv);5859 var child = std.process.spawn(io, .{60 .argv = argv,61 .stdin = .inherit,62 .stdout = .inherit,63 .stderr = .inherit,64 }) catch |e| {65 errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});66 return e;67 };6869 const term = child.wait(io) catch |e| {70 errors.error_info.setMessage("process wait failed", .{});71 return e;72 };7374 return switch (term) {75 .exited => |c| c,76 else => 1,77 };78}798081fn 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 {82 output.flush();83 const argv = try buildArgv(gpa, machine, cmd);84 defer if (!machine.local) gpa.free(argv);8586 var env = try base_env.clone(gpa);87 defer env.deinit();88 try env.put("PS1", ps1);89 try env.put("NINA_PS1", ps1);9091 var child = std.process.spawn(io, .{92 .argv = argv,93 .stdin = .inherit,94 .stdout = .inherit,95 .stderr = .inherit,96 .environ_map = &env,97 }) catch |e| {98 errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});99 return e;100 };101102 const term = child.wait(io) catch |e| {103 errors.error_info.setMessage("process wait failed", .{});104 return e;105 };106107 return switch (term) {108 .exited => |c| c,109 else => 1,110 };111}112113fn createInteractiveShellRc(gpa: std.mem.Allocator, io: std.Io) ![]u8 {114 const out = try captureLocal(gpa, io, &.{ "mktemp", "/tmp/nina-shell-rc.XXXXXX" });115 defer gpa.free(out);116117 const path = std.mem.trim(u8, out, " \t\r\n");118 if (path.len == 0) return error.FileNotFound;119 const owned_path = try gpa.dupe(u8, path);120 errdefer gpa.free(owned_path);121122 const file = std.Io.Dir.createFile(.cwd(), io, owned_path, .{}) catch {123 errors.error_info.setMessage("could not write shell prompt setup", .{});124 return error.FileNotFound;125 };126 errdefer file.close(io);127128 const content =129 \\PS1="${NINA_PS1:-$PS1}"130 \\trap 'exit 130' INT131 \\132 ;133 file.writePositionalAll(io, content, 0) catch {134 errors.error_info.setMessage("could not write shell prompt setup", .{});135 return error.FileNotFound;136 };137 file.close(io);138139 return owned_path;140}141142143pub fn streamLocal(io: std.Io, cmd: []const []const u8) !u8 {144 output.flush();145 var child = std.process.spawn(io, .{146 .argv = cmd,147 .stdin = .inherit,148 .stdout = .inherit,149 .stderr = .inherit,150 }) catch |e| {151 errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});152 return e;153 };154 const term = child.wait(io) catch {155 errors.error_info.setMessage("process wait failed", .{});156 return error.ProcessFailed;157 };158 return switch (term) {159 .exited => |c| c,160 else => 1,161 };162}163164165pub fn captureLocal(gpa: std.mem.Allocator, io: std.Io, cmd: []const []const u8) ![]u8 {166 const result = std.process.run(gpa, io, .{ .argv = cmd }) catch return error.ProcessFailed;167 defer gpa.free(result.stderr);168 switch (result.term) {169 .exited => |c| if (c != 0) {170 gpa.free(result.stdout);171 return error.ProcessFailed;172 },173 else => {174 gpa.free(result.stdout);175 return error.ProcessFailed;176 },177 }178 return result.stdout;179}180181182183pub fn ensureDir(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) void {184 _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir }) catch {};185}186187188189190pub fn runHook(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, hook_name: []const u8) !HookRun {191 const home = environ.get("HOME") orelse return .{192 .result = .not_found,193 .output = try gpa.dupe(u8, ""),194 };195196 const hook_dir = try std.fs.path.join(gpa, &.{ home, ".config", "nina", "hooks" });197 defer gpa.free(hook_dir);198 ensureDir(gpa, io, hook_dir);199200 const hook_path = try std.fs.path.join(gpa, &.{ hook_dir, hook_name });201 defer gpa.free(hook_path);202203 const executable = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", "test -x \"$1\"", "nina-hook-check", hook_path } }) catch return .{204 .result = .not_found,205 .output = try gpa.dupe(u8, ""),206 };207 defer gpa.free(executable.stdout);208 defer gpa.free(executable.stderr);209 const is_executable = switch (executable.term) {210 .exited => |code| code == 0,211 else => false,212 };213 if (!is_executable) return .{214 .result = .not_found,215 .output = try gpa.dupe(u8, ""),216 };217218 const tmp_raw = try captureLocal(gpa, io, &.{ "mktemp", "/tmp/nina-hook.XXXXXX" });219 defer gpa.free(tmp_raw);220 const tmp_output = std.mem.trim(u8, tmp_raw, " \t\r\n");221 defer if (std.fs.path.isAbsolute(tmp_output)) std.Io.Dir.deleteFileAbsolute(io, tmp_output) catch {};222223 const result = try std.process.run(gpa, io, .{224 .argv = &.{225 "sh",226 "-c",227 "$1 > \"$2\" 2>&1; code=$?; tail -c 4096 \"$2\"; exit \"$code\"",228 "nina-hook-run",229 hook_path,230 tmp_output,231 },232 .stdout_limit = .limited(4096),233 .stderr_limit = .limited(512),234 });235 defer gpa.free(result.stdout);236 defer gpa.free(result.stderr);237238 const exit_code = switch (result.term) {239 .exited => |code| code,240 else => 1,241 };242 return .{243 .result = if (exit_code == 0) .ok else .failed,244 .exit_code = exit_code,245 .output = try std.fmt.allocPrint(gpa, "{s}{s}", .{ result.stdout, result.stderr }),246 };247}248249test "runHook ignores non-executable hooks and captures failures" {250 const a = std.testing.allocator;251 const io = std.testing.io;252253 var tmp = std.testing.tmpDir(.{});254 defer tmp.cleanup();255256 const home = try std.fmt.allocPrint(a, ".zig-cache/tmp/{s}", .{&tmp.sub_path});257 defer a.free(home);258259 var env: std.process.Environ.Map = .init(a);260 defer env.deinit();261 try env.put("HOME", home);262263 var hook_dir = try tmp.dir.createDirPathOpen(io, ".config/nina/hooks", .{});264 defer hook_dir.close(io);265266 const script =267 \\#!/bin/sh268 \\echo hook says no269 \\echo detail >&2270 \\exit 3271 \\272 ;273 {274 const file = try hook_dir.createFile(io, "pre-apply", .{});275 defer file.close(io);276 try file.writePositionalAll(io, script, 0);277 try file.setPermissions(io, .fromMode(0o644));278 }279280 const missing = try runHook(a, io, &env, "pre-apply");281 defer a.free(missing.output);282 try std.testing.expectEqual(HookResult.not_found, missing.result);283284 try hook_dir.setFilePermissions(io, "pre-apply", .fromMode(0o755), .{});285286 const failed = try runHook(a, io, &env, "pre-apply");287 defer a.free(failed.output);288 try std.testing.expectEqual(HookResult.failed, failed.result);289 try std.testing.expectEqual(@as(u8, 3), failed.exit_code);290 try std.testing.expect(std.mem.indexOf(u8, failed.output, "hook says no") != null);291 try std.testing.expect(std.mem.indexOf(u8, failed.output, "detail") != null);292}293294fn buildArgv(gpa: std.mem.Allocator, machine: *const types.Machine, cmd: []const []const u8) ![]const []const u8 {295 if (machine.local) return cmd;296297 const host = machine.host orelse {298 errors.error_info.setMessage("machine '{s}' has no host configured", .{machine.name});299 return error.SshFailed;300 };301302 var ssh: std.ArrayList([]const u8) = .empty;303 try ssh.append(gpa, "ssh");304 try ssh.append(gpa, "-o");305 try ssh.append(gpa, "BatchMode=yes");306 try ssh.append(gpa, "-o");307 try ssh.append(gpa, "StrictHostKeyChecking=accept-new");308 if (machine.ssh_key) |key| {309 try ssh.append(gpa, "-i");310 try ssh.append(gpa, key);311 }312 const addr = if (machine.user) |u|313 try std.fmt.allocPrint(gpa, "{s}@{s}", .{ u, host })314 else315 try gpa.dupe(u8, host);316 try ssh.append(gpa, addr);317 for (cmd) |arg| try ssh.append(gpa, arg);318 return ssh.toOwnedSlice(gpa);319}320321322323324325326327328pub fn dirHasFlake(gpa: std.mem.Allocator, io: std.Io, dir: []const u8) bool {329 const flake_path = std.fs.path.join(gpa, &.{ dir, "flake.nix" }) catch return false;330 defer gpa.free(flake_path);331 return pathExists(io, flake_path);332}333334pub fn configHasFlake(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {335 if (!machine.local) return false;336 return dirHasFlake(gpa, io, machine.config_path);337}338339340341342343fn useFlakeFlag(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {344 if (!configHasFlake(gpa, io, machine)) return false;345 var path = machine.config_path;346 while (path.len > 1 and path[path.len - 1] == '/') path = path[0 .. path.len - 1];347 return !std.mem.eql(u8, path, "/etc/nixos");348}349350351352353354fn nixosRebuildRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, flake: bool) !u8 {355 const argv: []const []const u8 = if (flake)356 &.{ "sudo", "nixos-rebuild", verb, "--flake", machine.config_path }357 else358 &.{ "sudo", "nixos-rebuild", verb };359 output.flush();360 const r = try capture(gpa, io, machine, argv);361 defer gpa.free(r.stdout);362 defer gpa.free(r.stderr);363 errors.setBuildStderr(r.stderr);364 return r.exit_code;365}366367pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {368 const flake = useFlakeFlag(gpa, io, machine);369 if (flake) {370 output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});371 } else {372 output.printSubstep("nixos-rebuild switch", .{});373 }374 return nixosRebuildRun(io, machine, gpa, "switch", flake);375}376377378379380381pub fn nixosRebuildSwitchWithPanel(382 io: std.Io,383 machine: *const types.Machine,384 gpa: std.mem.Allocator,385 panel: *output.BuildPanel,386) !u8 {387 const flake = useFlakeFlag(gpa, io, machine);388 if (flake) {389 output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});390 } else {391 output.printSubstep("nixos-rebuild switch", .{});392 }393 if (!output.colorEnabled()) return nixosRebuildRun(io, machine, gpa, "switch", flake);394 return nixosRebuildRunStreamed(io, machine, gpa, "switch", flake, panel);395}396397fn nixosRebuildRunStreamed(398 io: std.Io,399 machine: *const types.Machine,400 gpa: std.mem.Allocator,401 verb: []const u8,402 flake: bool,403 panel: *output.BuildPanel,404) !u8 {405 const argv: []const []const u8 = if (flake)406 &.{ "sudo", "nixos-rebuild", verb, "--flake", machine.config_path }407 else408 &.{ "sudo", "nixos-rebuild", verb };409410 output.flush();411 const built_argv = try buildArgv(gpa, machine, argv);412 defer if (!machine.local) gpa.free(built_argv);413414 var child = std.process.spawn(io, .{415 .argv = built_argv,416 .stdin = .ignore,417 .stdout = .ignore,418 .stderr = .pipe,419 }) catch |e| {420 errors.error_info.setMessage("failed to spawn nixos-rebuild", .{});421 return e;422 };423424 var accumulated: std.ArrayList(u8) = .empty;425 defer accumulated.deinit(gpa);426427 if (child.stderr) |stderr_file| {428 var reader_buf: [8192]u8 = undefined;429 var fr = std.Io.File.Reader.initStreaming(stderr_file, io, &reader_buf);430 while (true) {431 const maybe = fr.interface.takeDelimiter('\n') catch break;432 const raw = maybe orelse break;433 accumulated.appendSlice(gpa, raw) catch {};434 const line = std.mem.trimEnd(u8, raw, "\r\n");435 panel.update(line);436 panel.render();437 }438 }439440 errors.setBuildStderr(accumulated.items);441442 const term = child.wait(io) catch |e| {443 errors.error_info.setMessage("nixos-rebuild wait failed", .{});444 return e;445 };446 return switch (term) {447 .exited => |code| code,448 else => 1,449 };450}451452pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {453 return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine));454}455456pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {457 return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine));458}459460461462463464465466467468469const GEN_LIST_SCRIPT =470 \\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 }'471;472473pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {474 const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });475 defer gpa.free(r.stderr);476 defer gpa.free(r.stdout);477 if (r.exit_code != 0) return error.ProcessFailed;478 return parseGenerations(gpa, r.stdout);479}480481fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {482 var gens: std.ArrayList(types.GenerationInfo) = .empty;483 var lines = std.mem.splitScalar(u8, output_str, '\n');484 while (lines.next()) |line| {485 const trimmed = std.mem.trim(u8, line, " \t");486 if (trimmed.len == 0) continue;487 var parts = std.mem.tokenizeAny(u8, trimmed, " \t");488 const num_str = parts.next() orelse continue;489 const date_str = parts.next() orelse continue;490 const time_str = parts.next() orelse continue;491 const rest = parts.rest();492 const current = std.mem.indexOf(u8, rest, "current") != null;493 const num = std.fmt.parseInt(u32, num_str, 10) catch continue;494 try gens.append(gpa, .{495 .number = num,496 .date = try gpa.dupe(u8, date_str),497 .time = try gpa.dupe(u8, time_str),498 .current = current,499 });500 }501 return gens.toOwnedSlice(gpa);502}503504pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {505 const gens = try getGenerations(gpa, io, machine);506 defer gpa.free(gens);507 for (gens) |g| {508 if (g.current) return g.number;509 }510 return 0;511}512513pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {514 515 516 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 });517 defer gpa.free(cmd);518 return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });519}520521pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {522 return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });523}524525pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {526 const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});527 defer gpa.free(n_str);528 return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });529}530531pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {532 return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });533}534535536537pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {538 if (delete_old) {539 return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });540 }541 542 543 544 const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });545 defer gpa.free(cmd);546 return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });547}548549550551pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {552 const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });553 defer gpa.free(r.stderr);554 defer gpa.free(r.stdout);555 if (r.exit_code != 0) return error.ProcessFailed;556 return parseChannels(gpa, r.stdout);557}558559fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {560 var channels: std.ArrayList(types.ChannelInfo) = .empty;561 var lines = std.mem.splitScalar(u8, output_str, '\n');562 while (lines.next()) |line| {563 const trimmed = std.mem.trim(u8, line, " \t\r");564 if (trimmed.len == 0) continue;565 const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;566 try channels.append(gpa, .{567 .name = try gpa.dupe(u8, trimmed[0..space]),568 .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),569 });570 }571 return channels.toOwnedSlice(gpa);572}573574pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {575 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });576}577578pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {579 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });580}581582pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {583 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });584}585586587588pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {589 const cmd: []const []const u8 = if (user)590 &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }591 else592 &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };593 const r = try capture(gpa, io, machine, cmd);594 defer gpa.free(r.stderr);595 defer gpa.free(r.stdout);596 if (r.exit_code != 0) return error.ProcessFailed;597 return parseServices(gpa, r.stdout);598}599600fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {601 var svcs: std.ArrayList(types.ServiceInfo) = .empty;602 var lines = std.mem.splitScalar(u8, output_str, '\n');603 while (lines.next()) |line| {604 const trimmed = std.mem.trim(u8, line, " \t\r");605 if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; 606 var parts = std.mem.tokenizeAny(u8, trimmed, " \t");607 const name = parts.next() orelse continue;608 _ = parts.next(); 609 const active_str = parts.next() orelse continue;610 const sub_str = parts.next() orelse "unknown";611612 const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))613 (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)614 else if (std.mem.eql(u8, active_str, "failed"))615 .failed616 else617 .inactive;618619 try svcs.append(gpa, .{620 .name = try gpa.dupe(u8, name),621 .state = state,622 .uptime = null,623 });624 }625 return svcs.toOwnedSlice(gpa);626}627628pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {629 630 631 if (user) {632 return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });633 }634 return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });635}636637pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {638 const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});639 defer gpa.free(n_str);640 if (user) {641 if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });642 return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });643 }644 if (follow) {645 return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });646 }647 return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });648}649650651652pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {653 const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});654 defer gpa.free(pkg_ref);655 656 657 return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });658}659660pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {661 662 663 return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });664}665666pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {667 const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });668 defer gpa.free(r.stderr);669 if (r.exit_code != 0) return error.ProcessFailed;670 return r.stdout;671}672673674pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {675 const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });676 defer gpa.free(r.stderr);677 if (r.exit_code != 0) {678 gpa.free(r.stdout);679 return error.ProcessFailed;680 }681 return r.stdout;682}683684685686687688689pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {690 const js = profileListJson(gpa, io, machine) catch return null;691 defer gpa.free(js);692 return profileJsonNinaElement(gpa, js);693}694695pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {696 const name = profileNinaElement(gpa, io, machine) orelse return false;697 gpa.free(name);698 return true;699}700701702703704705fn storePathIsNina(path: []const u8) bool {706 const prefix = "/nix/store/";707 if (!std.mem.startsWith(u8, path, prefix)) return false;708 const rel = path[prefix.len..];709 710 const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];711 if (entry.len < 34) return false; 712 const pname_ver = entry[33..]; 713 return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");714}715716717718719720721fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {722 var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;723 defer parsed.deinit();724 const root = parsed.value;725 if (root != .object) return null;726 const elements = root.object.get("elements") orelse return null;727 switch (elements) {728 .object => |obj| {729 730 if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;731 732 733 734 var it = obj.iterator();735 while (it.next()) |kv| {736 const val = kv.value_ptr.*;737 if (val != .object) continue;738 const sps = val.object.get("storePaths") orelse continue;739 if (sps != .array) continue;740 for (sps.array.items) |sp| {741 if (sp == .string and storePathIsNina(sp.string))742 return gpa.dupe(u8, kv.key_ptr.*) catch null;743 }744 }745 return null;746 },747 .array => |arr| {748 749 for (arr.items) |el| {750 if (el != .object) continue;751 const ap = el.object.get("attrPath") orelse continue;752 if (ap != .string) continue;753 if (std.mem.eql(u8, ap.string, "nina") or754 std.mem.endsWith(u8, ap.string, ".nina"))755 return gpa.dupe(u8, "nina") catch null;756 757 758 const sps = el.object.get("storePaths") orelse continue;759 if (sps != .array) continue;760 for (sps.array.items) |sp| {761 if (sp != .string) continue;762 if (!storePathIsNina(sp.string)) continue;763 const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;764 const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;765 return gpa.dupe(u8, el_name) catch null;766 }767 }768 return null;769 },770 else => return null,771 }772}773774test "profileJsonNinaElement finds element name from profile JSON" {775 const a = std.testing.allocator;776777 778 const named =779 \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},780 \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}781 ;782 const r1 = profileJsonNinaElement(a, named);783 defer if (r1) |n| a.free(n);784 try std.testing.expectEqualStrings("nina", r1.?);785786 787 const default_key =788 \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}789 ;790 const r2 = profileJsonNinaElement(a, default_key);791 defer if (r2) |n| a.free(n);792 try std.testing.expectEqualStrings("default", r2.?);793794 795 const decoy =796 \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}797 ;798 const r3 = profileJsonNinaElement(a, decoy);799 try std.testing.expectEqual(@as(?[]const u8, null), r3);800801 802 const arr =803 \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}804 ;805 const r4 = profileJsonNinaElement(a, arr);806 defer if (r4) |n| a.free(n);807 try std.testing.expectEqualStrings("nina", r4.?);808809 810 const arr_default =811 \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}812 ;813 const r5 = profileJsonNinaElement(a, arr_default);814 defer if (r5) |n| a.free(n);815 try std.testing.expectEqualStrings("default", r5.?);816817 818 try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));819 try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));820}821822823824825pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {826 const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });827 defer gpa.free(r.stderr);828 if (r.exit_code != 0) {829 gpa.free(r.stdout);830 return error.ProcessFailed;831 }832 return r.stdout;833}834835pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {836 return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });837}838839840841pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {842 return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });843}844845pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {846 return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });847}848849pub const SystemStatus = struct { size: []u8, age: []u8 };850851852853854855const STATUS_SCRIPT =856 \\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} ))"857;858859pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {860 const unknown = SystemStatus{861 .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },862 .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },863 };864 const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;865 defer gpa.free(r.stdout);866 defer gpa.free(r.stderr);867 if (r.exit_code != 0) return unknown;868869 var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");870 const sz_str = it.next() orelse return unknown;871 const age_str = it.next() orelse return unknown;872 const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;873 const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;874875 gpa.free(unknown.size);876 gpa.free(unknown.age);877 return .{878 .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),879 .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),880 };881}882883884885886pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {887 const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch888 return gpa.dupe(u8, "unknown");889 defer gpa.free(r.stderr);890 const state = std.mem.trim(u8, r.stdout, " \t\n\r");891 const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");892 gpa.free(r.stdout);893 return owned;894}895896fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {897 if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});898 if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});899 if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});900 return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});901}902903pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {904 return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });905}906907pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {908 909 910 911 912 913 914 const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });915 defer gpa.free(pi.stdout);916 defer gpa.free(pi.stderr);917918 const scan = scanStoreJson(pi.stdout);919 const total_owned = try humanSize(gpa, scan.total_bytes);920921 return .{922 .total_size = total_owned,923 .live_paths = scan.count,924 .reclaimable_paths = 0,925 };926}927928const StoreScan = struct { count: u64, total_bytes: u64 };929930931932933fn scanStoreJson(json_str: []const u8) StoreScan {934 const needle = "\"narSize\":";935 var count: u64 = 0;936 var total: u64 = 0;937 var i: usize = 0;938 while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {939 var j = pos + needle.len;940 while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}941 var val: u64 = 0;942 var any = false;943 while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {944 val = val * 10 + (json_str[j] - '0');945 any = true;946 }947 if (any) {948 count += 1;949 total += val;950 }951 i = j;952 }953 return .{ .count = count, .total_bytes = total };954}955956fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {957 const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };958 var val: f64 = @floatFromInt(bytes);959 var unit: usize = 0;960 while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;961 if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });962 return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });963}964965pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {966 967 968 const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});969 defer gpa.free(expr);970 const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });971 defer gpa.free(r.stderr);972 if (r.exit_code != 0) {973 gpa.free(r.stdout);974 return error.ProcessFailed;975 }976 return r.stdout;977}978979980981pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8) !u8 {982 if (input) |inp| {983 return stream(io, machine, gpa, &.{ "nix", "flake", "update", inp });984 }985 return stream(io, machine, gpa, &.{ "nix", "flake", "update" });986}987988989990991pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {992 return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });993}994995pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {996 return stream(io, machine, gpa, &.{ "nix", "flake", "check" });997}998999pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1000 return stream(io, machine, gpa, &.{ "nix", "flake", "init" });1001}10021003pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1004 return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });1005}10061007pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {1008 return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });1009}10101011pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1012 const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });1013 defer gpa.free(r.stderr);1014 if (r.exit_code != 0) {1015 gpa.free(r.stdout);1016 return error.ProcessFailed;1017 }1018 return r.stdout;1019}1020102110221023pub fn nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8) !u8 {1024 if (attr) |a| {1025 const ref = try std.fmt.allocPrint(gpa, ".#{s}", .{a});1026 defer gpa.free(ref);1027 return stream(io, machine, gpa, &.{ "nix", "build", ref });1028 }1029 return stream(io, machine, gpa, &.{ "nix", "build" });1030}10311032pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1033 1034 const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");1035 if (is_url) {1036 return stream(io, machine, gpa, &.{ "nix", "run", pkg, "--no-write-lock-file" });1037 }1038 1039 if (std.mem.indexOfScalar(u8, pkg, '#') != null) {1040 return stream(io, machine, gpa, &.{ "nix", "run", pkg });1041 }1042 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1043 defer gpa.free(ref);1044 return stream(io, machine, gpa, &.{ "nix", "run", ref });1045}10461047pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1048 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1049 defer gpa.free(ref);1050 return stream(io, machine, gpa, &.{ "nix", "shell", ref });1051}10521053pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {1054 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1055 defer gpa.free(ref);1056 const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});1057 defer gpa.free(ps1);1058 if (machine.local) {1059 const rc_path = try createInteractiveShellRc(gpa, io);1060 defer {1061 std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1062 gpa.free(rc_path);1063 }1064 return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref, "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, ps1);1065 }1066 return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);1067}10681069pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8) !u8 {1070 if (run_cmd) |cmd| {1071 1072 return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1073 }1074 return stream(io, machine, gpa, &.{ "nix", "develop" });1075}10761077pub 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 {1078 if (run_cmd) |cmd| {1079 1080 return stream(io, machine, gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1081 }1082 if (machine.local) {1083 const rc_path = try createInteractiveShellRc(gpa, io);1084 defer {1085 std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1086 gpa.free(rc_path);1087 }1088 return streamEnv(io, machine, gpa, &.{ "nix", "develop", "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, "(nina: dev) -> ");1089 }1090 return streamEnv(io, machine, gpa, &.{ "nix", "develop" }, base_env, "(nina: dev) -> ");1091}10921093pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1094 return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });1095}1096109710981099pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {1100 if (check) {1101 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });1102 }1103 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });1104}1105110611071108pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1109 const r = try capture(gpa, io, machine, &.{"nixos-version"});1110 defer gpa.free(r.stderr);1111 if (r.exit_code != 0) {1112 gpa.free(r.stdout);1113 return error.ProcessFailed;1114 }1115 return r.stdout;1116}11171118pub fn kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1119 const r = try capture(gpa, io, machine, &.{ "uname", "-r" });1120 defer gpa.free(r.stderr);1121 if (r.exit_code != 0) {1122 gpa.free(r.stdout);1123 return error.ProcessFailed;1124 }1125 return r.stdout;1126}11271128pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1129 const r = try capture(gpa, io, machine, &.{"uptime"});1130 defer gpa.free(r.stderr);1131 if (r.exit_code != 0) {1132 gpa.free(r.stdout);1133 return error.ProcessFailed;1134 }1135 return r.stdout;1136}1137113811391140pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {1141 const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });1142 defer gpa.free(r.stderr);1143 defer gpa.free(r.stdout);1144 if (r.exit_code != 0) return error.ProcessFailed;1145 return parseBootEntries(gpa, r.stdout);1146}11471148fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {1149 var entries: std.ArrayList(types.BootEntry) = .empty;1150 var lines = std.mem.splitScalar(u8, output_str, '\n');1151 while (lines.next()) |line| {1152 const trimmed = std.mem.trim(u8, line, " \t\r");1153 if (std.mem.startsWith(u8, trimmed, "title:")) {1154 const title = std.mem.trim(u8, trimmed[6..], " \t");1155 const current = std.mem.indexOf(u8, title, "(current)") != null;1156 try entries.append(gpa, .{1157 .title = try gpa.dupe(u8, title),1158 .current = current,1159 });1160 }1161 }1162 return entries.toOwnedSlice(gpa);1163}1164116511661167fn pkgInstallable(gpa: std.mem.Allocator, pkg: []const u8) ![]u8 {1168 return std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1169}11701171fn resolvePkgStorePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, installable: []const u8) ![]u8 {1172 const r = try capture(gpa, io, machine, &.{ "nix", "build", "--no-link", "--print-out-paths", installable });1173 defer gpa.free(r.stderr);1174 defer gpa.free(r.stdout);1175 if (r.exit_code != 0) return error.PackageNotFound;11761177 var lines = std.mem.tokenizeAny(u8, r.stdout, "\r\n");1178 const first_path = lines.next() orelse return error.PackageNotFound;1179 const store_path = std.mem.trim(u8, first_path, " \t");1180 if (store_path.len == 0) return error.PackageNotFound;1181 return gpa.dupe(u8, store_path);1182}11831184pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1185 const installable = try pkgInstallable(gpa, pkg);1186 defer gpa.free(installable);1187 const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1188 defer gpa.free(store_path);1189 return stream(io, machine, gpa, &.{ "nix", "why-depends", "/run/current-system", store_path });1190}11911192pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1193 const installable = try pkgInstallable(gpa, pkg);1194 defer gpa.free(installable);1195 const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1196 defer gpa.free(store_path);1197 return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", store_path });1198}11991200pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {1201 const installable = try pkgInstallable(gpa, pkg);1202 defer gpa.free(installable);1203 const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", "--json", installable });1204 defer gpa.free(r.stderr);1205 defer gpa.free(r.stdout);1206 if (r.exit_code != 0) return error.ProcessFailed;12071208 const nar_size = try pathInfoNarSize(gpa, r.stdout);1209 return humanPkgSize(gpa, nar_size);1210}12111212pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1213 const installable = try pkgInstallable(gpa, pkg);1214 defer gpa.free(installable);1215 const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1216 defer gpa.free(store_path);1217 return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", store_path });1218}12191220fn pathInfoNarSize(gpa: std.mem.Allocator, json_str: []const u8) !u64 {1221 var parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.ProcessFailed;1222 defer parsed.deinit();1223 switch (parsed.value) {1224 .object => |obj| {1225 var it = obj.iterator();1226 while (it.next()) |entry| {1227 if (entry.value_ptr.* == .object) {1228 if (entry.value_ptr.object.get("narSize")) |v| {1229 if (v == .integer and v.integer >= 0) return @intCast(v.integer);1230 }1231 }1232 }1233 },1234 .array => |arr| {1235 for (arr.items) |item| {1236 if (item == .object) {1237 if (item.object.get("narSize")) |v| {1238 if (v == .integer and v.integer >= 0) return @intCast(v.integer);1239 }1240 }1241 }1242 },1243 else => {},1244 }1245 return error.ProcessFailed;1246}12471248fn humanPkgSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1249 const units = [_][]const u8{ "B", "KiB", "MiB", "GiB", "TiB" };1250 var val: f64 = @floatFromInt(bytes);1251 var unit: usize = 0;1252 while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1253 if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1254 return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1255}12561257test "pathInfoNarSize parses object and array shapes" {1258 try std.testing.expectEqual(@as(u64, 1064629862), try pathInfoNarSize(std.testing.allocator,1259 \\{"/nix/store/abc-ffmpeg":{"narSize":1064629862}}1260 ));1261 try std.testing.expectEqual(@as(u64, 2048), try pathInfoNarSize(std.testing.allocator,1262 \\[{"path":"/nix/store/abc-pkg","narSize":2048}]1263 ));1264}1265126612671268pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {1269 const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });1270 defer gpa.free(r.stderr);1271 if (r.exit_code != 0) {1272 gpa.free(r.stdout);1273 return error.ProcessFailed;1274 }1275 return r.stdout;1276}12771278pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {1279 const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });1280 defer gpa.free(r.stderr);1281 if (r.exit_code != 0) {1282 gpa.free(r.stdout);1283 return error.ProcessFailed;1284 }1285 return r.stdout;1286}1287128812891290pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {1291 1292 1293}12941295pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {1296 if (line) |l| {1297 const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});1298 defer gpa.free(line_arg);1299 return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });1300 }1301 return stream(io, &types.Machine{}, gpa, &.{ editor, path });1302}13031304pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {1305 const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});1306 defer gpa.free(a_str);1307 const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});1308 defer gpa.free(b_str);1309 1310 if (output.colorEnabled()) {1311 return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });1312 }1313 1314 1315 const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });1316 defer gpa.free(r.stdout);1317 defer gpa.free(r.stderr);1318 const cleaned = try stripAnsi(gpa, r.stdout);1319 defer gpa.free(cleaned);1320 output.raw(cleaned);1321 return r.exit_code;1322}1323132413251326fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1327 var out: std.ArrayList(u8) = .empty;1328 errdefer out.deinit(gpa);1329 var i: usize = 0;1330 while (i < input.len) {1331 if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1332 i += 2;1333 while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1334 if (i < input.len) i += 1; 1335 continue;1336 }1337 try out.append(gpa, input[i]);1338 i += 1;1339 }1340 return out.toOwnedSlice(gpa);1341}13421343test "stripAnsi removes CSI color sequences" {1344 const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1345 defer std.testing.allocator.free(cleaned);1346 try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1347}1348134913501351pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1352 var checks: std.ArrayList(types.DoctorCheck) = .empty;13531354 1355 {1356 const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1357 defer gpa.free(r.stdout);1358 defer gpa.free(r.stderr);1359 const active = std.mem.indexOf(u8, r.stdout, "active") != null;1360 try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1361 }13621363 1364 1365 1366 {1367 const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1368 &.{ "sudo", "nixos-rebuild", "dry-build", "--flake", machine.config_path }1369 else1370 &.{ "sudo", "nixos-rebuild", "dry-build" };1371 const r = try capture(gpa, io, machine, argv);1372 defer gpa.free(r.stdout);1373 defer gpa.free(r.stderr);1374 try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1375 }13761377 1378 {1379 const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1380 defer gpa.free(r.stdout);1381 defer gpa.free(r.stderr);1382 const has_channel = r.exit_code == 0 and r.stdout.len > 0;1383 try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1384 }13851386 return checks.toOwnedSlice(gpa);1387}13881389139013911392139313941395pub const HomeManagerMode = enum {1396 1397 standalone,1398 1399 1400 module,1401 none,1402};14031404fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1405 const home = environ.get("HOME") orelse return null;1406 return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1407}140814091410pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1411 const dir = homeConfigDir(gpa, environ) orelse return null;1412 defer gpa.free(dir);1413 return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1414}14151416pub fn pathExists(io: std.Io, path: []const u8) bool {1417 const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1418 f.close(io);1419 return true;1420}1421142214231424fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1425 var buf: [256]u8 = undefined;1426 const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1427 const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1428 defer gpa.free(r.stdout);1429 defer gpa.free(r.stderr);1430 return switch (r.term) {1431 .exited => |code| code == 0,1432 else => false,1433 };1434}14351436pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1437 if (commandExists(gpa, io, "home-manager")) return .standalone;1438 if (homeNixPath(gpa, environ)) |p| {1439 defer gpa.free(p);1440 if (pathExists(io, p)) return .module;1441 }1442 return .none;1443}14441445144614471448pub fn homeFlakeRef(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1449 const dir = homeConfigDir(gpa, environ) orelse return null;1450 defer gpa.free(dir);1451 const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch return null;1452 defer gpa.free(flake);1453 if (!pathExists(io, flake)) return null;1454 const user = environ.get("USER") orelse "default";1455 return std.fmt.allocPrint(gpa, "{s}#{s}", .{ dir, user }) catch null;1456}14571458pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1459 output.flush();1460 const r = try capture(gpa, io, machine, &.{ "home-manager", "switch" });1461 defer gpa.free(r.stdout);1462 defer gpa.free(r.stderr);1463 errors.setBuildStderr(r.stderr);1464 return r.exit_code;1465}14661467pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8) !u8 {1468 output.flush();1469 const r = try capture(gpa, io, machine, &.{ "home-manager", "switch", "--flake", flake_ref });1470 defer gpa.free(r.stdout);1471 defer gpa.free(r.stderr);1472 errors.setBuildStderr(r.stderr);1473 return r.exit_code;1474}1475147614771478pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1479 output.flush();1480 const r = try capture(gpa, io, machine, &.{ "home-manager", "switch", "--rollback" });1481 defer gpa.free(r.stdout);1482 defer gpa.free(r.stderr);1483 errors.setBuildStderr(r.stderr);1484 return r.exit_code;1485}148614871488148914901491pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1492 output.flush();1493 const r = try capture(gpa, io, machine, &.{ "sh", "-c", "d=$(mktemp -d) && cd \"$d\" && home-manager build" });1494 defer gpa.free(r.stdout);1495 defer gpa.free(r.stderr);1496 errors.setBuildStderr(r.stderr);1497 return r.exit_code;1498}14991500pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1501 const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1502 defer gpa.free(r.stderr);1503 if (r.exit_code != 0) {1504 gpa.free(r.stdout);1505 return error.ProcessFailed;1506 }1507 return r.stdout;1508}150915101511pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1512 const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1513 defer gpa.free(r.stderr);1514 if (r.exit_code != 0) {1515 gpa.free(r.stdout);1516 return error.ProcessFailed;1517 }1518 return r.stdout;1519}1520152115221523pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1524 if (output.colorEnabled()) {1525 return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1526 }1527 const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1528 defer gpa.free(r.stdout);1529 defer gpa.free(r.stderr);1530 const cleaned = try stripAnsi(gpa, r.stdout);1531 defer gpa.free(cleaned);1532 output.raw(cleaned);1533 return r.exit_code;1534}1535153615371538pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1539 const home = environ.get("HOME") orelse return error.FileNotFound;1540 const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1541 defer gpa.free(path);1542 const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1543 if (last == 0) return content;15441545 1546 1547 var lines: std.ArrayList([]const u8) = .empty;1548 defer lines.deinit(gpa);1549 var it = std.mem.splitScalar(u8, content, '\n');1550 while (it.next()) |line| {1551 if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1552 try lines.append(gpa, line);1553 }1554 if (lines.items.len <= last) return content;15551556 var out: std.ArrayList(u8) = .empty;1557 errdefer out.deinit(gpa);1558 for (lines.items[lines.items.len - last ..]) |line| {1559 try out.appendSlice(gpa, line);1560 try out.append(gpa, '\n');1561 }1562 gpa.free(content);1563 return out.toOwnedSlice(gpa);1564}156515661567156815691570pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1571 const home = environ.get("HOME") orelse return;1572 var buf: [512]u8 = undefined;1573 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1574 const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1575 file.close(io);1576}15771578pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1579 const home = environ.get("HOME") orelse return false;1580 var buf: [512]u8 = undefined;1581 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1582 if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1583 f.close(io);1584 std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1585 return true;1586 } else |_| {1587 return false;1588 }1589}15901591pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1592 const home = environ.get("HOME") orelse return;1593 var path_buf: [512]u8 = undefined;1594 const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1595 const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1596 (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1597 defer file.close(io);1598 const size = file.length(io) catch 0;1599 file.writePositionalAll(io, entry, size) catch {};1600}160116021603160416051606pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1607 const argv = [_][]const u8{1608 "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1609 };1610 const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1611 defer gpa.free(result.stderr);16121613 const marker = "\nHTTP_STATUS:";1614 const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1615 gpa.free(result.stdout);1616 return error.NetworkError;1617 };1618 const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1619 const status = std.fmt.parseInt(u16, status_str, 10) catch {1620 gpa.free(result.stdout);1621 return error.NetworkError;1622 };1623 if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1624 if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1625 const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1626 gpa.free(result.stdout);1627 return e;1628 };1629 gpa.free(result.stdout);1630 return body;1631}1632163316341635pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1636 const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1637 errdefer gpa.free(tmp_path);16381639 var child = std.process.spawn(io, .{1640 .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1641 .stdin = .close,1642 .stdout = .close,1643 .stderr = .inherit,1644 }) catch return error.NetworkError;1645 const term = child.wait(io) catch return error.NetworkError;1646 switch (term) {1647 .exited => |c| if (c != 0) return error.NetworkError,1648 else => return error.NetworkError,1649 }1650 return tmp_path;1651}165216531654pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1655 const len = try std.process.executablePath(io, buf);1656 return buf[0..len];1657}16581659166016611662pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1663 const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1664 errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1665 return error.FileNotFound;1666 };1667 defer gpa.free(bytes);16681669 var hasher = std.crypto.hash.Blake3.init(.{});1670 hasher.update(bytes);1671 var raw: [32]u8 = undefined;1672 hasher.final(&raw);1673 const hex = std.fmt.bytesToHex(raw, .lower);1674 if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;16751676 var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1677 const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1678 return error.NameTooLong;16791680 {1681 const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1682 errors.error_info.setMessage("cannot write to {s}", .{install_path});1683 errors.error_info.setSuggestion("try: sudo nina update", .{});1684 return error.AccessDenied;1685 };1686 defer f.close(io);1687 f.writePositionalAll(io, bytes, 0) catch {1688 errors.error_info.setMessage("cannot write to {s}", .{install_path});1689 return error.AccessDenied;1690 };1691 try f.setPermissions(io, .fromMode(0o755));1692 }1693 errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};16941695 if (comptime builtin.os.tag == .macos) {1696 _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1697 }16981699 std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1700 error.AccessDenied => {1701 errors.error_info.setMessage("cannot replace {s}", .{install_path});1702 errors.error_info.setSuggestion("try: sudo nina update", .{});1703 return error.AccessDenied;1704 },1705 else => return e,1706 };1707}1708170917101711pub const NixFeatureStatus = struct {1712 nix_command: bool = false,1713 flakes: bool = false,17141715 pub fn allEnabled(self: NixFeatureStatus) bool {1716 return self.nix_command and self.flakes;1717 }1718};17191720fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {1721 var lines = std.mem.splitScalar(u8, conf, '\n');1722 while (lines.next()) |line| {1723 const trimmed = std.mem.trim(u8, line, " \t");1724 if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;1725 if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;1726 if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;1727 }1728}17291730pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {1731 var status = NixFeatureStatus{};17321733 if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {1734 defer gpa.free(conf);1735 scanConfFeatures(conf, &status);1736 }17371738 if (environ.get("HOME")) |home| {1739 var buf: [512]u8 = undefined;1740 const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;1741 if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {1742 defer gpa.free(conf);1743 scanConfFeatures(conf, &status);1744 }1745 }17461747 return status;1748}17491750pub fn isNixOS(io: std.Io) bool {1751 const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;1752 file.close(io);1753 return true;1754}1755175617571758pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {1759 const home = environ.get("HOME") orelse {1760 errors.error_info.setMessage("HOME not set", .{});1761 return error.ConfigNotFound;1762 };17631764 const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});1765 defer gpa.free(dir_path);1766 const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});1767 errdefer gpa.free(file_path);17681769 _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};17701771 const line = "experimental-features = nix-command flakes\n";1772 const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch1773 (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {1774 errors.error_info.setMessage("could not write {s}", .{file_path});1775 return error.FileNotFound;1776 });1777 defer file.close(io);17781779 const size = file.length(io) catch 0;1780 file.writePositionalAll(io, line, size) catch {1781 errors.error_info.setMessage("could not write {s}", .{file_path});1782 return error.FileNotFound;1783 };17841785 return file_path;1786}17871788178917901791179217931794pub const NIXOS_FEATURES_LINE =1795 "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";1796179717981799pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {1800 const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;1801 defer gpa.free(conf);1802 return std.mem.indexOf(u8, conf, "experimental-features") != null and1803 std.mem.indexOf(u8, conf, "nix-command") != null and1804 std.mem.indexOf(u8, conf, "flakes") != null;1805}18061807fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {1808 if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;1809 return captureLocal(gpa, io, &.{ "sudo", "cat", path });1810}181118121813181418151816pub fn appendFeaturesToNixosConfig(1817 gpa: std.mem.Allocator,1818 io: std.Io,1819 environ: *const std.process.Environ.Map,1820 path: []const u8,1821) !void {1822 const conf = readMaybeSudo(gpa, io, path) catch {1823 errors.error_info.setMessage("could not read {s}", .{path});1824 return error.ConfigNotFound;1825 };1826 defer gpa.free(conf);18271828 if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; 18291830 const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {1831 errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});1832 return error.MalformedConfig;1833 };18341835 const home = environ.get("HOME") orelse {1836 errors.error_info.setMessage("HOME not set", .{});1837 return error.ConfigNotFound;1838 };1839 const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});1840 defer gpa.free(tmp_path);18411842 var buf: std.ArrayList(u8) = .empty;1843 defer buf.deinit(gpa);1844 try buf.appendSlice(gpa, conf[0..brace]);1845 if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');1846 try buf.appendSlice(gpa, " # added by nina setup — flakes + the new nix CLI\n");1847 try buf.appendSlice(gpa, " ");1848 try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);1849 try buf.append(gpa, '\n');1850 try buf.appendSlice(gpa, conf[brace..]);18511852 const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {1853 errors.error_info.setMessage("could not write {s}", .{tmp_path});1854 return error.FileNotFound;1855 };1856 tmp.writePositionalAll(io, buf.items, 0) catch {1857 tmp.close(io);1858 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1859 errors.error_info.setMessage("could not write {s}", .{tmp_path});1860 return error.FileNotFound;1861 };1862 tmp.close(io);18631864 1865 1866 1867 const code = streamLocal(io, &.{1868 "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,1869 }) catch {1870 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1871 errors.error_info.setMessage("could not write {s}", .{path});1872 return error.ProcessFailed;1873 };1874 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};1875 if (code != 0) {1876 errors.error_info.setMessage("sudo cp into {s} failed", .{path});1877 return error.ProcessFailed;1878 }1879}