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}3940fn runPreHook(ctx: Ctx, hook_name: []const u8) !bool {41 const hook = try exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name);42 defer ctx.gpa.free(hook.output);43 switch (hook.result) {44 .not_found, .ok => return true,45 .failed => {46 output.hookFailed(hook_name, hook.exit_code, hook.output);47 return output.confirmDefaultNo("continue anyway?");48 },49 }50}5152fn runPostHook(ctx: Ctx, hook_name: []const u8) void {53 const hook = exec.runHook(ctx.gpa, ctx.io, ctx.environ, hook_name) catch return;54 defer ctx.gpa.free(hook.output);55 if (hook.result == .failed) {56 output.hookWarning(hook_name, hook.exit_code, hook.output);57 }58}5960pub fn apply(ctx: Ctx) !void {61 if (ctx.dry) {62 output.applyDry(ctx.machine.name);63 const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);64 if (code != 0) return error.BuildFailed;65 output.applyDryDone();66 return;67 }68 if (ctx.check) {69 return check(ctx);70 }7172 if (!try runPreHook(ctx, "pre-apply")) {73 output.aborted();74 return error.HookAborted;75 }7677 output.applyStart(ctx.machine.name);78 const start = std.Io.Clock.awake.now(ctx.io);7980 const code = exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa) catch |e| {81 exec.markApplyFailed(ctx.io, ctx.environ);82 output.applyFailed("");83 return e;84 };8586 if (code != 0) {87 exec.markApplyFailed(ctx.io, ctx.environ);88 output.applyFailed("");89 return error.BuildFailed;90 }9192 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());93 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));94 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;95 const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);96 output.applyDone(gen, elapsed, after_failure);97 runPostHook(ctx, "post-apply");98 logAction(ctx, "apply", gen);99}100101pub fn check(ctx: Ctx) !void {102 output.checkStart(ctx.machine.name);103 const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);104 if (code != 0) {105 output.checkFailed("");106 return error.BuildFailed;107 }108 output.checkOk();109}110111pub fn back(ctx: Ctx) !void {112 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);113 defer ctx.gpa.free(gens);114115 var current: u32 = 0;116 for (gens) |g| if (g.current) {117 current = g.number;118 };119120 121 122 var prev: u32 = 0;123 var has_prev = false;124 for (gens) |g| {125 if (g.number < current and (!has_prev or g.number > prev)) {126 prev = g.number;127 has_prev = true;128 }129 }130 if (!has_prev) {131 output.alreadyOldest();132 return;133 }134135 if (!try runPreHook(ctx, "pre-back")) {136 output.aborted();137 return error.HookAborted;138 }139140 output.backStart(ctx.machine.name, current, prev);141 if (ctx.cfg.confirm and !output.confirm("")) return;142143 144 145 146 const code = if (flakeSystem(ctx))147 try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, prev)148 else149 try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);150 if (code != 0) return error.BuildFailed;151 output.backDone(prev);152 runPostHook(ctx, "post-back");153}154155pub fn go(ctx: Ctx) !void {156 if (ctx.args.len == 0) return error.Internal;157 const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;158 const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);159160 output.goStart(ctx.machine.name, current, target);161 if (ctx.cfg.confirm and !output.confirm("")) return;162163 const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);164 if (code != 0) return error.ProcessFailed;165 output.generationDone(target);166}167168pub fn history(ctx: Ctx) !void {169 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);170 defer ctx.gpa.free(gens);171 output.historyHeader(ctx.machine.name);172 for (gens) |g| output.historyRow(g);173}174175const gen_help = [_][2][]const u8{176 .{ "list", "list generations" },177 .{ "current", "show current generation" },178 .{ "delete <n>", "delete generation n" },179 .{ "delete old", "delete old generations" },180};181182pub fn genCmd(ctx: Ctx) !void {183 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("gen", &gen_help, null);184 if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);185 if (std.mem.eql(u8, ctx.sub, "current")) {186 const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);187 output.genCurrent(n);188 return;189 }190 if (std.mem.eql(u8, ctx.sub, "delete")) {191 if (ctx.args.len == 0) return error.Internal;192 if (std.mem.eql(u8, ctx.args[0], "old")) {193 if (ctx.cfg.confirm and !output.confirm("")) return;194 _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);195 } else {196 const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;197 if (ctx.cfg.confirm and !output.confirm("")) return;198 _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);199 }200 output.done();201 return;202 }203 return error.Internal;204}205206pub fn clean(ctx: Ctx) !void {207 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);208 defer ctx.gpa.free(gens);209 const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");210 const total: u32 = @intCast(gens.len);211 212 213 const keep: u32 = if (all) 1 else ctx.cfg.generations;214 if (total <= keep) {215 output.cleanNothing(ctx.machine.name, total);216 return;217 }218 output.cleanStart(ctx.machine.name, keep, total);219 if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;220 _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);221 output.cleanDone();222}223224pub fn statusCmd(ctx: Ctx) !void {225 output.statusHeader();226 227 228 if (ctx.all and ctx.cfg.machines.len > 0) {229 for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);230 } else {231 statusRowFor(ctx, &ctx.machine);232 }233 homeStatusLine(ctx);234}235236237238239fn homeStatusLine(ctx: Ctx) void {240 if (exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ) != .standalone) return;241 const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return;242 defer ctx.gpa.free(out);243 const gens = parseHomeGenerations(ctx.gpa, out) catch return;244 defer freeHomeGens(ctx.gpa, gens);245 if (gens.len == 0) return;246 output.statusHomeRow(gens[0].number, gens[0].date);247}248249fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {250 251 252 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {253 output.statusRow(machine.name, 0, "", "", false);254 return;255 };256 const st = exec.systemStatus(ctx.gpa, ctx.io, machine);257 defer ctx.gpa.free(st.size);258 defer ctx.gpa.free(st.age);259 output.statusRow(machine.name, gen, st.age, st.size, true);260}261262pub fn diff(ctx: Ctx) !void {263 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);264 defer ctx.gpa.free(gens);265 var current: u32 = 0;266 var prev: u32 = 0;267 for (gens) |g| {268 if (g.current) current = g.number;269 if (!g.current and g.number > prev and g.number < current) prev = g.number;270 }271 if (ctx.args.len >= 2) {272 const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;273 const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;274 output.diffHeader(a, b, ctx.machine.name);275 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;276 } else {277 output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);278 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;279 }280}281282pub fn mood(ctx: Ctx) !void {283 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;284 const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);285 defer ctx.gpa.free(st.size);286 defer ctx.gpa.free(st.age);287 const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");288 defer ctx.gpa.free(state);289 output.mood(ctx.machine.name, state, gen, st.age, st.size);290}291292pub fn doctor(ctx: Ctx) !void {293 output.doctorHeader(ctx.machine.name);294 const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);295 defer ctx.gpa.free(checks);296 var warnings: u32 = 0;297 var failures: u32 = 0;298 for (checks) |ch| {299 output.doctorRow(ch);300 if (ch.status == .warn) warnings += 1;301 if (ch.status == .fail) failures += 1;302 }303304 305 306 const hm_mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);307 if (hm_mode != .none) {308 const note = homeDoctorNote(ctx, hm_mode);309 defer ctx.gpa.free(note);310 output.doctorRow(.{ .name = "home manager", .status = .ok, .note = note });311 }312313 output.doctorSummary(warnings, failures);314}315316317318fn homeDoctorNote(ctx: Ctx, mode: exec.HomeManagerMode) []const u8 {319 const label = switch (mode) {320 .standalone => "standalone",321 .module => "module",322 .none => "",323 };324 if (mode == .standalone) {325 const gen = homeCurrentGen(ctx);326 if (gen != 0)327 return std.fmt.allocPrint(ctx.gpa, "{s} gen {d}", .{ label, gen }) catch328 (ctx.gpa.dupe(u8, label) catch "");329 }330 return ctx.gpa.dupe(u8, label) catch "";331}332333334pub fn update(ctx: Ctx) !void {335 output.updateSelfStart();336337 if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {338 output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));339 return error.Internal;340 }341342 const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");343 const source_url = env_url orelse UPDATE_URL;344345 const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {346 error.NetworkError, error.HttpError => {347 output.updateSelfNetworkError();348 return;349 },350 else => return e,351 };352 defer ctx.gpa.free(body);353354 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {355 output.printWarning("could not parse release metadata");356 return;357 };358 defer parsed.deinit();359360 const root = parsed.value;361 if (root != .object) {362 output.printWarning("malformed release metadata");363 return;364 }365366 const remote_ver = blk: {367 const v = root.object.get("version") orelse {368 output.printWarning("malformed release metadata");369 return;370 };371 break :blk switch (v) {372 .string => |s| s,373 else => {374 output.printWarning("malformed release metadata");375 return;376 },377 };378 };379 const release_notes = blk: {380 const v = root.object.get("release_notes") orelse break :blk "";381 break :blk switch (v) {382 .string => |s| s,383 else => "",384 };385 };386387 if (std.mem.eql(u8, remote_ver, version.VERSION)) {388 output.updateSelfCurrent(version.VERSION);389 return;390 }391392 output.updateSelfAvailable(version.VERSION, remote_ver);393 output.updateSelfReleaseNotes(release_notes);394 if (ctx.check) return;395396 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;397 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {398 errors.error_info.setMessage("could not determine install path", .{});399 return error.Internal;400 };401402 403 404 405 406 407 if (std.mem.startsWith(u8, install_path, "/nix/store/")) {408 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);409 defer {410 if (nina_element) |n| ctx.gpa.free(n);411 }412 if (nina_element == null) {413 output.updateSelfNotInProfile();414 return;415 }416 const element = nina_element.?;417 output.updateSelfNixManaged(remote_ver);418 if (ctx.cfg.confirm and !output.confirm("")) return;419 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", element }) catch {420 output.updateSelfNixFailed();421 return;422 };423 if (ec != 0) {424 output.updateSelfNixFailed();425 return;426 }427 output.updateSelfDone(version.VERSION, remote_ver);428 return;429 }430431 const plat_info = blk: {432 const pv = root.object.get("platforms") orelse break :blk null;433 if (pv != .object) break :blk null;434 break :blk pv.object.get(version.PLATFORM);435 };436 if (plat_info == null) {437 output.updateSelfNoPlatform(version.PLATFORM);438 return;439 }440441 const dl_url = blk: {442 const v = plat_info.?.object.get("url") orelse {443 output.printWarning("malformed release metadata");444 return;445 };446 break :blk switch (v) {447 .string => |s| s,448 else => {449 output.printWarning("malformed release metadata");450 return;451 },452 };453 };454455 const raw_cksum = blk: {456 if (plat_info.?.object.get("blake3")) |v|457 break :blk switch (v) {458 .string => |s| s,459 else => {460 output.printWarning("malformed release metadata");461 return;462 },463 };464 if (plat_info.?.object.get("checksum")) |v|465 break :blk switch (v) {466 .string => |s| s,467 else => {468 output.printWarning("malformed release metadata");469 return;470 },471 };472 output.printWarning("missing checksum in release metadata");473 return;474 };475 const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;476477 if (ctx.cfg.confirm and !output.confirm("")) return;478479 output.updateSelfDownloading(remote_ver, version.PLATFORM);480 const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {481 output.printWarning("download failed — check your connection and try again");482 return;483 };484 defer ctx.gpa.free(tmp_path);485486 output.updateSelfVerifying();487 exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {488 error.ChecksumMismatch => {489 output.updateSelfChecksumFailed();490 return;491 },492 else => return e,493 };494495 output.updateSelfDone(version.VERSION, remote_ver);496}497498499500501pub fn goodbye(ctx: Ctx) !void {502 output.goodbyeStart();503504 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;505 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {506 errors.error_info.setMessage("could not determine install path", .{});507 return error.Internal;508 };509510 511 if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {512 output.goodbyeFile(install_path);513 if (ctx.cfg.confirm and !output.confirm("")) return;514 std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {515 errors.error_info.setMessage("could not remove {s}", .{install_path});516 return e;517 };518 output.goodbyeDone();519 return;520 }521522 523 const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);524 defer {525 if (nina_element) |n| ctx.gpa.free(n);526 }527528 if (nina_element == null) {529 errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});530 return error.Internal;531 }532533 output.goodbyeNix();534 if (ctx.cfg.confirm and !output.confirm("")) return;535 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {536 output.goodbyeFailed("nix profile remove failed");537 return;538 };539 if (ec != 0) {540 output.goodbyeFailed("nix profile remove failed");541 return;542 }543 output.goodbyeDone();544}545546fn channelUpdateCmd(ctx: Ctx) !void {547 output.updateStart(ctx.machine.name);548 _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);549 output.updateDone();550}551552pub fn upgrade(ctx: Ctx) !void {553 if (!try runPreHook(ctx, "pre-upgrade")) {554 output.aborted();555 return error.HookAborted;556 }557558 output.upgradeStart(ctx.machine.name);559 560 561 562 if (flakeSystem(ctx)) {563 output.printSubstep("updating flake inputs", .{});564 _ = exec.flakeUpdateAt(ctx.io, &ctx.machine, ctx.gpa, ctx.machine.config_path) catch {};565 } else {566 output.printSubstep("updating channels", .{});567 _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};568 }569 output.printSubstep("rebuilding", .{});570 const start = std.Io.Clock.awake.now(ctx.io);571 const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);572 if (code != 0) {573 output.applyFailed("");574 return error.BuildFailed;575 }576 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());577 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));578 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;579 output.applyDone(gen, elapsed, false);580 runPostHook(ctx, "post-upgrade");581}582583pub fn log(ctx: Ctx) !void {584 output.logHeader(ctx.machine.name);585 const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {586 587 return;588 };589 defer ctx.gpa.free(content);590 var lines = std.mem.splitScalar(u8, content, '\n');591 while (lines.next()) |line| {592 const t = std.mem.trim(u8, line, " \t\r");593 if (t.len == 0) continue;594 if (t[0] == '{') {595 renderJsonLogLine(ctx.gpa, t);596 } else {597 598 var parts = std.mem.tokenizeScalar(u8, t, '\t');599 const date = parts.next() orelse continue;600 const time = parts.next() orelse "";601 const action = parts.next() orelse "";602 const detail = parts.next() orelse "";603 output.logRow(date, time, action, detail);604 }605 }606}607608609610fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {611 const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {612 output.logRow(line, "", "", ""); 613 return;614 };615 defer parsed.deinit();616 if (parsed.value != .object) return;617 const o = parsed.value.object;618619 const ts = jsonStr(o, "ts");620 const date = if (ts.len >= 10) ts[0..10] else ts;621 const time = if (ts.len >= 16) ts[11..16] else "";622 const action = jsonStr(o, "command");623 const outcome = jsonStr(o, "outcome");624625 var buf: [160]u8 = undefined;626 var detail: []const u8 = outcome;627 if (o.get("gen_after")) |g| {628 if (g == .integer) {629 detail = std.fmt.bufPrint(&buf, "{s} -> gen {d}", .{ outcome, g.integer }) catch outcome;630 }631 }632 output.logRow(date, time, action, detail);633}634635fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {636 if (o.get(key)) |v| {637 if (v == .string) return v.string;638 }639 return "";640}641642pub fn edit(ctx: Ctx) !void {643 const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");644 const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";645 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });646 defer ctx.gpa.free(path);647 output.editOpen(path, ctx.cfg.editor);648 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);649}650651pub fn fmt(ctx: Ctx) !void {652 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});653 defer ctx.gpa.free(path);654 if (ctx.check) {655 const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);656 if (code != 0) output.fmtNeedsFormat() else output.fmtDone();657 return;658 }659 output.fmtStart(path);660 _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);661 output.fmtDone();662}663664pub fn repl(ctx: Ctx) !void {665 output.replStart();666 _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);667}668669pub fn develop(ctx: Ctx) !void {670 if (std.mem.eql(u8, ctx.sub, "show")) {671 _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);672 return;673 }674 const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))675 ctx.args[0]676 else677 null;678 output.developStart(&.{});679 _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);680 output.developDone();681}682683pub fn info(ctx: Ctx) !void {684 output.infoHeader(ctx.machine.name);685 const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");686 defer ctx.gpa.free(nixos_ver);687 output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));688689 const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");690 defer ctx.gpa.free(kernel);691 output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));692693 const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");694 defer ctx.gpa.free(uptime);695 output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));696}697698pub fn boot(ctx: Ctx) !void {699 output.bootHeader(ctx.machine.name);700 const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};701 defer ctx.gpa.free(entries);702 for (entries, 0..) |entry, i| output.bootEntry(entry, i);703}704705pub fn searchCmd(ctx: Ctx) !void {706 const query = if (ctx.args.len > 0) ctx.args[0] else "";707 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);708 const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);709 if (selected) |npkg| try selectAndInstall(ctx, npkg);710}711712pub fn optionCmd(ctx: Ctx) !void {713 const query = if (ctx.args.len > 0) ctx.args[0] else "";714 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);715 _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);716}717718pub fn install(ctx: Ctx) !void {719 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;720721 api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);722723 724 const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {725 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});726 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});727 return error.PackageNotFound;728 };729730 if (pkgs.len == 0) {731 732 if (closestPackage(ctx, pkg_name)) |sugg| {733 output.didYouMean(pkg_name, sugg.pname);734 if (output.confirm("")) try selectAndInstall(ctx, sugg);735 return;736 }737 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});738 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});739 return error.PackageNotFound;740 }741742 743 744 var found = pkgs[0];745 for (pkgs) |p| {746 if (std.mem.eql(u8, p.pname, pkg_name)) {747 found = p;748 break;749 }750 }751 try selectAndInstall(ctx, found);752}753754755756757fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {758 if (query.len < 2) return null;759 var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};760 if (candidates.len == 0 and query.len > 2) {761 candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};762 }763 if (candidates.len == 0) return null;764765 var best: ?types.NixPackage = null;766 var best_dist: usize = std.math.maxInt(usize);767 for (candidates) |p| {768 const d = editDistance(query, p.pname);769 if (d > 0 and d < best_dist) {770 best_dist = d;771 best = p;772 }773 }774 775 const threshold = @max(@as(usize, 2), query.len / 3);776 return if (best_dist <= threshold) best else null;777}778779780781fn editDistance(a: []const u8, b: []const u8) usize {782 const n = b.len;783 if (a.len == 0) return n;784 if (n == 0) return a.len;785 if (n + 1 > 128) return std.math.maxInt(usize);786 var prev: [128]usize = undefined;787 var curr: [128]usize = undefined;788 var j: usize = 0;789 while (j <= n) : (j += 1) prev[j] = j;790 var i: usize = 1;791 while (i <= a.len) : (i += 1) {792 curr[0] = i;793 j = 1;794 while (j <= n) : (j += 1) {795 const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;796 curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));797 }798 @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);799 }800 return prev[n];801}802803test "editDistance is case-insensitive Levenshtein" {804 try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));805 try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));806 try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));807 try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));808}809810811812813814fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {815 output.installSelectPrompt(npkg.pname, npkg.version);816817 var choice_buf: [8]u8 = undefined;818 var choice_len: usize = 0;819 while (choice_len < choice_buf.len) {820 const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;821 if (n == 0) break;822 if (choice_buf[choice_len] == '\n') break;823 choice_len += 1;824 }825 const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");826827 if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {828 try profileInstallPkg(ctx, npkg);829 } else if (choice[0] == 's' or choice[0] == 'S') {830 try systemInstallPkg(ctx, npkg);831 } else if (choice[0] == 't' or choice[0] == 'T') {832 try tryPkg(ctx, npkg);833 }834}835836fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {837 output.installStart(npkg.pname, .profile);838 output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});839 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));840 const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);841 if (code != 0) return error.ProcessFailed;842 output.installDone(npkg.pname);843}844845fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {846 const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});847 defer ctx.gpa.free(config_path);848 const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;849 output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);850 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);851 if (ctx.cfg.confirm) {852 if (output.confirm("apply now? ")) {853 try apply(ctx);854 }855 }856}857858fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {859 output.tryStart(npkg.pname);860 output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});861 output.tryExitHint();862 _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);863 output.tryDone();864}865866pub fn remove(ctx: Ctx) !void {867 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;868 output.removeStart(pkg_name);869 const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);870 if (code != 0) return error.ProcessFailed;871 output.done();872}873874pub fn list(ctx: Ctx) !void {875 output.listHeader(ctx.machine.name);876877 878 879 880 if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {881 defer ctx.gpa.free(json);882 output.listSection("profile");883 renderProfileJson(ctx.gpa, json);884 }885886 887 888 if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {889 defer ctx.gpa.free(paths);890 output.blankLine();891 output.listSection("system");892 var lines = std.mem.splitScalar(u8, paths, '\n');893 while (lines.next()) |line| {894 const t = std.mem.trim(u8, line, " \t\r");895 if (t.len == 0) continue;896 const row = pkgFromStorePath(t);897 898 if (row.version.len == 0) continue;899 output.listPkg(row.name, row.version);900 }901 }902}903904const PkgRow = struct { name: []const u8, version: []const u8 };905906907908909910fn pkgFromStorePath(path: []const u8) PkgRow {911 const base = std.fs.path.basename(path);912 const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;913 var i: usize = 0;914 while (i + 1 < after_hash.len) : (i += 1) {915 if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {916 return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };917 }918 }919 return .{ .name = after_hash, .version = "" };920}921922923924925fn stripOutputSuffix(ver: []const u8) []const u8 {926 const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };927 for (suffixes) |s| {928 if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];929 }930 return ver;931}932933test "pkgFromStorePath splits name and version at first dash-digit" {934 const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");935 try std.testing.expectEqualStrings("ripgrep", a.name);936 try std.testing.expectEqualStrings("15.1.0", a.version);937938 const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");939 try std.testing.expectEqualStrings("helix", b.name);940 try std.testing.expectEqualStrings("25.01", b.version);941942 943 const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");944 try std.testing.expectEqualStrings("curl", c.name);945 try std.testing.expectEqualStrings("8.20.0", c.version);946}947948fn firstStorePath(el: std.json.Value) ?[]const u8 {949 if (el != .object) return null;950 const sp = el.object.get("storePaths") orelse return null;951 if (sp != .array or sp.array.items.len == 0) return null;952 const first = sp.array.items[0];953 return if (first == .string) first.string else null;954}955956957958fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {959 const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;960 defer parsed.deinit();961 if (parsed.value != .object) return;962 const elements = parsed.value.object.get("elements") orelse return;963 switch (elements) {964 .object => |obj| {965 var it = obj.iterator();966 while (it.next()) |entry| {967 const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";968 output.listPkg(entry.key_ptr.*, ver);969 }970 },971 .array => |arr| {972 for (arr.items) |el| {973 const path = firstStorePath(el) orelse continue;974 const row = pkgFromStorePath(path);975 output.listPkg(row.name, row.version);976 }977 },978 else => {},979 }980}981982pub fn tryCmd(ctx: Ctx) !void {983 const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;984 const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };985 try tryPkg(ctx, shell_pkg);986}987988989990const home_help = [_][2][]const u8{991 .{ "apply", "apply home-manager configuration" },992 .{ "apply --dry", "preview changes without activating" },993 .{ "back", "roll back one generation" },994 .{ "history", "list all generations" },995 .{ "edit", "open home.nix" },996 .{ "check", "validate without applying" },997 .{ "diff", "compare the latest two generations" },998 .{ "packages", "list managed packages" },999};10001001const HomeGen = struct {1002 number: u32,1003 date: []const u8,1004 time: []const u8,1005 path: []const u8,1006};10071008100910101011fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {1012 var gens: std.ArrayList(HomeGen) = .empty;1013 var lines = std.mem.splitScalar(u8, out_str, '\n');1014 while (lines.next()) |line| {1015 const t = std.mem.trim(u8, line, " \t\r");1016 if (t.len == 0) continue;1017 var it = std.mem.tokenizeAny(u8, t, " \t");1018 const date = it.next() orelse continue;1019 const time = it.next() orelse continue;1020 var number: ?u32 = null;1021 var path: []const u8 = "";1022 while (it.next()) |tok| {1023 if (std.mem.eql(u8, tok, "id")) {1024 if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;1025 } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {1026 path = tok;1027 }1028 }1029 const num = number orelse continue;1030 try gens.append(gpa, .{1031 .number = num,1032 .date = try gpa.dupe(u8, date),1033 .time = try gpa.dupe(u8, time),1034 .path = try gpa.dupe(u8, path),1035 });1036 }1037 return gens.toOwnedSlice(gpa);1038}10391040fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {1041 for (gens) |g| {1042 gpa.free(g.date);1043 gpa.free(g.time);1044 gpa.free(g.path);1045 }1046 gpa.free(gens);1047}10481049test "parseHomeGenerations reads id, date and store path" {1050 const a = std.testing.allocator;1051 const sample =1052 \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation1053 \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation1054 ;1055 const gens = try parseHomeGenerations(a, sample);1056 defer freeHomeGens(a, gens);1057 try std.testing.expectEqual(@as(usize, 2), gens.len);1058 try std.testing.expectEqual(@as(u32, 765), gens[0].number);1059 try std.testing.expectEqualStrings("2026-06-01", gens[0].date);1060 try std.testing.expectEqualStrings("11:56", gens[0].time);1061 try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);1062 try std.testing.expectEqual(@as(u32, 764), gens[1].number);1063}106410651066fn homeCurrentGen(ctx: Ctx) u32 {1067 const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;1068 defer ctx.gpa.free(out);1069 const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;1070 defer freeHomeGens(ctx.gpa, gens);1071 return if (gens.len > 0) gens[0].number else 0;1072}10731074pub fn home(ctx: Ctx) !void {1075 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))1076 return output.subcommandHelp("home", &home_help, null);10771078 1079 1080 1081 1082 1083 if (!ctx.machine.local) {1084 output.homeLocalOnly(ctx.machine.name);1085 return;1086 }10871088 const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);1089 if (mode == .none) {1090 output.homeNotInstalled();1091 return;1092 }10931094 1095 1096 if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);1097 1098 if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);10991100 if (mode == .module) {1101 output.homeModuleManaged();1102 return;1103 }11041105 if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);1106 if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);1107 if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);1108 if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);1109 if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);11101111 return output.subcommandHelp("home", &home_help, null);1112}11131114fn homePackages(ctx: Ctx) !void {1115 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1116 defer ctx.gpa.free(out);1117 const gens = try parseHomeGenerations(ctx.gpa, out);1118 defer freeHomeGens(ctx.gpa, gens);11191120 output.homePackagesHeader(ctx.machine.name);1121 if (gens.len == 0 or gens[0].path.len == 0) return;11221123 1124 1125 1126 1127 1128 const gen_refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;1129 defer ctx.gpa.free(gen_refs);11301131 var refs = gen_refs;1132 var env_refs: ?[]u8 = null;1133 defer if (env_refs) |e| ctx.gpa.free(e);1134 if (findHomeManagerPath(gen_refs)) |pkg_path| {1135 if (exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, pkg_path)) |e| {1136 env_refs = e;1137 refs = e;1138 } else |_| {}1139 }11401141 1142 1143 1144 var seen = std.StringHashMap(void).init(ctx.gpa);1145 defer seen.deinit();1146 var lines = std.mem.splitScalar(u8, refs, '\n');1147 while (lines.next()) |line| {1148 const t = std.mem.trim(u8, line, " \t\r");1149 if (t.len == 0) continue;1150 const row = pkgFromStorePath(t);1151 if (row.version.len == 0) continue;1152 if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;1153 if (seen.contains(row.name)) continue;1154 seen.put(row.name, {}) catch {};1155 output.listPkg(row.name, row.version);1156 }1157}1158115911601161fn findHomeManagerPath(refs: []const u8) ?[]const u8 {1162 var lines = std.mem.splitScalar(u8, refs, '\n');1163 while (lines.next()) |line| {1164 const t = std.mem.trim(u8, line, " \t\r");1165 if (std.mem.indexOf(u8, t, "home-manager-path") != null) return t;1166 }1167 return null;1168}11691170test "findHomeManagerPath picks the env, not the generation or infra" {1171 const refs =1172 \\/nix/store/aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa-bash-5.31173 \\/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path1174 \\/nix/store/cccccccccccccccccccccccccccccccc-coreutils-9.111175 ;1176 try std.testing.expectEqualStrings(1177 "/nix/store/bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb-home-manager-path",1178 findHomeManagerPath(refs).?,1179 );1180 try std.testing.expectEqual(@as(?[]const u8, null), findHomeManagerPath("/nix/store/x-bash-5.3\n"));1181}11821183fn homeDiff(ctx: Ctx) !void {1184 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1185 defer ctx.gpa.free(out);1186 const gens = try parseHomeGenerations(ctx.gpa, out);1187 defer freeHomeGens(ctx.gpa, gens);11881189 1190 if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {1191 output.homeNothingToDiff();1192 return;1193 }1194 const newer = gens[0];1195 const older = gens[1];1196 output.homeDiffHeader(older.number, newer.number, ctx.machine.name);1197 if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)1198 return error.ProcessFailed;1199}12001201fn homeCheck(ctx: Ctx) !void {1202 output.homeCheckStart(ctx.machine.name);1203 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1204 if (code != 0) {1205 output.checkFailed("");1206 return error.BuildFailed;1207 }1208 output.homeCheckOk();1209}12101211fn homeEdit(ctx: Ctx) !void {1212 1213 1214 const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1215 errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1216 return error.ConfigNotFound;1217 };1218 defer ctx.gpa.free(path);1219 output.homeEditOpen(path, ctx.cfg.editor);1220 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1221}12221223fn homeHistory(ctx: Ctx) !void {1224 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1225 defer ctx.gpa.free(out);1226 const gens = try parseHomeGenerations(ctx.gpa, out);1227 defer freeHomeGens(ctx.gpa, gens);1228 output.homeHistoryHeader(ctx.machine.name);1229 1230 for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1231}12321233fn homeBack(ctx: Ctx) !void {1234 const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1235 defer ctx.gpa.free(out);1236 const gens = try parseHomeGenerations(ctx.gpa, out);1237 defer freeHomeGens(ctx.gpa, gens);12381239 1240 if (gens.len < 2) {1241 output.alreadyOldest();1242 return;1243 }1244 const current = gens[0].number;1245 const prev = gens[1].number;12461247 output.homeBackStart(ctx.machine.name, current, prev);1248 if (ctx.cfg.confirm and !output.confirm("")) return;1249 const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1250 if (code != 0) return error.BuildFailed;1251 output.homeBackDone(prev);1252}12531254fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1255 1256 if (mode == .module) {1257 output.homeModuleManaged();1258 return;1259 }1260 if (ctx.dry) {1261 output.homeApplyDry(ctx.machine.name);1262 const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1263 if (code != 0) return error.BuildFailed;1264 output.homeApplyDryDone();1265 return;1266 }12671268 if (!try runPreHook(ctx, "pre-home")) {1269 output.aborted();1270 return error.HookAborted;1271 }12721273 output.homeApplyStart(ctx.machine.name);1274 const flake_ref = exec.homeFlakeRef(ctx.gpa, ctx.io, ctx.environ);1275 defer if (flake_ref) |r| ctx.gpa.free(r);1276 if (flake_ref) |ref| {1277 output.printSubstep("home-manager switch --flake {s}", .{ref});1278 } else {1279 output.printSubstep("home-manager switch", .{});1280 }12811282 const start = std.Io.Clock.awake.now(ctx.io);1283 const code = if (flake_ref) |ref|1284 try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)1285 else1286 try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1287 if (code != 0) return error.BuildFailed;12881289 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1290 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1291 output.homeApplyDone(homeCurrentGen(ctx), elapsed);1292 runPostHook(ctx, "post-home");1293}1294129512961297const service_help = [_][2][]const u8{1298 .{ "list", "list running services" },1299 .{ "logs <svc>", "show service logs" },1300 .{ "status <svc>", "service status" },1301 .{ "start <svc>", "start a service" },1302 .{ "stop <svc>", "stop a service" },1303 .{ "restart <svc>", "restart a service" },1304 .{ "enable <svc>", "enable at boot" },1305 .{ "disable <svc>", "disable at boot" },1306};13071308pub fn service(ctx: Ctx) !void {1309 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");1310 if (std.mem.eql(u8, ctx.sub, "list")) {1311 output.serviceListHeader(ctx.machine.name);1312 const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1313 defer ctx.gpa.free(svcs);1314 for (svcs) |s| output.serviceRow(s);1315 return;1316 }1317 if (std.mem.eql(u8, ctx.sub, "logs")) {1318 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1319 const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1320 output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1321 _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1322 return;1323 }1324 if (std.mem.eql(u8, ctx.sub, "status")) {1325 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1326 output.serviceVerb("status", name, ctx.machine.name);1327 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1328 return;1329 }1330 1331 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1332 if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1333 if (!output.confirm("")) return;1334 }1335 output.serviceVerb(ctx.sub, name, ctx.machine.name);1336 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1337 output.serviceDone();1338}1339134013411342const flake_help = [_][2][]const u8{1343 .{ "init", "create a new flake.nix" },1344 .{ "update", "update flake inputs" },1345 .{ "update <in>", "update a specific input" },1346 .{ "check", "validate the flake" },1347 .{ "show", "inspect flake outputs" },1348 .{ "lock", "regenerate flake.lock" },1349 .{ "clone <url>", "clone a flake repository" },1350};13511352pub fn flake(ctx: Ctx) !void {1353 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1354 if (std.mem.eql(u8, ctx.sub, "update")) {1355 output.flakeUpdateStart();1356 const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1357 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1358 output.flakeLockWritten();1359 return;1360 }1361 if (std.mem.eql(u8, ctx.sub, "check")) {1362 output.flakeCheckStart();1363 const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1364 if (code == 0) output.flakeValid() else output.checkFailed("");1365 return;1366 }1367 if (std.mem.eql(u8, ctx.sub, "show")) {1368 const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1369 if (json_out) |j| {1370 defer ctx.gpa.free(j);1371 output.flakeShowHeader("flake outputs");1372 1373 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1374 defer parsed.deinit();1375 if (parsed.value == .object) {1376 var it = parsed.value.object.iterator();1377 while (it.next()) |entry| {1378 if (entry.value_ptr.* == .object) {1379 var inner = entry.value_ptr.object.iterator();1380 while (inner.next()) |e2| {1381 const desc = if (e2.value_ptr.* == .object)1382 if (e2.value_ptr.object.get("description")) |d|1383 if (d == .string) d.string else ""1384 else1385 ""1386 else1387 "";1388 output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1389 }1390 }1391 }1392 }1393 }1394 return;1395 }1396 if (std.mem.eql(u8, ctx.sub, "init")) {1397 _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1398 return;1399 }1400 if (std.mem.eql(u8, ctx.sub, "lock")) {1401 _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1402 return;1403 }1404 if (std.mem.eql(u8, ctx.sub, "clone")) {1405 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1406 _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1407 return;1408 }1409}1410141114121413const store_help = [_][2][]const u8{1414 .{ "info", "store size and counts" },1415 .{ "path <attr>", "store path of a package" },1416 .{ "gc", "collect garbage" },1417 .{ "verify", "verify store integrity" },1418 .{ "repair", "repair corrupted paths" },1419};14201421pub fn store(ctx: Ctx) !void {1422 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1423 if (std.mem.eql(u8, ctx.sub, "gc")) {1424 _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1425 return;1426 }1427 if (std.mem.eql(u8, ctx.sub, "verify")) {1428 output.storeVerifyStart();1429 _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1430 return;1431 }1432 if (std.mem.eql(u8, ctx.sub, "repair")) {1433 if (ctx.cfg.confirm and !output.confirm("")) return;1434 output.storeRepairStart();1435 _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1436 return;1437 }1438 if (std.mem.eql(u8, ctx.sub, "info")) {1439 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1440 output.storeInfo(si);1441 return;1442 }1443 if (std.mem.eql(u8, ctx.sub, "path")) {1444 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1445 const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1446 defer ctx.gpa.free(path);1447 output.storePath(path);1448 return;1449 }1450 1451 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1452 output.storeInfo(si);1453}1454145514561457const channel_help = [_][2][]const u8{1458 .{ "list", "list channels" },1459 .{ "add <url> [name]", "add a channel" },1460 .{ "remove <name>", "remove a channel" },1461 .{ "update", "update all channels" },1462};14631464pub fn channel(ctx: Ctx) !void {1465 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1466 1467 if (flakeSystem(ctx)) output.flakeChannelNote();1468 if (std.mem.eql(u8, ctx.sub, "list")) {1469 output.channelListHeader(ctx.machine.name);1470 const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1471 defer ctx.gpa.free(chans);1472 for (chans) |ch| output.channelRow(ch);1473 return;1474 }1475 if (std.mem.eql(u8, ctx.sub, "add")) {1476 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1477 const name = if (ctx.args.len > 1) ctx.args[1] else "";1478 _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1479 output.channelDone();1480 return;1481 }1482 if (std.mem.eql(u8, ctx.sub, "remove")) {1483 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1484 _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1485 output.channelDone();1486 return;1487 }1488 if (std.mem.eql(u8, ctx.sub, "update")) {1489 return channelUpdateCmd(ctx);1490 }1491}1492149314941495pub fn profile(ctx: Ctx) !void {1496 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1497 output.profileListHeader();1498 const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1499 if (out) |o| {1500 defer ctx.gpa.free(o);1501 var lines = std.mem.splitScalar(u8, o, '\n');1502 while (lines.next()) |line| {1503 const t = std.mem.trim(u8, line, " \t\r");1504 if (t.len == 0) continue;1505 output.profileRow(t, "", "");1506 }1507 }1508 return;1509 }1510 if (std.mem.eql(u8, ctx.sub, "install")) {1511 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1512 _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1513 output.done();1514 return;1515 }1516 if (std.mem.eql(u8, ctx.sub, "remove")) {1517 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1518 _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1519 output.done();1520 return;1521 }1522 if (std.mem.eql(u8, ctx.sub, "upgrade")) {1523 _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1524 output.done();1525 return;1526 }1527}1528152915301531const pkg_help = [_][2][]const u8{1532 .{ "why <pkg>", "what pulled it in" },1533 .{ "deps <pkg>", "direct dependencies" },1534 .{ "size <pkg>", "closure size" },1535 .{ "path <pkg>", "store path" },1536 .{ "closure <pkg>", "full closure" },1537};15381539pub fn pkg(ctx: Ctx) !void {1540 if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1541 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1542 if (std.mem.eql(u8, ctx.sub, "why")) {1543 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1544 return;1545 }1546 if (std.mem.eql(u8, ctx.sub, "deps")) {1547 if (try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1548 return;1549 }1550 if (std.mem.eql(u8, ctx.sub, "size")) {1551 const s = try exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name);1552 defer ctx.gpa.free(s);1553 output.pkgResult("size", s);1554 return;1555 }1556 if (std.mem.eql(u8, ctx.sub, "path")) {1557 const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1558 defer ctx.gpa.free(p);1559 output.pkgResult("path", p);1560 return;1561 }1562 if (std.mem.eql(u8, ctx.sub, "closure")) {1563 if (try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1564 return;1565 }1566}1567156815691570pub fn why(ctx: Ctx) !void {1571 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1572 if (try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name) != 0) return error.PackageNotFound;1573}1574157515761577pub fn pin(ctx: Ctx) !void {1578 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1579 const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1580 exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1581 output.pinDone(input, commit);1582}15831584pub fn unpin(ctx: Ctx) !void {1585 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1586 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1587 output.unpinDone(input);1588}1589159015911592pub fn hash(ctx: Ctx) !void {1593 const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1594 const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1595 defer ctx.gpa.free(h);1596 output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1597}15981599pub fn fetch(ctx: Ctx) !void {1600 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1601 const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1602 defer ctx.gpa.free(h);1603 output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1604}1605160616071608pub fn build(ctx: Ctx) !void {1609 const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1610 output.buildStart(attr orelse "default");1611 const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1612 if (code != 0) return error.BuildFailed;1613 output.buildDone();1614}16151616pub fn runCmd(ctx: Ctx) !void {1617 const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1618 output.runStart(pkg_arg);1619 _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1620}1621162216231624pub fn hello(ctx: Ctx) !void {1625 output.hello(ctx.cfg.machines);1626}16271628const ConfigKind = enum { flake, channel, none };1629163016311632fn scanConfig(io: std.Io) ConfigKind {1633 if (exec.pathExists(io, "/etc/nixos/flake.nix")) return .flake;1634 if (exec.pathExists(io, "/etc/nixos/configuration.nix")) return .channel;1635 return .none;1636}16371638163916401641pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1642 output.firstRunBanner();1643 output.firstRunNoConfig();16441645 var name_buf: [256]u8 = undefined;1646 var path_buf: [256]u8 = undefined;16471648 const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);16491650 output.firstRunScanning();1651 const kind = scanConfig(io);1652 switch (kind) {1653 .flake => output.firstRunDetected("/etc/nixos/flake.nix", true),1654 .channel => output.firstRunDetected("/etc/nixos/configuration.nix", false),1655 .none => output.firstRunNoneFound(),1656 }16571658 1659 1660 const default_path: []const u8 = if (kind == .none) "" else "/etc/nixos";1661 const config_path = output.firstRunPromptDefault("config path", default_path, kind != .none, &path_buf);16621663 1664 1665 const use_flakes = exec.dirHasFlake(gpa, io, config_path);16661667 const conf_path = try config.configPath(gpa, environ);1668 defer gpa.free(conf_path);1669 if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);16701671 1672 const flake_line = if (use_flakes) "flake = true\n" else "";1673 var content_buf: [1024]u8 = undefined;1674 const content = try std.fmt.bufPrint(1675 &content_buf,1676 "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = true\n",1677 .{ flake_line, machine_name, config_path },1678 );16791680 const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1681 errors.error_info.setMessage("could not write {s}", .{conf_path});1682 return error.Internal;1683 };1684 defer file.close(io);1685 file.writePositionalAll(io, content, 0) catch {1686 errors.error_info.setMessage("could not write {s}", .{conf_path});1687 return error.Internal;1688 };16891690 output.firstRunWritten(conf_path);1691}16921693pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1694 1695 1696 1697 config.migrateLegacyConfig(gpa, io, environ);1698 if (config.configPath(gpa, environ)) |conf_path| {1699 defer gpa.free(conf_path);1700 if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1701 f.close(io);1702 } else |_| {1703 try firstRunWizard(gpa, io, environ);1704 errors.error_info.reset();1705 }1706 } else |_| {}17071708 output.setupCheck();1709 const status = exec.checkNixFeatures(gpa, io, environ);1710 output.setupFeatures(status.nix_command, status.flakes);17111712 if (status.allEnabled()) {1713 output.setupAllSet();1714 api.ensureRegistryPinned(gpa, io, environ);1715 return;1716 }17171718 1719 1720 1721 1722 if (exec.isNixOS(io)) {1723 const conf_path = "/etc/nixos/configuration.nix";1724 if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1725 output.setupNixosNeedsRebuild(conf_path);1726 return;1727 }1728 output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1729 if (output.confirmDefaultNo("add it now?")) {1730 if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1731 output.setupNixosWrote(conf_path);1732 } else |_| {1733 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1734 }1735 } else {1736 output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1737 }1738 return;1739 }17401741 1742 output.setupEnabling();1743 const path = try exec.enableNixFeatures(gpa, io, environ);1744 defer gpa.free(path);17451746 output.setupDone(path);1747 api.ensureRegistryPinned(gpa, io, environ);1748}1749175017511752fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1753 var ts_buf: [32]u8 = undefined;1754 const ts = nowIso(ctx.io, &ts_buf);1755 var buf: [256]u8 = undefined;1756 const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1757 ts, ctx.machine.name, action, gen,1758 }) catch return;1759 exec.appendNinaLog(ctx.io, ctx.environ, entry);1760}1761176217631764fn nowIso(io: std.Io, buf: []u8) []const u8 {1765 const fallback = "1970-01-01T00:00:00Z";1766 const ns = std.Io.Clock.real.now(io).toNanoseconds();1767 if (ns <= 0) return fallback;1768 const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1769 const es = std.time.epoch.EpochSeconds{ .secs = secs };1770 const ed = es.getEpochDay();1771 const yd = ed.calculateYearDay();1772 const md = yd.calculateMonthDay();1773 const ds = es.getDaySeconds();1774 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", .{1775 yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1776 ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1777 }) catch return fallback;1778}