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) {91 current = g.number;92 };9394 95 96 var prev: u32 = 0;97 var has_prev = false;98 for (gens) |g| {99 if (g.number < current and (!has_prev or g.number > prev)) {100 prev = g.number;101 has_prev = true;102 }103 }104 if (!has_prev) {105 output.alreadyOldest();106 return;107 }108109 output.backStart(ctx.machine.name, current, prev);110 if (ctx.cfg.confirm and !output.confirm("")) return;111112 const code = try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);113 if (code != 0) return error.BuildFailed;114 output.backDone(prev);115}116117pub fn go(ctx: Ctx) !void {118 if (ctx.args.len == 0) return error.Internal;119 const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;120 const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);121122 output.goStart(ctx.machine.name, current, target);123 if (ctx.cfg.confirm and !output.confirm("")) return;124125 const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);126 if (code != 0) return error.ProcessFailed;127 output.generationDone(target);128}129130pub fn history(ctx: Ctx) !void {131 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);132 defer ctx.gpa.free(gens);133 output.historyHeader(ctx.machine.name);134 for (gens) |g| output.historyRow(g);135}136137const gen_help = [_][2][]const u8{138 .{ "list", "list generations" },139 .{ "current", "show current generation" },140 .{ "delete <n>", "delete generation n" },141 .{ "delete old", "delete old generations" },142};143144pub fn genCmd(ctx: Ctx) !void {145 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("gen", &gen_help, null);146 if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);147 if (std.mem.eql(u8, ctx.sub, "current")) {148 const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);149 output.genCurrent(n);150 return;151 }152 if (std.mem.eql(u8, ctx.sub, "delete")) {153 if (ctx.args.len == 0) return error.Internal;154 if (std.mem.eql(u8, ctx.args[0], "old")) {155 if (ctx.cfg.confirm and !output.confirm("")) return;156 _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);157 } else {158 const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;159 if (ctx.cfg.confirm and !output.confirm("")) return;160 _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);161 }162 output.done();163 return;164 }165 return error.Internal;166}167168pub fn clean(ctx: Ctx) !void {169 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);170 defer ctx.gpa.free(gens);171 const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");172 const total: u32 = @intCast(gens.len);173 174 175 const keep: u32 = if (all) 1 else ctx.cfg.generations;176 if (total <= keep) {177 output.cleanNothing(ctx.machine.name, total);178 return;179 }180 output.cleanStart(ctx.machine.name, keep, total);181 if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;182 _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);183 output.cleanDone();184}185186pub fn statusCmd(ctx: Ctx) !void {187 output.statusHeader();188 189 190 if (ctx.all and ctx.cfg.machines.len > 0) {191 for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);192 } else {193 statusRowFor(ctx, &ctx.machine);194 }195 homeStatusLine(ctx);196}197198199200201fn homeStatusLine(ctx: Ctx) void {202 if (exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ) != .standalone) return;203 const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return;204 defer ctx.gpa.free(out);205 const gens = parseHomeGenerations(ctx.gpa, out) catch return;206 defer freeHomeGens(ctx.gpa, gens);207 if (gens.len == 0) return;208 output.statusHomeRow(gens[0].number, gens[0].date);209}210211fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {212 213 214 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {215 output.statusRow(machine.name, 0, "", "", false);216 return;217 };218 const st = exec.systemStatus(ctx.gpa, ctx.io, machine);219 defer ctx.gpa.free(st.size);220 defer ctx.gpa.free(st.age);221 output.statusRow(machine.name, gen, st.age, st.size, true);222}223224pub fn diff(ctx: Ctx) !void {225 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);226 defer ctx.gpa.free(gens);227 var current: u32 = 0;228 var prev: u32 = 0;229 for (gens) |g| {230 if (g.current) current = g.number;231 if (!g.current and g.number > prev and g.number < current) prev = g.number;232 }233 if (ctx.args.len >= 2) {234 const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;235 const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;236 output.diffHeader(a, b, ctx.machine.name);237 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;238 } else {239 output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);240 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;241 }242}243244pub fn mood(ctx: Ctx) !void {245 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;246 const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);247 defer ctx.gpa.free(st.size);248 defer ctx.gpa.free(st.age);249 const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");250 defer ctx.gpa.free(state);251 output.mood(ctx.machine.name, state, gen, st.age, st.size);252}253254pub fn doctor(ctx: Ctx) !void {255 output.doctorHeader(ctx.machine.name);256 const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);257 defer ctx.gpa.free(checks);258 var warnings: u32 = 0;259 var failures: u32 = 0;260 for (checks) |ch| {261 output.doctorRow(ch);262 if (ch.status == .warn) warnings += 1;263 if (ch.status == .fail) failures += 1;264 }265266 267 268 const hm_mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);269 if (hm_mode != .none) {270 const note = homeDoctorNote(ctx, hm_mode);271 defer ctx.gpa.free(note);272 output.doctorRow(.{ .name = "home manager", .status = .ok, .note = note });273 }274275 output.doctorSummary(warnings, failures);276}277278279280fn homeDoctorNote(ctx: Ctx, mode: exec.HomeManagerMode) []const u8 {281 const label = switch (mode) {282 .standalone => "standalone",283 .module => "module",284 .none => "",285 };286 if (mode == .standalone) {287 const gen = homeCurrentGen(ctx);288 if (gen != 0)289 return std.fmt.allocPrint(ctx.gpa, "{s} gen {d}", .{ label, gen }) catch290 (ctx.gpa.dupe(u8, label) catch "");291 }292 return ctx.gpa.dupe(u8, label) catch "";293}294295296pub fn update(ctx: Ctx) !void {297 output.updateSelfStart();298299 if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {300 output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));301 return error.Internal;302 }303304 const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");305 const source_url = env_url orelse UPDATE_URL;306307 const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {308 error.NetworkError, error.HttpError => {309 output.updateSelfNetworkError();310 return;311 },312 else => return e,313 };314 defer ctx.gpa.free(body);315316 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {317 output.printWarning("could not parse release metadata");318 return;319 };320 defer parsed.deinit();321322 const root = parsed.value;323 if (root != .object) {324 output.printWarning("malformed release metadata");325 return;326 }327328 const remote_ver = blk: {329 const v = root.object.get("version") orelse {330 output.printWarning("malformed release metadata");331 return;332 };333 break :blk switch (v) {334 .string => |s| s,335 else => {336 output.printWarning("malformed release metadata");337 return;338 },339 };340 };341 const release_notes = blk: {342 const v = root.object.get("release_notes") orelse break :blk "";343 break :blk switch (v) {344 .string => |s| s,345 else => "",346 };347 };348349 if (std.mem.eql(u8, remote_ver, version.VERSION)) {350 output.updateSelfCurrent(version.VERSION);351 return;352 }353354 output.updateSelfAvailable(version.VERSION, remote_ver);355 output.updateSelfReleaseNotes(release_notes);356 if (ctx.check) return;357358 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;359 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {360 errors.error_info.setMessage("could not determine install path", .{});361 return error.Internal;362 };363364 365 366 367 368 369 if (std.mem.startsWith(u8, install_path, "/nix/store/")) {370 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);371 defer {372 if (nina_element) |n| ctx.gpa.free(n);373 }374 if (nina_element == null) {375 output.updateSelfNotInProfile();376 return;377 }378 const element = nina_element.?;379 output.updateSelfNixManaged(remote_ver);380 if (ctx.cfg.confirm and !output.confirm("")) return;381 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", element }) catch {382 output.updateSelfNixFailed();383 return;384 };385 if (ec != 0) {386 output.updateSelfNixFailed();387 return;388 }389 output.updateSelfDone(version.VERSION, remote_ver);390 return;391 }392393 const plat_info = blk: {394 const pv = root.object.get("platforms") orelse break :blk null;395 if (pv != .object) break :blk null;396 break :blk pv.object.get(version.PLATFORM);397 };398 if (plat_info == null) {399 output.updateSelfNoPlatform(version.PLATFORM);400 return;401 }402403 const dl_url = blk: {404 const v = plat_info.?.object.get("url") orelse {405 output.printWarning("malformed release metadata");406 return;407 };408 break :blk switch (v) {409 .string => |s| s,410 else => {411 output.printWarning("malformed release metadata");412 return;413 },414 };415 };416417 const raw_cksum = blk: {418 if (plat_info.?.object.get("blake3")) |v|419 break :blk switch (v) {420 .string => |s| s,421 else => {422 output.printWarning("malformed release metadata");423 return;424 },425 };426 if (plat_info.?.object.get("checksum")) |v|427 break :blk switch (v) {428 .string => |s| s,429 else => {430 output.printWarning("malformed release metadata");431 return;432 },433 };434 output.printWarning("missing checksum in release metadata");435 return;436 };437 const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;438439 if (ctx.cfg.confirm and !output.confirm("")) return;440441 output.updateSelfDownloading(remote_ver, version.PLATFORM);442 const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {443 output.printWarning("download failed — check your connection and try again");444 return;445 };446 defer ctx.gpa.free(tmp_path);447448 output.updateSelfVerifying();449 exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {450 error.ChecksumMismatch => {451 output.updateSelfChecksumFailed();452 return;453 },454 else => return e,455 };456457 output.updateSelfDone(version.VERSION, remote_ver);458}459460461462463pub fn goodbye(ctx: Ctx) !void {464 output.goodbyeStart();465466 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;467 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {468 errors.error_info.setMessage("could not determine install path", .{});469 return error.Internal;470 };471472 473 if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {474 output.goodbyeFile(install_path);475 if (ctx.cfg.confirm and !output.confirm("")) return;476 std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {477 errors.error_info.setMessage("could not remove {s}", .{install_path});478 return e;479 };480 output.goodbyeDone();481 return;482 }483484 485 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);486 defer {487 if (nina_element) |n| ctx.gpa.free(n);488 }489490 if (nina_element == null) {491 errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});492 return error.Internal;493 }494495 output.goodbyeNix();496 if (ctx.cfg.confirm and !output.confirm("")) return;497 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {498 output.goodbyeFailed("nix profile remove failed");499 return;500 };501 if (ec != 0) {502 output.goodbyeFailed("nix profile remove failed");503 return;504 }505 output.goodbyeDone();506}507508fn channelUpdateCmd(ctx: Ctx) !void {509 output.updateStart(ctx.machine.name);510 _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);511 output.updateDone();512}513514pub fn upgrade(ctx: Ctx) !void {515 output.upgradeStart(ctx.machine.name);516 517 518 519 if (flakeSystem(ctx)) {520 output.printSubstep("updating flake inputs", .{});521 _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};522 } else {523 output.printSubstep("updating channels", .{});524 _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};525 }526 output.printSubstep("rebuilding", .{});527 const start = std.Io.Clock.awake.now(ctx.io);528 const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);529 if (code != 0) {530 output.applyFailed("");531 return error.BuildFailed;532 }533 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());534 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));535 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;536 output.applyDone(gen, elapsed, false);537}538539pub fn log(ctx: Ctx) !void {540 output.logHeader(ctx.machine.name);541 const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {542 543 return;544 };545 defer ctx.gpa.free(content);546 var lines = std.mem.splitScalar(u8, content, '\n');547 while (lines.next()) |line| {548 const t = std.mem.trim(u8, line, " \t\r");549 if (t.len == 0) continue;550 if (t[0] == '{') {551 renderJsonLogLine(ctx.gpa, t);552 } else {553 554 var parts = std.mem.tokenizeScalar(u8, t, '\t');555 const date = parts.next() orelse continue;556 const time = parts.next() orelse "";557 const action = parts.next() orelse "";558 const detail = parts.next() orelse "";559 output.logRow(date, time, action, detail);560 }561 }562}563564565566fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {567 const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {568 output.logRow(line, "", "", ""); 569 return;570 };571 defer parsed.deinit();572 if (parsed.value != .object) return;573 const o = parsed.value.object;574575 const ts = jsonStr(o, "ts");576 const date = if (ts.len >= 10) ts[0..10] else ts;577 const time = if (ts.len >= 16) ts[11..16] else "";578 const action = jsonStr(o, "command");579 const outcome = jsonStr(o, "outcome");580581 var buf: [160]u8 = undefined;582 var detail: []const u8 = outcome;583 if (o.get("gen_after")) |g| {584 if (g == .integer) {585 detail = std.fmt.bufPrint(&buf, "{s} -> gen {d}", .{ outcome, g.integer }) catch outcome;586 }587 }588 output.logRow(date, time, action, detail);589}590591fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {592 if (o.get(key)) |v| {593 if (v == .string) return v.string;594 }595 return "";596}597598pub fn edit(ctx: Ctx) !void {599 const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");600 const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";601 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });602 defer ctx.gpa.free(path);603 output.editOpen(path, ctx.cfg.editor);604 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);605}606607pub fn fmt(ctx: Ctx) !void {608 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});609 defer ctx.gpa.free(path);610 if (ctx.check) {611 const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);612 if (code != 0) output.fmtNeedsFormat() else output.fmtDone();613 return;614 }615 output.fmtStart(path);616 _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);617 output.fmtDone();618}619620pub fn repl(ctx: Ctx) !void {621 output.replStart();622 _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);623}624625pub fn develop(ctx: Ctx) !void {626 if (std.mem.eql(u8, ctx.sub, "show")) {627 _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);628 return;629 }630 const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))631 ctx.args[0]632 else633 null;634 output.developStart(&.{});635 _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);636 output.developDone();637}638639pub fn info(ctx: Ctx) !void {640 output.infoHeader(ctx.machine.name);641 const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");642 defer ctx.gpa.free(nixos_ver);643 output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));644645 const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");646 defer ctx.gpa.free(kernel);647 output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));648649 const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");650 defer ctx.gpa.free(uptime);651 output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));652}653654pub fn boot(ctx: Ctx) !void {655 output.bootHeader(ctx.machine.name);656 const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};657 defer ctx.gpa.free(entries);658 for (entries, 0..) |entry, i| output.bootEntry(entry, i);659}660661pub fn searchCmd(ctx: Ctx) !void {662 const query = if (ctx.args.len > 0) ctx.args[0] else "";663 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);664 const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);665 if (selected) |npkg| try selectAndInstall(ctx, npkg);666}667668pub fn optionCmd(ctx: Ctx) !void {669 const query = if (ctx.args.len > 0) ctx.args[0] else "";670 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);671 _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);672}673674pub fn install(ctx: Ctx) !void {675 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;676677 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);678679 680 const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {681 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});682 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});683 return error.PackageNotFound;684 };685686 if (pkgs.len == 0) {687 688 if (closestPackage(ctx, pkg_name)) |sugg| {689 output.didYouMean(pkg_name, sugg.pname);690 if (output.confirm("")) try selectAndInstall(ctx, sugg);691 return;692 }693 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});694 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});695 return error.PackageNotFound;696 }697698 699 700 var found = pkgs[0];701 for (pkgs) |p| {702 if (std.mem.eql(u8, p.pname, pkg_name)) {703 found = p;704 break;705 }706 }707 try selectAndInstall(ctx, found);708}709710711712713fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {714 if (query.len < 2) return null;715 var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};716 if (candidates.len == 0 and query.len > 2) {717 candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};718 }719 if (candidates.len == 0) return null;720721 var best: ?types.NixPackage = null;722 var best_dist: usize = std.math.maxInt(usize);723 for (candidates) |p| {724 const d = editDistance(query, p.pname);725 if (d > 0 and d < best_dist) {726 best_dist = d;727 best = p;728 }729 }730 731 const threshold = @max(@as(usize, 2), query.len / 3);732 return if (best_dist <= threshold) best else null;733}734735736737fn editDistance(a: []const u8, b: []const u8) usize {738 const n = b.len;739 if (a.len == 0) return n;740 if (n == 0) return a.len;741 if (n + 1 > 128) return std.math.maxInt(usize);742 var prev: [128]usize = undefined;743 var curr: [128]usize = undefined;744 var j: usize = 0;745 while (j <= n) : (j += 1) prev[j] = j;746 var i: usize = 1;747 while (i <= a.len) : (i += 1) {748 curr[0] = i;749 j = 1;750 while (j <= n) : (j += 1) {751 const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;752 curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));753 }754 @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);755 }756 return prev[n];757}758759test "editDistance is case-insensitive Levenshtein" {760 try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));761 try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));762 try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));763 try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));764}765766767768769770fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {771 output.installSelectPrompt(npkg.pname, npkg.version);772773 var choice_buf: [8]u8 = undefined;774 var choice_len: usize = 0;775 while (choice_len < choice_buf.len) {776 const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;777 if (n == 0) break;778 if (choice_buf[choice_len] == '\n') break;779 choice_len += 1;780 }781 const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");782783 if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {784 try profileInstallPkg(ctx, npkg);785 } else if (choice[0] == 's' or choice[0] == 'S') {786 try systemInstallPkg(ctx, npkg);787 } else if (choice[0] == 't' or choice[0] == 'T') {788 try tryPkg(ctx, npkg);789 }790}791792fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {793 output.installStart(npkg.pname, .profile);794 output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});795 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));796 const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);797 if (code != 0) return error.ProcessFailed;798 output.installDone(npkg.pname);799}800801fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {802 const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});803 defer ctx.gpa.free(config_path);804 const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;805 output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);806 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);807 if (ctx.cfg.confirm) {808 if (output.confirm("apply now? ")) {809 try apply(ctx);810 }811 }812}813814fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {815 output.tryStart(npkg.pname);816 output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});817 output.tryExitHint();818 _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);819 output.tryDone();820}821822pub fn remove(ctx: Ctx) !void {823 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;824 output.removeStart(pkg_name);825 const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);826 if (code != 0) return error.ProcessFailed;827 output.done();828}829830pub fn list(ctx: Ctx) !void {831 output.listHeader(ctx.machine.name);832833 834 835 836 if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {837 defer ctx.gpa.free(json);838 output.listSection("profile");839 renderProfileJson(ctx.gpa, json);840 }841842 843 844 if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {845 defer ctx.gpa.free(paths);846 output.blankLine();847 output.listSection("system");848 var lines = std.mem.splitScalar(u8, paths, '\n');849 while (lines.next()) |line| {850 const t = std.mem.trim(u8, line, " \t\r");851 if (t.len == 0) continue;852 const row = pkgFromStorePath(t);853 854 if (row.version.len == 0) continue;855 output.listPkg(row.name, row.version);856 }857 }858}859860const PkgRow = struct { name: []const u8, version: []const u8 };861862863864865866fn pkgFromStorePath(path: []const u8) PkgRow {867 const base = std.fs.path.basename(path);868 const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;869 var i: usize = 0;870 while (i + 1 < after_hash.len) : (i += 1) {871 if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {872 return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };873 }874 }875 return .{ .name = after_hash, .version = "" };876}877878879880881fn stripOutputSuffix(ver: []const u8) []const u8 {882 const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };883 for (suffixes) |s| {884 if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];885 }886 return ver;887}888889test "pkgFromStorePath splits name and version at first dash-digit" {890 const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");891 try std.testing.expectEqualStrings("ripgrep", a.name);892 try std.testing.expectEqualStrings("15.1.0", a.version);893894 const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");895 try std.testing.expectEqualStrings("helix", b.name);896 try std.testing.expectEqualStrings("25.01", b.version);897898 899 const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");900 try std.testing.expectEqualStrings("curl", c.name);901 try std.testing.expectEqualStrings("8.20.0", c.version);902}903904fn firstStorePath(el: std.json.Value) ?[]const u8 {905 if (el != .object) return null;906 const sp = el.object.get("storePaths") orelse return null;907 if (sp != .array or sp.array.items.len == 0) return null;908 const first = sp.array.items[0];909 return if (first == .string) first.string else null;910}911912913914fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {915 const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;916 defer parsed.deinit();917 if (parsed.value != .object) return;918 const elements = parsed.value.object.get("elements") orelse return;919 switch (elements) {920 .object => |obj| {921 var it = obj.iterator();922 while (it.next()) |entry| {923 const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";924 output.listPkg(entry.key_ptr.*, ver);925 }926 },927 .array => |arr| {928 for (arr.items) |el| {929 const path = firstStorePath(el) orelse continue;930 const row = pkgFromStorePath(path);931 output.listPkg(row.name, row.version);932 }933 },934 else => {},935 }936}937938pub fn tryCmd(ctx: Ctx) !void {939 const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;940 const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };941 try tryPkg(ctx, shell_pkg);942}943944945946const home_help = [_][2][]const u8{947 .{ "apply", "apply home-manager configuration" },948 .{ "apply --dry", "preview changes without activating" },949 .{ "back", "roll back one generation" },950 .{ "history", "list all generations" },951 .{ "edit", "open home.nix" },952 .{ "check", "validate without applying" },953 .{ "diff", "compare the latest two generations" },954 .{ "packages", "list managed packages" },955};956957const HomeGen = struct {958 number: u32,959 date: []const u8,960 time: []const u8,961 path: []const u8,962};963964965966967fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {968 var gens: std.ArrayList(HomeGen) = .empty;969 var lines = std.mem.splitScalar(u8, out_str, '\n');970 while (lines.next()) |line| {971 const t = std.mem.trim(u8, line, " \t\r");972 if (t.len == 0) continue;973 var it = std.mem.tokenizeAny(u8, t, " \t");974 const date = it.next() orelse continue;975 const time = it.next() orelse continue;976 var number: ?u32 = null;977 var path: []const u8 = "";978 while (it.next()) |tok| {979 if (std.mem.eql(u8, tok, "id")) {980 if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;981 } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {982 path = tok;983 }984 }985 const num = number orelse continue;986 try gens.append(gpa, .{987 .number = num,988 .date = try gpa.dupe(u8, date),989 .time = try gpa.dupe(u8, time),990 .path = try gpa.dupe(u8, path),991 });992 }993 return gens.toOwnedSlice(gpa);994}995996fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {997 for (gens) |g| {998 gpa.free(g.date);999 gpa.free(g.time);1000 gpa.free(g.path);1001 }1002 gpa.free(gens);1003}10041005test "parseHomeGenerations reads id, date and store path" {1006 const a = std.testing.allocator;1007 const sample =1008 \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1009 \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1010 ;1011 const gens = try parseHomeGenerations(a, sample);1012 defer freeHomeGens(a, gens);1013 try std.testing.expectEqual(@as(usize, 2), gens.len);1014 try std.testing.expectEqual(@as(u32, 765), gens[0].number);1015 try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1016 try std.testing.expectEqualStrings("11:56", gens[0].time);1017 try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1018 try std.testing.expectEqual(@as(u32, 764), gens[1].number);1019}102010211022fn homeCurrentGen(ctx: Ctx) u32 {1023 const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1024 defer ctx.gpa.free(out);1025 const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1026 defer freeHomeGens(ctx.gpa, gens);1027 return if (gens.len > 0) gens[0].number else 0;1028}10291030pub fn home(ctx: Ctx) !void {1031 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1032 return output.subcommandHelp("home", &home_help, null);10331034 1035 1036 1037 1038 1039 if (!ctx.machine.local) {1040 output.homeLocalOnly(ctx.machine.name);1041 return;1042 }10431044 const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1045 if (mode == .none) {1046 output.homeNotInstalled();1047 return;1048 }10491050 1051 1052 if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1053 1054 if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);10551056 if (mode == .module) {1057 output.homeModuleManaged();1058 return;1059 }10601061 if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1062 if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1063 if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1064 if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1065 if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);10661067 return output.subcommandHelp("home", &home_help, null);1068}10691070fn homePackages(ctx: Ctx) !void {1071 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1072 defer ctx.gpa.free(out);1073 const gens = try parseHomeGenerations(ctx.gpa, out);1074 defer freeHomeGens(ctx.gpa, gens);10751076 output.homePackagesHeader(ctx.machine.name);1077 if (gens.len == 0 or gens[0].path.len == 0) return;10781079 1080 1081 1082 1083 1084 const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1085 defer ctx.gpa.free(gen_refs);10861087 var refs = gen_refs;1088 var env_refs: ?[]u8 = null;1089 defer if (env_refs) |e| ctx.gpa.free(e);1090 if (findHomeManagerPath(gen_refs)) |pkg_path| {1091 if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1092 env_refs = e;1093 refs = e;1094 } else |_| {}1095 }10961097 1098 1099 1100 var seen = std.StringHashMap(void).init(ctx.gpa);1101 defer seen.deinit();1102 var lines = std.mem.splitScalar(u8, refs, '\n');1103 while (lines.next()) |line| {1104 const t = std.mem.trim(u8, line, " \t\r");1105 if (t.len == 0) continue;1106 const row = pkgFromStorePath(t);1107 if (row.version.len == 0) continue;1108 if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1109 if (seen.contains(row.name)) continue;1110 seen.put(row.name, {}) catch {};1111 output.listPkg(row.name, row.version);1112 }1113}1114111511161117fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1118 var lines = std.mem.splitScalar(u8, refs, '\n');1119 while (lines.next()) |line| {1120 const t = std.mem.trim(u8, line, " \t\r");1121 if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1122 }1123 return null;1124}11251126test "findHomeManagerPath picks the env, not the generation or infra" {1127 const refs =1128 \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31129 \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1130 \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111131 ;1132 try std.testing.expectEqualStrings(1133 "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1134 findHomeManagerPath(refs).?,1135 );1136 try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1137}11381139fn homeDiff(ctx: Ctx) !void {1140 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1141 defer ctx.gpa.free(out);1142 const gens = try parseHomeGenerations(ctx.gpa, out);1143 defer freeHomeGens(ctx.gpa, gens);11441145 1146 if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1147 output.homeNothingToDiff();1148 return;1149 }1150 const newer = gens[0];1151 const older = gens[1];1152 output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1153 if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1154 return error.ProcessFailed;1155}11561157fn homeCheck(ctx: Ctx) !void {1158 output.homeCheckStart(ctx.machine.name);1159 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1160 if (code != 0) {1161 output.checkFailed("");1162 return error.BuildFailed;1163 }1164 output.homeCheckOk();1165}11661167fn homeEdit(ctx: Ctx) !void {1168 1169 1170 const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1171 errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1172 return error.ConfigNotFound;1173 };1174 defer ctx.gpa.free(path);1175 output.homeEditOpen(path, ctx.cfg.editor);1176 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1177}11781179fn homeHistory(ctx: Ctx) !void {1180 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1181 defer ctx.gpa.free(out);1182 const gens = try parseHomeGenerations(ctx.gpa, out);1183 defer freeHomeGens(ctx.gpa, gens);1184 output.homeHistoryHeader(ctx.machine.name);1185 1186 for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1187}11881189fn homeBack(ctx: Ctx) !void {1190 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1191 defer ctx.gpa.free(out);1192 const gens = try parseHomeGenerations(ctx.gpa, out);1193 defer freeHomeGens(ctx.gpa, gens);11941195 1196 if (gens.len < 2) {1197 output.alreadyOldest();1198 return;1199 }1200 const current = gens[0].number;1201 const prev = gens[1].number;12021203 output.homeBackStart(ctx.machine.name, current, prev);1204 if (ctx.cfg.confirm and !output.confirm("")) return;1205 const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1206 if (code != 0) return error.BuildFailed;1207 output.homeBackDone(prev);1208}12091210fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1211 1212 if (mode == .module) {1213 output.homeModuleManaged();1214 return;1215 }1216 if (ctx.dry) {1217 output.homeApplyDry(ctx.machine.name);1218 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1219 if (code != 0) return error.BuildFailed;1220 output.homeApplyDryDone();1221 return;1222 }12231224 output.homeApplyStart(ctx.machine.name);1225 const flake_ref = exec.homeFlakeRef(ctx.gpa, ctx.io, ctx.environ);1226 defer if (flake_ref) |r| ctx.gpa.free(r);1227 if (flake_ref) |ref| {1228 output.printSubstep("home-manager switch --flake {s}", .{ref});1229 } else {1230 output.printSubstep("home-manager switch", .{});1231 }12321233 const start = std.Io.Clock.awake.now(ctx.io);1234 const code = if (flake_ref) |ref|1235 try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)1236 else1237 try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1238 if (code != 0) return error.BuildFailed;12391240 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1241 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1242 output.homeApplyDone(homeCurrentGen(ctx), elapsed);1243}1244124512461247const service_help = [_][2][]const u8{1248 .{ "list", "list running services" },1249 .{ "logs <svc>", "show service logs" },1250 .{ "status <svc>", "service status" },1251 .{ "start <svc>", "start a service" },1252 .{ "stop <svc>", "stop a service" },1253 .{ "restart <svc>", "restart a service" },1254 .{ "enable <svc>", "enable at boot" },1255 .{ "disable <svc>", "disable at boot" },1256};12571258pub fn service(ctx: Ctx) !void {1259 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");1260 if (std.mem.eql(u8, ctx.sub, "list")) {1261 output.serviceListHeader(ctx.machine.name);1262 const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1263 defer ctx.gpa.free(svcs);1264 for (svcs) |s| output.serviceRow(s);1265 return;1266 }1267 if (std.mem.eql(u8, ctx.sub, "logs")) {1268 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1269 const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1270 output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1271 _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1272 return;1273 }1274 if (std.mem.eql(u8, ctx.sub, "status")) {1275 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1276 output.serviceVerb("status", name, ctx.machine.name);1277 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1278 return;1279 }1280 1281 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1282 if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1283 if (!output.confirm("")) return;1284 }1285 output.serviceVerb(ctx.sub, name, ctx.machine.name);1286 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1287 output.serviceDone();1288}1289129012911292const flake_help = [_][2][]const u8{1293 .{ "init", "create a new flake.nix" },1294 .{ "update", "update flake inputs" },1295 .{ "update <in>", "update a specific input" },1296 .{ "check", "validate the flake" },1297 .{ "show", "inspect flake outputs" },1298 .{ "lock", "regenerate flake.lock" },1299 .{ "clone <url>", "clone a flake repository" },1300};13011302pub fn flake(ctx: Ctx) !void {1303 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1304 if (std.mem.eql(u8, ctx.sub, "update")) {1305 output.flakeUpdateStart();1306 const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1307 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1308 output.flakeLockWritten();1309 return;1310 }1311 if (std.mem.eql(u8, ctx.sub, "check")) {1312 output.flakeCheckStart();1313 const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1314 if (code == 0) output.flakeValid() else output.checkFailed("");1315 return;1316 }1317 if (std.mem.eql(u8, ctx.sub, "show")) {1318 const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1319 if (json_out) |j| {1320 defer ctx.gpa.free(j);1321 output.flakeShowHeader("flake outputs");1322 1323 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1324 defer parsed.deinit();1325 if (parsed.value == .object) {1326 var it = parsed.value.object.iterator();1327 while (it.next()) |entry| {1328 if (entry.value_ptr.* == .object) {1329 var inner = entry.value_ptr.object.iterator();1330 while (inner.next()) |e2| {1331 const desc = if (e2.value_ptr.* == .object)1332 if (e2.value_ptr.object.get("description")) |d|1333 if (d == .string) d.string else ""1334 else1335 ""1336 else1337 "";1338 output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1339 }1340 }1341 }1342 }1343 }1344 return;1345 }1346 if (std.mem.eql(u8, ctx.sub, "init")) {1347 _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1348 return;1349 }1350 if (std.mem.eql(u8, ctx.sub, "lock")) {1351 _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1352 return;1353 }1354 if (std.mem.eql(u8, ctx.sub, "clone")) {1355 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1356 _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1357 return;1358 }1359}1360136113621363const store_help = [_][2][]const u8{1364 .{ "info", "store size and counts" },1365 .{ "path <attr>", "store path of a package" },1366 .{ "gc", "collect garbage" },1367 .{ "verify", "verify store integrity" },1368 .{ "repair", "repair corrupted paths" },1369};13701371pub fn store(ctx: Ctx) !void {1372 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1373 if (std.mem.eql(u8, ctx.sub, "gc")) {1374 _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1375 return;1376 }1377 if (std.mem.eql(u8, ctx.sub, "verify")) {1378 output.storeVerifyStart();1379 _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1380 return;1381 }1382 if (std.mem.eql(u8, ctx.sub, "repair")) {1383 if (ctx.cfg.confirm and !output.confirm("")) return;1384 output.storeRepairStart();1385 _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1386 return;1387 }1388 if (std.mem.eql(u8, ctx.sub, "info")) {1389 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1390 output.storeInfo(si);1391 return;1392 }1393 if (std.mem.eql(u8, ctx.sub, "path")) {1394 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1395 const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1396 defer ctx.gpa.free(path);1397 output.storePath(path);1398 return;1399 }1400 1401 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1402 output.storeInfo(si);1403}1404140514061407const channel_help = [_][2][]const u8{1408 .{ "list", "list channels" },1409 .{ "add <url> [name]", "add a channel" },1410 .{ "remove <name>", "remove a channel" },1411 .{ "update", "update all channels" },1412};14131414pub fn channel(ctx: Ctx) !void {1415 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1416 1417 if (flakeSystem(ctx)) output.flakeChannelNote();1418 if (std.mem.eql(u8, ctx.sub, "list")) {1419 output.channelListHeader(ctx.machine.name);1420 const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1421 defer ctx.gpa.free(chans);1422 for (chans) |ch| output.channelRow(ch);1423 return;1424 }1425 if (std.mem.eql(u8, ctx.sub, "add")) {1426 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1427 const name = if (ctx.args.len > 1) ctx.args[1] else "";1428 _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1429 output.channelDone();1430 return;1431 }1432 if (std.mem.eql(u8, ctx.sub, "remove")) {1433 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1434 _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1435 output.channelDone();1436 return;1437 }1438 if (std.mem.eql(u8, ctx.sub, "update")) {1439 return channelUpdateCmd(ctx);1440 }1441}1442144314441445pub fn profile(ctx: Ctx) !void {1446 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1447 output.profileListHeader();1448 const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1449 if (out) |o| {1450 defer ctx.gpa.free(o);1451 var lines = std.mem.splitScalar(u8, o, '\n');1452 while (lines.next()) |line| {1453 const t = std.mem.trim(u8, line, " \t\r");1454 if (t.len == 0) continue;1455 output.profileRow(t, "", "");1456 }1457 }1458 return;1459 }1460 if (std.mem.eql(u8, ctx.sub, "install")) {1461 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1462 _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1463 output.done();1464 return;1465 }1466 if (std.mem.eql(u8, ctx.sub, "remove")) {1467 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1468 _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1469 output.done();1470 return;1471 }1472 if (std.mem.eql(u8, ctx.sub, "upgrade")) {1473 _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1474 output.done();1475 return;1476 }1477}1478147914801481const pkg_help = [_][2][]const u8{1482 .{ "why <pkg>", "what pulled it in" },1483 .{ "deps <pkg>", "direct dependencies" },1484 .{ "size <pkg>", "closure size" },1485 .{ "path <pkg>", "store path" },1486 .{ "closure <pkg>", "full closure" },1487};14881489pub fn pkg(ctx: Ctx) !void {1490 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1491 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1492 if (std.mem.eql(u8, ctx.sub, "why")) {1493 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1494 return;1495 }1496 if (std.mem.eql(u8, ctx.sub, "deps")) {1497 if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1498 return;1499 }1500 if (std.mem.eql(u8, ctx.sub, "size")) {1501 const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1502 defer ctx.gpa.free(s);1503 output.pkgResult("size", s);1504 return;1505 }1506 if (std.mem.eql(u8, ctx.sub, "path")) {1507 const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1508 defer ctx.gpa.free(p);1509 output.pkgResult("path", p);1510 return;1511 }1512 if (std.mem.eql(u8, ctx.sub, "closure")) {1513 if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1514 return;1515 }1516}1517151815191520pub fn why(ctx: Ctx) !void {1521 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1522 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1523}1524152515261527pub fn pin(ctx: Ctx) !void {1528 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1529 const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1530 exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1531 output.pinDone(input, commit);1532}15331534pub fn unpin(ctx: Ctx) !void {1535 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1536 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1537 output.unpinDone(input);1538}1539154015411542pub fn hash(ctx: Ctx) !void {1543 const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1544 const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1545 defer ctx.gpa.free(h);1546 output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1547}15481549pub fn fetch(ctx: Ctx) !void {1550 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1551 const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1552 defer ctx.gpa.free(h);1553 output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1554}1555155615571558pub fn build(ctx: Ctx) !void {1559 const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1560 output.buildStart(attr orelse "default");1561 const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1562 if (code != 0) return error.BuildFailed;1563 output.buildDone();1564}15651566pub fn runCmd(ctx: Ctx) !void {1567 const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1568 output.runStart(pkg_arg);1569 _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1570}1571157215731574pub fn hello(ctx: Ctx) !void {1575 output.hello(ctx.cfg.machines);1576}15771578const ConfigKind = enum { flake, channel, none };1579158015811582fn scanConfig(io: std.Io) ConfigKind {1583 if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1584 if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1585 return .none;1586}15871588158915901591pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1592 output.firstRunBanner();1593 output.firstRunNoConfig();15941595 var name_buf: [256]u8 = undefined;1596 var path_buf: [256]u8 = undefined;15971598 const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);15991600 output.firstRunScanning();1601 const kind = scanConfig(io);1602 switch (kind) {1603 .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),1604 .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),1605 .none => output.firstRunNoneFound(),1606 }16071608 1609 1610 const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";1611 const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);16121613 1614 1615 const use_flakes = exec.dirHasFlake(gpa, io, config_path);16161617 const conf_path = try config.configPath(gpa, environ);1618 defer gpa.free(conf_path);1619 if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);16201621 1622 const flake_line = if (use_flakes) "flake = true\n" else "";1623 var content_buf: [1024]u8 = undefined;1624 const content = try std.fmt.bufPrint(1625 &content_buf,1626 "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",1627 .{ flake_line, machine_name, config_path },1628 );16291630 const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1631 errors.error_info.setMessage("could not write {s}", .{conf_path});1632 return error.Internal;1633 };1634 defer file.close(io);1635 file.writePositionalAll(io, content, 0) catch {1636 errors.error_info.setMessage("could not write {s}", .{conf_path});1637 return error.Internal;1638 };16391640 output.firstRunWritten(conf_path);1641}16421643pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1644 1645 1646 1647 config.migrateLegacyConfig(gpa, io, environ);1648 if (config.configPath(gpa, environ)) |conf_path| {1649 defer gpa.free(conf_path);1650 if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1651 f.close(io);1652 } else |_| {1653 try firstRunWizard(gpa, io, environ);1654 errors.error_info.reset();1655 }1656 } else |_| {}16571658 output.setupCheck();1659 const status = exec.checkNixFeatures(gpa, io, environ);1660 output.setupFeatures(status.nix_command, status.flakes);16611662 if (status.allEnabled()) {1663 output.setupAllSet();1664 api.ensureRegistryPinned(gpa, io, environ);1665 return;1666 }16671668 1669 1670 1671 1672 if (exec.isNixOS(io)) {1673 const conf_path = "/etc/nixos/configuration.nix";1674 if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1675 output.setupNixosNeedsRebuild(conf_path);1676 return;1677 }1678 output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1679 if (output.confirmDefaultNo("add it now?")) {1680 if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1681 output.setupNixosWrote(conf_path);1682 } else |_| {1683 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1684 }1685 } else {1686 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1687 }1688 return;1689 }16901691 1692 output.setupEnabling();1693 const path = try exec.enableNixFeatures(gpa, io, environ);1694 defer gpa.free(path);16951696 output.setupDone(path);1697 api.ensureRegistryPinned(gpa, io, environ);1698}1699170017011702fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1703 var ts_buf: [32]u8 = undefined;1704 const ts = nowIso(ctx.io, &ts_buf);1705 var buf: [256]u8 = undefined;1706 const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1707 ts, ctx.machine.name, action, gen,1708 }) catch return;1709 exec.appendNinaLog(ctx.io, ctx.environ, entry);1710}1711171217131714fn nowIso(io: std.Io, buf: []u8) []const u8 {1715 const fallback = "1970-01-01T00:00:00Z";1716 const ns = std.Io.Clock.real.now(io).toNanoseconds();1717 if (ns <= 0) return fallback;1718 const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1719 const es = std.time.epoch.EpochSeconds{ .secs = secs };1720 const ed = es.getEpochDay();1721 const yd = ed.calculateYearDay();1722 const md = yd.calculateMonthDay();1723 const ds = es.getDaySeconds();1724 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", .{1725 yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1726 ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1727 }) catch return fallback;1728}