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) output.updateSelfNixFailed();386 return;387 }388389 const plat_info = blk: {390 const pv = root.object.get("platforms") orelse break :blk null;391 if (pv != .object) break :blk null;392 break :blk pv.object.get(version.PLATFORM);393 };394 if (plat_info == null) {395 output.updateSelfNoPlatform(version.PLATFORM);396 return;397 }398399 const dl_url = blk: {400 const v = plat_info.?.object.get("url") orelse {401 output.printWarning("malformed release metadata");402 return;403 };404 break :blk switch (v) {405 .string => |s| s,406 else => {407 output.printWarning("malformed release metadata");408 return;409 },410 };411 };412413 const raw_cksum = blk: {414 if (plat_info.?.object.get("blake3")) |v|415 break :blk switch (v) {416 .string => |s| s,417 else => {418 output.printWarning("malformed release metadata");419 return;420 },421 };422 if (plat_info.?.object.get("checksum")) |v|423 break :blk switch (v) {424 .string => |s| s,425 else => {426 output.printWarning("malformed release metadata");427 return;428 },429 };430 output.printWarning("missing checksum in release metadata");431 return;432 };433 const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;434435 if (ctx.cfg.confirm and !output.confirm("")) return;436437 output.updateSelfDownloading(remote_ver, version.PLATFORM);438 const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {439 output.printWarning("download failed — check your connection and try again");440 return;441 };442 defer ctx.gpa.free(tmp_path);443444 output.updateSelfVerifying();445 exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {446 error.ChecksumMismatch => {447 output.updateSelfChecksumFailed();448 return;449 },450 else => return e,451 };452453 output.updateSelfDone(version.VERSION, remote_ver);454}455456457458459pub fn goodbye(ctx: Ctx) !void {460 output.goodbyeStart();461462 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;463 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {464 errors.error_info.setMessage("could not determine install path", .{});465 return error.Internal;466 };467468 469 if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {470 output.goodbyeFile(install_path);471 if (ctx.cfg.confirm and !output.confirm("")) return;472 std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {473 errors.error_info.setMessage("could not remove {s}", .{install_path});474 return e;475 };476 output.goodbyeDone();477 return;478 }479480 481 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);482 defer {483 if (nina_element) |n| ctx.gpa.free(n);484 }485486 if (nina_element == null) {487 errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});488 return error.Internal;489 }490491 output.goodbyeNix();492 if (ctx.cfg.confirm and !output.confirm("")) return;493 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {494 output.goodbyeFailed("nix profile remove failed");495 return;496 };497 if (ec != 0) {498 output.goodbyeFailed("nix profile remove failed");499 return;500 }501 output.goodbyeDone();502}503504fn channelUpdateCmd(ctx: Ctx) !void {505 output.updateStart(ctx.machine.name);506 _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);507 output.updateDone();508}509510pub fn upgrade(ctx: Ctx) !void {511 output.upgradeStart(ctx.machine.name);512 513 514 515 if (flakeSystem(ctx)) {516 output.printSubstep("updating flake inputs", .{});517 _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};518 } else {519 output.printSubstep("updating channels", .{});520 _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};521 }522 output.printSubstep("rebuilding", .{});523 const start = std.Io.Clock.awake.now(ctx.io);524 const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);525 if (code != 0) {526 output.applyFailed("");527 return error.BuildFailed;528 }529 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());530 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));531 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;532 output.applyDone(gen, elapsed, false);533}534535pub fn log(ctx: Ctx) !void {536 output.logHeader(ctx.machine.name);537 const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {538 539 return;540 };541 defer ctx.gpa.free(content);542 var lines = std.mem.splitScalar(u8, content, '\n');543 while (lines.next()) |line| {544 const t = std.mem.trim(u8, line, " \t\r");545 if (t.len == 0) continue;546 if (t[0] == '{') {547 renderJsonLogLine(ctx.gpa, t);548 } else {549 550 var parts = std.mem.tokenizeScalar(u8, t, '\t');551 const date = parts.next() orelse continue;552 const time = parts.next() orelse "";553 const action = parts.next() orelse "";554 const detail = parts.next() orelse "";555 output.logRow(date, time, action, detail);556 }557 }558}559560561562fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {563 const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {564 output.logRow(line, "", "", ""); 565 return;566 };567 defer parsed.deinit();568 if (parsed.value != .object) return;569 const o = parsed.value.object;570571 const ts = jsonStr(o, "ts");572 const date = if (ts.len >= 10) ts[0..10] else ts;573 const time = if (ts.len >= 16) ts[11..16] else "";574 const action = jsonStr(o, "command");575 const outcome = jsonStr(o, "outcome");576577 var buf: [160]u8 = undefined;578 var detail: []const u8 = outcome;579 if (o.get("gen_after")) |g| {580 if (g == .integer) {581 detail = std.fmt.bufPrint(&buf, "{s} -> gen {d}", .{ outcome, g.integer }) catch outcome;582 }583 }584 output.logRow(date, time, action, detail);585}586587fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {588 if (o.get(key)) |v| {589 if (v == .string) return v.string;590 }591 return "";592}593594pub fn edit(ctx: Ctx) !void {595 const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");596 const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";597 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });598 defer ctx.gpa.free(path);599 output.editOpen(path, ctx.cfg.editor);600 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);601}602603pub fn fmt(ctx: Ctx) !void {604 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});605 defer ctx.gpa.free(path);606 if (ctx.check) {607 const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);608 if (code != 0) output.fmtNeedsFormat() else output.fmtDone();609 return;610 }611 output.fmtStart(path);612 _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);613 output.fmtDone();614}615616pub fn repl(ctx: Ctx) !void {617 output.replStart();618 _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);619}620621pub fn develop(ctx: Ctx) !void {622 if (std.mem.eql(u8, ctx.sub, "show")) {623 _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);624 return;625 }626 const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))627 ctx.args[0]628 else629 null;630 output.developStart(&.{});631 _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);632 output.developDone();633}634635pub fn info(ctx: Ctx) !void {636 output.infoHeader(ctx.machine.name);637 const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");638 defer ctx.gpa.free(nixos_ver);639 output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));640641 const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");642 defer ctx.gpa.free(kernel);643 output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));644645 const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");646 defer ctx.gpa.free(uptime);647 output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));648}649650pub fn boot(ctx: Ctx) !void {651 output.bootHeader(ctx.machine.name);652 const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};653 defer ctx.gpa.free(entries);654 for (entries, 0..) |entry, i| output.bootEntry(entry, i);655}656657pub fn searchCmd(ctx: Ctx) !void {658 const query = if (ctx.args.len > 0) ctx.args[0] else "";659 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);660 const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);661 if (selected) |npkg| try selectAndInstall(ctx, npkg);662}663664pub fn optionCmd(ctx: Ctx) !void {665 const query = if (ctx.args.len > 0) ctx.args[0] else "";666 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);667 _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);668}669670pub fn install(ctx: Ctx) !void {671 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;672673 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);674675 676 const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {677 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});678 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});679 return error.PackageNotFound;680 };681682 if (pkgs.len == 0) {683 684 if (closestPackage(ctx, pkg_name)) |sugg| {685 output.didYouMean(pkg_name, sugg.pname);686 if (output.confirm("")) try selectAndInstall(ctx, sugg);687 return;688 }689 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});690 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});691 return error.PackageNotFound;692 }693694 695 696 var found = pkgs[0];697 for (pkgs) |p| {698 if (std.mem.eql(u8, p.pname, pkg_name)) {699 found = p;700 break;701 }702 }703 try selectAndInstall(ctx, found);704}705706707708709fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {710 if (query.len < 2) return null;711 var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};712 if (candidates.len == 0 and query.len > 2) {713 candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};714 }715 if (candidates.len == 0) return null;716717 var best: ?types.NixPackage = null;718 var best_dist: usize = std.math.maxInt(usize);719 for (candidates) |p| {720 const d = editDistance(query, p.pname);721 if (d > 0 and d < best_dist) {722 best_dist = d;723 best = p;724 }725 }726 727 const threshold = @max(@as(usize, 2), query.len / 3);728 return if (best_dist <= threshold) best else null;729}730731732733fn editDistance(a: []const u8, b: []const u8) usize {734 const n = b.len;735 if (a.len == 0) return n;736 if (n == 0) return a.len;737 if (n + 1 > 128) return std.math.maxInt(usize);738 var prev: [128]usize = undefined;739 var curr: [128]usize = undefined;740 var j: usize = 0;741 while (j <= n) : (j += 1) prev[j] = j;742 var i: usize = 1;743 while (i <= a.len) : (i += 1) {744 curr[0] = i;745 j = 1;746 while (j <= n) : (j += 1) {747 const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;748 curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));749 }750 @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);751 }752 return prev[n];753}754755test "editDistance is case-insensitive Levenshtein" {756 try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));757 try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));758 try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));759 try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));760}761762763764765766fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {767 output.installSelectPrompt(npkg.pname, npkg.version);768769 var choice_buf: [8]u8 = undefined;770 var choice_len: usize = 0;771 while (choice_len < choice_buf.len) {772 const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;773 if (n == 0) break;774 if (choice_buf[choice_len] == '\n') break;775 choice_len += 1;776 }777 const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");778779 if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {780 try profileInstallPkg(ctx, npkg);781 } else if (choice[0] == 's' or choice[0] == 'S') {782 try systemInstallPkg(ctx, npkg);783 } else if (choice[0] == 't' or choice[0] == 'T') {784 try tryPkg(ctx, npkg);785 }786}787788fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {789 output.installStart(npkg.pname, .profile);790 output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});791 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));792 const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);793 if (code != 0) return error.ProcessFailed;794 output.installDone(npkg.pname);795}796797fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {798 const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});799 defer ctx.gpa.free(config_path);800 const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;801 output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);802 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);803 if (ctx.cfg.confirm) {804 if (output.confirm("apply now? ")) {805 try apply(ctx);806 }807 }808}809810fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {811 output.tryStart(npkg.pname);812 output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});813 output.tryExitHint();814 _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);815 output.tryDone();816}817818pub fn remove(ctx: Ctx) !void {819 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;820 output.removeStart(pkg_name);821 const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);822 if (code != 0) return error.ProcessFailed;823 output.done();824}825826pub fn list(ctx: Ctx) !void {827 output.listHeader(ctx.machine.name);828829 830 831 832 if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {833 defer ctx.gpa.free(json);834 output.listSection("profile");835 renderProfileJson(ctx.gpa, json);836 }837838 839 840 if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {841 defer ctx.gpa.free(paths);842 output.blankLine();843 output.listSection("system");844 var lines = std.mem.splitScalar(u8, paths, '\n');845 while (lines.next()) |line| {846 const t = std.mem.trim(u8, line, " \t\r");847 if (t.len == 0) continue;848 const row = pkgFromStorePath(t);849 850 if (row.version.len == 0) continue;851 output.listPkg(row.name, row.version);852 }853 }854}855856const PkgRow = struct { name: []const u8, version: []const u8 };857858859860861862fn pkgFromStorePath(path: []const u8) PkgRow {863 const base = std.fs.path.basename(path);864 const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;865 var i: usize = 0;866 while (i + 1 < after_hash.len) : (i += 1) {867 if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {868 return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };869 }870 }871 return .{ .name = after_hash, .version = "" };872}873874875876877fn stripOutputSuffix(ver: []const u8) []const u8 {878 const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };879 for (suffixes) |s| {880 if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];881 }882 return ver;883}884885test "pkgFromStorePath splits name and version at first dash-digit" {886 const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");887 try std.testing.expectEqualStrings("ripgrep", a.name);888 try std.testing.expectEqualStrings("15.1.0", a.version);889890 const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");891 try std.testing.expectEqualStrings("helix", b.name);892 try std.testing.expectEqualStrings("25.01", b.version);893894 895 const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");896 try std.testing.expectEqualStrings("curl", c.name);897 try std.testing.expectEqualStrings("8.20.0", c.version);898}899900fn firstStorePath(el: std.json.Value) ?[]const u8 {901 if (el != .object) return null;902 const sp = el.object.get("storePaths") orelse return null;903 if (sp != .array or sp.array.items.len == 0) return null;904 const first = sp.array.items[0];905 return if (first == .string) first.string else null;906}907908909910fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {911 const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;912 defer parsed.deinit();913 if (parsed.value != .object) return;914 const elements = parsed.value.object.get("elements") orelse return;915 switch (elements) {916 .object => |obj| {917 var it = obj.iterator();918 while (it.next()) |entry| {919 const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";920 output.listPkg(entry.key_ptr.*, ver);921 }922 },923 .array => |arr| {924 for (arr.items) |el| {925 const path = firstStorePath(el) orelse continue;926 const row = pkgFromStorePath(path);927 output.listPkg(row.name, row.version);928 }929 },930 else => {},931 }932}933934pub fn tryCmd(ctx: Ctx) !void {935 const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;936 const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };937 try tryPkg(ctx, shell_pkg);938}939940941942const home_help = [_][2][]const u8{943 .{ "apply", "apply home manager configuration" },944 .{ "apply --dry", "preview changes" },945 .{ "back", "roll back one generation" },946 .{ "history", "list all generations" },947 .{ "edit", "open home.nix" },948 .{ "check", "validate without applying" },949 .{ "diff", "changes between generations" },950 .{ "packages", "list managed packages" },951};952953const HomeGen = struct {954 number: u32,955 date: []const u8,956 time: []const u8,957 path: []const u8,958};959960961962963fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {964 var gens: std.ArrayList(HomeGen) = .empty;965 var lines = std.mem.splitScalar(u8, out_str, '\n');966 while (lines.next()) |line| {967 const t = std.mem.trim(u8, line, " \t\r");968 if (t.len == 0) continue;969 var it = std.mem.tokenizeAny(u8, t, " \t");970 const date = it.next() orelse continue;971 const time = it.next() orelse continue;972 var number: ?u32 = null;973 var path: []const u8 = "";974 while (it.next()) |tok| {975 if (std.mem.eql(u8, tok, "id")) {976 if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;977 } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {978 path = tok;979 }980 }981 const num = number orelse continue;982 try gens.append(gpa, .{983 .number = num,984 .date = try gpa.dupe(u8, date),985 .time = try gpa.dupe(u8, time),986 .path = try gpa.dupe(u8, path),987 });988 }989 return gens.toOwnedSlice(gpa);990}991992fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {993 for (gens) |g| {994 gpa.free(g.date);995 gpa.free(g.time);996 gpa.free(g.path);997 }998 gpa.free(gens);999}10001001test "parseHomeGenerations reads id, date and store path" {1002 const a = std.testing.allocator;1003 const sample =1004 \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1005 \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1006 ;1007 const gens = try parseHomeGenerations(a, sample);1008 defer freeHomeGens(a, gens);1009 try std.testing.expectEqual(@as(usize, 2), gens.len);1010 try std.testing.expectEqual(@as(u32, 765), gens[0].number);1011 try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1012 try std.testing.expectEqualStrings("11:56", gens[0].time);1013 try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1014 try std.testing.expectEqual(@as(u32, 764), gens[1].number);1015}101610171018fn homeCurrentGen(ctx: Ctx) u32 {1019 const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1020 defer ctx.gpa.free(out);1021 const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1022 defer freeHomeGens(ctx.gpa, gens);1023 return if (gens.len > 0) gens[0].number else 0;1024}10251026pub fn home(ctx: Ctx) !void {1027 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1028 return output.subcommandHelp("home", &home_help, null);10291030 1031 1032 1033 1034 1035 if (!ctx.machine.local) {1036 output.homeLocalOnly(ctx.machine.name);1037 return;1038 }10391040 const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1041 if (mode == .none) {1042 output.homeNotInstalled();1043 return;1044 }10451046 1047 1048 if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1049 1050 if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);10511052 if (mode == .module) {1053 output.homeModuleManaged();1054 return;1055 }10561057 if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1058 if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1059 if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1060 if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1061 if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);10621063 return output.subcommandHelp("home", &home_help, null);1064}10651066fn homePackages(ctx: Ctx) !void {1067 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1068 defer ctx.gpa.free(out);1069 const gens = try parseHomeGenerations(ctx.gpa, out);1070 defer freeHomeGens(ctx.gpa, gens);10711072 output.homePackagesHeader(ctx.machine.name);1073 if (gens.len == 0 or gens[0].path.len == 0) return;10741075 1076 1077 1078 1079 1080 const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1081 defer ctx.gpa.free(gen_refs);10821083 var refs = gen_refs;1084 var env_refs: ?[]u8 = null;1085 defer if (env_refs) |e| ctx.gpa.free(e);1086 if (findHomeManagerPath(gen_refs)) |pkg_path| {1087 if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1088 env_refs = e;1089 refs = e;1090 } else |_| {}1091 }10921093 1094 1095 1096 var seen = std.StringHashMap(void).init(ctx.gpa);1097 defer seen.deinit();1098 var lines = std.mem.splitScalar(u8, refs, '\n');1099 while (lines.next()) |line| {1100 const t = std.mem.trim(u8, line, " \t\r");1101 if (t.len == 0) continue;1102 const row = pkgFromStorePath(t);1103 if (row.version.len == 0) continue;1104 if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1105 if (seen.contains(row.name)) continue;1106 seen.put(row.name, {}) catch {};1107 output.listPkg(row.name, row.version);1108 }1109}1110111111121113fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1114 var lines = std.mem.splitScalar(u8, refs, '\n');1115 while (lines.next()) |line| {1116 const t = std.mem.trim(u8, line, " \t\r");1117 if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1118 }1119 return null;1120}11211122test "findHomeManagerPath picks the env, not the generation or infra" {1123 const refs =1124 \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31125 \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1126 \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111127 ;1128 try std.testing.expectEqualStrings(1129 "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1130 findHomeManagerPath(refs).?,1131 );1132 try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1133}11341135fn homeDiff(ctx: Ctx) !void {1136 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1137 defer ctx.gpa.free(out);1138 const gens = try parseHomeGenerations(ctx.gpa, out);1139 defer freeHomeGens(ctx.gpa, gens);11401141 1142 if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1143 output.homeNothingToDiff();1144 return;1145 }1146 const newer = gens[0];1147 const older = gens[1];1148 output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1149 if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1150 return error.ProcessFailed;1151}11521153fn homeCheck(ctx: Ctx) !void {1154 output.homeCheckStart(ctx.machine.name);1155 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1156 if (code != 0) {1157 output.checkFailed("");1158 return error.BuildFailed;1159 }1160 output.homeCheckOk();1161}11621163fn homeEdit(ctx: Ctx) !void {1164 1165 1166 const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1167 errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1168 return error.ConfigNotFound;1169 };1170 defer ctx.gpa.free(path);1171 output.homeEditOpen(path, ctx.cfg.editor);1172 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1173}11741175fn homeHistory(ctx: Ctx) !void {1176 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1177 defer ctx.gpa.free(out);1178 const gens = try parseHomeGenerations(ctx.gpa, out);1179 defer freeHomeGens(ctx.gpa, gens);1180 output.homeHistoryHeader(ctx.machine.name);1181 1182 for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1183}11841185fn homeBack(ctx: Ctx) !void {1186 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1187 defer ctx.gpa.free(out);1188 const gens = try parseHomeGenerations(ctx.gpa, out);1189 defer freeHomeGens(ctx.gpa, gens);11901191 1192 if (gens.len < 2) {1193 output.alreadyOldest();1194 return;1195 }1196 const current = gens[0].number;1197 const prev = gens[1].number;11981199 output.homeBackStart(ctx.machine.name, current, prev);1200 if (ctx.cfg.confirm and !output.confirm("")) return;1201 const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1202 if (code != 0) return error.BuildFailed;1203 output.homeBackDone(prev);1204}12051206fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1207 1208 if (mode == .module) {1209 output.homeModuleManaged();1210 return;1211 }1212 if (ctx.dry) {1213 output.homeApplyDry(ctx.machine.name);1214 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1215 if (code != 0) return error.BuildFailed;1216 output.homeApplyDryDone();1217 return;1218 }12191220 output.homeApplyStart(ctx.machine.name);1221 const flake_ref = exec.homeFlakeRef(ctx.gpa, ctx.io, ctx.environ);1222 defer if (flake_ref) |r| ctx.gpa.free(r);1223 if (flake_ref) |ref| {1224 output.printSubstep("home-manager switch --flake {s}", .{ref});1225 } else {1226 output.printSubstep("home-manager switch", .{});1227 }12281229 const start = std.Io.Clock.awake.now(ctx.io);1230 const code = if (flake_ref) |ref|1231 try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)1232 else1233 try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1234 if (code != 0) return error.BuildFailed;12351236 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1237 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1238 output.homeApplyDone(homeCurrentGen(ctx), elapsed);1239}1240124112421243const service_help = [_][2][]const u8{1244 .{ "list", "list running services" },1245 .{ "logs <svc>", "show service logs" },1246 .{ "status <svc>", "service status" },1247 .{ "start <svc>", "start a service" },1248 .{ "stop <svc>", "stop a service" },1249 .{ "restart <svc>", "restart a service" },1250 .{ "enable <svc>", "enable at boot" },1251 .{ "disable <svc>", "disable at boot" },1252};12531254pub fn service(ctx: Ctx) !void {1255 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");1256 if (std.mem.eql(u8, ctx.sub, "list")) {1257 output.serviceListHeader(ctx.machine.name);1258 const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1259 defer ctx.gpa.free(svcs);1260 for (svcs) |s| output.serviceRow(s);1261 return;1262 }1263 if (std.mem.eql(u8, ctx.sub, "logs")) {1264 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1265 const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1266 output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1267 _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1268 return;1269 }1270 if (std.mem.eql(u8, ctx.sub, "status")) {1271 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1272 output.serviceVerb("status", name, ctx.machine.name);1273 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1274 return;1275 }1276 1277 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1278 if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1279 if (!output.confirm("")) return;1280 }1281 output.serviceVerb(ctx.sub, name, ctx.machine.name);1282 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1283 output.serviceDone();1284}1285128612871288const flake_help = [_][2][]const u8{1289 .{ "init", "create a new flake.nix" },1290 .{ "update", "update flake inputs" },1291 .{ "update <in>", "update a specific input" },1292 .{ "check", "validate the flake" },1293 .{ "show", "inspect flake outputs" },1294 .{ "lock", "regenerate flake.lock" },1295 .{ "clone <url>", "clone a flake repository" },1296};12971298pub fn flake(ctx: Ctx) !void {1299 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1300 if (std.mem.eql(u8, ctx.sub, "update")) {1301 output.flakeUpdateStart();1302 const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1303 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1304 output.flakeLockWritten();1305 return;1306 }1307 if (std.mem.eql(u8, ctx.sub, "check")) {1308 output.flakeCheckStart();1309 const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1310 if (code == 0) output.flakeValid() else output.checkFailed("");1311 return;1312 }1313 if (std.mem.eql(u8, ctx.sub, "show")) {1314 const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1315 if (json_out) |j| {1316 defer ctx.gpa.free(j);1317 output.flakeShowHeader("flake outputs");1318 1319 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1320 defer parsed.deinit();1321 if (parsed.value == .object) {1322 var it = parsed.value.object.iterator();1323 while (it.next()) |entry| {1324 if (entry.value_ptr.* == .object) {1325 var inner = entry.value_ptr.object.iterator();1326 while (inner.next()) |e2| {1327 const desc = if (e2.value_ptr.* == .object)1328 if (e2.value_ptr.object.get("description")) |d|1329 if (d == .string) d.string else ""1330 else1331 ""1332 else1333 "";1334 output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1335 }1336 }1337 }1338 }1339 }1340 return;1341 }1342 if (std.mem.eql(u8, ctx.sub, "init")) {1343 _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1344 return;1345 }1346 if (std.mem.eql(u8, ctx.sub, "lock")) {1347 _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1348 return;1349 }1350 if (std.mem.eql(u8, ctx.sub, "clone")) {1351 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1352 _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1353 return;1354 }1355}1356135713581359const store_help = [_][2][]const u8{1360 .{ "info", "store size and counts" },1361 .{ "path <attr>", "store path of a package" },1362 .{ "gc", "collect garbage" },1363 .{ "verify", "verify store integrity" },1364 .{ "repair", "repair corrupted paths" },1365};13661367pub fn store(ctx: Ctx) !void {1368 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1369 if (std.mem.eql(u8, ctx.sub, "gc")) {1370 _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1371 return;1372 }1373 if (std.mem.eql(u8, ctx.sub, "verify")) {1374 output.storeVerifyStart();1375 _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1376 return;1377 }1378 if (std.mem.eql(u8, ctx.sub, "repair")) {1379 if (ctx.cfg.confirm and !output.confirm("")) return;1380 output.storeRepairStart();1381 _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1382 return;1383 }1384 if (std.mem.eql(u8, ctx.sub, "info")) {1385 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1386 output.storeInfo(si);1387 return;1388 }1389 if (std.mem.eql(u8, ctx.sub, "path")) {1390 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1391 const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1392 defer ctx.gpa.free(path);1393 output.storePath(path);1394 return;1395 }1396 1397 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1398 output.storeInfo(si);1399}1400140114021403const channel_help = [_][2][]const u8{1404 .{ "list", "list channels" },1405 .{ "add <url> [name]", "add a channel" },1406 .{ "remove <name>", "remove a channel" },1407 .{ "update", "update all channels" },1408};14091410pub fn channel(ctx: Ctx) !void {1411 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1412 1413 if (flakeSystem(ctx)) output.flakeChannelNote();1414 if (std.mem.eql(u8, ctx.sub, "list")) {1415 output.channelListHeader(ctx.machine.name);1416 const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1417 defer ctx.gpa.free(chans);1418 for (chans) |ch| output.channelRow(ch);1419 return;1420 }1421 if (std.mem.eql(u8, ctx.sub, "add")) {1422 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1423 const name = if (ctx.args.len > 1) ctx.args[1] else "";1424 _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1425 output.channelDone();1426 return;1427 }1428 if (std.mem.eql(u8, ctx.sub, "remove")) {1429 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1430 _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1431 output.channelDone();1432 return;1433 }1434 if (std.mem.eql(u8, ctx.sub, "update")) {1435 return channelUpdateCmd(ctx);1436 }1437}1438143914401441pub fn profile(ctx: Ctx) !void {1442 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1443 output.profileListHeader();1444 const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1445 if (out) |o| {1446 defer ctx.gpa.free(o);1447 var lines = std.mem.splitScalar(u8, o, '\n');1448 while (lines.next()) |line| {1449 const t = std.mem.trim(u8, line, " \t\r");1450 if (t.len == 0) continue;1451 output.profileRow(t, "", "");1452 }1453 }1454 return;1455 }1456 if (std.mem.eql(u8, ctx.sub, "install")) {1457 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1458 _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1459 output.done();1460 return;1461 }1462 if (std.mem.eql(u8, ctx.sub, "remove")) {1463 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1464 _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1465 output.done();1466 return;1467 }1468 if (std.mem.eql(u8, ctx.sub, "upgrade")) {1469 _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1470 output.done();1471 return;1472 }1473}1474147514761477const pkg_help = [_][2][]const u8{1478 .{ "why <pkg>", "what pulled it in" },1479 .{ "deps <pkg>", "direct dependencies" },1480 .{ "size <pkg>", "closure size" },1481 .{ "path <pkg>", "store path" },1482 .{ "closure <pkg>", "full closure" },1483};14841485pub fn pkg(ctx: Ctx) !void {1486 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1487 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1488 if (std.mem.eql(u8, ctx.sub, "why")) {1489 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1490 return;1491 }1492 if (std.mem.eql(u8, ctx.sub, "deps")) {1493 if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1494 return;1495 }1496 if (std.mem.eql(u8, ctx.sub, "size")) {1497 const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1498 defer ctx.gpa.free(s);1499 output.pkgResult("size", s);1500 return;1501 }1502 if (std.mem.eql(u8, ctx.sub, "path")) {1503 const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1504 defer ctx.gpa.free(p);1505 output.pkgResult("path", p);1506 return;1507 }1508 if (std.mem.eql(u8, ctx.sub, "closure")) {1509 if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1510 return;1511 }1512}1513151415151516pub fn why(ctx: Ctx) !void {1517 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1518 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1519}1520152115221523pub fn pin(ctx: Ctx) !void {1524 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1525 const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1526 exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1527 output.pinDone(input, commit);1528}15291530pub fn unpin(ctx: Ctx) !void {1531 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1532 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1533 output.unpinDone(input);1534}1535153615371538pub fn hash(ctx: Ctx) !void {1539 const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1540 const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1541 defer ctx.gpa.free(h);1542 output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1543}15441545pub fn fetch(ctx: Ctx) !void {1546 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1547 const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1548 defer ctx.gpa.free(h);1549 output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1550}1551155215531554pub fn build(ctx: Ctx) !void {1555 const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1556 output.buildStart(attr orelse "default");1557 const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1558 if (code != 0) return error.BuildFailed;1559 output.buildDone();1560}15611562pub fn runCmd(ctx: Ctx) !void {1563 const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1564 output.runStart(pkg_arg);1565 _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1566}1567156815691570pub fn hello(ctx: Ctx) !void {1571 output.hello(ctx.cfg.machines);1572}15731574const ConfigKind = enum { flake, channel, none };1575157615771578fn scanConfig(io: std.Io) ConfigKind {1579 if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1580 if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1581 return .none;1582}15831584158515861587pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1588 output.firstRunBanner();1589 output.firstRunNoConfig();15901591 var name_buf: [256]u8 = undefined;1592 var path_buf: [256]u8 = undefined;15931594 const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);15951596 output.firstRunScanning();1597 const kind = scanConfig(io);1598 switch (kind) {1599 .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),1600 .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),1601 .none => output.firstRunNoneFound(),1602 }16031604 1605 1606 const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";1607 const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);16081609 1610 1611 const use_flakes = exec.dirHasFlake(gpa, io, config_path);16121613 const conf_path = try config.configPath(gpa, environ);1614 defer gpa.free(conf_path);1615 if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);16161617 1618 const flake_line = if (use_flakes) "flake = true\n" else "";1619 var content_buf: [1024]u8 = undefined;1620 const content = try std.fmt.bufPrint(1621 &content_buf,1622 "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",1623 .{ flake_line, machine_name, config_path },1624 );16251626 const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1627 errors.error_info.setMessage("could not write {s}", .{conf_path});1628 return error.Internal;1629 };1630 defer file.close(io);1631 file.writePositionalAll(io, content, 0) catch {1632 errors.error_info.setMessage("could not write {s}", .{conf_path});1633 return error.Internal;1634 };16351636 output.firstRunWritten(conf_path);1637}16381639pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1640 1641 1642 1643 config.migrateLegacyConfig(gpa, io, environ);1644 if (config.configPath(gpa, environ)) |conf_path| {1645 defer gpa.free(conf_path);1646 if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1647 f.close(io);1648 } else |_| {1649 try firstRunWizard(gpa, io, environ);1650 errors.error_info.reset();1651 }1652 } else |_| {}16531654 output.setupCheck();1655 const status = exec.checkNixFeatures(gpa, io, environ);1656 output.setupFeatures(status.nix_command, status.flakes);16571658 if (status.allEnabled()) {1659 output.setupAllSet();1660 api.ensureRegistryPinned(gpa, io, environ);1661 return;1662 }16631664 1665 1666 1667 1668 if (exec.isNixOS(io)) {1669 const conf_path = "/etc/nixos/configuration.nix";1670 if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1671 output.setupNixosNeedsRebuild(conf_path);1672 return;1673 }1674 output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1675 if (output.confirmDefaultNo("add it now?")) {1676 if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1677 output.setupNixosWrote(conf_path);1678 } else |_| {1679 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1680 }1681 } else {1682 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1683 }1684 return;1685 }16861687 1688 output.setupEnabling();1689 const path = try exec.enableNixFeatures(gpa, io, environ);1690 defer gpa.free(path);16911692 output.setupDone(path);1693 api.ensureRegistryPinned(gpa, io, environ);1694}1695169616971698fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1699 var ts_buf: [32]u8 = undefined;1700 const ts = nowIso(ctx.io, &ts_buf);1701 var buf: [256]u8 = undefined;1702 const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1703 ts, ctx.machine.name, action, gen,1704 }) catch return;1705 exec.appendNinaLog(ctx.io, ctx.environ, entry);1706}1707170817091710fn nowIso(io: std.Io, buf: []u8) []const u8 {1711 const fallback = "1970-01-01T00:00:00Z";1712 const ns = std.Io.Clock.real.now(io).toNanoseconds();1713 if (ns <= 0) return fallback;1714 const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1715 const es = std.time.epoch.EpochSeconds{ .secs = secs };1716 const ed = es.getEpochDay();1717 const yd = ed.calculateYearDay();1718 const md = yd.calculateMonthDay();1719 const ds = es.getDaySeconds();1720 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", .{1721 yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1722 ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1723 }) catch return fallback;1724}