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";1516pub const Ctx = struct {17 gpa: std.mem.Allocator,18 io: std.Io,19 environ: *const std.process.Environ.Map,20 machine: types.Machine,21 cfg: types.NinaConfig,22 args: []const []const u8, 23 sub: []const u8, 24 dry: bool,25 check: bool,26 no_apply: bool,27 all: bool,28 last: u32,29 json: bool,30};3132pub fn apply(ctx: Ctx) !void {33 if (ctx.dry) {34 output.applyDry(ctx.machine.name);35 const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);36 if (code != 0) return error.BuildFailed;37 output.applyDryDone();38 return;39 }40 if (ctx.check) {41 return check(ctx);42 }4344 output.applyStart(ctx.machine.name);45 const start = std.Io.Clock.awake.now(ctx.io);4647 const code = exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa) catch |e| {48 exec.markApplyFailed(ctx.io, ctx.environ);49 output.applyFailed("");50 return e;51 };5253 if (code != 0) {54 exec.markApplyFailed(ctx.io, ctx.environ);55 output.applyFailed("");56 return error.BuildFailed;57 }5859 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());60 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));61 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;62 const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);63 output.applyDone(gen, elapsed, after_failure);64 logAction(ctx, "apply", gen);65}6667pub fn check(ctx: Ctx) !void {68 output.checkStart(ctx.machine.name);69 const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);70 if (code != 0) {71 output.checkFailed("");72 return error.BuildFailed;73 }74 output.checkOk();75}7677pub fn back(ctx: Ctx) !void {78 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);79 defer ctx.gpa.free(gens);8081 var current: u32 = 0;82 for (gens) |g| if (g.current) { current = g.number; };8384 85 86 var prev: u32 = 0;87 var has_prev = false;88 for (gens) |g| {89 if (g.number < current and (!has_prev or g.number > prev)) {90 prev = g.number;91 has_prev = true;92 }93 }94 if (!has_prev) {95 output.alreadyOldest();96 return;97 }9899 output.backStart(ctx.machine.name, current, prev);100 if (ctx.cfg.confirm and !output.confirm("")) return;101102 const code = try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);103 if (code != 0) return error.BuildFailed;104 output.backDone(prev);105}106107pub fn go(ctx: Ctx) !void {108 if (ctx.args.len == 0) return error.Internal;109 const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;110 const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);111112 output.goStart(ctx.machine.name, current, target);113 if (ctx.cfg.confirm and !output.confirm("")) return;114115 const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);116 if (code != 0) return error.ProcessFailed;117 output.generationDone(target);118}119120pub fn history(ctx: Ctx) !void {121 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);122 defer ctx.gpa.free(gens);123 output.historyHeader(ctx.machine.name);124 for (gens) |g| output.historyRow(g);125}126127const gen_help = [_][2][]const u8{128 .{ "list", "list generations" },129 .{ "current", "show current generation" },130 .{ "delete <n>", "delete generation n" },131 .{ "delete old", "delete old generations" },132};133134pub fn genCmd(ctx: Ctx) !void {135 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("gen", &gen_help);136 if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);137 if (std.mem.eql(u8, ctx.sub, "current")) {138 const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);139 output.genCurrent(n);140 return;141 }142 if (std.mem.eql(u8, ctx.sub, "delete")) {143 if (ctx.args.len == 0) return error.Internal;144 if (std.mem.eql(u8, ctx.args[0], "old")) {145 if (ctx.cfg.confirm and !output.confirm("")) return;146 _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);147 } else {148 const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;149 if (ctx.cfg.confirm and !output.confirm("")) return;150 _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);151 }152 output.done();153 return;154 }155 return error.Internal;156}157158pub fn clean(ctx: Ctx) !void {159 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);160 defer ctx.gpa.free(gens);161 const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");162 const total: u32 = @intCast(gens.len);163 164 165 const keep: u32 = if (all) 1 else ctx.cfg.generations;166 if (total <= keep) {167 output.cleanNothing(ctx.machine.name, total);168 return;169 }170 output.cleanStart(ctx.machine.name, keep, total);171 if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;172 _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);173 output.cleanDone();174}175176pub fn statusCmd(ctx: Ctx) !void {177 output.statusHeader();178 179 180 if (ctx.all and ctx.cfg.machines.len > 0) {181 for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);182 return;183 }184 statusRowFor(ctx, &ctx.machine);185}186187fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {188 189 190 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {191 output.statusRow(machine.name, 0, "", "", false);192 return;193 };194 const st = exec.systemStatus(ctx.gpa, ctx.io, machine);195 defer ctx.gpa.free(st.size);196 defer ctx.gpa.free(st.age);197 output.statusRow(machine.name, gen, st.age, st.size, true);198}199200pub fn diff(ctx: Ctx) !void {201 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);202 defer ctx.gpa.free(gens);203 var current: u32 = 0;204 var prev: u32 = 0;205 for (gens) |g| {206 if (g.current) current = g.number;207 if (!g.current and g.number > prev and g.number < current) prev = g.number;208 }209 if (ctx.args.len >= 2) {210 const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;211 const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;212 output.diffHeader(a, b, ctx.machine.name);213 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;214 } else {215 output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);216 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;217 }218}219220pub fn mood(ctx: Ctx) !void {221 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;222 const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);223 defer ctx.gpa.free(st.size);224 defer ctx.gpa.free(st.age);225 const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");226 defer ctx.gpa.free(state);227 output.mood(ctx.machine.name, state, gen, st.age, st.size);228}229230pub fn doctor(ctx: Ctx) !void {231 output.doctorHeader(ctx.machine.name);232 const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);233 defer ctx.gpa.free(checks);234 var warnings: u32 = 0;235 var failures: u32 = 0;236 for (checks) |ch| {237 output.doctorRow(ch);238 if (ch.status == .warn) warnings += 1;239 if (ch.status == .fail) failures += 1;240 }241 output.doctorSummary(warnings, failures);242}243244245pub fn update(ctx: Ctx) !void {246 output.updateSelfStart();247248 if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {249 output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));250 return error.Internal;251 }252253 const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");254 const source_url = env_url orelse UPDATE_URL;255256 const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {257 error.NetworkError, error.HttpError => {258 output.updateSelfNetworkError();259 return;260 },261 else => return e,262 };263 defer ctx.gpa.free(body);264265 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {266 output.printWarning("could not parse release metadata");267 return;268 };269 defer parsed.deinit();270271 const root = parsed.value;272 if (root != .object) { output.printWarning("malformed release metadata"); return; }273274 const remote_ver = blk: {275 const v = root.object.get("version") orelse { output.printWarning("malformed release metadata"); return; };276 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };277 };278279 if (std.mem.eql(u8, remote_ver, version.VERSION)) {280 output.updateSelfCurrent(version.VERSION);281 return;282 }283284 output.updateSelfAvailable(version.VERSION, remote_ver);285 if (ctx.check) return;286287 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;288 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {289 errors.error_info.setMessage("could not determine install path", .{});290 return error.Internal;291 };292293 294 295 296 297 298 if (std.mem.startsWith(u8, install_path, "/nix/store/")) {299 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);300 defer {301 if (nina_element) |n| ctx.gpa.free(n);302 }303 if (nina_element == null) {304 output.updateSelfNotInProfile();305 return;306 }307 const element = nina_element.?;308 output.updateSelfNixManaged(remote_ver);309 if (ctx.cfg.confirm and !output.confirm("")) return;310 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", element }) catch {311 output.updateSelfNixFailed();312 return;313 };314 if (ec != 0) output.updateSelfNixFailed();315 return;316 }317318 const plat_info = blk: {319 const pv = root.object.get("platforms") orelse break :blk null;320 if (pv != .object) break :blk null;321 break :blk pv.object.get(version.PLATFORM);322 };323 if (plat_info == null) { output.updateSelfNoPlatform(version.PLATFORM); return; }324325 const dl_url = blk: {326 const v = plat_info.?.object.get("url") orelse { output.printWarning("malformed release metadata"); return; };327 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };328 };329330 const raw_cksum = blk: {331 if (plat_info.?.object.get("blake3")) |v|332 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };333 if (plat_info.?.object.get("checksum")) |v|334 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };335 output.printWarning("missing checksum in release metadata");336 return;337 };338 const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;339340 if (ctx.cfg.confirm and !output.confirm("")) return;341342 output.updateSelfDownloading(remote_ver, version.PLATFORM);343 const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {344 output.printWarning("download failed — check your connection and try again");345 return;346 };347 defer ctx.gpa.free(tmp_path);348349 output.updateSelfVerifying();350 exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {351 error.ChecksumMismatch => { output.updateSelfChecksumFailed(); return; },352 else => return e,353 };354355 output.updateSelfDone(version.VERSION, remote_ver);356}357358359360361pub fn goodbye(ctx: Ctx) !void {362 output.goodbyeStart();363364 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;365 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {366 errors.error_info.setMessage("could not determine install path", .{});367 return error.Internal;368 };369370 371 if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {372 output.goodbyeFile(install_path);373 if (ctx.cfg.confirm and !output.confirm("")) return;374 std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {375 errors.error_info.setMessage("could not remove {s}", .{install_path});376 return e;377 };378 output.goodbyeDone();379 return;380 }381382 383 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);384 defer {385 if (nina_element) |n| ctx.gpa.free(n);386 }387388 if (nina_element == null) {389 errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});390 return error.Internal;391 }392393 output.goodbyeNix();394 if (ctx.cfg.confirm and !output.confirm("")) return;395 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {396 output.goodbyeFailed("nix profile remove failed");397 return;398 };399 if (ec != 0) {400 output.goodbyeFailed("nix profile remove failed");401 return;402 }403 output.goodbyeDone();404}405406fn channelUpdateCmd(ctx: Ctx) !void {407 output.updateStart(ctx.machine.name);408 _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);409 output.updateDone();410}411412pub fn upgrade(ctx: Ctx) !void {413 output.upgradeStart(ctx.machine.name);414 output.printSubstep("updating channels", .{});415 _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};416 output.printSubstep("rebuilding", .{});417 const start = std.Io.Clock.awake.now(ctx.io);418 const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);419 if (code != 0) {420 output.applyFailed("");421 return error.BuildFailed;422 }423 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());424 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));425 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;426 output.applyDone(gen, elapsed, false);427}428429pub fn log(ctx: Ctx) !void {430 output.logHeader(ctx.machine.name);431 const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {432 433 return;434 };435 defer ctx.gpa.free(content);436 var lines = std.mem.splitScalar(u8, content, '\n');437 while (lines.next()) |line| {438 const t = std.mem.trim(u8, line, " \t\r");439 if (t.len == 0) continue;440 if (t[0] == '{') {441 renderJsonLogLine(ctx.gpa, t);442 } else {443 444 var parts = std.mem.tokenizeScalar(u8, t, '\t');445 const date = parts.next() orelse continue;446 const time = parts.next() orelse "";447 const action = parts.next() orelse "";448 const detail = parts.next() orelse "";449 output.logRow(date, time, action, detail);450 }451 }452}453454455456fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {457 const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {458 output.logRow(line, "", "", ""); 459 return;460 };461 defer parsed.deinit();462 if (parsed.value != .object) return;463 const o = parsed.value.object;464465 const ts = jsonStr(o, "ts");466 const date = if (ts.len >= 10) ts[0..10] else ts;467 const time = if (ts.len >= 16) ts[11..16] else "";468 const action = jsonStr(o, "command");469 const outcome = jsonStr(o, "outcome");470471 var buf: [160]u8 = undefined;472 var detail: []const u8 = outcome;473 if (o.get("gen_after")) |g| {474 if (g == .integer) {475 detail = std.fmt.bufPrint(&buf, "{s} -> gen {d}", .{ outcome, g.integer }) catch outcome;476 }477 }478 output.logRow(date, time, action, detail);479}480481fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {482 if (o.get(key)) |v| {483 if (v == .string) return v.string;484 }485 return "";486}487488pub fn edit(ctx: Ctx) !void {489 const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");490 const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";491 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });492 defer ctx.gpa.free(path);493 output.editOpen(path, ctx.cfg.editor);494 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);495}496497pub fn fmt(ctx: Ctx) !void {498 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});499 defer ctx.gpa.free(path);500 if (ctx.check) {501 const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);502 if (code != 0) output.fmtNeedsFormat() else output.fmtDone();503 return;504 }505 output.fmtStart(path);506 _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);507 output.fmtDone();508}509510pub fn repl(ctx: Ctx) !void {511 output.replStart();512 _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);513}514515pub fn develop(ctx: Ctx) !void {516 if (std.mem.eql(u8, ctx.sub, "show")) {517 _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);518 return;519 }520 const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))521 ctx.args[0]522 else523 null;524 output.developStart(&.{});525 _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);526 output.developDone();527}528529pub fn info(ctx: Ctx) !void {530 output.infoHeader(ctx.machine.name);531 const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");532 defer ctx.gpa.free(nixos_ver);533 output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));534535 const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");536 defer ctx.gpa.free(kernel);537 output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));538539 const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");540 defer ctx.gpa.free(uptime);541 output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));542}543544pub fn boot(ctx: Ctx) !void {545 output.bootHeader(ctx.machine.name);546 const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};547 defer ctx.gpa.free(entries);548 for (entries, 0..) |entry, i| output.bootEntry(entry, i);549}550551pub fn searchCmd(ctx: Ctx) !void {552 const query = if (ctx.args.len > 0) ctx.args[0] else "";553 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);554 const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);555 if (selected) |npkg| try selectAndInstall(ctx, npkg);556}557558pub fn optionCmd(ctx: Ctx) !void {559 const query = if (ctx.args.len > 0) ctx.args[0] else "";560 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);561 _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);562}563564pub fn install(ctx: Ctx) !void {565 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;566567 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);568569 570 const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {571 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});572 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});573 return error.PackageNotFound;574 };575576 if (pkgs.len == 0) {577 578 if (closestPackage(ctx, pkg_name)) |sugg| {579 output.didYouMean(pkg_name, sugg.pname);580 if (output.confirm("")) try selectAndInstall(ctx, sugg);581 return;582 }583 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});584 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});585 return error.PackageNotFound;586 }587588 589 590 var found = pkgs[0];591 for (pkgs) |p| {592 if (std.mem.eql(u8, p.pname, pkg_name)) {593 found = p;594 break;595 }596 }597 try selectAndInstall(ctx, found);598}599600601602603fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {604 if (query.len < 2) return null;605 var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};606 if (candidates.len == 0 and query.len > 2) {607 candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};608 }609 if (candidates.len == 0) return null;610611 var best: ?types.NixPackage = null;612 var best_dist: usize = std.math.maxInt(usize);613 for (candidates) |p| {614 const d = editDistance(query, p.pname);615 if (d > 0 and d < best_dist) {616 best_dist = d;617 best = p;618 }619 }620 621 const threshold = @max(@as(usize, 2), query.len / 3);622 return if (best_dist <= threshold) best else null;623}624625626627fn editDistance(a: []const u8, b: []const u8) usize {628 const n = b.len;629 if (a.len == 0) return n;630 if (n == 0) return a.len;631 if (n + 1 > 128) return std.math.maxInt(usize);632 var prev: [128]usize = undefined;633 var curr: [128]usize = undefined;634 var j: usize = 0;635 while (j <= n) : (j += 1) prev[j] = j;636 var i: usize = 1;637 while (i <= a.len) : (i += 1) {638 curr[0] = i;639 j = 1;640 while (j <= n) : (j += 1) {641 const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;642 curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));643 }644 @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);645 }646 return prev[n];647}648649test "editDistance is case-insensitive Levenshtein" {650 try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));651 try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));652 try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));653 try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));654}655656657658659660fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {661 output.installSelectPrompt(npkg.pname, npkg.version);662663 var choice_buf: [8]u8 = undefined;664 var choice_len: usize = 0;665 while (choice_len < choice_buf.len) {666 const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;667 if (n == 0) break;668 if (choice_buf[choice_len] == '\n') break;669 choice_len += 1;670 }671 const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");672673 if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {674 try profileInstallPkg(ctx, npkg);675 } else if (choice[0] == 's' or choice[0] == 'S') {676 try systemInstallPkg(ctx, npkg);677 } else if (choice[0] == 't' or choice[0] == 'T') {678 try tryPkg(ctx, npkg);679 }680}681682fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {683 output.installStart(npkg.pname, .profile);684 output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});685 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));686 const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);687 if (code != 0) return error.ProcessFailed;688 output.installDone(npkg.pname);689}690691fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {692 const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});693 defer ctx.gpa.free(config_path);694 const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;695 output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);696 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);697 if (ctx.cfg.confirm) {698 if (output.confirm("apply now? ")) {699 try apply(ctx);700 }701 }702}703704fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {705 output.tryStart(npkg.pname);706 output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});707 output.tryExitHint();708 _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);709 output.tryDone();710}711712pub fn remove(ctx: Ctx) !void {713 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;714 output.removeStart(pkg_name);715 const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);716 if (code != 0) return error.ProcessFailed;717 output.done();718}719720pub fn list(ctx: Ctx) !void {721 output.listHeader(ctx.machine.name);722723 724 725 726 if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {727 defer ctx.gpa.free(json);728 output.listSection("profile");729 renderProfileJson(ctx.gpa, json);730 }731732 733 734 if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {735 defer ctx.gpa.free(paths);736 output.blankLine();737 output.listSection("system");738 var lines = std.mem.splitScalar(u8, paths, '\n');739 while (lines.next()) |line| {740 const t = std.mem.trim(u8, line, " \t\r");741 if (t.len == 0) continue;742 const row = pkgFromStorePath(t);743 744 if (row.version.len == 0) continue;745 output.listPkg(row.name, row.version);746 }747 }748}749750const PkgRow = struct { name: []const u8, version: []const u8 };751752753754755756fn pkgFromStorePath(path: []const u8) PkgRow {757 const base = std.fs.path.basename(path);758 const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;759 var i: usize = 0;760 while (i + 1 < after_hash.len) : (i += 1) {761 if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {762 return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };763 }764 }765 return .{ .name = after_hash, .version = "" };766}767768769770771fn stripOutputSuffix(ver: []const u8) []const u8 {772 const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };773 for (suffixes) |s| {774 if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];775 }776 return ver;777}778779test "pkgFromStorePath splits name and version at first dash-digit" {780 const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");781 try std.testing.expectEqualStrings("ripgrep", a.name);782 try std.testing.expectEqualStrings("15.1.0", a.version);783784 const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");785 try std.testing.expectEqualStrings("helix", b.name);786 try std.testing.expectEqualStrings("25.01", b.version);787788 789 const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");790 try std.testing.expectEqualStrings("curl", c.name);791 try std.testing.expectEqualStrings("8.20.0", c.version);792}793794fn firstStorePath(el: std.json.Value) ?[]const u8 {795 if (el != .object) return null;796 const sp = el.object.get("storePaths") orelse return null;797 if (sp != .array or sp.array.items.len == 0) return null;798 const first = sp.array.items[0];799 return if (first == .string) first.string else null;800}801802803804fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {805 const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;806 defer parsed.deinit();807 if (parsed.value != .object) return;808 const elements = parsed.value.object.get("elements") orelse return;809 switch (elements) {810 .object => |obj| {811 var it = obj.iterator();812 while (it.next()) |entry| {813 const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";814 output.listPkg(entry.key_ptr.*, ver);815 }816 },817 .array => |arr| {818 for (arr.items) |el| {819 const path = firstStorePath(el) orelse continue;820 const row = pkgFromStorePath(path);821 output.listPkg(row.name, row.version);822 }823 },824 else => {},825 }826}827828pub fn tryCmd(ctx: Ctx) !void {829 const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;830 const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };831 try tryPkg(ctx, shell_pkg);832}833834835836const service_help = [_][2][]const u8{837 .{ "list", "list running services" },838 .{ "logs <svc>", "show service logs" },839 .{ "status <svc>", "service status" },840 .{ "start <svc>", "start a service" },841 .{ "stop <svc>", "stop a service" },842 .{ "restart <svc>", "restart a service" },843 .{ "enable <svc>", "enable at boot" },844 .{ "disable <svc>", "disable at boot" },845};846847pub fn service(ctx: Ctx) !void {848 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("service", &service_help);849 if (std.mem.eql(u8, ctx.sub, "list")) {850 output.serviceListHeader(ctx.machine.name);851 const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine) catch &.{};852 defer ctx.gpa.free(svcs);853 for (svcs) |s| output.serviceRow(s);854 return;855 }856 if (std.mem.eql(u8, ctx.sub, "logs")) {857 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;858 const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");859 output.serviceLogsHeader(name, ctx.last, ctx.machine.name);860 _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow);861 return;862 }863 if (std.mem.eql(u8, ctx.sub, "status")) {864 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;865 output.serviceVerb("status", name, ctx.machine.name);866 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name);867 return;868 }869 870 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;871 if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {872 if (!output.confirm("")) return;873 }874 output.serviceVerb(ctx.sub, name, ctx.machine.name);875 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name);876 output.serviceDone();877}878879880881const flake_help = [_][2][]const u8{882 .{ "init", "create a new flake.nix" },883 .{ "update", "update flake inputs" },884 .{ "update <in>", "update a specific input" },885 .{ "check", "validate the flake" },886 .{ "show", "inspect flake outputs" },887 .{ "lock", "regenerate flake.lock" },888 .{ "clone <url>", "clone a flake repository" },889};890891pub fn flake(ctx: Ctx) !void {892 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help);893 if (std.mem.eql(u8, ctx.sub, "update")) {894 output.flakeUpdateStart();895 const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;896 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);897 output.flakeLockWritten();898 return;899 }900 if (std.mem.eql(u8, ctx.sub, "check")) {901 output.flakeCheckStart();902 const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);903 if (code == 0) output.flakeValid() else output.checkFailed("");904 return;905 }906 if (std.mem.eql(u8, ctx.sub, "show")) {907 const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;908 if (json_out) |j| {909 defer ctx.gpa.free(j);910 output.flakeShowHeader("flake outputs");911 912 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;913 defer parsed.deinit();914 if (parsed.value == .object) {915 var it = parsed.value.object.iterator();916 while (it.next()) |entry| {917 if (entry.value_ptr.* == .object) {918 var inner = entry.value_ptr.object.iterator();919 while (inner.next()) |e2| {920 const desc = if (e2.value_ptr.* == .object)921 if (e2.value_ptr.object.get("description")) |d|922 if (d == .string) d.string else ""923 else ""924 else "";925 output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);926 }927 }928 }929 }930 }931 return;932 }933 if (std.mem.eql(u8, ctx.sub, "init")) {934 _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);935 return;936 }937 if (std.mem.eql(u8, ctx.sub, "lock")) {938 _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);939 return;940 }941 if (std.mem.eql(u8, ctx.sub, "clone")) {942 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;943 _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);944 return;945 }946}947948949950const store_help = [_][2][]const u8{951 .{ "info", "store size and counts" },952 .{ "path <attr>", "store path of a package" },953 .{ "gc", "collect garbage" },954 .{ "verify", "verify store integrity" },955 .{ "repair", "repair corrupted paths" },956};957958pub fn store(ctx: Ctx) !void {959 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help);960 if (std.mem.eql(u8, ctx.sub, "gc")) {961 _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);962 return;963 }964 if (std.mem.eql(u8, ctx.sub, "verify")) {965 output.storeVerifyStart();966 _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);967 return;968 }969 if (std.mem.eql(u8, ctx.sub, "repair")) {970 if (ctx.cfg.confirm and !output.confirm("")) return;971 output.storeRepairStart();972 _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);973 return;974 }975 if (std.mem.eql(u8, ctx.sub, "info")) {976 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);977 output.storeInfo(si);978 return;979 }980 if (std.mem.eql(u8, ctx.sub, "path")) {981 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;982 const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);983 defer ctx.gpa.free(path);984 output.storePath(path);985 return;986 }987 988 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);989 output.storeInfo(si);990}991992993994const channel_help = [_][2][]const u8{995 .{ "list", "list channels" },996 .{ "add <url> [name]", "add a channel" },997 .{ "remove <name>", "remove a channel" },998 .{ "update", "update all channels" },999};10001001pub fn channel(ctx: Ctx) !void {1002 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help);1003 1004 if (ctx.cfg.flake) output.flakeChannelNote();1005 if (std.mem.eql(u8, ctx.sub, "list")) {1006 output.channelListHeader(ctx.machine.name);1007 const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1008 defer ctx.gpa.free(chans);1009 for (chans) |ch| output.channelRow(ch);1010 return;1011 }1012 if (std.mem.eql(u8, ctx.sub, "add")) {1013 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1014 const name = if (ctx.args.len > 1) ctx.args[1] else "";1015 _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1016 output.channelDone();1017 return;1018 }1019 if (std.mem.eql(u8, ctx.sub, "remove")) {1020 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1021 _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1022 output.channelDone();1023 return;1024 }1025 if (std.mem.eql(u8, ctx.sub, "update")) {1026 return channelUpdateCmd(ctx);1027 }1028}1029103010311032pub fn profile(ctx: Ctx) !void {1033 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1034 output.profileListHeader();1035 const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1036 if (out) |o| {1037 defer ctx.gpa.free(o);1038 var lines = std.mem.splitScalar(u8, o, '\n');1039 while (lines.next()) |line| {1040 const t = std.mem.trim(u8, line, " \t\r");1041 if (t.len == 0) continue;1042 output.profileRow(t, "", "");1043 }1044 }1045 return;1046 }1047 if (std.mem.eql(u8, ctx.sub, "install")) {1048 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1049 _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1050 output.done();1051 return;1052 }1053 if (std.mem.eql(u8, ctx.sub, "remove")) {1054 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1055 _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1056 output.done();1057 return;1058 }1059 if (std.mem.eql(u8, ctx.sub, "upgrade")) {1060 _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1061 output.done();1062 return;1063 }1064}1065106610671068const pkg_help = [_][2][]const u8{1069 .{ "why <pkg>", "what pulled it in" },1070 .{ "deps <pkg>", "direct dependencies" },1071 .{ "size <pkg>", "closure size" },1072 .{ "path <pkg>", "store path" },1073 .{ "closure <pkg>", "full closure" },1074};10751076pub fn pkg(ctx: Ctx) !void {1077 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help);1078 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1079 if (std.mem.eql(u8, ctx.sub, "why")) {1080 _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1081 return;1082 }1083 if (std.mem.eql(u8, ctx.sub, "deps")) {1084 _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);1085 return;1086 }1087 if (std.mem.eql(u8, ctx.sub, "size")) {1088 const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;1089 if (s) |sz| {1090 defer ctx.gpa.free(sz);1091 output.pkgResult("size", sz);1092 }1093 return;1094 }1095 if (std.mem.eql(u8, ctx.sub, "path")) {1096 const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1097 defer ctx.gpa.free(p);1098 output.pkgResult("path", p);1099 return;1100 }1101 if (std.mem.eql(u8, ctx.sub, "closure")) {1102 _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);1103 return;1104 }1105}1106110711081109pub fn pin(ctx: Ctx) !void {1110 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1111 const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1112 exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1113 output.pinDone(input, commit);1114}11151116pub fn unpin(ctx: Ctx) !void {1117 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1118 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1119 output.unpinDone(input);1120}1121112211231124pub fn hash(ctx: Ctx) !void {1125 const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1126 const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1127 defer ctx.gpa.free(h);1128 output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1129}11301131pub fn fetch(ctx: Ctx) !void {1132 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1133 const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1134 defer ctx.gpa.free(h);1135 output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1136}1137113811391140pub fn build(ctx: Ctx) !void {1141 const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1142 output.buildStart(attr orelse "default");1143 const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1144 if (code != 0) return error.BuildFailed;1145 output.buildDone();1146}11471148pub fn runCmd(ctx: Ctx) !void {1149 const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1150 output.runStart(pkg_arg);1151 _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1152}1153115411551156pub fn hello(ctx: Ctx) !void {1157 output.hello(ctx.cfg.machines);1158}1159116011611162pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1163 output.firstRunBanner();1164 output.firstRunNoConfig();11651166 var name_buf: [256]u8 = undefined;1167 var path_buf: [256]u8 = undefined;1168 var local_buf: [256]u8 = undefined;11691170 const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);11711172 1173 1174 1175 const use_flakes = output.firstRunManageType();1176 const config_path = if (use_flakes)1177 output.firstRunPrompt("flake directory", "~/nixos-config", &path_buf)1178 else1179 output.firstRunPrompt("config path", "/etc/nixos", &path_buf);1180 const local_str = output.firstRunPrompt("local", "true", &local_buf);11811182 const conf_path = try config.configPath(gpa, environ);1183 defer gpa.free(conf_path);1184 if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);11851186 1187 const flake_line = if (use_flakes) "flake = true\n" else "";1188 var content_buf: [1024]u8 = undefined;1189 const content = try std.fmt.bufPrint(1190 &content_buf,1191 "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = {s}\n",1192 .{ flake_line, machine_name, config_path, local_str },1193 );11941195 const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1196 errors.error_info.setMessage("could not write {s}", .{conf_path});1197 return error.Internal;1198 };1199 defer file.close(io);1200 file.writePositionalAll(io, content, 0) catch {1201 errors.error_info.setMessage("could not write {s}", .{conf_path});1202 return error.Internal;1203 };12041205 output.firstRunWritten(conf_path);1206}12071208pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1209 1210 1211 1212 config.migrateLegacyConfig(gpa, io, environ);1213 if (config.configPath(gpa, environ)) |conf_path| {1214 defer gpa.free(conf_path);1215 if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1216 f.close(io);1217 } else |_| {1218 try firstRunWizard(gpa, io, environ);1219 errors.error_info.reset();1220 }1221 } else |_| {}12221223 output.setupCheck();1224 const status = exec.checkNixFeatures(gpa, io, environ);1225 output.setupFeatures(status.nix_command, status.flakes);12261227 if (status.allEnabled()) {1228 output.setupAllSet();1229 api.ensureRegistryPinned(gpa, io, environ);1230 return;1231 }12321233 1234 1235 1236 1237 if (exec.isNixOS(io)) {1238 const conf_path = "/etc/nixos/configuration.nix";1239 if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1240 output.setupNixosNeedsRebuild(conf_path);1241 return;1242 }1243 output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1244 if (output.confirmDefaultNo("add it now?")) {1245 if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1246 output.setupNixosWrote(conf_path);1247 } else |_| {1248 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1249 }1250 } else {1251 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1252 }1253 return;1254 }12551256 1257 output.setupEnabling();1258 const path = try exec.enableNixFeatures(gpa, io, environ);1259 defer gpa.free(path);12601261 output.setupDone(path);1262 api.ensureRegistryPinned(gpa, io, environ);1263}1264126512661267fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1268 var ts_buf: [32]u8 = undefined;1269 const ts = nowIso(ctx.io, &ts_buf);1270 var buf: [256]u8 = undefined;1271 const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1272 ts, ctx.machine.name, action, gen,1273 }) catch return;1274 exec.appendNinaLog(ctx.io, ctx.environ, entry);1275}1276127712781279fn nowIso(io: std.Io, buf: []u8) []const u8 {1280 const fallback = "1970-01-01T00:00:00Z";1281 const ns = std.Io.Clock.real.now(io).toNanoseconds();1282 if (ns <= 0) return fallback;1283 const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1284 const es = std.time.epoch.EpochSeconds{ .secs = secs };1285 const ed = es.getEpochDay();1286 const yd = ed.calculateYearDay();1287 const md = yd.calculateMonthDay();1288 const ds = es.getDaySeconds();1289 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", .{1290 yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1291 ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1292 }) catch return fallback;1293}