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);952953 return output.subcommandHelp("home", &home_help, null);954}955956fn homeCheck(ctx: Ctx) !void {957 output.homeCheckStart(ctx.machine.name);958 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);959 if (code != 0) {960 output.checkFailed("");961 return error.BuildFailed;962 }963 output.homeCheckOk();964}965966fn homeEdit(ctx: Ctx) !void {967 968 969 const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {970 errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});971 return error.ConfigNotFound;972 };973 defer ctx.gpa.free(path);974 output.homeEditOpen(path, ctx.cfg.editor);975 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);976}977978fn homeHistory(ctx: Ctx) !void {979 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);980 defer ctx.gpa.free(out);981 const gens = try parseHomeGenerations(ctx.gpa, out);982 defer freeHomeGens(ctx.gpa, gens);983 output.homeHistoryHeader(ctx.machine.name);984 985 for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);986}987988fn homeBack(ctx: Ctx) !void {989 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);990 defer ctx.gpa.free(out);991 const gens = try parseHomeGenerations(ctx.gpa, out);992 defer freeHomeGens(ctx.gpa, gens);993994 995 if (gens.len < 2) {996 output.alreadyOldest();997 return;998 }999 const current = gens[0].number;1000 const prev = gens[1].number;10011002 output.homeBackStart(ctx.machine.name, current, prev);1003 if (ctx.cfg.confirm and !output.confirm("")) return;1004 const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1005 if (code != 0) return error.BuildFailed;1006 output.homeBackDone(prev);1007}10081009fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1010 1011 if (mode == .module) {1012 output.homeModuleManaged();1013 return;1014 }1015 if (ctx.dry) {1016 output.homeApplyDry(ctx.machine.name);1017 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1018 if (code != 0) return error.BuildFailed;1019 output.homeApplyDryDone();1020 return;1021 }10221023 output.homeApplyStart(ctx.machine.name);1024 const flake_ref = exec.homeFlakeRef(ctx.gpa, ctx.io, ctx.environ);1025 defer if (flake_ref) |r| ctx.gpa.free(r);1026 if (flake_ref) |ref| {1027 output.printSubstep("home-manager switch --flake {s}", .{ref});1028 } else {1029 output.printSubstep("home-manager switch", .{});1030 }10311032 const start = std.Io.Clock.awake.now(ctx.io);1033 const code = if (flake_ref) |ref|1034 try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)1035 else1036 try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1037 if (code != 0) return error.BuildFailed;10381039 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1040 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1041 output.homeApplyDone(homeCurrentGen(ctx), elapsed);1042}1043104410451046const service_help = [_][2][]const u8{1047 .{ "list", "list running services" },1048 .{ "logs <svc>", "show service logs" },1049 .{ "status <svc>", "service status" },1050 .{ "start <svc>", "start a service" },1051 .{ "stop <svc>", "stop a service" },1052 .{ "restart <svc>", "restart a service" },1053 .{ "enable <svc>", "enable at boot" },1054 .{ "disable <svc>", "disable at boot" },1055};10561057pub fn service(ctx: Ctx) !void {1058 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");1059 if (std.mem.eql(u8, ctx.sub, "list")) {1060 output.serviceListHeader(ctx.machine.name);1061 const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1062 defer ctx.gpa.free(svcs);1063 for (svcs) |s| output.serviceRow(s);1064 return;1065 }1066 if (std.mem.eql(u8, ctx.sub, "logs")) {1067 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1068 const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1069 output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1070 _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1071 return;1072 }1073 if (std.mem.eql(u8, ctx.sub, "status")) {1074 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1075 output.serviceVerb("status", name, ctx.machine.name);1076 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1077 return;1078 }1079 1080 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1081 if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1082 if (!output.confirm("")) return;1083 }1084 output.serviceVerb(ctx.sub, name, ctx.machine.name);1085 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1086 output.serviceDone();1087}1088108910901091const flake_help = [_][2][]const u8{1092 .{ "init", "create a new flake.nix" },1093 .{ "update", "update flake inputs" },1094 .{ "update <in>", "update a specific input" },1095 .{ "check", "validate the flake" },1096 .{ "show", "inspect flake outputs" },1097 .{ "lock", "regenerate flake.lock" },1098 .{ "clone <url>", "clone a flake repository" },1099};11001101pub fn flake(ctx: Ctx) !void {1102 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1103 if (std.mem.eql(u8, ctx.sub, "update")) {1104 output.flakeUpdateStart();1105 const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1106 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1107 output.flakeLockWritten();1108 return;1109 }1110 if (std.mem.eql(u8, ctx.sub, "check")) {1111 output.flakeCheckStart();1112 const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1113 if (code == 0) output.flakeValid() else output.checkFailed("");1114 return;1115 }1116 if (std.mem.eql(u8, ctx.sub, "show")) {1117 const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1118 if (json_out) |j| {1119 defer ctx.gpa.free(j);1120 output.flakeShowHeader("flake outputs");1121 1122 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1123 defer parsed.deinit();1124 if (parsed.value == .object) {1125 var it = parsed.value.object.iterator();1126 while (it.next()) |entry| {1127 if (entry.value_ptr.* == .object) {1128 var inner = entry.value_ptr.object.iterator();1129 while (inner.next()) |e2| {1130 const desc = if (e2.value_ptr.* == .object)1131 if (e2.value_ptr.object.get("description")) |d|1132 if (d == .string) d.string else ""1133 else ""1134 else "";1135 output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1136 }1137 }1138 }1139 }1140 }1141 return;1142 }1143 if (std.mem.eql(u8, ctx.sub, "init")) {1144 _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1145 return;1146 }1147 if (std.mem.eql(u8, ctx.sub, "lock")) {1148 _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1149 return;1150 }1151 if (std.mem.eql(u8, ctx.sub, "clone")) {1152 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1153 _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1154 return;1155 }1156}1157115811591160const store_help = [_][2][]const u8{1161 .{ "info", "store size and counts" },1162 .{ "path <attr>", "store path of a package" },1163 .{ "gc", "collect garbage" },1164 .{ "verify", "verify store integrity" },1165 .{ "repair", "repair corrupted paths" },1166};11671168pub fn store(ctx: Ctx) !void {1169 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1170 if (std.mem.eql(u8, ctx.sub, "gc")) {1171 _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1172 return;1173 }1174 if (std.mem.eql(u8, ctx.sub, "verify")) {1175 output.storeVerifyStart();1176 _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1177 return;1178 }1179 if (std.mem.eql(u8, ctx.sub, "repair")) {1180 if (ctx.cfg.confirm and !output.confirm("")) return;1181 output.storeRepairStart();1182 _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1183 return;1184 }1185 if (std.mem.eql(u8, ctx.sub, "info")) {1186 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1187 output.storeInfo(si);1188 return;1189 }1190 if (std.mem.eql(u8, ctx.sub, "path")) {1191 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1192 const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1193 defer ctx.gpa.free(path);1194 output.storePath(path);1195 return;1196 }1197 1198 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1199 output.storeInfo(si);1200}1201120212031204const channel_help = [_][2][]const u8{1205 .{ "list", "list channels" },1206 .{ "add <url> [name]", "add a channel" },1207 .{ "remove <name>", "remove a channel" },1208 .{ "update", "update all channels" },1209};12101211pub fn channel(ctx: Ctx) !void {1212 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1213 1214 if (flakeSystem(ctx)) output.flakeChannelNote();1215 if (std.mem.eql(u8, ctx.sub, "list")) {1216 output.channelListHeader(ctx.machine.name);1217 const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1218 defer ctx.gpa.free(chans);1219 for (chans) |ch| output.channelRow(ch);1220 return;1221 }1222 if (std.mem.eql(u8, ctx.sub, "add")) {1223 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1224 const name = if (ctx.args.len > 1) ctx.args[1] else "";1225 _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1226 output.channelDone();1227 return;1228 }1229 if (std.mem.eql(u8, ctx.sub, "remove")) {1230 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1231 _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1232 output.channelDone();1233 return;1234 }1235 if (std.mem.eql(u8, ctx.sub, "update")) {1236 return channelUpdateCmd(ctx);1237 }1238}1239124012411242pub fn profile(ctx: Ctx) !void {1243 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1244 output.profileListHeader();1245 const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1246 if (out) |o| {1247 defer ctx.gpa.free(o);1248 var lines = std.mem.splitScalar(u8, o, '\n');1249 while (lines.next()) |line| {1250 const t = std.mem.trim(u8, line, " \t\r");1251 if (t.len == 0) continue;1252 output.profileRow(t, "", "");1253 }1254 }1255 return;1256 }1257 if (std.mem.eql(u8, ctx.sub, "install")) {1258 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1259 _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1260 output.done();1261 return;1262 }1263 if (std.mem.eql(u8, ctx.sub, "remove")) {1264 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1265 _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1266 output.done();1267 return;1268 }1269 if (std.mem.eql(u8, ctx.sub, "upgrade")) {1270 _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1271 output.done();1272 return;1273 }1274}1275127612771278const pkg_help = [_][2][]const u8{1279 .{ "why <pkg>", "what pulled it in" },1280 .{ "deps <pkg>", "direct dependencies" },1281 .{ "size <pkg>", "closure size" },1282 .{ "path <pkg>", "store path" },1283 .{ "closure <pkg>", "full closure" },1284};12851286pub fn pkg(ctx: Ctx) !void {1287 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1288 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1289 if (std.mem.eql(u8, ctx.sub, "why")) {1290 _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1291 return;1292 }1293 if (std.mem.eql(u8, ctx.sub, "deps")) {1294 _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);1295 return;1296 }1297 if (std.mem.eql(u8, ctx.sub, "size")) {1298 const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;1299 if (s) |sz| {1300 defer ctx.gpa.free(sz);1301 output.pkgResult("size", sz);1302 }1303 return;1304 }1305 if (std.mem.eql(u8, ctx.sub, "path")) {1306 const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1307 defer ctx.gpa.free(p);1308 output.pkgResult("path", p);1309 return;1310 }1311 if (std.mem.eql(u8, ctx.sub, "closure")) {1312 _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);1313 return;1314 }1315}1316131713181319pub fn why(ctx: Ctx) !void {1320 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1321 _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1322}1323132413251326pub fn pin(ctx: Ctx) !void {1327 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1328 const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1329 exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1330 output.pinDone(input, commit);1331}13321333pub fn unpin(ctx: Ctx) !void {1334 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1335 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1336 output.unpinDone(input);1337}1338133913401341pub fn hash(ctx: Ctx) !void {1342 const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1343 const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1344 defer ctx.gpa.free(h);1345 output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1346}13471348pub fn fetch(ctx: Ctx) !void {1349 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1350 const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1351 defer ctx.gpa.free(h);1352 output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1353}1354135513561357pub fn build(ctx: Ctx) !void {1358 const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1359 output.buildStart(attr orelse "default");1360 const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1361 if (code != 0) return error.BuildFailed;1362 output.buildDone();1363}13641365pub fn runCmd(ctx: Ctx) !void {1366 const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1367 output.runStart(pkg_arg);1368 _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1369}1370137113721373pub fn hello(ctx: Ctx) !void {1374 output.hello(ctx.cfg.machines);1375}1376137713781379pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1380 output.firstRunBanner();1381 output.firstRunNoConfig();13821383 var name_buf: [256]u8 = undefined;1384 var path_buf: [256]u8 = undefined;1385 var local_buf: [256]u8 = undefined;13861387 const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);13881389 1390 1391 1392 const use_flakes = output.firstRunManageType();1393 const config_path = if (use_flakes)1394 output.firstRunPrompt("flake directory", "~/nixos-config", &path_buf)1395 else1396 output.firstRunPrompt("config path", "/etc/nixos", &path_buf);1397 const local_str = output.firstRunPrompt("local", "true", &local_buf);13981399 const conf_path = try config.configPath(gpa, environ);1400 defer gpa.free(conf_path);1401 if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);14021403 1404 const flake_line = if (use_flakes) "flake = true\n" else "";1405 var content_buf: [1024]u8 = undefined;1406 const content = try std.fmt.bufPrint(1407 &content_buf,1408 "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = {s}\n",1409 .{ flake_line, machine_name, config_path, local_str },1410 );14111412 const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1413 errors.error_info.setMessage("could not write {s}", .{conf_path});1414 return error.Internal;1415 };1416 defer file.close(io);1417 file.writePositionalAll(io, content, 0) catch {1418 errors.error_info.setMessage("could not write {s}", .{conf_path});1419 return error.Internal;1420 };14211422 output.firstRunWritten(conf_path);1423}14241425pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1426 1427 1428 1429 config.migrateLegacyConfig(gpa, io, environ);1430 if (config.configPath(gpa, environ)) |conf_path| {1431 defer gpa.free(conf_path);1432 if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1433 f.close(io);1434 } else |_| {1435 try firstRunWizard(gpa, io, environ);1436 errors.error_info.reset();1437 }1438 } else |_| {}14391440 output.setupCheck();1441 const status = exec.checkNixFeatures(gpa, io, environ);1442 output.setupFeatures(status.nix_command, status.flakes);14431444 if (status.allEnabled()) {1445 output.setupAllSet();1446 api.ensureRegistryPinned(gpa, io, environ);1447 return;1448 }14491450 1451 1452 1453 1454 if (exec.isNixOS(io)) {1455 const conf_path = "/etc/nixos/configuration.nix";1456 if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1457 output.setupNixosNeedsRebuild(conf_path);1458 return;1459 }1460 output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1461 if (output.confirmDefaultNo("add it now?")) {1462 if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1463 output.setupNixosWrote(conf_path);1464 } else |_| {1465 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1466 }1467 } else {1468 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1469 }1470 return;1471 }14721473 1474 output.setupEnabling();1475 const path = try exec.enableNixFeatures(gpa, io, environ);1476 defer gpa.free(path);14771478 output.setupDone(path);1479 api.ensureRegistryPinned(gpa, io, environ);1480}1481148214831484fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1485 var ts_buf: [32]u8 = undefined;1486 const ts = nowIso(ctx.io, &ts_buf);1487 var buf: [256]u8 = undefined;1488 const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1489 ts, ctx.machine.name, action, gen,1490 }) catch return;1491 exec.appendNinaLog(ctx.io, ctx.environ, entry);1492}1493149414951496fn nowIso(io: std.Io, buf: []u8) []const u8 {1497 const fallback = "1970-01-01T00:00:00Z";1498 const ns = std.Io.Clock.real.now(io).toNanoseconds();1499 if (ns <= 0) return fallback;1500 const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1501 const es = std.time.epoch.EpochSeconds{ .secs = secs };1502 const ed = es.getEpochDay();1503 const yd = ed.calculateYearDay();1504 const md = yd.calculateMonthDay();1505 const ds = es.getDaySeconds();1506 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", .{1507 yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1508 ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1509 }) catch return fallback;1510}