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);941 942 if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);943944 if (mode == .module) {945 output.homeModuleManaged();946 return;947 }948949 if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);950 if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);951 if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);952 if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);953954 return output.subcommandHelp("home", &home_help, null);955}956957fn homeDiff(ctx: Ctx) !void {958 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);959 defer ctx.gpa.free(out);960 const gens = try parseHomeGenerations(ctx.gpa, out);961 defer freeHomeGens(ctx.gpa, gens);962963 964 if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {965 output.homeNothingToDiff();966 return;967 }968 const newer = gens[0];969 const older = gens[1];970 output.homeDiffHeader(older.number, newer.number, ctx.machine.name);971 if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)972 return error.ProcessFailed;973}974975fn homeCheck(ctx: Ctx) !void {976 output.homeCheckStart(ctx.machine.name);977 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);978 if (code != 0) {979 output.checkFailed("");980 return error.BuildFailed;981 }982 output.homeCheckOk();983}984985fn homeEdit(ctx: Ctx) !void {986 987 988 const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {989 errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});990 return error.ConfigNotFound;991 };992 defer ctx.gpa.free(path);993 output.homeEditOpen(path, ctx.cfg.editor);994 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);995}996997fn homeHistory(ctx: Ctx) !void {998 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);999 defer ctx.gpa.free(out);1000 const gens = try parseHomeGenerations(ctx.gpa, out);1001 defer freeHomeGens(ctx.gpa, gens);1002 output.homeHistoryHeader(ctx.machine.name);1003 1004 for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1005}10061007fn homeBack(ctx: Ctx) !void {1008 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1009 defer ctx.gpa.free(out);1010 const gens = try parseHomeGenerations(ctx.gpa, out);1011 defer freeHomeGens(ctx.gpa, gens);10121013 1014 if (gens.len < 2) {1015 output.alreadyOldest();1016 return;1017 }1018 const current = gens[0].number;1019 const prev = gens[1].number;10201021 output.homeBackStart(ctx.machine.name, current, prev);1022 if (ctx.cfg.confirm and !output.confirm("")) return;1023 const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1024 if (code != 0) return error.BuildFailed;1025 output.homeBackDone(prev);1026}10271028fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1029 1030 if (mode == .module) {1031 output.homeModuleManaged();1032 return;1033 }1034 if (ctx.dry) {1035 output.homeApplyDry(ctx.machine.name);1036 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1037 if (code != 0) return error.BuildFailed;1038 output.homeApplyDryDone();1039 return;1040 }10411042 output.homeApplyStart(ctx.machine.name);1043 const flake_ref = exec.homeFlakeRef(ctx.gpa, ctx.io, ctx.environ);1044 defer if (flake_ref) |r| ctx.gpa.free(r);1045 if (flake_ref) |ref| {1046 output.printSubstep("home-manager switch --flake {s}", .{ref});1047 } else {1048 output.printSubstep("home-manager switch", .{});1049 }10501051 const start = std.Io.Clock.awake.now(ctx.io);1052 const code = if (flake_ref) |ref|1053 try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)1054 else1055 try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1056 if (code != 0) return error.BuildFailed;10571058 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1059 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1060 output.homeApplyDone(homeCurrentGen(ctx), elapsed);1061}1062106310641065const service_help = [_][2][]const u8{1066 .{ "list", "list running services" },1067 .{ "logs <svc>", "show service logs" },1068 .{ "status <svc>", "service status" },1069 .{ "start <svc>", "start a service" },1070 .{ "stop <svc>", "stop a service" },1071 .{ "restart <svc>", "restart a service" },1072 .{ "enable <svc>", "enable at boot" },1073 .{ "disable <svc>", "disable at boot" },1074};10751076pub fn service(ctx: Ctx) !void {1077 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");1078 if (std.mem.eql(u8, ctx.sub, "list")) {1079 output.serviceListHeader(ctx.machine.name);1080 const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1081 defer ctx.gpa.free(svcs);1082 for (svcs) |s| output.serviceRow(s);1083 return;1084 }1085 if (std.mem.eql(u8, ctx.sub, "logs")) {1086 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1087 const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1088 output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1089 _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1090 return;1091 }1092 if (std.mem.eql(u8, ctx.sub, "status")) {1093 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1094 output.serviceVerb("status", name, ctx.machine.name);1095 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1096 return;1097 }1098 1099 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1100 if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1101 if (!output.confirm("")) return;1102 }1103 output.serviceVerb(ctx.sub, name, ctx.machine.name);1104 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1105 output.serviceDone();1106}1107110811091110const flake_help = [_][2][]const u8{1111 .{ "init", "create a new flake.nix" },1112 .{ "update", "update flake inputs" },1113 .{ "update <in>", "update a specific input" },1114 .{ "check", "validate the flake" },1115 .{ "show", "inspect flake outputs" },1116 .{ "lock", "regenerate flake.lock" },1117 .{ "clone <url>", "clone a flake repository" },1118};11191120pub fn flake(ctx: Ctx) !void {1121 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1122 if (std.mem.eql(u8, ctx.sub, "update")) {1123 output.flakeUpdateStart();1124 const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1125 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1126 output.flakeLockWritten();1127 return;1128 }1129 if (std.mem.eql(u8, ctx.sub, "check")) {1130 output.flakeCheckStart();1131 const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1132 if (code == 0) output.flakeValid() else output.checkFailed("");1133 return;1134 }1135 if (std.mem.eql(u8, ctx.sub, "show")) {1136 const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1137 if (json_out) |j| {1138 defer ctx.gpa.free(j);1139 output.flakeShowHeader("flake outputs");1140 1141 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1142 defer parsed.deinit();1143 if (parsed.value == .object) {1144 var it = parsed.value.object.iterator();1145 while (it.next()) |entry| {1146 if (entry.value_ptr.* == .object) {1147 var inner = entry.value_ptr.object.iterator();1148 while (inner.next()) |e2| {1149 const desc = if (e2.value_ptr.* == .object)1150 if (e2.value_ptr.object.get("description")) |d|1151 if (d == .string) d.string else ""1152 else ""1153 else "";1154 output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1155 }1156 }1157 }1158 }1159 }1160 return;1161 }1162 if (std.mem.eql(u8, ctx.sub, "init")) {1163 _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1164 return;1165 }1166 if (std.mem.eql(u8, ctx.sub, "lock")) {1167 _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1168 return;1169 }1170 if (std.mem.eql(u8, ctx.sub, "clone")) {1171 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1172 _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1173 return;1174 }1175}1176117711781179const store_help = [_][2][]const u8{1180 .{ "info", "store size and counts" },1181 .{ "path <attr>", "store path of a package" },1182 .{ "gc", "collect garbage" },1183 .{ "verify", "verify store integrity" },1184 .{ "repair", "repair corrupted paths" },1185};11861187pub fn store(ctx: Ctx) !void {1188 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1189 if (std.mem.eql(u8, ctx.sub, "gc")) {1190 _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1191 return;1192 }1193 if (std.mem.eql(u8, ctx.sub, "verify")) {1194 output.storeVerifyStart();1195 _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1196 return;1197 }1198 if (std.mem.eql(u8, ctx.sub, "repair")) {1199 if (ctx.cfg.confirm and !output.confirm("")) return;1200 output.storeRepairStart();1201 _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1202 return;1203 }1204 if (std.mem.eql(u8, ctx.sub, "info")) {1205 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1206 output.storeInfo(si);1207 return;1208 }1209 if (std.mem.eql(u8, ctx.sub, "path")) {1210 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1211 const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1212 defer ctx.gpa.free(path);1213 output.storePath(path);1214 return;1215 }1216 1217 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1218 output.storeInfo(si);1219}1220122112221223const channel_help = [_][2][]const u8{1224 .{ "list", "list channels" },1225 .{ "add <url> [name]", "add a channel" },1226 .{ "remove <name>", "remove a channel" },1227 .{ "update", "update all channels" },1228};12291230pub fn channel(ctx: Ctx) !void {1231 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1232 1233 if (flakeSystem(ctx)) output.flakeChannelNote();1234 if (std.mem.eql(u8, ctx.sub, "list")) {1235 output.channelListHeader(ctx.machine.name);1236 const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1237 defer ctx.gpa.free(chans);1238 for (chans) |ch| output.channelRow(ch);1239 return;1240 }1241 if (std.mem.eql(u8, ctx.sub, "add")) {1242 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1243 const name = if (ctx.args.len > 1) ctx.args[1] else "";1244 _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1245 output.channelDone();1246 return;1247 }1248 if (std.mem.eql(u8, ctx.sub, "remove")) {1249 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1250 _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1251 output.channelDone();1252 return;1253 }1254 if (std.mem.eql(u8, ctx.sub, "update")) {1255 return channelUpdateCmd(ctx);1256 }1257}1258125912601261pub fn profile(ctx: Ctx) !void {1262 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1263 output.profileListHeader();1264 const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1265 if (out) |o| {1266 defer ctx.gpa.free(o);1267 var lines = std.mem.splitScalar(u8, o, '\n');1268 while (lines.next()) |line| {1269 const t = std.mem.trim(u8, line, " \t\r");1270 if (t.len == 0) continue;1271 output.profileRow(t, "", "");1272 }1273 }1274 return;1275 }1276 if (std.mem.eql(u8, ctx.sub, "install")) {1277 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1278 _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1279 output.done();1280 return;1281 }1282 if (std.mem.eql(u8, ctx.sub, "remove")) {1283 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1284 _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1285 output.done();1286 return;1287 }1288 if (std.mem.eql(u8, ctx.sub, "upgrade")) {1289 _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1290 output.done();1291 return;1292 }1293}1294129512961297const pkg_help = [_][2][]const u8{1298 .{ "why <pkg>", "what pulled it in" },1299 .{ "deps <pkg>", "direct dependencies" },1300 .{ "size <pkg>", "closure size" },1301 .{ "path <pkg>", "store path" },1302 .{ "closure <pkg>", "full closure" },1303};13041305pub fn pkg(ctx: Ctx) !void {1306 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1307 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1308 if (std.mem.eql(u8, ctx.sub, "why")) {1309 _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1310 return;1311 }1312 if (std.mem.eql(u8, ctx.sub, "deps")) {1313 _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);1314 return;1315 }1316 if (std.mem.eql(u8, ctx.sub, "size")) {1317 const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;1318 if (s) |sz| {1319 defer ctx.gpa.free(sz);1320 output.pkgResult("size", sz);1321 }1322 return;1323 }1324 if (std.mem.eql(u8, ctx.sub, "path")) {1325 const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1326 defer ctx.gpa.free(p);1327 output.pkgResult("path", p);1328 return;1329 }1330 if (std.mem.eql(u8, ctx.sub, "closure")) {1331 _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);1332 return;1333 }1334}1335133613371338pub fn why(ctx: Ctx) !void {1339 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1340 _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1341}1342134313441345pub fn pin(ctx: Ctx) !void {1346 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1347 const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1348 exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1349 output.pinDone(input, commit);1350}13511352pub fn unpin(ctx: Ctx) !void {1353 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1354 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1355 output.unpinDone(input);1356}1357135813591360pub fn hash(ctx: Ctx) !void {1361 const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1362 const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1363 defer ctx.gpa.free(h);1364 output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1365}13661367pub fn fetch(ctx: Ctx) !void {1368 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1369 const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1370 defer ctx.gpa.free(h);1371 output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1372}1373137413751376pub fn build(ctx: Ctx) !void {1377 const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1378 output.buildStart(attr orelse "default");1379 const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1380 if (code != 0) return error.BuildFailed;1381 output.buildDone();1382}13831384pub fn runCmd(ctx: Ctx) !void {1385 const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1386 output.runStart(pkg_arg);1387 _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1388}1389139013911392pub fn hello(ctx: Ctx) !void {1393 output.hello(ctx.cfg.machines);1394}1395139613971398pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1399 output.firstRunBanner();1400 output.firstRunNoConfig();14011402 var name_buf: [256]u8 = undefined;1403 var path_buf: [256]u8 = undefined;1404 var local_buf: [256]u8 = undefined;14051406 const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);14071408 1409 1410 1411 const use_flakes = output.firstRunManageType();1412 const config_path = if (use_flakes)1413 output.firstRunPrompt("flake directory", "~/nixos-config", &path_buf)1414 else1415 output.firstRunPrompt("config path", "/etc/nixos", &path_buf);1416 const local_str = output.firstRunPrompt("local", "true", &local_buf);14171418 const conf_path = try config.configPath(gpa, environ);1419 defer gpa.free(conf_path);1420 if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);14211422 1423 const flake_line = if (use_flakes) "flake = true\n" else "";1424 var content_buf: [1024]u8 = undefined;1425 const content = try std.fmt.bufPrint(1426 &content_buf,1427 "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = {s}\n",1428 .{ flake_line, machine_name, config_path, local_str },1429 );14301431 const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1432 errors.error_info.setMessage("could not write {s}", .{conf_path});1433 return error.Internal;1434 };1435 defer file.close(io);1436 file.writePositionalAll(io, content, 0) catch {1437 errors.error_info.setMessage("could not write {s}", .{conf_path});1438 return error.Internal;1439 };14401441 output.firstRunWritten(conf_path);1442}14431444pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1445 1446 1447 1448 config.migrateLegacyConfig(gpa, io, environ);1449 if (config.configPath(gpa, environ)) |conf_path| {1450 defer gpa.free(conf_path);1451 if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1452 f.close(io);1453 } else |_| {1454 try firstRunWizard(gpa, io, environ);1455 errors.error_info.reset();1456 }1457 } else |_| {}14581459 output.setupCheck();1460 const status = exec.checkNixFeatures(gpa, io, environ);1461 output.setupFeatures(status.nix_command, status.flakes);14621463 if (status.allEnabled()) {1464 output.setupAllSet();1465 api.ensureRegistryPinned(gpa, io, environ);1466 return;1467 }14681469 1470 1471 1472 1473 if (exec.isNixOS(io)) {1474 const conf_path = "/etc/nixos/configuration.nix";1475 if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1476 output.setupNixosNeedsRebuild(conf_path);1477 return;1478 }1479 output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1480 if (output.confirmDefaultNo("add it now?")) {1481 if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1482 output.setupNixosWrote(conf_path);1483 } else |_| {1484 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1485 }1486 } else {1487 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1488 }1489 return;1490 }14911492 1493 output.setupEnabling();1494 const path = try exec.enableNixFeatures(gpa, io, environ);1495 defer gpa.free(path);14961497 output.setupDone(path);1498 api.ensureRegistryPinned(gpa, io, environ);1499}1500150115021503fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1504 var ts_buf: [32]u8 = undefined;1505 const ts = nowIso(ctx.io, &ts_buf);1506 var buf: [256]u8 = undefined;1507 const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1508 ts, ctx.machine.name, action, gen,1509 }) catch return;1510 exec.appendNinaLog(ctx.io, ctx.environ, entry);1511}1512151315141515fn nowIso(io: std.Io, buf: []u8) []const u8 {1516 const fallback = "1970-01-01T00:00:00Z";1517 const ns = std.Io.Clock.real.now(io).toNanoseconds();1518 if (ns <= 0) return fallback;1519 const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1520 const es = std.time.epoch.EpochSeconds{ .secs = secs };1521 const ed = es.getEpochDay();1522 const yd = ed.calculateYearDay();1523 const md = yd.calculateMonthDay();1524 const ds = es.getDaySeconds();1525 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", .{1526 yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1527 ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1528 }) catch return fallback;1529}