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, extra_flags: []const []const u8) !u8 {355 var argv: std.ArrayList([]const u8) = .empty;356 defer argv.deinit(gpa);357 try argv.appendSlice(gpa, &.{ "sudo", "nixos-rebuild", verb });358 if (flake) try argv.appendSlice(gpa, &.{ "--flake", machine.config_path });359 try argv.appendSlice(gpa, extra_flags);360361 output.flush();362 const r = try capture(gpa, io, machine, argv.items);363 defer gpa.free(r.stdout);364 defer gpa.free(r.stderr);365 errors.setBuildStderr(r.stderr);366 return r.exit_code;367}368369pub fn nixosRebuildSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {370 const flake = useFlakeFlag(gpa, io, machine);371 if (flake) {372 output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});373 } else {374 output.printSubstep("nixos-rebuild switch", .{});375 }376 return nixosRebuildRun(io, machine, gpa, "switch", flake, extra_flags);377}378379380381382383pub fn nixosRebuildSwitchWithPanel(384 io: std.Io,385 machine: *const types.Machine,386 gpa: std.mem.Allocator,387 panel: *output.BuildPanel,388 extra_flags: []const []const u8,389) !u8 {390 const flake = useFlakeFlag(gpa, io, machine);391 if (flake) {392 output.printSubstep("nixos-rebuild switch --flake {s}", .{machine.config_path});393 } else {394 output.printSubstep("nixos-rebuild switch", .{});395 }396 if (!output.colorEnabled()) return nixosRebuildRun(io, machine, gpa, "switch", flake, extra_flags);397 return nixosRebuildRunStreamed(io, machine, gpa, "switch", flake, panel, extra_flags);398}399400401402403404fn runStreamedCapture(io: std.Io, gpa: std.mem.Allocator, argv: []const []const u8, panel: *output.BuildPanel) !u8 {405 var child = std.process.spawn(io, .{406 .argv = argv,407 .stdin = .ignore,408 .stdout = .ignore,409 .stderr = .pipe,410 }) catch |e| {411 errors.error_info.setMessage("failed to spawn nixos-rebuild", .{});412 return e;413 };414415 var accumulated: std.ArrayList(u8) = .empty;416 defer accumulated.deinit(gpa);417418 if (child.stderr) |stderr_file| {419 var reader_buf: [8192]u8 = undefined;420 var fr = std.Io.File.Reader.initStreaming(stderr_file, io, &reader_buf);421 while (true) {422 const raw = fr.interface.takeDelimiter('\n') catch |err| switch (err) {423 424 425 426 427 428 error.StreamTooLong => {429 _ = fr.interface.discardDelimiterInclusive('\n') catch break;430 continue;431 },432 error.ReadFailed => break,433 } orelse break;434 435 436 accumulated.appendSlice(gpa, raw) catch {};437 accumulated.append(gpa, '\n') catch {};438 const line = std.mem.trimEnd(u8, raw, "\r");439 panel.update(line);440 panel.render();441 }442 }443444 errors.setBuildStderr(accumulated.items);445446 const term = child.wait(io) catch |e| {447 errors.error_info.setMessage("nixos-rebuild wait failed", .{});448 return e;449 };450 return switch (term) {451 .exited => |code| code,452 else => 1,453 };454}455456fn nixosRebuildRunStreamed(457 io: std.Io,458 machine: *const types.Machine,459 gpa: std.mem.Allocator,460 verb: []const u8,461 flake: bool,462 panel: *output.BuildPanel,463 extra_flags: []const []const u8,464) !u8 {465 var argv_list: std.ArrayList([]const u8) = .empty;466 defer argv_list.deinit(gpa);467 try argv_list.appendSlice(gpa, &.{ "sudo", "nixos-rebuild", verb });468 if (flake) try argv_list.appendSlice(gpa, &.{ "--flake", machine.config_path });469 try argv_list.appendSlice(gpa, extra_flags);470471 output.flush();472 const built_argv = try buildArgv(gpa, machine, argv_list.items);473 defer if (!machine.local) gpa.free(built_argv);474475 return runStreamedCapture(io, gpa, built_argv, panel);476}477478test "runStreamedCapture preserves newlines and survives an oversized stderr line (NINA-001/002)" {479 const a = std.testing.allocator;480 const io = std.testing.io;481482 var panel: output.BuildPanel = .{};483484 485 486 487 var oversized: [9000]u8 = undefined;488 @memset(&oversized, 'x');489490 const script = try std.fmt.allocPrint(a,491 \\printf 'these 3 paths will be fetched (12.3 MiB download, 45.6 MiB unpacked)\n'492 \\printf '%s\n' "{s}"493 \\printf 'error: nina test canary xyz-explanation\n'494 \\printf 'For full logs, run some-command\n'495 \\exit 1496 , .{oversized});497 defer a.free(script);498499 const exit_code = try runStreamedCapture(io, a, &.{ "sh", "-c", script }, &panel);500 try std.testing.expectEqual(@as(u8, 1), exit_code);501502 const stderr = errors.getBuildStderr();503 504 505 506 try std.testing.expect(std.mem.indexOf(u8, stderr, "error: nina test canary xyz-explanation\n") != null);507508 const translated = errors.translateError(a, stderr);509 510 511 512 try std.testing.expect(!std.mem.eql(u8, translated.body, "something went wrong that nina couldn't translate."));513}514515pub fn nixosRebuildDryActivate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {516 return nixosRebuildRun(io, machine, gpa, "dry-activate", useFlakeFlag(gpa, io, machine), extra_flags);517}518519pub fn nixosRebuildBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {520 return nixosRebuildRun(io, machine, gpa, "build", useFlakeFlag(gpa, io, machine), extra_flags);521}522523524525526527528529530531532const GEN_LIST_SCRIPT =533 \\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 }'534;535536pub fn getGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.GenerationInfo {537 const r = try capture(gpa, io, machine, &.{ "sh", "-c", GEN_LIST_SCRIPT });538 defer gpa.free(r.stderr);539 defer gpa.free(r.stdout);540 if (r.exit_code != 0) return error.ProcessFailed;541 return parseGenerations(gpa, r.stdout);542}543544fn parseGenerations(gpa: std.mem.Allocator, output_str: []const u8) ![]types.GenerationInfo {545 var gens: std.ArrayList(types.GenerationInfo) = .empty;546 var lines = std.mem.splitScalar(u8, output_str, '\n');547 while (lines.next()) |line| {548 const trimmed = std.mem.trim(u8, line, " \t");549 if (trimmed.len == 0) continue;550 var parts = std.mem.tokenizeAny(u8, trimmed, " \t");551 const num_str = parts.next() orelse continue;552 const date_str = parts.next() orelse continue;553 const time_str = parts.next() orelse continue;554 const rest = parts.rest();555 const current = std.mem.indexOf(u8, rest, "current") != null;556 const num = std.fmt.parseInt(u32, num_str, 10) catch continue;557 try gens.append(gpa, .{558 .number = num,559 .date = try gpa.dupe(u8, date_str),560 .time = try gpa.dupe(u8, time_str),561 .current = current,562 });563 }564 return gens.toOwnedSlice(gpa);565}566567pub fn getCurrentGeneration(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !u32 {568 const gens = try getGenerations(gpa, io, machine);569 defer gpa.free(gens);570 for (gens) |g| {571 if (g.current) return g.number;572 }573 return 0;574}575576pub fn switchGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {577 578 579 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 });580 defer gpa.free(cmd);581 return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });582}583584pub fn rollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {585 return stream(io, machine, gpa, &.{ "sudo", "nixos-rebuild", "switch", "--rollback" });586}587588pub fn deleteGeneration(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, n: u32) !u8 {589 const n_str = try std.fmt.allocPrint(gpa, "{d}", .{n});590 defer gpa.free(n_str);591 return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", n_str });592}593594pub fn deleteOldGenerations(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {595 return stream(io, machine, gpa, &.{ "sudo", "nix-env", "-p", SYSTEM_PROFILE, "--delete-generations", "old" });596}597598599600pub fn collectGarbage(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, delete_old: bool, keep: u32) !u8 {601 if (delete_old) {602 return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage", "-d" });603 }604 605 606 607 const cmd = try std.fmt.allocPrint(gpa, "nix-env -p {s} --delete-generations +{d} && nix-collect-garbage", .{ SYSTEM_PROFILE, keep });608 defer gpa.free(cmd);609 return stream(io, machine, gpa, &.{ "sudo", "sh", "-c", cmd });610}611612613614pub fn channelList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.ChannelInfo {615 const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });616 defer gpa.free(r.stderr);617 defer gpa.free(r.stdout);618 if (r.exit_code != 0) return error.ProcessFailed;619 return parseChannels(gpa, r.stdout);620}621622fn parseChannels(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ChannelInfo {623 var channels: std.ArrayList(types.ChannelInfo) = .empty;624 var lines = std.mem.splitScalar(u8, output_str, '\n');625 while (lines.next()) |line| {626 const trimmed = std.mem.trim(u8, line, " \t\r");627 if (trimmed.len == 0) continue;628 const space = std.mem.indexOfScalar(u8, trimmed, ' ') orelse continue;629 try channels.append(gpa, .{630 .name = try gpa.dupe(u8, trimmed[0..space]),631 .url = try gpa.dupe(u8, std.mem.trim(u8, trimmed[space + 1 ..], " \t")),632 });633 }634 return channels.toOwnedSlice(gpa);635}636637pub fn channelUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {638 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--update" });639}640641pub fn channelAdd(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8, name: []const u8) !u8 {642 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--add", url, name });643}644645pub fn channelRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8) !u8 {646 return stream(io, machine, gpa, &.{ "sudo", "nix-channel", "--remove", name });647}648649650651pub fn serviceList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, user: bool) ![]types.ServiceInfo {652 const cmd: []const []const u8 = if (user)653 &.{ "systemctl", "--user", "list-units", "--type=service", "--no-legend", "--no-pager" }654 else655 &.{ "systemctl", "list-units", "--type=service", "--no-legend", "--no-pager" };656 const r = try capture(gpa, io, machine, cmd);657 defer gpa.free(r.stderr);658 defer gpa.free(r.stdout);659 if (r.exit_code != 0) return error.ProcessFailed;660 return parseServices(gpa, r.stdout);661}662663fn parseServices(gpa: std.mem.Allocator, output_str: []const u8) ![]types.ServiceInfo {664 var svcs: std.ArrayList(types.ServiceInfo) = .empty;665 var lines = std.mem.splitScalar(u8, output_str, '\n');666 while (lines.next()) |line| {667 const trimmed = std.mem.trim(u8, line, " \t\r");668 if (trimmed.len == 0 or trimmed[0] == 0xE2) continue; 669 var parts = std.mem.tokenizeAny(u8, trimmed, " \t");670 const name = parts.next() orelse continue;671 _ = parts.next(); 672 const active_str = parts.next() orelse continue;673 const sub_str = parts.next() orelse "unknown";674675 const state: types.ServiceState = if (std.mem.eql(u8, active_str, "active"))676 (if (std.mem.eql(u8, sub_str, "running") or std.mem.eql(u8, sub_str, "exited")) .active else .active)677 else if (std.mem.eql(u8, active_str, "failed"))678 .failed679 else680 .inactive;681682 try svcs.append(gpa, .{683 .name = try gpa.dupe(u8, name),684 .state = state,685 .uptime = null,686 });687 }688 return svcs.toOwnedSlice(gpa);689}690691pub fn serviceCtl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, verb: []const u8, name: []const u8, user: bool) !u8 {692 693 694 if (user) {695 return stream(io, machine, gpa, &.{ "systemctl", "--user", "--no-pager", verb, name });696 }697 return stream(io, machine, gpa, &.{ "sudo", "systemctl", "--no-pager", verb, name });698}699700pub fn serviceLogs(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, name: []const u8, last: u32, follow: bool, user: bool) !u8 {701 const n_str = try std.fmt.allocPrint(gpa, "{d}", .{last});702 defer gpa.free(n_str);703 if (user) {704 if (follow) return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-f" });705 return stream(io, machine, gpa, &.{ "journalctl", "--user", "-u", name, "-n", n_str, "--no-pager" });706 }707 if (follow) {708 return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-f" });709 }710 return stream(io, machine, gpa, &.{ "journalctl", "-u", name, "-n", n_str, "--no-pager" });711}712713714715716717718fn streamWithEnvVar(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, cmd: []const []const u8, base_env: *const std.process.Environ.Map, key: []const u8, val: []const u8) !u8 {719 output.flush();720 const argv = try buildArgv(gpa, machine, cmd);721 defer if (!machine.local) gpa.free(argv);722723 var env = try base_env.clone(gpa);724 defer env.deinit();725 try env.put(key, val);726727 var child = std.process.spawn(io, .{728 .argv = argv,729 .stdin = .inherit,730 .stdout = .inherit,731 .stderr = .inherit,732 .environ_map = &env,733 }) catch |e| {734 errors.error_info.setMessage("failed to spawn: {s}", .{cmd[0]});735 return e;736 };737738 const term = child.wait(io) catch |e| {739 errors.error_info.setMessage("process wait failed", .{});740 return e;741 };742743 return switch (term) {744 .exited => |c| c,745 else => 1,746 };747}748749pub fn profileInstall(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, environ: *const std.process.Environ.Map, attr: []const u8, allow_unfree: bool) !u8 {750 const pkg_ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{attr});751 defer gpa.free(pkg_ref);752 753 754 if (allow_unfree) {755 756 757 758 759 return streamWithEnvVar(io, machine, gpa, &.{ "nix", "profile", "add", "--impure", pkg_ref }, environ, "NIXPKGS_ALLOW_UNFREE", "1");760 }761 return stream(io, machine, gpa, &.{ "nix", "profile", "add", pkg_ref });762}763764pub fn profileRemove(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: []const u8) !u8 {765 766 767 return stream(io, machine, gpa, &.{ "nix", "profile", "remove", attr });768}769770pub fn profileList(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {771 const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list" });772 defer gpa.free(r.stderr);773 if (r.exit_code != 0) return error.ProcessFailed;774 return r.stdout;775}776777778pub fn profileListJson(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {779 const r = try capture(gpa, io, machine, &.{ "nix", "profile", "list", "--json" });780 defer gpa.free(r.stderr);781 if (r.exit_code != 0) {782 gpa.free(r.stdout);783 return error.ProcessFailed;784 }785 return r.stdout;786}787788789790791792793pub fn profileNinaElement(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ?[]const u8 {794 const js = profileListJson(gpa, io, machine) catch return null;795 defer gpa.free(js);796 return profileJsonNinaElement(gpa, js);797}798799800pub fn profileHasNina(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) bool {801 const name = profileNinaElement(gpa, io, machine) orelse return false;802 gpa.free(name);803 return true;804}805806807808809810fn storePathIsNina(path: []const u8) bool {811 const prefix = "/nix/store/";812 if (!std.mem.startsWith(u8, path, prefix)) return false;813 const rel = path[prefix.len..];814 815 const entry = rel[0 .. std.mem.indexOf(u8, rel, "/") orelse rel.len];816 if (entry.len < 34) return false; 817 const pname_ver = entry[33..]; 818 return std.mem.startsWith(u8, pname_ver, "nina-") or std.mem.eql(u8, pname_ver, "nina");819}820821822823824825826fn profileJsonNinaElement(gpa: std.mem.Allocator, js: []const u8) ?[]const u8 {827 var parsed = std.json.parseFromSlice(std.json.Value, gpa, js, .{}) catch return null;828 defer parsed.deinit();829 const root = parsed.value;830 if (root != .object) return null;831 const elements = root.object.get("elements") orelse return null;832 switch (elements) {833 .object => |obj| {834 835 if (obj.contains("nina")) return gpa.dupe(u8, "nina") catch null;836 837 838 839 var it = obj.iterator();840 while (it.next()) |kv| {841 const val = kv.value_ptr.*;842 if (val != .object) continue;843 const sps = val.object.get("storePaths") orelse continue;844 if (sps != .array) continue;845 for (sps.array.items) |sp| {846 if (sp == .string and storePathIsNina(sp.string))847 return gpa.dupe(u8, kv.key_ptr.*) catch null;848 }849 }850 return null;851 },852 .array => |arr| {853 854 for (arr.items) |el| {855 if (el != .object) continue;856 const ap = el.object.get("attrPath") orelse continue;857 if (ap != .string) continue;858 if (std.mem.eql(u8, ap.string, "nina") or859 std.mem.endsWith(u8, ap.string, ".nina"))860 return gpa.dupe(u8, "nina") catch null;861 862 863 const sps = el.object.get("storePaths") orelse continue;864 if (sps != .array) continue;865 for (sps.array.items) |sp| {866 if (sp != .string) continue;867 if (!storePathIsNina(sp.string)) continue;868 const dot = std.mem.lastIndexOf(u8, ap.string, ".") orelse 0;869 const el_name = if (dot > 0) ap.string[dot + 1 ..] else ap.string;870 return gpa.dupe(u8, el_name) catch null;871 }872 }873 return null;874 },875 else => return null,876 }877}878879test "profileJsonNinaElement finds element name from profile JSON" {880 const a = std.testing.allocator;881882 883 const named =884 \\{"elements":{"bat":{"storePaths":["/nix/store/h0000000000000000000000000000000-bat-0.26.1"]},885 \\"nina":{"attrPath":"packages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}},"version":3}886 ;887 const r1 = profileJsonNinaElement(a, named);888 defer if (r1) |n| a.free(n);889 try std.testing.expectEqualStrings("nina", r1.?);890891 892 const default_key =893 \\{"elements":{"default":{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}},"version":3}894 ;895 const r2 = profileJsonNinaElement(a, default_key);896 defer if (r2) |n| a.free(n);897 try std.testing.expectEqualStrings("default", r2.?);898899 900 const decoy =901 \\{"elements":{"luminance":{"storePaths":["/nix/store/x0000000000000000000000000000000-luminance-nina-1.0"]}},"version":3}902 ;903 const r3 = profileJsonNinaElement(a, decoy);904 try std.testing.expectEqual(@as(?[]const u8, null), r3);905906 907 const arr =908 \\{"elements":[{"attrPath":"legacyPackages.x86_64-linux.nina","storePaths":["/nix/store/a0000000000000000000000000000000-nina-3.0.15"]}],"version":2}909 ;910 const r4 = profileJsonNinaElement(a, arr);911 defer if (r4) |n| a.free(n);912 try std.testing.expectEqualStrings("nina", r4.?);913914 915 const arr_default =916 \\{"elements":[{"attrPath":"packages.x86_64-linux.default","storePaths":["/nix/store/w0000000000000000000000000000000-nina-3.0.16"]}],"version":2}917 ;918 const r5 = profileJsonNinaElement(a, arr_default);919 defer if (r5) |n| a.free(n);920 try std.testing.expectEqualStrings("default", r5.?);921922 923 try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "{\"elements\":{},\"version\":3}"));924 try std.testing.expectEqual(@as(?[]const u8, null), profileJsonNinaElement(a, "not json"));925}926927928929930pub fn systemPackagePaths(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {931 const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", "/run/current-system/sw" });932 defer gpa.free(r.stderr);933 if (r.exit_code != 0) {934 gpa.free(r.stdout);935 return error.ProcessFailed;936 }937 return r.stdout;938}939940pub fn profileUpgrade(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {941 return stream(io, machine, gpa, &.{ "nix", "profile", "upgrade", ".*" });942}943944945946pub fn storeGc(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {947 return stream(io, machine, gpa, &.{ "sudo", "nix-collect-garbage" });948}949950pub fn storeVerify(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {951 return stream(io, machine, gpa, &.{ "nix", "store", "verify", "--all" });952}953954955956pub fn storeOptimise(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {957 return stream(io, machine, gpa, &.{ "nix", "store", "optimise" });958}959960pub const SystemStatus = struct { size: []u8, age: []u8 };961962963964965966const STATUS_SCRIPT =967 \\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} ))"968;969970pub fn systemStatus(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) SystemStatus {971 const unknown = SystemStatus{972 .size = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },973 .age = gpa.dupe(u8, "") catch return .{ .size = "", .age = "" },974 };975 const r = capture(gpa, io, machine, &.{ "sh", "-c", STATUS_SCRIPT }) catch return unknown;976 defer gpa.free(r.stdout);977 defer gpa.free(r.stderr);978 if (r.exit_code != 0) return unknown;979980 var it = std.mem.tokenizeAny(u8, r.stdout, " \t\n\r");981 const sz_str = it.next() orelse return unknown;982 const age_str = it.next() orelse return unknown;983 const bytes = std.fmt.parseInt(u64, sz_str, 10) catch 0;984 const age_secs = std.fmt.parseInt(u64, age_str, 10) catch 0;985986 gpa.free(unknown.size);987 gpa.free(unknown.age);988 return .{989 .size = humanSize(gpa, bytes) catch (gpa.dupe(u8, "") catch ""),990 .age = humanAgo(gpa, age_secs) catch (gpa.dupe(u8, "") catch ""),991 };992}993994995996997pub fn systemRunningState(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {998 const r = capture(gpa, io, machine, &.{ "systemctl", "is-system-running" }) catch999 return gpa.dupe(u8, "unknown");1000 defer gpa.free(r.stderr);1001 const state = std.mem.trim(u8, r.stdout, " \t\n\r");1002 const owned = try gpa.dupe(u8, if (state.len > 0) state else "unknown");1003 gpa.free(r.stdout);1004 return owned;1005}10061007fn humanAgo(gpa: std.mem.Allocator, secs: u64) ![]u8 {1008 if (secs < 60) return std.fmt.allocPrint(gpa, "{d}s ago", .{secs});1009 if (secs < 3600) return std.fmt.allocPrint(gpa, "{d}m ago", .{secs / 60});1010 if (secs < 86400) return std.fmt.allocPrint(gpa, "{d}h ago", .{secs / 3600});1011 return std.fmt.allocPrint(gpa, "{d}d ago", .{secs / 86400});1012}10131014pub fn storeRepair(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1015 return stream(io, machine, gpa, &.{ "sudo", "nix", "store", "repair", "--all" });1016}10171018pub fn storeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) !types.StoreInfo {1019 1020 1021 1022 1023 1024 1025 const pi = try capture(gpa, io, machine, &.{ "sh", "-c", "timeout 90 nix path-info --all --json 2>/dev/null" });1026 defer gpa.free(pi.stdout);1027 defer gpa.free(pi.stderr);10281029 const scan = scanStoreJson(pi.stdout);1030 const total_owned = try humanSize(gpa, scan.total_bytes);10311032 return .{1033 .total_size = total_owned,1034 .live_paths = scan.count,1035 .reclaimable_paths = 0,1036 };1037}10381039const StoreScan = struct { count: u64, total_bytes: u64 };10401041104210431044fn scanStoreJson(json_str: []const u8) StoreScan {1045 const needle = "\"narSize\":";1046 var count: u64 = 0;1047 var total: u64 = 0;1048 var i: usize = 0;1049 while (std.mem.indexOfPos(u8, json_str, i, needle)) |pos| {1050 var j = pos + needle.len;1051 while (j < json_str.len and json_str[j] == ' ') : (j += 1) {}1052 var val: u64 = 0;1053 var any = false;1054 while (j < json_str.len and json_str[j] >= '0' and json_str[j] <= '9') : (j += 1) {1055 val = val * 10 + (json_str[j] - '0');1056 any = true;1057 }1058 if (any) {1059 count += 1;1060 total += val;1061 }1062 i = j;1063 }1064 return .{ .count = count, .total_bytes = total };1065}10661067fn humanSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1068 const units = [_][]const u8{ "B", "KB", "MB", "GB", "TB" };1069 var val: f64 = @floatFromInt(bytes);1070 var unit: usize = 0;1071 while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1072 if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1073 return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1074}10751076pub fn storePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, attr: []const u8) ![]u8 {1077 1078 1079 const expr = try std.fmt.allocPrint(gpa, "nixpkgs#{s}.outPath", .{attr});1080 defer gpa.free(expr);1081 const r = try capture(gpa, io, machine, &.{ "nix", "eval", "--raw", expr });1082 defer gpa.free(r.stderr);1083 if (r.exit_code != 0) {1084 gpa.free(r.stdout);1085 return error.ProcessFailed;1086 }1087 return r.stdout;1088}1089109010911092pub fn flakeUpdate(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, input: ?[]const u8, extra_flags: []const []const u8) !u8 {1093 var argv: std.ArrayList([]const u8) = .empty;1094 defer argv.deinit(gpa);1095 try argv.appendSlice(gpa, &.{ "nix", "flake", "update" });1096 if (input) |inp| try argv.append(gpa, inp);1097 try argv.appendSlice(gpa, extra_flags);1098 return stream(io, machine, gpa, argv.items);1099}11001101110211031104pub fn flakeUpdateAt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, dir: []const u8) !u8 {1105 return stream(io, machine, gpa, &.{ "sh", "-c", "cd \"$0\" && nix flake update", dir });1106}11071108pub fn flakeCheck(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {1109 var argv: std.ArrayList([]const u8) = .empty;1110 defer argv.deinit(gpa);1111 try argv.appendSlice(gpa, &.{ "nix", "flake", "check" });1112 try argv.appendSlice(gpa, extra_flags);1113 return stream(io, machine, gpa, argv.items);1114}11151116pub fn flakeInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1117 return stream(io, machine, gpa, &.{ "nix", "flake", "init" });1118}11191120pub fn flakeLock(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1121 return stream(io, machine, gpa, &.{ "nix", "flake", "lock" });1122}11231124pub fn flakeClone(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, url: []const u8) !u8 {1125 return stream(io, machine, gpa, &.{ "nix", "flake", "clone", url });1126}11271128pub fn flakeShow(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1129 const r = try capture(gpa, io, machine, &.{ "nix", "flake", "show", "--json" });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 nixBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, attr: ?[]const u8, extra_flags: []const []const u8) !u8 {1141 var argv: std.ArrayList([]const u8) = .empty;1142 defer argv.deinit(gpa);1143 try argv.append(gpa, "nix");1144 try argv.append(gpa, "build");1145 var ref_buf: ?[]u8 = null;1146 defer if (ref_buf) |r| gpa.free(r);1147 if (attr) |a| {1148 ref_buf = try std.fmt.allocPrint(gpa, ".#{s}", .{a});1149 try argv.append(gpa, ref_buf.?);1150 }1151 try argv.appendSlice(gpa, extra_flags);1152 return stream(io, machine, gpa, argv.items);1153}11541155pub fn nixRun(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, extra_flags: []const []const u8) !u8 {1156 1157 const is_url = std.mem.startsWith(u8, pkg, "http://") or std.mem.startsWith(u8, pkg, "https://") or std.mem.startsWith(u8, pkg, "github:");11581159 var argv: std.ArrayList([]const u8) = .empty;1160 defer argv.deinit(gpa);1161 try argv.append(gpa, "nix");1162 try argv.append(gpa, "run");11631164 var ref_buf: ?[]u8 = null;1165 defer if (ref_buf) |r| gpa.free(r);1166 if (is_url) {1167 try argv.append(gpa, pkg);1168 try argv.append(gpa, "--no-write-lock-file");1169 } else if (std.mem.indexOfScalar(u8, pkg, '#') != null) {1170 1171 try argv.append(gpa, pkg);1172 } else {1173 ref_buf = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1174 try argv.append(gpa, ref_buf.?);1175 }11761177 1178 1179 try argv.appendSlice(gpa, extra_flags);1180 return stream(io, machine, gpa, argv.items);1181}11821183pub fn nixShell(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1184 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1185 defer gpa.free(ref);1186 return stream(io, machine, gpa, &.{ "nix", "shell", ref });1187}11881189pub fn nixShellPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8, base_env: *const std.process.Environ.Map) !u8 {1190 const ref = try std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1191 defer gpa.free(ref);1192 const ps1 = try std.fmt.allocPrint(gpa, "(nina: {s}) -> ", .{pkg});1193 defer gpa.free(ps1);1194 if (machine.local) {1195 const rc_path = try createInteractiveShellRc(gpa, io);1196 defer {1197 std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1198 gpa.free(rc_path);1199 }1200 return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref, "--command", "bash", "--rcfile", rc_path, "-i" }, base_env, ps1);1201 }1202 return streamEnv(io, machine, gpa, &.{ "nix", "shell", ref }, base_env, ps1);1203}12041205pub fn nixDevelop(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8, extra_flags: []const []const u8) !u8 {1206 if (run_cmd) |cmd| {1207 1208 var argv: std.ArrayList([]const u8) = .empty;1209 defer argv.deinit(gpa);1210 try argv.appendSlice(gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1211 try argv.appendSlice(gpa, extra_flags);1212 return stream(io, machine, gpa, argv.items);1213 }1214 var argv: std.ArrayList([]const u8) = .empty;1215 defer argv.deinit(gpa);1216 try argv.append(gpa, "nix");1217 try argv.append(gpa, "develop");1218 try argv.appendSlice(gpa, extra_flags);1219 return stream(io, machine, gpa, argv.items);1220}12211222pub fn nixDevelopPs1(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, run_cmd: ?[]const u8, base_env: *const std.process.Environ.Map, extra_flags: []const []const u8) !u8 {1223 if (run_cmd) |cmd| {1224 1225 var argv: std.ArrayList([]const u8) = .empty;1226 defer argv.deinit(gpa);1227 try argv.appendSlice(gpa, &.{ "nix", "develop", "--command", "sh", "-c", cmd });1228 try argv.appendSlice(gpa, extra_flags);1229 return stream(io, machine, gpa, argv.items);1230 }1231 if (machine.local) {1232 const rc_path = try createInteractiveShellRc(gpa, io);1233 defer {1234 std.Io.Dir.deleteFile(.cwd(), io, rc_path) catch {};1235 gpa.free(rc_path);1236 }1237 var argv: std.ArrayList([]const u8) = .empty;1238 defer argv.deinit(gpa);1239 try argv.append(gpa, "nix");1240 try argv.append(gpa, "develop");1241 try argv.appendSlice(gpa, extra_flags);1242 try argv.appendSlice(gpa, &.{ "--command", "bash", "--rcfile", rc_path, "-i" });1243 return streamEnv(io, machine, gpa, argv.items, base_env, "(nina: dev) -> ");1244 }1245 var argv: std.ArrayList([]const u8) = .empty;1246 defer argv.deinit(gpa);1247 try argv.append(gpa, "nix");1248 try argv.append(gpa, "develop");1249 try argv.appendSlice(gpa, extra_flags);1250 return streamEnv(io, machine, gpa, argv.items, base_env, "(nina: dev) -> ");1251}12521253pub fn nixRepl(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1254 return stream(io, machine, gpa, &.{ "nix", "repl", "--expr", "import <nixpkgs> {}" });1255}1256125712581259pub fn nixpkgsFmt(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, path: []const u8, check: bool) !u8 {1260 if (check) {1261 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", "--check", path });1262 }1263 return stream(io, machine, gpa, &.{ "nixpkgs-fmt", path });1264}1265126612671268pub fn systemInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1269 const r = try capture(gpa, io, machine, &.{"nixos-version"});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 kernelInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1279 const r = try capture(gpa, io, machine, &.{ "uname", "-r" });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}12871288pub fn uptimeInfo(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1289 const r = try capture(gpa, io, machine, &.{"uptime"});1290 defer gpa.free(r.stderr);1291 if (r.exit_code != 0) {1292 gpa.free(r.stdout);1293 return error.ProcessFailed;1294 }1295 return r.stdout;1296}1297129812991300pub fn bootEntries(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.BootEntry {1301 const r = try capture(gpa, io, machine, &.{ "bootctl", "list" });1302 defer gpa.free(r.stderr);1303 defer gpa.free(r.stdout);1304 if (r.exit_code != 0) return error.ProcessFailed;1305 return parseBootEntries(gpa, r.stdout);1306}13071308fn parseBootEntries(gpa: std.mem.Allocator, output_str: []const u8) ![]types.BootEntry {1309 var entries: std.ArrayList(types.BootEntry) = .empty;1310 var lines = std.mem.splitScalar(u8, output_str, '\n');1311 while (lines.next()) |line| {1312 const trimmed = std.mem.trim(u8, line, " \t\r");1313 if (std.mem.startsWith(u8, trimmed, "title:")) {1314 const title = std.mem.trim(u8, trimmed[6..], " \t");1315 const current = std.mem.indexOf(u8, title, "(current)") != null;1316 try entries.append(gpa, .{1317 .title = try gpa.dupe(u8, title),1318 .current = current,1319 });1320 }1321 }1322 return entries.toOwnedSlice(gpa);1323}1324132513261327fn pkgInstallable(gpa: std.mem.Allocator, pkg: []const u8) ![]u8 {1328 return std.fmt.allocPrint(gpa, "nixpkgs#{s}", .{pkg});1329}13301331fn resolvePkgStorePath(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, installable: []const u8) ![]u8 {1332 const r = try capture(gpa, io, machine, &.{ "nix", "build", "--no-link", "--print-out-paths", installable });1333 defer gpa.free(r.stderr);1334 defer gpa.free(r.stdout);1335 if (r.exit_code != 0) return error.PackageNotFound;13361337 var lines = std.mem.tokenizeAny(u8, r.stdout, "\r\n");1338 const first_path = lines.next() orelse return error.PackageNotFound;1339 const store_path = std.mem.trim(u8, first_path, " \t");1340 if (store_path.len == 0) return error.PackageNotFound;1341 return gpa.dupe(u8, store_path);1342}13431344pub fn pkgWhy(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1345 const installable = try pkgInstallable(gpa, pkg);1346 defer gpa.free(installable);1347 const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1348 defer gpa.free(store_path);1349 return stream(io, machine, gpa, &.{ "nix", "why-depends", "/run/current-system", store_path });1350}13511352pub fn pkgDeps(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1353 const installable = try pkgInstallable(gpa, pkg);1354 defer gpa.free(installable);1355 const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1356 defer gpa.free(store_path);1357 return stream(io, machine, gpa, &.{ "nix-store", "--query", "--requisites", store_path });1358}13591360pub fn pkgSize(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, pkg: []const u8) ![]u8 {1361 const installable = try pkgInstallable(gpa, pkg);1362 defer gpa.free(installable);1363 const r = try capture(gpa, io, machine, &.{ "nix", "path-info", "-s", "--json", installable });1364 defer gpa.free(r.stderr);1365 defer gpa.free(r.stdout);1366 if (r.exit_code != 0) return error.ProcessFailed;13671368 const nar_size = try pathInfoNarSize(gpa, r.stdout);1369 return humanPkgSize(gpa, nar_size);1370}13711372pub fn pkgClosure(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, pkg: []const u8) !u8 {1373 const installable = try pkgInstallable(gpa, pkg);1374 defer gpa.free(installable);1375 const store_path = try resolvePkgStorePath(gpa, io, machine, installable);1376 defer gpa.free(store_path);1377 return stream(io, machine, gpa, &.{ "nix", "path-info", "-rS", store_path });1378}13791380fn pathInfoNarSize(gpa: std.mem.Allocator, json_str: []const u8) !u64 {1381 var parsed = std.json.parseFromSlice(std.json.Value, gpa, json_str, .{}) catch return error.ProcessFailed;1382 defer parsed.deinit();1383 switch (parsed.value) {1384 .object => |obj| {1385 var it = obj.iterator();1386 while (it.next()) |entry| {1387 if (entry.value_ptr.* == .object) {1388 if (entry.value_ptr.object.get("narSize")) |v| {1389 if (v == .integer and v.integer >= 0) return @intCast(v.integer);1390 }1391 }1392 }1393 },1394 .array => |arr| {1395 for (arr.items) |item| {1396 if (item == .object) {1397 if (item.object.get("narSize")) |v| {1398 if (v == .integer and v.integer >= 0) return @intCast(v.integer);1399 }1400 }1401 }1402 },1403 else => {},1404 }1405 return error.ProcessFailed;1406}14071408fn humanPkgSize(gpa: std.mem.Allocator, bytes: u64) ![]u8 {1409 const units = [_][]const u8{ "B", "KiB", "MiB", "GiB", "TiB" };1410 var val: f64 = @floatFromInt(bytes);1411 var unit: usize = 0;1412 while (val >= 1024.0 and unit + 1 < units.len) : (unit += 1) val /= 1024.0;1413 if (unit == 0) return std.fmt.allocPrint(gpa, "{d} {s}", .{ bytes, units[0] });1414 return std.fmt.allocPrint(gpa, "{d:.1} {s}", .{ val, units[unit] });1415}14161417test "pathInfoNarSize parses object and array shapes" {1418 try std.testing.expectEqual(@as(u64, 1064629862), try pathInfoNarSize(std.testing.allocator,1419 \\{"/nix/store/abc-ffmpeg":{"narSize":1064629862}}1420 ));1421 try std.testing.expectEqual(@as(u64, 2048), try pathInfoNarSize(std.testing.allocator,1422 \\[{"path":"/nix/store/abc-pkg","narSize":2048}]1423 ));1424}1425142614271428pub fn nixHash(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, path: []const u8) ![]u8 {1429 const r = try capture(gpa, io, machine, &.{ "nix", "hash", "path", path });1430 defer gpa.free(r.stderr);1431 if (r.exit_code != 0) {1432 gpa.free(r.stdout);1433 return error.ProcessFailed;1434 }1435 return r.stdout;1436}14371438pub fn nixFetch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, url: []const u8) ![]u8 {1439 const r = try capture(gpa, io, machine, &.{ "nix-prefetch-url", url });1440 defer gpa.free(r.stderr);1441 if (r.exit_code != 0) {1442 gpa.free(r.stdout);1443 return error.ProcessFailed;1444 }1445 return r.stdout;1446}1447144814491450pub fn editFlakeLock(_: std.mem.Allocator, _: []const u8, _: []const u8) !void {1451 1452 1453}14541455pub fn openEditor(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8, line: ?u32) !u8 {1456 if (line) |l| {1457 const line_arg = try std.fmt.allocPrint(gpa, "+{d}", .{l});1458 defer gpa.free(line_arg);1459 return stream(io, &types.Machine{}, gpa, &.{ editor, path, line_arg });1460 }1461 return stream(io, &types.Machine{}, gpa, &.{ editor, path });1462}14631464146514661467pub fn openEditorSudo(io: std.Io, gpa: std.mem.Allocator, editor: []const u8, path: []const u8) !u8 {1468 return stream(io, &types.Machine{}, gpa, &.{ "sudo", "-E", editor, path });1469}14701471pub fn diffClosures(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a: u32, b: u32) !u8 {1472 const a_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{a});1473 defer gpa.free(a_str);1474 const b_str = try std.fmt.allocPrint(gpa, "/nix/var/nix/profiles/system-{d}-link", .{b});1475 defer gpa.free(b_str);1476 1477 if (output.colorEnabled()) {1478 return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_str, b_str });1479 }1480 1481 1482 const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_str, b_str });1483 defer gpa.free(r.stdout);1484 defer gpa.free(r.stderr);1485 const cleaned = try stripAnsi(gpa, r.stdout);1486 defer gpa.free(cleaned);1487 output.raw(cleaned);1488 return r.exit_code;1489}1490149114921493fn stripAnsi(gpa: std.mem.Allocator, input: []const u8) ![]u8 {1494 var out: std.ArrayList(u8) = .empty;1495 errdefer out.deinit(gpa);1496 var i: usize = 0;1497 while (i < input.len) {1498 if (input[i] == 0x1b and i + 1 < input.len and input[i + 1] == '[') {1499 i += 2;1500 while (i < input.len and !(input[i] >= 0x40 and input[i] <= 0x7e)) : (i += 1) {}1501 if (i < input.len) i += 1; 1502 continue;1503 }1504 try out.append(gpa, input[i]);1505 i += 1;1506 }1507 return out.toOwnedSlice(gpa);1508}15091510test "stripAnsi removes CSI color sequences" {1511 const cleaned = try stripAnsi(std.testing.allocator, "kepr: \x1b[31;1m13.1 KiB\x1b[0m");1512 defer std.testing.allocator.free(cleaned);1513 try std.testing.expectEqualStrings("kepr: 13.1 KiB", cleaned);1514}1515151615171518pub fn runDoctorChecks(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]types.DoctorCheck {1519 var checks: std.ArrayList(types.DoctorCheck) = .empty;15201521 1522 {1523 const r = try capture(gpa, io, machine, &.{ "systemctl", "is-active", "nix-daemon" });1524 defer gpa.free(r.stdout);1525 defer gpa.free(r.stderr);1526 const active = std.mem.indexOf(u8, r.stdout, "active") != null;1527 try checks.append(gpa, .{ .name = "nix daemon", .status = if (active) .ok else .fail });1528 }15291530 1531 1532 1533 {1534 const argv: []const []const u8 = if (useFlakeFlag(gpa, io, machine))1535 &.{ "sudo", "nixos-rebuild", "dry-build", "--flake", machine.config_path }1536 else1537 &.{ "sudo", "nixos-rebuild", "dry-build" };1538 const r = try capture(gpa, io, machine, argv);1539 defer gpa.free(r.stdout);1540 defer gpa.free(r.stderr);1541 try checks.append(gpa, .{ .name = "config syntax", .status = if (r.exit_code == 0) .ok else .fail });1542 }15431544 1545 {1546 const r = try capture(gpa, io, machine, &.{ "nix-channel", "--list" });1547 defer gpa.free(r.stdout);1548 defer gpa.free(r.stderr);1549 const has_channel = r.exit_code == 0 and r.stdout.len > 0;1550 try checks.append(gpa, .{ .name = "channel", .status = if (has_channel) .ok else .warn });1551 }15521553 return checks.toOwnedSlice(gpa);1554}15551556155715581559156015611562pub const HomeManagerMode = enum {1563 1564 standalone,1565 1566 1567 module,1568 none,1569};15701571fn homeConfigDir(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1572 const home = environ.get("HOME") orelse return null;1573 return std.fmt.allocPrint(gpa, "{s}/.config/home-manager", .{home}) catch null;1574}157515761577pub fn homeNixPath(gpa: std.mem.Allocator, environ: *const std.process.Environ.Map) ?[]const u8 {1578 const dir = homeConfigDir(gpa, environ) orelse return null;1579 defer gpa.free(dir);1580 return std.fmt.allocPrint(gpa, "{s}/home.nix", .{dir}) catch null;1581}15821583pub fn pathExists(io: std.Io, path: []const u8) bool {1584 const f = std.Io.Dir.openFile(.cwd(), io, path, .{}) catch return false;1585 f.close(io);1586 return true;1587}1588158915901591fn commandExists(gpa: std.mem.Allocator, io: std.Io, name: []const u8) bool {1592 var buf: [256]u8 = undefined;1593 const cmd = std.fmt.bufPrint(&buf, "command -v {s} >/dev/null 2>&1", .{name}) catch return false;1594 const r = std.process.run(gpa, io, .{ .argv = &.{ "sh", "-c", cmd } }) catch return false;1595 defer gpa.free(r.stdout);1596 defer gpa.free(r.stderr);1597 return switch (r.term) {1598 .exited => |code| code == 0,1599 else => false,1600 };1601}16021603pub fn detectHomeManager(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) HomeManagerMode {1604 if (commandExists(gpa, io, "home-manager")) return .standalone;1605 if (homeNixPath(gpa, environ)) |p| {1606 defer gpa.free(p);1607 if (pathExists(io, p)) return .module;1608 }1609 return .none;1610}16111612161316141615pub fn homeFlakeDir(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ?[]const u8 {1616 const dir = homeConfigDir(gpa, environ) orelse return null;1617 const flake = std.fmt.allocPrint(gpa, "{s}/flake.nix", .{dir}) catch {1618 gpa.free(dir);1619 return null;1620 };1621 defer gpa.free(flake);1622 if (!pathExists(io, flake)) {1623 gpa.free(dir);1624 return null;1625 }1626 return dir;1627}162816291630163116321633pub fn homeManagerAttr(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, environ: *const std.process.Environ.Map) ![]const u8 {1634 const user = environ.get("USER") orelse "user";16351636 const arch_r = try capture(gpa, io, machine, &.{ "uname", "-m" });1637 defer gpa.free(arch_r.stdout);1638 defer gpa.free(arch_r.stderr);1639 if (arch_r.exit_code != 0) return error.ProcessFailed;1640 const arch = std.mem.trim(u8, arch_r.stdout, " \t\r\n");16411642 const os_r = try capture(gpa, io, machine, &.{ "uname", "-s" });1643 defer gpa.free(os_r.stdout);1644 defer gpa.free(os_r.stderr);1645 if (os_r.exit_code != 0) return error.ProcessFailed;1646 const os = try gpa.dupe(u8, std.mem.trim(u8, os_r.stdout, " \t\r\n"));1647 defer gpa.free(os);1648 for (os) |*ch| ch.* = std.ascii.toLower(ch.*);16491650 if (arch.len == 0 or os.len == 0) return error.ProcessFailed;1651 return std.fmt.allocPrint(gpa, "{s}-{s}-{s}", .{ user, arch, os });1652}165316541655165616571658fn homeBranchFromVersion(gpa: std.mem.Allocator, version_raw: []const u8) ![]const u8 {1659 const v = std.mem.trim(u8, version_raw, " \t\r\n");1660 if (std.mem.indexOf(u8, v, "pre") != null or1661 std.mem.indexOf(u8, v, "unstable") != null)1662 return gpa.dupe(u8, "master");16631664 const head = v[0 .. std.mem.indexOfScalar(u8, v, ' ') orelse v.len];1665 var it = std.mem.splitScalar(u8, head, '.');1666 const major = it.next() orelse "";1667 const minor = it.next() orelse "";1668 if (allDigits(major) and allDigits(minor))1669 return std.fmt.allocPrint(gpa, "release-{s}.{s}", .{ major, minor });16701671 return gpa.dupe(u8, "master");1672}16731674fn allDigits(s: []const u8) bool {1675 if (s.len == 0) return false;1676 for (s) |ch| if (!std.ascii.isDigit(ch)) return false;1677 return true;1678}16791680test "homeBranchFromVersion maps channels to HM branches" {1681 const a = std.testing.allocator;1682 const cases = [_]struct { in: []const u8, want: []const u8 }{1683 .{ .in = "25.05.20250115.abcdef (Warbler)", .want = "release-25.05" },1684 .{ .in = "24.11.20241201.deadbee (Vicuna)", .want = "release-24.11" },1685 .{ .in = "25.11pre-git", .want = "master" },1686 .{ .in = "25.05pre789012.abcdef (Warbler)", .want = "master" },1687 .{ .in = "nixos-unstable", .want = "master" },1688 .{ .in = "garbage", .want = "master" },1689 };1690 for (cases) |c| {1691 const got = try homeBranchFromVersion(a, c.in);1692 defer a.free(got);1693 try std.testing.expectEqualStrings(c.want, got);1694 }1695}1696169716981699fn detectHomeManagerBranch(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]const u8 {1700 const r = capture(gpa, io, machine, &.{"nixos-version"}) catch1701 return gpa.dupe(u8, "master");1702 defer gpa.free(r.stdout);1703 defer gpa.free(r.stderr);1704 if (r.exit_code != 0) return gpa.dupe(u8, "master");1705 return homeBranchFromVersion(gpa, r.stdout);1706}17071708170917101711pub fn homeManagerInit(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, switch_on_init: bool, dir: ?[]const u8) !u8 {1712 const branch = try detectHomeManagerBranch(gpa, io, machine);1713 defer gpa.free(branch);1714 const flake_ref = try std.fmt.allocPrint(gpa, "home-manager/{s}", .{branch});1715 defer gpa.free(flake_ref);17161717 var argv: std.ArrayList([]const u8) = .empty;1718 defer argv.deinit(gpa);1719 try argv.appendSlice(gpa, &.{ "nix", "run", flake_ref, "--", "init" });1720 if (switch_on_init) try argv.append(gpa, "--switch");1721 if (dir) |d| try argv.append(gpa, d);17221723 return stream(io, machine, gpa, argv.items);1724}17251726pub fn homeManagerSwitch(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {1727 output.flush();1728 var argv: std.ArrayList([]const u8) = .empty;1729 defer argv.deinit(gpa);1730 try argv.appendSlice(gpa, &.{ "home-manager", "switch" });1731 try argv.appendSlice(gpa, extra_flags);1732 const r = try capture(gpa, io, machine, argv.items);1733 defer gpa.free(r.stdout);1734 defer gpa.free(r.stderr);1735 errors.setBuildStderr(r.stderr);1736 return r.exit_code;1737}17381739174017411742pub const SwitchOutcome = enum { ok, attr_missing, failed };17431744pub fn homeManagerSwitchFlake(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, flake_ref: []const u8, extra_flags: []const []const u8) !SwitchOutcome {1745 output.flush();1746 var argv: std.ArrayList([]const u8) = .empty;1747 defer argv.deinit(gpa);1748 try argv.appendSlice(gpa, &.{ "home-manager", "switch", "--flake", flake_ref });1749 try argv.appendSlice(gpa, extra_flags);1750 const r = try capture(gpa, io, machine, argv.items);1751 defer gpa.free(r.stdout);1752 defer gpa.free(r.stderr);1753 if (r.exit_code == 0) return .ok;1754 1755 1756 1757 if (std.mem.indexOf(u8, r.stderr, "does not provide attribute") != null)1758 return .attr_missing;1759 errors.setBuildStderr(r.stderr);1760 return .failed;1761}1762176317641765pub fn homeManagerRollback(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator) !u8 {1766 output.flush();1767 const r = try capture(gpa, io, machine, &.{ "home-manager", "switch", "--rollback" });1768 defer gpa.free(r.stdout);1769 defer gpa.free(r.stderr);1770 errors.setBuildStderr(r.stderr);1771 return r.exit_code;1772}177317741775177617771778pub fn homeManagerBuild(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, extra_flags: []const []const u8) !u8 {1779 output.flush();1780 1781 1782 1783 var argv: std.ArrayList([]const u8) = .empty;1784 defer argv.deinit(gpa);1785 try argv.appendSlice(gpa, &.{ "sh", "-c", "d=$(mktemp -d) && cd \"$d\" && home-manager build \"$@\"", "--" });1786 try argv.appendSlice(gpa, extra_flags);1787 const r = try capture(gpa, io, machine, argv.items);1788 defer gpa.free(r.stdout);1789 defer gpa.free(r.stderr);1790 errors.setBuildStderr(r.stderr);1791 return r.exit_code;1792}17931794pub fn homeGenerations(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine) ![]u8 {1795 const r = try capture(gpa, io, machine, &.{ "home-manager", "generations" });1796 defer gpa.free(r.stderr);1797 if (r.exit_code != 0) {1798 gpa.free(r.stdout);1799 return error.ProcessFailed;1800 }1801 return r.stdout;1802}180318041805pub fn homeGenerationReferences(gpa: std.mem.Allocator, io: std.Io, machine: *const types.Machine, gen_path: []const u8) ![]u8 {1806 const r = try capture(gpa, io, machine, &.{ "nix-store", "-q", "--references", gen_path });1807 defer gpa.free(r.stderr);1808 if (r.exit_code != 0) {1809 gpa.free(r.stdout);1810 return error.ProcessFailed;1811 }1812 return r.stdout;1813}1814181518161817pub fn diffClosuresPaths(io: std.Io, machine: *const types.Machine, gpa: std.mem.Allocator, a_path: []const u8, b_path: []const u8) !u8 {1818 if (output.colorEnabled()) {1819 return stream(io, machine, gpa, &.{ "nix", "store", "diff-closures", a_path, b_path });1820 }1821 const r = try capture(gpa, io, machine, &.{ "nix", "store", "diff-closures", a_path, b_path });1822 defer gpa.free(r.stdout);1823 defer gpa.free(r.stderr);1824 const cleaned = try stripAnsi(gpa, r.stdout);1825 defer gpa.free(cleaned);1826 output.raw(cleaned);1827 return r.exit_code;1828}1829183018311832pub fn readNinaLog(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map, last: u32) ![]u8 {1833 const home = environ.get("HOME") orelse return error.FileNotFound;1834 const path = try std.fmt.allocPrint(gpa, "{s}/.nina.log", .{home});1835 defer gpa.free(path);1836 const content = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return error.FileNotFound;1837 if (last == 0) return content;18381839 1840 1841 var lines: std.ArrayList([]const u8) = .empty;1842 defer lines.deinit(gpa);1843 var it = std.mem.splitScalar(u8, content, '\n');1844 while (it.next()) |line| {1845 if (std.mem.trim(u8, line, " \t\r").len == 0) continue;1846 try lines.append(gpa, line);1847 }1848 if (lines.items.len <= last) return content;18491850 var out: std.ArrayList(u8) = .empty;1851 errdefer out.deinit(gpa);1852 for (lines.items[lines.items.len - last ..]) |line| {1853 try out.appendSlice(gpa, line);1854 try out.append(gpa, '\n');1855 }1856 gpa.free(content);1857 return out.toOwnedSlice(gpa);1858}185918601861186218631864pub fn markApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) void {1865 const home = environ.get("HOME") orelse return;1866 var buf: [512]u8 = undefined;1867 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return;1868 const file = std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return;1869 file.close(io);1870}18711872pub fn takeApplyFailed(io: std.Io, environ: *const std.process.Environ.Map) bool {1873 const home = environ.get("HOME") orelse return false;1874 var buf: [512]u8 = undefined;1875 const path = std.fmt.bufPrint(&buf, "{s}/.nina-apply-failed", .{home}) catch return false;1876 if (std.Io.Dir.openFile(.cwd(), io, path, .{})) |f| {1877 f.close(io);1878 std.Io.Dir.deleteFile(.cwd(), io, path) catch {};1879 return true;1880 } else |_| {1881 return false;1882 }1883}18841885pub fn appendNinaLog(io: std.Io, environ: *const std.process.Environ.Map, entry: []const u8) void {1886 const home = environ.get("HOME") orelse return;1887 var path_buf: [512]u8 = undefined;1888 const path = std.fmt.bufPrint(&path_buf, "{s}/.nina.log", .{home}) catch return;1889 const file = std.Io.Dir.openFile(.cwd(), io, path, .{ .mode = .read_write }) catch1890 (std.Io.Dir.createFile(.cwd(), io, path, .{}) catch return);1891 defer file.close(io);1892 const size = file.length(io) catch 0;1893 file.writePositionalAll(io, entry, size) catch {};1894}189518961897189818991900pub fn fetchUrl(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1901 const argv = [_][]const u8{1902 "curl", "-s", "-L", "-w", "\nHTTP_STATUS:%{http_code}", "-m", "30", "--", url,1903 };1904 const result = std.process.run(gpa, io, .{ .argv = &argv }) catch return error.NetworkError;1905 defer gpa.free(result.stderr);19061907 const marker = "\nHTTP_STATUS:";1908 const mark_idx = std.mem.lastIndexOf(u8, result.stdout, marker) orelse {1909 gpa.free(result.stdout);1910 return error.NetworkError;1911 };1912 const status_str = std.mem.trim(u8, result.stdout[mark_idx + marker.len ..], " \r\n");1913 const status = std.fmt.parseInt(u16, status_str, 10) catch {1914 gpa.free(result.stdout);1915 return error.NetworkError;1916 };1917 if (status == 0) { gpa.free(result.stdout); return error.NetworkError; }1918 if (status < 200 or status >= 300) { gpa.free(result.stdout); return error.HttpError; }1919 const body = gpa.dupe(u8, result.stdout[0..mark_idx]) catch |e| {1920 gpa.free(result.stdout);1921 return e;1922 };1923 gpa.free(result.stdout);1924 return body;1925}1926192719281929pub fn downloadToTemp(gpa: std.mem.Allocator, io: std.Io, url: []const u8) ![]u8 {1930 const tmp_path = try gpa.dupe(u8, "/tmp/nina-update.bin");1931 errdefer gpa.free(tmp_path);19321933 var child = std.process.spawn(io, .{1934 .argv = &.{ "curl", "-fsSL", "-m", "300", "-o", tmp_path, "--", url },1935 .stdin = .close,1936 .stdout = .close,1937 .stderr = .inherit,1938 }) catch return error.NetworkError;1939 const term = child.wait(io) catch return error.NetworkError;1940 switch (term) {1941 .exited => |c| if (c != 0) return error.NetworkError,1942 else => return error.NetworkError,1943 }1944 return tmp_path;1945}194619471948pub fn selfExePath(io: std.Io, buf: *[std.Io.Dir.max_path_bytes]u8) ![]const u8 {1949 const len = try std.process.executablePath(io, buf);1950 return buf[0..len];1951}19521953195419551956pub fn verifyAndInstall(gpa: std.mem.Allocator, io: std.Io, tmp_path: []const u8, expected_hex: []const u8, install_path: []const u8) !void {1957 const bytes = std.Io.Dir.readFileAlloc(.cwd(), io, tmp_path, gpa, .unlimited) catch {1958 errors.error_info.setMessage("downloaded file not found: {s}", .{tmp_path});1959 return error.FileNotFound;1960 };1961 defer gpa.free(bytes);19621963 var hasher = std.crypto.hash.Blake3.init(.{});1964 hasher.update(bytes);1965 var raw: [32]u8 = undefined;1966 hasher.final(&raw);1967 const hex = std.fmt.bytesToHex(raw, .lower);1968 if (!std.mem.eql(u8, &hex, expected_hex)) return error.ChecksumMismatch;19691970 var inst_tmp_buf: [std.Io.Dir.max_path_bytes + 8]u8 = undefined;1971 const inst_tmp = std.fmt.bufPrint(&inst_tmp_buf, "{s}.new", .{install_path}) catch1972 return error.NameTooLong;19731974 {1975 const f = std.Io.Dir.createFileAbsolute(io, inst_tmp, .{}) catch {1976 errors.error_info.setMessage("cannot write to {s}", .{install_path});1977 errors.error_info.setSuggestion("try: sudo nina update", .{});1978 return error.AccessDenied;1979 };1980 defer f.close(io);1981 f.writePositionalAll(io, bytes, 0) catch {1982 errors.error_info.setMessage("cannot write to {s}", .{install_path});1983 return error.AccessDenied;1984 };1985 try f.setPermissions(io, .fromMode(0o755));1986 }1987 errdefer std.Io.Dir.deleteFileAbsolute(io, inst_tmp) catch {};19881989 if (comptime builtin.os.tag == .macos) {1990 _ = captureLocal(gpa, io, &.{ "codesign", "-f", "-s", "-", inst_tmp }) catch {};1991 }19921993 std.Io.Dir.renameAbsolute(inst_tmp, install_path, io) catch |e| switch (e) {1994 error.AccessDenied => {1995 errors.error_info.setMessage("cannot replace {s}", .{install_path});1996 errors.error_info.setSuggestion("try: sudo nina update", .{});1997 return error.AccessDenied;1998 },1999 else => return e,2000 };2001}2002200320042005pub const NixFeatureStatus = struct {2006 nix_command: bool = false,2007 flakes: bool = false,20082009 pub fn allEnabled(self: NixFeatureStatus) bool {2010 return self.nix_command and self.flakes;2011 }2012};20132014fn scanConfFeatures(conf: []const u8, status: *NixFeatureStatus) void {2015 var lines = std.mem.splitScalar(u8, conf, '\n');2016 while (lines.next()) |line| {2017 const trimmed = std.mem.trim(u8, line, " \t");2018 if (!std.mem.startsWith(u8, trimmed, "experimental-features")) continue;2019 if (std.mem.indexOf(u8, trimmed, "nix-command") != null) status.nix_command = true;2020 if (std.mem.indexOf(u8, trimmed, "flakes") != null) status.flakes = true;2021 }2022}20232024pub fn checkNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) NixFeatureStatus {2025 var status = NixFeatureStatus{};20262027 if (std.Io.Dir.readFileAlloc(.cwd(), io, "/etc/nix/nix.conf", gpa, .unlimited) catch null) |conf| {2028 defer gpa.free(conf);2029 scanConfFeatures(conf, &status);2030 }20312032 if (environ.get("HOME")) |home| {2033 var buf: [512]u8 = undefined;2034 const path = std.fmt.bufPrint(&buf, "{s}/.config/nix/nix.conf", .{home}) catch return status;2035 if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |conf| {2036 defer gpa.free(conf);2037 scanConfFeatures(conf, &status);2038 }2039 }20402041 return status;2042}20432044pub fn isNixOS(io: std.Io) bool {2045 const file = std.Io.Dir.openFile(.cwd(), io, "/etc/NIXOS", .{}) catch return false;2046 file.close(io);2047 return true;2048}2049205020512052pub fn enableNixFeatures(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) ![]const u8 {2053 const home = environ.get("HOME") orelse {2054 errors.error_info.setMessage("HOME not set", .{});2055 return error.ConfigNotFound;2056 };20572058 const dir_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix", .{home});2059 defer gpa.free(dir_path);2060 const file_path = try std.fmt.allocPrint(gpa, "{s}/.config/nix/nix.conf", .{home});2061 errdefer gpa.free(file_path);20622063 _ = captureLocal(gpa, io, &.{ "mkdir", "-p", dir_path }) catch {};20642065 const line = "experimental-features = nix-command flakes\n";2066 const file = std.Io.Dir.openFile(.cwd(), io, file_path, .{ .mode = .read_write }) catch2067 (std.Io.Dir.createFile(.cwd(), io, file_path, .{}) catch {2068 errors.error_info.setMessage("could not write {s}", .{file_path});2069 return error.FileNotFound;2070 });2071 defer file.close(io);20722073 const size = file.length(io) catch 0;2074 file.writePositionalAll(io, line, size) catch {2075 errors.error_info.setMessage("could not write {s}", .{file_path});2076 return error.FileNotFound;2077 };20782079 return file_path;2080}20812082208320842085208620872088pub const NIXOS_FEATURES_LINE =2089 "nix.settings.experimental-features = [ \"nix-command\" \"flakes\" ];";2090209120922093pub fn nixosConfigEnablesFeatures(gpa: std.mem.Allocator, io: std.Io, path: []const u8) bool {2094 const conf = std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch return false;2095 defer gpa.free(conf);2096 return std.mem.indexOf(u8, conf, "experimental-features") != null and2097 std.mem.indexOf(u8, conf, "nix-command") != null and2098 std.mem.indexOf(u8, conf, "flakes") != null;2099}21002101fn readMaybeSudo(gpa: std.mem.Allocator, io: std.Io, path: []const u8) ![]u8 {2102 if (std.Io.Dir.readFileAlloc(.cwd(), io, path, gpa, .unlimited) catch null) |data| return data;2103 return captureLocal(gpa, io, &.{ "sudo", "cat", path });2104}210521062107210821092110pub fn appendFeaturesToNixosConfig(2111 gpa: std.mem.Allocator,2112 io: std.Io,2113 environ: *const std.process.Environ.Map,2114 path: []const u8,2115) !void {2116 const conf = readMaybeSudo(gpa, io, path) catch {2117 errors.error_info.setMessage("could not read {s}", .{path});2118 return error.ConfigNotFound;2119 };2120 defer gpa.free(conf);21212122 if (std.mem.indexOf(u8, conf, "experimental-features") != null) return; 21232124 const brace = std.mem.lastIndexOfScalar(u8, conf, '}') orelse {2125 errors.error_info.setMessage("no closing brace in {s} — add the line by hand", .{path});2126 return error.MalformedConfig;2127 };21282129 const home = environ.get("HOME") orelse {2130 errors.error_info.setMessage("HOME not set", .{});2131 return error.ConfigNotFound;2132 };2133 const tmp_path = try std.fmt.allocPrint(gpa, "{s}/.nina-configuration.nix", .{home});2134 defer gpa.free(tmp_path);21352136 var buf: std.ArrayList(u8) = .empty;2137 defer buf.deinit(gpa);2138 try buf.appendSlice(gpa, conf[0..brace]);2139 if (brace == 0 or conf[brace - 1] != '\n') try buf.append(gpa, '\n');2140 try buf.appendSlice(gpa, " # added by nina setup — flakes + the new nix CLI\n");2141 try buf.appendSlice(gpa, " ");2142 try buf.appendSlice(gpa, NIXOS_FEATURES_LINE);2143 try buf.append(gpa, '\n');2144 try buf.appendSlice(gpa, conf[brace..]);21452146 const tmp = std.Io.Dir.createFile(.cwd(), io, tmp_path, .{}) catch {2147 errors.error_info.setMessage("could not write {s}", .{tmp_path});2148 return error.FileNotFound;2149 };2150 tmp.writePositionalAll(io, buf.items, 0) catch {2151 tmp.close(io);2152 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2153 errors.error_info.setMessage("could not write {s}", .{tmp_path});2154 return error.FileNotFound;2155 };2156 tmp.close(io);21572158 2159 2160 2161 const code = streamLocal(io, &.{2162 "sudo", "sh", "-c", "cp -- \"$0\" \"$0.nina-bak\" && cp -- \"$1\" \"$0\"", path, tmp_path,2163 }) catch {2164 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2165 errors.error_info.setMessage("could not write {s}", .{path});2166 return error.ProcessFailed;2167 };2168 std.Io.Dir.deleteFile(.cwd(), io, tmp_path) catch {};2169 if (code != 0) {2170 errors.error_info.setMessage("sudo cp into {s} failed", .{path});2171 return error.ProcessFailed;2172 }2173}