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 user: bool, 31};3233pub fn apply(ctx: Ctx) !void {34 if (ctx.dry) {35 output.applyDry(ctx.machine.name);36 const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);37 if (code != 0) return error.BuildFailed;38 output.applyDryDone();39 return;40 }41 if (ctx.check) {42 return check(ctx);43 }4445 output.applyStart(ctx.machine.name);46 const start = std.Io.Clock.awake.now(ctx.io);4748 const code = exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa) catch |e| {49 exec.markApplyFailed(ctx.io, ctx.environ);50 output.applyFailed("");51 return e;52 };5354 if (code != 0) {55 exec.markApplyFailed(ctx.io, ctx.environ);56 output.applyFailed("");57 return error.BuildFailed;58 }5960 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());61 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));62 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;63 const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);64 output.applyDone(gen, elapsed, after_failure);65 logAction(ctx, "apply", gen);66}6768pub fn check(ctx: Ctx) !void {69 output.checkStart(ctx.machine.name);70 const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);71 if (code != 0) {72 output.checkFailed("");73 return error.BuildFailed;74 }75 output.checkOk();76}7778pub fn back(ctx: Ctx) !void {79 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);80 defer ctx.gpa.free(gens);8182 var current: u32 = 0;83 for (gens) |g| if (g.current) { current = g.number; };8485 86 87 var prev: u32 = 0;88 var has_prev = false;89 for (gens) |g| {90 if (g.number < current and (!has_prev or g.number > prev)) {91 prev = g.number;92 has_prev = true;93 }94 }95 if (!has_prev) {96 output.alreadyOldest();97 return;98 }99100 output.backStart(ctx.machine.name, current, prev);101 if (ctx.cfg.confirm and !output.confirm("")) return;102103 const code = try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);104 if (code != 0) return error.BuildFailed;105 output.backDone(prev);106}107108pub fn go(ctx: Ctx) !void {109 if (ctx.args.len == 0) return error.Internal;110 const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;111 const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);112113 output.goStart(ctx.machine.name, current, target);114 if (ctx.cfg.confirm and !output.confirm("")) return;115116 const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);117 if (code != 0) return error.ProcessFailed;118 output.generationDone(target);119}120121pub fn history(ctx: Ctx) !void {122 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);123 defer ctx.gpa.free(gens);124 output.historyHeader(ctx.machine.name);125 for (gens) |g| output.historyRow(g);126}127128const gen_help = [_][2][]const u8{129 .{ "list", "list generations" },130 .{ "current", "show current generation" },131 .{ "delete <n>", "delete generation n" },132 .{ "delete old", "delete old generations" },133};134135pub fn genCmd(ctx: Ctx) !void {136 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("gen", &gen_help, null);137 if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);138 if (std.mem.eql(u8, ctx.sub, "current")) {139 const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);140 output.genCurrent(n);141 return;142 }143 if (std.mem.eql(u8, ctx.sub, "delete")) {144 if (ctx.args.len == 0) return error.Internal;145 if (std.mem.eql(u8, ctx.args[0], "old")) {146 if (ctx.cfg.confirm and !output.confirm("")) return;147 _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);148 } else {149 const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;150 if (ctx.cfg.confirm and !output.confirm("")) return;151 _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);152 }153 output.done();154 return;155 }156 return error.Internal;157}158159pub fn clean(ctx: Ctx) !void {160 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);161 defer ctx.gpa.free(gens);162 const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");163 const total: u32 = @intCast(gens.len);164 165 166 const keep: u32 = if (all) 1 else ctx.cfg.generations;167 if (total <= keep) {168 output.cleanNothing(ctx.machine.name, total);169 return;170 }171 output.cleanStart(ctx.machine.name, keep, total);172 if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;173 _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);174 output.cleanDone();175}176177pub fn statusCmd(ctx: Ctx) !void {178 output.statusHeader();179 180 181 if (ctx.all and ctx.cfg.machines.len > 0) {182 for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);183 return;184 }185 statusRowFor(ctx, &ctx.machine);186}187188fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {189 190 191 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {192 output.statusRow(machine.name, 0, "", "", false);193 return;194 };195 const st = exec.systemStatus(ctx.gpa, ctx.io, machine);196 defer ctx.gpa.free(st.size);197 defer ctx.gpa.free(st.age);198 output.statusRow(machine.name, gen, st.age, st.size, true);199}200201pub fn diff(ctx: Ctx) !void {202 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);203 defer ctx.gpa.free(gens);204 var current: u32 = 0;205 var prev: u32 = 0;206 for (gens) |g| {207 if (g.current) current = g.number;208 if (!g.current and g.number > prev and g.number < current) prev = g.number;209 }210 if (ctx.args.len >= 2) {211 const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;212 const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;213 output.diffHeader(a, b, ctx.machine.name);214 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;215 } else {216 output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);217 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;218 }219}220221pub fn mood(ctx: Ctx) !void {222 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;223 const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);224 defer ctx.gpa.free(st.size);225 defer ctx.gpa.free(st.age);226 const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");227 defer ctx.gpa.free(state);228 output.mood(ctx.machine.name, state, gen, st.age, st.size);229}230231pub fn doctor(ctx: Ctx) !void {232 output.doctorHeader(ctx.machine.name);233 const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);234 defer ctx.gpa.free(checks);235 var warnings: u32 = 0;236 var failures: u32 = 0;237 for (checks) |ch| {238 output.doctorRow(ch);239 if (ch.status == .warn) warnings += 1;240 if (ch.status == .fail) failures += 1;241 }242 output.doctorSummary(warnings, failures);243}244245246pub fn update(ctx: Ctx) !void {247 output.updateSelfStart();248249 if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {250 output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));251 return error.Internal;252 }253254 const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");255 const source_url = env_url orelse UPDATE_URL;256257 const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {258 error.NetworkError, error.HttpError => {259 output.updateSelfNetworkError();260 return;261 },262 else => return e,263 };264 defer ctx.gpa.free(body);265266 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {267 output.printWarning("could not parse release metadata");268 return;269 };270 defer parsed.deinit();271272 const root = parsed.value;273 if (root != .object) { output.printWarning("malformed release metadata"); return; }274275 const remote_ver = blk: {276 const v = root.object.get("version") orelse { output.printWarning("malformed release metadata"); return; };277 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };278 };279280 if (std.mem.eql(u8, remote_ver, version.VERSION)) {281 output.updateSelfCurrent(version.VERSION);282 return;283 }284285 output.updateSelfAvailable(version.VERSION, remote_ver);286 if (ctx.check) return;287288 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;289 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {290 errors.error_info.setMessage("could not determine install path", .{});291 return error.Internal;292 };293294 295 296 297 298 299 if (std.mem.startsWith(u8, install_path, "/nix/store/")) {300 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);301 defer {302 if (nina_element) |n| ctx.gpa.free(n);303 }304 if (nina_element == null) {305 output.updateSelfNotInProfile();306 return;307 }308 const element = nina_element.?;309 output.updateSelfNixManaged(remote_ver);310 if (ctx.cfg.confirm and !output.confirm("")) return;311 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", element }) catch {312 output.updateSelfNixFailed();313 return;314 };315 if (ec != 0) output.updateSelfNixFailed();316 return;317 }318319 const plat_info = blk: {320 const pv = root.object.get("platforms") orelse break :blk null;321 if (pv != .object) break :blk null;322 break :blk pv.object.get(version.PLATFORM);323 };324 if (plat_info == null) { output.updateSelfNoPlatform(version.PLATFORM); return; }325326 const dl_url = blk: {327 const v = plat_info.?.object.get("url") orelse { output.printWarning("malformed release metadata"); return; };328 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };329 };330331 const raw_cksum = blk: {332 if (plat_info.?.object.get("blake3")) |v|333 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };334 if (plat_info.?.object.get("checksum")) |v|335 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };336 output.printWarning("missing checksum in release metadata");337 return;338 };339 const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;340341 if (ctx.cfg.confirm and !output.confirm("")) return;342343 output.updateSelfDownloading(remote_ver, version.PLATFORM);344 const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {345 output.printWarning("download failed — check your connection and try again");346 return;347 };348 defer ctx.gpa.free(tmp_path);349350 output.updateSelfVerifying();351 exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {352 error.ChecksumMismatch => { output.updateSelfChecksumFailed(); return; },353 else => return e,354 };355356 output.updateSelfDone(version.VERSION, remote_ver);357}358359360361362pub fn goodbye(ctx: Ctx) !void {363 output.goodbyeStart();364365 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;366 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {367 errors.error_info.setMessage("could not determine install path", .{});368 return error.Internal;369 };370371 372 if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {373 output.goodbyeFile(install_path);374 if (ctx.cfg.confirm and !output.confirm("")) return;375 std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {376 errors.error_info.setMessage("could not remove {s}", .{install_path});377 return e;378 };379 output.goodbyeDone();380 return;381 }382383 384 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);385 defer {386 if (nina_element) |n| ctx.gpa.free(n);387 }388389 if (nina_element == null) {390 errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});391 return error.Internal;392 }393394 output.goodbyeNix();395 if (ctx.cfg.confirm and !output.confirm("")) return;396 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {397 output.goodbyeFailed("nix profile remove failed");398 return;399 };400 if (ec != 0) {401 output.goodbyeFailed("nix profile remove failed");402 return;403 }404 output.goodbyeDone();405}406407fn channelUpdateCmd(ctx: Ctx) !void {408 output.updateStart(ctx.machine.name);409 _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);410 output.updateDone();411}412413pub fn upgrade(ctx: Ctx) !void {414 output.upgradeStart(ctx.machine.name);415 output.printSubstep("updating channels", .{});416 _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};417 output.printSubstep("rebuilding", .{});418 const start = std.Io.Clock.awake.now(ctx.io);419 const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);420 if (code != 0) {421 output.applyFailed("");422 return error.BuildFailed;423 }424 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());425 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));426 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;427 output.applyDone(gen, elapsed, false);428}429430pub fn log(ctx: Ctx) !void {431 output.logHeader(ctx.machine.name);432 const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {433 434 return;435 };436 defer ctx.gpa.free(content);437 var lines = std.mem.splitScalar(u8, content, '\n');438 while (lines.next()) |line| {439 const t = std.mem.trim(u8, line, " \t\r");440 if (t.len == 0) continue;441 if (t[0] == '{') {442 renderJsonLogLine(ctx.gpa, t);443 } else {444 445 var parts = std.mem.tokenizeScalar(u8, t, '\t');446 const date = parts.next() orelse continue;447 const time = parts.next() orelse "";448 const action = parts.next() orelse "";449 const detail = parts.next() orelse "";450 output.logRow(date, time, action, detail);451 }452 }453}454455456457fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {458 const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {459 output.logRow(line, "", "", ""); 460 return;461 };462 defer parsed.deinit();463 if (parsed.value != .object) return;464 const o = parsed.value.object;465466 const ts = jsonStr(o, "ts");467 const date = if (ts.len >= 10) ts[0..10] else ts;468 const time = if (ts.len >= 16) ts[11..16] else "";469 const action = jsonStr(o, "command");470 const outcome = jsonStr(o, "outcome");471472 var buf: [160]u8 = undefined;473 var detail: []const u8 = outcome;474 if (o.get("gen_after")) |g| {475 if (g == .integer) {476 detail = std.fmt.bufPrint(&buf, "{s} -> gen {d}", .{ outcome, g.integer }) catch outcome;477 }478 }479 output.logRow(date, time, action, detail);480}481482fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {483 if (o.get(key)) |v| {484 if (v == .string) return v.string;485 }486 return "";487}488489pub fn edit(ctx: Ctx) !void {490 const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");491 const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";492 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });493 defer ctx.gpa.free(path);494 output.editOpen(path, ctx.cfg.editor);495 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);496}497498pub fn fmt(ctx: Ctx) !void {499 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});500 defer ctx.gpa.free(path);501 if (ctx.check) {502 const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);503 if (code != 0) output.fmtNeedsFormat() else output.fmtDone();504 return;505 }506 output.fmtStart(path);507 _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);508 output.fmtDone();509}510511pub fn repl(ctx: Ctx) !void {512 output.replStart();513 _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);514}515516pub fn develop(ctx: Ctx) !void {517 if (std.mem.eql(u8, ctx.sub, "show")) {518 _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);519 return;520 }521 const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))522 ctx.args[0]523 else524 null;525 output.developStart(&.{});526 _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);527 output.developDone();528}529530pub fn info(ctx: Ctx) !void {531 output.infoHeader(ctx.machine.name);532 const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");533 defer ctx.gpa.free(nixos_ver);534 output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));535536 const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");537 defer ctx.gpa.free(kernel);538 output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));539540 const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");541 defer ctx.gpa.free(uptime);542 output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));543}544545pub fn boot(ctx: Ctx) !void {546 output.bootHeader(ctx.machine.name);547 const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};548 defer ctx.gpa.free(entries);549 for (entries, 0..) |entry, i| output.bootEntry(entry, i);550}551552pub fn searchCmd(ctx: Ctx) !void {553 const query = if (ctx.args.len > 0) ctx.args[0] else "";554 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);555 const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);556 if (selected) |npkg| try selectAndInstall(ctx, npkg);557}558559pub fn optionCmd(ctx: Ctx) !void {560 const query = if (ctx.args.len > 0) ctx.args[0] else "";561 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);562 _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);563}564565pub fn install(ctx: Ctx) !void {566 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;567568 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);569570 571 const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {572 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});573 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});574 return error.PackageNotFound;575 };576577 if (pkgs.len == 0) {578 579 if (closestPackage(ctx, pkg_name)) |sugg| {580 output.didYouMean(pkg_name, sugg.pname);581 if (output.confirm("")) try selectAndInstall(ctx, sugg);582 return;583 }584 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});585 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});586 return error.PackageNotFound;587 }588589 590 591 var found = pkgs[0];592 for (pkgs) |p| {593 if (std.mem.eql(u8, p.pname, pkg_name)) {594 found = p;595 break;596 }597 }598 try selectAndInstall(ctx, found);599}600601602603604fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {605 if (query.len < 2) return null;606 var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};607 if (candidates.len == 0 and query.len > 2) {608 candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};609 }610 if (candidates.len == 0) return null;611612 var best: ?types.NixPackage = null;613 var best_dist: usize = std.math.maxInt(usize);614 for (candidates) |p| {615 const d = editDistance(query, p.pname);616 if (d > 0 and d < best_dist) {617 best_dist = d;618 best = p;619 }620 }621 622 const threshold = @max(@as(usize, 2), query.len / 3);623 return if (best_dist <= threshold) best else null;624}625626627628fn editDistance(a: []const u8, b: []const u8) usize {629 const n = b.len;630 if (a.len == 0) return n;631 if (n == 0) return a.len;632 if (n + 1 > 128) return std.math.maxInt(usize);633 var prev: [128]usize = undefined;634 var curr: [128]usize = undefined;635 var j: usize = 0;636 while (j <= n) : (j += 1) prev[j] = j;637 var i: usize = 1;638 while (i <= a.len) : (i += 1) {639 curr[0] = i;640 j = 1;641 while (j <= n) : (j += 1) {642 const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;643 curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));644 }645 @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);646 }647 return prev[n];648}649650test "editDistance is case-insensitive Levenshtein" {651 try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));652 try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));653 try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));654 try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));655}656657658659660661fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {662 output.installSelectPrompt(npkg.pname, npkg.version);663664 var choice_buf: [8]u8 = undefined;665 var choice_len: usize = 0;666 while (choice_len < choice_buf.len) {667 const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;668 if (n == 0) break;669 if (choice_buf[choice_len] == '\n') break;670 choice_len += 1;671 }672 const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");673674 if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {675 try profileInstallPkg(ctx, npkg);676 } else if (choice[0] == 's' or choice[0] == 'S') {677 try systemInstallPkg(ctx, npkg);678 } else if (choice[0] == 't' or choice[0] == 'T') {679 try tryPkg(ctx, npkg);680 }681}682683fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {684 output.installStart(npkg.pname, .profile);685 output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});686 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));687 const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);688 if (code != 0) return error.ProcessFailed;689 output.installDone(npkg.pname);690}691692fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {693 const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});694 defer ctx.gpa.free(config_path);695 const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;696 output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);697 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);698 if (ctx.cfg.confirm) {699 if (output.confirm("apply now? ")) {700 try apply(ctx);701 }702 }703}704705fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {706 output.tryStart(npkg.pname);707 output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});708 output.tryExitHint();709 _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);710 output.tryDone();711}712713pub fn remove(ctx: Ctx) !void {714 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;715 output.removeStart(pkg_name);716 const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);717 if (code != 0) return error.ProcessFailed;718 output.done();719}720721pub fn list(ctx: Ctx) !void {722 output.listHeader(ctx.machine.name);723724 725 726 727 if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {728 defer ctx.gpa.free(json);729 output.listSection("profile");730 renderProfileJson(ctx.gpa, json);731 }732733 734 735 if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {736 defer ctx.gpa.free(paths);737 output.blankLine();738 output.listSection("system");739 var lines = std.mem.splitScalar(u8, paths, '\n');740 while (lines.next()) |line| {741 const t = std.mem.trim(u8, line, " \t\r");742 if (t.len == 0) continue;743 const row = pkgFromStorePath(t);744 745 if (row.version.len == 0) continue;746 output.listPkg(row.name, row.version);747 }748 }749}750751const PkgRow = struct { name: []const u8, version: []const u8 };752753754755756757fn pkgFromStorePath(path: []const u8) PkgRow {758 const base = std.fs.path.basename(path);759 const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;760 var i: usize = 0;761 while (i + 1 < after_hash.len) : (i += 1) {762 if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {763 return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };764 }765 }766 return .{ .name = after_hash, .version = "" };767}768769770771772fn stripOutputSuffix(ver: []const u8) []const u8 {773 const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };774 for (suffixes) |s| {775 if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];776 }777 return ver;778}779780test "pkgFromStorePath splits name and version at first dash-digit" {781 const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");782 try std.testing.expectEqualStrings("ripgrep", a.name);783 try std.testing.expectEqualStrings("15.1.0", a.version);784785 const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");786 try std.testing.expectEqualStrings("helix", b.name);787 try std.testing.expectEqualStrings("25.01", b.version);788789 790 const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");791 try std.testing.expectEqualStrings("curl", c.name);792 try std.testing.expectEqualStrings("8.20.0", c.version);793}794795fn firstStorePath(el: std.json.Value) ?[]const u8 {796 if (el != .object) return null;797 const sp = el.object.get("storePaths") orelse return null;798 if (sp != .array or sp.array.items.len == 0) return null;799 const first = sp.array.items[0];800 return if (first == .string) first.string else null;801}802803804805fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {806 const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;807 defer parsed.deinit();808 if (parsed.value != .object) return;809 const elements = parsed.value.object.get("elements") orelse return;810 switch (elements) {811 .object => |obj| {812 var it = obj.iterator();813 while (it.next()) |entry| {814 const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";815 output.listPkg(entry.key_ptr.*, ver);816 }817 },818 .array => |arr| {819 for (arr.items) |el| {820 const path = firstStorePath(el) orelse continue;821 const row = pkgFromStorePath(path);822 output.listPkg(row.name, row.version);823 }824 },825 else => {},826 }827}828829pub fn tryCmd(ctx: Ctx) !void {830 const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;831 const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };832 try tryPkg(ctx, shell_pkg);833}834835836837const service_help = [_][2][]const u8{838 .{ "list", "list running services" },839 .{ "logs <svc>", "show service logs" },840 .{ "status <svc>", "service status" },841 .{ "start <svc>", "start a service" },842 .{ "stop <svc>", "stop a service" },843 .{ "restart <svc>", "restart a service" },844 .{ "enable <svc>", "enable at boot" },845 .{ "disable <svc>", "disable at boot" },846};847848pub fn service(ctx: Ctx) !void {849 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");850 if (std.mem.eql(u8, ctx.sub, "list")) {851 output.serviceListHeader(ctx.machine.name);852 const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};853 defer ctx.gpa.free(svcs);854 for (svcs) |s| output.serviceRow(s);855 return;856 }857 if (std.mem.eql(u8, ctx.sub, "logs")) {858 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;859 const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");860 output.serviceLogsHeader(name, ctx.last, ctx.machine.name);861 _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);862 return;863 }864 if (std.mem.eql(u8, ctx.sub, "status")) {865 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;866 output.serviceVerb("status", name, ctx.machine.name);867 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);868 return;869 }870 871 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;872 if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {873 if (!output.confirm("")) return;874 }875 output.serviceVerb(ctx.sub, name, ctx.machine.name);876 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);877 output.serviceDone();878}879880881882const flake_help = [_][2][]const u8{883 .{ "init", "create a new flake.nix" },884 .{ "update", "update flake inputs" },885 .{ "update <in>", "update a specific input" },886 .{ "check", "validate the flake" },887 .{ "show", "inspect flake outputs" },888 .{ "lock", "regenerate flake.lock" },889 .{ "clone <url>", "clone a flake repository" },890};891892pub fn flake(ctx: Ctx) !void {893 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);894 if (std.mem.eql(u8, ctx.sub, "update")) {895 output.flakeUpdateStart();896 const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;897 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);898 output.flakeLockWritten();899 return;900 }901 if (std.mem.eql(u8, ctx.sub, "check")) {902 output.flakeCheckStart();903 const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);904 if (code == 0) output.flakeValid() else output.checkFailed("");905 return;906 }907 if (std.mem.eql(u8, ctx.sub, "show")) {908 const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;909 if (json_out) |j| {910 defer ctx.gpa.free(j);911 output.flakeShowHeader("flake outputs");912 913 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;914 defer parsed.deinit();915 if (parsed.value == .object) {916 var it = parsed.value.object.iterator();917 while (it.next()) |entry| {918 if (entry.value_ptr.* == .object) {919 var inner = entry.value_ptr.object.iterator();920 while (inner.next()) |e2| {921 const desc = if (e2.value_ptr.* == .object)922 if (e2.value_ptr.object.get("description")) |d|923 if (d == .string) d.string else ""924 else ""925 else "";926 output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);927 }928 }929 }930 }931 }932 return;933 }934 if (std.mem.eql(u8, ctx.sub, "init")) {935 _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);936 return;937 }938 if (std.mem.eql(u8, ctx.sub, "lock")) {939 _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);940 return;941 }942 if (std.mem.eql(u8, ctx.sub, "clone")) {943 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;944 _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);945 return;946 }947}948949950951const store_help = [_][2][]const u8{952 .{ "info", "store size and counts" },953 .{ "path <attr>", "store path of a package" },954 .{ "gc", "collect garbage" },955 .{ "verify", "verify store integrity" },956 .{ "repair", "repair corrupted paths" },957};958959pub fn store(ctx: Ctx) !void {960 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);961 if (std.mem.eql(u8, ctx.sub, "gc")) {962 _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);963 return;964 }965 if (std.mem.eql(u8, ctx.sub, "verify")) {966 output.storeVerifyStart();967 _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);968 return;969 }970 if (std.mem.eql(u8, ctx.sub, "repair")) {971 if (ctx.cfg.confirm and !output.confirm("")) return;972 output.storeRepairStart();973 _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);974 return;975 }976 if (std.mem.eql(u8, ctx.sub, "info")) {977 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);978 output.storeInfo(si);979 return;980 }981 if (std.mem.eql(u8, ctx.sub, "path")) {982 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;983 const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);984 defer ctx.gpa.free(path);985 output.storePath(path);986 return;987 }988 989 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);990 output.storeInfo(si);991}992993994995const channel_help = [_][2][]const u8{996 .{ "list", "list channels" },997 .{ "add <url> [name]", "add a channel" },998 .{ "remove <name>", "remove a channel" },999 .{ "update", "update all channels" },1000};10011002pub fn channel(ctx: Ctx) !void {1003 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1004 1005 if (ctx.cfg.flake) output.flakeChannelNote();1006 if (std.mem.eql(u8, ctx.sub, "list")) {1007 output.channelListHeader(ctx.machine.name);1008 const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1009 defer ctx.gpa.free(chans);1010 for (chans) |ch| output.channelRow(ch);1011 return;1012 }1013 if (std.mem.eql(u8, ctx.sub, "add")) {1014 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1015 const name = if (ctx.args.len > 1) ctx.args[1] else "";1016 _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1017 output.channelDone();1018 return;1019 }1020 if (std.mem.eql(u8, ctx.sub, "remove")) {1021 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1022 _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1023 output.channelDone();1024 return;1025 }1026 if (std.mem.eql(u8, ctx.sub, "update")) {1027 return channelUpdateCmd(ctx);1028 }1029}1030103110321033pub fn profile(ctx: Ctx) !void {1034 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1035 output.profileListHeader();1036 const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1037 if (out) |o| {1038 defer ctx.gpa.free(o);1039 var lines = std.mem.splitScalar(u8, o, '\n');1040 while (lines.next()) |line| {1041 const t = std.mem.trim(u8, line, " \t\r");1042 if (t.len == 0) continue;1043 output.profileRow(t, "", "");1044 }1045 }1046 return;1047 }1048 if (std.mem.eql(u8, ctx.sub, "install")) {1049 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1050 _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1051 output.done();1052 return;1053 }1054 if (std.mem.eql(u8, ctx.sub, "remove")) {1055 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1056 _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1057 output.done();1058 return;1059 }1060 if (std.mem.eql(u8, ctx.sub, "upgrade")) {1061 _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1062 output.done();1063 return;1064 }1065}1066106710681069const pkg_help = [_][2][]const u8{1070 .{ "why <pkg>", "what pulled it in" },1071 .{ "deps <pkg>", "direct dependencies" },1072 .{ "size <pkg>", "closure size" },1073 .{ "path <pkg>", "store path" },1074 .{ "closure <pkg>", "full closure" },1075};10761077pub fn pkg(ctx: Ctx) !void {1078 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1079 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1080 if (std.mem.eql(u8, ctx.sub, "why")) {1081 _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1082 return;1083 }1084 if (std.mem.eql(u8, ctx.sub, "deps")) {1085 _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);1086 return;1087 }1088 if (std.mem.eql(u8, ctx.sub, "size")) {1089 const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;1090 if (s) |sz| {1091 defer ctx.gpa.free(sz);1092 output.pkgResult("size", sz);1093 }1094 return;1095 }1096 if (std.mem.eql(u8, ctx.sub, "path")) {1097 const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1098 defer ctx.gpa.free(p);1099 output.pkgResult("path", p);1100 return;1101 }1102 if (std.mem.eql(u8, ctx.sub, "closure")) {1103 _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);1104 return;1105 }1106}1107110811091110pub fn why(ctx: Ctx) !void {1111 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1112 _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1113}1114111511161117pub fn pin(ctx: Ctx) !void {1118 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1119 const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1120 exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1121 output.pinDone(input, commit);1122}11231124pub fn unpin(ctx: Ctx) !void {1125 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1126 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1127 output.unpinDone(input);1128}1129113011311132pub fn hash(ctx: Ctx) !void {1133 const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1134 const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1135 defer ctx.gpa.free(h);1136 output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1137}11381139pub fn fetch(ctx: Ctx) !void {1140 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1141 const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1142 defer ctx.gpa.free(h);1143 output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1144}1145114611471148pub fn build(ctx: Ctx) !void {1149 const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1150 output.buildStart(attr orelse "default");1151 const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1152 if (code != 0) return error.BuildFailed;1153 output.buildDone();1154}11551156pub fn runCmd(ctx: Ctx) !void {1157 const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1158 output.runStart(pkg_arg);1159 _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1160}1161116211631164pub fn hello(ctx: Ctx) !void {1165 output.hello(ctx.cfg.machines);1166}1167116811691170pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1171 output.firstRunBanner();1172 output.firstRunNoConfig();11731174 var name_buf: [256]u8 = undefined;1175 var path_buf: [256]u8 = undefined;1176 var local_buf: [256]u8 = undefined;11771178 const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);11791180 1181 1182 1183 const use_flakes = output.firstRunManageType();1184 const config_path = if (use_flakes)1185 output.firstRunPrompt("flake directory", "~/nixos-config", &path_buf)1186 else1187 output.firstRunPrompt("config path", "/etc/nixos", &path_buf);1188 const local_str = output.firstRunPrompt("local", "true", &local_buf);11891190 const conf_path = try config.configPath(gpa, environ);1191 defer gpa.free(conf_path);1192 if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);11931194 1195 const flake_line = if (use_flakes) "flake = true\n" else "";1196 var content_buf: [1024]u8 = undefined;1197 const content = try std.fmt.bufPrint(1198 &content_buf,1199 "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = {s}\n",1200 .{ flake_line, machine_name, config_path, local_str },1201 );12021203 const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1204 errors.error_info.setMessage("could not write {s}", .{conf_path});1205 return error.Internal;1206 };1207 defer file.close(io);1208 file.writePositionalAll(io, content, 0) catch {1209 errors.error_info.setMessage("could not write {s}", .{conf_path});1210 return error.Internal;1211 };12121213 output.firstRunWritten(conf_path);1214}12151216pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1217 1218 1219 1220 config.migrateLegacyConfig(gpa, io, environ);1221 if (config.configPath(gpa, environ)) |conf_path| {1222 defer gpa.free(conf_path);1223 if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1224 f.close(io);1225 } else |_| {1226 try firstRunWizard(gpa, io, environ);1227 errors.error_info.reset();1228 }1229 } else |_| {}12301231 output.setupCheck();1232 const status = exec.checkNixFeatures(gpa, io, environ);1233 output.setupFeatures(status.nix_command, status.flakes);12341235 if (status.allEnabled()) {1236 output.setupAllSet();1237 api.ensureRegistryPinned(gpa, io, environ);1238 return;1239 }12401241 1242 1243 1244 1245 if (exec.isNixOS(io)) {1246 const conf_path = "/etc/nixos/configuration.nix";1247 if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1248 output.setupNixosNeedsRebuild(conf_path);1249 return;1250 }1251 output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1252 if (output.confirmDefaultNo("add it now?")) {1253 if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1254 output.setupNixosWrote(conf_path);1255 } else |_| {1256 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1257 }1258 } else {1259 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1260 }1261 return;1262 }12631264 1265 output.setupEnabling();1266 const path = try exec.enableNixFeatures(gpa, io, environ);1267 defer gpa.free(path);12681269 output.setupDone(path);1270 api.ensureRegistryPinned(gpa, io, environ);1271}1272127312741275fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1276 var ts_buf: [32]u8 = undefined;1277 const ts = nowIso(ctx.io, &ts_buf);1278 var buf: [256]u8 = undefined;1279 const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1280 ts, ctx.machine.name, action, gen,1281 }) catch return;1282 exec.appendNinaLog(ctx.io, ctx.environ, entry);1283}1284128512861287fn nowIso(io: std.Io, buf: []u8) []const u8 {1288 const fallback = "1970-01-01T00:00:00Z";1289 const ns = std.Io.Clock.real.now(io).toNanoseconds();1290 if (ns <= 0) return fallback;1291 const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1292 const es = std.time.epoch.EpochSeconds{ .secs = secs };1293 const ed = es.getEpochDay();1294 const yd = ed.calculateYearDay();1295 const md = yd.calculateMonthDay();1296 const ds = es.getDaySeconds();1297 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", .{1298 yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1299 ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1300 }) catch return fallback;1301}