123const std = @import("std");4const builtin = @import("builtin");5const types = @import("types.zig");6const errors = @import("errors.zig");7const config = @import("config.zig");8const output = @import("output.zig");9const exec = @import("exec.zig");10const api = @import("api.zig");11const search_tui = @import("search.zig");12const version = @import("version.zig");1314const UPDATE_URL = "https://kepr.uk/api/nina/releases/latest";1516pub const Ctx = struct {17 gpa: std.mem.Allocator,18 io: std.Io,19 environ: *const std.process.Environ.Map,20 machine: types.Machine,21 cfg: types.NinaConfig,22 args: []const []const u8, 23 sub: []const u8, 24 dry: bool,25 check: bool,26 no_apply: bool,27 all: bool,28 last: u32,29 json: bool,30};3132pub fn apply(ctx: Ctx) !void {33 if (ctx.dry) {34 output.applyDry(ctx.machine.name);35 const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);36 if (code != 0) return error.BuildFailed;37 output.applyDryDone();38 return;39 }40 if (ctx.check) {41 return check(ctx);42 }4344 output.applyStart(ctx.machine.name);45 const start = std.Io.Clock.awake.now(ctx.io);4647 const code = exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa) catch |e| {48 output.applyFailed("");49 return e;50 };5152 if (code != 0) {53 output.applyFailed("");54 return error.BuildFailed;55 }5657 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());58 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));59 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;60 output.applyDone(gen, elapsed);61 logAction(ctx, "apply", gen);62}6364pub fn check(ctx: Ctx) !void {65 output.checkStart(ctx.machine.name);66 const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);67 if (code != 0) {68 output.checkFailed("");69 return error.BuildFailed;70 }71 output.checkOk();72}7374pub fn back(ctx: Ctx) !void {75 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);76 defer ctx.gpa.free(gens);7778 var current: u32 = 0;79 for (gens) |g| if (g.current) { current = g.number; };80 const prev = if (current > 1) current - 1 else current;8182 output.backStart(ctx.machine.name, current, prev);83 if (ctx.cfg.confirm and !output.confirm("")) return;8485 const code = try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);86 if (code != 0) return error.BuildFailed;87 output.generationDone(prev);88}8990pub fn go(ctx: Ctx) !void {91 if (ctx.args.len == 0) return error.Internal;92 const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;93 const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);9495 output.goStart(ctx.machine.name, current, target);96 if (ctx.cfg.confirm and !output.confirm("")) return;9798 const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);99 if (code != 0) return error.ProcessFailed;100 output.generationDone(target);101}102103pub fn history(ctx: Ctx) !void {104 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);105 defer ctx.gpa.free(gens);106 output.historyHeader(ctx.machine.name);107 for (gens) |g| output.historyRow(g);108}109110pub fn genCmd(ctx: Ctx) !void {111 if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);112 if (std.mem.eql(u8, ctx.sub, "current")) {113 const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);114 output.genCurrent(n);115 return;116 }117 if (std.mem.eql(u8, ctx.sub, "delete")) {118 if (ctx.args.len == 0) return error.Internal;119 if (std.mem.eql(u8, ctx.args[0], "old")) {120 if (ctx.cfg.confirm and !output.confirm("")) return;121 _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);122 } else {123 const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;124 if (ctx.cfg.confirm and !output.confirm("")) return;125 _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);126 }127 output.done();128 return;129 }130 return error.Internal;131}132133pub fn clean(ctx: Ctx) !void {134 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);135 defer ctx.gpa.free(gens);136 output.cleanStart(ctx.machine.name, ctx.cfg.generations, @intCast(gens.len));137 if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;138 const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");139 _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);140 output.cleanDone("?");141}142143pub fn statusCmd(ctx: Ctx) !void {144 output.statusHeader();145 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;146 output.statusRow(ctx.machine.name, gen, "", "", true);147}148149pub fn diff(ctx: Ctx) !void {150 const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);151 defer ctx.gpa.free(gens);152 var current: u32 = 0;153 var prev: u32 = 0;154 for (gens) |g| {155 if (g.current) current = g.number;156 if (!g.current and g.number > prev and g.number < current) prev = g.number;157 }158 if (ctx.args.len >= 2) {159 const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;160 const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;161 output.diffHeader(a, b, ctx.machine.name);162 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;163 } else {164 output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);165 if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;166 }167}168169pub fn doctor(ctx: Ctx) !void {170 output.doctorHeader(ctx.machine.name);171 const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);172 defer ctx.gpa.free(checks);173 var warnings: u32 = 0;174 var failures: u32 = 0;175 for (checks) |ch| {176 output.doctorRow(ch);177 if (ch.status == .warn) warnings += 1;178 if (ch.status == .fail) failures += 1;179 }180 output.doctorSummary(warnings, failures);181}182183184pub fn update(ctx: Ctx) !void {185 output.updateSelfStart();186187 if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {188 output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));189 return error.Internal;190 }191192 const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");193 const source_url = env_url orelse UPDATE_URL;194195 const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {196 error.NetworkError, error.HttpError => {197 output.updateSelfNetworkError();198 return;199 },200 else => return e,201 };202 defer ctx.gpa.free(body);203204 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {205 output.printWarning("could not parse release metadata");206 return;207 };208 defer parsed.deinit();209210 const root = parsed.value;211 if (root != .object) { output.printWarning("malformed release metadata"); return; }212213 const remote_ver = blk: {214 const v = root.object.get("version") orelse { output.printWarning("malformed release metadata"); return; };215 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };216 };217218 if (std.mem.eql(u8, remote_ver, version.VERSION)) {219 output.updateSelfCurrent(version.VERSION);220 return;221 }222223 output.updateSelfAvailable(version.VERSION, remote_ver);224 if (ctx.check) return;225226 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;227 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {228 errors.error_info.setMessage("could not determine install path", .{});229 return error.Internal;230 };231232 233 234 if (std.mem.startsWith(u8, install_path, "/nix/store/")) {235 output.updateSelfNixManaged(remote_ver);236 if (ctx.cfg.confirm and !output.confirm("")) return;237 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", ".*nina.*" }) catch {238 output.updateSelfNixFailed();239 return;240 };241 if (ec != 0) output.updateSelfNixSystemManaged();242 return;243 }244245 const plat_info = blk: {246 const pv = root.object.get("platforms") orelse break :blk null;247 if (pv != .object) break :blk null;248 break :blk pv.object.get(version.PLATFORM);249 };250 if (plat_info == null) { output.updateSelfNoPlatform(version.PLATFORM); return; }251252 const dl_url = blk: {253 const v = plat_info.?.object.get("url") orelse { output.printWarning("malformed release metadata"); return; };254 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };255 };256257 const raw_cksum = blk: {258 if (plat_info.?.object.get("blake3")) |v|259 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };260 if (plat_info.?.object.get("checksum")) |v|261 break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };262 output.printWarning("missing checksum in release metadata");263 return;264 };265 const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;266267 if (ctx.cfg.confirm and !output.confirm("")) return;268269 output.updateSelfDownloading(remote_ver, version.PLATFORM);270 const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {271 output.printWarning("download failed — check your connection and try again");272 return;273 };274 defer ctx.gpa.free(tmp_path);275276 output.updateSelfVerifying();277 exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {278 error.ChecksumMismatch => { output.updateSelfChecksumFailed(); return; },279 else => return e,280 };281282 output.updateSelfDone(version.VERSION, remote_ver);283}284285286pub fn goodbye(ctx: Ctx) !void {287 output.goodbyeStart();288289 var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;290 const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {291 errors.error_info.setMessage("could not determine install path", .{});292 return error.Internal;293 };294295 if (std.mem.startsWith(u8, install_path, "/nix/store/")) {296 output.goodbyeNix();297 if (ctx.cfg.confirm and !output.confirm("")) return;298 const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", ".*nina.*" }) catch {299 output.goodbyeFailed("nix profile remove failed");300 return;301 };302 if (ec != 0) {303 output.goodbyeNixSystemManaged();304 return;305 }306 } else {307 output.goodbyeFile(install_path);308 if (ctx.cfg.confirm and !output.confirm("")) return;309 std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {310 errors.error_info.setMessage("could not remove {s}", .{install_path});311 return e;312 };313 }314315 316 if (ctx.environ.get("HOME")) |home| {317 const nina_nix: ?[]u8 = std.fmt.allocPrint(ctx.gpa, "{s}/nina.nix", .{home}) catch null;318 if (nina_nix) |path| {319 defer ctx.gpa.free(path);320 const exists = blk: {321 const bytes = std.Io.Dir.readFileAlloc(.cwd(), ctx.io, path, ctx.gpa, .unlimited) catch break :blk false;322 ctx.gpa.free(bytes);323 break :blk true;324 };325 if (exists) {326 output.goodbyeNixFileFound(path);327 if (!ctx.cfg.confirm or output.confirm("")) {328 std.Io.Dir.deleteFileAbsolute(ctx.io, path) catch {329 output.printWarning("could not remove ~/nina.nix — remove it manually to clean up");330 };331 }332 }333 }334 }335336 output.goodbyeDone();337}338339fn channelUpdateCmd(ctx: Ctx) !void {340 output.updateStart(ctx.machine.name);341 _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);342 output.updateDone();343}344345pub fn upgrade(ctx: Ctx) !void {346 output.upgradeStart(ctx.machine.name);347 output.printSubstep("updating channels", .{});348 _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};349 output.printSubstep("rebuilding", .{});350 const start = std.Io.Clock.awake.now(ctx.io);351 const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);352 if (code != 0) {353 output.applyFailed("");354 return error.BuildFailed;355 }356 const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());357 const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));358 const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;359 output.applyDone(gen, elapsed);360}361362pub fn log(ctx: Ctx) !void {363 output.logHeader(ctx.machine.name);364 const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {365 366 return;367 };368 defer ctx.gpa.free(content);369 var lines = std.mem.splitScalar(u8, content, '\n');370 while (lines.next()) |line| {371 if (line.len == 0) continue;372 var parts = std.mem.tokenizeScalar(u8, line, '\t');373 const date = parts.next() orelse continue;374 const time = parts.next() orelse "";375 const action = parts.next() orelse "";376 const detail = parts.next() orelse "";377 output.logRow(date, time, action, detail);378 }379}380381pub fn edit(ctx: Ctx) !void {382 const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");383 const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";384 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });385 defer ctx.gpa.free(path);386 output.editOpen(path, ctx.cfg.editor);387 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);388}389390pub fn fmt(ctx: Ctx) !void {391 const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});392 defer ctx.gpa.free(path);393 if (ctx.check) {394 const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);395 if (code != 0) output.fmtNeedsFormat() else output.fmtDone();396 return;397 }398 output.fmtStart(path);399 _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);400 output.fmtDone();401}402403pub fn repl(ctx: Ctx) !void {404 output.replStart();405 _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);406}407408pub fn develop(ctx: Ctx) !void {409 if (std.mem.eql(u8, ctx.sub, "show")) {410 _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);411 return;412 }413 const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))414 ctx.args[0]415 else416 null;417 output.developStart(&.{});418 _ = try exec.nixDevelop(ctx.io, &ctx.machine, ctx.gpa, run_cmd);419 output.developDone();420}421422pub fn info(ctx: Ctx) !void {423 output.infoHeader(ctx.machine.name);424 const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");425 defer ctx.gpa.free(nixos_ver);426 output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));427428 const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");429 defer ctx.gpa.free(kernel);430 output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));431432 const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");433 defer ctx.gpa.free(uptime);434 output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));435}436437pub fn boot(ctx: Ctx) !void {438 output.bootHeader(ctx.machine.name);439 const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};440 defer ctx.gpa.free(entries);441 for (entries, 0..) |entry, i| output.bootEntry(entry, i);442}443444pub fn searchCmd(ctx: Ctx) !void {445 const query = if (ctx.args.len > 0) ctx.args[0] else "";446 const result = try search_tui.run(ctx.gpa, ctx.io, query, .packages);447 if (result) |r| {448 installFromResult(ctx, r) catch |e| return e;449 }450}451452pub fn optionCmd(ctx: Ctx) !void {453 const query = if (ctx.args.len > 0) ctx.args[0] else "";454 _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);455}456457pub fn install(ctx: Ctx) !void {458 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;459460 461 const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {462 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});463 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});464 return error.PackageNotFound;465 };466 defer ctx.gpa.free(pkgs);467468 if (pkgs.len == 0) {469 errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});470 errors.error_info.setSuggestion("nina search {s}", .{pkg_name});471 return error.PackageNotFound;472 }473474 475 476 var found = pkgs[0];477 for (pkgs) |p| {478 if (std.mem.eql(u8, p.pname, pkg_name)) {479 found = p;480 break;481 }482 }483 output.installSelectPrompt(found.pname, found.version);484485 var choice_buf: [8]u8 = undefined;486 var choice_len: usize = 0;487 while (choice_len < choice_buf.len) {488 const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;489 if (n == 0) break;490 if (choice_buf[choice_len] == '\n') break;491 choice_len += 1;492 }493 const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");494495 if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {496 try profileInstallPkg(ctx, found);497 } else if (choice[0] == 's' or choice[0] == 'S') {498 try systemInstallPkg(ctx, found);499 } else if (choice[0] == 't' or choice[0] == 'T') {500 try tryPkg(ctx, found);501 }502}503504fn installFromResult(ctx: Ctx, result: types.SearchResult) !void {505 switch (result.action) {506 .profile => try profileInstallPkg(ctx, result.package),507 .system => try systemInstallPkg(ctx, result.package),508 }509}510511fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {512 output.installStart(npkg.pname, .profile);513 output.printSubstep("nix profile install nixpkgs#{s}", .{npkg.attr});514 output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile install nixpkgs#{s}", .{npkg.attr}));515 const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);516 if (code != 0) return error.ProcessFailed;517 output.installDone(npkg.pname);518}519520fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {521 const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});522 defer ctx.gpa.free(config_path);523 const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;524 output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);525 _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);526 if (ctx.cfg.confirm) {527 if (output.confirm("apply now? ")) {528 try apply(ctx);529 }530 }531}532533fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {534 output.tryStart(npkg.pname);535 output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});536 _ = try exec.nixShell(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);537 output.tryDone();538}539540pub fn remove(ctx: Ctx) !void {541 const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;542 output.installStart(pkg_name, .profile); 543 const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);544 if (code != 0) return error.ProcessFailed;545 output.done();546}547548pub fn list(ctx: Ctx) !void {549 output.listHeader();550 const profile_out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;551 if (profile_out) |out| {552 defer ctx.gpa.free(out);553 output.listSection("profile");554 var lines = std.mem.splitScalar(u8, out, '\n');555 while (lines.next()) |line| {556 const t = std.mem.trim(u8, line, " \t\r");557 if (t.len == 0) continue;558 output.listPkg(t, "");559 }560 }561}562563pub fn tryCmd(ctx: Ctx) !void {564 const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;565 const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };566 try tryPkg(ctx, shell_pkg);567}568569570571pub fn service(ctx: Ctx) !void {572 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {573 output.serviceListHeader(ctx.machine.name);574 const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine) catch &.{};575 defer ctx.gpa.free(svcs);576 for (svcs) |s| output.serviceRow(s);577 return;578 }579 if (std.mem.eql(u8, ctx.sub, "logs")) {580 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;581 const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");582 output.serviceLogsHeader(name, ctx.last, ctx.machine.name);583 _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow);584 return;585 }586 if (std.mem.eql(u8, ctx.sub, "status")) {587 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;588 output.serviceVerb("status", name, ctx.machine.name);589 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name);590 return;591 }592 593 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;594 if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {595 if (!output.confirm("")) return;596 }597 output.serviceVerb(ctx.sub, name, ctx.machine.name);598 _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name);599 output.serviceDone();600}601602603604pub fn flake(ctx: Ctx) !void {605 if (std.mem.eql(u8, ctx.sub, "update")) {606 output.flakeUpdateStart();607 const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;608 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);609 output.flakeLockWritten();610 return;611 }612 if (std.mem.eql(u8, ctx.sub, "check")) {613 output.flakeCheckStart();614 const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);615 if (code == 0) output.flakeValid() else output.checkFailed("");616 return;617 }618 if (std.mem.eql(u8, ctx.sub, "show")) {619 const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;620 if (json_out) |j| {621 defer ctx.gpa.free(j);622 output.flakeShowHeader(".");623 624 const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;625 defer parsed.deinit();626 if (parsed.value == .object) {627 var it = parsed.value.object.iterator();628 while (it.next()) |entry| {629 if (entry.value_ptr.* == .object) {630 var inner = entry.value_ptr.object.iterator();631 while (inner.next()) |e2| {632 const desc = if (e2.value_ptr.* == .object)633 if (e2.value_ptr.object.get("description")) |d|634 if (d == .string) d.string else ""635 else ""636 else "";637 output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);638 }639 }640 }641 }642 }643 return;644 }645 if (std.mem.eql(u8, ctx.sub, "init")) {646 _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);647 return;648 }649 if (std.mem.eql(u8, ctx.sub, "lock")) {650 _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);651 return;652 }653 if (std.mem.eql(u8, ctx.sub, "clone")) {654 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;655 _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);656 return;657 }658}659660661662pub fn store(ctx: Ctx) !void {663 if (std.mem.eql(u8, ctx.sub, "gc")) {664 _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);665 return;666 }667 if (std.mem.eql(u8, ctx.sub, "verify")) {668 output.storeVerifyStart();669 _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);670 return;671 }672 if (std.mem.eql(u8, ctx.sub, "repair")) {673 if (ctx.cfg.confirm and !output.confirm("")) return;674 output.storeRepairStart();675 _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);676 return;677 }678 if (std.mem.eql(u8, ctx.sub, "info")) {679 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);680 output.storeInfo(si);681 return;682 }683 if (std.mem.eql(u8, ctx.sub, "path")) {684 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;685 const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);686 defer ctx.gpa.free(path);687 output.storePath(path);688 return;689 }690 691 const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);692 output.storeInfo(si);693}694695696697pub fn channel(ctx: Ctx) !void {698 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {699 output.channelListHeader(ctx.machine.name);700 const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);701 defer ctx.gpa.free(chans);702 for (chans) |ch| output.channelRow(ch);703 return;704 }705 if (std.mem.eql(u8, ctx.sub, "add")) {706 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;707 const name = if (ctx.args.len > 1) ctx.args[1] else "";708 _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);709 output.channelDone();710 return;711 }712 if (std.mem.eql(u8, ctx.sub, "remove")) {713 const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;714 _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);715 output.channelDone();716 return;717 }718 if (std.mem.eql(u8, ctx.sub, "update")) {719 return channelUpdateCmd(ctx);720 }721}722723724725pub fn profile(ctx: Ctx) !void {726 if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {727 output.profileListHeader();728 const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;729 if (out) |o| {730 defer ctx.gpa.free(o);731 var lines = std.mem.splitScalar(u8, o, '\n');732 while (lines.next()) |line| {733 const t = std.mem.trim(u8, line, " \t\r");734 if (t.len == 0) continue;735 output.profileRow(t, "", "");736 }737 }738 return;739 }740 if (std.mem.eql(u8, ctx.sub, "install")) {741 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;742 _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);743 output.done();744 return;745 }746 if (std.mem.eql(u8, ctx.sub, "remove")) {747 const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;748 _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);749 output.done();750 return;751 }752 if (std.mem.eql(u8, ctx.sub, "upgrade")) {753 _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);754 output.done();755 return;756 }757}758759760761pub fn pkg(ctx: Ctx) !void {762 const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;763 if (std.mem.eql(u8, ctx.sub, "why")) {764 _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);765 return;766 }767 if (std.mem.eql(u8, ctx.sub, "deps")) {768 _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);769 return;770 }771 if (std.mem.eql(u8, ctx.sub, "size")) {772 const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;773 if (s) |sz| {774 defer ctx.gpa.free(sz);775 output.pkgResult("size", sz);776 }777 return;778 }779 if (std.mem.eql(u8, ctx.sub, "path")) {780 const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);781 defer ctx.gpa.free(p);782 output.pkgResult("path", p);783 return;784 }785 if (std.mem.eql(u8, ctx.sub, "closure")) {786 _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);787 return;788 }789}790791792793pub fn pin(ctx: Ctx) !void {794 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;795 const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;796 exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;797 output.pinDone(input, commit);798}799800pub fn unpin(ctx: Ctx) !void {801 const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;802 _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);803 output.unpinDone(input);804}805806807808pub fn hash(ctx: Ctx) !void {809 const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;810 const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);811 defer ctx.gpa.free(h);812 output.hashResult(std.mem.trim(u8, h, " \t\n\r"));813}814815pub fn fetch(ctx: Ctx) !void {816 const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;817 const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);818 defer ctx.gpa.free(h);819 output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);820}821822823824pub fn build(ctx: Ctx) !void {825 const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;826 output.buildStart(attr orelse "default");827 const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);828 if (code != 0) return error.BuildFailed;829 output.buildDone();830}831832pub fn runCmd(ctx: Ctx) !void {833 const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;834 output.runStart(pkg_arg);835 _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);836}837838839840pub fn hello(ctx: Ctx) !void {841 output.hello(ctx.cfg.machines);842}843844pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {845 output.setupCheck();846 const status = exec.checkNixFeatures(gpa, io, environ);847 output.setupFeatures(status.nix_command, status.flakes);848849 if (status.allEnabled()) {850 output.setupAllSet();851 return;852 }853854 output.setupEnabling();855 const path = try exec.enableNixFeatures(gpa, io, environ);856 defer gpa.free(path);857858 output.setupDone(path, exec.isNixOS(io));859}860861862863fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {864 var buf: [128]u8 = undefined;865 const entry = std.fmt.bufPrint(&buf, "{s}\t{s}\t{s}\tgen {d}\n", .{866 "2026", "00:00", action, gen,867 }) catch return;868 exec.appendNinaLog(ctx.io, ctx.environ, entry);869}