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(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 output.logRow(line, "", "", ""); 941 return;942 };943 defer parsed.deinit();944 if (parsed.value != .object) return;945 const o = parsed.value.object;946947 const ts = jsonStr(o, "ts");948 const date = if (ts.len >= 10) ts[0..10] else ts;949 const time = if (ts.len >= 16) ts[11..16] else "";950 const action = jsonStr(o, "command");951 const outcome = jsonStr(o, "outcome");952953 var buf: [160]u8 = undefined;954 var detail: []const u8 = outcome;955 if (o.get("gen_after")) |g| {956 if (g == .integer) {957 detail = std.fmt.bufPrint(&buf, "{s} -> gen {d}", .{ outcome, g.integer }) catch outcome;958 }959 }960 output.logRow(date, time, action, detail);961}962963fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {964 if (o.get(key)) |v| {965 if (v == .string) return v.string;966 }967 return "";968}969970pub fn edit(ctx: Ctx) !void {971 972 973 974 if (std.mem.eql(u8, ctx.sub, "hardware")) {975 output.editHardwareWarning();976 return;977 }978979 980 981 var open_dir = false;982 for (ctx.args) |arg| {983 if (std.mem.eql(u8, arg, "--dir")) open_dir = true;984 }985 if (open_dir) {986 output.editOpen(ctx.machine.config_path, ctx.cfg.editor);987 _ = try exec.openEditorSudo(ctx.io, ctx.gpa, ctx.cfg.editor, ctx.machine.config_path);988 return;989 }990991 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});992 defer ctx.gpa.free(path);993 output.editOpen(path, ctx.cfg.editor);994 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);995}996997pub fn fmt(ctx: Ctx) !void {998 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});999 defer ctx.gpa.free(path);1000 if (ctx.check) {1001 const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);1002 if (code != 0) output.fmtNeedsFormat() else output.fmtDone();1003 return;1004 }1005 output.fmtStart(path);1006 _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);1007 output.fmtDone();1008}10091010pub fn repl(ctx: Ctx) !void {1011 output.replStart();1012 _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);1013}10141015pub fn develop(ctx: Ctx) !void {1016 if (std.mem.eql(u8, ctx.sub, "show")) {1017 _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null, ctx.passthrough);1018 return;1019 }1020 const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))1021 ctx.args[0]1022 else1023 null;1024 output.developStart(&.{});1025 _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ, ctx.passthrough);1026 output.developDone();1027}10281029pub fn info(ctx: Ctx) !void {1030 output.infoHeader(ctx.machine.name);1031 const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");1032 defer ctx.gpa.free(nixos_ver);1033 output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));10341035 const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");1036 defer ctx.gpa.free(kernel);1037 output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));10381039 const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");1040 defer ctx.gpa.free(uptime);1041 output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));1042}10431044pub fn boot(ctx: Ctx) !void {1045 output.bootHeader(ctx.machine.name);1046 const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};1047 defer ctx.gpa.free(entries);1048 for (entries, 0..) |entry, i| output.bootEntry(entry, i);1049}10501051pub fn searchCmd(ctx: Ctx) !void {1052 const query = if (ctx.args.len > 0) ctx.args[0] else "";1053 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);1054 const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages, ctx.environ);1055 if (selected) |npkg| try selectAndInstall(ctx, npkg);1056}10571058pub fn optionCmd(ctx: Ctx) !void {1059 const query = if (ctx.args.len > 0) ctx.args[0] else "";1060 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);1061 _ = try search_tui.run(ctx.gpa, ctx.io, query, .options, ctx.environ);1062}10631064pub fn install(ctx: Ctx) !void {1065 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;10661067 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);10681069 1070 const pkgs = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, pkg_name) catch {1071 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});1072 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});1073 return error.PackageNotFound;1074 };10751076 if (pkgs.len == 0) {1077 1078 if (closestPackage(ctx, pkg_name)) |sugg| {1079 output.didYouMean(pkg_name, sugg.pname);1080 if (output.confirm("")) try selectAndInstall(ctx, sugg);1081 return;1082 }1083 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});1084 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});1085 return error.PackageNotFound;1086 }10871088 1089 1090 var found = pkgs[0];1091 for (pkgs) |p| {1092 if (std.mem.eql(u8, p.pname, pkg_name)) {1093 found = p;1094 break;1095 }1096 }1097 try selectAndInstall(ctx, found);1098}10991100110111021103fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {1104 if (query.len < 2) return null;1105 var candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..@min(query.len, 4)]) catch &.{};1106 if (candidates.len == 0 and query.len > 2) {1107 candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..2]) catch &.{};1108 }1109 if (candidates.len == 0) return null;11101111 var best: ?types.NixPackage = null;1112 var best_dist: usize = std.math.maxInt(usize);1113 for (candidates) |p| {1114 const d = editDistance(query, p.pname);1115 if (d > 0 and d < best_dist) {1116 best_dist = d;1117 best = p;1118 }1119 }1120 1121 const threshold = @max(@as(usize, 2), query.len / 3);1122 return if (best_dist <= threshold) best else null;1123}1124112511261127fn editDistance(a: []const u8, b: []const u8) usize {1128 const n = b.len;1129 if (a.len == 0) return n;1130 if (n == 0) return a.len;1131 if (n + 1 > 128) return std.math.maxInt(usize);1132 var prev: [128]usize = undefined;1133 var curr: [128]usize = undefined;1134 var j: usize = 0;1135 while (j <= n) : (j += 1) prev[j] = j;1136 var i: usize = 1;1137 while (i <= a.len) : (i += 1) {1138 curr[0] = i;1139 j = 1;1140 while (j <= n) : (j += 1) {1141 const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;1142 curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));1143 }1144 @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);1145 }1146 return prev[n];1147}11481149test "editDistance is case-insensitive Levenshtein" {1150 try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));1151 try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));1152 try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));1153 try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));1154}115511561157115811591160fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {1161 output.installSelectPrompt(npkg.pname, npkg.version);11621163 var choice_buf: [8]u8 = undefined;1164 var choice_len: usize = 0;1165 while (choice_len < choice_buf.len) {1166 const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;1167 if (n == 0) break;1168 if (choice_buf[choice_len] == '\n') break;1169 choice_len += 1;1170 }1171 const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");11721173 if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {1174 try profileInstallPkg(ctx, npkg);1175 } else if (choice[0] == 's' or choice[0] == 'S') {1176 try systemInstallPkg(ctx, npkg);1177 } else if (choice[0] == 't' or choice[0] == 'T') {1178 try tryPkg(ctx, npkg);1179 }1180}11811182fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1183 output.installStart(npkg.pname, .profile);1184 if (npkg.unfree) {1185 output.printSubstep("NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr});1186 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr}));1187 } else {1188 output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});1189 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));1190 }1191 const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, npkg.attr, npkg.unfree);1192 if (code != 0) return error.ProcessFailed;1193 output.installDone(npkg.pname);1194}11951196fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1197 const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1198 defer ctx.gpa.free(config_path);1199 const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;1200 output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);1201 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);1202 if (ctx.cfg.confirm) {1203 if (output.confirm("apply now? ")) {1204 try apply(ctx);1205 }1206 }1207}12081209fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {1210 output.tryStart(npkg.pname);1211 output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});1212 output.tryExitHint();1213 _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);1214 output.tryDone();1215}12161217pub fn remove(ctx: Ctx) !void {1218 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1219 output.removeStart(pkg_name);1220 const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);1221 if (code != 0) return error.ProcessFailed;1222 output.done();1223}12241225pub fn list(ctx: Ctx) !void {1226 output.listHeader(ctx.machine.name);12271228 1229 1230 1231 if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {1232 defer ctx.gpa.free(json);1233 output.listSection("profile");1234 renderProfileJson(ctx.gpa, json);1235 }12361237 1238 1239 if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {1240 defer ctx.gpa.free(paths);1241 output.blankLine();1242 output.listSection("system");1243 var lines = std.mem.splitScalar(u8, paths, '\n');1244 while (lines.next()) |line| {1245 const t = std.mem.trim(u8, line, " \t\r");1246 if (t.len == 0) continue;1247 const row = pkgFromStorePath(t);1248 1249 if (row.version.len == 0) continue;1250 output.listPkg(row.name, row.version);1251 }1252 }1253}12541255const PkgRow = struct { name: []const u8, version: []const u8 };125612571258125912601261fn pkgFromStorePath(path: []const u8) PkgRow {1262 const base = std.fs.path.basename(path);1263 const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;1264 var i: usize = 0;1265 while (i + 1 < after_hash.len) : (i += 1) {1266 if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {1267 return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };1268 }1269 }1270 return .{ .name = after_hash, .version = "" };1271}12721273127412751276fn stripOutputSuffix(ver: []const u8) []const u8 {1277 const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };1278 for (suffixes) |s| {1279 if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];1280 }1281 return ver;1282}12831284test "pkgFromStorePath splits name and version at first dash-digit" {1285 const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");1286 try std.testing.expectEqualStrings("ripgrep", a.name);1287 try std.testing.expectEqualStrings("15.1.0", a.version);12881289 const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");1290 try std.testing.expectEqualStrings("helix", b.name);1291 try std.testing.expectEqualStrings("25.01", b.version);12921293 1294 const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");1295 try std.testing.expectEqualStrings("curl", c.name);1296 try std.testing.expectEqualStrings("8.20.0", c.version);1297}12981299fn firstStorePath(el: std.json.Value) ?[]const u8 {1300 if (el != .object) return null;1301 const sp = el.object.get("storePaths") orelse return null;1302 if (sp != .array or sp.array.items.len == 0) return null;1303 const first = sp.array.items[0];1304 return if (first == .string) first.string else null;1305}1306130713081309fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {1310 const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;1311 defer parsed.deinit();1312 if (parsed.value != .object) return;1313 const elements = parsed.value.object.get("elements") orelse return;1314 switch (elements) {1315 .object => |obj| {1316 var it = obj.iterator();1317 while (it.next()) |entry| {1318 const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";1319 output.listPkg(entry.key_ptr.*, ver);1320 }1321 },1322 .array => |arr| {1323 for (arr.items) |el| {1324 const path = firstStorePath(el) orelse continue;1325 const row = pkgFromStorePath(path);1326 output.listPkg(row.name, row.version);1327 }1328 },1329 else => {},1330 }1331}13321333pub fn tryCmd(ctx: Ctx) !void {1334 const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1335 const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };1336 try tryPkg(ctx, shell_pkg);1337}1338133913401341const home_help = [_][2][]const u8{1342 .{ "init", "set up home manager for the first time" },1343 .{ "init --switch", "set up and activate immediately" },1344 .{ "apply", "apply home-manager configuration" },1345 .{ "apply --dry", "preview changes without activating" },1346 .{ "back", "roll back one generation" },1347 .{ "history", "list all generations" },1348 .{ "edit", "open home.nix" },1349 .{ "check", "validate without applying" },1350 .{ "diff", "compare the latest two generations" },1351 .{ "packages", "list managed packages" },1352};13531354const HomeGen = struct {1355 number: u32,1356 date: []const u8,1357 time: []const u8,1358 path: []const u8,1359};13601361136213631364fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1365 var gens: std.ArrayList(HomeGen) = .empty;1366 var lines = std.mem.splitScalar(u8, out_str, '\n');1367 while (lines.next()) |line| {1368 const t = std.mem.trim(u8, line, " \t\r");1369 if (t.len == 0) continue;1370 var it = std.mem.tokenizeAny(u8, t, " \t");1371 const date = it.next() orelse continue;1372 const time = it.next() orelse continue;1373 var number: ?u32 = null;1374 var path: []const u8 = "";1375 while (it.next()) |tok| {1376 if (std.mem.eql(u8, tok, "id")) {1377 if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1378 } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1379 path = tok;1380 }1381 }1382 const num = number orelse continue;1383 try gens.append(gpa, .{1384 .number = num,1385 .date = try gpa.dupe(u8, date),1386 .time = try gpa.dupe(u8, time),1387 .path = try gpa.dupe(u8, path),1388 });1389 }1390 return gens.toOwnedSlice(gpa);1391}13921393fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1394 for (gens) |g| {1395 gpa.free(g.date);1396 gpa.free(g.time);1397 gpa.free(g.path);1398 }1399 gpa.free(gens);1400}14011402test "parseHomeGenerations reads id, date and store path" {1403 const a = std.testing.allocator;1404 const sample =1405 \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1406 \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1407 ;1408 const gens = try parseHomeGenerations(a, sample);1409 defer freeHomeGens(a, gens);1410 try std.testing.expectEqual(@as(usize, 2), gens.len);1411 try std.testing.expectEqual(@as(u32, 765), gens[0].number);1412 try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1413 try std.testing.expectEqualStrings("11:56", gens[0].time);1414 try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1415 try std.testing.expectEqual(@as(u32, 764), gens[1].number);1416}141714181419fn homeCurrentGen(ctx: Ctx) u32 {1420 const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1421 defer ctx.gpa.free(out);1422 const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1423 defer freeHomeGens(ctx.gpa, gens);1424 return if (gens.len > 0) gens[0].number else 0;1425}14261427pub fn home(ctx: Ctx) !void {1428 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1429 return output.subcommandHelp("home", &home_help, null);14301431 1432 1433 1434 1435 1436 if (!ctx.machine.local) {1437 output.homeLocalOnly(ctx.machine.name);1438 return;1439 }14401441 1442 1443 if (std.mem.eql(u8, ctx.sub, "init")) return homeInitCmd(ctx);14441445 const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1446 if (mode == .none) {1447 output.homeNotInstalled();1448 return;1449 }14501451 1452 1453 if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1454 1455 if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);14561457 if (mode == .module) {1458 output.homeModuleManaged();1459 return;1460 }14611462 if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1463 if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1464 if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1465 if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1466 if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);14671468 return output.subcommandHelp("home", &home_help, null);1469}14701471fn homePackages(ctx: Ctx) !void {1472 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1473 defer ctx.gpa.free(out);1474 const gens = try parseHomeGenerations(ctx.gpa, out);1475 defer freeHomeGens(ctx.gpa, gens);14761477 output.homePackagesHeader(ctx.machine.name);1478 if (gens.len == 0 or gens[0].path.len == 0) return;14791480 1481 1482 1483 1484 1485 const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1486 defer ctx.gpa.free(gen_refs);14871488 var refs = gen_refs;1489 var env_refs: ?[]u8 = null;1490 defer if (env_refs) |e| ctx.gpa.free(e);1491 if (findHomeManagerPath(gen_refs)) |pkg_path| {1492 if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1493 env_refs = e;1494 refs = e;1495 } else |_| {}1496 }14971498 1499 1500 1501 var seen = std.StringHashMap(void).init(ctx.gpa);1502 defer seen.deinit();1503 var lines = std.mem.splitScalar(u8, refs, '\n');1504 while (lines.next()) |line| {1505 const t = std.mem.trim(u8, line, " \t\r");1506 if (t.len == 0) continue;1507 const row = pkgFromStorePath(t);1508 if (row.version.len == 0) continue;1509 if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1510 if (seen.contains(row.name)) continue;1511 seen.put(row.name, {}) catch {};1512 output.listPkg(row.name, row.version);1513 }1514}1515151615171518fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1519 var lines = std.mem.splitScalar(u8, refs, '\n');1520 while (lines.next()) |line| {1521 const t = std.mem.trim(u8, line, " \t\r");1522 if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1523 }1524 return null;1525}15261527test "findHomeManagerPath picks the env, not the generation or infra" {1528 const refs =1529 \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31530 \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1531 \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111532 ;1533 try std.testing.expectEqualStrings(1534 "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1535 findHomeManagerPath(refs).?,1536 );1537 try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1538}15391540fn homeDiff(ctx: Ctx) !void {1541 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1542 defer ctx.gpa.free(out);1543 const gens = try parseHomeGenerations(ctx.gpa, out);1544 defer freeHomeGens(ctx.gpa, gens);15451546 1547 if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1548 output.homeNothingToDiff();1549 return;1550 }1551 const newer = gens[0];1552 const older = gens[1];1553 output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1554 if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1555 return error.ProcessFailed;1556}15571558fn homeCheck(ctx: Ctx) !void {1559 output.homeCheckStart(ctx.machine.name);1560 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1561 if (code != 0) return error.BuildFailed;1562 output.homeCheckOk();1563}15641565fn homeEdit(ctx: Ctx) !void {1566 1567 1568 const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1569 errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1570 return error.ConfigNotFound;1571 };1572 defer ctx.gpa.free(path);1573 output.homeEditOpen(path, ctx.cfg.editor);1574 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1575}15761577fn homeHistory(ctx: Ctx) !void {1578 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1579 defer ctx.gpa.free(out);1580 const gens = try parseHomeGenerations(ctx.gpa, out);1581 defer freeHomeGens(ctx.gpa, gens);1582 output.homeHistoryHeader(ctx.machine.name);1583 1584 for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1585}15861587fn homeBack(ctx: Ctx) !void {1588 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1589 defer ctx.gpa.free(out);1590 const gens = try parseHomeGenerations(ctx.gpa, out);1591 defer freeHomeGens(ctx.gpa, gens);15921593 1594 if (gens.len < 2) {1595 output.alreadyOldest();1596 return;1597 }1598 const current = gens[0].number;1599 const prev = gens[1].number;16001601 output.homeBackStart(ctx.machine.name, current, prev);1602 if (ctx.cfg.confirm and !output.confirm("")) return;1603 const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1604 if (code != 0) return error.BuildFailed;1605 output.homeBackDone(prev);1606}16071608fn homeInitCmd(ctx: Ctx) !void {1609 var switch_on_init = false;1610 var dir: ?[]const u8 = null;1611 for (ctx.args) |arg| {1612 if (std.mem.eql(u8, arg, "--switch")) {1613 switch_on_init = true;1614 } else if (!std.mem.startsWith(u8, arg, "-")) {1615 dir = arg;1616 }1617 }16181619 1620 1621 if (dir == null) {1622 if (exec.homeNixPath(ctx.gpa, ctx.environ)) |path| {1623 defer ctx.gpa.free(path);1624 if (exec.pathExists(ctx.io, path)) {1625 output.homeInitExists(path);1626 return;1627 }1628 }1629 }16301631 output.homeInitStart(switch_on_init, dir);1632 const code = try exec.homeManagerInit(ctx.io, &ctx.machine, ctx.gpa, switch_on_init, dir);1633 if (code != 0) return error.BuildFailed;1634 output.homeInitDone(switch_on_init);1635}16361637fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1638 1639 if (mode == .module) {1640 output.homeModuleManaged();1641 return;1642 }1643 if (ctx.dry) {1644 output.homeApplyDry(ctx.machine.name);1645 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1646 if (code != 0) return error.BuildFailed;1647 output.homeApplyDryDone();1648 return;1649 }16501651 if (!try runPreHook(ctx, "pre-home")) {1652 output.aborted();1653 return error.HookAborted;1654 }16551656 output.homeApplyStart(ctx.machine.name);16571658 1659 1660 const dir = exec.homeFlakeDir(ctx.gpa, ctx.io, ctx.environ);1661 defer if (dir) |d| ctx.gpa.free(d);1662 if (dir) |d| return homeApplyFlake(ctx, d);16631664 output.printSubstep("home-manager switch", .{});1665 const start = std.Io.Clock.awake.now(ctx.io);1666 const code = try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1667 if (code != 0) return error.BuildFailed;16681669 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1670 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1671 output.homeApplyDone(homeCurrentGen(ctx), elapsed);1672 runPostHook(ctx, "post-home");1673}167416751676167716781679fn homeApplyFlake(ctx: Ctx, dir: []const u8) !void {1680 const user = ctx.environ.get("USER") orelse "default";16811682 var refs: std.ArrayList([]const u8) = .empty;1683 defer {1684 for (refs.items) |r| ctx.gpa.free(r);1685 refs.deinit(ctx.gpa);1686 }1687 if (exec.homeManagerAttr(ctx.gpa, ctx.io, &ctx.machine, ctx.environ) catch null) |attr| {1688 defer ctx.gpa.free(attr);1689 try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, attr }));1690 }1691 try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, user }));1692 try refs.append(ctx.gpa, try ctx.gpa.dupe(u8, dir));16931694 const start = std.Io.Clock.awake.now(ctx.io);1695 for (refs.items, 0..) |ref, i| {1696 output.printSubstep("home-manager switch --flake {s}", .{ref});1697 switch (try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref, ctx.passthrough)) {1698 .ok => {1699 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1700 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1701 output.homeApplyDone(homeCurrentGen(ctx), elapsed);1702 runPostHook(ctx, "post-home");1703 return;1704 },1705 1706 .attr_missing => {1707 if (i + 1 < refs.items.len) output.homeAttrFallback(ref);1708 continue;1709 },1710 .failed => return error.BuildFailed,1711 }1712 }1713 return error.BuildFailed;1714}1715171617171718const service_help = [_][2][]const u8{1719 .{ "list", "list running services" },1720 .{ "logs <svc>", "show service logs" },1721 .{ "status <svc>", "service status" },1722 .{ "start <svc>", "start a service" },1723 .{ "stop <svc>", "stop a service" },1724 .{ "restart <svc>", "restart a service" },1725 .{ "enable <svc>", "enable at boot" },1726 .{ "disable <svc>", "disable at boot" },1727};17281729pub fn service(ctx: Ctx) !void {1730 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");1731 if (std.mem.eql(u8, ctx.sub, "list")) {1732 output.serviceListHeader(ctx.machine.name);1733 const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1734 defer ctx.gpa.free(svcs);1735 for (svcs) |s| output.serviceRow(s);1736 return;1737 }1738 if (std.mem.eql(u8, ctx.sub, "logs")) {1739 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1740 const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1741 output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1742 _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1743 return;1744 }1745 if (std.mem.eql(u8, ctx.sub, "status")) {1746 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1747 output.serviceVerb("status", name, ctx.machine.name);1748 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1749 return;1750 }1751 1752 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1753 if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1754 if (!output.confirm("")) return;1755 }1756 output.serviceVerb(ctx.sub, name, ctx.machine.name);1757 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1758 output.serviceDone();1759}1760176117621763const flake_help = [_][2][]const u8{1764 .{ "init", "create a new flake.nix" },1765 .{ "update", "update flake inputs" },1766 .{ "update <in>", "update a specific input" },1767 .{ "check", "validate the flake" },1768 .{ "show", "inspect flake outputs" },1769 .{ "lock", "regenerate flake.lock" },1770 .{ "clone <url>", "clone a flake repository" },1771};17721773pub fn flake(ctx: Ctx) !void {1774 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1775 if (std.mem.eql(u8, ctx.sub, "update")) {1776 output.flakeUpdateStart();1777 const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1778 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input, ctx.passthrough);1779 output.flakeLockWritten();1780 return;1781 }1782 if (std.mem.eql(u8, ctx.sub, "check")) {1783 output.flakeCheckStart();1784 const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1785 if (code != 0) {1786 output.checkFailed("");1787 return error.CheckFailed;1788 }1789 output.flakeValid();1790 return;1791 }1792 if (std.mem.eql(u8, ctx.sub, "show")) {1793 const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1794 if (json_out) |j| {1795 defer ctx.gpa.free(j);1796 output.flakeShowHeader("flake outputs");1797 1798 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1799 defer parsed.deinit();1800 if (parsed.value == .object) {1801 var it = parsed.value.object.iterator();1802 while (it.next()) |entry| {1803 if (entry.value_ptr.* == .object) {1804 var inner = entry.value_ptr.object.iterator();1805 while (inner.next()) |e2| {1806 const desc = if (e2.value_ptr.* == .object)1807 if (e2.value_ptr.object.get("description")) |d|1808 if (d == .string) d.string else ""1809 else1810 ""1811 else1812 "";1813 output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1814 }1815 }1816 }1817 }1818 }1819 return;1820 }1821 if (std.mem.eql(u8, ctx.sub, "init")) {1822 _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1823 return;1824 }1825 if (std.mem.eql(u8, ctx.sub, "lock")) {1826 _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1827 return;1828 }1829 if (std.mem.eql(u8, ctx.sub, "clone")) {1830 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1831 _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1832 return;1833 }1834}1835183618371838const store_help = [_][2][]const u8{1839 .{ "info", "store size and counts" },1840 .{ "path <attr>", "store path of a package" },1841 .{ "gc", "collect garbage" },1842 .{ "optimise", "deduplicate store paths with hard links" },1843 .{ "verify", "verify store integrity" },1844 .{ "repair", "repair corrupted paths" },1845};18461847pub fn store(ctx: Ctx) !void {1848 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1849 if (std.mem.eql(u8, ctx.sub, "gc")) {1850 _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1851 return;1852 }1853 1854 if (std.mem.eql(u8, ctx.sub, "optimise") or std.mem.eql(u8, ctx.sub, "optimize")) {1855 output.storeOptimiseStart(ctx.machine.name);1856 _ = try exec.storeOptimise(ctx.io, &ctx.machine, ctx.gpa);1857 output.storeOptimiseDone();1858 return;1859 }1860 if (std.mem.eql(u8, ctx.sub, "verify")) {1861 output.storeVerifyStart();1862 _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1863 return;1864 }1865 if (std.mem.eql(u8, ctx.sub, "repair")) {1866 if (ctx.cfg.confirm and !output.confirm("")) return;1867 output.storeRepairStart();1868 _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1869 return;1870 }1871 if (std.mem.eql(u8, ctx.sub, "info")) {1872 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1873 output.storeInfo(si);1874 return;1875 }1876 if (std.mem.eql(u8, ctx.sub, "path")) {1877 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1878 const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1879 defer ctx.gpa.free(path);1880 output.storePath(path);1881 return;1882 }1883 1884 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1885 output.storeInfo(si);1886}1887188818891890const channel_help = [_][2][]const u8{1891 .{ "list", "list channels" },1892 .{ "add <url> [name]", "add a channel" },1893 .{ "remove <name>", "remove a channel" },1894 .{ "update", "update all channels" },1895};18961897pub fn channel(ctx: Ctx) !void {1898 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1899 1900 if (flakeSystem(ctx)) output.flakeChannelNote();1901 if (std.mem.eql(u8, ctx.sub, "list")) {1902 output.channelListHeader(ctx.machine.name);1903 const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1904 defer ctx.gpa.free(chans);1905 for (chans) |ch| output.channelRow(ch);1906 return;1907 }1908 if (std.mem.eql(u8, ctx.sub, "add")) {1909 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1910 const name = if (ctx.args.len > 1) ctx.args[1] else "";1911 _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1912 output.channelDone();1913 return;1914 }1915 if (std.mem.eql(u8, ctx.sub, "remove")) {1916 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1917 _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1918 output.channelDone();1919 return;1920 }1921 if (std.mem.eql(u8, ctx.sub, "update")) {1922 return channelUpdateCmd(ctx);1923 }1924}1925192619271928pub fn profile(ctx: Ctx) !void {1929 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1930 output.profileListHeader();1931 const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1932 if (out) |o| {1933 defer ctx.gpa.free(o);1934 var lines = std.mem.splitScalar(u8, o, '\n');1935 while (lines.next()) |line| {1936 const t = std.mem.trim(u8, line, " \t\r");1937 if (t.len == 0) continue;1938 output.profileRow(t, "", "");1939 }1940 }1941 return;1942 }1943 if (std.mem.eql(u8, ctx.sub, "install")) {1944 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1945 _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, attr, false);1946 output.done();1947 return;1948 }1949 if (std.mem.eql(u8, ctx.sub, "remove")) {1950 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1951 _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1952 output.done();1953 return;1954 }1955 if (std.mem.eql(u8, ctx.sub, "upgrade")) {1956 _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1957 output.done();1958 return;1959 }1960}1961196219631964const pkg_help = [_][2][]const u8{1965 .{ "why <pkg>", "what pulled it in" },1966 .{ "deps <pkg>", "direct dependencies" },1967 .{ "size <pkg>", "closure size" },1968 .{ "path <pkg>", "store path" },1969 .{ "closure <pkg>", "full closure" },1970};19711972pub fn pkg(ctx: Ctx) !void {1973 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1974 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1975 if (std.mem.eql(u8, ctx.sub, "why")) {1976 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1977 return;1978 }1979 if (std.mem.eql(u8, ctx.sub, "deps")) {1980 if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1981 return;1982 }1983 if (std.mem.eql(u8, ctx.sub, "size")) {1984 const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1985 defer ctx.gpa.free(s);1986 output.pkgResult("size", s);1987 return;1988 }1989 if (std.mem.eql(u8, ctx.sub, "path")) {1990 const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1991 defer ctx.gpa.free(p);1992 output.pkgResult("path", p);1993 return;1994 }1995 if (std.mem.eql(u8, ctx.sub, "closure")) {1996 if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1997 return;1998 }1999}2000200120022003pub fn why(ctx: Ctx) !void {2004 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;2005 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;2006}2007200820092010201120122013201420152016pub fn pin(ctx: Ctx) !void {2017 _ = ctx;2018 errors.error_info.setMessage("nina pin is not implemented yet", .{});2019 errors.error_info.setSuggestion("override manually: nix flake lock --override-input <input> <flake-ref>", .{});2020 return error.NotImplemented;2021}20222023pub fn unpin(ctx: Ctx) !void {2024 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;2025 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input, &.{});2026 output.unpinDone(input);2027}20282029test "pin reports NotImplemented instead of a fake success" {2030 2031 2032 const ctx: Ctx = undefined;2033 try std.testing.expectError(error.NotImplemented, pin(ctx));2034}2035203620372038pub fn hash(ctx: Ctx) !void {2039 const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;2040 const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);2041 defer ctx.gpa.free(h);2042 output.hashResult(std.mem.trim(u8, h, " \t\n\r"));2043}20442045pub fn fetch(ctx: Ctx) !void {2046 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;2047 const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);2048 defer ctx.gpa.free(h);2049 output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);2050}2051205220532054pub fn build(ctx: Ctx) !void {2055 const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;2056 output.buildStart(attr orelse "default");2057 const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr, ctx.passthrough);2058 if (code != 0) return error.BuildFailed;2059 output.buildDone();2060}20612062pub fn runCmd(ctx: Ctx) !void {2063 const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;2064 output.runStart(pkg_arg);2065 _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg, ctx.passthrough);2066}2067206820692070pub fn hello(ctx: Ctx) !void {2071 output.hello(ctx.cfg.machines);2072}20732074const ConfigKind = enum { flake, channel, none };2075207620772078fn scanConfig(io: std.Io) ConfigKind {2079 if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;2080 if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;2081 return .none;2082}20832084208520862087pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2088 output.firstRunBanner();2089 output.firstRunNoConfig();20902091 var name_buf: [256]u8 = undefined;2092 var path_buf: [256]u8 = undefined;20932094 const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);20952096 output.firstRunScanning();2097 const kind = scanConfig(io);2098 switch (kind) {2099 .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),2100 .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),2101 .none => output.firstRunNoneFound(),2102 }21032104 2105 2106 const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";2107 const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);21082109 2110 2111 const use_flakes = exec.dirHasFlake(gpa, io, config_path);21122113 const conf_path = try config.configPath(gpa, environ);2114 defer gpa.free(conf_path);2115 if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);21162117 2118 const flake_line = if (use_flakes) "flake = true\n" else "";2119 var content_buf: [1024]u8 = undefined;2120 const content = try std.fmt.bufPrint(2121 &content_buf,2122 "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",2123 .{ flake_line, machine_name, config_path },2124 );21252126 const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {2127 errors.error_info.setMessage("could not write {s}", .{conf_path});2128 return error.Internal;2129 };2130 defer file.close(io);2131 file.writePositionalAll(io, content, 0) catch {2132 errors.error_info.setMessage("could not write {s}", .{conf_path});2133 return error.Internal;2134 };21352136 output.firstRunWritten(conf_path);2137}21382139pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2140 2141 2142 2143 config.migrateLegacyConfig(gpa, io, environ);2144 if (config.configPath(gpa, environ)) |conf_path| {2145 defer gpa.free(conf_path);2146 if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {2147 f.close(io);2148 } else |_| {2149 try firstRunWizard(gpa, io, environ);2150 errors.error_info.reset();2151 }2152 } else |_| {}21532154 output.setupCheck();2155 const status = exec.checkNixFeatures(gpa, io, environ);2156 output.setupFeatures(status.nix_command, status.flakes);21572158 if (status.allEnabled()) {2159 output.setupAllSet();2160 api.ensureRegistryPinned(gpa, io, environ);2161 return;2162 }21632164 2165 2166 2167 2168 if (exec.isNixOS(io)) {2169 const conf_path = "/etc/nixos/configuration.nix";2170 if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {2171 output.setupNixosNeedsRebuild(conf_path);2172 return;2173 }2174 output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);2175 if (output.confirmDefaultNo("add it now?")) {2176 if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {2177 output.setupNixosWrote(conf_path);2178 } else |_| {2179 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2180 }2181 } else {2182 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2183 }2184 return;2185 }21862187 2188 output.setupEnabling();2189 const path = try exec.enableNixFeatures(gpa, io, environ);2190 defer gpa.free(path);21912192 output.setupDone(path);2193 api.ensureRegistryPinned(gpa, io, environ);2194}2195219621972198fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {2199 var ts_buf: [32]u8 = undefined;2200 const ts = nowIso(ctx.io, &ts_buf);2201 var buf: [256]u8 = undefined;2202 const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{2203 ts, ctx.machine.name, action, gen,2204 }) catch return;2205 exec.appendNinaLog(ctx.io, ctx.environ, entry);2206}2207220822092210fn nowIso(io: std.Io, buf: []u8) []const u8 {2211 const fallback = "1970-01-01T00:00:00Z";2212 const ns = std.Io.Clock.real.now(io).toNanoseconds();2213 if (ns <= 0) return fallback;2214 const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));2215 const es = std.time.epoch.EpochSeconds{ .secs = secs };2216 const ed = es.getEpochDay();2217 const yd = ed.calculateYearDay();2218 const md = yd.calculateMonthDay();2219 const ds = es.getDaySeconds();2220 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", .{2221 yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,2222 ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),2223 }) catch return fallback;2224}