123const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const config = @import("config.zig");8const output = @import("output.zig");9const exec = @import("exec.zig");10const api = @import("api.zig");11const search_tui = @import("search.zig");12const version = @import("version.zig");1314const UPDATE_URL = "https://kepr.uk/api/nina/releases/latest";1516pub const Ctx = struct {17 gpa: std.mem.Allocator,18 io: std.Io,19 environ: *const std.process.Environ.Map,20 machine: types.Machine,21 cfg: types.NinaConfig,22 args: []const []const u8, 23 sub: []const u8, 24 dry: bool,25 check: bool,26 no_apply: bool,27 all: bool,28 last: u32,29 json: bool,30};3132pub fn apply(ctx: Ctx) !void {33 if (ctx.dry) {34 output.applyDry(ctx.machine.name);35 const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);36 if (code != 0) return error.BuildFailed;37 output.applyDryDone();38 return;39 }40 if (ctx.check) {41 return check(ctx);42 }4344 output.applyStart(ctx.machine.name);45 const start = std.Io.Clock.awake.now(ctx.io);4647 const code = exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa) catch |e| {48 exec.markApplyFailed(ctx.io, ctx.environ);49 output.applyFailed("");50 return e;51 };5253 if (code != 0) {54 exec.markApplyFailed(ctx.io, ctx.environ);55 output.applyFailed("");56 return error.BuildFailed;57 }5859 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());60 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));61 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;62 const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);63 output.applyDone(gen, elapsed, after_failure);64 logAction(ctx, "apply", gen);65}6667pub fn check(ctx: Ctx) !void {68 output.checkStart(ctx.machine.name);69 const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);70 if (code != 0) {71 output.checkFailed("");72 return error.BuildFailed;73 }74 output.checkOk();75}7677pub fn back(ctx: Ctx) !void {78 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);79 defer ctx.gpa.free(gens);8081 var current: u32 = 0;82 for (gens) |g| if (g.current) { current = g.number; };8384 85 86 var prev: u32 = 0;87 var has_prev = false;88 for (gens) |g| {89 if (g.number < current and (!has_prev or g.number > prev)) {90 prev = g.number;91 has_prev = true;92 }93 }94 if (!has_prev) {95 output.alreadyOldest();96 return;97 }9899 output.backStart(ctx.machine.name, current, prev);100 if (ctx.cfg.confirm and !output.confirm("")) return;101102 const code = try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);103 if (code != 0) return error.BuildFailed;104 output.backDone(prev);105}106107pub fn go(ctx: Ctx) !void {108 if (ctx.args.len == 0) return error.Internal;109 const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;110 const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);111112 output.goStart(ctx.machine.name, current, target);113 if (ctx.cfg.confirm and !output.confirm("")) return;114115 const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);116 if (code != 0) return error.ProcessFailed;117 output.generationDone(target);118}119120pub fn history(ctx: Ctx) !void {121 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);122 defer ctx.gpa.free(gens);123 output.historyHeader(ctx.machine.name);124 for (gens) |g| output.historyRow(g);125}126127pub fn genCmd(ctx: Ctx) !void {128 if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);129 if (std.mem.eql(u8, ctx.sub, "current")) {130 const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);131 output.genCurrent(n);132 return;133 }134 if (std.mem.eql(u8, ctx.sub, "delete")) {135 if (ctx.args.len == 0) return error.Internal;136 if (std.mem.eql(u8, ctx.args[0], "old")) {137 if (ctx.cfg.confirm and !output.confirm("")) return;138 _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);139 } else {140 const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;141 if (ctx.cfg.confirm and !output.confirm("")) return;142 _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);143 }144 output.done();145 return;146 }147 return error.Internal;148}149150pub fn clean(ctx: Ctx) !void {151 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);152 defer ctx.gpa.free(gens);153 const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");154 const total: u32 = @intCast(gens.len);155 156 157 const keep: u32 = if (all) 1 else ctx.cfg.generations;158 if (total <= keep) {159 output.cleanNothing(ctx.machine.name, total);160 return;161 }162 output.cleanStart(ctx.machine.name, keep, total);163 if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;164 _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);165 output.cleanDone("?");166}167168pub fn statusCmd(ctx: Ctx) !void {169 output.statusHeader();170 171 172 if (ctx.all and ctx.cfg.machines.len > 0) {173 for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);174 return;175 }176 statusRowFor(ctx, &ctx.machine);177}178179fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {180 181 182 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {183 output.statusRow(machine.name, 0, "", "", false);184 return;185 };186 const st = exec.systemStatus(ctx.gpa, ctx.io, machine);187 defer ctx.gpa.free(st.size);188 defer ctx.gpa.free(st.age);189 output.statusRow(machine.name, gen, st.age, st.size, true);190}191192pub fn diff(ctx: Ctx) !void {193 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);194 defer ctx.gpa.free(gens);195 var current: u32 = 0;196 var prev: u32 = 0;197 for (gens) |g| {198 if (g.current) current = g.number;199 if (!g.current and g.number > prev and g.number < current) prev = g.number;200 }201 if (ctx.args.len >= 2) {202 const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;203 const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;204 output.diffHeader(a, b, ctx.machine.name);205 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;206 } else {207 output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);208 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;209 }210}211212pub fn mood(ctx: Ctx) !void {213 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;214 const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);215 defer ctx.gpa.free(st.size);216 defer ctx.gpa.free(st.age);217 const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");218 defer ctx.gpa.free(state);219 output.mood(ctx.machine.name, state, gen, st.age, st.size);220}221222pub fn doctor(ctx: Ctx) !void {223 output.doctorHeader(ctx.machine.name);224 const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);225 defer ctx.gpa.free(checks);226 var warnings: u32 = 0;227 var failures: u32 = 0;228 for (checks) |ch| {229 output.doctorRow(ch);230 if (ch.status == .warn) warnings += 1;231 if (ch.status == .fail) failures += 1;232 }233 output.doctorSummary(warnings, failures);234}235236237pub fn update(ctx: Ctx) !void {238 output.updateSelfStart();239240 if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {241 output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));242 return error.Internal;243 }244245 const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");246 const source_url = env_url orelse UPDATE_URL;247248 const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {249 error.NetworkError, error.HttpError => {250 output.updateSelfNetworkError();251 return;252 },253 else => return e,254 };255 defer ctx.gpa.free(body);256257 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {258 output.printWarning("could not parse release metadata");259 return;260 };261 defer parsed.deinit();262263 const root = parsed.value;264 if (root != .object) { output.printWarning("malformed release metadata"); return; }265266 const remote_ver = blk: {267 const v = root.object.get("version") orelse { output.printWarning("malformed release metadata"); return; };268 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };269 };270271 if (std.mem.eql(u8, remote_ver, version.VERSION)) {272 output.updateSelfCurrent(version.VERSION);273 return;274 }275276 output.updateSelfAvailable(version.VERSION, remote_ver);277 if (ctx.check) return;278279 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;280 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {281 errors.error_info.setMessage("could not determine install path", .{});282 return error.Internal;283 };284285 286 287 288 289 290 if (std.mem.startsWith(u8, install_path, "/nix/store/")) {291 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);292 defer {293 if (nina_element) |n| ctx.gpa.free(n);294 }295 if (nina_element == null) {296 output.updateSelfNixSystemManaged();297 return;298 }299 const element = nina_element.?;300 output.updateSelfNixManaged(remote_ver);301 if (ctx.cfg.confirm and !output.confirm("")) return;302 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", element }) catch {303 output.updateSelfNixFailed();304 return;305 };306 if (ec != 0) output.updateSelfNixFailed();307 return;308 }309310 const plat_info = blk: {311 const pv = root.object.get("platforms") orelse break :blk null;312 if (pv != .object) break :blk null;313 break :blk pv.object.get(version.PLATFORM);314 };315 if (plat_info == null) { output.updateSelfNoPlatform(version.PLATFORM); return; }316317 const dl_url = blk: {318 const v = plat_info.?.object.get("url") orelse { output.printWarning("malformed release metadata"); return; };319 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };320 };321322 const raw_cksum = blk: {323 if (plat_info.?.object.get("blake3")) |v|324 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };325 if (plat_info.?.object.get("checksum")) |v|326 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };327 output.printWarning("missing checksum in release metadata");328 return;329 };330 const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;331332 if (ctx.cfg.confirm and !output.confirm("")) return;333334 output.updateSelfDownloading(remote_ver, version.PLATFORM);335 const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {336 output.printWarning("download failed — check your connection and try again");337 return;338 };339 defer ctx.gpa.free(tmp_path);340341 output.updateSelfVerifying();342 exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {343 error.ChecksumMismatch => { output.updateSelfChecksumFailed(); return; },344 else => return e,345 };346347 output.updateSelfDone(version.VERSION, remote_ver);348}349350351352353pub fn goodbye(ctx: Ctx) !void {354 output.goodbyeStart();355356 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;357 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {358 errors.error_info.setMessage("could not determine install path", .{});359 return error.Internal;360 };361362 363 if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {364 output.goodbyeFile(install_path);365 if (ctx.cfg.confirm and !output.confirm("")) return;366 std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {367 errors.error_info.setMessage("could not remove {s}", .{install_path});368 return e;369 };370 output.goodbyeDone();371 return;372 }373374 375 376 377 378 379 380 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);381 defer {382 if (nina_element) |n| ctx.gpa.free(n);383 }384 const system_managed = ninaNixExists(ctx);385386 if (nina_element) |element| {387 output.goodbyeNix();388 if (ctx.cfg.confirm and !output.confirm("")) return;389 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", element }) catch {390 output.goodbyeFailed("nix profile remove failed");391 return;392 };393 if (ec != 0) {394 output.goodbyeFailed("nix profile remove failed");395 return;396 }397 }398399 400 401 if (system_managed or nina_element == null) {402 output.goodbyeNixSystemManaged();403 }404405 output.goodbyeDone();406}407408409fn ninaNixExists(ctx: Ctx) bool {410 const home = ctx.environ.get("HOME") orelse return false;411 const path = std.fmt.allocPrint(ctx.gpa, "{s}/nina.nix", .{home}) catch return false;412 defer ctx.gpa.free(path);413 const bytes = std.Io.Dir.readFileAlloc(.cwd(), ctx.io, path, ctx.gpa, .unlimited) catch return false;414 ctx.gpa.free(bytes);415 return true;416}417418fn channelUpdateCmd(ctx: Ctx) !void {419 output.updateStart(ctx.machine.name);420 _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);421 output.updateDone();422}423424pub fn upgrade(ctx: Ctx) !void {425 output.upgradeStart(ctx.machine.name);426 output.printSubstep("updating channels", .{});427 _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};428 output.printSubstep("rebuilding", .{});429 const start = std.Io.Clock.awake.now(ctx.io);430 const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);431 if (code != 0) {432 output.applyFailed("");433 return error.BuildFailed;434 }435 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());436 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));437 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;438 output.applyDone(gen, elapsed, false);439}440441pub fn log(ctx: Ctx) !void {442 output.logHeader(ctx.machine.name);443 const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {444 445 return;446 };447 defer ctx.gpa.free(content);448 var lines = std.mem.splitScalar(u8, content, '\n');449 while (lines.next()) |line| {450 const t = std.mem.trim(u8, line, " \t\r");451 if (t.len == 0) continue;452 if (t[0] == '{') {453 renderJsonLogLine(ctx.gpa, t);454 } else {455 456 var parts = std.mem.tokenizeScalar(u8, t, '\t');457 const date = parts.next() orelse continue;458 const time = parts.next() orelse "";459 const action = parts.next() orelse "";460 const detail = parts.next() orelse "";461 output.logRow(date, time, action, detail);462 }463 }464}465466467468fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {469 const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {470 output.logRow(line, "", "", ""); 471 return;472 };473 defer parsed.deinit();474 if (parsed.value != .object) return;475 const o = parsed.value.object;476477 const ts = jsonStr(o, "ts");478 const date = if (ts.len >= 10) ts[0..10] else ts;479 const time = if (ts.len >= 16) ts[11..16] else "";480 const action = jsonStr(o, "command");481 const outcome = jsonStr(o, "outcome");482483 var buf: [160]u8 = undefined;484 var detail: []const u8 = outcome;485 if (o.get("gen_after")) |g| {486 if (g == .integer) {487 detail = std.fmt.bufPrint(&buf, "{s} -> gen {d}", .{ outcome, g.integer }) catch outcome;488 }489 }490 output.logRow(date, time, action, detail);491}492493fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {494 if (o.get(key)) |v| {495 if (v == .string) return v.string;496 }497 return "";498}499500pub fn edit(ctx: Ctx) !void {501 const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");502 const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";503 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });504 defer ctx.gpa.free(path);505 output.editOpen(path, ctx.cfg.editor);506 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);507}508509pub fn fmt(ctx: Ctx) !void {510 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});511 defer ctx.gpa.free(path);512 if (ctx.check) {513 const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);514 if (code != 0) output.fmtNeedsFormat() else output.fmtDone();515 return;516 }517 output.fmtStart(path);518 _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);519 output.fmtDone();520}521522pub fn repl(ctx: Ctx) !void {523 output.replStart();524 _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);525}526527pub fn develop(ctx: Ctx) !void {528 if (std.mem.eql(u8, ctx.sub, "show")) {529 _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);530 return;531 }532 const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))533 ctx.args[0]534 else535 null;536 output.developStart(&.{});537 _ = try exec.nixDevelop(ctx.io, &ctx.machine, ctx.gpa, run_cmd);538 output.developDone();539}540541pub fn info(ctx: Ctx) !void {542 output.infoHeader(ctx.machine.name);543 const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");544 defer ctx.gpa.free(nixos_ver);545 output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));546547 const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");548 defer ctx.gpa.free(kernel);549 output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));550551 const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");552 defer ctx.gpa.free(uptime);553 output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));554}555556pub fn boot(ctx: Ctx) !void {557 output.bootHeader(ctx.machine.name);558 const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};559 defer ctx.gpa.free(entries);560 for (entries, 0..) |entry, i| output.bootEntry(entry, i);561}562563pub fn searchCmd(ctx: Ctx) !void {564 const query = if (ctx.args.len > 0) ctx.args[0] else "";565 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);566 const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);567 if (selected) |npkg| try selectAndInstall(ctx, npkg);568}569570pub fn optionCmd(ctx: Ctx) !void {571 const query = if (ctx.args.len > 0) ctx.args[0] else "";572 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);573 _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);574}575576pub fn install(ctx: Ctx) !void {577 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;578579 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);580581 582 const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {583 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});584 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});585 return error.PackageNotFound;586 };587588 if (pkgs.len == 0) {589 590 if (closestPackage(ctx, pkg_name)) |sugg| {591 output.didYouMean(pkg_name, sugg.pname);592 if (output.confirm("")) try selectAndInstall(ctx, sugg);593 return;594 }595 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});596 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});597 return error.PackageNotFound;598 }599600 601 602 var found = pkgs[0];603 for (pkgs) |p| {604 if (std.mem.eql(u8, p.pname, pkg_name)) {605 found = p;606 break;607 }608 }609 try selectAndInstall(ctx, found);610}611612613614615fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {616 if (query.len < 2) return null;617 var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};618 if (candidates.len == 0 and query.len > 2) {619 candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};620 }621 if (candidates.len == 0) return null;622623 var best: ?types.NixPackage = null;624 var best_dist: usize = std.math.maxInt(usize);625 for (candidates) |p| {626 const d = editDistance(query, p.pname);627 if (d > 0 and d < best_dist) {628 best_dist = d;629 best = p;630 }631 }632 633 const threshold = @max(@as(usize, 2), query.len / 3);634 return if (best_dist <= threshold) best else null;635}636637638639fn editDistance(a: []const u8, b: []const u8) usize {640 const n = b.len;641 if (a.len == 0) return n;642 if (n == 0) return a.len;643 if (n + 1 > 128) return std.math.maxInt(usize);644 var prev: [128]usize = undefined;645 var curr: [128]usize = undefined;646 var j: usize = 0;647 while (j <= n) : (j += 1) prev[j] = j;648 var i: usize = 1;649 while (i <= a.len) : (i += 1) {650 curr[0] = i;651 j = 1;652 while (j <= n) : (j += 1) {653 const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;654 curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));655 }656 @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);657 }658 return prev[n];659}660661test "editDistance is case-insensitive Levenshtein" {662 try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));663 try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));664 try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));665 try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));666}667668669670671672fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {673 output.installSelectPrompt(npkg.pname, npkg.version);674675 var choice_buf: [8]u8 = undefined;676 var choice_len: usize = 0;677 while (choice_len < choice_buf.len) {678 const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;679 if (n == 0) break;680 if (choice_buf[choice_len] == '\n') break;681 choice_len += 1;682 }683 const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");684685 if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {686 try profileInstallPkg(ctx, npkg);687 } else if (choice[0] == 's' or choice[0] == 'S') {688 try systemInstallPkg(ctx, npkg);689 } else if (choice[0] == 't' or choice[0] == 'T') {690 try tryPkg(ctx, npkg);691 }692}693694fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {695 output.installStart(npkg.pname, .profile);696 output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});697 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));698 const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);699 if (code != 0) return error.ProcessFailed;700 output.installDone(npkg.pname);701}702703fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {704 const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});705 defer ctx.gpa.free(config_path);706 const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;707 output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);708 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);709 if (ctx.cfg.confirm) {710 if (output.confirm("apply now? ")) {711 try apply(ctx);712 }713 }714}715716fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {717 output.tryStart(npkg.pname);718 output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});719 _ = try exec.nixShell(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);720 output.tryDone();721}722723pub fn remove(ctx: Ctx) !void {724 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;725 output.removeStart(pkg_name);726 const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);727 if (code != 0) return error.ProcessFailed;728 output.done();729}730731pub fn list(ctx: Ctx) !void {732 output.listHeader(ctx.machine.name);733734 735 736 737 if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {738 defer ctx.gpa.free(json);739 output.listSection("profile");740 renderProfileJson(ctx.gpa, json);741 }742743 744 745 if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {746 defer ctx.gpa.free(paths);747 output.blankLine();748 output.listSection("system");749 var lines = std.mem.splitScalar(u8, paths, '\n');750 while (lines.next()) |line| {751 const t = std.mem.trim(u8, line, " \t\r");752 if (t.len == 0) continue;753 const row = pkgFromStorePath(t);754 755 if (row.version.len == 0) continue;756 output.listPkg(row.name, row.version);757 }758 }759}760761const PkgRow = struct { name: []const u8, version: []const u8 };762763764765766767fn pkgFromStorePath(path: []const u8) PkgRow {768 const base = std.fs.path.basename(path);769 const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;770 var i: usize = 0;771 while (i + 1 < after_hash.len) : (i += 1) {772 if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {773 return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };774 }775 }776 return .{ .name = after_hash, .version = "" };777}778779780781782fn stripOutputSuffix(ver: []const u8) []const u8 {783 const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };784 for (suffixes) |s| {785 if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];786 }787 return ver;788}789790test "pkgFromStorePath splits name and version at first dash-digit" {791 const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");792 try std.testing.expectEqualStrings("ripgrep", a.name);793 try std.testing.expectEqualStrings("15.1.0", a.version);794795 const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");796 try std.testing.expectEqualStrings("helix", b.name);797 try std.testing.expectEqualStrings("25.01", b.version);798799 800 const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");801 try std.testing.expectEqualStrings("curl", c.name);802 try std.testing.expectEqualStrings("8.20.0", c.version);803}804805fn firstStorePath(el: std.json.Value) ?[]const u8 {806 if (el != .object) return null;807 const sp = el.object.get("storePaths") orelse return null;808 if (sp != .array or sp.array.items.len == 0) return null;809 const first = sp.array.items[0];810 return if (first == .string) first.string else null;811}812813814815fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {816 const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;817 defer parsed.deinit();818 if (parsed.value != .object) return;819 const elements = parsed.value.object.get("elements") orelse return;820 switch (elements) {821 .object => |obj| {822 var it = obj.iterator();823 while (it.next()) |entry| {824 const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";825 output.listPkg(entry.key_ptr.*, ver);826 }827 },828 .array => |arr| {829 for (arr.items) |el| {830 const path = firstStorePath(el) orelse continue;831 const row = pkgFromStorePath(path);832 output.listPkg(row.name, row.version);833 }834 },835 else => {},836 }837}838839pub fn tryCmd(ctx: Ctx) !void {840 const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;841 const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };842 try tryPkg(ctx, shell_pkg);843}844845846847pub fn service(ctx: Ctx) !void {848 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {849 output.serviceListHeader(ctx.machine.name);850 const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine) catch &.{};851 defer ctx.gpa.free(svcs);852 for (svcs) |s| output.serviceRow(s);853 return;854 }855 if (std.mem.eql(u8, ctx.sub, "logs")) {856 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;857 const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");858 output.serviceLogsHeader(name, ctx.last, ctx.machine.name);859 _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow);860 return;861 }862 if (std.mem.eql(u8, ctx.sub, "status")) {863 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;864 output.serviceVerb("status", name, ctx.machine.name);865 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name);866 return;867 }868 869 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;870 if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {871 if (!output.confirm("")) return;872 }873 output.serviceVerb(ctx.sub, name, ctx.machine.name);874 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name);875 output.serviceDone();876}877878879880pub fn flake(ctx: Ctx) !void {881 if (std.mem.eql(u8, ctx.sub, "update")) {882 output.flakeUpdateStart();883 const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;884 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);885 output.flakeLockWritten();886 return;887 }888 if (std.mem.eql(u8, ctx.sub, "check")) {889 output.flakeCheckStart();890 const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);891 if (code == 0) output.flakeValid() else output.checkFailed("");892 return;893 }894 if (std.mem.eql(u8, ctx.sub, "show")) {895 const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;896 if (json_out) |j| {897 defer ctx.gpa.free(j);898 output.flakeShowHeader("flake outputs");899 900 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;901 defer parsed.deinit();902 if (parsed.value == .object) {903 var it = parsed.value.object.iterator();904 while (it.next()) |entry| {905 if (entry.value_ptr.* == .object) {906 var inner = entry.value_ptr.object.iterator();907 while (inner.next()) |e2| {908 const desc = if (e2.value_ptr.* == .object)909 if (e2.value_ptr.object.get("description")) |d|910 if (d == .string) d.string else ""911 else ""912 else "";913 output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);914 }915 }916 }917 }918 }919 return;920 }921 if (std.mem.eql(u8, ctx.sub, "init")) {922 _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);923 return;924 }925 if (std.mem.eql(u8, ctx.sub, "lock")) {926 _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);927 return;928 }929 if (std.mem.eql(u8, ctx.sub, "clone")) {930 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;931 _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);932 return;933 }934}935936937938pub fn store(ctx: Ctx) !void {939 if (std.mem.eql(u8, ctx.sub, "gc")) {940 _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);941 return;942 }943 if (std.mem.eql(u8, ctx.sub, "verify")) {944 output.storeVerifyStart();945 _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);946 return;947 }948 if (std.mem.eql(u8, ctx.sub, "repair")) {949 if (ctx.cfg.confirm and !output.confirm("")) return;950 output.storeRepairStart();951 _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);952 return;953 }954 if (std.mem.eql(u8, ctx.sub, "info")) {955 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);956 output.storeInfo(si);957 return;958 }959 if (std.mem.eql(u8, ctx.sub, "path")) {960 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;961 const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);962 defer ctx.gpa.free(path);963 output.storePath(path);964 return;965 }966 967 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);968 output.storeInfo(si);969}970971972973pub fn channel(ctx: Ctx) !void {974 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {975 output.channelListHeader(ctx.machine.name);976 const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);977 defer ctx.gpa.free(chans);978 for (chans) |ch| output.channelRow(ch);979 return;980 }981 if (std.mem.eql(u8, ctx.sub, "add")) {982 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;983 const name = if (ctx.args.len > 1) ctx.args[1] else "";984 _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);985 output.channelDone();986 return;987 }988 if (std.mem.eql(u8, ctx.sub, "remove")) {989 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;990 _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);991 output.channelDone();992 return;993 }994 if (std.mem.eql(u8, ctx.sub, "update")) {995 return channelUpdateCmd(ctx);996 }997}99899910001001pub fn profile(ctx: Ctx) !void {1002 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1003 output.profileListHeader();1004 const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1005 if (out) |o| {1006 defer ctx.gpa.free(o);1007 var lines = std.mem.splitScalar(u8, o, '\n');1008 while (lines.next()) |line| {1009 const t = std.mem.trim(u8, line, " \t\r");1010 if (t.len == 0) continue;1011 output.profileRow(t, "", "");1012 }1013 }1014 return;1015 }1016 if (std.mem.eql(u8, ctx.sub, "install")) {1017 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1018 _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1019 output.done();1020 return;1021 }1022 if (std.mem.eql(u8, ctx.sub, "remove")) {1023 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1024 _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1025 output.done();1026 return;1027 }1028 if (std.mem.eql(u8, ctx.sub, "upgrade")) {1029 _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1030 output.done();1031 return;1032 }1033}1034103510361037pub fn pkg(ctx: Ctx) !void {1038 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1039 if (std.mem.eql(u8, ctx.sub, "why")) {1040 _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1041 return;1042 }1043 if (std.mem.eql(u8, ctx.sub, "deps")) {1044 _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);1045 return;1046 }1047 if (std.mem.eql(u8, ctx.sub, "size")) {1048 const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;1049 if (s) |sz| {1050 defer ctx.gpa.free(sz);1051 output.pkgResult("size", sz);1052 }1053 return;1054 }1055 if (std.mem.eql(u8, ctx.sub, "path")) {1056 const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1057 defer ctx.gpa.free(p);1058 output.pkgResult("path", p);1059 return;1060 }1061 if (std.mem.eql(u8, ctx.sub, "closure")) {1062 _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);1063 return;1064 }1065}1066106710681069pub fn pin(ctx: Ctx) !void {1070 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1071 const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1072 exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1073 output.pinDone(input, commit);1074}10751076pub fn unpin(ctx: Ctx) !void {1077 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1078 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1079 output.unpinDone(input);1080}1081108210831084pub fn hash(ctx: Ctx) !void {1085 const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1086 const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1087 defer ctx.gpa.free(h);1088 output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1089}10901091pub fn fetch(ctx: Ctx) !void {1092 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1093 const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1094 defer ctx.gpa.free(h);1095 output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1096}1097109810991100pub fn build(ctx: Ctx) !void {1101 const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1102 output.buildStart(attr orelse "default");1103 const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1104 if (code != 0) return error.BuildFailed;1105 output.buildDone();1106}11071108pub fn runCmd(ctx: Ctx) !void {1109 const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1110 output.runStart(pkg_arg);1111 _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1112}1113111411151116pub fn hello(ctx: Ctx) !void {1117 output.hello(ctx.cfg.machines);1118}11191120pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1121 output.setupCheck();1122 const status = exec.checkNixFeatures(gpa, io, environ);1123 output.setupFeatures(status.nix_command, status.flakes);11241125 if (status.allEnabled()) {1126 output.setupAllSet();1127 api.ensureRegistryPinned(gpa, io, environ);1128 return;1129 }11301131 1132 1133 1134 1135 if (exec.isNixOS(io)) {1136 const conf_path = "/etc/nixos/configuration.nix";1137 if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1138 output.setupNixosNeedsRebuild(conf_path);1139 return;1140 }1141 output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1142 if (output.confirmDefaultNo("add it now?")) {1143 if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1144 output.setupNixosWrote(conf_path);1145 } else |_| {1146 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1147 }1148 } else {1149 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1150 }1151 return;1152 }11531154 1155 output.setupEnabling();1156 const path = try exec.enableNixFeatures(gpa, io, environ);1157 defer gpa.free(path);11581159 output.setupDone(path);1160 api.ensureRegistryPinned(gpa, io, environ);1161}1162116311641165fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1166 var ts_buf: [32]u8 = undefined;1167 const ts = nowIso(ctx.io, &ts_buf);1168 var buf: [256]u8 = undefined;1169 const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1170 ts, ctx.machine.name, action, gen,1171 }) catch return;1172 exec.appendNinaLog(ctx.io, ctx.environ, entry);1173}1174117511761177fn nowIso(io: std.Io, buf: []u8) []const u8 {1178 const fallback = "1970-01-01T00:00:00Z";1179 const ns = std.Io.Clock.real.now(io).toNanoseconds();1180 if (ns <= 0) return fallback;1181 const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1182 const es = std.time.epoch.EpochSeconds{ .secs = secs };1183 const ed = es.getEpochDay();1184 const yd = ed.calculateYearDay();1185 const md = yd.calculateMonthDay();1186 const ds = es.getDaySeconds();1187 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", .{1188 yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1189 ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1190 }) catch return fallback;1191}