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}275276pub fn diff(ctx: Ctx) !void {277 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);278 defer ctx.gpa.free(gens);279 var current: u32 = 0;280 var prev: u32 = 0;281 for (gens) |g| {282 if (g.current) current = g.number;283 if (!g.current and g.number > prev and g.number < current) prev = g.number;284 }285 if (ctx.args.len >= 2) {286 const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;287 const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;288 output.diffHeader(a, b, ctx.machine.name);289 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;290 } else {291 output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);292 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;293 }294}295296pub fn mood(ctx: Ctx) !void {297 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;298 const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);299 defer ctx.gpa.free(st.size);300 defer ctx.gpa.free(st.age);301 const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");302 defer ctx.gpa.free(state);303 output.mood(ctx.machine.name, state, gen, st.age, st.size);304}305306pub fn doctor(ctx: Ctx) !void {307 output.doctorHeader(ctx.machine.name);308 const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);309 defer ctx.gpa.free(checks);310 var warnings: u32 = 0;311 var failures: u32 = 0;312 for (checks) |ch| {313 output.doctorRow(ch);314 if (ch.status == .warn) warnings += 1;315 if (ch.status == .fail) failures += 1;316 }317318 319 320 const hm_mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);321 if (hm_mode != .none) {322 const note = homeDoctorNote(ctx, hm_mode);323 defer ctx.gpa.free(note);324 output.doctorRow(.{ .name = "home manager", .status = .ok, .note = note });325 }326327 output.doctorSummary(warnings, failures);328}329330331332fn homeDoctorNote(ctx: Ctx, mode: exec.HomeManagerMode) []const u8 {333 const label = switch (mode) {334 .standalone => "standalone",335 .module => "module",336 .none => "",337 };338 if (mode == .standalone) {339 const gen = homeCurrentGen(ctx);340 if (gen != 0)341 return std.fmt.allocPrint(ctx.gpa, "{s} gen {d}", .{ label, gen }) catch342 (ctx.gpa.dupe(u8, label) catch "");343 }344 return ctx.gpa.dupe(u8, label) catch "";345}346347348pub fn update(ctx: Ctx) !void {349 output.updateSelfStart();350351 if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {352 output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));353 return error.Internal;354 }355356 const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");357 const source_url = env_url orelse UPDATE_URL;358359 const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {360 error.NetworkError, error.HttpError => {361 output.updateSelfNetworkError();362 return;363 },364 else => return e,365 };366 defer ctx.gpa.free(body);367368 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {369 output.printWarning("could not parse release metadata");370 return;371 };372 defer parsed.deinit();373374 const root = parsed.value;375 if (root != .object) {376 output.printWarning("malformed release metadata");377 return;378 }379380 const remote_ver = blk: {381 const v = root.object.get("version") orelse {382 output.printWarning("malformed release metadata");383 return;384 };385 break :blk switch (v) {386 .string => |s| s,387 else => {388 output.printWarning("malformed release metadata");389 return;390 },391 };392 };393 if (!remoteVersionNewer(version.VERSION, remote_ver)) {394 output.updateSelfCurrent(version.VERSION);395 return;396 }397398 const release_notes = try updateReleaseNotes(ctx.gpa, ctx.io, root, source_url, version.VERSION, remote_ver);399 defer ctx.gpa.free(release_notes);400401 output.updateSelfAvailable(version.VERSION, remote_ver);402 output.updateSelfReleaseNotes(release_notes);403 if (ctx.check) return;404405 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;406 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {407 errors.error_info.setMessage("could not determine install path", .{});408 return error.Internal;409 };410411 412 413 414 415 416 if (std.mem.startsWith(u8, install_path, "/nix/store/")) {417 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);418 defer if (nina_element) |n| ctx.gpa.free(n);419 if (nina_element == null) {420 output.updateSelfSystemManaged();421 return;422 }423 const element = nina_element.?;424 output.updateSelfNixManaged(remote_ver);425 if (ctx.cfg.confirm and !output.confirm("")) return;426 427 428 429 430 431 432 433 434 const remove_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "remove", element }) catch {435 output.updateSelfNixFailed();436 return;437 };438 defer ctx.gpa.free(remove_r.stdout);439 defer ctx.gpa.free(remove_r.stderr);440 if (remove_r.exit_code != 0) {441 output.raw(remove_r.stdout);442 output.raw(remove_r.stderr);443 output.updateSelfNixFailed();444 return;445 }446 447 448 449 450 451 const add_r = exec.capture(ctx.gpa, ctx.io, &ctx.machine, &.{ "nix", "profile", "add", "--no-write-lock-file", "--refresh", FLAKE_URL }) catch {452 output.updateSelfNixReinstallFailed();453 return;454 };455 defer ctx.gpa.free(add_r.stdout);456 defer ctx.gpa.free(add_r.stderr);457 if (add_r.exit_code != 0) {458 output.raw(add_r.stdout);459 output.raw(add_r.stderr);460 output.updateSelfNixReinstallFailed();461 return;462 }463 output.updateSelfDone(version.VERSION, remote_ver);464 output.updateSelfNixRehash();465 return;466 }467468 const plat_info = blk: {469 const pv = root.object.get("platforms") orelse break :blk null;470 if (pv != .object) break :blk null;471 break :blk pv.object.get(version.PLATFORM);472 };473 if (plat_info == null) {474 output.updateSelfNoPlatform(version.PLATFORM);475 return;476 }477478 const dl_url = blk: {479 const v = plat_info.?.object.get("url") orelse {480 output.printWarning("malformed release metadata");481 return;482 };483 break :blk switch (v) {484 .string => |s| s,485 else => {486 output.printWarning("malformed release metadata");487 return;488 },489 };490 };491492 const raw_cksum = blk: {493 if (plat_info.?.object.get("blake3")) |v|494 break :blk switch (v) {495 .string => |s| s,496 else => {497 output.printWarning("malformed release metadata");498 return;499 },500 };501 if (plat_info.?.object.get("checksum")) |v|502 break :blk switch (v) {503 .string => |s| s,504 else => {505 output.printWarning("malformed release metadata");506 return;507 },508 };509 output.printWarning("missing checksum in release metadata");510 return;511 };512 const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;513514 if (ctx.cfg.confirm and !output.confirm("")) return;515516 output.updateSelfDownloading(remote_ver, version.PLATFORM);517 const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {518 output.printWarning("download failed — check your connection and try again");519 return;520 };521 defer ctx.gpa.free(tmp_path);522523 output.updateSelfVerifying();524 exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {525 error.ChecksumMismatch => {526 output.updateSelfChecksumFailed();527 return;528 },529 else => return e,530 };531532 output.updateSelfDone(version.VERSION, remote_ver);533}534535536537538539540fn updateReleaseNotes(gpa: std.mem.Allocator, io: std.Io, root: std.json.Value, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {541 if (buildKeprArchiveReleaseNotes(gpa, io, source_url, current, latest) catch null) |notes| {542 if (std.mem.trim(u8, notes, " \t\r\n").len > 0) return notes;543 gpa.free(notes);544 }545 if (releaseNotesFromMetadata(gpa, root)) |notes| return notes;546 return gpa.dupe(u8, "");547}548549fn releaseNotesFromMetadata(gpa: std.mem.Allocator, root: std.json.Value) ?[]u8 {550 if (root != .object) return null;551 552 553 554 const v = root.object.get("notes") orelse return null;555 return switch (v) {556 .string => |s| gpa.dupe(u8, s) catch null,557 else => null,558 };559}560561fn buildKeprArchiveReleaseNotes(gpa: std.mem.Allocator, io: std.Io, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {562 const archive_url = try keprArchiveUrl(gpa, source_url);563 defer gpa.free(archive_url);564565 const body = exec.fetchUrl(gpa, io, archive_url) catch return gpa.dupe(u8, "");566 defer gpa.free(body);567568 return releaseNotesFromArchiveJson(gpa, body, current, latest);569}570571fn keprArchiveUrl(gpa: std.mem.Allocator, source_url: []const u8) ![]u8 {572 const scheme = std.mem.indexOf(u8, source_url, "://") orelse return error.InvalidUpdateSource;573 const path_start = std.mem.indexOfScalarPos(u8, source_url, scheme + 3, '/') orelse return error.InvalidUpdateSource;574 const origin = source_url[0..path_start];575 const path = source_url[path_start..];576 if (!std.mem.startsWith(u8, path, "/api/")) return error.InvalidUpdateSource;577578 const after_api = path["/api/".len..];579 const repo_end = std.mem.indexOfScalar(u8, after_api, '/') orelse return error.InvalidUpdateSource;580 const repo = after_api[0..repo_end];581 if (repo.len == 0) return error.InvalidUpdateSource;582583 return std.fmt.allocPrint(gpa, "{s}/{s}/archives.json?limit=100", .{ origin, repo });584}585586587588589590fn releaseNotesFromArchiveJson(gpa: std.mem.Allocator, body: []const u8, current: []const u8, latest: []const u8) ![]u8 {591 const parsed = std.json.parseFromSlice(std.json.Value, gpa, body, .{}) catch return gpa.dupe(u8, "");592 defer parsed.deinit();593594 if (parsed.value != .object) return gpa.dupe(u8, "");595 const saves_v = parsed.value.object.get("saves") orelse return gpa.dupe(u8, "");596 if (saves_v != .array) return gpa.dupe(u8, "");597598 599 var best_msg = std.StringHashMap([]const u8).init(gpa);600 defer best_msg.deinit();601 var order: std.ArrayList([]const u8) = .empty;602 defer order.deinit(gpa);603604 for (saves_v.array.items) |save| {605 if (save != .object) continue;606 const ver_v = save.object.get("version") orelse continue;607 const msg_v = save.object.get("message") orelse continue;608 if (ver_v != .string or msg_v != .string) continue;609 const ver = ver_v.string;610 const msg = std.mem.trim(u8, msg_v.string, " \t\r\n");611 if (msg.len == 0 or !versionInUpdateRange(ver, current, latest)) continue;612613 const entry = try best_msg.getOrPut(ver);614 if (!entry.found_existing) try order.append(gpa, ver);615 616 entry.value_ptr.* = msg;617 }618619 if (order.items.len == 0) return gpa.dupe(u8, "");620621 var out: std.ArrayList(u8) = .empty;622 errdefer out.deinit(gpa);623 for (order.items) |ver| {624 const msg = best_msg.get(ver).?;625 626 const summary_end = std.mem.indexOf(u8, msg, "\n") orelse msg.len;627 const summary = std.mem.trim(u8, msg[0..summary_end], " \t\r");628 if (summary.len == 0) continue;629 try appendLine(&out, gpa, "## {s}\n", .{ver});630 try appendLine(&out, gpa, "- {s}\n\n", .{summary});631 }632633 if (out.items.len == 0) {634 out.deinit(gpa);635 return gpa.dupe(u8, "");636 }637 return out.toOwnedSlice(gpa);638}639640fn appendLine(out: *std.ArrayList(u8), gpa: std.mem.Allocator, comptime template: []const u8, args: anytype) !void {641 const line = try std.fmt.allocPrint(gpa, template, args);642 defer gpa.free(line);643 try out.appendSlice(gpa, line);644}645646fn versionInUpdateRange(candidate: []const u8, current: []const u8, latest: []const u8) bool {647 const cand = parseSemver(candidate) orelse return std.mem.eql(u8, candidate, latest);648 const cur = parseSemver(current) orelse return std.mem.eql(u8, candidate, latest);649 const lat = parseSemver(latest) orelse return std.mem.eql(u8, candidate, latest);650 return compareSemver(cand, cur) == .gt and compareSemver(cand, lat) != .gt;651}652653fn remoteVersionNewer(current: []const u8, remote: []const u8) bool {654 const cur = parseSemver(current) orelse return !std.mem.eql(u8, current, remote);655 const rem = parseSemver(remote) orelse return !std.mem.eql(u8, current, remote);656 return compareSemver(rem, cur) == .gt;657}658659const VersionOrder = enum { lt, eq, gt };660661fn compareSemver(a: Semver, b: Semver) VersionOrder {662 if (a.major != b.major) return if (a.major < b.major) .lt else .gt;663 if (a.minor != b.minor) return if (a.minor < b.minor) .lt else .gt;664 if (a.patch != b.patch) return if (a.patch < b.patch) .lt else .gt;665 return .eq;666}667668fn parseSemver(raw: []const u8) ?Semver {669 const v = if (std.mem.startsWith(u8, raw, "v")) raw[1..] else raw;670 var it = std.mem.splitScalar(u8, v, '.');671 const major_s = it.next() orelse return null;672 const minor_s = it.next() orelse return null;673 const patch_s = it.next() orelse return null;674 if (it.next() != null) return null;675 return .{676 .major = std.fmt.parseInt(u32, major_s, 10) catch return null,677 .minor = std.fmt.parseInt(u32, minor_s, 10) catch return null,678 .patch = std.fmt.parseInt(u32, patch_s, 10) catch return null,679 };680}681682test "versionInUpdateRange includes only newer versions through latest" {683 try std.testing.expect(versionInUpdateRange("3.2.3", "3.1.9", "3.2.3"));684 try std.testing.expect(versionInUpdateRange("3.2.0", "3.1.9", "3.2.3"));685 try std.testing.expect(!versionInUpdateRange("3.1.9", "3.1.9", "3.2.3"));686 try std.testing.expect(!versionInUpdateRange("3.2.4", "3.1.9", "3.2.3"));687}688689test "remoteVersionNewer does not offer downgrades" {690 try std.testing.expect(remoteVersionNewer("3.2.3", "3.2.4"));691 try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.3"));692 try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.4"));693}694695test "releaseNotesFromArchiveJson uses oldest save per version" {696 697 698 const body =699 \\{700 \\ "saves": [701 \\ {"version":"3.2.3","message":"wip: record verification in CONTINUITY"},702 \\ {"version":"3.2.1","message":"old release"},703 \\ {"version":"3.2.3","message":"add streaming deflate path"}704 \\ ]705 \\}706 ;707 const notes = try releaseNotesFromArchiveJson(std.testing.allocator, body, "3.2.1", "3.2.3");708 defer std.testing.allocator.free(notes);709710 try std.testing.expect(std.mem.indexOf(u8, notes, "## 3.2.3") != null);711 try std.testing.expect(std.mem.indexOf(u8, notes, "- add streaming deflate path") != null);712 try std.testing.expect(std.mem.indexOf(u8, notes, "CONTINUITY") == null);713 try std.testing.expect(std.mem.indexOf(u8, notes, "old release") == null);714}715716test "releaseNotesFromMetadata reads canonical notes and ignores retired keys" {717 const a = std.testing.allocator;718719 720 {721 var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"notes\":\"colored progress bar\"}", .{});722 defer parsed.deinit();723 const got = releaseNotesFromMetadata(a, parsed.value).?;724 defer a.free(got);725 try std.testing.expectEqualStrings("colored progress bar", got);726 }727728 729 730 {731 var parsed = try std.json.parseFromSlice(std.json.Value, a, "{\"release_notes\":\"x\",\"changelog\":\"y\"}", .{});732 defer parsed.deinit();733 try std.testing.expect(releaseNotesFromMetadata(a, parsed.value) == null);734 }735}736737738739740pub fn goodbye(ctx: Ctx) !void {741 output.goodbyeStart();742743 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;744 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {745 errors.error_info.setMessage("could not determine install path", .{});746 return error.Internal;747 };748749 750 if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {751 output.goodbyeFile(install_path);752 if (ctx.cfg.confirm and !output.confirm("")) return;753 std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {754 errors.error_info.setMessage("could not remove {s}", .{install_path});755 return e;756 };757 output.goodbyeDone();758 return;759 }760761 762 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);763 defer {764 if (nina_element) |n| ctx.gpa.free(n);765 }766767 if (nina_element == null) {768 errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});769 return error.Internal;770 }771772 output.goodbyeNix();773 if (ctx.cfg.confirm and !output.confirm("")) return;774 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {775 output.goodbyeFailed("nix profile remove failed");776 return;777 };778 if (ec != 0) {779 output.goodbyeFailed("nix profile remove failed");780 return;781 }782 output.goodbyeDone();783}784785fn channelUpdateCmd(ctx: Ctx) !void {786 output.updateStart(ctx.machine.name);787 _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);788 output.updateDone();789}790791pub fn upgrade(ctx: Ctx) !void {792 if (!try runPreHook(ctx, "pre-upgrade")) {793 output.aborted();794 return error.HookAborted;795 }796797 output.upgradeStart(ctx.machine.name);798 799 800 801 if (flakeSystem(ctx)) {802 output.printSubstep("updating flake inputs", .{});803 _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};804 } else {805 output.printSubstep("updating channels", .{});806 _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};807 }808 output.printSubstep("rebuilding", .{});809 output.buildPanelInit();810 const start = std.Io.Clock.awake.now(ctx.io);811 var panel = output.BuildPanel{};812 const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel, ctx.passthrough) catch |e| {813 output.buildPanelClear();814 return e;815 };816 output.buildPanelClear();817 if (code != 0) {818 output.applyFailed("");819 return error.BuildFailed;820 }821 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());822 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));823 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;824 output.applyDone(gen, elapsed, false);825 runPostHook(ctx, "post-upgrade");826}827828pub fn log(ctx: Ctx) !void {829 output.logHeader(ctx.machine.name);830 const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {831 832 return;833 };834 defer ctx.gpa.free(content);835 var lines = std.mem.splitScalar(u8, content, '\n');836 while (lines.next()) |line| {837 const t = std.mem.trim(u8, line, " \t\r");838 if (t.len == 0) continue;839 if (t[0] == '{') {840 renderJsonLogLine(ctx.gpa, t);841 } else {842 843 var parts = std.mem.tokenizeScalar(u8, t, '\t');844 const date = parts.next() orelse continue;845 const time = parts.next() orelse "";846 const action = parts.next() orelse "";847 const detail = parts.next() orelse "";848 output.logRow(date, time, action, detail);849 }850 }851}852853854855fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {856 const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {857 output.logRow(line, "", "", ""); 858 return;859 };860 defer parsed.deinit();861 if (parsed.value != .object) return;862 const o = parsed.value.object;863864 const ts = jsonStr(o, "ts");865 const date = if (ts.len >= 10) ts[0..10] else ts;866 const time = if (ts.len >= 16) ts[11..16] else "";867 const action = jsonStr(o, "command");868 const outcome = jsonStr(o, "outcome");869870 var buf: [160]u8 = undefined;871 var detail: []const u8 = outcome;872 if (o.get("gen_after")) |g| {873 if (g == .integer) {874 detail = std.fmt.bufPrint(&buf, "{s} -> gen {d}", .{ outcome, g.integer }) catch outcome;875 }876 }877 output.logRow(date, time, action, detail);878}879880fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {881 if (o.get(key)) |v| {882 if (v == .string) return v.string;883 }884 return "";885}886887pub fn edit(ctx: Ctx) !void {888 889 890 891 if (std.mem.eql(u8, ctx.sub, "hardware")) {892 output.editHardwareWarning();893 return;894 }895896 897 898 var open_dir = false;899 for (ctx.args) |arg| {900 if (std.mem.eql(u8, arg, "--dir")) open_dir = true;901 }902 if (open_dir) {903 output.editOpen(ctx.machine.config_path, ctx.cfg.editor);904 _ = try exec.openEditorSudo(ctx.io, ctx.gpa, ctx.cfg.editor, ctx.machine.config_path);905 return;906 }907908 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});909 defer ctx.gpa.free(path);910 output.editOpen(path, ctx.cfg.editor);911 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);912}913914pub fn fmt(ctx: Ctx) !void {915 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});916 defer ctx.gpa.free(path);917 if (ctx.check) {918 const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);919 if (code != 0) output.fmtNeedsFormat() else output.fmtDone();920 return;921 }922 output.fmtStart(path);923 _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);924 output.fmtDone();925}926927pub fn repl(ctx: Ctx) !void {928 output.replStart();929 _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);930}931932pub fn develop(ctx: Ctx) !void {933 if (std.mem.eql(u8, ctx.sub, "show")) {934 _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null, ctx.passthrough);935 return;936 }937 const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))938 ctx.args[0]939 else940 null;941 output.developStart(&.{});942 _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ, ctx.passthrough);943 output.developDone();944}945946pub fn info(ctx: Ctx) !void {947 output.infoHeader(ctx.machine.name);948 const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");949 defer ctx.gpa.free(nixos_ver);950 output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));951952 const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");953 defer ctx.gpa.free(kernel);954 output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));955956 const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");957 defer ctx.gpa.free(uptime);958 output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));959}960961pub fn boot(ctx: Ctx) !void {962 output.bootHeader(ctx.machine.name);963 const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};964 defer ctx.gpa.free(entries);965 for (entries, 0..) |entry, i| output.bootEntry(entry, i);966}967968pub fn searchCmd(ctx: Ctx) !void {969 const query = if (ctx.args.len > 0) ctx.args[0] else "";970 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);971 const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages, ctx.environ);972 if (selected) |npkg| try selectAndInstall(ctx, npkg);973}974975pub fn optionCmd(ctx: Ctx) !void {976 const query = if (ctx.args.len > 0) ctx.args[0] else "";977 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);978 _ = try search_tui.run(ctx.gpa, ctx.io, query, .options, ctx.environ);979}980981pub fn install(ctx: Ctx) !void {982 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;983984 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);985986 987 const pkgs = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, pkg_name) catch {988 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});989 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});990 return error.PackageNotFound;991 };992993 if (pkgs.len == 0) {994 995 if (closestPackage(ctx, pkg_name)) |sugg| {996 output.didYouMean(pkg_name, sugg.pname);997 if (output.confirm("")) try selectAndInstall(ctx, sugg);998 return;999 }1000 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});1001 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});1002 return error.PackageNotFound;1003 }10041005 1006 1007 var found = pkgs[0];1008 for (pkgs) |p| {1009 if (std.mem.eql(u8, p.pname, pkg_name)) {1010 found = p;1011 break;1012 }1013 }1014 try selectAndInstall(ctx, found);1015}10161017101810191020fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {1021 if (query.len < 2) return null;1022 var candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..@min(query.len, 4)]) catch &.{};1023 if (candidates.len == 0 and query.len > 2) {1024 candidates = api.searchPackages(ctx.gpa, ctx.io, ctx.environ, query[0..2]) catch &.{};1025 }1026 if (candidates.len == 0) return null;10271028 var best: ?types.NixPackage = null;1029 var best_dist: usize = std.math.maxInt(usize);1030 for (candidates) |p| {1031 const d = editDistance(query, p.pname);1032 if (d > 0 and d < best_dist) {1033 best_dist = d;1034 best = p;1035 }1036 }1037 1038 const threshold = @max(@as(usize, 2), query.len / 3);1039 return if (best_dist <= threshold) best else null;1040}1041104210431044fn editDistance(a: []const u8, b: []const u8) usize {1045 const n = b.len;1046 if (a.len == 0) return n;1047 if (n == 0) return a.len;1048 if (n + 1 > 128) return std.math.maxInt(usize);1049 var prev: [128]usize = undefined;1050 var curr: [128]usize = undefined;1051 var j: usize = 0;1052 while (j <= n) : (j += 1) prev[j] = j;1053 var i: usize = 1;1054 while (i <= a.len) : (i += 1) {1055 curr[0] = i;1056 j = 1;1057 while (j <= n) : (j += 1) {1058 const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;1059 curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));1060 }1061 @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);1062 }1063 return prev[n];1064}10651066test "editDistance is case-insensitive Levenshtein" {1067 try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));1068 try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));1069 try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));1070 try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));1071}107210731074107510761077fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {1078 output.installSelectPrompt(npkg.pname, npkg.version);10791080 var choice_buf: [8]u8 = undefined;1081 var choice_len: usize = 0;1082 while (choice_len < choice_buf.len) {1083 const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;1084 if (n == 0) break;1085 if (choice_buf[choice_len] == '\n') break;1086 choice_len += 1;1087 }1088 const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");10891090 if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {1091 try profileInstallPkg(ctx, npkg);1092 } else if (choice[0] == 's' or choice[0] == 'S') {1093 try systemInstallPkg(ctx, npkg);1094 } else if (choice[0] == 't' or choice[0] == 'T') {1095 try tryPkg(ctx, npkg);1096 }1097}10981099fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1100 output.installStart(npkg.pname, .profile);1101 if (npkg.unfree) {1102 output.printSubstep("NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr});1103 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "NIXPKGS_ALLOW_UNFREE=1 nix profile add --impure nixpkgs#{s}", .{npkg.attr}));1104 } else {1105 output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});1106 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));1107 }1108 const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, npkg.attr, npkg.unfree);1109 if (code != 0) return error.ProcessFailed;1110 output.installDone(npkg.pname);1111}11121113fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1114 const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1115 defer ctx.gpa.free(config_path);1116 const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;1117 output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);1118 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);1119 if (ctx.cfg.confirm) {1120 if (output.confirm("apply now? ")) {1121 try apply(ctx);1122 }1123 }1124}11251126fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {1127 output.tryStart(npkg.pname);1128 output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});1129 output.tryExitHint();1130 _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);1131 output.tryDone();1132}11331134pub fn remove(ctx: Ctx) !void {1135 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1136 output.removeStart(pkg_name);1137 const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);1138 if (code != 0) return error.ProcessFailed;1139 output.done();1140}11411142pub fn list(ctx: Ctx) !void {1143 output.listHeader(ctx.machine.name);11441145 1146 1147 1148 if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {1149 defer ctx.gpa.free(json);1150 output.listSection("profile");1151 renderProfileJson(ctx.gpa, json);1152 }11531154 1155 1156 if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {1157 defer ctx.gpa.free(paths);1158 output.blankLine();1159 output.listSection("system");1160 var lines = std.mem.splitScalar(u8, paths, '\n');1161 while (lines.next()) |line| {1162 const t = std.mem.trim(u8, line, " \t\r");1163 if (t.len == 0) continue;1164 const row = pkgFromStorePath(t);1165 1166 if (row.version.len == 0) continue;1167 output.listPkg(row.name, row.version);1168 }1169 }1170}11711172const PkgRow = struct { name: []const u8, version: []const u8 };117311741175117611771178fn pkgFromStorePath(path: []const u8) PkgRow {1179 const base = std.fs.path.basename(path);1180 const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;1181 var i: usize = 0;1182 while (i + 1 < after_hash.len) : (i += 1) {1183 if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {1184 return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };1185 }1186 }1187 return .{ .name = after_hash, .version = "" };1188}11891190119111921193fn stripOutputSuffix(ver: []const u8) []const u8 {1194 const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };1195 for (suffixes) |s| {1196 if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];1197 }1198 return ver;1199}12001201test "pkgFromStorePath splits name and version at first dash-digit" {1202 const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");1203 try std.testing.expectEqualStrings("ripgrep", a.name);1204 try std.testing.expectEqualStrings("15.1.0", a.version);12051206 const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");1207 try std.testing.expectEqualStrings("helix", b.name);1208 try std.testing.expectEqualStrings("25.01", b.version);12091210 1211 const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");1212 try std.testing.expectEqualStrings("curl", c.name);1213 try std.testing.expectEqualStrings("8.20.0", c.version);1214}12151216fn firstStorePath(el: std.json.Value) ?[]const u8 {1217 if (el != .object) return null;1218 const sp = el.object.get("storePaths") orelse return null;1219 if (sp != .array or sp.array.items.len == 0) return null;1220 const first = sp.array.items[0];1221 return if (first == .string) first.string else null;1222}1223122412251226fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {1227 const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;1228 defer parsed.deinit();1229 if (parsed.value != .object) return;1230 const elements = parsed.value.object.get("elements") orelse return;1231 switch (elements) {1232 .object => |obj| {1233 var it = obj.iterator();1234 while (it.next()) |entry| {1235 const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";1236 output.listPkg(entry.key_ptr.*, ver);1237 }1238 },1239 .array => |arr| {1240 for (arr.items) |el| {1241 const path = firstStorePath(el) orelse continue;1242 const row = pkgFromStorePath(path);1243 output.listPkg(row.name, row.version);1244 }1245 },1246 else => {},1247 }1248}12491250pub fn tryCmd(ctx: Ctx) !void {1251 const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1252 const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };1253 try tryPkg(ctx, shell_pkg);1254}1255125612571258const home_help = [_][2][]const u8{1259 .{ "init", "set up home manager for the first time" },1260 .{ "init --switch", "set up and activate immediately" },1261 .{ "apply", "apply home-manager configuration" },1262 .{ "apply --dry", "preview changes without activating" },1263 .{ "back", "roll back one generation" },1264 .{ "history", "list all generations" },1265 .{ "edit", "open home.nix" },1266 .{ "check", "validate without applying" },1267 .{ "diff", "compare the latest two generations" },1268 .{ "packages", "list managed packages" },1269};12701271const HomeGen = struct {1272 number: u32,1273 date: []const u8,1274 time: []const u8,1275 path: []const u8,1276};12771278127912801281fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1282 var gens: std.ArrayList(HomeGen) = .empty;1283 var lines = std.mem.splitScalar(u8, out_str, '\n');1284 while (lines.next()) |line| {1285 const t = std.mem.trim(u8, line, " \t\r");1286 if (t.len == 0) continue;1287 var it = std.mem.tokenizeAny(u8, t, " \t");1288 const date = it.next() orelse continue;1289 const time = it.next() orelse continue;1290 var number: ?u32 = null;1291 var path: []const u8 = "";1292 while (it.next()) |tok| {1293 if (std.mem.eql(u8, tok, "id")) {1294 if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1295 } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1296 path = tok;1297 }1298 }1299 const num = number orelse continue;1300 try gens.append(gpa, .{1301 .number = num,1302 .date = try gpa.dupe(u8, date),1303 .time = try gpa.dupe(u8, time),1304 .path = try gpa.dupe(u8, path),1305 });1306 }1307 return gens.toOwnedSlice(gpa);1308}13091310fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1311 for (gens) |g| {1312 gpa.free(g.date);1313 gpa.free(g.time);1314 gpa.free(g.path);1315 }1316 gpa.free(gens);1317}13181319test "parseHomeGenerations reads id, date and store path" {1320 const a = std.testing.allocator;1321 const sample =1322 \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1323 \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1324 ;1325 const gens = try parseHomeGenerations(a, sample);1326 defer freeHomeGens(a, gens);1327 try std.testing.expectEqual(@as(usize, 2), gens.len);1328 try std.testing.expectEqual(@as(u32, 765), gens[0].number);1329 try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1330 try std.testing.expectEqualStrings("11:56", gens[0].time);1331 try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1332 try std.testing.expectEqual(@as(u32, 764), gens[1].number);1333}133413351336fn homeCurrentGen(ctx: Ctx) u32 {1337 const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1338 defer ctx.gpa.free(out);1339 const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1340 defer freeHomeGens(ctx.gpa, gens);1341 return if (gens.len > 0) gens[0].number else 0;1342}13431344pub fn home(ctx: Ctx) !void {1345 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1346 return output.subcommandHelp("home", &home_help, null);13471348 1349 1350 1351 1352 1353 if (!ctx.machine.local) {1354 output.homeLocalOnly(ctx.machine.name);1355 return;1356 }13571358 1359 1360 if (std.mem.eql(u8, ctx.sub, "init")) return homeInitCmd(ctx);13611362 const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1363 if (mode == .none) {1364 output.homeNotInstalled();1365 return;1366 }13671368 1369 1370 if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1371 1372 if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);13731374 if (mode == .module) {1375 output.homeModuleManaged();1376 return;1377 }13781379 if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1380 if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1381 if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1382 if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1383 if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);13841385 return output.subcommandHelp("home", &home_help, null);1386}13871388fn homePackages(ctx: Ctx) !void {1389 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1390 defer ctx.gpa.free(out);1391 const gens = try parseHomeGenerations(ctx.gpa, out);1392 defer freeHomeGens(ctx.gpa, gens);13931394 output.homePackagesHeader(ctx.machine.name);1395 if (gens.len == 0 or gens[0].path.len == 0) return;13961397 1398 1399 1400 1401 1402 const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1403 defer ctx.gpa.free(gen_refs);14041405 var refs = gen_refs;1406 var env_refs: ?[]u8 = null;1407 defer if (env_refs) |e| ctx.gpa.free(e);1408 if (findHomeManagerPath(gen_refs)) |pkg_path| {1409 if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1410 env_refs = e;1411 refs = e;1412 } else |_| {}1413 }14141415 1416 1417 1418 var seen = std.StringHashMap(void).init(ctx.gpa);1419 defer seen.deinit();1420 var lines = std.mem.splitScalar(u8, refs, '\n');1421 while (lines.next()) |line| {1422 const t = std.mem.trim(u8, line, " \t\r");1423 if (t.len == 0) continue;1424 const row = pkgFromStorePath(t);1425 if (row.version.len == 0) continue;1426 if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1427 if (seen.contains(row.name)) continue;1428 seen.put(row.name, {}) catch {};1429 output.listPkg(row.name, row.version);1430 }1431}1432143314341435fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1436 var lines = std.mem.splitScalar(u8, refs, '\n');1437 while (lines.next()) |line| {1438 const t = std.mem.trim(u8, line, " \t\r");1439 if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1440 }1441 return null;1442}14431444test "findHomeManagerPath picks the env, not the generation or infra" {1445 const refs =1446 \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31447 \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1448 \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111449 ;1450 try std.testing.expectEqualStrings(1451 "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1452 findHomeManagerPath(refs).?,1453 );1454 try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1455}14561457fn homeDiff(ctx: Ctx) !void {1458 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1459 defer ctx.gpa.free(out);1460 const gens = try parseHomeGenerations(ctx.gpa, out);1461 defer freeHomeGens(ctx.gpa, gens);14621463 1464 if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1465 output.homeNothingToDiff();1466 return;1467 }1468 const newer = gens[0];1469 const older = gens[1];1470 output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1471 if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1472 return error.ProcessFailed;1473}14741475fn homeCheck(ctx: Ctx) !void {1476 output.homeCheckStart(ctx.machine.name);1477 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1478 if (code != 0) return error.BuildFailed;1479 output.homeCheckOk();1480}14811482fn homeEdit(ctx: Ctx) !void {1483 1484 1485 const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1486 errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1487 return error.ConfigNotFound;1488 };1489 defer ctx.gpa.free(path);1490 output.homeEditOpen(path, ctx.cfg.editor);1491 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1492}14931494fn homeHistory(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);1499 output.homeHistoryHeader(ctx.machine.name);1500 1501 for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1502}15031504fn homeBack(ctx: Ctx) !void {1505 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1506 defer ctx.gpa.free(out);1507 const gens = try parseHomeGenerations(ctx.gpa, out);1508 defer freeHomeGens(ctx.gpa, gens);15091510 1511 if (gens.len < 2) {1512 output.alreadyOldest();1513 return;1514 }1515 const current = gens[0].number;1516 const prev = gens[1].number;15171518 output.homeBackStart(ctx.machine.name, current, prev);1519 if (ctx.cfg.confirm and !output.confirm("")) return;1520 const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1521 if (code != 0) return error.BuildFailed;1522 output.homeBackDone(prev);1523}15241525fn homeInitCmd(ctx: Ctx) !void {1526 var switch_on_init = false;1527 var dir: ?[]const u8 = null;1528 for (ctx.args) |arg| {1529 if (std.mem.eql(u8, arg, "--switch")) {1530 switch_on_init = true;1531 } else if (!std.mem.startsWith(u8, arg, "-")) {1532 dir = arg;1533 }1534 }15351536 1537 1538 if (dir == null) {1539 if (exec.homeNixPath(ctx.gpa, ctx.environ)) |path| {1540 defer ctx.gpa.free(path);1541 if (exec.pathExists(ctx.io, path)) {1542 output.homeInitExists(path);1543 return;1544 }1545 }1546 }15471548 output.homeInitStart(switch_on_init, dir);1549 const code = try exec.homeManagerInit(ctx.io, &ctx.machine, ctx.gpa, switch_on_init, dir);1550 if (code != 0) return error.BuildFailed;1551 output.homeInitDone(switch_on_init);1552}15531554fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1555 1556 if (mode == .module) {1557 output.homeModuleManaged();1558 return;1559 }1560 if (ctx.dry) {1561 output.homeApplyDry(ctx.machine.name);1562 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1563 if (code != 0) return error.BuildFailed;1564 output.homeApplyDryDone();1565 return;1566 }15671568 if (!try runPreHook(ctx, "pre-home")) {1569 output.aborted();1570 return error.HookAborted;1571 }15721573 output.homeApplyStart(ctx.machine.name);15741575 1576 1577 const dir = exec.homeFlakeDir(ctx.gpa, ctx.io, ctx.environ);1578 defer if (dir) |d| ctx.gpa.free(d);1579 if (dir) |d| return homeApplyFlake(ctx, d);15801581 output.printSubstep("home-manager switch", .{});1582 const start = std.Io.Clock.awake.now(ctx.io);1583 const code = try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1584 if (code != 0) return error.BuildFailed;15851586 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1587 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1588 output.homeApplyDone(homeCurrentGen(ctx), elapsed);1589 runPostHook(ctx, "post-home");1590}159115921593159415951596fn homeApplyFlake(ctx: Ctx, dir: []const u8) !void {1597 const user = ctx.environ.get("USER") orelse "default";15981599 var refs: std.ArrayList([]const u8) = .empty;1600 defer {1601 for (refs.items) |r| ctx.gpa.free(r);1602 refs.deinit(ctx.gpa);1603 }1604 if (exec.homeManagerAttr(ctx.gpa, ctx.io, &ctx.machine, ctx.environ) catch null) |attr| {1605 defer ctx.gpa.free(attr);1606 try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, attr }));1607 }1608 try refs.append(ctx.gpa, try std.fmt.allocPrint(ctx.gpa, "{s}#{s}", .{ dir, user }));1609 try refs.append(ctx.gpa, try ctx.gpa.dupe(u8, dir));16101611 const start = std.Io.Clock.awake.now(ctx.io);1612 for (refs.items, 0..) |ref, i| {1613 output.printSubstep("home-manager switch --flake {s}", .{ref});1614 switch (try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref, ctx.passthrough)) {1615 .ok => {1616 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1617 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1618 output.homeApplyDone(homeCurrentGen(ctx), elapsed);1619 runPostHook(ctx, "post-home");1620 return;1621 },1622 1623 .attr_missing => {1624 if (i + 1 < refs.items.len) output.homeAttrFallback(ref);1625 continue;1626 },1627 .failed => return error.BuildFailed,1628 }1629 }1630 return error.BuildFailed;1631}1632163316341635const service_help = [_][2][]const u8{1636 .{ "list", "list running services" },1637 .{ "logs <svc>", "show service logs" },1638 .{ "status <svc>", "service status" },1639 .{ "start <svc>", "start a service" },1640 .{ "stop <svc>", "stop a service" },1641 .{ "restart <svc>", "restart a service" },1642 .{ "enable <svc>", "enable at boot" },1643 .{ "disable <svc>", "disable at boot" },1644};16451646pub fn service(ctx: Ctx) !void {1647 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");1648 if (std.mem.eql(u8, ctx.sub, "list")) {1649 output.serviceListHeader(ctx.machine.name);1650 const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1651 defer ctx.gpa.free(svcs);1652 for (svcs) |s| output.serviceRow(s);1653 return;1654 }1655 if (std.mem.eql(u8, ctx.sub, "logs")) {1656 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1657 const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1658 output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1659 _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1660 return;1661 }1662 if (std.mem.eql(u8, ctx.sub, "status")) {1663 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1664 output.serviceVerb("status", name, ctx.machine.name);1665 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1666 return;1667 }1668 1669 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1670 if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1671 if (!output.confirm("")) return;1672 }1673 output.serviceVerb(ctx.sub, name, ctx.machine.name);1674 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1675 output.serviceDone();1676}1677167816791680const flake_help = [_][2][]const u8{1681 .{ "init", "create a new flake.nix" },1682 .{ "update", "update flake inputs" },1683 .{ "update <in>", "update a specific input" },1684 .{ "check", "validate the flake" },1685 .{ "show", "inspect flake outputs" },1686 .{ "lock", "regenerate flake.lock" },1687 .{ "clone <url>", "clone a flake repository" },1688};16891690pub fn flake(ctx: Ctx) !void {1691 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1692 if (std.mem.eql(u8, ctx.sub, "update")) {1693 output.flakeUpdateStart();1694 const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1695 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input, ctx.passthrough);1696 output.flakeLockWritten();1697 return;1698 }1699 if (std.mem.eql(u8, ctx.sub, "check")) {1700 output.flakeCheckStart();1701 const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa, ctx.passthrough);1702 if (code != 0) {1703 output.checkFailed("");1704 return error.CheckFailed;1705 }1706 output.flakeValid();1707 return;1708 }1709 if (std.mem.eql(u8, ctx.sub, "show")) {1710 const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1711 if (json_out) |j| {1712 defer ctx.gpa.free(j);1713 output.flakeShowHeader("flake outputs");1714 1715 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1716 defer parsed.deinit();1717 if (parsed.value == .object) {1718 var it = parsed.value.object.iterator();1719 while (it.next()) |entry| {1720 if (entry.value_ptr.* == .object) {1721 var inner = entry.value_ptr.object.iterator();1722 while (inner.next()) |e2| {1723 const desc = if (e2.value_ptr.* == .object)1724 if (e2.value_ptr.object.get("description")) |d|1725 if (d == .string) d.string else ""1726 else1727 ""1728 else1729 "";1730 output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1731 }1732 }1733 }1734 }1735 }1736 return;1737 }1738 if (std.mem.eql(u8, ctx.sub, "init")) {1739 _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1740 return;1741 }1742 if (std.mem.eql(u8, ctx.sub, "lock")) {1743 _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1744 return;1745 }1746 if (std.mem.eql(u8, ctx.sub, "clone")) {1747 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1748 _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1749 return;1750 }1751}1752175317541755const store_help = [_][2][]const u8{1756 .{ "info", "store size and counts" },1757 .{ "path <attr>", "store path of a package" },1758 .{ "gc", "collect garbage" },1759 .{ "optimise", "deduplicate store paths with hard links" },1760 .{ "verify", "verify store integrity" },1761 .{ "repair", "repair corrupted paths" },1762};17631764pub fn store(ctx: Ctx) !void {1765 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1766 if (std.mem.eql(u8, ctx.sub, "gc")) {1767 _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1768 return;1769 }1770 1771 if (std.mem.eql(u8, ctx.sub, "optimise") or std.mem.eql(u8, ctx.sub, "optimize")) {1772 output.storeOptimiseStart(ctx.machine.name);1773 _ = try exec.storeOptimise(ctx.io, &ctx.machine, ctx.gpa);1774 output.storeOptimiseDone();1775 return;1776 }1777 if (std.mem.eql(u8, ctx.sub, "verify")) {1778 output.storeVerifyStart();1779 _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1780 return;1781 }1782 if (std.mem.eql(u8, ctx.sub, "repair")) {1783 if (ctx.cfg.confirm and !output.confirm("")) return;1784 output.storeRepairStart();1785 _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1786 return;1787 }1788 if (std.mem.eql(u8, ctx.sub, "info")) {1789 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1790 output.storeInfo(si);1791 return;1792 }1793 if (std.mem.eql(u8, ctx.sub, "path")) {1794 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1795 const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1796 defer ctx.gpa.free(path);1797 output.storePath(path);1798 return;1799 }1800 1801 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1802 output.storeInfo(si);1803}1804180518061807const channel_help = [_][2][]const u8{1808 .{ "list", "list channels" },1809 .{ "add <url> [name]", "add a channel" },1810 .{ "remove <name>", "remove a channel" },1811 .{ "update", "update all channels" },1812};18131814pub fn channel(ctx: Ctx) !void {1815 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1816 1817 if (flakeSystem(ctx)) output.flakeChannelNote();1818 if (std.mem.eql(u8, ctx.sub, "list")) {1819 output.channelListHeader(ctx.machine.name);1820 const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1821 defer ctx.gpa.free(chans);1822 for (chans) |ch| output.channelRow(ch);1823 return;1824 }1825 if (std.mem.eql(u8, ctx.sub, "add")) {1826 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1827 const name = if (ctx.args.len > 1) ctx.args[1] else "";1828 _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1829 output.channelDone();1830 return;1831 }1832 if (std.mem.eql(u8, ctx.sub, "remove")) {1833 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1834 _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1835 output.channelDone();1836 return;1837 }1838 if (std.mem.eql(u8, ctx.sub, "update")) {1839 return channelUpdateCmd(ctx);1840 }1841}1842184318441845pub fn profile(ctx: Ctx) !void {1846 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1847 output.profileListHeader();1848 const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1849 if (out) |o| {1850 defer ctx.gpa.free(o);1851 var lines = std.mem.splitScalar(u8, o, '\n');1852 while (lines.next()) |line| {1853 const t = std.mem.trim(u8, line, " \t\r");1854 if (t.len == 0) continue;1855 output.profileRow(t, "", "");1856 }1857 }1858 return;1859 }1860 if (std.mem.eql(u8, ctx.sub, "install")) {1861 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1862 _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, ctx.environ, attr, false);1863 output.done();1864 return;1865 }1866 if (std.mem.eql(u8, ctx.sub, "remove")) {1867 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1868 _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1869 output.done();1870 return;1871 }1872 if (std.mem.eql(u8, ctx.sub, "upgrade")) {1873 _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1874 output.done();1875 return;1876 }1877}1878187918801881const pkg_help = [_][2][]const u8{1882 .{ "why <pkg>", "what pulled it in" },1883 .{ "deps <pkg>", "direct dependencies" },1884 .{ "size <pkg>", "closure size" },1885 .{ "path <pkg>", "store path" },1886 .{ "closure <pkg>", "full closure" },1887};18881889pub fn pkg(ctx: Ctx) !void {1890 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1891 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1892 if (std.mem.eql(u8, ctx.sub, "why")) {1893 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1894 return;1895 }1896 if (std.mem.eql(u8, ctx.sub, "deps")) {1897 if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1898 return;1899 }1900 if (std.mem.eql(u8, ctx.sub, "size")) {1901 const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1902 defer ctx.gpa.free(s);1903 output.pkgResult("size", s);1904 return;1905 }1906 if (std.mem.eql(u8, ctx.sub, "path")) {1907 const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1908 defer ctx.gpa.free(p);1909 output.pkgResult("path", p);1910 return;1911 }1912 if (std.mem.eql(u8, ctx.sub, "closure")) {1913 if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1914 return;1915 }1916}1917191819191920pub fn why(ctx: Ctx) !void {1921 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1922 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1923}1924192519261927pub fn pin(ctx: Ctx) !void {1928 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1929 const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1930 exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1931 output.pinDone(input, commit);1932}19331934pub fn unpin(ctx: Ctx) !void {1935 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1936 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input, &.{});1937 output.unpinDone(input);1938}1939194019411942pub fn hash(ctx: Ctx) !void {1943 const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1944 const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1945 defer ctx.gpa.free(h);1946 output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1947}19481949pub fn fetch(ctx: Ctx) !void {1950 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1951 const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1952 defer ctx.gpa.free(h);1953 output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1954}1955195619571958pub fn build(ctx: Ctx) !void {1959 const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1960 output.buildStart(attr orelse "default");1961 const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr, ctx.passthrough);1962 if (code != 0) return error.BuildFailed;1963 output.buildDone();1964}19651966pub fn runCmd(ctx: Ctx) !void {1967 const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1968 output.runStart(pkg_arg);1969 _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg, ctx.passthrough);1970}1971197219731974pub fn hello(ctx: Ctx) !void {1975 output.hello(ctx.cfg.machines);1976}19771978const ConfigKind = enum { flake, channel, none };1979198019811982fn scanConfig(io: std.Io) ConfigKind {1983 if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1984 if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1985 return .none;1986}19871988198919901991pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1992 output.firstRunBanner();1993 output.firstRunNoConfig();19941995 var name_buf: [256]u8 = undefined;1996 var path_buf: [256]u8 = undefined;19971998 const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);19992000 output.firstRunScanning();2001 const kind = scanConfig(io);2002 switch (kind) {2003 .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),2004 .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),2005 .none => output.firstRunNoneFound(),2006 }20072008 2009 2010 const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";2011 const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);20122013 2014 2015 const use_flakes = exec.dirHasFlake(gpa, io, config_path);20162017 const conf_path = try config.configPath(gpa, environ);2018 defer gpa.free(conf_path);2019 if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);20202021 2022 const flake_line = if (use_flakes) "flake = true\n" else "";2023 var content_buf: [1024]u8 = undefined;2024 const content = try std.fmt.bufPrint(2025 &content_buf,2026 "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",2027 .{ flake_line, machine_name, config_path },2028 );20292030 const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {2031 errors.error_info.setMessage("could not write {s}", .{conf_path});2032 return error.Internal;2033 };2034 defer file.close(io);2035 file.writePositionalAll(io, content, 0) catch {2036 errors.error_info.setMessage("could not write {s}", .{conf_path});2037 return error.Internal;2038 };20392040 output.firstRunWritten(conf_path);2041}20422043pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {2044 2045 2046 2047 config.migrateLegacyConfig(gpa, io, environ);2048 if (config.configPath(gpa, environ)) |conf_path| {2049 defer gpa.free(conf_path);2050 if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {2051 f.close(io);2052 } else |_| {2053 try firstRunWizard(gpa, io, environ);2054 errors.error_info.reset();2055 }2056 } else |_| {}20572058 output.setupCheck();2059 const status = exec.checkNixFeatures(gpa, io, environ);2060 output.setupFeatures(status.nix_command, status.flakes);20612062 if (status.allEnabled()) {2063 output.setupAllSet();2064 api.ensureRegistryPinned(gpa, io, environ);2065 return;2066 }20672068 2069 2070 2071 2072 if (exec.isNixOS(io)) {2073 const conf_path = "/etc/nixos/configuration.nix";2074 if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {2075 output.setupNixosNeedsRebuild(conf_path);2076 return;2077 }2078 output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);2079 if (output.confirmDefaultNo("add it now?")) {2080 if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {2081 output.setupNixosWrote(conf_path);2082 } else |_| {2083 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2084 }2085 } else {2086 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);2087 }2088 return;2089 }20902091 2092 output.setupEnabling();2093 const path = try exec.enableNixFeatures(gpa, io, environ);2094 defer gpa.free(path);20952096 output.setupDone(path);2097 api.ensureRegistryPinned(gpa, io, environ);2098}2099210021012102fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {2103 var ts_buf: [32]u8 = undefined;2104 const ts = nowIso(ctx.io, &ts_buf);2105 var buf: [256]u8 = undefined;2106 const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{2107 ts, ctx.machine.name, action, gen,2108 }) catch return;2109 exec.appendNinaLog(ctx.io, ctx.environ, entry);2110}2111211221132114fn nowIso(io: std.Io, buf: []u8) []const u8 {2115 const fallback = "1970-01-01T00:00:00Z";2116 const ns = std.Io.Clock.real.now(io).toNanoseconds();2117 if (ns <= 0) return fallback;2118 const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));2119 const es = std.time.epoch.EpochSeconds{ .secs = secs };2120 const ed = es.getEpochDay();2121 const yd = ed.calculateYearDay();2122 const md = yd.calculateMonthDay();2123 const ds = es.getDaySeconds();2124 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", .{2125 yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,2126 ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),2127 }) catch return fallback;2128}