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}344345346pub fn update(ctx: Ctx) !void {347 output.updateSelfStart();348349 if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {350 output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));351 return error.Internal;352 }353354 const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");355 const source_url = env_url orelse UPDATE_URL;356357 const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {358 error.NetworkError, error.HttpError => {359 output.updateSelfNetworkError();360 return;361 },362 else => return e,363 };364 defer ctx.gpa.free(body);365366 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {367 output.printWarning("could not parse release metadata");368 return;369 };370 defer parsed.deinit();371372 const root = parsed.value;373 if (root != .object) {374 output.printWarning("malformed release metadata");375 return;376 }377378 const remote_ver = blk: {379 const v = root.object.get("version") orelse {380 output.printWarning("malformed release metadata");381 return;382 };383 break :blk switch (v) {384 .string => |s| s,385 else => {386 output.printWarning("malformed release metadata");387 return;388 },389 };390 };391 if (!remoteVersionNewer(version.VERSION, remote_ver)) {392 output.updateSelfCurrent(version.VERSION);393 return;394 }395396 const release_notes = try updateReleaseNotes(ctx.gpa, ctx.io, root, source_url, version.VERSION, remote_ver);397 defer ctx.gpa.free(release_notes);398399 output.updateSelfAvailable(version.VERSION, remote_ver);400 output.updateSelfReleaseNotes(release_notes);401 if (ctx.check) return;402403 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;404 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {405 errors.error_info.setMessage("could not determine install path", .{});406 return error.Internal;407 };408409 410 411 412 413 414 if (std.mem.startsWith(u8, install_path, "/nix/store/")) {415 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);416 defer {417 if (nina_element) |n| ctx.gpa.free(n);418 }419 if (nina_element == null) {420 output.updateSelfNotInProfile();421 return;422 }423 const element = nina_element.?;424 output.updateSelfNixManaged(remote_ver);425 if (ctx.cfg.confirm and !output.confirm("")) return;426 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", element }) catch {427 output.updateSelfNixFailed();428 return;429 };430 if (ec != 0) {431 output.updateSelfNixFailed();432 return;433 }434 output.updateSelfDone(version.VERSION, remote_ver);435 return;436 }437438 const plat_info = blk: {439 const pv = root.object.get("platforms") orelse break :blk null;440 if (pv != .object) break :blk null;441 break :blk pv.object.get(version.PLATFORM);442 };443 if (plat_info == null) {444 output.updateSelfNoPlatform(version.PLATFORM);445 return;446 }447448 const dl_url = blk: {449 const v = plat_info.?.object.get("url") orelse {450 output.printWarning("malformed release metadata");451 return;452 };453 break :blk switch (v) {454 .string => |s| s,455 else => {456 output.printWarning("malformed release metadata");457 return;458 },459 };460 };461462 const raw_cksum = blk: {463 if (plat_info.?.object.get("blake3")) |v|464 break :blk switch (v) {465 .string => |s| s,466 else => {467 output.printWarning("malformed release metadata");468 return;469 },470 };471 if (plat_info.?.object.get("checksum")) |v|472 break :blk switch (v) {473 .string => |s| s,474 else => {475 output.printWarning("malformed release metadata");476 return;477 },478 };479 output.printWarning("missing checksum in release metadata");480 return;481 };482 const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;483484 if (ctx.cfg.confirm and !output.confirm("")) return;485486 output.updateSelfDownloading(remote_ver, version.PLATFORM);487 const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {488 output.printWarning("download failed — check your connection and try again");489 return;490 };491 defer ctx.gpa.free(tmp_path);492493 output.updateSelfVerifying();494 exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {495 error.ChecksumMismatch => {496 output.updateSelfChecksumFailed();497 return;498 },499 else => return e,500 };501502 output.updateSelfDone(version.VERSION, remote_ver);503}504505fn updateReleaseNotes(gpa: std.mem.Allocator, io: std.Io, root: std.json.Value, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {506 if (releaseNotesFromMetadata(gpa, root)) |notes| {507 if (std.mem.trim(u8, notes, " \t\r\n").len > 0) return notes;508 gpa.free(notes);509 }510 return buildKeprArchiveReleaseNotes(gpa, io, source_url, current, latest) catch gpa.dupe(u8, "");511}512513fn releaseNotesFromMetadata(gpa: std.mem.Allocator, root: std.json.Value) ?[]u8 {514 if (root != .object) return null;515 const keys = [_][]const u8{ "release_notes", "changelog", "notes" };516 for (keys) |key| {517 const v = root.object.get(key) orelse continue;518 switch (v) {519 .string => |s| return gpa.dupe(u8, s) catch null,520 else => {},521 }522 }523 return null;524}525526fn buildKeprArchiveReleaseNotes(gpa: std.mem.Allocator, io: std.Io, source_url: []const u8, current: []const u8, latest: []const u8) ![]u8 {527 const archive_url = try keprArchiveUrl(gpa, source_url);528 defer gpa.free(archive_url);529530 const body = exec.fetchUrl(gpa, io, archive_url) catch return gpa.dupe(u8, "");531 defer gpa.free(body);532533 return releaseNotesFromArchiveJson(gpa, body, current, latest);534}535536fn keprArchiveUrl(gpa: std.mem.Allocator, source_url: []const u8) ![]u8 {537 const scheme = std.mem.indexOf(u8, source_url, "://") orelse return error.InvalidUpdateSource;538 const path_start = std.mem.indexOfScalarPos(u8, source_url, scheme + 3, '/') orelse return error.InvalidUpdateSource;539 const origin = source_url[0..path_start];540 const path = source_url[path_start..];541 if (!std.mem.startsWith(u8, path, "/api/")) return error.InvalidUpdateSource;542543 const after_api = path["/api/".len..];544 const repo_end = std.mem.indexOfScalar(u8, after_api, '/') orelse return error.InvalidUpdateSource;545 const repo = after_api[0..repo_end];546 if (repo.len == 0) return error.InvalidUpdateSource;547548 return std.fmt.allocPrint(gpa, "{s}/{s}/archives.json?limit=40", .{ origin, repo });549}550551fn releaseNotesFromArchiveJson(gpa: std.mem.Allocator, body: []const u8, current: []const u8, latest: []const u8) ![]u8 {552 const parsed = std.json.parseFromSlice(std.json.Value, gpa, body, .{}) catch return gpa.dupe(u8, "");553 defer parsed.deinit();554555 if (parsed.value != .object) return gpa.dupe(u8, "");556 const saves_v = parsed.value.object.get("saves") orelse return gpa.dupe(u8, "");557 if (saves_v != .array) return gpa.dupe(u8, "");558559 var out: std.ArrayList(u8) = .empty;560 errdefer out.deinit(gpa);561 var any = false;562 for (saves_v.array.items) |save| {563 if (save != .object) continue;564 const ver_v = save.object.get("version") orelse continue;565 const msg_v = save.object.get("message") orelse continue;566 if (ver_v != .string or msg_v != .string) continue;567 const ver = ver_v.string;568 const msg = std.mem.trim(u8, msg_v.string, " \t\r\n");569 if (msg.len == 0 or !versionInUpdateRange(ver, current, latest)) continue;570571 try appendFmt(&out, gpa, "## {s}\n", .{ver});572 try appendFmt(&out, gpa, "- {s}\n\n", .{msg});573 any = true;574 }575576 if (!any) {577 out.deinit(gpa);578 return gpa.dupe(u8, "");579 }580 return out.toOwnedSlice(gpa);581}582583fn appendFmt(out: *std.ArrayList(u8), gpa: std.mem.Allocator, comptime template: []const u8, args: anytype) !void {584 const line = try std.fmt.allocPrint(gpa, template, args);585 defer gpa.free(line);586 try out.appendSlice(gpa, line);587}588589fn versionInUpdateRange(candidate: []const u8, current: []const u8, latest: []const u8) bool {590 const cand = parseSemver(candidate) orelse return std.mem.eql(u8, candidate, latest);591 const cur = parseSemver(current) orelse return std.mem.eql(u8, candidate, latest);592 const lat = parseSemver(latest) orelse return std.mem.eql(u8, candidate, latest);593 return compareSemver(cand, cur) == .gt and compareSemver(cand, lat) != .gt;594}595596fn remoteVersionNewer(current: []const u8, remote: []const u8) bool {597 const cur = parseSemver(current) orelse return !std.mem.eql(u8, current, remote);598 const rem = parseSemver(remote) orelse return !std.mem.eql(u8, current, remote);599 return compareSemver(rem, cur) == .gt;600}601602const VersionOrder = enum { lt, eq, gt };603604fn compareSemver(a: Semver, b: Semver) VersionOrder {605 if (a.major != b.major) return if (a.major < b.major) .lt else .gt;606 if (a.minor != b.minor) return if (a.minor < b.minor) .lt else .gt;607 if (a.patch != b.patch) return if (a.patch < b.patch) .lt else .gt;608 return .eq;609}610611fn parseSemver(raw: []const u8) ?Semver {612 const v = if (std.mem.startsWith(u8, raw, "v")) raw[1..] else raw;613 var it = std.mem.splitScalar(u8, v, '.');614 const major_s = it.next() orelse return null;615 const minor_s = it.next() orelse return null;616 const patch_s = it.next() orelse return null;617 if (it.next() != null) return null;618 return .{619 .major = std.fmt.parseInt(u32, major_s, 10) catch return null,620 .minor = std.fmt.parseInt(u32, minor_s, 10) catch return null,621 .patch = std.fmt.parseInt(u32, patch_s, 10) catch return null,622 };623}624625test "versionInUpdateRange includes only newer versions through latest" {626 try std.testing.expect(versionInUpdateRange("3.2.3", "3.1.9", "3.2.3"));627 try std.testing.expect(versionInUpdateRange("3.2.0", "3.1.9", "3.2.3"));628 try std.testing.expect(!versionInUpdateRange("3.1.9", "3.1.9", "3.2.3"));629 try std.testing.expect(!versionInUpdateRange("3.2.4", "3.1.9", "3.2.3"));630}631632test "remoteVersionNewer does not offer downgrades" {633 try std.testing.expect(remoteVersionNewer("3.2.3", "3.2.4"));634 try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.3"));635 try std.testing.expect(!remoteVersionNewer("3.2.4", "3.2.4"));636}637638test "releaseNotesFromArchiveJson builds changelog from versioned saves" {639 const body =640 \\{641 \\ "saves": [642 \\ {"version":"3.2.3","message":"upgrade: live build panel during rebuild phase"},643 \\ {"version":"3.1.9","message":"old release"},644 \\ {"version":null,"message":"unversioned"}645 \\ ]646 \\}647 ;648 const notes = try releaseNotesFromArchiveJson(std.testing.allocator, body, "3.1.9", "3.2.3");649 defer std.testing.allocator.free(notes);650651 try std.testing.expect(std.mem.indexOf(u8, notes, "## 3.2.3") != null);652 try std.testing.expect(std.mem.indexOf(u8, notes, "- upgrade: live build panel") != null);653 try std.testing.expect(std.mem.indexOf(u8, notes, "old release") == null);654}655656657658659pub fn goodbye(ctx: Ctx) !void {660 output.goodbyeStart();661662 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;663 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {664 errors.error_info.setMessage("could not determine install path", .{});665 return error.Internal;666 };667668 669 if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {670 output.goodbyeFile(install_path);671 if (ctx.cfg.confirm and !output.confirm("")) return;672 std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {673 errors.error_info.setMessage("could not remove {s}", .{install_path});674 return e;675 };676 output.goodbyeDone();677 return;678 }679680 681 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);682 defer {683 if (nina_element) |n| ctx.gpa.free(n);684 }685686 if (nina_element == null) {687 errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});688 return error.Internal;689 }690691 output.goodbyeNix();692 if (ctx.cfg.confirm and !output.confirm("")) return;693 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {694 output.goodbyeFailed("nix profile remove failed");695 return;696 };697 if (ec != 0) {698 output.goodbyeFailed("nix profile remove failed");699 return;700 }701 output.goodbyeDone();702}703704fn channelUpdateCmd(ctx: Ctx) !void {705 output.updateStart(ctx.machine.name);706 _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);707 output.updateDone();708}709710pub fn upgrade(ctx: Ctx) !void {711 if (!try runPreHook(ctx, "pre-upgrade")) {712 output.aborted();713 return error.HookAborted;714 }715716 output.upgradeStart(ctx.machine.name);717 718 719 720 if (flakeSystem(ctx)) {721 output.printSubstep("updating flake inputs", .{});722 _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};723 } else {724 output.printSubstep("updating channels", .{});725 _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};726 }727 output.printSubstep("rebuilding", .{});728 output.buildPanelInit();729 const start = std.Io.Clock.awake.now(ctx.io);730 var panel = output.BuildPanel{};731 const code = exec.nixosRebuildSwitchWithPanel(ctx.io, &ctx.machine, ctx.gpa, &panel) catch |e| {732 output.buildPanelClear();733 return e;734 };735 output.buildPanelClear();736 if (code != 0) {737 output.applyFailed("");738 return error.BuildFailed;739 }740 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());741 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));742 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;743 output.applyDone(gen, elapsed, false);744 runPostHook(ctx, "post-upgrade");745}746747pub fn log(ctx: Ctx) !void {748 output.logHeader(ctx.machine.name);749 const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {750 751 return;752 };753 defer ctx.gpa.free(content);754 var lines = std.mem.splitScalar(u8, content, '\n');755 while (lines.next()) |line| {756 const t = std.mem.trim(u8, line, " \t\r");757 if (t.len == 0) continue;758 if (t[0] == '{') {759 renderJsonLogLine(ctx.gpa, t);760 } else {761 762 var parts = std.mem.tokenizeScalar(u8, t, '\t');763 const date = parts.next() orelse continue;764 const time = parts.next() orelse "";765 const action = parts.next() orelse "";766 const detail = parts.next() orelse "";767 output.logRow(date, time, action, detail);768 }769 }770}771772773774fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {775 const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {776 output.logRow(line, "", "", ""); 777 return;778 };779 defer parsed.deinit();780 if (parsed.value != .object) return;781 const o = parsed.value.object;782783 const ts = jsonStr(o, "ts");784 const date = if (ts.len >= 10) ts[0..10] else ts;785 const time = if (ts.len >= 16) ts[11..16] else "";786 const action = jsonStr(o, "command");787 const outcome = jsonStr(o, "outcome");788789 var buf: [160]u8 = undefined;790 var detail: []const u8 = outcome;791 if (o.get("gen_after")) |g| {792 if (g == .integer) {793 detail = std.fmt.bufPrint(&buf, "{s} -> gen {d}", .{ outcome, g.integer }) catch outcome;794 }795 }796 output.logRow(date, time, action, detail);797}798799fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {800 if (o.get(key)) |v| {801 if (v == .string) return v.string;802 }803 return "";804}805806pub fn edit(ctx: Ctx) !void {807 const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");808 const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";809 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });810 defer ctx.gpa.free(path);811 output.editOpen(path, ctx.cfg.editor);812 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);813}814815pub fn fmt(ctx: Ctx) !void {816 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});817 defer ctx.gpa.free(path);818 if (ctx.check) {819 const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);820 if (code != 0) output.fmtNeedsFormat() else output.fmtDone();821 return;822 }823 output.fmtStart(path);824 _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);825 output.fmtDone();826}827828pub fn repl(ctx: Ctx) !void {829 output.replStart();830 _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);831}832833pub fn develop(ctx: Ctx) !void {834 if (std.mem.eql(u8, ctx.sub, "show")) {835 _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);836 return;837 }838 const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))839 ctx.args[0]840 else841 null;842 output.developStart(&.{});843 _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);844 output.developDone();845}846847pub fn info(ctx: Ctx) !void {848 output.infoHeader(ctx.machine.name);849 const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");850 defer ctx.gpa.free(nixos_ver);851 output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));852853 const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");854 defer ctx.gpa.free(kernel);855 output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));856857 const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");858 defer ctx.gpa.free(uptime);859 output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));860}861862pub fn boot(ctx: Ctx) !void {863 output.bootHeader(ctx.machine.name);864 const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};865 defer ctx.gpa.free(entries);866 for (entries, 0..) |entry, i| output.bootEntry(entry, i);867}868869pub fn searchCmd(ctx: Ctx) !void {870 const query = if (ctx.args.len > 0) ctx.args[0] else "";871 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);872 const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);873 if (selected) |npkg| try selectAndInstall(ctx, npkg);874}875876pub fn optionCmd(ctx: Ctx) !void {877 const query = if (ctx.args.len > 0) ctx.args[0] else "";878 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);879 _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);880}881882pub fn install(ctx: Ctx) !void {883 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;884885 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);886887 888 const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {889 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});890 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});891 return error.PackageNotFound;892 };893894 if (pkgs.len == 0) {895 896 if (closestPackage(ctx, pkg_name)) |sugg| {897 output.didYouMean(pkg_name, sugg.pname);898 if (output.confirm("")) try selectAndInstall(ctx, sugg);899 return;900 }901 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});902 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});903 return error.PackageNotFound;904 }905906 907 908 var found = pkgs[0];909 for (pkgs) |p| {910 if (std.mem.eql(u8, p.pname, pkg_name)) {911 found = p;912 break;913 }914 }915 try selectAndInstall(ctx, found);916}917918919920921fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {922 if (query.len < 2) return null;923 var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};924 if (candidates.len == 0 and query.len > 2) {925 candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};926 }927 if (candidates.len == 0) return null;928929 var best: ?types.NixPackage = null;930 var best_dist: usize = std.math.maxInt(usize);931 for (candidates) |p| {932 const d = editDistance(query, p.pname);933 if (d > 0 and d < best_dist) {934 best_dist = d;935 best = p;936 }937 }938 939 const threshold = @max(@as(usize, 2), query.len / 3);940 return if (best_dist <= threshold) best else null;941}942943944945fn editDistance(a: []const u8, b: []const u8) usize {946 const n = b.len;947 if (a.len == 0) return n;948 if (n == 0) return a.len;949 if (n + 1 > 128) return std.math.maxInt(usize);950 var prev: [128]usize = undefined;951 var curr: [128]usize = undefined;952 var j: usize = 0;953 while (j <= n) : (j += 1) prev[j] = j;954 var i: usize = 1;955 while (i <= a.len) : (i += 1) {956 curr[0] = i;957 j = 1;958 while (j <= n) : (j += 1) {959 const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;960 curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));961 }962 @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);963 }964 return prev[n];965}966967test "editDistance is case-insensitive Levenshtein" {968 try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));969 try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));970 try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));971 try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));972}973974975976977978fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {979 output.installSelectPrompt(npkg.pname, npkg.version);980981 var choice_buf: [8]u8 = undefined;982 var choice_len: usize = 0;983 while (choice_len < choice_buf.len) {984 const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;985 if (n == 0) break;986 if (choice_buf[choice_len] == '\n') break;987 choice_len += 1;988 }989 const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");990991 if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {992 try profileInstallPkg(ctx, npkg);993 } else if (choice[0] == 's' or choice[0] == 'S') {994 try systemInstallPkg(ctx, npkg);995 } else if (choice[0] == 't' or choice[0] == 'T') {996 try tryPkg(ctx, npkg);997 }998}9991000fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1001 output.installStart(npkg.pname, .profile);1002 output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});1003 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));1004 const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);1005 if (code != 0) return error.ProcessFailed;1006 output.installDone(npkg.pname);1007}10081009fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {1010 const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});1011 defer ctx.gpa.free(config_path);1012 const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;1013 output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);1014 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);1015 if (ctx.cfg.confirm) {1016 if (output.confirm("apply now? ")) {1017 try apply(ctx);1018 }1019 }1020}10211022fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {1023 output.tryStart(npkg.pname);1024 output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});1025 output.tryExitHint();1026 _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);1027 output.tryDone();1028}10291030pub fn remove(ctx: Ctx) !void {1031 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1032 output.removeStart(pkg_name);1033 const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);1034 if (code != 0) return error.ProcessFailed;1035 output.done();1036}10371038pub fn list(ctx: Ctx) !void {1039 output.listHeader(ctx.machine.name);10401041 1042 1043 1044 if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {1045 defer ctx.gpa.free(json);1046 output.listSection("profile");1047 renderProfileJson(ctx.gpa, json);1048 }10491050 1051 1052 if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {1053 defer ctx.gpa.free(paths);1054 output.blankLine();1055 output.listSection("system");1056 var lines = std.mem.splitScalar(u8, paths, '\n');1057 while (lines.next()) |line| {1058 const t = std.mem.trim(u8, line, " \t\r");1059 if (t.len == 0) continue;1060 const row = pkgFromStorePath(t);1061 1062 if (row.version.len == 0) continue;1063 output.listPkg(row.name, row.version);1064 }1065 }1066}10671068const PkgRow = struct { name: []const u8, version: []const u8 };106910701071107210731074fn pkgFromStorePath(path: []const u8) PkgRow {1075 const base = std.fs.path.basename(path);1076 const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;1077 var i: usize = 0;1078 while (i + 1 < after_hash.len) : (i += 1) {1079 if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {1080 return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };1081 }1082 }1083 return .{ .name = after_hash, .version = "" };1084}10851086108710881089fn stripOutputSuffix(ver: []const u8) []const u8 {1090 const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };1091 for (suffixes) |s| {1092 if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];1093 }1094 return ver;1095}10961097test "pkgFromStorePath splits name and version at first dash-digit" {1098 const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");1099 try std.testing.expectEqualStrings("ripgrep", a.name);1100 try std.testing.expectEqualStrings("15.1.0", a.version);11011102 const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");1103 try std.testing.expectEqualStrings("helix", b.name);1104 try std.testing.expectEqualStrings("25.01", b.version);11051106 1107 const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");1108 try std.testing.expectEqualStrings("curl", c.name);1109 try std.testing.expectEqualStrings("8.20.0", c.version);1110}11111112fn firstStorePath(el: std.json.Value) ?[]const u8 {1113 if (el != .object) return null;1114 const sp = el.object.get("storePaths") orelse return null;1115 if (sp != .array or sp.array.items.len == 0) return null;1116 const first = sp.array.items[0];1117 return if (first == .string) first.string else null;1118}1119112011211122fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {1123 const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;1124 defer parsed.deinit();1125 if (parsed.value != .object) return;1126 const elements = parsed.value.object.get("elements") orelse return;1127 switch (elements) {1128 .object => |obj| {1129 var it = obj.iterator();1130 while (it.next()) |entry| {1131 const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";1132 output.listPkg(entry.key_ptr.*, ver);1133 }1134 },1135 .array => |arr| {1136 for (arr.items) |el| {1137 const path = firstStorePath(el) orelse continue;1138 const row = pkgFromStorePath(path);1139 output.listPkg(row.name, row.version);1140 }1141 },1142 else => {},1143 }1144}11451146pub fn tryCmd(ctx: Ctx) !void {1147 const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1148 const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };1149 try tryPkg(ctx, shell_pkg);1150}1151115211531154const home_help = [_][2][]const u8{1155 .{ "apply", "apply home-manager configuration" },1156 .{ "apply --dry", "preview changes without activating" },1157 .{ "back", "roll back one generation" },1158 .{ "history", "list all generations" },1159 .{ "edit", "open home.nix" },1160 .{ "check", "validate without applying" },1161 .{ "diff", "compare the latest two generations" },1162 .{ "packages", "list managed packages" },1163};11641165const HomeGen = struct {1166 number: u32,1167 date: []const u8,1168 time: []const u8,1169 path: []const u8,1170};11711172117311741175fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1176 var gens: std.ArrayList(HomeGen) = .empty;1177 var lines = std.mem.splitScalar(u8, out_str, '\n');1178 while (lines.next()) |line| {1179 const t = std.mem.trim(u8, line, " \t\r");1180 if (t.len == 0) continue;1181 var it = std.mem.tokenizeAny(u8, t, " \t");1182 const date = it.next() orelse continue;1183 const time = it.next() orelse continue;1184 var number: ?u32 = null;1185 var path: []const u8 = "";1186 while (it.next()) |tok| {1187 if (std.mem.eql(u8, tok, "id")) {1188 if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1189 } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1190 path = tok;1191 }1192 }1193 const num = number orelse continue;1194 try gens.append(gpa, .{1195 .number = num,1196 .date = try gpa.dupe(u8, date),1197 .time = try gpa.dupe(u8, time),1198 .path = try gpa.dupe(u8, path),1199 });1200 }1201 return gens.toOwnedSlice(gpa);1202}12031204fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1205 for (gens) |g| {1206 gpa.free(g.date);1207 gpa.free(g.time);1208 gpa.free(g.path);1209 }1210 gpa.free(gens);1211}12121213test "parseHomeGenerations reads id, date and store path" {1214 const a = std.testing.allocator;1215 const sample =1216 \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1217 \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1218 ;1219 const gens = try parseHomeGenerations(a, sample);1220 defer freeHomeGens(a, gens);1221 try std.testing.expectEqual(@as(usize, 2), gens.len);1222 try std.testing.expectEqual(@as(u32, 765), gens[0].number);1223 try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1224 try std.testing.expectEqualStrings("11:56", gens[0].time);1225 try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1226 try std.testing.expectEqual(@as(u32, 764), gens[1].number);1227}122812291230fn homeCurrentGen(ctx: Ctx) u32 {1231 const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1232 defer ctx.gpa.free(out);1233 const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1234 defer freeHomeGens(ctx.gpa, gens);1235 return if (gens.len > 0) gens[0].number else 0;1236}12371238pub fn home(ctx: Ctx) !void {1239 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1240 return output.subcommandHelp("home", &home_help, null);12411242 1243 1244 1245 1246 1247 if (!ctx.machine.local) {1248 output.homeLocalOnly(ctx.machine.name);1249 return;1250 }12511252 const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1253 if (mode == .none) {1254 output.homeNotInstalled();1255 return;1256 }12571258 1259 1260 if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1261 1262 if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);12631264 if (mode == .module) {1265 output.homeModuleManaged();1266 return;1267 }12681269 if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1270 if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1271 if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1272 if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1273 if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);12741275 return output.subcommandHelp("home", &home_help, null);1276}12771278fn homePackages(ctx: Ctx) !void {1279 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1280 defer ctx.gpa.free(out);1281 const gens = try parseHomeGenerations(ctx.gpa, out);1282 defer freeHomeGens(ctx.gpa, gens);12831284 output.homePackagesHeader(ctx.machine.name);1285 if (gens.len == 0 or gens[0].path.len == 0) return;12861287 1288 1289 1290 1291 1292 const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1293 defer ctx.gpa.free(gen_refs);12941295 var refs = gen_refs;1296 var env_refs: ?[]u8 = null;1297 defer if (env_refs) |e| ctx.gpa.free(e);1298 if (findHomeManagerPath(gen_refs)) |pkg_path| {1299 if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1300 env_refs = e;1301 refs = e;1302 } else |_| {}1303 }13041305 1306 1307 1308 var seen = std.StringHashMap(void).init(ctx.gpa);1309 defer seen.deinit();1310 var lines = std.mem.splitScalar(u8, refs, '\n');1311 while (lines.next()) |line| {1312 const t = std.mem.trim(u8, line, " \t\r");1313 if (t.len == 0) continue;1314 const row = pkgFromStorePath(t);1315 if (row.version.len == 0) continue;1316 if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1317 if (seen.contains(row.name)) continue;1318 seen.put(row.name, {}) catch {};1319 output.listPkg(row.name, row.version);1320 }1321}1322132313241325fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1326 var lines = std.mem.splitScalar(u8, refs, '\n');1327 while (lines.next()) |line| {1328 const t = std.mem.trim(u8, line, " \t\r");1329 if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1330 }1331 return null;1332}13331334test "findHomeManagerPath picks the env, not the generation or infra" {1335 const refs =1336 \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31337 \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1338 \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111339 ;1340 try std.testing.expectEqualStrings(1341 "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1342 findHomeManagerPath(refs).?,1343 );1344 try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1345}13461347fn homeDiff(ctx: Ctx) !void {1348 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1349 defer ctx.gpa.free(out);1350 const gens = try parseHomeGenerations(ctx.gpa, out);1351 defer freeHomeGens(ctx.gpa, gens);13521353 1354 if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1355 output.homeNothingToDiff();1356 return;1357 }1358 const newer = gens[0];1359 const older = gens[1];1360 output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1361 if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1362 return error.ProcessFailed;1363}13641365fn homeCheck(ctx: Ctx) !void {1366 output.homeCheckStart(ctx.machine.name);1367 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1368 if (code != 0) return error.BuildFailed;1369 output.homeCheckOk();1370}13711372fn homeEdit(ctx: Ctx) !void {1373 1374 1375 const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1376 errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1377 return error.ConfigNotFound;1378 };1379 defer ctx.gpa.free(path);1380 output.homeEditOpen(path, ctx.cfg.editor);1381 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1382}13831384fn homeHistory(ctx: Ctx) !void {1385 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1386 defer ctx.gpa.free(out);1387 const gens = try parseHomeGenerations(ctx.gpa, out);1388 defer freeHomeGens(ctx.gpa, gens);1389 output.homeHistoryHeader(ctx.machine.name);1390 1391 for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1392}13931394fn homeBack(ctx: Ctx) !void {1395 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1396 defer ctx.gpa.free(out);1397 const gens = try parseHomeGenerations(ctx.gpa, out);1398 defer freeHomeGens(ctx.gpa, gens);13991400 1401 if (gens.len < 2) {1402 output.alreadyOldest();1403 return;1404 }1405 const current = gens[0].number;1406 const prev = gens[1].number;14071408 output.homeBackStart(ctx.machine.name, current, prev);1409 if (ctx.cfg.confirm and !output.confirm("")) return;1410 const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1411 if (code != 0) return error.BuildFailed;1412 output.homeBackDone(prev);1413}14141415fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1416 1417 if (mode == .module) {1418 output.homeModuleManaged();1419 return;1420 }1421 if (ctx.dry) {1422 output.homeApplyDry(ctx.machine.name);1423 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1424 if (code != 0) return error.BuildFailed;1425 output.homeApplyDryDone();1426 return;1427 }14281429 if (!try runPreHook(ctx, "pre-home")) {1430 output.aborted();1431 return error.HookAborted;1432 }14331434 output.homeApplyStart(ctx.machine.name);1435 const flake_ref = exec.homeFlakeRef(ctx.gpa, ctx.io, ctx.environ);1436 defer if (flake_ref) |r| ctx.gpa.free(r);1437 if (flake_ref) |ref| {1438 output.printSubstep("home-manager switch --flake {s}", .{ref});1439 } else {1440 output.printSubstep("home-manager switch", .{});1441 }14421443 const start = std.Io.Clock.awake.now(ctx.io);1444 const code = if (flake_ref) |ref|1445 try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)1446 else1447 try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1448 if (code != 0) return error.BuildFailed;14491450 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1451 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1452 output.homeApplyDone(homeCurrentGen(ctx), elapsed);1453 runPostHook(ctx, "post-home");1454}1455145614571458const service_help = [_][2][]const u8{1459 .{ "list", "list running services" },1460 .{ "logs <svc>", "show service logs" },1461 .{ "status <svc>", "service status" },1462 .{ "start <svc>", "start a service" },1463 .{ "stop <svc>", "stop a service" },1464 .{ "restart <svc>", "restart a service" },1465 .{ "enable <svc>", "enable at boot" },1466 .{ "disable <svc>", "disable at boot" },1467};14681469pub fn service(ctx: Ctx) !void {1470 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");1471 if (std.mem.eql(u8, ctx.sub, "list")) {1472 output.serviceListHeader(ctx.machine.name);1473 const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1474 defer ctx.gpa.free(svcs);1475 for (svcs) |s| output.serviceRow(s);1476 return;1477 }1478 if (std.mem.eql(u8, ctx.sub, "logs")) {1479 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1480 const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1481 output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1482 _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1483 return;1484 }1485 if (std.mem.eql(u8, ctx.sub, "status")) {1486 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1487 output.serviceVerb("status", name, ctx.machine.name);1488 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1489 return;1490 }1491 1492 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1493 if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1494 if (!output.confirm("")) return;1495 }1496 output.serviceVerb(ctx.sub, name, ctx.machine.name);1497 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1498 output.serviceDone();1499}1500150115021503const flake_help = [_][2][]const u8{1504 .{ "init", "create a new flake.nix" },1505 .{ "update", "update flake inputs" },1506 .{ "update <in>", "update a specific input" },1507 .{ "check", "validate the flake" },1508 .{ "show", "inspect flake outputs" },1509 .{ "lock", "regenerate flake.lock" },1510 .{ "clone <url>", "clone a flake repository" },1511};15121513pub fn flake(ctx: Ctx) !void {1514 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1515 if (std.mem.eql(u8, ctx.sub, "update")) {1516 output.flakeUpdateStart();1517 const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1518 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1519 output.flakeLockWritten();1520 return;1521 }1522 if (std.mem.eql(u8, ctx.sub, "check")) {1523 output.flakeCheckStart();1524 const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1525 if (code == 0) output.flakeValid() else output.checkFailed("");1526 return;1527 }1528 if (std.mem.eql(u8, ctx.sub, "show")) {1529 const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1530 if (json_out) |j| {1531 defer ctx.gpa.free(j);1532 output.flakeShowHeader("flake outputs");1533 1534 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1535 defer parsed.deinit();1536 if (parsed.value == .object) {1537 var it = parsed.value.object.iterator();1538 while (it.next()) |entry| {1539 if (entry.value_ptr.* == .object) {1540 var inner = entry.value_ptr.object.iterator();1541 while (inner.next()) |e2| {1542 const desc = if (e2.value_ptr.* == .object)1543 if (e2.value_ptr.object.get("description")) |d|1544 if (d == .string) d.string else ""1545 else1546 ""1547 else1548 "";1549 output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1550 }1551 }1552 }1553 }1554 }1555 return;1556 }1557 if (std.mem.eql(u8, ctx.sub, "init")) {1558 _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1559 return;1560 }1561 if (std.mem.eql(u8, ctx.sub, "lock")) {1562 _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1563 return;1564 }1565 if (std.mem.eql(u8, ctx.sub, "clone")) {1566 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1567 _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1568 return;1569 }1570}1571157215731574const store_help = [_][2][]const u8{1575 .{ "info", "store size and counts" },1576 .{ "path <attr>", "store path of a package" },1577 .{ "gc", "collect garbage" },1578 .{ "verify", "verify store integrity" },1579 .{ "repair", "repair corrupted paths" },1580};15811582pub fn store(ctx: Ctx) !void {1583 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1584 if (std.mem.eql(u8, ctx.sub, "gc")) {1585 _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1586 return;1587 }1588 if (std.mem.eql(u8, ctx.sub, "verify")) {1589 output.storeVerifyStart();1590 _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1591 return;1592 }1593 if (std.mem.eql(u8, ctx.sub, "repair")) {1594 if (ctx.cfg.confirm and !output.confirm("")) return;1595 output.storeRepairStart();1596 _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1597 return;1598 }1599 if (std.mem.eql(u8, ctx.sub, "info")) {1600 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1601 output.storeInfo(si);1602 return;1603 }1604 if (std.mem.eql(u8, ctx.sub, "path")) {1605 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1606 const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1607 defer ctx.gpa.free(path);1608 output.storePath(path);1609 return;1610 }1611 1612 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1613 output.storeInfo(si);1614}1615161616171618const channel_help = [_][2][]const u8{1619 .{ "list", "list channels" },1620 .{ "add <url> [name]", "add a channel" },1621 .{ "remove <name>", "remove a channel" },1622 .{ "update", "update all channels" },1623};16241625pub fn channel(ctx: Ctx) !void {1626 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1627 1628 if (flakeSystem(ctx)) output.flakeChannelNote();1629 if (std.mem.eql(u8, ctx.sub, "list")) {1630 output.channelListHeader(ctx.machine.name);1631 const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1632 defer ctx.gpa.free(chans);1633 for (chans) |ch| output.channelRow(ch);1634 return;1635 }1636 if (std.mem.eql(u8, ctx.sub, "add")) {1637 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1638 const name = if (ctx.args.len > 1) ctx.args[1] else "";1639 _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1640 output.channelDone();1641 return;1642 }1643 if (std.mem.eql(u8, ctx.sub, "remove")) {1644 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1645 _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1646 output.channelDone();1647 return;1648 }1649 if (std.mem.eql(u8, ctx.sub, "update")) {1650 return channelUpdateCmd(ctx);1651 }1652}1653165416551656pub fn profile(ctx: Ctx) !void {1657 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1658 output.profileListHeader();1659 const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1660 if (out) |o| {1661 defer ctx.gpa.free(o);1662 var lines = std.mem.splitScalar(u8, o, '\n');1663 while (lines.next()) |line| {1664 const t = std.mem.trim(u8, line, " \t\r");1665 if (t.len == 0) continue;1666 output.profileRow(t, "", "");1667 }1668 }1669 return;1670 }1671 if (std.mem.eql(u8, ctx.sub, "install")) {1672 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1673 _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1674 output.done();1675 return;1676 }1677 if (std.mem.eql(u8, ctx.sub, "remove")) {1678 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1679 _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1680 output.done();1681 return;1682 }1683 if (std.mem.eql(u8, ctx.sub, "upgrade")) {1684 _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1685 output.done();1686 return;1687 }1688}1689169016911692const pkg_help = [_][2][]const u8{1693 .{ "why <pkg>", "what pulled it in" },1694 .{ "deps <pkg>", "direct dependencies" },1695 .{ "size <pkg>", "closure size" },1696 .{ "path <pkg>", "store path" },1697 .{ "closure <pkg>", "full closure" },1698};16991700pub fn pkg(ctx: Ctx) !void {1701 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1702 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1703 if (std.mem.eql(u8, ctx.sub, "why")) {1704 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1705 return;1706 }1707 if (std.mem.eql(u8, ctx.sub, "deps")) {1708 if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1709 return;1710 }1711 if (std.mem.eql(u8, ctx.sub, "size")) {1712 const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1713 defer ctx.gpa.free(s);1714 output.pkgResult("size", s);1715 return;1716 }1717 if (std.mem.eql(u8, ctx.sub, "path")) {1718 const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1719 defer ctx.gpa.free(p);1720 output.pkgResult("path", p);1721 return;1722 }1723 if (std.mem.eql(u8, ctx.sub, "closure")) {1724 if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1725 return;1726 }1727}1728172917301731pub fn why(ctx: Ctx) !void {1732 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1733 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1734}1735173617371738pub fn pin(ctx: Ctx) !void {1739 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1740 const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1741 exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1742 output.pinDone(input, commit);1743}17441745pub fn unpin(ctx: Ctx) !void {1746 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1747 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1748 output.unpinDone(input);1749}1750175117521753pub fn hash(ctx: Ctx) !void {1754 const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1755 const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1756 defer ctx.gpa.free(h);1757 output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1758}17591760pub fn fetch(ctx: Ctx) !void {1761 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1762 const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1763 defer ctx.gpa.free(h);1764 output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1765}1766176717681769pub fn build(ctx: Ctx) !void {1770 const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1771 output.buildStart(attr orelse "default");1772 const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1773 if (code != 0) return error.BuildFailed;1774 output.buildDone();1775}17761777pub fn runCmd(ctx: Ctx) !void {1778 const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1779 output.runStart(pkg_arg);1780 _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1781}1782178317841785pub fn hello(ctx: Ctx) !void {1786 output.hello(ctx.cfg.machines);1787}17881789const ConfigKind = enum { flake, channel, none };1790179117921793fn scanConfig(io: std.Io) ConfigKind {1794 if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1795 if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1796 return .none;1797}17981799180018011802pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1803 output.firstRunBanner();1804 output.firstRunNoConfig();18051806 var name_buf: [256]u8 = undefined;1807 var path_buf: [256]u8 = undefined;18081809 const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);18101811 output.firstRunScanning();1812 const kind = scanConfig(io);1813 switch (kind) {1814 .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),1815 .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),1816 .none => output.firstRunNoneFound(),1817 }18181819 1820 1821 const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";1822 const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);18231824 1825 1826 const use_flakes = exec.dirHasFlake(gpa, io, config_path);18271828 const conf_path = try config.configPath(gpa, environ);1829 defer gpa.free(conf_path);1830 if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);18311832 1833 const flake_line = if (use_flakes) "flake = true\n" else "";1834 var content_buf: [1024]u8 = undefined;1835 const content = try std.fmt.bufPrint(1836 &content_buf,1837 "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",1838 .{ flake_line, machine_name, config_path },1839 );18401841 const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1842 errors.error_info.setMessage("could not write {s}", .{conf_path});1843 return error.Internal;1844 };1845 defer file.close(io);1846 file.writePositionalAll(io, content, 0) catch {1847 errors.error_info.setMessage("could not write {s}", .{conf_path});1848 return error.Internal;1849 };18501851 output.firstRunWritten(conf_path);1852}18531854pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1855 1856 1857 1858 config.migrateLegacyConfig(gpa, io, environ);1859 if (config.configPath(gpa, environ)) |conf_path| {1860 defer gpa.free(conf_path);1861 if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1862 f.close(io);1863 } else |_| {1864 try firstRunWizard(gpa, io, environ);1865 errors.error_info.reset();1866 }1867 } else |_| {}18681869 output.setupCheck();1870 const status = exec.checkNixFeatures(gpa, io, environ);1871 output.setupFeatures(status.nix_command, status.flakes);18721873 if (status.allEnabled()) {1874 output.setupAllSet();1875 api.ensureRegistryPinned(gpa, io, environ);1876 return;1877 }18781879 1880 1881 1882 1883 if (exec.isNixOS(io)) {1884 const conf_path = "/etc/nixos/configuration.nix";1885 if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1886 output.setupNixosNeedsRebuild(conf_path);1887 return;1888 }1889 output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1890 if (output.confirmDefaultNo("add it now?")) {1891 if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1892 output.setupNixosWrote(conf_path);1893 } else |_| {1894 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1895 }1896 } else {1897 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1898 }1899 return;1900 }19011902 1903 output.setupEnabling();1904 const path = try exec.enableNixFeatures(gpa, io, environ);1905 defer gpa.free(path);19061907 output.setupDone(path);1908 api.ensureRegistryPinned(gpa, io, environ);1909}1910191119121913fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1914 var ts_buf: [32]u8 = undefined;1915 const ts = nowIso(ctx.io, &ts_buf);1916 var buf: [256]u8 = undefined;1917 const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1918 ts, ctx.machine.name, action, gen,1919 }) catch return;1920 exec.appendNinaLog(ctx.io, ctx.environ, entry);1921}1922192319241925fn nowIso(io: std.Io, buf: []u8) []const u8 {1926 const fallback = "1970-01-01T00:00:00Z";1927 const ns = std.Io.Clock.real.now(io).toNanoseconds();1928 if (ns <= 0) return fallback;1929 const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1930 const es = std.time.epoch.EpochSeconds{ .secs = secs };1931 const ed = es.getEpochDay();1932 const yd = ed.calculateYearDay();1933 const md = yd.calculateMonthDay();1934 const ds = es.getDaySeconds();1935 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", .{1936 yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1937 ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1938 }) catch return fallback;1939}