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};3233343536fn flakeSystem(ctx: Ctx) bool {37 return ctx.cfg.flake or exec.configHasFlake(ctx.gpa, ctx.io, &ctx.machine);38}3940pub fn apply(ctx: Ctx) !void {41 if (ctx.dry) {42 output.applyDry(ctx.machine.name);43 const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);44 if (code != 0) return error.BuildFailed;45 output.applyDryDone();46 return;47 }48 if (ctx.check) {49 return check(ctx);50 }5152 output.applyStart(ctx.machine.name);53 const start = std.Io.Clock.awake.now(ctx.io);5455 const code = exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa) catch |e| {56 exec.markApplyFailed(ctx.io, ctx.environ);57 output.applyFailed("");58 return e;59 };6061 if (code != 0) {62 exec.markApplyFailed(ctx.io, ctx.environ);63 output.applyFailed("");64 return error.BuildFailed;65 }6667 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());68 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));69 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;70 const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);71 output.applyDone(gen, elapsed, after_failure);72 logAction(ctx, "apply", gen);73}7475pub fn check(ctx: Ctx) !void {76 output.checkStart(ctx.machine.name);77 const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);78 if (code != 0) {79 output.checkFailed("");80 return error.BuildFailed;81 }82 output.checkOk();83}8485pub fn back(ctx: Ctx) !void {86 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);87 defer ctx.gpa.free(gens);8889 var current: u32 = 0;90 for (gens) |g| if (g.current) { current = g.number; };9192 93 94 var prev: u32 = 0;95 var has_prev = false;96 for (gens) |g| {97 if (g.number < current and (!has_prev or g.number > prev)) {98 prev = g.number;99 has_prev = true;100 }101 }102 if (!has_prev) {103 output.alreadyOldest();104 return;105 }106107 output.backStart(ctx.machine.name, current, prev);108 if (ctx.cfg.confirm and !output.confirm("")) return;109110 const code = try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);111 if (code != 0) return error.BuildFailed;112 output.backDone(prev);113}114115pub fn go(ctx: Ctx) !void {116 if (ctx.args.len == 0) return error.Internal;117 const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;118 const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);119120 output.goStart(ctx.machine.name, current, target);121 if (ctx.cfg.confirm and !output.confirm("")) return;122123 const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);124 if (code != 0) return error.ProcessFailed;125 output.generationDone(target);126}127128pub fn history(ctx: Ctx) !void {129 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);130 defer ctx.gpa.free(gens);131 output.historyHeader(ctx.machine.name);132 for (gens) |g| output.historyRow(g);133}134135const gen_help = [_][2][]const u8{136 .{ "list", "list generations" },137 .{ "current", "show current generation" },138 .{ "delete <n>", "delete generation n" },139 .{ "delete old", "delete old generations" },140};141142pub fn genCmd(ctx: Ctx) !void {143 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("gen", &gen_help, null);144 if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);145 if (std.mem.eql(u8, ctx.sub, "current")) {146 const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);147 output.genCurrent(n);148 return;149 }150 if (std.mem.eql(u8, ctx.sub, "delete")) {151 if (ctx.args.len == 0) return error.Internal;152 if (std.mem.eql(u8, ctx.args[0], "old")) {153 if (ctx.cfg.confirm and !output.confirm("")) return;154 _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);155 } else {156 const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;157 if (ctx.cfg.confirm and !output.confirm("")) return;158 _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);159 }160 output.done();161 return;162 }163 return error.Internal;164}165166pub fn clean(ctx: Ctx) !void {167 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);168 defer ctx.gpa.free(gens);169 const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");170 const total: u32 = @intCast(gens.len);171 172 173 const keep: u32 = if (all) 1 else ctx.cfg.generations;174 if (total <= keep) {175 output.cleanNothing(ctx.machine.name, total);176 return;177 }178 output.cleanStart(ctx.machine.name, keep, total);179 if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;180 _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);181 output.cleanDone();182}183184pub fn statusCmd(ctx: Ctx) !void {185 output.statusHeader();186 187 188 if (ctx.all and ctx.cfg.machines.len > 0) {189 for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);190 return;191 }192 statusRowFor(ctx, &ctx.machine);193}194195fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {196 197 198 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {199 output.statusRow(machine.name, 0, "", "", false);200 return;201 };202 const st = exec.systemStatus(ctx.gpa, ctx.io, machine);203 defer ctx.gpa.free(st.size);204 defer ctx.gpa.free(st.age);205 output.statusRow(machine.name, gen, st.age, st.size, true);206}207208pub fn diff(ctx: Ctx) !void {209 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);210 defer ctx.gpa.free(gens);211 var current: u32 = 0;212 var prev: u32 = 0;213 for (gens) |g| {214 if (g.current) current = g.number;215 if (!g.current and g.number > prev and g.number < current) prev = g.number;216 }217 if (ctx.args.len >= 2) {218 const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;219 const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;220 output.diffHeader(a, b, ctx.machine.name);221 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;222 } else {223 output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);224 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;225 }226}227228pub fn mood(ctx: Ctx) !void {229 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;230 const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);231 defer ctx.gpa.free(st.size);232 defer ctx.gpa.free(st.age);233 const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");234 defer ctx.gpa.free(state);235 output.mood(ctx.machine.name, state, gen, st.age, st.size);236}237238pub fn doctor(ctx: Ctx) !void {239 output.doctorHeader(ctx.machine.name);240 const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);241 defer ctx.gpa.free(checks);242 var warnings: u32 = 0;243 var failures: u32 = 0;244 for (checks) |ch| {245 output.doctorRow(ch);246 if (ch.status == .warn) warnings += 1;247 if (ch.status == .fail) failures += 1;248 }249 output.doctorSummary(warnings, failures);250}251252253pub fn update(ctx: Ctx) !void {254 output.updateSelfStart();255256 if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {257 output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));258 return error.Internal;259 }260261 const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");262 const source_url = env_url orelse UPDATE_URL;263264 const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {265 error.NetworkError, error.HttpError => {266 output.updateSelfNetworkError();267 return;268 },269 else => return e,270 };271 defer ctx.gpa.free(body);272273 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {274 output.printWarning("could not parse release metadata");275 return;276 };277 defer parsed.deinit();278279 const root = parsed.value;280 if (root != .object) { output.printWarning("malformed release metadata"); return; }281282 const remote_ver = blk: {283 const v = root.object.get("version") orelse { output.printWarning("malformed release metadata"); return; };284 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };285 };286287 if (std.mem.eql(u8, remote_ver, version.VERSION)) {288 output.updateSelfCurrent(version.VERSION);289 return;290 }291292 output.updateSelfAvailable(version.VERSION, remote_ver);293 if (ctx.check) return;294295 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;296 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {297 errors.error_info.setMessage("could not determine install path", .{});298 return error.Internal;299 };300301 302 303 304 305 306 if (std.mem.startsWith(u8, install_path, "/nix/store/")) {307 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);308 defer {309 if (nina_element) |n| ctx.gpa.free(n);310 }311 if (nina_element == null) {312 output.updateSelfNotInProfile();313 return;314 }315 const element = nina_element.?;316 output.updateSelfNixManaged(remote_ver);317 if (ctx.cfg.confirm and !output.confirm("")) return;318 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", element }) catch {319 output.updateSelfNixFailed();320 return;321 };322 if (ec != 0) output.updateSelfNixFailed();323 return;324 }325326 const plat_info = blk: {327 const pv = root.object.get("platforms") orelse break :blk null;328 if (pv != .object) break :blk null;329 break :blk pv.object.get(version.PLATFORM);330 };331 if (plat_info == null) { output.updateSelfNoPlatform(version.PLATFORM); return; }332333 const dl_url = blk: {334 const v = plat_info.?.object.get("url") orelse { output.printWarning("malformed release metadata"); return; };335 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };336 };337338 const raw_cksum = blk: {339 if (plat_info.?.object.get("blake3")) |v|340 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };341 if (plat_info.?.object.get("checksum")) |v|342 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };343 output.printWarning("missing checksum in release metadata");344 return;345 };346 const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;347348 if (ctx.cfg.confirm and !output.confirm("")) return;349350 output.updateSelfDownloading(remote_ver, version.PLATFORM);351 const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {352 output.printWarning("download failed — check your connection and try again");353 return;354 };355 defer ctx.gpa.free(tmp_path);356357 output.updateSelfVerifying();358 exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {359 error.ChecksumMismatch => { output.updateSelfChecksumFailed(); return; },360 else => return e,361 };362363 output.updateSelfDone(version.VERSION, remote_ver);364}365366367368369pub fn goodbye(ctx: Ctx) !void {370 output.goodbyeStart();371372 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;373 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {374 errors.error_info.setMessage("could not determine install path", .{});375 return error.Internal;376 };377378 379 if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {380 output.goodbyeFile(install_path);381 if (ctx.cfg.confirm and !output.confirm("")) return;382 std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {383 errors.error_info.setMessage("could not remove {s}", .{install_path});384 return e;385 };386 output.goodbyeDone();387 return;388 }389390 391 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);392 defer {393 if (nina_element) |n| ctx.gpa.free(n);394 }395396 if (nina_element == null) {397 errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});398 return error.Internal;399 }400401 output.goodbyeNix();402 if (ctx.cfg.confirm and !output.confirm("")) return;403 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {404 output.goodbyeFailed("nix profile remove failed");405 return;406 };407 if (ec != 0) {408 output.goodbyeFailed("nix profile remove failed");409 return;410 }411 output.goodbyeDone();412}413414fn channelUpdateCmd(ctx: Ctx) !void {415 output.updateStart(ctx.machine.name);416 _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);417 output.updateDone();418}419420pub fn upgrade(ctx: Ctx) !void {421 output.upgradeStart(ctx.machine.name);422 output.printSubstep("updating channels", .{});423 _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};424 output.printSubstep("rebuilding", .{});425 const start = std.Io.Clock.awake.now(ctx.io);426 const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);427 if (code != 0) {428 output.applyFailed("");429 return error.BuildFailed;430 }431 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());432 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));433 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;434 output.applyDone(gen, elapsed, false);435}436437pub fn log(ctx: Ctx) !void {438 output.logHeader(ctx.machine.name);439 const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {440 441 return;442 };443 defer ctx.gpa.free(content);444 var lines = std.mem.splitScalar(u8, content, '\n');445 while (lines.next()) |line| {446 const t = std.mem.trim(u8, line, " \t\r");447 if (t.len == 0) continue;448 if (t[0] == '{') {449 renderJsonLogLine(ctx.gpa, t);450 } else {451 452 var parts = std.mem.tokenizeScalar(u8, t, '\t');453 const date = parts.next() orelse continue;454 const time = parts.next() orelse "";455 const action = parts.next() orelse "";456 const detail = parts.next() orelse "";457 output.logRow(date, time, action, detail);458 }459 }460}461462463464fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {465 const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {466 output.logRow(line, "", "", ""); 467 return;468 };469 defer parsed.deinit();470 if (parsed.value != .object) return;471 const o = parsed.value.object;472473 const ts = jsonStr(o, "ts");474 const date = if (ts.len >= 10) ts[0..10] else ts;475 const time = if (ts.len >= 16) ts[11..16] else "";476 const action = jsonStr(o, "command");477 const outcome = jsonStr(o, "outcome");478479 var buf: [160]u8 = undefined;480 var detail: []const u8 = outcome;481 if (o.get("gen_after")) |g| {482 if (g == .integer) {483 detail = std.fmt.bufPrint(&buf, "{s} -> gen {d}", .{ outcome, g.integer }) catch outcome;484 }485 }486 output.logRow(date, time, action, detail);487}488489fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {490 if (o.get(key)) |v| {491 if (v == .string) return v.string;492 }493 return "";494}495496pub fn edit(ctx: Ctx) !void {497 const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");498 const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";499 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });500 defer ctx.gpa.free(path);501 output.editOpen(path, ctx.cfg.editor);502 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);503}504505pub fn fmt(ctx: Ctx) !void {506 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});507 defer ctx.gpa.free(path);508 if (ctx.check) {509 const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);510 if (code != 0) output.fmtNeedsFormat() else output.fmtDone();511 return;512 }513 output.fmtStart(path);514 _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);515 output.fmtDone();516}517518pub fn repl(ctx: Ctx) !void {519 output.replStart();520 _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);521}522523pub fn develop(ctx: Ctx) !void {524 if (std.mem.eql(u8, ctx.sub, "show")) {525 _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);526 return;527 }528 const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))529 ctx.args[0]530 else531 null;532 output.developStart(&.{});533 _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);534 output.developDone();535}536537pub fn info(ctx: Ctx) !void {538 output.infoHeader(ctx.machine.name);539 const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");540 defer ctx.gpa.free(nixos_ver);541 output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));542543 const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");544 defer ctx.gpa.free(kernel);545 output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));546547 const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");548 defer ctx.gpa.free(uptime);549 output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));550}551552pub fn boot(ctx: Ctx) !void {553 output.bootHeader(ctx.machine.name);554 const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};555 defer ctx.gpa.free(entries);556 for (entries, 0..) |entry, i| output.bootEntry(entry, i);557}558559pub fn searchCmd(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 const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);563 if (selected) |npkg| try selectAndInstall(ctx, npkg);564}565566pub fn optionCmd(ctx: Ctx) !void {567 const query = if (ctx.args.len > 0) ctx.args[0] else "";568 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);569 _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);570}571572pub fn install(ctx: Ctx) !void {573 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;574575 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);576577 578 const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {579 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});580 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});581 return error.PackageNotFound;582 };583584 if (pkgs.len == 0) {585 586 if (closestPackage(ctx, pkg_name)) |sugg| {587 output.didYouMean(pkg_name, sugg.pname);588 if (output.confirm("")) try selectAndInstall(ctx, sugg);589 return;590 }591 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});592 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});593 return error.PackageNotFound;594 }595596 597 598 var found = pkgs[0];599 for (pkgs) |p| {600 if (std.mem.eql(u8, p.pname, pkg_name)) {601 found = p;602 break;603 }604 }605 try selectAndInstall(ctx, found);606}607608609610611fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {612 if (query.len < 2) return null;613 var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};614 if (candidates.len == 0 and query.len > 2) {615 candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};616 }617 if (candidates.len == 0) return null;618619 var best: ?types.NixPackage = null;620 var best_dist: usize = std.math.maxInt(usize);621 for (candidates) |p| {622 const d = editDistance(query, p.pname);623 if (d > 0 and d < best_dist) {624 best_dist = d;625 best = p;626 }627 }628 629 const threshold = @max(@as(usize, 2), query.len / 3);630 return if (best_dist <= threshold) best else null;631}632633634635fn editDistance(a: []const u8, b: []const u8) usize {636 const n = b.len;637 if (a.len == 0) return n;638 if (n == 0) return a.len;639 if (n + 1 > 128) return std.math.maxInt(usize);640 var prev: [128]usize = undefined;641 var curr: [128]usize = undefined;642 var j: usize = 0;643 while (j <= n) : (j += 1) prev[j] = j;644 var i: usize = 1;645 while (i <= a.len) : (i += 1) {646 curr[0] = i;647 j = 1;648 while (j <= n) : (j += 1) {649 const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;650 curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));651 }652 @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);653 }654 return prev[n];655}656657test "editDistance is case-insensitive Levenshtein" {658 try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));659 try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));660 try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));661 try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));662}663664665666667668fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {669 output.installSelectPrompt(npkg.pname, npkg.version);670671 var choice_buf: [8]u8 = undefined;672 var choice_len: usize = 0;673 while (choice_len < choice_buf.len) {674 const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;675 if (n == 0) break;676 if (choice_buf[choice_len] == '\n') break;677 choice_len += 1;678 }679 const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");680681 if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {682 try profileInstallPkg(ctx, npkg);683 } else if (choice[0] == 's' or choice[0] == 'S') {684 try systemInstallPkg(ctx, npkg);685 } else if (choice[0] == 't' or choice[0] == 'T') {686 try tryPkg(ctx, npkg);687 }688}689690fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {691 output.installStart(npkg.pname, .profile);692 output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});693 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));694 const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);695 if (code != 0) return error.ProcessFailed;696 output.installDone(npkg.pname);697}698699fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {700 const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});701 defer ctx.gpa.free(config_path);702 const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;703 output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);704 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);705 if (ctx.cfg.confirm) {706 if (output.confirm("apply now? ")) {707 try apply(ctx);708 }709 }710}711712fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {713 output.tryStart(npkg.pname);714 output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});715 output.tryExitHint();716 _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);717 output.tryDone();718}719720pub fn remove(ctx: Ctx) !void {721 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;722 output.removeStart(pkg_name);723 const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);724 if (code != 0) return error.ProcessFailed;725 output.done();726}727728pub fn list(ctx: Ctx) !void {729 output.listHeader(ctx.machine.name);730731 732 733 734 if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {735 defer ctx.gpa.free(json);736 output.listSection("profile");737 renderProfileJson(ctx.gpa, json);738 }739740 741 742 if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {743 defer ctx.gpa.free(paths);744 output.blankLine();745 output.listSection("system");746 var lines = std.mem.splitScalar(u8, paths, '\n');747 while (lines.next()) |line| {748 const t = std.mem.trim(u8, line, " \t\r");749 if (t.len == 0) continue;750 const row = pkgFromStorePath(t);751 752 if (row.version.len == 0) continue;753 output.listPkg(row.name, row.version);754 }755 }756}757758const PkgRow = struct { name: []const u8, version: []const u8 };759760761762763764fn pkgFromStorePath(path: []const u8) PkgRow {765 const base = std.fs.path.basename(path);766 const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;767 var i: usize = 0;768 while (i + 1 < after_hash.len) : (i += 1) {769 if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {770 return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };771 }772 }773 return .{ .name = after_hash, .version = "" };774}775776777778779fn stripOutputSuffix(ver: []const u8) []const u8 {780 const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };781 for (suffixes) |s| {782 if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];783 }784 return ver;785}786787test "pkgFromStorePath splits name and version at first dash-digit" {788 const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");789 try std.testing.expectEqualStrings("ripgrep", a.name);790 try std.testing.expectEqualStrings("15.1.0", a.version);791792 const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");793 try std.testing.expectEqualStrings("helix", b.name);794 try std.testing.expectEqualStrings("25.01", b.version);795796 797 const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");798 try std.testing.expectEqualStrings("curl", c.name);799 try std.testing.expectEqualStrings("8.20.0", c.version);800}801802fn firstStorePath(el: std.json.Value) ?[]const u8 {803 if (el != .object) return null;804 const sp = el.object.get("storePaths") orelse return null;805 if (sp != .array or sp.array.items.len == 0) return null;806 const first = sp.array.items[0];807 return if (first == .string) first.string else null;808}809810811812fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {813 const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;814 defer parsed.deinit();815 if (parsed.value != .object) return;816 const elements = parsed.value.object.get("elements") orelse return;817 switch (elements) {818 .object => |obj| {819 var it = obj.iterator();820 while (it.next()) |entry| {821 const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";822 output.listPkg(entry.key_ptr.*, ver);823 }824 },825 .array => |arr| {826 for (arr.items) |el| {827 const path = firstStorePath(el) orelse continue;828 const row = pkgFromStorePath(path);829 output.listPkg(row.name, row.version);830 }831 },832 else => {},833 }834}835836pub fn tryCmd(ctx: Ctx) !void {837 const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;838 const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };839 try tryPkg(ctx, shell_pkg);840}841842843844const home_help = [_][2][]const u8{845 .{ "apply", "apply home manager configuration" },846 .{ "apply --dry", "preview changes" },847 .{ "back", "roll back one generation" },848 .{ "history", "list all generations" },849 .{ "edit", "open home.nix" },850 .{ "check", "validate without applying" },851 .{ "diff", "changes between generations" },852 .{ "packages", "list managed packages" },853};854855const HomeGen = struct {856 number: u32,857 date: []const u8,858 time: []const u8,859 path: []const u8,860};861862863864865fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {866 var gens: std.ArrayList(HomeGen) = .empty;867 var lines = std.mem.splitScalar(u8, out_str, '\n');868 while (lines.next()) |line| {869 const t = std.mem.trim(u8, line, " \t\r");870 if (t.len == 0) continue;871 var it = std.mem.tokenizeAny(u8, t, " \t");872 const date = it.next() orelse continue;873 const time = it.next() orelse continue;874 var number: ?u32 = null;875 var path: []const u8 = "";876 while (it.next()) |tok| {877 if (std.mem.eql(u8, tok, "id")) {878 if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;879 } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {880 path = tok;881 }882 }883 const num = number orelse continue;884 try gens.append(gpa, .{885 .number = num,886 .date = try gpa.dupe(u8, date),887 .time = try gpa.dupe(u8, time),888 .path = try gpa.dupe(u8, path),889 });890 }891 return gens.toOwnedSlice(gpa);892}893894fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {895 for (gens) |g| {896 gpa.free(g.date);897 gpa.free(g.time);898 gpa.free(g.path);899 }900 gpa.free(gens);901}902903test "parseHomeGenerations reads id, date and store path" {904 const a = std.testing.allocator;905 const sample =906 \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation907 \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation908 ;909 const gens = try parseHomeGenerations(a, sample);910 defer freeHomeGens(a, gens);911 try std.testing.expectEqual(@as(usize, 2), gens.len);912 try std.testing.expectEqual(@as(u32, 765), gens[0].number);913 try std.testing.expectEqualStrings("2026-06-01", gens[0].date);914 try std.testing.expectEqualStrings("11:56", gens[0].time);915 try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);916 try std.testing.expectEqual(@as(u32, 764), gens[1].number);917}918919920fn homeCurrentGen(ctx: Ctx) u32 {921 const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;922 defer ctx.gpa.free(out);923 const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;924 defer freeHomeGens(ctx.gpa, gens);925 return if (gens.len > 0) gens[0].number else 0;926}927928pub fn home(ctx: Ctx) !void {929 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))930 return output.subcommandHelp("home", &home_help, null);931932 const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);933 if (mode == .none) {934 output.homeNotInstalled();935 return;936 }937938 939 940 if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);941942 if (mode == .module) {943 output.homeModuleManaged();944 return;945 }946947 return output.subcommandHelp("home", &home_help, null);948}949950fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {951 952 if (mode == .module) {953 output.homeModuleManaged();954 return;955 }956 if (ctx.dry) {957 output.homeApplyDry(ctx.machine.name);958 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);959 if (code != 0) return error.BuildFailed;960 output.homeApplyDryDone();961 return;962 }963964 output.homeApplyStart(ctx.machine.name);965 const flake_ref = exec.homeFlakeRef(ctx.gpa, ctx.io, ctx.environ);966 defer if (flake_ref) |r| ctx.gpa.free(r);967 if (flake_ref) |ref| {968 output.printSubstep("home-manager switch --flake {s}", .{ref});969 } else {970 output.printSubstep("home-manager switch", .{});971 }972973 const start = std.Io.Clock.awake.now(ctx.io);974 const code = if (flake_ref) |ref|975 try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)976 else977 try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);978 if (code != 0) return error.BuildFailed;979980 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());981 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));982 output.homeApplyDone(homeCurrentGen(ctx), elapsed);983}984985986987const service_help = [_][2][]const u8{988 .{ "list", "list running services" },989 .{ "logs <svc>", "show service logs" },990 .{ "status <svc>", "service status" },991 .{ "start <svc>", "start a service" },992 .{ "stop <svc>", "stop a service" },993 .{ "restart <svc>", "restart a service" },994 .{ "enable <svc>", "enable at boot" },995 .{ "disable <svc>", "disable at boot" },996};997998pub fn service(ctx: Ctx) !void {999 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");1000 if (std.mem.eql(u8, ctx.sub, "list")) {1001 output.serviceListHeader(ctx.machine.name);1002 const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1003 defer ctx.gpa.free(svcs);1004 for (svcs) |s| output.serviceRow(s);1005 return;1006 }1007 if (std.mem.eql(u8, ctx.sub, "logs")) {1008 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1009 const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1010 output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1011 _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1012 return;1013 }1014 if (std.mem.eql(u8, ctx.sub, "status")) {1015 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1016 output.serviceVerb("status", name, ctx.machine.name);1017 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1018 return;1019 }1020 1021 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1022 if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1023 if (!output.confirm("")) return;1024 }1025 output.serviceVerb(ctx.sub, name, ctx.machine.name);1026 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1027 output.serviceDone();1028}1029103010311032const flake_help = [_][2][]const u8{1033 .{ "init", "create a new flake.nix" },1034 .{ "update", "update flake inputs" },1035 .{ "update <in>", "update a specific input" },1036 .{ "check", "validate the flake" },1037 .{ "show", "inspect flake outputs" },1038 .{ "lock", "regenerate flake.lock" },1039 .{ "clone <url>", "clone a flake repository" },1040};10411042pub fn flake(ctx: Ctx) !void {1043 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1044 if (std.mem.eql(u8, ctx.sub, "update")) {1045 output.flakeUpdateStart();1046 const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1047 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1048 output.flakeLockWritten();1049 return;1050 }1051 if (std.mem.eql(u8, ctx.sub, "check")) {1052 output.flakeCheckStart();1053 const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1054 if (code == 0) output.flakeValid() else output.checkFailed("");1055 return;1056 }1057 if (std.mem.eql(u8, ctx.sub, "show")) {1058 const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1059 if (json_out) |j| {1060 defer ctx.gpa.free(j);1061 output.flakeShowHeader("flake outputs");1062 1063 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1064 defer parsed.deinit();1065 if (parsed.value == .object) {1066 var it = parsed.value.object.iterator();1067 while (it.next()) |entry| {1068 if (entry.value_ptr.* == .object) {1069 var inner = entry.value_ptr.object.iterator();1070 while (inner.next()) |e2| {1071 const desc = if (e2.value_ptr.* == .object)1072 if (e2.value_ptr.object.get("description")) |d|1073 if (d == .string) d.string else ""1074 else ""1075 else "";1076 output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1077 }1078 }1079 }1080 }1081 }1082 return;1083 }1084 if (std.mem.eql(u8, ctx.sub, "init")) {1085 _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1086 return;1087 }1088 if (std.mem.eql(u8, ctx.sub, "lock")) {1089 _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1090 return;1091 }1092 if (std.mem.eql(u8, ctx.sub, "clone")) {1093 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1094 _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1095 return;1096 }1097}1098109911001101const store_help = [_][2][]const u8{1102 .{ "info", "store size and counts" },1103 .{ "path <attr>", "store path of a package" },1104 .{ "gc", "collect garbage" },1105 .{ "verify", "verify store integrity" },1106 .{ "repair", "repair corrupted paths" },1107};11081109pub fn store(ctx: Ctx) !void {1110 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1111 if (std.mem.eql(u8, ctx.sub, "gc")) {1112 _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1113 return;1114 }1115 if (std.mem.eql(u8, ctx.sub, "verify")) {1116 output.storeVerifyStart();1117 _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1118 return;1119 }1120 if (std.mem.eql(u8, ctx.sub, "repair")) {1121 if (ctx.cfg.confirm and !output.confirm("")) return;1122 output.storeRepairStart();1123 _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1124 return;1125 }1126 if (std.mem.eql(u8, ctx.sub, "info")) {1127 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1128 output.storeInfo(si);1129 return;1130 }1131 if (std.mem.eql(u8, ctx.sub, "path")) {1132 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1133 const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1134 defer ctx.gpa.free(path);1135 output.storePath(path);1136 return;1137 }1138 1139 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1140 output.storeInfo(si);1141}1142114311441145const channel_help = [_][2][]const u8{1146 .{ "list", "list channels" },1147 .{ "add <url> [name]", "add a channel" },1148 .{ "remove <name>", "remove a channel" },1149 .{ "update", "update all channels" },1150};11511152pub fn channel(ctx: Ctx) !void {1153 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1154 1155 if (flakeSystem(ctx)) output.flakeChannelNote();1156 if (std.mem.eql(u8, ctx.sub, "list")) {1157 output.channelListHeader(ctx.machine.name);1158 const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1159 defer ctx.gpa.free(chans);1160 for (chans) |ch| output.channelRow(ch);1161 return;1162 }1163 if (std.mem.eql(u8, ctx.sub, "add")) {1164 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1165 const name = if (ctx.args.len > 1) ctx.args[1] else "";1166 _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1167 output.channelDone();1168 return;1169 }1170 if (std.mem.eql(u8, ctx.sub, "remove")) {1171 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1172 _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1173 output.channelDone();1174 return;1175 }1176 if (std.mem.eql(u8, ctx.sub, "update")) {1177 return channelUpdateCmd(ctx);1178 }1179}1180118111821183pub fn profile(ctx: Ctx) !void {1184 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1185 output.profileListHeader();1186 const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1187 if (out) |o| {1188 defer ctx.gpa.free(o);1189 var lines = std.mem.splitScalar(u8, o, '\n');1190 while (lines.next()) |line| {1191 const t = std.mem.trim(u8, line, " \t\r");1192 if (t.len == 0) continue;1193 output.profileRow(t, "", "");1194 }1195 }1196 return;1197 }1198 if (std.mem.eql(u8, ctx.sub, "install")) {1199 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1200 _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1201 output.done();1202 return;1203 }1204 if (std.mem.eql(u8, ctx.sub, "remove")) {1205 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1206 _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1207 output.done();1208 return;1209 }1210 if (std.mem.eql(u8, ctx.sub, "upgrade")) {1211 _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1212 output.done();1213 return;1214 }1215}1216121712181219const pkg_help = [_][2][]const u8{1220 .{ "why <pkg>", "what pulled it in" },1221 .{ "deps <pkg>", "direct dependencies" },1222 .{ "size <pkg>", "closure size" },1223 .{ "path <pkg>", "store path" },1224 .{ "closure <pkg>", "full closure" },1225};12261227pub fn pkg(ctx: Ctx) !void {1228 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1229 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1230 if (std.mem.eql(u8, ctx.sub, "why")) {1231 _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1232 return;1233 }1234 if (std.mem.eql(u8, ctx.sub, "deps")) {1235 _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);1236 return;1237 }1238 if (std.mem.eql(u8, ctx.sub, "size")) {1239 const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;1240 if (s) |sz| {1241 defer ctx.gpa.free(sz);1242 output.pkgResult("size", sz);1243 }1244 return;1245 }1246 if (std.mem.eql(u8, ctx.sub, "path")) {1247 const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1248 defer ctx.gpa.free(p);1249 output.pkgResult("path", p);1250 return;1251 }1252 if (std.mem.eql(u8, ctx.sub, "closure")) {1253 _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);1254 return;1255 }1256}1257125812591260pub fn why(ctx: Ctx) !void {1261 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1262 _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1263}1264126512661267pub fn pin(ctx: Ctx) !void {1268 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1269 const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1270 exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1271 output.pinDone(input, commit);1272}12731274pub fn unpin(ctx: Ctx) !void {1275 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1276 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1277 output.unpinDone(input);1278}1279128012811282pub fn hash(ctx: Ctx) !void {1283 const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1284 const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1285 defer ctx.gpa.free(h);1286 output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1287}12881289pub fn fetch(ctx: Ctx) !void {1290 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1291 const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1292 defer ctx.gpa.free(h);1293 output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1294}1295129612971298pub fn build(ctx: Ctx) !void {1299 const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1300 output.buildStart(attr orelse "default");1301 const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1302 if (code != 0) return error.BuildFailed;1303 output.buildDone();1304}13051306pub fn runCmd(ctx: Ctx) !void {1307 const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1308 output.runStart(pkg_arg);1309 _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1310}1311131213131314pub fn hello(ctx: Ctx) !void {1315 output.hello(ctx.cfg.machines);1316}1317131813191320pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1321 output.firstRunBanner();1322 output.firstRunNoConfig();13231324 var name_buf: [256]u8 = undefined;1325 var path_buf: [256]u8 = undefined;1326 var local_buf: [256]u8 = undefined;13271328 const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);13291330 1331 1332 1333 const use_flakes = output.firstRunManageType();1334 const config_path = if (use_flakes)1335 output.firstRunPrompt("flake directory", "~/nixos-config", &path_buf)1336 else1337 output.firstRunPrompt("config path", "/etc/nixos", &path_buf);1338 const local_str = output.firstRunPrompt("local", "true", &local_buf);13391340 const conf_path = try config.configPath(gpa, environ);1341 defer gpa.free(conf_path);1342 if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);13431344 1345 const flake_line = if (use_flakes) "flake = true\n" else "";1346 var content_buf: [1024]u8 = undefined;1347 const content = try std.fmt.bufPrint(1348 &content_buf,1349 "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = {s}\n",1350 .{ flake_line, machine_name, config_path, local_str },1351 );13521353 const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1354 errors.error_info.setMessage("could not write {s}", .{conf_path});1355 return error.Internal;1356 };1357 defer file.close(io);1358 file.writePositionalAll(io, content, 0) catch {1359 errors.error_info.setMessage("could not write {s}", .{conf_path});1360 return error.Internal;1361 };13621363 output.firstRunWritten(conf_path);1364}13651366pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1367 1368 1369 1370 config.migrateLegacyConfig(gpa, io, environ);1371 if (config.configPath(gpa, environ)) |conf_path| {1372 defer gpa.free(conf_path);1373 if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1374 f.close(io);1375 } else |_| {1376 try firstRunWizard(gpa, io, environ);1377 errors.error_info.reset();1378 }1379 } else |_| {}13801381 output.setupCheck();1382 const status = exec.checkNixFeatures(gpa, io, environ);1383 output.setupFeatures(status.nix_command, status.flakes);13841385 if (status.allEnabled()) {1386 output.setupAllSet();1387 api.ensureRegistryPinned(gpa, io, environ);1388 return;1389 }13901391 1392 1393 1394 1395 if (exec.isNixOS(io)) {1396 const conf_path = "/etc/nixos/configuration.nix";1397 if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1398 output.setupNixosNeedsRebuild(conf_path);1399 return;1400 }1401 output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1402 if (output.confirmDefaultNo("add it now?")) {1403 if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1404 output.setupNixosWrote(conf_path);1405 } else |_| {1406 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1407 }1408 } else {1409 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1410 }1411 return;1412 }14131414 1415 output.setupEnabling();1416 const path = try exec.enableNixFeatures(gpa, io, environ);1417 defer gpa.free(path);14181419 output.setupDone(path);1420 api.ensureRegistryPinned(gpa, io, environ);1421}1422142314241425fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1426 var ts_buf: [32]u8 = undefined;1427 const ts = nowIso(ctx.io, &ts_buf);1428 var buf: [256]u8 = undefined;1429 const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1430 ts, ctx.machine.name, action, gen,1431 }) catch return;1432 exec.appendNinaLog(ctx.io, ctx.environ, entry);1433}1434143514361437fn nowIso(io: std.Io, buf: []u8) []const u8 {1438 const fallback = "1970-01-01T00:00:00Z";1439 const ns = std.Io.Clock.real.now(io).toNanoseconds();1440 if (ns <= 0) return fallback;1441 const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1442 const es = std.time.epoch.EpochSeconds{ .secs = secs };1443 const ed = es.getEpochDay();1444 const yd = ed.calculateYearDay();1445 const md = yd.calculateMonthDay();1446 const ds = es.getDaySeconds();1447 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", .{1448 yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1449 ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1450 }) catch return fallback;1451}