123const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const config = @import("config.zig");8const output = @import("output.zig");9const exec = @import("exec.zig");10const api = @import("api.zig");11const search_tui = @import("search.zig");12const version = @import("version.zig");1314const UPDATE_URL = "https://kepr.uk/api/nina/releases/latest";15const FLAKE_URL = "https://kepr.uk/nina/archive/HEAD.tar.gz#nina";1617const Semver = struct {18 major: u32,19 minor: u32,20 patch: u32,21};2223pub const Ctx = struct {24 gpa: std.mem.Allocator,25 io: std.Io,26 environ: *const std.process.Environ.Map,27 machine: types.Machine,28 cfg: types.NinaConfig,29 args: []const []const u8, 30 passthrough: []const []const u8, 31 sub: []const u8, 32 dry: bool,33 check: bool,34 no_apply: bool,35 all: bool,36 last: u32,37 json: bool,38 user: bool, 39};4041424344fn flakeSystem(ctx: Ctx) bool {45 return ctx.cfg.flake or exec.configHasFlake(ctx.gpa, ctx.io, &ctx.machine);46}4748fn runPreHook(ctx: Ctx, hook_name: []const u8) !bool {49 const hook = try exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name);50 defer ctx.gpa.free(hook.output);51 switch (hook.result) {52 .not_found, .ok => return true,53 .failed => {54 output.hookFailed(ctx.gpa, hook_name, hook.exit_code, hook.output);55 return output.confirmDefaultNo("continue anyway?");56 },57 }58}5960fn runPostHook(ctx: Ctx, hook_name: []const u8) void {61 const hook = exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name) catch return;62 defer ctx.gpa.free(hook.output);63 if (hook.result == .failed) {64 output.hookWarning(hook_name, hook.exit_code, hook.output);65 }66}6768pub fn apply(ctx: Ctx) !void {69 if (ctx.dry) {70 output.applyDry(ctx.machine.name);71 const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);72 if (code != 0) return error.BuildFailed;73 output.applyDryDone();74 return;75 }76 if (ctx.check) {77 return check(ctx);78 }7980 if (!try runPreHook(ctx, "pre-apply")) {81 output.aborted();82 return error.HookAborted;83 }8485 output.applyStart(ctx.machine.name);86 output.buildPanelInit();87 const start = std.Io.Clock.awake.now(ctx.io);8889 var panel = output.BuildPanel{};90 const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel, ctx.passthrough) catch |e| {91 output.buildPanelClear();92 exec.markApplyFailed(ctx.io, ctx.environ);93 return e;94 };95 output.buildPanelClear();9697 if (code != 0) {98 exec.markApplyFailed(ctx.io, ctx.environ);99 return error.BuildFailed;100 }101102 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());103 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));104 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;105 const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);106 output.applyDone(gen, elapsed, after_failure);107 108 const warnings = errors.extractWarnings(ctx.gpa, errors.getBuildStderr()) catch &.{};109 defer {110 for (warnings) |w| ctx.gpa.free(w);111 ctx.gpa.free(warnings);112 }113 if (warnings.len > 0) output.buildWarnings(warnings);114 runPostHook(ctx, "post-apply");115 logAction(ctx, "apply", gen);116}117118pub fn check(ctx: Ctx) !void {119 output.checkStart(ctx.machine.name);120 const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);121 if (code != 0) return error.BuildFailed;122 output.checkOk();123}124125pub fn back(ctx: Ctx) !void {126 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);127 defer ctx.gpa.free(gens);128129 var current: u32 = 0;130 for (gens) |g| if (g.current) {131 current = g.number;132 };133134 135 136 var prev: u32 = 0;137 var has_prev = false;138 for (gens) |g| {139 if (g.number < current and (!has_prev or g.number > prev)) {140 prev = g.number;141 has_prev = true;142 }143 }144 if (!has_prev) {145 output.alreadyOldest();146 return;147 }148149 if (!try runPreHook(ctx, "pre-back")) {150 output.aborted();151 return error.HookAborted;152 }153154 output.backStart(ctx.machine.name, current, prev);155 if (ctx.cfg.confirm and !output.confirm("")) return;156157 158 159 160 const code = if (flakeSystem(ctx))161 try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, prev)162 else163 try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);164 if (code != 0) return error.BuildFailed;165 output.backDone(prev);166 runPostHook(ctx, "post-back");167}168169pub fn go(ctx: Ctx) !void {170 if (ctx.args.len == 0) return error.Internal;171 const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;172 const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);173174 output.goStart(ctx.machine.name, current, target);175 if (ctx.cfg.confirm and !output.confirm("")) return;176177 const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);178 if (code != 0) return error.ProcessFailed;179 output.generationDone(target);180}181182pub fn history(ctx: Ctx) !void {183 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);184 defer ctx.gpa.free(gens);185 output.historyHeader(ctx.machine.name);186 for (gens) |g| output.historyRow(g);187}188189const gen_help = [_][2][]const u8{190 .{ "list", "list generations" },191 .{ "current", "show current generation" },192 .{ "delete <n>", "delete generation n" },193 .{ "delete old", "delete old generations" },194};195196pub fn genCmd(ctx: Ctx) !void {197 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("gen", &gen_help, null);198 if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);199 if (std.mem.eql(u8, ctx.sub, "current")) {200 const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);201 output.genCurrent(n);202 return;203 }204 if (std.mem.eql(u8, ctx.sub, "delete")) {205 if (ctx.args.len == 0) return error.Internal;206 if (std.mem.eql(u8, ctx.args[0], "old")) {207 if (ctx.cfg.confirm and !output.confirm("")) return;208 _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);209 } else {210 const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;211 if (ctx.cfg.confirm and !output.confirm("")) return;212 _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);213 }214 output.done();215 return;216 }217 return error.Internal;218}219220pub fn clean(ctx: Ctx) !void {221 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);222 defer ctx.gpa.free(gens);223 const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");224 const total: u32 = @intCast(gens.len);225 226 227 const keep: u32 = if (all) 1 else ctx.cfg.generations;228 if (total <= keep) {229 output.cleanNothing(ctx.machine.name, total);230 return;231 }232 output.cleanStart(ctx.machine.name, keep, total);233 if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;234 _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);235 output.cleanDone();236}237238pub fn statusCmd(ctx: Ctx) !void {239 output.statusHeader();240 241 242 if (ctx.all and ctx.cfg.machines.len > 0) {243 for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);244 } else {245 statusRowFor(ctx, &ctx.machine);246 }247 homeStatusLine(ctx);248}249250251252253fn homeStatusLine(ctx: Ctx) void {254 if (exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ) != .standalone) return;255 const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return;256 defer ctx.gpa.free(out);257 const gens = parseHomeGenerations(ctx.gpa, out) catch return;258 defer freeHomeGens(ctx.gpa, gens);259 if (gens.len == 0) return;260 output.statusHomeRow(gens[0].number, gens[0].date);261}262263fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {264 265 266 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {267 output.statusRow(machine.name, 0, "", "", false);268 return;269 };270 const st = exec.systemStatus(ctx.gpa, ctx.io, machine);271 defer ctx.gpa.free(st.size);272 defer ctx.gpa.free(st.age);273 output.statusRow(machine.name, gen, st.age, st.size, true);274}275276277278279280281282283fn diffTargets(gens: []const types.GenerationInfo, args: []const []const u8) ?struct { a: u32, b: u32 } {284 var current: u32 = 0;285 var prev: u32 = 0;286 for (gens) |g| {287 if (g.current) current = g.number;288 if (!g.current and g.number > prev and g.number < current) prev = g.number;289 }290 if (args.len >= 2) {291 const a = std.fmt.parseInt(u32, args[0], 10) catch blk: {292 if (current == 0) return null;293 break :blk current - 1;294 };295 const b = std.fmt.parseInt(u32, args[1], 10) catch blk: {296 if (current == 0) return null;297 break :blk current;298 };299 return .{ .a = a, .b = b };300 }301 if (current == 0 or gens.len < 2) return null;302 return .{ .a = if (prev > 0) prev else current - 1, .b = current };303}304305pub fn diff(ctx: Ctx) !void {306 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);307 defer ctx.gpa.free(gens);308 const targets = diffTargets(gens, ctx.args) orelse {309 output.diffCannotDetermine();310 return;311 };312 output.diffHeader(targets.a, targets.b, ctx.machine.name);313 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, targets.a, targets.b) != 0) return error.ProcessFailed;314}315316test "diffTargets returns null when no generation is marked current" {317 const gens = [_]types.GenerationInfo{318 .{ .number = 1, .date = "", .time = "", .current = false },319 .{ .number = 2, .date = "", .time = "", .current = false },320 };321 try std.testing.expect(diffTargets(&gens, &.{}) == null);322}323324test "diffTargets returns null with fewer than two generations and no explicit args" {325 const gens = [_]types.GenerationInfo{326 .{ .number = 1, .date = "", .time = "", .current = true },327 };328 try std.testing.expect(diffTargets(&gens, &.{}) == null);329}330331test "diffTargets falls back to prev/current when both are known" {332 const gens = [_]types.GenerationInfo{333 .{ .number = 1, .date = "", .time = "", .current = false },334 .{ .number = 2, .date = "", .time = "", .current = true },335 };336 const targets = diffTargets(&gens, &.{}).?;337 try std.testing.expectEqual(@as(u32, 1), targets.a);338 try std.testing.expectEqual(@as(u32, 2), targets.b);339}340341test "diffTargets returns null when explicit args fail to parse and no current generation exists" {342 const gens = [_]types.GenerationInfo{343 .{ .number = 1, .date = "", .time = "", .current = false },344 };345 try std.testing.expect(diffTargets(&gens, &.{ "not-a-number", "2" }) == null);346}347348test "diffTargets uses explicit args verbatim when both parse" {349 const gens = [_]types.GenerationInfo{350 .{ .number = 1, .date = "", .time = "", .current = false },351 };352 const targets = diffTargets(&gens, &.{ "3", "5" }).?;353 try std.testing.expectEqual(@as(u32, 3), targets.a);354 try std.testing.expectEqual(@as(u32, 5), targets.b);355}356357pub fn mood(ctx: Ctx) !void {358 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;359 const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);360 defer ctx.gpa.free(st.size);361 defer ctx.gpa.free(st.age);362 const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");363 defer ctx.gpa.free(state);364 output.mood(ctx.machine.name, state, gen, st.age, st.size);365}366367pub fn doctor(ctx: Ctx) !void {368 output.doctorHeader(ctx.machine.name);369 const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);370 defer ctx.gpa.free(checks);371 var warnings: u32 = 0;372 var failures: u32 = 0;373 for (checks) |ch| {374 output.doctorRow(ch);375 if (ch.status == .warn) warnings += 1;376 if (ch.status == .fail) failures += 1;377 }378379 380 381 const hm_mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);382 if (hm_mode != .none) {383 const note = homeDoctorNote(ctx, hm_mode);384 defer ctx.gpa.free(note);385 output.doctorRow(.{ .name = "home manager", .status = .ok, .note = note });386 }387388 output.doctorSummary(warnings, failures);389}390391392393fn homeDoctorNote(ctx: Ctx, mode: exec.HomeManagerMode) []const u8 {394 const label = switch (mode) {395 .standalone => "standalone",396 .module => "module",397 .none => "",398 };399 if (mode == .standalone) {400 const gen = homeCurrentGen(ctx);401 if (gen != 0)402 return std.fmt.allocPrint(ctx.gpa, "{s} gen {d}", .{ label, gen }) catch403 (ctx.gpa.dupe(u8, label) catch "");404 }405 return ctx.gpa.dupe(u8, label) catch "";406}407408409pub fn update(ctx: Ctx) !void {410 output.updateSelfStart();411412 if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {413 output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));414 return error.Internal;415 }416417 const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");418 const source_url = env_url orelse UPDATE_URL;419420 const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {421 error.NetworkError, error.HttpError => {422 output.updateSelfNetworkError();423 return;424 },425 else => return e,426 };427 defer ctx.gpa.free(body);428429 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {430 output.printWarning("could not parse release metadata");431 return;432 };433 defer parsed.deinit();434435 const root = parsed.value;436 if (root != .object) {437 output.printWarning("malformed release metadata");438 return;439 }440441 const remote_ver = blk: {442 const v = root.object.get("version") orelse {443 output.printWarning("malformed release metadata");444 return;445 };446 break :blk switch (v) {447 .string => |s| s,448 else => {449 output.printWarning("malformed release metadata");450 return;451 },452 };453 };454 if (!remoteVersionNewer(version.VERSION, remote_ver)) {455 output.updateSelfCurrent(version.VERSION);456 return;457 }458459 const release_notes = try updateReleaseNotes(ctx.gpa, ctx.io, root, source_url, version.VERSION, remote_ver);460 defer ctx.gpa.free(release_notes);461462 output.updateSelfAvailable(version.VERSION, remote_ver);463 output.updateSelfReleaseNotes(release_notes);464 if (ctx.check) return;465466 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;467 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {468 errors.error_info.setMessage("could not determine install path", .{});469 return error.Internal;470 };471472 473 474 475 476 477 if (std.mem.startsWith(u8, install_path, "/nix/store/")) {478 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);479 defer if (nina_element) |n| ctx.gpa.free(n);480 if (nina_element == null) {481 output.updateSelfSystemManaged();482 return;483 }484 const element = nina_element.?;485 output.updateSelfNixManaged(remote_ver);486 if (ctx.cfg.confirm and !output.confirm("")) return;487 488 489 490 491 492 493 494 const prefetch_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "build", "--no-link", "--refresh", FLAKE_URL }) catch {495 output.updateSelfNixPrefetchFailed();496 return;497 };498 defer ctx.gpa.free(prefetch_r.stdout);499 defer ctx.gpa.free(prefetch_r.stderr);500 if (prefetch_r.exit_code != 0) {501 output.raw(prefetch_r.stdout);502 output.raw(prefetch_r.stderr);503 output.updateSelfNixPrefetchFailed();504 return;505 }506 507 508 509 510 511 512 513 514 const remove_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "remove", element }) catch {515 output.updateSelfNixFailed();516 return;517 };518 defer ctx.gpa.free(remove_r.stdout);519 defer ctx.gpa.free(remove_r.stderr);520 if (remove_r.exit_code != 0) {521 output.raw(remove_r.stdout);522 output.raw(remove_r.stderr);523 output.updateSelfNixFailed();524 return;525 }526 527 528 529 530 531 const add_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "add", "--no-write-lock-file", "--refresh", FLAKE_URL }) catch {532 output.updateSelfNixReinstallFailed();533 return;534 };535 defer ctx.gpa.free(add_r.stdout);536 defer ctx.gpa.free(add_r.stderr);537 if (add_r.exit_code != 0) {538 output.raw(add_r.stdout);539 output.raw(add_r.stderr);540 output.updateSelfNixReinstallFailed();541 return;542 }543 output.updateSelfDone(version.VERSION, remote_ver);544 output.updateSelfNixRehash();545 return;546 }547548 const plat_info = blk: {549 const pv = root.object.get("platforms") orelse break :blk null;550 if (pv != .object) break :blk null;551 break :blk pv.object.get(version.PLATFORM);552 };553 if (plat_info == null) {554 output.updateSelfNoPlatform(version.PLATFORM);555 return;556 }557558 const dl_url = blk: {559 const v = plat_info.?.object.get("url") orelse {560 output.printWarning("malformed release metadata");561 return;562 };563 break :blk switch (v) {564 .string => |s| s,565 else => {566 output.printWarning("malformed release metadata");567 return;568 },569 };570 };571572 const raw_cksum = blk: {573 if (plat_info.?.object.get("blake3")) |v|574 break :blk switch (v) {575 .string => |s| s,576 else => {577 output.printWarning("malformed release metadata");578 return;579 },580 };581 if (plat_info.?.object.get("checksum")) |v|582 break :blk switch (v) {583 .string => |s| s,584 else => {585 output.printWarning("malformed release metadata");586 return;587 },588 };589 output.printWarning("missing checksum in release metadata");590 return;591 };592 const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;593594 if (ctx.cfg.confirm and !output.confirm("")) return;595596 output.updateSelfDownloading(remote_ver, version.PLATFORM);597 const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {598 output.printWarning("download failed — check your connection and try again");599 return;600 };601 defer ctx.gpa.free(tmp_path);602 603 604 defer std.Io.Dir.deleteFileAbsolute(ctx.io, tmp_path) catch {};605606 output.updateSelfVerifying();607 exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {608 error.ChecksumMismatch => {609 output.updateSelfChecksumFailed();610 return;611 },612 else => return e,613 };614615 output.updateSelfDone(version.VERSION, remote_ver);616}617618619620621622623fn updateReleaseNotes(gpa: std.mem.Allocator, io: std.Io, root: std.json.Value, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {624 if (buildKeprArchiveReleaseNotes(gpa, io, source_url, current, latest) catch null) |notes| {625 if (std.mem.trim(u8, notes, " \t\r\n").len > 0) return notes;626 gpa.free(notes);627 }628 if (releaseNotesFromMetadata(gpa, root)) |notes| return notes;629 return gpa.dupe(u8, "");630}631632fn releaseNotesFromMetadata(gpa: std.mem.Allocator, root: std.json.Value) ?[]u8 {633 if (root != .object) return null;634 635 636 637 const v = root.object.get("notes") orelse return null;638 return switch (v) {639 .string => |s| gpa.dupe(u8, s) catch null,640 else => null,641 };642}643644fn buildKeprArchiveReleaseNotes(gpa: std.mem.Allocator, io: std.Io, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {645 const archive_url = try keprArchiveUrl(gpa, source_url);646 defer gpa.free(archive_url);647648 const body = exec.fetchUrl(gpa, io, archive_url) catch return gpa.dupe(u8, "");649 defer gpa.free(body);650651 return releaseNotesFromArchiveJson(gpa, body, current, latest);652}653654fn keprArchiveUrl(gpa: std.mem.Allocator, source_url: []const u8) ![]u8 {655 const scheme = std.mem.indexOf(u8, source_url, "://") orelse return error.InvalidUpdateSource;656 const path_start = std.mem.indexOfScalarPos(u8, source_url, scheme + 3, '/') orelse return error.InvalidUpdateSource;657 const origin = source_url[0..path_start];658 const path = source_url[path_start..];659 if (!std.mem.startsWith(u8, path, "/api/")) return error.InvalidUpdateSource;660661 const after_api = path["/api/".len..];662 const repo_end = std.mem.indexOfScalar(u8, after_api, '/') orelse return error.InvalidUpdateSource;663 const repo = after_api[0..repo_end];664 if (repo.len == 0) return error.InvalidUpdateSource;665666 return std.fmt.allocPrint(gpa, "{s}/{s}/archives.json?limit=100", .{ origin, repo });667}668669670671672673fn releaseNotesFromArchiveJson(gpa: std.mem.Allocator, body: []const u8, current: []const u8, latest: []const u8) ![]u8 {674 const parsed = std.json.parseFromSlice(std.json.Value, gpa, body, .{}) catch return gpa.dupe(u8, "");675 defer parsed.deinit();676677 if (parsed.value != .object) return gpa.dupe(u8, "");678 const saves_v = parsed.value.object.get("saves") orelse return gpa.dupe(u8, "");679 if (saves_v != .array) return gpa.dupe(u8, "");680681 682 var best_msg = std.StringHashMap([]const u8).init(gpa);683 defer best_msg.deinit();684 var order: std.ArrayList([]const u8) = .empty;685 defer order.deinit(gpa);686687 for (saves_v.array.items) |save| {688 if (save != .object) continue;689 const ver_v = save.object.get("version") orelse continue;690 const msg_v = save.object.get("message") orelse continue;691 if (ver_v != .string or msg_v != .string) continue;692 const ver = ver_v.string;693 const msg = std.mem.trim(u8, msg_v.string, " \t\r\n");694 if (msg.len == 0 or !versionInUpdateRange(ver, current, latest)) continue;695696 const entry = try best_msg.getOrPut(ver);697 if (!entry.found_existing) try order.append(gpa, ver);698 699 entry.value_ptr.* = msg;700 }701702 if (order.items.len == 0) return gpa.dupe(u8, "");703704 var out: std.ArrayList(u8) = .empty;705 errdefer out.deinit(gpa);706 for (order.items) |ver| {707 const msg = best_msg.get(ver).?;708 709 const summary_end = std.mem.indexOf(u8, msg, "\n") orelse msg.len;710 const summary = std.mem.trim(u8, msg[0..summary_end], " \t\r");711 if (summary.len == 0) continue;712 try appendLine(&out, gpa, "## {s}\n", .{ver});713 try appendLine(&out, gpa, "- {s}\n\n", .{summary});714 }715716 if (out.items.len == 0) {717 out.deinit(gpa);718 return gpa.dupe(u8, "");719 }720 return out.toOwnedSlice(gpa);721}722723fn appendLine(out: *std.ArrayList(u8), gpa: std.mem.Allocator, comptime template: []const u8, args: anytype) !void {724 const line = try std.fmt.allocPrint(gpa, template, args);725 defer gpa.free(line);726 try out.appendSlice(gpa, line);727}728729fn versionInUpdateRange(candidate: []const u8, current: []const u8, latest: []const u8) bool {730 const cand = parseSemver(candidate) orelse return std.mem.eql(u8, candidate, latest);731 const cur = parseSemver(current) orelse return std.mem.eql(u8, candidate, latest);732 const lat = parseSemver(latest) orelse return std.mem.eql(u8, candidate, latest);733 return compareSemver(cand, cur) == .gt and compareSemver(cand, lat) != .gt;734}735736fn remoteVersionNewer(current: []const u8, remote: []const u8) bool {737 const cur = parseSemver(current) orelse return !std.mem.eql(u8, current, remote);738 const rem = parseSemver(remote) orelse return !std.mem.eql(u8, current, remote);739 return compareSemver(rem, cur) == .gt;740}741742const VersionOrder = enum { lt, eq, gt };743744fn compareSemver(a: Semver, b: Semver) VersionOrder {745 if (a.major != b.major) return if (a.major < b.major) .lt else .gt;746 if (a.minor != b.minor) return if (a.minor < b.minor) .lt else .gt;747 if (a.patch != b.patch) return if (a.patch < b.patch) .lt else .gt;748 return .eq;749}750751fn parseSemver(raw: []const u8) ?Semver {752 const v = if (std.mem.startsWith(u8, raw, "v")) raw[1..] else raw;753 var it = std.mem.splitScalar(u8, v, '.');754 const major_s = it.next() orelse return null;755 const minor_s = it.next() orelse return null;756 const patch_s = it.next() orelse return null;757 if (it.next() != null) return null;758 return .{759 .major = std.fmt.parseInt(u32, major_s, 10) catch return null,760 .minor = std.fmt.parseInt(u32, minor_s, 10) catch return null,761 .patch = std.fmt.parseInt(u32, patch_s, 10) catch return null,762 };763}764765test "versionInUpdateRange includes only newer versions through latest" {766 try std.testing.expect(versionInUpdateRange("3.2.3", "3.1.9", "3.2.3"));767 try std.testing.expect(versionInUpdateRange("3.2.0", "3.1.9", "3.2.3"));768 try std.testing.expect(!versionInUpdateRange("3.1.9", "3.1.9", "3.2.3"));769 try std.testing.expect(!versionInUpdateRange("3.2.4", "3.1.9", "3.2.3"));770}771772test "remoteVersionNewer does not offer downgrades" {773 try std.testing.expect(remoteVersionNewer("3.2.3", "3.2.4"));774 try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.3"));775 try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.4"));776}777778test "releaseNotesFromArchiveJson uses oldest save per version" {779 780 781 const body =782 \\{783 \\ "saves": [784 \\ {"version":"3.2.3","message":"wip: record verification in CONTINUITY"},785 \\ {"version":"3.2.1","message":"old release"},786 \\ {"version":"3.2.3","message":"add streaming deflate path"}787 \\ ]788 \\}789 ;790 const notes = try releaseNotesFromArchiveJson(std.testing.allocator, body, "3.2.1", "3.2.3");791 defer std.testing.allocator.free(notes);792793 try std.testing.expect(std.mem.indexOf(u8, notes, "## 3.2.3") != null);794 try std.testing.expect(std.mem.indexOf(u8, notes, "- add streaming deflate path") != null);795 try std.testing.expect(std.mem.indexOf(u8, notes, "CONTINUITY") == null);796 try std.testing.expect(std.mem.indexOf(u8, notes, "old release") == null);797}798799test "releaseNotesFromMetadata reads canonical notes and ignores retired keys" {800 const a = std.testing.allocator;801802 803 {804 var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"notes\":\"colored progress bar\"}", .{});805 defer parsed.deinit();806 const got = releaseNotesFromMetadata(a, parsed.value).?;807 defer a.free(got);808 try std.testing.expectEqualStrings("colored progress bar", got);809 }810811 812 813 {814 var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"release_notes\":\"x\",\"changelog\":\"y\"}", .{});815 defer parsed.deinit();816 try std.testing.expect(releaseNotesFromMetadata(a, parsed.value) == null);817 }818}819820821822823pub fn goodbye(ctx: Ctx) !void {824 output.goodbyeStart();825826 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;827 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {828 errors.error_info.setMessage("could not determine install path", .{});829 return error.Internal;830 };831832 833 if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {834 output.goodbyeFile(install_path);835 if (ctx.cfg.confirm and !output.confirm("")) return;836 std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {837 errors.error_info.setMessage("could not remove {s}", .{install_path});838 return e;839 };840 output.goodbyeDone();841 return;842 }843844 845 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);846 defer {847 if (nina_element) |n| ctx.gpa.free(n);848 }849850 if (nina_element == null) {851 errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});852 return error.Internal;853 }854855 output.goodbyeNix();856 if (ctx.cfg.confirm and !output.confirm("")) return;857 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {858 output.goodbyeFailed("nix profile remove failed");859 return;860 };861 if (ec != 0) {862 output.goodbyeFailed("nix profile remove failed");863 return;864 }865 output.goodbyeDone();866}867868fn channelUpdateCmd(ctx: Ctx) !void {869 output.updateStart(ctx.machine.name);870 _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);871 output.updateDone();872}873874pub fn upgrade(ctx: Ctx) !void {875 if (!try runPreHook(ctx, "pre-upgrade")) {876 output.aborted();877 return error.HookAborted;878 }879880 output.upgradeStart(ctx.machine.name);881 882 883 884 if (flakeSystem(ctx)) {885 output.printSubstep("updating flake inputs", .{});886 _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};887 } else {888 output.printSubstep("updating channels", .{});889 _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};890 }891 output.printSubstep("rebuilding", .{});892 output.buildPanelInit();893 const start = std.Io.Clock.awake.now(ctx.io);894 var panel = output.BuildPanel{};895 const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel, ctx.passthrough) catch |e| {896 output.buildPanelClear();897 return e;898 };899 output.buildPanelClear();900 if (code != 0) {901 output.applyFailed("");902 return error.BuildFailed;903 }904 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());905 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));906 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;907 output.applyDone(gen, elapsed, false);908 runPostHook(ctx, "post-upgrade");909}910911pub fn log(ctx: Ctx) !void {912 output.logHeader(ctx.machine.name);913 const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {914 915 return;916 };917 defer ctx.gpa.free(content);918 var lines = std.mem.splitScalar(u8, content, '\n');919 while (lines.next()) |line| {920 const t = std.mem.trim(u8, line, " \t\r");921 if (t.len == 0) continue;922 if (t[0] == '{') {923 renderJsonLogLine(ctx.gpa, t);924 } else {925 926 var parts = std.mem.tokenizeScalar(u8, t, '\t');927 const date = parts.next() orelse continue;928 const time = parts.next() orelse "";929 const action = parts.next() orelse "";930 const detail = parts.next() orelse "";931 output.logRow(date, time, action, detail);932 }933 }934}935936937938fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {939 const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {940 941 942 943 const cleaned = output.sanitize(gpa, line) catch line;944 defer if (cleaned.ptr != line.ptr) gpa.free(cleaned);945 output.logRow(cleaned, "", "", "");946 return;947 };948 defer parsed.deinit();949 if (parsed.value != .object) return;950 const o = parsed.value.object;951952 const ts = jsonStr(o, "ts");953 const date = if (ts.len >= 10) ts[0..10] else ts;954 const time = if (ts.len >= 16) ts[11..16] else "";955 const action = jsonStr(o, "command");956 const outcome = jsonStr(o, "outcome");957958 var buf: [160]u8 = undefined;959 var detail: []const u8 = outcome;960 if (o.get("gen_after")) |g| {961 if (g == .integer) {962 detail = std.fmt.bufPrint(&buf, "{s} -> gen {d}", .{ outcome, g.integer }) catch outcome;963 }964 }965 output.logRow(date, time, action, detail);966}967968fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {969 if (o.get(key)) |v| {970 if (v == .string) return v.string;971 }972 return "";973}974975pub fn edit(ctx: Ctx) !void {976 977 978 979 if (std.mem.eql(u8, ctx.sub, "hardware")) {980 output.editHardwareWarning();981 return;982 }983984 985 986 var open_dir = false;987 for (ctx.args) |arg| {988 if (std.mem.eql(u8, arg, "--dir")) open_dir = true;989 }990 if (open_dir) {991 output.editOpen(ctx.machine.config_path, ctx.cfg.editor);992 _ = try exec.openEditorSudo(ctx.io, ctx.gpa, ctx.cfg.editor, ctx.machine.config_path);993 return;994 }995996 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});997 defer ctx.gpa.free(path);998 output.editOpen(path, ctx.cfg.editor);999 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1000}10011002pub fn fmt(ctx: Ctx) !void {1003 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1004 defer ctx.gpa.free(path);1005 if (ctx.check) {1006 const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);1007 if (code != 0) output.fmtNeedsFormat() else output.fmtDone();1008 return;1009 }1010 output.fmtStart(path);1011 _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);1012 output.fmtDone();1013}10141015pub fn repl(ctx: Ctx) !void {1016 output.replStart();1017 _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);1018}10191020pub fn develop(ctx: Ctx) !void {1021 if (std.mem.eql(u8, ctx.sub, "show")) {1022 _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null, ctx.passthrough);1023 return;1024 }1025 const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))1026 ctx.args[0]1027 else1028 null;1029 output.developStart(&.{});1030 _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ, ctx.passthrough);1031 output.developDone();1032}10331034pub fn info(ctx: Ctx) !void {1035 output.infoHeader(ctx.machine.name);1036 const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");1037 defer ctx.gpa.free(nixos_ver);1038 output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));10391040 const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");1041 defer ctx.gpa.free(kernel);1042 output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));10431044 const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");1045 defer ctx.gpa.free(uptime);1046 output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));1047}10481049pub fn boot(ctx: Ctx) !void {1050 output.bootHeader(ctx.machine.name);1051 const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};1052 defer ctx.gpa.free(entries);1053 for (entries, 0..) |entry, i| output.bootEntry(entry, i);1054}10551056pub fn searchCmd(ctx: Ctx) !void {1057 const query = if (ctx.args.len > 0) ctx.args[0] else "";1058 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);1059 const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages, ctx.environ);1060 if (selected) |npkg| try selectAndInstall(ctx, npkg);1061}10621063pub fn optionCmd(ctx: Ctx) !void {1064 const query = if (ctx.args.len > 0) ctx.args[0] else "";1065 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);1066 _ = try search_tui.run(ctx.gpa, ctx.io, query, .options, ctx.environ);1067}10681069pub fn install(ctx: Ctx) !void {1070 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;10711072 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);10731074 1075 const pkgs = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, pkg_name) catch {1076 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});1077 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});1078 return error.PackageNotFound;1079 };10801081 if (pkgs.len == 0) {1082 1083 if (closestPackage(ctx, pkg_name)) |sugg| {1084 output.didYouMean(pkg_name, sugg.pname);1085 if (output.confirm("")) try selectAndInstall(ctx, sugg);1086 return;1087 }1088 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});1089 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});1090 return error.PackageNotFound;1091 }10921093 1094 1095 var found = pkgs[0];1096 for (pkgs) |p| {1097 if (std.mem.eql(u8, p.pname, pkg_name)) {1098 found = p;1099 break;1100 }1101 }1102 try selectAndInstall(ctx, found);1103}11041105110611071108fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {1109 if (query.len < 2) return null;1110 var candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..@min(query.len, 4)]) catch &.{};1111 if (candidates.len == 0 and query.len > 2) {1112 candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..2]) catch &.{};1113 }1114 if (candidates.len == 0) return null;11151116 var best: ?types.NixPackage = null;1117 var best_dist: usize = std.math.maxInt(usize);1118 for (candidates) |p| {1119 const d = editDistance(query, p.pname);1120 if (d > 0 and d < best_dist) {1121 best_dist = d;1122 best = p;1123 }1124 }1125 1126 const threshold = @max(@as(usize, 2), query.len / 3);1127 return if (best_dist <= threshold) best else null;1128}1129113011311132fn editDistance(a: []const u8, b: []const u8) usize {1133 const n = b.len;1134 if (a.len == 0) return n;1135 if (n == 0) return a.len;1136 if (n + 1 > 128) return std.math.maxInt(usize);1137 var prev: [128]usize = undefined;1138 var curr: [128]usize = undefined;1139 var j: usize = 0;1140 while (j <= n) : (j += 1) prev[j] = j;1141 var i: usize = 1;1142 while (i <= a.len) : (i += 1) {1143 curr[0] = i;1144 j = 1;1145 while (j <= n) : (j += 1) {1146 const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;1147 curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));1148 }1149 @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);1150 }1151 return prev[n];1152}11531154test "editDistance is case-insensitive Levenshtein" {1155 try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));1156 try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));1157 try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));1158 try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));1159}116011611162116311641165fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {1166 output.installSelectPrompt(npkg.pname, npkg.version);11671168 var choice_buf: [8]u8 = undefined;1169 var choice_len: usize = 0;1170 while (choice_len < choice_buf.len) {1171 const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;1172 if (n == 0) break;1173 if (choice_buf[choice_len] == '\n') break;1174 choice_len += 1;1175 }1176 const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");11771178 if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {1179 try profileInstallPkg(ctx, npkg);1180 } else if (choice[0] == 's' or choice[0] == 'S') {1181 try systemInstallPkg(ctx, npkg);1182 } else if (choice[0] == 't' or choice[0] == 'T') {1183 try tryPkg(ctx, npkg);1184 }1185}11861187fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1188 output.installStart(npkg.pname, .profile);1189 if (npkg.unfree) {1190 output.printSubstep("NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr});1191 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr}));1192 } else {1193 output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});1194 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));1195 }1196 const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, npkg.attr, npkg.unfree);1197 if (code != 0) return error.ProcessFailed;1198 output.installDone(npkg.pname);1199}12001201fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1202 const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1203 defer ctx.gpa.free(config_path);1204 const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;1205 output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);1206 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);1207 if (ctx.cfg.confirm) {1208 if (output.confirm("apply now? ")) {1209 try apply(ctx);1210 }1211 }1212}12131214fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {1215 output.tryStart(npkg.pname);1216 output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});1217 output.tryExitHint();1218 _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);1219 output.tryDone();1220}12211222pub fn remove(ctx: Ctx) !void {1223 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1224 output.removeStart(pkg_name);1225 const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);1226 if (code != 0) return error.ProcessFailed;1227 output.done();1228}12291230pub fn list(ctx: Ctx) !void {1231 output.listHeader(ctx.machine.name);12321233 1234 1235 1236 if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {1237 defer ctx.gpa.free(json);1238 output.listSection("profile");1239 renderProfileJson(ctx.gpa, json);1240 }12411242 1243 1244 if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {1245 defer ctx.gpa.free(paths);1246 output.blankLine();1247 output.listSection("system");1248 var lines = std.mem.splitScalar(u8, paths, '\n');1249 while (lines.next()) |line| {1250 const t = std.mem.trim(u8, line, " \t\r");1251 if (t.len == 0) continue;1252 const row = pkgFromStorePath(t);1253 1254 if (row.version.len == 0) continue;1255 output.listPkg(row.name, row.version);1256 }1257 }1258}12591260const PkgRow = struct { name: []const u8, version: []const u8 };126112621263126412651266fn pkgFromStorePath(path: []const u8) PkgRow {1267 const base = std.fs.path.basename(path);1268 const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;1269 var i: usize = 0;1270 while (i + 1 < after_hash.len) : (i += 1) {1271 if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {1272 return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };1273 }1274 }1275 return .{ .name = after_hash, .version = "" };1276}12771278127912801281fn stripOutputSuffix(ver: []const u8) []const u8 {1282 const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };1283 for (suffixes) |s| {1284 if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];1285 }1286 return ver;1287}12881289test "pkgFromStorePath splits name and version at first dash-digit" {1290 const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");1291 try std.testing.expectEqualStrings("ripgrep", a.name);1292 try std.testing.expectEqualStrings("15.1.0", a.version);12931294 const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");1295 try std.testing.expectEqualStrings("helix", b.name);1296 try std.testing.expectEqualStrings("25.01", b.version);12971298 1299 const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");1300 try std.testing.expectEqualStrings("curl", c.name);1301 try std.testing.expectEqualStrings("8.20.0", c.version);1302}13031304fn firstStorePath(el: std.json.Value) ?[]const u8 {1305 if (el != .object) return null;1306 const sp = el.object.get("storePaths") orelse return null;1307 if (sp != .array or sp.array.items.len == 0) return null;1308 const first = sp.array.items[0];1309 return if (first == .string) first.string else null;1310}1311131213131314fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {1315 const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;1316 defer parsed.deinit();1317 if (parsed.value != .object) return;1318 const elements = parsed.value.object.get("elements") orelse return;1319 switch (elements) {1320 .object => |obj| {1321 var it = obj.iterator();1322 while (it.next()) |entry| {1323 const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";1324 output.listPkg(entry.key_ptr.*, ver);1325 }1326 },1327 .array => |arr| {1328 for (arr.items) |el| {1329 const path = firstStorePath(el) orelse continue;1330 const row = pkgFromStorePath(path);1331 output.listPkg(row.name, row.version);1332 }1333 },1334 else => {},1335 }1336}13371338pub fn tryCmd(ctx: Ctx) !void {1339 const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1340 const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };1341 try tryPkg(ctx, shell_pkg);1342}1343134413451346const home_help = [_][2][]const u8{1347 .{ "init", "set up home manager for the first time" },1348 .{ "init --switch", "set up and activate immediately" },1349 .{ "apply", "apply home-manager configuration" },1350 .{ "apply --dry", "preview changes without activating" },1351 .{ "back", "roll back one generation" },1352 .{ "history", "list all generations" },1353 .{ "edit", "open home.nix" },1354 .{ "check", "validate without applying" },1355 .{ "diff", "compare the latest two generations" },1356 .{ "packages", "list managed packages" },1357};13581359const HomeGen = struct {1360 number: u32,1361 date: []const u8,1362 time: []const u8,1363 path: []const u8,1364};13651366136713681369fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1370 var gens: std.ArrayList(HomeGen) = .empty;1371 var lines = std.mem.splitScalar(u8, out_str, '\n');1372 while (lines.next()) |line| {1373 const t = std.mem.trim(u8, line, " \t\r");1374 if (t.len == 0) continue;1375 var it = std.mem.tokenizeAny(u8, t, " \t");1376 const date = it.next() orelse continue;1377 const time = it.next() orelse continue;1378 var number: ?u32 = null;1379 var path: []const u8 = "";1380 while (it.next()) |tok| {1381 if (std.mem.eql(u8, tok, "id")) {1382 if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1383 } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1384 path = tok;1385 }1386 }1387 const num = number orelse continue;1388 try gens.append(gpa, .{1389 .number = num,1390 .date = try gpa.dupe(u8, date),1391 .time = try gpa.dupe(u8, time),1392 .path = try gpa.dupe(u8, path),1393 });1394 }1395 return gens.toOwnedSlice(gpa);1396}13971398fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1399 for (gens) |g| {1400 gpa.free(g.date);1401 gpa.free(g.time);1402 gpa.free(g.path);1403 }1404 gpa.free(gens);1405}14061407test "parseHomeGenerations reads id, date and store path" {1408 const a = std.testing.allocator;1409 const sample =1410 \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1411 \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1412 ;1413 const gens = try parseHomeGenerations(a, sample);1414 defer freeHomeGens(a, gens);1415 try std.testing.expectEqual(@as(usize, 2), gens.len);1416 try std.testing.expectEqual(@as(u32, 765), gens[0].number);1417 try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1418 try std.testing.expectEqualStrings("11:56", gens[0].time);1419 try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1420 try std.testing.expectEqual(@as(u32, 764), gens[1].number);1421}142214231424fn homeCurrentGen(ctx: Ctx) u32 {1425 const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1426 defer ctx.gpa.free(out);1427 const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1428 defer freeHomeGens(ctx.gpa, gens);1429 return if (gens.len > 0) gens[0].number else 0;1430}14311432pub fn home(ctx: Ctx) !void {1433 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1434 return output.subcommandHelp("home", &home_help, null);14351436 1437 1438 1439 1440 1441 if (!ctx.machine.local) {1442 output.homeLocalOnly(ctx.machine.name);1443 return;1444 }14451446 1447 1448 if (std.mem.eql(u8, ctx.sub, "init")) return homeInitCmd(ctx);14491450 const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1451 if (mode == .none) {1452 output.homeNotInstalled();1453 return;1454 }14551456 1457 1458 if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1459 1460 if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);14611462 if (mode == .module) {1463 output.homeModuleManaged();1464 return;1465 }14661467 if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1468 if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1469 if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1470 if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1471 if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);14721473 return output.subcommandHelp("home", &home_help, null);1474}14751476fn homePackages(ctx: Ctx) !void {1477 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1478 defer ctx.gpa.free(out);1479 const gens = try parseHomeGenerations(ctx.gpa, out);1480 defer freeHomeGens(ctx.gpa, gens);14811482 output.homePackagesHeader(ctx.machine.name);1483 if (gens.len == 0 or gens[0].path.len == 0) return;14841485 1486 1487 1488 1489 1490 const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1491 defer ctx.gpa.free(gen_refs);14921493 var refs = gen_refs;1494 var env_refs: ?[]u8 = null;1495 defer if (env_refs) |e| ctx.gpa.free(e);1496 if (findHomeManagerPath(gen_refs)) |pkg_path| {1497 if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1498 env_refs = e;1499 refs = e;1500 } else |_| {}1501 }15021503 1504 1505 1506 var seen = std.StringHashMap(void).init(ctx.gpa);1507 defer seen.deinit();1508 var lines = std.mem.splitScalar(u8, refs, '\n');1509 while (lines.next()) |line| {1510 const t = std.mem.trim(u8, line, " \t\r");1511 if (t.len == 0) continue;1512 const row = pkgFromStorePath(t);1513 if (row.version.len == 0) continue;1514 if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1515 if (seen.contains(row.name)) continue;1516 seen.put(row.name, {}) catch {};1517 output.listPkg(row.name, row.version);1518 }1519}1520152115221523fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1524 var lines = std.mem.splitScalar(u8, refs, '\n');1525 while (lines.next()) |line| {1526 const t = std.mem.trim(u8, line, " \t\r");1527 if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1528 }1529 return null;1530}15311532test "findHomeManagerPath picks the env, not the generation or infra" {1533 const refs =1534 \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31535 \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1536 \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111537 ;1538 try std.testing.expectEqualStrings(1539 "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1540 findHomeManagerPath(refs).?,1541 );1542 try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1543}15441545fn homeDiff(ctx: Ctx) !void {1546 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1547 defer ctx.gpa.free(out);1548 const gens = try parseHomeGenerations(ctx.gpa, out);1549 defer freeHomeGens(ctx.gpa, gens);15501551 1552 if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1553 output.homeNothingToDiff();1554 return;1555 }1556 const newer = gens[0];1557 const older = gens[1];1558 output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1559 if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1560 return error.ProcessFailed;1561}15621563fn homeCheck(ctx: Ctx) !void {1564 output.homeCheckStart(ctx.machine.name);1565 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1566 if (code != 0) return error.BuildFailed;1567 output.homeCheckOk();1568}15691570fn homeEdit(ctx: Ctx) !void {1571 1572 1573 const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1574 errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1575 return error.ConfigNotFound;1576 };1577 defer ctx.gpa.free(path);1578 output.homeEditOpen(path, ctx.cfg.editor);1579 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1580}15811582fn homeHistory(ctx: Ctx) !void {1583 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1584 defer ctx.gpa.free(out);1585 const gens = try parseHomeGenerations(ctx.gpa, out);1586 defer freeHomeGens(ctx.gpa, gens);1587 output.homeHistoryHeader(ctx.machine.name);1588 1589 for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1590}15911592fn homeBack(ctx: Ctx) !void {1593 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1594 defer ctx.gpa.free(out);1595 const gens = try parseHomeGenerations(ctx.gpa, out);1596 defer freeHomeGens(ctx.gpa, gens);15971598 1599 if (gens.len < 2) {1600 output.alreadyOldest();1601 return;1602 }1603 const current = gens[0].number;1604 const prev = gens[1].number;16051606 output.homeBackStart(ctx.machine.name, current, prev);1607 if (ctx.cfg.confirm and !output.confirm("")) return;1608 const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1609 if (code != 0) return error.BuildFailed;1610 output.homeBackDone(prev);1611}16121613fn homeInitCmd(ctx: Ctx) !void {1614 var switch_on_init = false;1615 var dir: ?[]const u8 = null;1616 for (ctx.args) |arg| {1617 if (std.mem.eql(u8, arg, "--switch")) {1618 switch_on_init = true;1619 } else if (!std.mem.startsWith(u8, arg, "-")) {1620 dir = arg;1621 }1622 }16231624 1625 1626 if (dir == null) {1627 if (exec.homeNixPath(ctx.gpa, ctx.environ)) |path| {1628 defer ctx.gpa.free(path);1629 if (exec.pathExists(ctx.io, path)) {1630 output.homeInitExists(path);1631 return;1632 }1633 }1634 }16351636 output.homeInitStart(switch_on_init, dir);1637 const code = try exec.homeManagerInit(ctx.io, &ctx.machine, ctx.gpa, switch_on_init, dir);1638 if (code != 0) return error.BuildFailed;1639 output.homeInitDone(switch_on_init);1640}16411642fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1643 1644 if (mode == .module) {1645 output.homeModuleManaged();1646 return;1647 }1648 if (ctx.dry) {1649 output.homeApplyDry(ctx.machine.name);1650 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1651 if (code != 0) return error.BuildFailed;1652 output.homeApplyDryDone();1653 return;1654 }16551656 if (!try runPreHook(ctx, "pre-home")) {1657 output.aborted();1658 return error.HookAborted;1659 }16601661 output.homeApplyStart(ctx.machine.name);16621663 1664 1665 const dir = exec.homeFlakeDir(ctx.gpa, ctx.io, ctx.environ);1666 defer if (dir) |d| ctx.gpa.free(d);1667 if (dir) |d| return homeApplyFlake(ctx, d);16681669 output.printSubstep("home-manager switch", .{});1670 const start = std.Io.Clock.awake.now(ctx.io);1671 const code = try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1672 if (code != 0) return error.BuildFailed;16731674 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1675 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1676 output.homeApplyDone(homeCurrentGen(ctx), elapsed);1677 runPostHook(ctx, "post-home");1678}167916801681168216831684fn homeApplyFlake(ctx: Ctx, dir: []const u8) !void {1685 const user = ctx.environ.get("USER") orelse "default";16861687 var refs: std.ArrayList([]const u8) = .empty;1688 defer {1689 for (refs.items) |r| ctx.gpa.free(r);1690 refs.deinit(ctx.gpa);1691 }1692 if (exec.homeManagerAttr(ctx.gpa, ctx.io, &ctx.machine, ctx.environ) catch null) |attr| {1693 defer ctx.gpa.free(attr);1694 try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, attr }));1695 }1696 try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, user }));1697 try refs.append(ctx.gpa, try ctx.gpa.dupe(u8, dir));16981699 const start = std.Io.Clock.awake.now(ctx.io);1700 for (refs.items, 0..) |ref, i| {1701 output.printSubstep("home-manager switch --flake {s}", .{ref});1702 switch (try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref, ctx.passthrough)) {1703 .ok => {1704 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1705 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1706 output.homeApplyDone(homeCurrentGen(ctx), elapsed);1707 runPostHook(ctx, "post-home");1708 return;1709 },1710 1711 .attr_missing => {1712 if (i + 1 < refs.items.len) output.homeAttrFallback(ref);1713 continue;1714 },1715 .failed => return error.BuildFailed,1716 }1717 }1718 return error.BuildFailed;1719}1720172117221723const service_help = [_][2][]const u8{1724 .{ "list", "list running services" },1725 .{ "logs <svc>", "show service logs" },1726 .{ "status <svc>", "service status" },1727 .{ "start <svc>", "start a service" },1728 .{ "stop <svc>", "stop a service" },1729 .{ "restart <svc>", "restart a service" },1730 .{ "enable <svc>", "enable at boot" },1731 .{ "disable <svc>", "disable at boot" },1732};173317341735173617371738fn serviceVerbAllowed(verb: []const u8) bool {1739 const known = [_][]const u8{ "start", "stop", "restart", "enable", "disable" };1740 for (known) |v| {1741 if (std.mem.eql(u8, verb, v)) return true;1742 }1743 return false;1744}17451746pub fn service(ctx: Ctx) !void {1747 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("service", &service_help, "add --user to act on user services");1748 if (std.mem.eql(u8, ctx.sub, "list")) {1749 output.serviceListHeader(ctx.machine.name);1750 const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1751 defer ctx.gpa.free(svcs);1752 for (svcs) |s| output.serviceRow(s);1753 return;1754 }1755 if (std.mem.eql(u8, ctx.sub, "logs")) {1756 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1757 const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1758 output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1759 _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1760 return;1761 }1762 if (std.mem.eql(u8, ctx.sub, "status")) {1763 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1764 output.serviceVerb("status", name, ctx.machine.name);1765 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1766 return;1767 }1768 1769 1770 1771 if (!serviceVerbAllowed(ctx.sub)) {1772 output.subcommandHelp("service", &service_help, "add --user to act on user services");1773 return error.Internal;1774 }1775 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1776 if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1777 if (!output.confirm("")) return;1778 }1779 output.serviceVerb(ctx.sub, name, ctx.machine.name);1780 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1781 output.serviceDone();1782}17831784test "serviceVerbAllowed allows only the verbs listed in service_help" {1785 try std.testing.expect(serviceVerbAllowed("start"));1786 try std.testing.expect(serviceVerbAllowed("stop"));1787 try std.testing.expect(serviceVerbAllowed("restart"));1788 try std.testing.expect(serviceVerbAllowed("enable"));1789 try std.testing.expect(serviceVerbAllowed("disable"));1790}17911792test "serviceVerbAllowed rejects verbs systemctl accepts but nina never confirmed or documented" {1793 try std.testing.expect(!serviceVerbAllowed("mask"));1794 try std.testing.expect(!serviceVerbAllowed("kill"));1795 try std.testing.expect(!serviceVerbAllowed("revert"));1796 try std.testing.expect(!serviceVerbAllowed("edit"));1797 try std.testing.expect(!serviceVerbAllowed("isolate"));1798 try std.testing.expect(!serviceVerbAllowed("starting")); 1799}1800180118021803180418051806fn subcommandKnown(help_rows: []const [2][]const u8, sub: []const u8) bool {1807 for (help_rows) |row| {1808 const verb = if (std.mem.indexOfScalar(u8, row[0], ' ')) |i| row[0][0..i] else row[0];1809 if (std.mem.eql(u8, verb, sub)) return true;1810 }1811 return false;1812}1813181418151816const flake_help = [_][2][]const u8{1817 .{ "init", "create a new flake.nix" },1818 .{ "update", "update flake inputs" },1819 .{ "update <in>", "update a specific input" },1820 .{ "check", "validate the flake" },1821 .{ "show", "inspect flake outputs" },1822 .{ "lock", "regenerate flake.lock" },1823 .{ "clone <url>", "clone a flake repository" },1824};18251826pub fn flake(ctx: Ctx) !void {1827 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1828 if (!subcommandKnown(&flake_help, ctx.sub)) {1829 output.subcommandHelp("flake", &flake_help, null);1830 return error.Internal;1831 }1832 if (std.mem.eql(u8, ctx.sub, "update")) {1833 output.flakeUpdateStart();1834 const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1835 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input, ctx.passthrough);1836 output.flakeLockWritten();1837 return;1838 }1839 if (std.mem.eql(u8, ctx.sub, "check")) {1840 output.flakeCheckStart();1841 const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1842 if (code != 0) {1843 output.checkFailed("");1844 return error.CheckFailed;1845 }1846 output.flakeValid();1847 return;1848 }1849 if (std.mem.eql(u8, ctx.sub, "show")) {1850 const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1851 if (json_out) |j| {1852 defer ctx.gpa.free(j);1853 output.flakeShowHeader("flake outputs");1854 1855 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1856 defer parsed.deinit();1857 if (parsed.value == .object) {1858 var it = parsed.value.object.iterator();1859 while (it.next()) |entry| {1860 if (entry.value_ptr.* == .object) {1861 var inner = entry.value_ptr.object.iterator();1862 while (inner.next()) |e2| {1863 const desc = if (e2.value_ptr.* == .object)1864 if (e2.value_ptr.object.get("description")) |d|1865 if (d == .string) d.string else ""1866 else1867 ""1868 else1869 "";1870 output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1871 }1872 }1873 }1874 }1875 }1876 return;1877 }1878 if (std.mem.eql(u8, ctx.sub, "init")) {1879 _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1880 return;1881 }1882 if (std.mem.eql(u8, ctx.sub, "lock")) {1883 _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1884 return;1885 }1886 if (std.mem.eql(u8, ctx.sub, "clone")) {1887 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1888 _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1889 return;1890 }1891}1892189318941895const store_help = [_][2][]const u8{1896 .{ "info", "store size and counts" },1897 .{ "path <attr>", "store path of a package" },1898 .{ "gc", "collect garbage" },1899 .{ "optimise", "deduplicate store paths with hard links" },1900 .{ "verify", "verify store integrity" },1901 .{ "repair", "repair corrupted paths" },1902};19031904pub fn store(ctx: Ctx) !void {1905 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1906 if (std.mem.eql(u8, ctx.sub, "gc")) {1907 _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1908 return;1909 }1910 1911 if (std.mem.eql(u8, ctx.sub, "optimise") or std.mem.eql(u8, ctx.sub, "optimize")) {1912 output.storeOptimiseStart(ctx.machine.name);1913 _ = try exec.storeOptimise(ctx.io, &ctx.machine, ctx.gpa);1914 output.storeOptimiseDone();1915 return;1916 }1917 if (std.mem.eql(u8, ctx.sub, "verify")) {1918 output.storeVerifyStart();1919 _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1920 return;1921 }1922 if (std.mem.eql(u8, ctx.sub, "repair")) {1923 if (ctx.cfg.confirm and !output.confirm("")) return;1924 output.storeRepairStart();1925 _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1926 return;1927 }1928 if (std.mem.eql(u8, ctx.sub, "info")) {1929 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1930 output.storeInfo(si);1931 return;1932 }1933 if (std.mem.eql(u8, ctx.sub, "path")) {1934 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1935 const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1936 defer ctx.gpa.free(path);1937 output.storePath(path);1938 return;1939 }1940 1941 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1942 output.storeInfo(si);1943}1944194519461947const channel_help = [_][2][]const u8{1948 .{ "list", "list channels" },1949 .{ "add <url> [name]", "add a channel" },1950 .{ "remove <name>", "remove a channel" },1951 .{ "update", "update all channels" },1952};19531954pub fn channel(ctx: Ctx) !void {1955 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1956 if (!subcommandKnown(&channel_help, ctx.sub)) {1957 output.subcommandHelp("channel", &channel_help, null);1958 return error.Internal;1959 }1960 1961 if (flakeSystem(ctx)) output.flakeChannelNote();1962 if (std.mem.eql(u8, ctx.sub, "list")) {1963 output.channelListHeader(ctx.machine.name);1964 const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1965 defer ctx.gpa.free(chans);1966 for (chans) |ch| output.channelRow(ch);1967 return;1968 }1969 if (std.mem.eql(u8, ctx.sub, "add")) {1970 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1971 const name = if (ctx.args.len > 1) ctx.args[1] else "";1972 _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1973 output.channelDone();1974 return;1975 }1976 if (std.mem.eql(u8, ctx.sub, "remove")) {1977 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1978 _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1979 output.channelDone();1980 return;1981 }1982 if (std.mem.eql(u8, ctx.sub, "update")) {1983 return channelUpdateCmd(ctx);1984 }1985}1986198719881989const profile_help = [_][2][]const u8{1990 .{ "list", "list profile packages" },1991 .{ "install <attr>", "install a package into your profile" },1992 .{ "remove <attr>", "remove a package from your profile" },1993 .{ "upgrade", "upgrade all profile packages" },1994};19951996pub fn profile(ctx: Ctx) !void {1997 if (std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("profile", &profile_help, null);1998 if (ctx.sub.len > 0 and !subcommandKnown(&profile_help, ctx.sub)) {1999 output.subcommandHelp("profile", &profile_help, null);2000 return error.Internal;2001 }2002 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {2003 output.profileListHeader();2004 const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;2005 if (out) |o| {2006 defer ctx.gpa.free(o);2007 var lines = std.mem.splitScalar(u8, o, '\n');2008 while (lines.next()) |line| {2009 const t = std.mem.trim(u8, line, " \t\r");2010 if (t.len == 0) continue;2011 output.profileRow(t, "", "");2012 }2013 }2014 return;2015 }2016 if (std.mem.eql(u8, ctx.sub, "install")) {2017 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;2018 _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, attr, false);2019 output.done();2020 return;2021 }2022 if (std.mem.eql(u8, ctx.sub, "remove")) {2023 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;2024 _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);2025 output.done();2026 return;2027 }2028 if (std.mem.eql(u8, ctx.sub, "upgrade")) {2029 _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);2030 output.done();2031 return;2032 }2033}2034203520362037const pkg_help = [_][2][]const u8{2038 .{ "why <pkg>", "what pulled it in" },2039 .{ "deps <pkg>", "direct dependencies" },2040 .{ "size <pkg>", "closure size" },2041 .{ "path <pkg>", "store path" },2042 .{ "closure <pkg>", "full closure" },2043};20442045pub fn pkg(ctx: Ctx) !void {2046 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);2047 if (!subcommandKnown(&pkg_help, ctx.sub)) {2048 output.subcommandHelp("pkg", &pkg_help, null);2049 return error.Internal;2050 }2051 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;2052 if (std.mem.eql(u8, ctx.sub, "why")) {2053 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;2054 return;2055 }2056 if (std.mem.eql(u8, ctx.sub, "deps")) {2057 if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;2058 return;2059 }2060 if (std.mem.eql(u8, ctx.sub, "size")) {2061 const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);2062 defer ctx.gpa.free(s);2063 output.pkgResult("size", s);2064 return;2065 }2066 if (std.mem.eql(u8, ctx.sub, "path")) {2067 const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);2068 defer ctx.gpa.free(p);2069 output.pkgResult("path", p);2070 return;2071 }2072 if (std.mem.eql(u8, ctx.sub, "closure")) {2073 if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;2074 return;2075 }2076}20772078test "subcommandKnown rejects a garbage subcommand for each of flake/channel/profile/pkg" {2079 try std.testing.expect(subcommandKnown(&flake_help, "update"));2080 try std.testing.expect(!subcommandKnown(&flake_help, "updtae"));20812082 try std.testing.expect(subcommandKnown(&channel_help, "add"));2083 try std.testing.expect(!subcommandKnown(&channel_help, "addd"));20842085 try std.testing.expect(subcommandKnown(&profile_help, "install"));2086 try std.testing.expect(!subcommandKnown(&profile_help, "instal"));20872088 try std.testing.expect(subcommandKnown(&pkg_help, "closure"));2089 try std.testing.expect(!subcommandKnown(&pkg_help, "closures"));2090}2091209220932094pub fn why(ctx: Ctx) !void {2095 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;2096 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;2097}2098209921002101210221032104210521062107pub fn pin(ctx: Ctx) !void {2108 _ = ctx;2109 errors.error_info.setMessage("nina pin is not implemented yet", .{});2110 errors.error_info.setSuggestion("override manually: nix flake lock --override-input <input> <flake-ref>", .{});2111 return error.NotImplemented;2112}21132114pub fn unpin(ctx: Ctx) !void {2115 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;2116 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input, &.{});2117 output.unpinDone(input);2118}21192120test "pin reports NotImplemented instead of a fake success" {2121 2122 2123 const ctx: Ctx = undefined;2124 try std.testing.expectError(error.NotImplemented, pin(ctx));2125}2126212721282129pub fn hash(ctx: Ctx) !void {2130 const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;2131 const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);2132 defer ctx.gpa.free(h);2133 output.hashResult(std.mem.trim(u8, h, " \t\n\r"));2134}21352136pub fn fetch(ctx: Ctx) !void {2137 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;2138 const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);2139 defer ctx.gpa.free(h);2140 output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);2141}2142214321442145pub fn build(ctx: Ctx) !void {2146 const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;2147 output.buildStart(attr orelse "default");2148 const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr, ctx.passthrough);2149 if (code != 0) return error.BuildFailed;2150 output.buildDone();2151}21522153pub fn runCmd(ctx: Ctx) !void {2154 const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;2155 output.runStart(pkg_arg);2156 _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg, ctx.passthrough);2157}2158215921602161pub fn hello(ctx: Ctx) !void {2162 output.hello(ctx.cfg.machines);2163}21642165const ConfigKind = enum { flake, channel, none };2166216721682169fn scanConfig(io: std.Io) ConfigKind {2170 if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;2171 if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;2172 return .none;2173}21742175217621772178pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2179 output.firstRunBanner();2180 output.firstRunNoConfig();21812182 var name_buf: [256]u8 = undefined;2183 var path_buf: [256]u8 = undefined;21842185 const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);21862187 output.firstRunScanning();2188 const kind = scanConfig(io);2189 switch (kind) {2190 .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),2191 .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),2192 .none => output.firstRunNoneFound(),2193 }21942195 2196 2197 const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";2198 const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);21992200 2201 2202 const use_flakes = exec.dirHasFlake(gpa, io, config_path);22032204 const conf_path = try config.configPath(gpa, environ);2205 defer gpa.free(conf_path);2206 if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);22072208 2209 const flake_line = if (use_flakes) "flake = true\n" else "";2210 var content_buf: [1024]u8 = undefined;2211 const content = try std.fmt.bufPrint(2212 &content_buf,2213 "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",2214 .{ flake_line, machine_name, config_path },2215 );22162217 const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {2218 errors.error_info.setMessage("could not write {s}", .{conf_path});2219 return error.Internal;2220 };2221 defer file.close(io);2222 file.writePositionalAll(io, content, 0) catch {2223 errors.error_info.setMessage("could not write {s}", .{conf_path});2224 return error.Internal;2225 };22262227 output.firstRunWritten(conf_path);2228}22292230pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2231 2232 2233 2234 config.migrateLegacyConfig(gpa, io, environ);2235 if (config.configPath(gpa, environ)) |conf_path| {2236 defer gpa.free(conf_path);2237 if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {2238 f.close(io);2239 } else |_| {2240 try firstRunWizard(gpa, io, environ);2241 errors.error_info.reset();2242 }2243 } else |_| {}22442245 output.setupCheck();2246 const status = exec.checkNixFeatures(gpa, io, environ);2247 output.setupFeatures(status.nix_command, status.flakes);22482249 if (status.allEnabled()) {2250 output.setupAllSet();2251 api.ensureRegistryPinned(gpa, io, environ);2252 return;2253 }22542255 2256 2257 2258 2259 if (exec.isNixOS(io)) {2260 const conf_path = "/etc/nixos/configuration.nix";2261 if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {2262 output.setupNixosNeedsRebuild(conf_path);2263 return;2264 }2265 output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);2266 if (output.confirmDefaultNo("add it now?")) {2267 if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {2268 output.setupNixosWrote(conf_path);2269 } else |_| {2270 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2271 }2272 } else {2273 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2274 }2275 return;2276 }22772278 2279 output.setupEnabling();2280 const path = try exec.enableNixFeatures(gpa, io, environ);2281 defer gpa.free(path);22822283 output.setupDone(path);2284 api.ensureRegistryPinned(gpa, io, environ);2285}22862287228822892290229122922293fn jsonEscape(buf: []u8, s: []const u8) []const u8 {2294 var i: usize = 0;2295 for (s) |ch| {2296 const esc: ?u8 = switch (ch) {2297 '"' => '"',2298 '\\' => '\\',2299 '\n' => 'n',2300 '\r' => 'r',2301 '\t' => 't',2302 else => null,2303 };2304 if (esc) |e| {2305 if (i + 2 > buf.len) break;2306 buf[i] = '\\';2307 buf[i + 1] = e;2308 i += 2;2309 } else {2310 if (i + 1 > buf.len) break;2311 buf[i] = ch;2312 i += 1;2313 }2314 }2315 return buf[0..i];2316}23172318fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {2319 var ts_buf: [32]u8 = undefined;2320 const ts = nowIso(ctx.io, &ts_buf);2321 2322 2323 2324 var name_buf: [128]u8 = undefined;2325 const machine_name = jsonEscape(&name_buf, ctx.machine.name);2326 var buf: [256]u8 = undefined;2327 const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{2328 ts, machine_name, action, gen,2329 }) catch return;2330 exec.appendNinaLog(ctx.io, ctx.environ, entry);2331}23322333test "jsonEscape lets a machine name containing quotes and backslashes round-trip through JSON" {2334 var esc_buf: [128]u8 = undefined;2335 const escaped = jsonEscape(&esc_buf, "kyoshi\" evil\\host");23362337 var line_buf: [256]u8 = undefined;2338 const entry = std.fmt.bufPrint(&line_buf, "{{\"ts\":\"2026-01-01T00:00:00Z\",\"machine\":\"{s}\",\"command\":\"apply\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":5,\"duration_ms\":0}}\n", .{escaped}) catch unreachable;23392340 const parsed = try std.json.parseFromSlice(std.json.Value, std.testing.allocator, entry, .{});2341 defer parsed.deinit();2342 try std.testing.expect(parsed.value == .object);2343 try std.testing.expectEqualStrings("kyoshi\" evil\\host", parsed.value.object.get("machine").?.string);2344}2345234623472348fn nowIso(io: std.Io, buf: []u8) []const u8 {2349 const fallback = "1970-01-01T00:00:00Z";2350 const ns = std.Io.Clock.real.now(io).toNanoseconds();2351 if (ns <= 0) return fallback;2352 const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));2353 const es = std.time.epoch.EpochSeconds{ .secs = secs };2354 const ed = es.getEpochDay();2355 const yd = ed.calculateYearDay();2356 const md = yd.calculateMonthDay();2357 const ds = es.getDaySeconds();2358 return std.fmt.bufPrint(buf, "{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}Z", .{2359 yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,2360 ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),2361 }) catch return fallback;2362}