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";1516const Semver = struct {17 major: u32,18 minor: u32,19 patch: u32,20};2122pub const Ctx = struct {23 gpa: std.mem.Allocator,24 io: std.Io,25 environ: *const std.process.Environ.Map,26 machine: types.Machine,27 cfg: types.NinaConfig,28 args: []const []const u8, 29 sub: []const u8, 30 dry: bool,31 check: bool,32 no_apply: bool,33 all: bool,34 last: u32,35 json: bool,36 user: bool, 37};3839404142fn flakeSystem(ctx: Ctx) bool {43 return ctx.cfg.flake or exec.configHasFlake(ctx.gpa, ctx.io, &ctx.machine);44}4546fn runPreHook(ctx: Ctx, hook_name: []const u8) !bool {47 const hook = try exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name);48 defer ctx.gpa.free(hook.output);49 switch (hook.result) {50 .not_found, .ok => return true,51 .failed => {52 output.hookFailed(hook_name, hook.exit_code, hook.output);53 return output.confirmDefaultNo("continue anyway?");54 },55 }56}5758fn runPostHook(ctx: Ctx, hook_name: []const u8) void {59 const hook = exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name) catch return;60 defer ctx.gpa.free(hook.output);61 if (hook.result == .failed) {62 output.hookWarning(hook_name, hook.exit_code, hook.output);63 }64}6566pub fn apply(ctx: Ctx) !void {67 if (ctx.dry) {68 output.applyDry(ctx.machine.name);69 const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);70 if (code != 0) return error.BuildFailed;71 output.applyDryDone();72 return;73 }74 if (ctx.check) {75 return check(ctx);76 }7778 if (!try runPreHook(ctx, "pre-apply")) {79 output.aborted();80 return error.HookAborted;81 }8283 output.applyStart(ctx.machine.name);84 output.buildPanelInit();85 const start = std.Io.Clock.awake.now(ctx.io);8687 var panel = output.BuildPanel{};88 const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel) catch |e| {89 output.buildPanelClear();90 exec.markApplyFailed(ctx.io, ctx.environ);91 return e;92 };93 output.buildPanelClear();9495 if (code != 0) {96 exec.markApplyFailed(ctx.io, ctx.environ);97 return error.BuildFailed;98 }99100 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());101 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));102 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;103 const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);104 output.applyDone(gen, elapsed, after_failure);105 106 const warnings = errors.extractWarnings(ctx.gpa, errors.getBuildStderr()) catch &.{};107 defer {108 for (warnings) |w| ctx.gpa.free(w);109 ctx.gpa.free(warnings);110 }111 if (warnings.len > 0) output.buildWarnings(warnings);112 runPostHook(ctx, "post-apply");113 logAction(ctx, "apply", gen);114}115116pub fn check(ctx: Ctx) !void {117 output.checkStart(ctx.machine.name);118 const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);119 if (code != 0) return error.BuildFailed;120 output.checkOk();121}122123pub fn back(ctx: Ctx) !void {124 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);125 defer ctx.gpa.free(gens);126127 var current: u32 = 0;128 for (gens) |g| if (g.current) {129 current = g.number;130 };131132 133 134 var prev: u32 = 0;135 var has_prev = false;136 for (gens) |g| {137 if (g.number < current and (!has_prev or g.number > prev)) {138 prev = g.number;139 has_prev = true;140 }141 }142 if (!has_prev) {143 output.alreadyOldest();144 return;145 }146147 if (!try runPreHook(ctx, "pre-back")) {148 output.aborted();149 return error.HookAborted;150 }151152 output.backStart(ctx.machine.name, current, prev);153 if (ctx.cfg.confirm and !output.confirm("")) return;154155 156 157 158 const code = if (flakeSystem(ctx))159 try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, prev)160 else161 try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);162 if (code != 0) return error.BuildFailed;163 output.backDone(prev);164 runPostHook(ctx, "post-back");165}166167pub fn go(ctx: Ctx) !void {168 if (ctx.args.len == 0) return error.Internal;169 const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;170 const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);171172 output.goStart(ctx.machine.name, current, target);173 if (ctx.cfg.confirm and !output.confirm("")) return;174175 const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);176 if (code != 0) return error.ProcessFailed;177 output.generationDone(target);178}179180pub fn history(ctx: Ctx) !void {181 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);182 defer ctx.gpa.free(gens);183 output.historyHeader(ctx.machine.name);184 for (gens) |g| output.historyRow(g);185}186187const gen_help = [_][2][]const u8{188 .{ "list", "list generations" },189 .{ "current", "show current generation" },190 .{ "delete <n>", "delete generation n" },191 .{ "delete old", "delete old generations" },192};193194pub fn genCmd(ctx: Ctx) !void {195 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("gen", &gen_help, null);196 if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);197 if (std.mem.eql(u8, ctx.sub, "current")) {198 const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);199 output.genCurrent(n);200 return;201 }202 if (std.mem.eql(u8, ctx.sub, "delete")) {203 if (ctx.args.len == 0) return error.Internal;204 if (std.mem.eql(u8, ctx.args[0], "old")) {205 if (ctx.cfg.confirm and !output.confirm("")) return;206 _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);207 } else {208 const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;209 if (ctx.cfg.confirm and !output.confirm("")) return;210 _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);211 }212 output.done();213 return;214 }215 return error.Internal;216}217218pub fn clean(ctx: Ctx) !void {219 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);220 defer ctx.gpa.free(gens);221 const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");222 const total: u32 = @intCast(gens.len);223 224 225 const keep: u32 = if (all) 1 else ctx.cfg.generations;226 if (total <= keep) {227 output.cleanNothing(ctx.machine.name, total);228 return;229 }230 output.cleanStart(ctx.machine.name, keep, total);231 if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;232 _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);233 output.cleanDone();234}235236pub fn statusCmd(ctx: Ctx) !void {237 output.statusHeader();238 239 240 if (ctx.all and ctx.cfg.machines.len > 0) {241 for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);242 } else {243 statusRowFor(ctx, &ctx.machine);244 }245 homeStatusLine(ctx);246}247248249250251fn homeStatusLine(ctx: Ctx) void {252 if (exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ) != .standalone) return;253 const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return;254 defer ctx.gpa.free(out);255 const gens = parseHomeGenerations(ctx.gpa, out) catch return;256 defer freeHomeGens(ctx.gpa, gens);257 if (gens.len == 0) return;258 output.statusHomeRow(gens[0].number, gens[0].date);259}260261fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {262 263 264 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {265 output.statusRow(machine.name, 0, "", "", false);266 return;267 };268 const st = exec.systemStatus(ctx.gpa, ctx.io, machine);269 defer ctx.gpa.free(st.size);270 defer ctx.gpa.free(st.age);271 output.statusRow(machine.name, gen, st.age, st.size, true);272}273274pub fn diff(ctx: Ctx) !void {275 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);276 defer ctx.gpa.free(gens);277 var current: u32 = 0;278 var prev: u32 = 0;279 for (gens) |g| {280 if (g.current) current = g.number;281 if (!g.current and g.number > prev and g.number < current) prev = g.number;282 }283 if (ctx.args.len >= 2) {284 const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;285 const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;286 output.diffHeader(a, b, ctx.machine.name);287 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;288 } else {289 output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);290 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;291 }292}293294pub fn mood(ctx: Ctx) !void {295 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;296 const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);297 defer ctx.gpa.free(st.size);298 defer ctx.gpa.free(st.age);299 const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");300 defer ctx.gpa.free(state);301 output.mood(ctx.machine.name, state, gen, st.age, st.size);302}303304pub fn doctor(ctx: Ctx) !void {305 output.doctorHeader(ctx.machine.name);306 const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);307 defer ctx.gpa.free(checks);308 var warnings: u32 = 0;309 var failures: u32 = 0;310 for (checks) |ch| {311 output.doctorRow(ch);312 if (ch.status == .warn) warnings += 1;313 if (ch.status == .fail) failures += 1;314 }315316 317 318 const hm_mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);319 if (hm_mode != .none) {320 const note = homeDoctorNote(ctx, hm_mode);321 defer ctx.gpa.free(note);322 output.doctorRow(.{ .name = "home manager", .status = .ok, .note = note });323 }324325 output.doctorSummary(warnings, failures);326}327328329330fn homeDoctorNote(ctx: Ctx, mode: exec.HomeManagerMode) []const u8 {331 const label = switch (mode) {332 .standalone => "standalone",333 .module => "module",334 .none => "",335 };336 if (mode == .standalone) {337 const gen = homeCurrentGen(ctx);338 if (gen != 0)339 return std.fmt.allocPrint(ctx.gpa, "{s} gen {d}", .{ label, gen }) catch340 (ctx.gpa.dupe(u8, label) catch "");341 }342 return ctx.gpa.dupe(u8, label) catch "";343}344345346347348fn nixUpgradeNoOp(s: []const u8) bool {349 return std.mem.indexOf(u8, s, "No packages to upgrade") != null or350 std.mem.indexOf(u8, s, "does not match any packages") != null;351}352353354pub fn update(ctx: Ctx) !void {355 output.updateSelfStart();356357 if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {358 output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));359 return error.Internal;360 }361362 const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");363 const source_url = env_url orelse UPDATE_URL;364365 const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {366 error.NetworkError, error.HttpError => {367 output.updateSelfNetworkError();368 return;369 },370 else => return e,371 };372 defer ctx.gpa.free(body);373374 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {375 output.printWarning("could not parse release metadata");376 return;377 };378 defer parsed.deinit();379380 const root = parsed.value;381 if (root != .object) {382 output.printWarning("malformed release metadata");383 return;384 }385386 const remote_ver = blk: {387 const v = root.object.get("version") orelse {388 output.printWarning("malformed release metadata");389 return;390 };391 break :blk switch (v) {392 .string => |s| s,393 else => {394 output.printWarning("malformed release metadata");395 return;396 },397 };398 };399 if (!remoteVersionNewer(version.VERSION, remote_ver)) {400 output.updateSelfCurrent(version.VERSION);401 return;402 }403404 const release_notes = try updateReleaseNotes(ctx.gpa, ctx.io, root, source_url, version.VERSION, remote_ver);405 defer ctx.gpa.free(release_notes);406407 output.updateSelfAvailable(version.VERSION, remote_ver);408 output.updateSelfReleaseNotes(release_notes);409 if (ctx.check) return;410411 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;412 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {413 errors.error_info.setMessage("could not determine install path", .{});414 return error.Internal;415 };416417 418 419 420 421 422 if (std.mem.startsWith(u8, install_path, "/nix/store/")) {423 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);424 defer if (nina_element) |n| ctx.gpa.free(n);425 if (nina_element == null) {426 output.updateSelfSystemManaged();427 return;428 }429 const element = nina_element.?;430 output.updateSelfNixManaged(remote_ver);431 if (ctx.cfg.confirm and !output.confirm("")) return;432 433 434 435 436 437 438 const r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "upgrade", element }) catch {439 output.updateSelfNixFailed();440 return;441 };442 defer ctx.gpa.free(r.stdout);443 defer ctx.gpa.free(r.stderr);444 output.raw(r.stdout);445 output.raw(r.stderr);446 if (r.exit_code != 0 or nixUpgradeNoOp(r.stdout) or nixUpgradeNoOp(r.stderr)) {447 output.updateSelfNixFailed();448 return;449 }450 output.updateSelfDone(version.VERSION, remote_ver);451 output.updateSelfNixRehash();452 return;453 }454455 const plat_info = blk: {456 const pv = root.object.get("platforms") orelse break :blk null;457 if (pv != .object) break :blk null;458 break :blk pv.object.get(version.PLATFORM);459 };460 if (plat_info == null) {461 output.updateSelfNoPlatform(version.PLATFORM);462 return;463 }464465 const dl_url = blk: {466 const v = plat_info.?.object.get("url") orelse {467 output.printWarning("malformed release metadata");468 return;469 };470 break :blk switch (v) {471 .string => |s| s,472 else => {473 output.printWarning("malformed release metadata");474 return;475 },476 };477 };478479 const raw_cksum = blk: {480 if (plat_info.?.object.get("blake3")) |v|481 break :blk switch (v) {482 .string => |s| s,483 else => {484 output.printWarning("malformed release metadata");485 return;486 },487 };488 if (plat_info.?.object.get("checksum")) |v|489 break :blk switch (v) {490 .string => |s| s,491 else => {492 output.printWarning("malformed release metadata");493 return;494 },495 };496 output.printWarning("missing checksum in release metadata");497 return;498 };499 const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;500501 if (ctx.cfg.confirm and !output.confirm("")) return;502503 output.updateSelfDownloading(remote_ver, version.PLATFORM);504 const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {505 output.printWarning("download failed — check your connection and try again");506 return;507 };508 defer ctx.gpa.free(tmp_path);509510 output.updateSelfVerifying();511 exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {512 error.ChecksumMismatch => {513 output.updateSelfChecksumFailed();514 return;515 },516 else => return e,517 };518519 output.updateSelfDone(version.VERSION, remote_ver);520}521522fn updateReleaseNotes(gpa: std.mem.Allocator, io: std.Io, root: std.json.Value, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {523 if (releaseNotesFromMetadata(gpa, root)) |notes| {524 if (std.mem.trim(u8, notes, " \t\r\n").len > 0) return notes;525 gpa.free(notes);526 }527 return buildKeprArchiveReleaseNotes(gpa, io, source_url, current, latest) catch gpa.dupe(u8, "");528}529530fn releaseNotesFromMetadata(gpa: std.mem.Allocator, root: std.json.Value) ?[]u8 {531 if (root != .object) return null;532 533 534 535 const v = root.object.get("notes") orelse return null;536 return switch (v) {537 .string => |s| gpa.dupe(u8, s) catch null,538 else => null,539 };540}541542fn buildKeprArchiveReleaseNotes(gpa: std.mem.Allocator, io: std.Io, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {543 const archive_url = try keprArchiveUrl(gpa, source_url);544 defer gpa.free(archive_url);545546 const body = exec.fetchUrl(gpa, io, archive_url) catch return gpa.dupe(u8, "");547 defer gpa.free(body);548549 return releaseNotesFromArchiveJson(gpa, body, current, latest);550}551552fn keprArchiveUrl(gpa: std.mem.Allocator, source_url: []const u8) ![]u8 {553 const scheme = std.mem.indexOf(u8, source_url, "://") orelse return error.InvalidUpdateSource;554 const path_start = std.mem.indexOfScalarPos(u8, source_url, scheme + 3, '/') orelse return error.InvalidUpdateSource;555 const origin = source_url[0..path_start];556 const path = source_url[path_start..];557 if (!std.mem.startsWith(u8, path, "/api/")) return error.InvalidUpdateSource;558559 const after_api = path["/api/".len..];560 const repo_end = std.mem.indexOfScalar(u8, after_api, '/') orelse return error.InvalidUpdateSource;561 const repo = after_api[0..repo_end];562 if (repo.len == 0) return error.InvalidUpdateSource;563564 return std.fmt.allocPrint(gpa, "{s}/{s}/archives.json?limit=100", .{ origin, repo });565}566567568569570571fn releaseNotesFromArchiveJson(gpa: std.mem.Allocator, body: []const u8, current: []const u8, latest: []const u8) ![]u8 {572 const parsed = std.json.parseFromSlice(std.json.Value, gpa, body, .{}) catch return gpa.dupe(u8, "");573 defer parsed.deinit();574575 if (parsed.value != .object) return gpa.dupe(u8, "");576 const saves_v = parsed.value.object.get("saves") orelse return gpa.dupe(u8, "");577 if (saves_v != .array) return gpa.dupe(u8, "");578579 580 var best_msg = std.StringHashMap([]const u8).init(gpa);581 defer best_msg.deinit();582 var order: std.ArrayList([]const u8) = .empty;583 defer order.deinit(gpa);584585 for (saves_v.array.items) |save| {586 if (save != .object) continue;587 const ver_v = save.object.get("version") orelse continue;588 const msg_v = save.object.get("message") orelse continue;589 if (ver_v != .string or msg_v != .string) continue;590 const ver = ver_v.string;591 const msg = std.mem.trim(u8, msg_v.string, " \t\r\n");592 if (msg.len == 0 or !versionInUpdateRange(ver, current, latest)) continue;593594 const entry = try best_msg.getOrPut(ver);595 if (!entry.found_existing) try order.append(gpa, ver);596 597 entry.value_ptr.* = msg;598 }599600 if (order.items.len == 0) return gpa.dupe(u8, "");601602 var out: std.ArrayList(u8) = .empty;603 errdefer out.deinit(gpa);604 for (order.items) |ver| {605 const msg = best_msg.get(ver).?;606 607 const summary_end = std.mem.indexOf(u8, msg, "\n") orelse msg.len;608 const summary = std.mem.trim(u8, msg[0..summary_end], " \t\r");609 if (summary.len == 0) continue;610 try appendLine(&out, gpa, "## {s}\n", .{ver});611 try appendLine(&out, gpa, "- {s}\n\n", .{summary});612 }613614 if (out.items.len == 0) {615 out.deinit(gpa);616 return gpa.dupe(u8, "");617 }618 return out.toOwnedSlice(gpa);619}620621fn appendLine(out: *std.ArrayList(u8), gpa: std.mem.Allocator, comptime template: []const u8, args: anytype) !void {622 const line = try std.fmt.allocPrint(gpa, template, args);623 defer gpa.free(line);624 try out.appendSlice(gpa, line);625}626627fn versionInUpdateRange(candidate: []const u8, current: []const u8, latest: []const u8) bool {628 const cand = parseSemver(candidate) orelse return std.mem.eql(u8, candidate, latest);629 const cur = parseSemver(current) orelse return std.mem.eql(u8, candidate, latest);630 const lat = parseSemver(latest) orelse return std.mem.eql(u8, candidate, latest);631 return compareSemver(cand, cur) == .gt and compareSemver(cand, lat) != .gt;632}633634fn remoteVersionNewer(current: []const u8, remote: []const u8) bool {635 const cur = parseSemver(current) orelse return !std.mem.eql(u8, current, remote);636 const rem = parseSemver(remote) orelse return !std.mem.eql(u8, current, remote);637 return compareSemver(rem, cur) == .gt;638}639640const VersionOrder = enum { lt, eq, gt };641642fn compareSemver(a: Semver, b: Semver) VersionOrder {643 if (a.major != b.major) return if (a.major < b.major) .lt else .gt;644 if (a.minor != b.minor) return if (a.minor < b.minor) .lt else .gt;645 if (a.patch != b.patch) return if (a.patch < b.patch) .lt else .gt;646 return .eq;647}648649fn parseSemver(raw: []const u8) ?Semver {650 const v = if (std.mem.startsWith(u8, raw, "v")) raw[1..] else raw;651 var it = std.mem.splitScalar(u8, v, '.');652 const major_s = it.next() orelse return null;653 const minor_s = it.next() orelse return null;654 const patch_s = it.next() orelse return null;655 if (it.next() != null) return null;656 return .{657 .major = std.fmt.parseInt(u32, major_s, 10) catch return null,658 .minor = std.fmt.parseInt(u32, minor_s, 10) catch return null,659 .patch = std.fmt.parseInt(u32, patch_s, 10) catch return null,660 };661}662663test "versionInUpdateRange includes only newer versions through latest" {664 try std.testing.expect(versionInUpdateRange("3.2.3", "3.1.9", "3.2.3"));665 try std.testing.expect(versionInUpdateRange("3.2.0", "3.1.9", "3.2.3"));666 try std.testing.expect(!versionInUpdateRange("3.1.9", "3.1.9", "3.2.3"));667 try std.testing.expect(!versionInUpdateRange("3.2.4", "3.1.9", "3.2.3"));668}669670test "nixUpgradeNoOp catches nix's exit-0 no-op warnings" {671 672 try std.testing.expect(nixUpgradeNoOp("warning: No packages to upgrade. Use 'nix profile list'..."));673 try std.testing.expect(nixUpgradeNoOp("warning: Package name 'https://kepr.uk/nina/archive/HEAD.tar.gz' does not match any packages in the profile."));674 675 try std.testing.expect(!nixUpgradeNoOp("building '/nix/store/...-nina-3.4.1.drv'...\n"));676 try std.testing.expect(!nixUpgradeNoOp(""));677}678679test "remoteVersionNewer does not offer downgrades" {680 try std.testing.expect(remoteVersionNewer("3.2.3", "3.2.4"));681 try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.3"));682 try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.4"));683}684685test "releaseNotesFromArchiveJson uses oldest save per version" {686 687 688 const body =689 \\{690 \\ "saves": [691 \\ {"version":"3.2.3","message":"wip: record verification in CONTINUITY"},692 \\ {"version":"3.2.1","message":"old release"},693 \\ {"version":"3.2.3","message":"add streaming deflate path"}694 \\ ]695 \\}696 ;697 const notes = try releaseNotesFromArchiveJson(std.testing.allocator, body, "3.2.1", "3.2.3");698 defer std.testing.allocator.free(notes);699700 try std.testing.expect(std.mem.indexOf(u8, notes, "## 3.2.3") != null);701 try std.testing.expect(std.mem.indexOf(u8, notes, "- add streaming deflate path") != null);702 try std.testing.expect(std.mem.indexOf(u8, notes, "CONTINUITY") == null);703 try std.testing.expect(std.mem.indexOf(u8, notes, "old release") == null);704}705706test "releaseNotesFromMetadata reads canonical notes and ignores retired keys" {707 const a = std.testing.allocator;708709 710 {711 var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"notes\":\"colored progress bar\"}", .{});712 defer parsed.deinit();713 const got = releaseNotesFromMetadata(a, parsed.value).?;714 defer a.free(got);715 try std.testing.expectEqualStrings("colored progress bar", got);716 }717718 719 720 {721 var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"release_notes\":\"x\",\"changelog\":\"y\"}", .{});722 defer parsed.deinit();723 try std.testing.expect(releaseNotesFromMetadata(a, parsed.value) == null);724 }725}726727728729730pub fn goodbye(ctx: Ctx) !void {731 output.goodbyeStart();732733 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;734 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {735 errors.error_info.setMessage("could not determine install path", .{});736 return error.Internal;737 };738739 740 if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {741 output.goodbyeFile(install_path);742 if (ctx.cfg.confirm and !output.confirm("")) return;743 std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {744 errors.error_info.setMessage("could not remove {s}", .{install_path});745 return e;746 };747 output.goodbyeDone();748 return;749 }750751 752 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);753 defer {754 if (nina_element) |n| ctx.gpa.free(n);755 }756757 if (nina_element == null) {758 errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});759 return error.Internal;760 }761762 output.goodbyeNix();763 if (ctx.cfg.confirm and !output.confirm("")) return;764 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {765 output.goodbyeFailed("nix profile remove failed");766 return;767 };768 if (ec != 0) {769 output.goodbyeFailed("nix profile remove failed");770 return;771 }772 output.goodbyeDone();773}774775fn channelUpdateCmd(ctx: Ctx) !void {776 output.updateStart(ctx.machine.name);777 _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);778 output.updateDone();779}780781pub fn upgrade(ctx: Ctx) !void {782 if (!try runPreHook(ctx, "pre-upgrade")) {783 output.aborted();784 return error.HookAborted;785 }786787 output.upgradeStart(ctx.machine.name);788 789 790 791 if (flakeSystem(ctx)) {792 output.printSubstep("updating flake inputs", .{});793 _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};794 } else {795 output.printSubstep("updating channels", .{});796 _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};797 }798 output.printSubstep("rebuilding", .{});799 output.buildPanelInit();800 const start = std.Io.Clock.awake.now(ctx.io);801 var panel = output.BuildPanel{};802 const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel) catch |e| {803 output.buildPanelClear();804 return e;805 };806 output.buildPanelClear();807 if (code != 0) {808 output.applyFailed("");809 return error.BuildFailed;810 }811 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());812 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));813 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;814 output.applyDone(gen, elapsed, false);815 runPostHook(ctx, "post-upgrade");816}817818pub fn log(ctx: Ctx) !void {819 output.logHeader(ctx.machine.name);820 const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {821 822 return;823 };824 defer ctx.gpa.free(content);825 var lines = std.mem.splitScalar(u8, content, '\n');826 while (lines.next()) |line| {827 const t = std.mem.trim(u8, line, " \t\r");828 if (t.len == 0) continue;829 if (t[0] == '{') {830 renderJsonLogLine(ctx.gpa, t);831 } else {832 833 var parts = std.mem.tokenizeScalar(u8, t, '\t');834 const date = parts.next() orelse continue;835 const time = parts.next() orelse "";836 const action = parts.next() orelse "";837 const detail = parts.next() orelse "";838 output.logRow(date, time, action, detail);839 }840 }841}842843844845fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {846 const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {847 output.logRow(line, "", "", ""); 848 return;849 };850 defer parsed.deinit();851 if (parsed.value != .object) return;852 const o = parsed.value.object;853854 const ts = jsonStr(o, "ts");855 const date = if (ts.len >= 10) ts[0..10] else ts;856 const time = if (ts.len >= 16) ts[11..16] else "";857 const action = jsonStr(o, "command");858 const outcome = jsonStr(o, "outcome");859860 var buf: [160]u8 = undefined;861 var detail: []const u8 = outcome;862 if (o.get("gen_after")) |g| {863 if (g == .integer) {864 detail = std.fmt.bufPrint(&buf, "{s} -> gen {d}", .{ outcome, g.integer }) catch outcome;865 }866 }867 output.logRow(date, time, action, detail);868}869870fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {871 if (o.get(key)) |v| {872 if (v == .string) return v.string;873 }874 return "";875}876877pub fn edit(ctx: Ctx) !void {878 879 880 881 if (std.mem.eql(u8, ctx.sub, "hardware")) {882 output.editHardwareWarning();883 return;884 }885886 887 888 var open_dir = false;889 for (ctx.args) |arg| {890 if (std.mem.eql(u8, arg, "--dir")) open_dir = true;891 }892 if (open_dir) {893 output.editOpen(ctx.machine.config_path, ctx.cfg.editor);894 _ = try exec.openEditorSudo(ctx.io, ctx.gpa, ctx.cfg.editor, ctx.machine.config_path);895 return;896 }897898 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});899 defer ctx.gpa.free(path);900 output.editOpen(path, ctx.cfg.editor);901 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);902}903904pub fn fmt(ctx: Ctx) !void {905 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});906 defer ctx.gpa.free(path);907 if (ctx.check) {908 const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);909 if (code != 0) output.fmtNeedsFormat() else output.fmtDone();910 return;911 }912 output.fmtStart(path);913 _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);914 output.fmtDone();915}916917pub fn repl(ctx: Ctx) !void {918 output.replStart();919 _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);920}921922pub fn develop(ctx: Ctx) !void {923 if (std.mem.eql(u8, ctx.sub, "show")) {924 _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);925 return;926 }927 const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))928 ctx.args[0]929 else930 null;931 output.developStart(&.{});932 _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);933 output.developDone();934}935936pub fn info(ctx: Ctx) !void {937 output.infoHeader(ctx.machine.name);938 const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");939 defer ctx.gpa.free(nixos_ver);940 output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));941942 const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");943 defer ctx.gpa.free(kernel);944 output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));945946 const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");947 defer ctx.gpa.free(uptime);948 output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));949}950951pub fn boot(ctx: Ctx) !void {952 output.bootHeader(ctx.machine.name);953 const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};954 defer ctx.gpa.free(entries);955 for (entries, 0..) |entry, i| output.bootEntry(entry, i);956}957958pub fn searchCmd(ctx: Ctx) !void {959 const query = if (ctx.args.len > 0) ctx.args[0] else "";960 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);961 const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages, ctx.environ);962 if (selected) |npkg| try selectAndInstall(ctx, npkg);963}964965pub fn optionCmd(ctx: Ctx) !void {966 const query = if (ctx.args.len > 0) ctx.args[0] else "";967 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);968 _ = try search_tui.run(ctx.gpa, ctx.io, query, .options, ctx.environ);969}970971pub fn install(ctx: Ctx) !void {972 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;973974 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);975976 977 const pkgs = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, pkg_name) catch {978 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});979 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});980 return error.PackageNotFound;981 };982983 if (pkgs.len == 0) {984 985 if (closestPackage(ctx, pkg_name)) |sugg| {986 output.didYouMean(pkg_name, sugg.pname);987 if (output.confirm("")) try selectAndInstall(ctx, sugg);988 return;989 }990 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});991 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});992 return error.PackageNotFound;993 }994995 996 997 var found = pkgs[0];998 for (pkgs) |p| {999 if (std.mem.eql(u8, p.pname, pkg_name)) {1000 found = p;1001 break;1002 }1003 }1004 try selectAndInstall(ctx, found);1005}10061007100810091010fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {1011 if (query.len < 2) return null;1012 var candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..@min(query.len, 4)]) catch &.{};1013 if (candidates.len == 0 and query.len > 2) {1014 candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..2]) catch &.{};1015 }1016 if (candidates.len == 0) return null;10171018 var best: ?types.NixPackage = null;1019 var best_dist: usize = std.math.maxInt(usize);1020 for (candidates) |p| {1021 const d = editDistance(query, p.pname);1022 if (d > 0 and d < best_dist) {1023 best_dist = d;1024 best = p;1025 }1026 }1027 1028 const threshold = @max(@as(usize, 2), query.len / 3);1029 return if (best_dist <= threshold) best else null;1030}1031103210331034fn editDistance(a: []const u8, b: []const u8) usize {1035 const n = b.len;1036 if (a.len == 0) return n;1037 if (n == 0) return a.len;1038 if (n + 1 > 128) return std.math.maxInt(usize);1039 var prev: [128]usize = undefined;1040 var curr: [128]usize = undefined;1041 var j: usize = 0;1042 while (j <= n) : (j += 1) prev[j] = j;1043 var i: usize = 1;1044 while (i <= a.len) : (i += 1) {1045 curr[0] = i;1046 j = 1;1047 while (j <= n) : (j += 1) {1048 const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;1049 curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));1050 }1051 @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);1052 }1053 return prev[n];1054}10551056test "editDistance is case-insensitive Levenshtein" {1057 try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));1058 try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));1059 try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));1060 try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));1061}106210631064106510661067fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {1068 output.installSelectPrompt(npkg.pname, npkg.version);10691070 var choice_buf: [8]u8 = undefined;1071 var choice_len: usize = 0;1072 while (choice_len < choice_buf.len) {1073 const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;1074 if (n == 0) break;1075 if (choice_buf[choice_len] == '\n') break;1076 choice_len += 1;1077 }1078 const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");10791080 if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {1081 try profileInstallPkg(ctx, npkg);1082 } else if (choice[0] == 's' or choice[0] == 'S') {1083 try systemInstallPkg(ctx, npkg);1084 } else if (choice[0] == 't' or choice[0] == 'T') {1085 try tryPkg(ctx, npkg);1086 }1087}10881089fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1090 output.installStart(npkg.pname, .profile);1091 if (npkg.unfree) {1092 output.printSubstep("NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr});1093 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr}));1094 } else {1095 output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});1096 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));1097 }1098 const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, npkg.attr, npkg.unfree);1099 if (code != 0) return error.ProcessFailed;1100 output.installDone(npkg.pname);1101}11021103fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1104 const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1105 defer ctx.gpa.free(config_path);1106 const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;1107 output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);1108 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);1109 if (ctx.cfg.confirm) {1110 if (output.confirm("apply now? ")) {1111 try apply(ctx);1112 }1113 }1114}11151116fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {1117 output.tryStart(npkg.pname);1118 output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});1119 output.tryExitHint();1120 _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);1121 output.tryDone();1122}11231124pub fn remove(ctx: Ctx) !void {1125 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1126 output.removeStart(pkg_name);1127 const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);1128 if (code != 0) return error.ProcessFailed;1129 output.done();1130}11311132pub fn list(ctx: Ctx) !void {1133 output.listHeader(ctx.machine.name);11341135 1136 1137 1138 if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {1139 defer ctx.gpa.free(json);1140 output.listSection("profile");1141 renderProfileJson(ctx.gpa, json);1142 }11431144 1145 1146 if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {1147 defer ctx.gpa.free(paths);1148 output.blankLine();1149 output.listSection("system");1150 var lines = std.mem.splitScalar(u8, paths, '\n');1151 while (lines.next()) |line| {1152 const t = std.mem.trim(u8, line, " \t\r");1153 if (t.len == 0) continue;1154 const row = pkgFromStorePath(t);1155 1156 if (row.version.len == 0) continue;1157 output.listPkg(row.name, row.version);1158 }1159 }1160}11611162const PkgRow = struct { name: []const u8, version: []const u8 };116311641165116611671168fn pkgFromStorePath(path: []const u8) PkgRow {1169 const base = std.fs.path.basename(path);1170 const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;1171 var i: usize = 0;1172 while (i + 1 < after_hash.len) : (i += 1) {1173 if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {1174 return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };1175 }1176 }1177 return .{ .name = after_hash, .version = "" };1178}11791180118111821183fn stripOutputSuffix(ver: []const u8) []const u8 {1184 const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };1185 for (suffixes) |s| {1186 if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];1187 }1188 return ver;1189}11901191test "pkgFromStorePath splits name and version at first dash-digit" {1192 const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");1193 try std.testing.expectEqualStrings("ripgrep", a.name);1194 try std.testing.expectEqualStrings("15.1.0", a.version);11951196 const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");1197 try std.testing.expectEqualStrings("helix", b.name);1198 try std.testing.expectEqualStrings("25.01", b.version);11991200 1201 const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");1202 try std.testing.expectEqualStrings("curl", c.name);1203 try std.testing.expectEqualStrings("8.20.0", c.version);1204}12051206fn firstStorePath(el: std.json.Value) ?[]const u8 {1207 if (el != .object) return null;1208 const sp = el.object.get("storePaths") orelse return null;1209 if (sp != .array or sp.array.items.len == 0) return null;1210 const first = sp.array.items[0];1211 return if (first == .string) first.string else null;1212}1213121412151216fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {1217 const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;1218 defer parsed.deinit();1219 if (parsed.value != .object) return;1220 const elements = parsed.value.object.get("elements") orelse return;1221 switch (elements) {1222 .object => |obj| {1223 var it = obj.iterator();1224 while (it.next()) |entry| {1225 const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";1226 output.listPkg(entry.key_ptr.*, ver);1227 }1228 },1229 .array => |arr| {1230 for (arr.items) |el| {1231 const path = firstStorePath(el) orelse continue;1232 const row = pkgFromStorePath(path);1233 output.listPkg(row.name, row.version);1234 }1235 },1236 else => {},1237 }1238}12391240pub fn tryCmd(ctx: Ctx) !void {1241 const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1242 const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };1243 try tryPkg(ctx, shell_pkg);1244}1245124612471248const home_help = [_][2][]const u8{1249 .{ "init", "set up home manager for the first time" },1250 .{ "init --switch", "set up and activate immediately" },1251 .{ "apply", "apply home-manager configuration" },1252 .{ "apply --dry", "preview changes without activating" },1253 .{ "back", "roll back one generation" },1254 .{ "history", "list all generations" },1255 .{ "edit", "open home.nix" },1256 .{ "check", "validate without applying" },1257 .{ "diff", "compare the latest two generations" },1258 .{ "packages", "list managed packages" },1259};12601261const HomeGen = struct {1262 number: u32,1263 date: []const u8,1264 time: []const u8,1265 path: []const u8,1266};12671268126912701271fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1272 var gens: std.ArrayList(HomeGen) = .empty;1273 var lines = std.mem.splitScalar(u8, out_str, '\n');1274 while (lines.next()) |line| {1275 const t = std.mem.trim(u8, line, " \t\r");1276 if (t.len == 0) continue;1277 var it = std.mem.tokenizeAny(u8, t, " \t");1278 const date = it.next() orelse continue;1279 const time = it.next() orelse continue;1280 var number: ?u32 = null;1281 var path: []const u8 = "";1282 while (it.next()) |tok| {1283 if (std.mem.eql(u8, tok, "id")) {1284 if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1285 } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1286 path = tok;1287 }1288 }1289 const num = number orelse continue;1290 try gens.append(gpa, .{1291 .number = num,1292 .date = try gpa.dupe(u8, date),1293 .time = try gpa.dupe(u8, time),1294 .path = try gpa.dupe(u8, path),1295 });1296 }1297 return gens.toOwnedSlice(gpa);1298}12991300fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1301 for (gens) |g| {1302 gpa.free(g.date);1303 gpa.free(g.time);1304 gpa.free(g.path);1305 }1306 gpa.free(gens);1307}13081309test "parseHomeGenerations reads id, date and store path" {1310 const a = std.testing.allocator;1311 const sample =1312 \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1313 \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1314 ;1315 const gens = try parseHomeGenerations(a, sample);1316 defer freeHomeGens(a, gens);1317 try std.testing.expectEqual(@as(usize, 2), gens.len);1318 try std.testing.expectEqual(@as(u32, 765), gens[0].number);1319 try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1320 try std.testing.expectEqualStrings("11:56", gens[0].time);1321 try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1322 try std.testing.expectEqual(@as(u32, 764), gens[1].number);1323}132413251326fn homeCurrentGen(ctx: Ctx) u32 {1327 const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1328 defer ctx.gpa.free(out);1329 const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1330 defer freeHomeGens(ctx.gpa, gens);1331 return if (gens.len > 0) gens[0].number else 0;1332}13331334pub fn home(ctx: Ctx) !void {1335 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1336 return output.subcommandHelp("home", &home_help, null);13371338 1339 1340 1341 1342 1343 if (!ctx.machine.local) {1344 output.homeLocalOnly(ctx.machine.name);1345 return;1346 }13471348 1349 1350 if (std.mem.eql(u8, ctx.sub, "init")) return homeInitCmd(ctx);13511352 const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1353 if (mode == .none) {1354 output.homeNotInstalled();1355 return;1356 }13571358 1359 1360 if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1361 1362 if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);13631364 if (mode == .module) {1365 output.homeModuleManaged();1366 return;1367 }13681369 if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1370 if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1371 if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1372 if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1373 if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);13741375 return output.subcommandHelp("home", &home_help, null);1376}13771378fn homePackages(ctx: Ctx) !void {1379 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1380 defer ctx.gpa.free(out);1381 const gens = try parseHomeGenerations(ctx.gpa, out);1382 defer freeHomeGens(ctx.gpa, gens);13831384 output.homePackagesHeader(ctx.machine.name);1385 if (gens.len == 0 or gens[0].path.len == 0) return;13861387 1388 1389 1390 1391 1392 const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1393 defer ctx.gpa.free(gen_refs);13941395 var refs = gen_refs;1396 var env_refs: ?[]u8 = null;1397 defer if (env_refs) |e| ctx.gpa.free(e);1398 if (findHomeManagerPath(gen_refs)) |pkg_path| {1399 if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1400 env_refs = e;1401 refs = e;1402 } else |_| {}1403 }14041405 1406 1407 1408 var seen = std.StringHashMap(void).init(ctx.gpa);1409 defer seen.deinit();1410 var lines = std.mem.splitScalar(u8, refs, '\n');1411 while (lines.next()) |line| {1412 const t = std.mem.trim(u8, line, " \t\r");1413 if (t.len == 0) continue;1414 const row = pkgFromStorePath(t);1415 if (row.version.len == 0) continue;1416 if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1417 if (seen.contains(row.name)) continue;1418 seen.put(row.name, {}) catch {};1419 output.listPkg(row.name, row.version);1420 }1421}1422142314241425fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1426 var lines = std.mem.splitScalar(u8, refs, '\n');1427 while (lines.next()) |line| {1428 const t = std.mem.trim(u8, line, " \t\r");1429 if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1430 }1431 return null;1432}14331434test "findHomeManagerPath picks the env, not the generation or infra" {1435 const refs =1436 \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31437 \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1438 \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111439 ;1440 try std.testing.expectEqualStrings(1441 "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1442 findHomeManagerPath(refs).?,1443 );1444 try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1445}14461447fn homeDiff(ctx: Ctx) !void {1448 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1449 defer ctx.gpa.free(out);1450 const gens = try parseHomeGenerations(ctx.gpa, out);1451 defer freeHomeGens(ctx.gpa, gens);14521453 1454 if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1455 output.homeNothingToDiff();1456 return;1457 }1458 const newer = gens[0];1459 const older = gens[1];1460 output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1461 if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1462 return error.ProcessFailed;1463}14641465fn homeCheck(ctx: Ctx) !void {1466 output.homeCheckStart(ctx.machine.name);1467 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1468 if (code != 0) return error.BuildFailed;1469 output.homeCheckOk();1470}14711472fn homeEdit(ctx: Ctx) !void {1473 1474 1475 const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1476 errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1477 return error.ConfigNotFound;1478 };1479 defer ctx.gpa.free(path);1480 output.homeEditOpen(path, ctx.cfg.editor);1481 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1482}14831484fn homeHistory(ctx: Ctx) !void {1485 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1486 defer ctx.gpa.free(out);1487 const gens = try parseHomeGenerations(ctx.gpa, out);1488 defer freeHomeGens(ctx.gpa, gens);1489 output.homeHistoryHeader(ctx.machine.name);1490 1491 for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1492}14931494fn homeBack(ctx: Ctx) !void {1495 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1496 defer ctx.gpa.free(out);1497 const gens = try parseHomeGenerations(ctx.gpa, out);1498 defer freeHomeGens(ctx.gpa, gens);14991500 1501 if (gens.len < 2) {1502 output.alreadyOldest();1503 return;1504 }1505 const current = gens[0].number;1506 const prev = gens[1].number;15071508 output.homeBackStart(ctx.machine.name, current, prev);1509 if (ctx.cfg.confirm and !output.confirm("")) return;1510 const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1511 if (code != 0) return error.BuildFailed;1512 output.homeBackDone(prev);1513}15141515fn homeInitCmd(ctx: Ctx) !void {1516 var switch_on_init = false;1517 var dir: ?[]const u8 = null;1518 for (ctx.args) |arg| {1519 if (std.mem.eql(u8, arg, "--switch")) {1520 switch_on_init = true;1521 } else if (!std.mem.startsWith(u8, arg, "-")) {1522 dir = arg;1523 }1524 }15251526 1527 1528 if (dir == null) {1529 if (exec.homeNixPath(ctx.gpa, ctx.environ)) |path| {1530 defer ctx.gpa.free(path);1531 if (exec.pathExists(ctx.io, path)) {1532 output.homeInitExists(path);1533 return;1534 }1535 }1536 }15371538 output.homeInitStart(switch_on_init, dir);1539 const code = try exec.homeManagerInit(ctx.io, &ctx.machine, ctx.gpa, switch_on_init, dir);1540 if (code != 0) return error.BuildFailed;1541 output.homeInitDone(switch_on_init);1542}15431544fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1545 1546 if (mode == .module) {1547 output.homeModuleManaged();1548 return;1549 }1550 if (ctx.dry) {1551 output.homeApplyDry(ctx.machine.name);1552 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1553 if (code != 0) return error.BuildFailed;1554 output.homeApplyDryDone();1555 return;1556 }15571558 if (!try runPreHook(ctx, "pre-home")) {1559 output.aborted();1560 return error.HookAborted;1561 }15621563 output.homeApplyStart(ctx.machine.name);15641565 1566 1567 const dir = exec.homeFlakeDir(ctx.gpa, ctx.io, ctx.environ);1568 defer if (dir) |d| ctx.gpa.free(d);1569 if (dir) |d| return homeApplyFlake(ctx, d);15701571 output.printSubstep("home-manager switch", .{});1572 const start = std.Io.Clock.awake.now(ctx.io);1573 const code = try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1574 if (code != 0) return error.BuildFailed;15751576 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1577 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1578 output.homeApplyDone(homeCurrentGen(ctx), elapsed);1579 runPostHook(ctx, "post-home");1580}158115821583158415851586fn homeApplyFlake(ctx: Ctx, dir: []const u8) !void {1587 const user = ctx.environ.get("USER") orelse "default";15881589 var refs: std.ArrayList([]const u8) = .empty;1590 defer {1591 for (refs.items) |r| ctx.gpa.free(r);1592 refs.deinit(ctx.gpa);1593 }1594 if (exec.homeManagerAttr(ctx.gpa, ctx.io, &ctx.machine, ctx.environ) catch null) |attr| {1595 defer ctx.gpa.free(attr);1596 try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, attr }));1597 }1598 try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, user }));1599 try refs.append(ctx.gpa, try ctx.gpa.dupe(u8, dir));16001601 const start = std.Io.Clock.awake.now(ctx.io);1602 for (refs.items, 0..) |ref, i| {1603 output.printSubstep("home-manager switch --flake {s}", .{ref});1604 switch (try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)) {1605 .ok => {1606 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1607 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1608 output.homeApplyDone(homeCurrentGen(ctx), elapsed);1609 runPostHook(ctx, "post-home");1610 return;1611 },1612 1613 .attr_missing => {1614 if (i + 1 < refs.items.len) output.homeAttrFallback(ref);1615 continue;1616 },1617 .failed => return error.BuildFailed,1618 }1619 }1620 return error.BuildFailed;1621}1622162316241625const service_help = [_][2][]const u8{1626 .{ "list", "list running services" },1627 .{ "logs <svc>", "show service logs" },1628 .{ "status <svc>", "service status" },1629 .{ "start <svc>", "start a service" },1630 .{ "stop <svc>", "stop a service" },1631 .{ "restart <svc>", "restart a service" },1632 .{ "enable <svc>", "enable at boot" },1633 .{ "disable <svc>", "disable at boot" },1634};16351636pub fn service(ctx: Ctx) !void {1637 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");1638 if (std.mem.eql(u8, ctx.sub, "list")) {1639 output.serviceListHeader(ctx.machine.name);1640 const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1641 defer ctx.gpa.free(svcs);1642 for (svcs) |s| output.serviceRow(s);1643 return;1644 }1645 if (std.mem.eql(u8, ctx.sub, "logs")) {1646 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1647 const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1648 output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1649 _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1650 return;1651 }1652 if (std.mem.eql(u8, ctx.sub, "status")) {1653 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1654 output.serviceVerb("status", name, ctx.machine.name);1655 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1656 return;1657 }1658 1659 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1660 if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1661 if (!output.confirm("")) return;1662 }1663 output.serviceVerb(ctx.sub, name, ctx.machine.name);1664 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1665 output.serviceDone();1666}1667166816691670const flake_help = [_][2][]const u8{1671 .{ "init", "create a new flake.nix" },1672 .{ "update", "update flake inputs" },1673 .{ "update <in>", "update a specific input" },1674 .{ "check", "validate the flake" },1675 .{ "show", "inspect flake outputs" },1676 .{ "lock", "regenerate flake.lock" },1677 .{ "clone <url>", "clone a flake repository" },1678};16791680pub fn flake(ctx: Ctx) !void {1681 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1682 if (std.mem.eql(u8, ctx.sub, "update")) {1683 output.flakeUpdateStart();1684 const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1685 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1686 output.flakeLockWritten();1687 return;1688 }1689 if (std.mem.eql(u8, ctx.sub, "check")) {1690 output.flakeCheckStart();1691 const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1692 if (code == 0) output.flakeValid() else output.checkFailed("");1693 return;1694 }1695 if (std.mem.eql(u8, ctx.sub, "show")) {1696 const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1697 if (json_out) |j| {1698 defer ctx.gpa.free(j);1699 output.flakeShowHeader("flake outputs");1700 1701 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1702 defer parsed.deinit();1703 if (parsed.value == .object) {1704 var it = parsed.value.object.iterator();1705 while (it.next()) |entry| {1706 if (entry.value_ptr.* == .object) {1707 var inner = entry.value_ptr.object.iterator();1708 while (inner.next()) |e2| {1709 const desc = if (e2.value_ptr.* == .object)1710 if (e2.value_ptr.object.get("description")) |d|1711 if (d == .string) d.string else ""1712 else1713 ""1714 else1715 "";1716 output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1717 }1718 }1719 }1720 }1721 }1722 return;1723 }1724 if (std.mem.eql(u8, ctx.sub, "init")) {1725 _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1726 return;1727 }1728 if (std.mem.eql(u8, ctx.sub, "lock")) {1729 _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1730 return;1731 }1732 if (std.mem.eql(u8, ctx.sub, "clone")) {1733 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1734 _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1735 return;1736 }1737}1738173917401741const store_help = [_][2][]const u8{1742 .{ "info", "store size and counts" },1743 .{ "path <attr>", "store path of a package" },1744 .{ "gc", "collect garbage" },1745 .{ "optimise", "deduplicate store paths with hard links" },1746 .{ "verify", "verify store integrity" },1747 .{ "repair", "repair corrupted paths" },1748};17491750pub fn store(ctx: Ctx) !void {1751 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1752 if (std.mem.eql(u8, ctx.sub, "gc")) {1753 _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1754 return;1755 }1756 1757 if (std.mem.eql(u8, ctx.sub, "optimise") or std.mem.eql(u8, ctx.sub, "optimize")) {1758 output.storeOptimiseStart(ctx.machine.name);1759 _ = try exec.storeOptimise(ctx.io, &ctx.machine, ctx.gpa);1760 output.storeOptimiseDone();1761 return;1762 }1763 if (std.mem.eql(u8, ctx.sub, "verify")) {1764 output.storeVerifyStart();1765 _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1766 return;1767 }1768 if (std.mem.eql(u8, ctx.sub, "repair")) {1769 if (ctx.cfg.confirm and !output.confirm("")) return;1770 output.storeRepairStart();1771 _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1772 return;1773 }1774 if (std.mem.eql(u8, ctx.sub, "info")) {1775 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1776 output.storeInfo(si);1777 return;1778 }1779 if (std.mem.eql(u8, ctx.sub, "path")) {1780 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1781 const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1782 defer ctx.gpa.free(path);1783 output.storePath(path);1784 return;1785 }1786 1787 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1788 output.storeInfo(si);1789}1790179117921793const channel_help = [_][2][]const u8{1794 .{ "list", "list channels" },1795 .{ "add <url> [name]", "add a channel" },1796 .{ "remove <name>", "remove a channel" },1797 .{ "update", "update all channels" },1798};17991800pub fn channel(ctx: Ctx) !void {1801 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1802 1803 if (flakeSystem(ctx)) output.flakeChannelNote();1804 if (std.mem.eql(u8, ctx.sub, "list")) {1805 output.channelListHeader(ctx.machine.name);1806 const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1807 defer ctx.gpa.free(chans);1808 for (chans) |ch| output.channelRow(ch);1809 return;1810 }1811 if (std.mem.eql(u8, ctx.sub, "add")) {1812 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1813 const name = if (ctx.args.len > 1) ctx.args[1] else "";1814 _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1815 output.channelDone();1816 return;1817 }1818 if (std.mem.eql(u8, ctx.sub, "remove")) {1819 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1820 _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1821 output.channelDone();1822 return;1823 }1824 if (std.mem.eql(u8, ctx.sub, "update")) {1825 return channelUpdateCmd(ctx);1826 }1827}1828182918301831pub fn profile(ctx: Ctx) !void {1832 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1833 output.profileListHeader();1834 const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1835 if (out) |o| {1836 defer ctx.gpa.free(o);1837 var lines = std.mem.splitScalar(u8, o, '\n');1838 while (lines.next()) |line| {1839 const t = std.mem.trim(u8, line, " \t\r");1840 if (t.len == 0) continue;1841 output.profileRow(t, "", "");1842 }1843 }1844 return;1845 }1846 if (std.mem.eql(u8, ctx.sub, "install")) {1847 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1848 _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, attr, false);1849 output.done();1850 return;1851 }1852 if (std.mem.eql(u8, ctx.sub, "remove")) {1853 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1854 _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1855 output.done();1856 return;1857 }1858 if (std.mem.eql(u8, ctx.sub, "upgrade")) {1859 _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1860 output.done();1861 return;1862 }1863}1864186518661867const pkg_help = [_][2][]const u8{1868 .{ "why <pkg>", "what pulled it in" },1869 .{ "deps <pkg>", "direct dependencies" },1870 .{ "size <pkg>", "closure size" },1871 .{ "path <pkg>", "store path" },1872 .{ "closure <pkg>", "full closure" },1873};18741875pub fn pkg(ctx: Ctx) !void {1876 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1877 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1878 if (std.mem.eql(u8, ctx.sub, "why")) {1879 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1880 return;1881 }1882 if (std.mem.eql(u8, ctx.sub, "deps")) {1883 if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1884 return;1885 }1886 if (std.mem.eql(u8, ctx.sub, "size")) {1887 const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1888 defer ctx.gpa.free(s);1889 output.pkgResult("size", s);1890 return;1891 }1892 if (std.mem.eql(u8, ctx.sub, "path")) {1893 const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1894 defer ctx.gpa.free(p);1895 output.pkgResult("path", p);1896 return;1897 }1898 if (std.mem.eql(u8, ctx.sub, "closure")) {1899 if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1900 return;1901 }1902}1903190419051906pub fn why(ctx: Ctx) !void {1907 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1908 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1909}1910191119121913pub fn pin(ctx: Ctx) !void {1914 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1915 const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1916 exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1917 output.pinDone(input, commit);1918}19191920pub fn unpin(ctx: Ctx) !void {1921 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1922 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1923 output.unpinDone(input);1924}1925192619271928pub fn hash(ctx: Ctx) !void {1929 const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1930 const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1931 defer ctx.gpa.free(h);1932 output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1933}19341935pub fn fetch(ctx: Ctx) !void {1936 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1937 const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1938 defer ctx.gpa.free(h);1939 output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1940}1941194219431944pub fn build(ctx: Ctx) !void {1945 const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1946 output.buildStart(attr orelse "default");1947 const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1948 if (code != 0) return error.BuildFailed;1949 output.buildDone();1950}19511952pub fn runCmd(ctx: Ctx) !void {1953 const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1954 output.runStart(pkg_arg);1955 _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1956}1957195819591960pub fn hello(ctx: Ctx) !void {1961 output.hello(ctx.cfg.machines);1962}19631964const ConfigKind = enum { flake, channel, none };1965196619671968fn scanConfig(io: std.Io) ConfigKind {1969 if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1970 if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1971 return .none;1972}19731974197519761977pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1978 output.firstRunBanner();1979 output.firstRunNoConfig();19801981 var name_buf: [256]u8 = undefined;1982 var path_buf: [256]u8 = undefined;19831984 const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);19851986 output.firstRunScanning();1987 const kind = scanConfig(io);1988 switch (kind) {1989 .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),1990 .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),1991 .none => output.firstRunNoneFound(),1992 }19931994 1995 1996 const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";1997 const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);19981999 2000 2001 const use_flakes = exec.dirHasFlake(gpa, io, config_path);20022003 const conf_path = try config.configPath(gpa, environ);2004 defer gpa.free(conf_path);2005 if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);20062007 2008 const flake_line = if (use_flakes) "flake = true\n" else "";2009 var content_buf: [1024]u8 = undefined;2010 const content = try std.fmt.bufPrint(2011 &content_buf,2012 "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",2013 .{ flake_line, machine_name, config_path },2014 );20152016 const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {2017 errors.error_info.setMessage("could not write {s}", .{conf_path});2018 return error.Internal;2019 };2020 defer file.close(io);2021 file.writePositionalAll(io, content, 0) catch {2022 errors.error_info.setMessage("could not write {s}", .{conf_path});2023 return error.Internal;2024 };20252026 output.firstRunWritten(conf_path);2027}20282029pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2030 2031 2032 2033 config.migrateLegacyConfig(gpa, io, environ);2034 if (config.configPath(gpa, environ)) |conf_path| {2035 defer gpa.free(conf_path);2036 if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {2037 f.close(io);2038 } else |_| {2039 try firstRunWizard(gpa, io, environ);2040 errors.error_info.reset();2041 }2042 } else |_| {}20432044 output.setupCheck();2045 const status = exec.checkNixFeatures(gpa, io, environ);2046 output.setupFeatures(status.nix_command, status.flakes);20472048 if (status.allEnabled()) {2049 output.setupAllSet();2050 api.ensureRegistryPinned(gpa, io, environ);2051 return;2052 }20532054 2055 2056 2057 2058 if (exec.isNixOS(io)) {2059 const conf_path = "/etc/nixos/configuration.nix";2060 if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {2061 output.setupNixosNeedsRebuild(conf_path);2062 return;2063 }2064 output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);2065 if (output.confirmDefaultNo("add it now?")) {2066 if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {2067 output.setupNixosWrote(conf_path);2068 } else |_| {2069 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2070 }2071 } else {2072 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2073 }2074 return;2075 }20762077 2078 output.setupEnabling();2079 const path = try exec.enableNixFeatures(gpa, io, environ);2080 defer gpa.free(path);20812082 output.setupDone(path);2083 api.ensureRegistryPinned(gpa, io, environ);2084}2085208620872088fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {2089 var ts_buf: [32]u8 = undefined;2090 const ts = nowIso(ctx.io, &ts_buf);2091 var buf: [256]u8 = undefined;2092 const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{2093 ts, ctx.machine.name, action, gen,2094 }) catch return;2095 exec.appendNinaLog(ctx.io, ctx.environ, entry);2096}2097209820992100fn nowIso(io: std.Io, buf: []u8) []const u8 {2101 const fallback = "1970-01-01T00:00:00Z";2102 const ns = std.Io.Clock.real.now(io).toNanoseconds();2103 if (ns <= 0) return fallback;2104 const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));2105 const es = std.time.epoch.EpochSeconds{ .secs = secs };2106 const ed = es.getEpochDay();2107 const yd = ed.calculateYearDay();2108 const md = yd.calculateMonthDay();2109 const ds = es.getDaySeconds();2110 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", .{2111 yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,2112 ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),2113 }) catch return fallback;2114}