commands.zig

59.3 KB · raw

1// commands.zig — all command handlers2// Orchestrates exec/api/output. Zero direct stdout writes.3const 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,   // positional args after subcommand23    sub: []const u8,            // subcommand (e.g. "list" in "service list")24    dry: bool,25    check: bool,26    no_apply: bool,27    all: bool,28    last: u32,29    json: bool,30    user: bool,            // --user: operate on user (vs system) services31};3233// A system is flake-managed when the config says so OR a flake.nix is present in34// the config dir. Detection means a fresh channel user who points nina at a flake35// dir gets the right behavior without editing config first.36fn flakeSystem(ctx: Ctx) bool {37    return ctx.cfg.flake or exec.configHasFlake(ctx.gpa, ctx.io, &ctx.machine);38}3940pub fn apply(ctx: Ctx) !void {41    if (ctx.dry) {42        output.applyDry(ctx.machine.name);43        const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);44        if (code != 0) return error.BuildFailed;45        output.applyDryDone();46        return;47    }48    if (ctx.check) {49        return check(ctx);50    }5152    output.applyStart(ctx.machine.name);53    const start = std.Io.Clock.awake.now(ctx.io);5455    const code = exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa) catch |e| {56        exec.markApplyFailed(ctx.io, ctx.environ);57        output.applyFailed("");58        return e;59    };6061    if (code != 0) {62        exec.markApplyFailed(ctx.io, ctx.environ);63        output.applyFailed("");64        return error.BuildFailed;65    }6667    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());68    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));69    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;70    const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);71    output.applyDone(gen, elapsed, after_failure);72    logAction(ctx, "apply", gen);73}7475pub fn check(ctx: Ctx) !void {76    output.checkStart(ctx.machine.name);77    const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);78    if (code != 0) {79        output.checkFailed("");80        return error.BuildFailed;81    }82    output.checkOk();83}8485pub fn back(ctx: Ctx) !void {86    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);87    defer ctx.gpa.free(gens);8889    var current: u32 = 0;90    for (gens) |g| if (g.current) { current = g.number; };9192    // Newest generation older than current. If there is none, we're already at the93    // oldest — stop cleanly instead of letting rollback fail with 'build failed'.94    var prev: u32 = 0;95    var has_prev = false;96    for (gens) |g| {97        if (g.number < current and (!has_prev or g.number > prev)) {98            prev = g.number;99            has_prev = true;100        }101    }102    if (!has_prev) {103        output.alreadyOldest();104        return;105    }106107    output.backStart(ctx.machine.name, current, prev);108    if (ctx.cfg.confirm and !output.confirm("")) return;109110    const code = try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);111    if (code != 0) return error.BuildFailed;112    output.backDone(prev);113}114115pub fn go(ctx: Ctx) !void {116    if (ctx.args.len == 0) return error.Internal;117    const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;118    const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);119120    output.goStart(ctx.machine.name, current, target);121    if (ctx.cfg.confirm and !output.confirm("")) return;122123    const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);124    if (code != 0) return error.ProcessFailed;125    output.generationDone(target);126}127128pub fn history(ctx: Ctx) !void {129    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);130    defer ctx.gpa.free(gens);131    output.historyHeader(ctx.machine.name);132    for (gens) |g| output.historyRow(g);133}134135const gen_help = [_][2][]const u8{136    .{ "list", "list generations" },137    .{ "current", "show current generation" },138    .{ "delete <n>", "delete generation n" },139    .{ "delete old", "delete old generations" },140};141142pub fn genCmd(ctx: Ctx) !void {143    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("gen", &gen_help, null);144    if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);145    if (std.mem.eql(u8, ctx.sub, "current")) {146        const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);147        output.genCurrent(n);148        return;149    }150    if (std.mem.eql(u8, ctx.sub, "delete")) {151        if (ctx.args.len == 0) return error.Internal;152        if (std.mem.eql(u8, ctx.args[0], "old")) {153            if (ctx.cfg.confirm and !output.confirm("")) return;154            _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);155        } else {156            const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;157            if (ctx.cfg.confirm and !output.confirm("")) return;158            _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);159        }160        output.done();161        return;162    }163    return error.Internal;164}165166pub fn clean(ctx: Ctx) !void {167    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);168    defer ctx.gpa.free(gens);169    const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");170    const total: u32 = @intCast(gens.len);171    // `clean all` keeps only the current generation; otherwise keep the configured172    // count. With nothing older than the keep limit, there's nothing to collect.173    const keep: u32 = if (all) 1 else ctx.cfg.generations;174    if (total <= keep) {175        output.cleanNothing(ctx.machine.name, total);176        return;177    }178    output.cleanStart(ctx.machine.name, keep, total);179    if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;180    _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);181    output.cleanDone();182}183184pub fn statusCmd(ctx: Ctx) !void {185    output.statusHeader();186    // --all renders every configured machine; remotes route through the same SSH187    // path as exec.capture. An unreachable machine is shown in red, not fatal.188    if (ctx.all and ctx.cfg.machines.len > 0) {189        for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);190        return;191    }192    statusRowFor(ctx, &ctx.machine);193}194195fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {196    // A failure to read the current generation means we couldn't reach or query197    // the machine — mark it unreachable rather than reporting a bogus gen 0.198    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {199        output.statusRow(machine.name, 0, "", "", false);200        return;201    };202    const st = exec.systemStatus(ctx.gpa, ctx.io, machine);203    defer ctx.gpa.free(st.size);204    defer ctx.gpa.free(st.age);205    output.statusRow(machine.name, gen, st.age, st.size, true);206}207208pub fn diff(ctx: Ctx) !void {209    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);210    defer ctx.gpa.free(gens);211    var current: u32 = 0;212    var prev: u32 = 0;213    for (gens) |g| {214        if (g.current) current = g.number;215        if (!g.current and g.number > prev and g.number < current) prev = g.number;216    }217    if (ctx.args.len >= 2) {218        const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;219        const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;220        output.diffHeader(a, b, ctx.machine.name);221        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;222    } else {223        output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);224        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;225    }226}227228pub fn mood(ctx: Ctx) !void {229    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;230    const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);231    defer ctx.gpa.free(st.size);232    defer ctx.gpa.free(st.age);233    const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");234    defer ctx.gpa.free(state);235    output.mood(ctx.machine.name, state, gen, st.age, st.size);236}237238pub fn doctor(ctx: Ctx) !void {239    output.doctorHeader(ctx.machine.name);240    const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);241    defer ctx.gpa.free(checks);242    var warnings: u32 = 0;243    var failures: u32 = 0;244    for (checks) |ch| {245        output.doctorRow(ch);246        if (ch.status == .warn) warnings += 1;247        if (ch.status == .fail) failures += 1;248    }249    output.doctorSummary(warnings, failures);250}251252// nina update — kepr self-update for the nina binary itself.253pub fn update(ctx: Ctx) !void {254    output.updateSelfStart();255256    if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {257        output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));258        return error.Internal;259    }260261    const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");262    const source_url = env_url orelse UPDATE_URL;263264    const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {265        error.NetworkError, error.HttpError => {266            output.updateSelfNetworkError();267            return;268        },269        else => return e,270    };271    defer ctx.gpa.free(body);272273    const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {274        output.printWarning("could not parse release metadata");275        return;276    };277    defer parsed.deinit();278279    const root = parsed.value;280    if (root != .object) { output.printWarning("malformed release metadata"); return; }281282    const remote_ver = blk: {283        const v = root.object.get("version") orelse { output.printWarning("malformed release metadata"); return; };284        break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };285    };286287    if (std.mem.eql(u8, remote_ver, version.VERSION)) {288        output.updateSelfCurrent(version.VERSION);289        return;290    }291292    output.updateSelfAvailable(version.VERSION, remote_ver);293    if (ctx.check) return;294295    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;296    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {297        errors.error_info.setMessage("could not determine install path", .{});298        return error.Internal;299    };300301    // When running from the nix store, defer to nix profile upgrade so nix302    // manages the transition (the store is read-only; binary replacement fails).303    // A NixOS system install also resolves into the store but isn't a profile304    // element, so check the profile to avoid a no-op `upgrade` — it updates with305    // the next nixos-rebuild instead.306    if (std.mem.startsWith(u8, install_path, "/nix/store/")) {307        const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);308        defer {309            if (nina_element) |n| ctx.gpa.free(n);310        }311        if (nina_element == null) {312            output.updateSelfNotInProfile();313            return;314        }315        const element = nina_element.?;316        output.updateSelfNixManaged(remote_ver);317        if (ctx.cfg.confirm and !output.confirm("")) return;318        const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", element }) catch {319            output.updateSelfNixFailed();320            return;321        };322        if (ec != 0) output.updateSelfNixFailed();323        return;324    }325326    const plat_info = blk: {327        const pv = root.object.get("platforms") orelse break :blk null;328        if (pv != .object) break :blk null;329        break :blk pv.object.get(version.PLATFORM);330    };331    if (plat_info == null) { output.updateSelfNoPlatform(version.PLATFORM); return; }332333    const dl_url = blk: {334        const v = plat_info.?.object.get("url") orelse { output.printWarning("malformed release metadata"); return; };335        break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };336    };337338    const raw_cksum = blk: {339        if (plat_info.?.object.get("blake3")) |v|340            break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };341        if (plat_info.?.object.get("checksum")) |v|342            break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };343        output.printWarning("missing checksum in release metadata");344        return;345    };346    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;347348    if (ctx.cfg.confirm and !output.confirm("")) return;349350    output.updateSelfDownloading(remote_ver, version.PLATFORM);351    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {352        output.printWarning("download failed — check your connection and try again");353        return;354    };355    defer ctx.gpa.free(tmp_path);356357    output.updateSelfVerifying();358    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {359        error.ChecksumMismatch => { output.updateSelfChecksumFailed(); return; },360        else => return e,361    };362363    output.updateSelfDone(version.VERSION, remote_ver);364}365366// nina goodbye — clean uninstall. Three install paths:367// - nix profile (binary in nix store with a profile element) → nix profile remove368// - koh build or source build (plain binary on PATH) → delete the file369pub fn goodbye(ctx: Ctx) !void {370    output.goodbyeStart();371372    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;373    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {374        errors.error_info.setMessage("could not determine install path", .{});375        return error.Internal;376    };377378    // A binary outside the nix store is a koh build or source build — delete it.379    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {380        output.goodbyeFile(install_path);381        if (ctx.cfg.confirm and !output.confirm("")) return;382        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {383            errors.error_info.setMessage("could not remove {s}", .{install_path});384            return e;385        };386        output.goodbyeDone();387        return;388    }389390    // Binary is in the nix store — find and remove the profile element.391    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);392    defer {393        if (nina_element) |n| ctx.gpa.free(n);394    }395396    if (nina_element == null) {397        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});398        return error.Internal;399    }400401    output.goodbyeNix();402    if (ctx.cfg.confirm and !output.confirm("")) return;403    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {404        output.goodbyeFailed("nix profile remove failed");405        return;406    };407    if (ec != 0) {408        output.goodbyeFailed("nix profile remove failed");409        return;410    }411    output.goodbyeDone();412}413414fn channelUpdateCmd(ctx: Ctx) !void {415    output.updateStart(ctx.machine.name);416    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);417    output.updateDone();418}419420pub fn upgrade(ctx: Ctx) !void {421    output.upgradeStart(ctx.machine.name);422    output.printSubstep("updating channels", .{});423    _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};424    output.printSubstep("rebuilding", .{});425    const start = std.Io.Clock.awake.now(ctx.io);426    const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);427    if (code != 0) {428        output.applyFailed("");429        return error.BuildFailed;430    }431    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());432    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));433    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;434    output.applyDone(gen, elapsed, false);435}436437pub fn log(ctx: Ctx) !void {438    output.logHeader(ctx.machine.name);439    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {440        // No log yet — that's fine441        return;442    };443    defer ctx.gpa.free(content);444    var lines = std.mem.splitScalar(u8, content, '\n');445    while (lines.next()) |line| {446        const t = std.mem.trim(u8, line, " \t\r");447        if (t.len == 0) continue;448        if (t[0] == '{') {449            renderJsonLogLine(ctx.gpa, t);450        } else {451            // legacy tab-separated format452            var parts = std.mem.tokenizeScalar(u8, t, '\t');453            const date = parts.next() orelse continue;454            const time = parts.next() orelse "";455            const action = parts.next() orelse "";456            const detail = parts.next() orelse "";457            output.logRow(date, time, action, detail);458        }459    }460}461462// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.463// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.464fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {465    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {466        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop467        return;468    };469    defer parsed.deinit();470    if (parsed.value != .object) return;471    const o = parsed.value.object;472473    const ts = jsonStr(o, "ts");474    const date = if (ts.len >= 10) ts[0..10] else ts;475    const time = if (ts.len >= 16) ts[11..16] else "";476    const action = jsonStr(o, "command");477    const outcome = jsonStr(o, "outcome");478479    var buf: [160]u8 = undefined;480    var detail: []const u8 = outcome;481    if (o.get("gen_after")) |g| {482        if (g == .integer) {483            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;484        }485    }486    output.logRow(date, time, action, detail);487}488489fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {490    if (o.get(key)) |v| {491        if (v == .string) return v.string;492    }493    return "";494}495496pub fn edit(ctx: Ctx) !void {497    const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");498    const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";499    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });500    defer ctx.gpa.free(path);501    output.editOpen(path, ctx.cfg.editor);502    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);503}504505pub fn fmt(ctx: Ctx) !void {506    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});507    defer ctx.gpa.free(path);508    if (ctx.check) {509        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);510        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();511        return;512    }513    output.fmtStart(path);514    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);515    output.fmtDone();516}517518pub fn repl(ctx: Ctx) !void {519    output.replStart();520    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);521}522523pub fn develop(ctx: Ctx) !void {524    if (std.mem.eql(u8, ctx.sub, "show")) {525        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);526        return;527    }528    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))529        ctx.args[0]530    else531        null;532    output.developStart(&.{});533    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);534    output.developDone();535}536537pub fn info(ctx: Ctx) !void {538    output.infoHeader(ctx.machine.name);539    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");540    defer ctx.gpa.free(nixos_ver);541    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));542543    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");544    defer ctx.gpa.free(kernel);545    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));546547    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");548    defer ctx.gpa.free(uptime);549    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));550}551552pub fn boot(ctx: Ctx) !void {553    output.bootHeader(ctx.machine.name);554    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};555    defer ctx.gpa.free(entries);556    for (entries, 0..) |entry, i| output.bootEntry(entry, i);557}558559pub fn searchCmd(ctx: Ctx) !void {560    const query = if (ctx.args.len > 0) ctx.args[0] else "";561    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);562    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);563    if (selected) |npkg| try selectAndInstall(ctx, npkg);564}565566pub fn optionCmd(ctx: Ctx) !void {567    const query = if (ctx.args.len > 0) ctx.args[0] else "";568    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);569    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);570}571572pub fn install(ctx: Ctx) !void {573    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;574575    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);576577    // Search for the package to get the attr578    const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {579        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});580        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});581        return error.PackageNotFound;582    };583584    if (pkgs.len == 0) {585        // No matches — likely a typo. Suggest the closest real package and offer it.586        if (closestPackage(ctx, pkg_name)) |sugg| {587            output.didYouMean(pkg_name, sugg.pname);588            if (output.confirm("")) try selectAndInstall(ctx, sugg);589            return;590        }591        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});592        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});593        return error.PackageNotFound;594    }595596    // Prefer an exact name match over the first search result — `install ripgrep`597    // must pick "ripgrep", not the alphabetically-first match like "repgrep".598    var found = pkgs[0];599    for (pkgs) |p| {600        if (std.mem.eql(u8, p.pname, pkg_name)) {601            found = p;602            break;603        }604    }605    try selectAndInstall(ctx, found);606}607608// Find the real package whose name is closest to a not-found query (typo help).609// Typos usually keep the leading characters, so gather candidates with a prefix610// search and rank by edit distance; return the best only if it's typo-close.611fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {612    if (query.len < 2) return null;613    var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};614    if (candidates.len == 0 and query.len > 2) {615        candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};616    }617    if (candidates.len == 0) return null;618619    var best: ?types.NixPackage = null;620    var best_dist: usize = std.math.maxInt(usize);621    for (candidates) |p| {622        const d = editDistance(query, p.pname);623        if (d > 0 and d < best_dist) {624            best_dist = d;625            best = p;626        }627    }628    // Only suggest a genuinely close name, scaled to query length.629    const threshold = @max(@as(usize, 2), query.len / 3);630    return if (best_dist <= threshold) best else null;631}632633// Case-insensitive Levenshtein distance. Names longer than the row buffer are634// treated as far away (never suggested).635fn editDistance(a: []const u8, b: []const u8) usize {636    const n = b.len;637    if (a.len == 0) return n;638    if (n == 0) return a.len;639    if (n + 1 > 128) return std.math.maxInt(usize);640    var prev: [128]usize = undefined;641    var curr: [128]usize = undefined;642    var j: usize = 0;643    while (j <= n) : (j += 1) prev[j] = j;644    var i: usize = 1;645    while (i <= a.len) : (i += 1) {646        curr[0] = i;647        j = 1;648        while (j <= n) : (j += 1) {649            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;650            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));651        }652        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);653    }654    return prev[n];655}656657test "editDistance is case-insensitive Levenshtein" {658    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));659    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));660    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));661    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));662}663664// Prompt for the install method (profile / system / try) and dispatch. Shared by665// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys666// are read here, after the search widget's raw mode is gone, so they don't667// collide with typing a query.668fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {669    output.installSelectPrompt(npkg.pname, npkg.version);670671    var choice_buf: [8]u8 = undefined;672    var choice_len: usize = 0;673    while (choice_len < choice_buf.len) {674        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;675        if (n == 0) break;676        if (choice_buf[choice_len] == '\n') break;677        choice_len += 1;678    }679    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");680681    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {682        try profileInstallPkg(ctx, npkg);683    } else if (choice[0] == 's' or choice[0] == 'S') {684        try systemInstallPkg(ctx, npkg);685    } else if (choice[0] == 't' or choice[0] == 'T') {686        try tryPkg(ctx, npkg);687    }688}689690fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {691    output.installStart(npkg.pname, .profile);692    output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});693    output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));694    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);695    if (code != 0) return error.ProcessFailed;696    output.installDone(npkg.pname);697}698699fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {700    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});701    defer ctx.gpa.free(config_path);702    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;703    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);704    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);705    if (ctx.cfg.confirm) {706        if (output.confirm("apply now? ")) {707            try apply(ctx);708        }709    }710}711712fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {713    output.tryStart(npkg.pname);714    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});715    output.tryExitHint();716    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);717    output.tryDone();718}719720pub fn remove(ctx: Ctx) !void {721    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;722    output.removeStart(pkg_name);723    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);724    if (code != 0) return error.ProcessFailed;725    output.done();726}727728pub fn list(ctx: Ctx) !void {729    output.listHeader(ctx.machine.name);730731    // Profile packages: parse `nix profile list --json` into clean name+version732    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"733    // blocks.734    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {735        defer ctx.gpa.free(json);736        output.listSection("profile");737        renderProfileJson(ctx.gpa, json);738    }739740    // System packages: the references of /run/current-system/sw, each a741    // <hash>-<name>-<version> store path.742    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {743        defer ctx.gpa.free(paths);744        output.blankLine();745        output.listSection("system");746        var lines = std.mem.splitScalar(u8, paths, '\n');747        while (lines.next()) |line| {748            const t = std.mem.trim(u8, line, " \t\r");749            if (t.len == 0) continue;750            const row = pkgFromStorePath(t);751            // Skip support paths with no parseable version (man pages, wrappers).752            if (row.version.len == 0) continue;753            output.listPkg(row.name, row.version);754        }755    }756}757758const PkgRow = struct { name: []const u8, version: []const u8 };759760// Split a nix store path basename (<hash>-<name>-<version>) into name + version.761// Version begins at the first '-' followed by a digit, which reliably lands on762// the name/version boundary since the 32-char hash and package names start with763// non-digits.764fn pkgFromStorePath(path: []const u8) PkgRow {765    const base = std.fs.path.basename(path);766    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;767    var i: usize = 0;768    while (i + 1 < after_hash.len) : (i += 1) {769        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {770            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };771        }772    }773    return .{ .name = after_hash, .version = "" };774}775776// Multi-output derivations append the output name to the store path (e.g.777// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads778// as just the version.779fn stripOutputSuffix(ver: []const u8) []const u8 {780    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };781    for (suffixes) |s| {782        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];783    }784    return ver;785}786787test "pkgFromStorePath splits name and version at first dash-digit" {788    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");789    try std.testing.expectEqualStrings("ripgrep", a.name);790    try std.testing.expectEqualStrings("15.1.0", a.version);791792    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");793    try std.testing.expectEqualStrings("helix", b.name);794    try std.testing.expectEqualStrings("25.01", b.version);795796    // multi-output store paths drop their output-name suffix797    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");798    try std.testing.expectEqualStrings("curl", c.name);799    try std.testing.expectEqualStrings("8.20.0", c.version);800}801802fn firstStorePath(el: std.json.Value) ?[]const u8 {803    if (el != .object) return null;804    const sp = el.object.get("storePaths") orelse return null;805    if (sp != .array or sp.array.items.len == 0) return null;806    const first = sp.array.items[0];807    return if (first == .string) first.string else null;808}809810// `nix profile list --json` has two shapes across nix versions: newer keys each811// element by name (object), older lists them positionally (array). Handle both.812fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {813    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;814    defer parsed.deinit();815    if (parsed.value != .object) return;816    const elements = parsed.value.object.get("elements") orelse return;817    switch (elements) {818        .object => |obj| {819            var it = obj.iterator();820            while (it.next()) |entry| {821                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";822                output.listPkg(entry.key_ptr.*, ver);823            }824        },825        .array => |arr| {826            for (arr.items) |el| {827                const path = firstStorePath(el) orelse continue;828                const row = pkgFromStorePath(path);829                output.listPkg(row.name, row.version);830            }831        },832        else => {},833    }834}835836pub fn tryCmd(ctx: Ctx) !void {837    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;838    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };839    try tryPkg(ctx, shell_pkg);840}841842// --- Home Manager commands ---843844const home_help = [_][2][]const u8{845    .{ "apply", "apply home manager configuration" },846    .{ "apply --dry", "preview changes" },847    .{ "back", "roll back one generation" },848    .{ "history", "list all generations" },849    .{ "edit", "open home.nix" },850    .{ "check", "validate without applying" },851    .{ "diff", "changes between generations" },852    .{ "packages", "list managed packages" },853};854855const HomeGen = struct {856    number: u32,857    date: []const u8,858    time: []const u8,859    path: []const u8,860};861862// `home-manager generations` lines read:863//   2026-06-01 11:56 : id 765 -> /nix/store/<hash>-home-manager-generation864// Newest first, so index 0 is the current generation.865fn parseHomeGenerations(gpa: std.mem.Allocator, out_str: []const u8) ![]HomeGen {866    var gens: std.ArrayList(HomeGen) = .empty;867    var lines = std.mem.splitScalar(u8, out_str, '\n');868    while (lines.next()) |line| {869        const t = std.mem.trim(u8, line, " \t\r");870        if (t.len == 0) continue;871        var it = std.mem.tokenizeAny(u8, t, " \t");872        const date = it.next() orelse continue;873        const time = it.next() orelse continue;874        var number: ?u32 = null;875        var path: []const u8 = "";876        while (it.next()) |tok| {877            if (std.mem.eql(u8, tok, "id")) {878                if (it.next()) |n| number = std.fmt.parseInt(u32, n, 10) catch null;879            } else if (std.mem.startsWith(u8, tok, "/nix/store/")) {880                path = tok;881            }882        }883        const num = number orelse continue;884        try gens.append(gpa, .{885            .number = num,886            .date = try gpa.dupe(u8, date),887            .time = try gpa.dupe(u8, time),888            .path = try gpa.dupe(u8, path),889        });890    }891    return gens.toOwnedSlice(gpa);892}893894fn freeHomeGens(gpa: std.mem.Allocator, gens: []HomeGen) void {895    for (gens) |g| {896        gpa.free(g.date);897        gpa.free(g.time);898        gpa.free(g.path);899    }900    gpa.free(gens);901}902903test "parseHomeGenerations reads id, date and store path" {904    const a = std.testing.allocator;905    const sample =906        \\2026-06-01 11:56 : id 765 -> /nix/store/aaaa-home-manager-generation907        \\2026-05-31 10:29 : id 764 -> /nix/store/bbbb-home-manager-generation908    ;909    const gens = try parseHomeGenerations(a, sample);910    defer freeHomeGens(a, gens);911    try std.testing.expectEqual(@as(usize, 2), gens.len);912    try std.testing.expectEqual(@as(u32, 765), gens[0].number);913    try std.testing.expectEqualStrings("2026-06-01", gens[0].date);914    try std.testing.expectEqualStrings("11:56", gens[0].time);915    try std.testing.expectEqualStrings("/nix/store/aaaa-home-manager-generation", gens[0].path);916    try std.testing.expectEqual(@as(u32, 764), gens[1].number);917}918919// Current (newest) home generation number, or 0 if unavailable.920fn homeCurrentGen(ctx: Ctx) u32 {921    const out = exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine) catch return 0;922    defer ctx.gpa.free(out);923    const gens = parseHomeGenerations(ctx.gpa, out) catch return 0;924    defer freeHomeGens(ctx.gpa, gens);925    return if (gens.len > 0) gens[0].number else 0;926}927928pub fn home(ctx: Ctx) !void {929    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help"))930        return output.subcommandHelp("home", &home_help, null);931932    const mode = exec.detectHomeManager(ctx.gpa, ctx.io, ctx.environ);933    if (mode == .none) {934        output.homeNotInstalled();935        return;936    }937938    // apply is the only command meaningful in module mode (it redirects to939    // `nina apply`); everything else needs the standalone home-manager CLI.940    if (std.mem.eql(u8, ctx.sub, "apply")) return homeApply(ctx, mode);941    // edit just opens the local home.nix — fine in module mode too.942    if (std.mem.eql(u8, ctx.sub, "edit")) return homeEdit(ctx);943944    if (mode == .module) {945        output.homeModuleManaged();946        return;947    }948949    if (std.mem.eql(u8, ctx.sub, "back")) return homeBack(ctx);950    if (std.mem.eql(u8, ctx.sub, "history")) return homeHistory(ctx);951    if (std.mem.eql(u8, ctx.sub, "check")) return homeCheck(ctx);952    if (std.mem.eql(u8, ctx.sub, "diff")) return homeDiff(ctx);953    if (std.mem.eql(u8, ctx.sub, "packages")) return homePackages(ctx);954955    return output.subcommandHelp("home", &home_help, null);956}957958fn homePackages(ctx: Ctx) !void {959    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);960    defer ctx.gpa.free(out);961    const gens = try parseHomeGenerations(ctx.gpa, out);962    defer freeHomeGens(ctx.gpa, gens);963964    output.homePackagesHeader(ctx.machine.name);965    if (gens.len == 0 or gens[0].path.len == 0) return;966967    // The current generation's references are its managed packages (plus a few968    // home-manager scaffolding paths and versionless support outputs we skip).969    const refs = exec.homeGenerationReferences(ctx.gpa, ctx.io, &ctx.machine, gens[0].path) catch return;970    defer ctx.gpa.free(refs);971    var lines = std.mem.splitScalar(u8, refs, '\n');972    while (lines.next()) |line| {973        const t = std.mem.trim(u8, line, " \t\r");974        if (t.len == 0) continue;975        const row = pkgFromStorePath(t);976        if (row.version.len == 0) continue;977        if (std.mem.indexOf(u8, row.name, "home-manager") != null) continue;978        output.listPkg(row.name, row.version);979    }980}981982fn homeDiff(ctx: Ctx) !void {983    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);984    defer ctx.gpa.free(out);985    const gens = try parseHomeGenerations(ctx.gpa, out);986    defer freeHomeGens(ctx.gpa, gens);987988    // Need two generations and both their store paths to diff their closures.989    if (gens.len < 2 or gens[0].path.len == 0 or gens[1].path.len == 0) {990        output.homeNothingToDiff();991        return;992    }993    const newer = gens[0];994    const older = gens[1];995    output.homeDiffHeader(older.number, newer.number, ctx.machine.name);996    if (try exec.diffClosuresPaths(ctx.io, &ctx.machine, ctx.gpa, older.path, newer.path) != 0)997        return error.ProcessFailed;998}9991000fn homeCheck(ctx: Ctx) !void {1001    output.homeCheckStart(ctx.machine.name);1002    const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1003    if (code != 0) {1004        output.checkFailed("");1005        return error.BuildFailed;1006    }1007    output.homeCheckOk();1008}10091010fn homeEdit(ctx: Ctx) !void {1011    // Standalone home config lives at ~/.config/home-manager/home.nix; the same1012    // path is what detection keys on for module mode, so it resolves for both.1013    const path = exec.homeNixPath(ctx.gpa, ctx.environ) orelse {1014        errors.error_info.setMessage("could not resolve ~/.config/home-manager/home.nix", .{});1015        return error.ConfigNotFound;1016    };1017    defer ctx.gpa.free(path);1018    output.homeEditOpen(path, ctx.cfg.editor);1019    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);1020}10211022fn homeHistory(ctx: Ctx) !void {1023    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1024    defer ctx.gpa.free(out);1025    const gens = try parseHomeGenerations(ctx.gpa, out);1026    defer freeHomeGens(ctx.gpa, gens);1027    output.homeHistoryHeader(ctx.machine.name);1028    // Newest-first from home-manager; the first row is the current generation.1029    for (gens, 0..) |g, i| output.homeHistoryRow(g.number, g.date, g.time, i == 0);1030}10311032fn homeBack(ctx: Ctx) !void {1033    const out = try exec.homeGenerations(ctx.gpa, ctx.io, &ctx.machine);1034    defer ctx.gpa.free(out);1035    const gens = try parseHomeGenerations(ctx.gpa, out);1036    defer freeHomeGens(ctx.gpa, gens);10371038    // Newest-first: [0] is current, [1] is the generation to roll back to.1039    if (gens.len < 2) {1040        output.alreadyOldest();1041        return;1042    }1043    const current = gens[0].number;1044    const prev = gens[1].number;10451046    output.homeBackStart(ctx.machine.name, current, prev);1047    if (ctx.cfg.confirm and !output.confirm("")) return;1048    const code = try exec.homeManagerRollback(ctx.io, &ctx.machine, ctx.gpa);1049    if (code != 0) return error.BuildFailed;1050    output.homeBackDone(prev);1051}10521053fn homeApply(ctx: Ctx, mode: exec.HomeManagerMode) !void {1054    // NixOS/flake module: home config is rebuilt by nixos-rebuild — redirect.1055    if (mode == .module) {1056        output.homeModuleManaged();1057        return;1058    }1059    if (ctx.dry) {1060        output.homeApplyDry(ctx.machine.name);1061        const code = try exec.homeManagerBuild(ctx.io, &ctx.machine, ctx.gpa);1062        if (code != 0) return error.BuildFailed;1063        output.homeApplyDryDone();1064        return;1065    }10661067    output.homeApplyStart(ctx.machine.name);1068    const flake_ref = exec.homeFlakeRef(ctx.gpa, ctx.io, ctx.environ);1069    defer if (flake_ref) |r| ctx.gpa.free(r);1070    if (flake_ref) |ref| {1071        output.printSubstep("home-manager switch --flake {s}", .{ref});1072    } else {1073        output.printSubstep("home-manager switch", .{});1074    }10751076    const start = std.Io.Clock.awake.now(ctx.io);1077    const code = if (flake_ref) |ref|1078        try exec.homeManagerSwitchFlake(ctx.io, &ctx.machine, ctx.gpa, ref)1079    else1080        try exec.homeManagerSwitch(ctx.io, &ctx.machine, ctx.gpa);1081    if (code != 0) return error.BuildFailed;10821083    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());1084    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));1085    output.homeApplyDone(homeCurrentGen(ctx), elapsed);1086}10871088// --- Service commands ---10891090const service_help = [_][2][]const u8{1091    .{ "list", "list running services" },1092    .{ "logs <svc>", "show service logs" },1093    .{ "status <svc>", "service status" },1094    .{ "start <svc>", "start a service" },1095    .{ "stop <svc>", "stop a service" },1096    .{ "restart <svc>", "restart a service" },1097    .{ "enable <svc>", "enable at boot" },1098    .{ "disable <svc>", "disable at boot" },1099};11001101pub fn service(ctx: Ctx) !void {1102    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");1103    if (std.mem.eql(u8, ctx.sub, "list")) {1104        output.serviceListHeader(ctx.machine.name);1105        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};1106        defer ctx.gpa.free(svcs);1107        for (svcs) |s| output.serviceRow(s);1108        return;1109    }1110    if (std.mem.eql(u8, ctx.sub, "logs")) {1111        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1112        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");1113        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);1114        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);1115        return;1116    }1117    if (std.mem.eql(u8, ctx.sub, "status")) {1118        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1119        output.serviceVerb("status", name, ctx.machine.name);1120        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);1121        return;1122    }1123    // start/stop/restart/enable/disable1124    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1125    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {1126        if (!output.confirm("")) return;1127    }1128    output.serviceVerb(ctx.sub, name, ctx.machine.name);1129    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);1130    output.serviceDone();1131}11321133// --- Flake commands ---11341135const flake_help = [_][2][]const u8{1136    .{ "init", "create a new flake.nix" },1137    .{ "update", "update flake inputs" },1138    .{ "update <in>", "update a specific input" },1139    .{ "check", "validate the flake" },1140    .{ "show", "inspect flake outputs" },1141    .{ "lock", "regenerate flake.lock" },1142    .{ "clone <url>", "clone a flake repository" },1143};11441145pub fn flake(ctx: Ctx) !void {1146    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);1147    if (std.mem.eql(u8, ctx.sub, "update")) {1148        output.flakeUpdateStart();1149        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1150        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1151        output.flakeLockWritten();1152        return;1153    }1154    if (std.mem.eql(u8, ctx.sub, "check")) {1155        output.flakeCheckStart();1156        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);1157        if (code == 0) output.flakeValid() else output.checkFailed("");1158        return;1159    }1160    if (std.mem.eql(u8, ctx.sub, "show")) {1161        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;1162        if (json_out) |j| {1163            defer ctx.gpa.free(j);1164            output.flakeShowHeader("flake outputs");1165            // Parse and display the flake outputs1166            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;1167            defer parsed.deinit();1168            if (parsed.value == .object) {1169                var it = parsed.value.object.iterator();1170                while (it.next()) |entry| {1171                    if (entry.value_ptr.* == .object) {1172                        var inner = entry.value_ptr.object.iterator();1173                        while (inner.next()) |e2| {1174                            const desc = if (e2.value_ptr.* == .object)1175                                if (e2.value_ptr.object.get("description")) |d|1176                                    if (d == .string) d.string else ""1177                                else ""1178                            else "";1179                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);1180                        }1181                    }1182                }1183            }1184        }1185        return;1186    }1187    if (std.mem.eql(u8, ctx.sub, "init")) {1188        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);1189        return;1190    }1191    if (std.mem.eql(u8, ctx.sub, "lock")) {1192        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);1193        return;1194    }1195    if (std.mem.eql(u8, ctx.sub, "clone")) {1196        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1197        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);1198        return;1199    }1200}12011202// --- Store commands ---12031204const store_help = [_][2][]const u8{1205    .{ "info", "store size and counts" },1206    .{ "path <attr>", "store path of a package" },1207    .{ "gc", "collect garbage" },1208    .{ "verify", "verify store integrity" },1209    .{ "repair", "repair corrupted paths" },1210};12111212pub fn store(ctx: Ctx) !void {1213    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);1214    if (std.mem.eql(u8, ctx.sub, "gc")) {1215        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);1216        return;1217    }1218    if (std.mem.eql(u8, ctx.sub, "verify")) {1219        output.storeVerifyStart();1220        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);1221        return;1222    }1223    if (std.mem.eql(u8, ctx.sub, "repair")) {1224        if (ctx.cfg.confirm and !output.confirm("")) return;1225        output.storeRepairStart();1226        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);1227        return;1228    }1229    if (std.mem.eql(u8, ctx.sub, "info")) {1230        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1231        output.storeInfo(si);1232        return;1233    }1234    if (std.mem.eql(u8, ctx.sub, "path")) {1235        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1236        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);1237        defer ctx.gpa.free(path);1238        output.storePath(path);1239        return;1240    }1241    // default: info1242    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);1243    output.storeInfo(si);1244}12451246// --- Channel commands ---12471248const channel_help = [_][2][]const u8{1249    .{ "list", "list channels" },1250    .{ "add <url> [name]", "add a channel" },1251    .{ "remove <name>", "remove a channel" },1252    .{ "update", "update all channels" },1253};12541255pub fn channel(ctx: Ctx) !void {1256    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1257    // On a flake-managed system, nix-channel operations generally don't apply.1258    if (flakeSystem(ctx)) output.flakeChannelNote();1259    if (std.mem.eql(u8, ctx.sub, "list")) {1260        output.channelListHeader(ctx.machine.name);1261        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1262        defer ctx.gpa.free(chans);1263        for (chans) |ch| output.channelRow(ch);1264        return;1265    }1266    if (std.mem.eql(u8, ctx.sub, "add")) {1267        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1268        const name = if (ctx.args.len > 1) ctx.args[1] else "";1269        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1270        output.channelDone();1271        return;1272    }1273    if (std.mem.eql(u8, ctx.sub, "remove")) {1274        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1275        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1276        output.channelDone();1277        return;1278    }1279    if (std.mem.eql(u8, ctx.sub, "update")) {1280        return channelUpdateCmd(ctx);1281    }1282}12831284// --- Profile commands ---12851286pub fn profile(ctx: Ctx) !void {1287    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1288        output.profileListHeader();1289        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1290        if (out) |o| {1291            defer ctx.gpa.free(o);1292            var lines = std.mem.splitScalar(u8, o, '\n');1293            while (lines.next()) |line| {1294                const t = std.mem.trim(u8, line, " \t\r");1295                if (t.len == 0) continue;1296                output.profileRow(t, "", "");1297            }1298        }1299        return;1300    }1301    if (std.mem.eql(u8, ctx.sub, "install")) {1302        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1303        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1304        output.done();1305        return;1306    }1307    if (std.mem.eql(u8, ctx.sub, "remove")) {1308        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1309        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1310        output.done();1311        return;1312    }1313    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1314        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1315        output.done();1316        return;1317    }1318}13191320// --- Pkg commands ---13211322const pkg_help = [_][2][]const u8{1323    .{ "why <pkg>", "what pulled it in" },1324    .{ "deps <pkg>", "direct dependencies" },1325    .{ "size <pkg>", "closure size" },1326    .{ "path <pkg>", "store path" },1327    .{ "closure <pkg>", "full closure" },1328};13291330pub fn pkg(ctx: Ctx) !void {1331    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1332    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1333    if (std.mem.eql(u8, ctx.sub, "why")) {1334        _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1335        return;1336    }1337    if (std.mem.eql(u8, ctx.sub, "deps")) {1338        _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);1339        return;1340    }1341    if (std.mem.eql(u8, ctx.sub, "size")) {1342        const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;1343        if (s) |sz| {1344            defer ctx.gpa.free(sz);1345            output.pkgResult("size", sz);1346        }1347        return;1348    }1349    if (std.mem.eql(u8, ctx.sub, "path")) {1350        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1351        defer ctx.gpa.free(p);1352        output.pkgResult("path", p);1353        return;1354    }1355    if (std.mem.eql(u8, ctx.sub, "closure")) {1356        _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);1357        return;1358    }1359}13601361// Top-level alias for `nina pkg why <pkg>` — surfaces what pulled a package in1362// without the user needing to know about the `pkg` subgroup.1363pub fn why(ctx: Ctx) !void {1364    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1365    _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1366}13671368// --- Pin / Unpin ---13691370pub fn pin(ctx: Ctx) !void {1371    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1372    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1373    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1374    output.pinDone(input, commit);1375}13761377pub fn unpin(ctx: Ctx) !void {1378    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1379    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1380    output.unpinDone(input);1381}13821383// --- Hash / Fetch ---13841385pub fn hash(ctx: Ctx) !void {1386    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1387    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1388    defer ctx.gpa.free(h);1389    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1390}13911392pub fn fetch(ctx: Ctx) !void {1393    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1394    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1395    defer ctx.gpa.free(h);1396    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1397}13981399// --- Build / Run ---14001401pub fn build(ctx: Ctx) !void {1402    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1403    output.buildStart(attr orelse "default");1404    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1405    if (code != 0) return error.BuildFailed;1406    output.buildDone();1407}14081409pub fn runCmd(ctx: Ctx) !void {1410    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1411    output.runStart(pkg_arg);1412    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1413}14141415// --- Hello ---14161417pub fn hello(ctx: Ctx) !void {1418    output.hello(ctx.cfg.machines);1419}14201421// Runs when ~/.nina.conf is absent on first invocation (interactive TTY only).1422// Prompts for machine name, config path, and local flag, then writes the file.1423pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1424    output.firstRunBanner();1425    output.firstRunNoConfig();14261427    var name_buf: [256]u8 = undefined;1428    var path_buf: [256]u8 = undefined;1429    var local_buf: [256]u8 = undefined;14301431    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);14321433    // Flake-based systems don't have a traditional /etc/nixos/configuration.nix —1434    // their config lives wherever flake.nix is. Ask, then prompt for the right1435    // path and record `flake = true` so channel commands can warn appropriately.1436    const use_flakes = output.firstRunManageType();1437    const config_path = if (use_flakes)1438        output.firstRunPrompt("flake directory", "~/nixos-config", &path_buf)1439    else1440        output.firstRunPrompt("config path", "/etc/nixos", &path_buf);1441    const local_str = output.firstRunPrompt("local", "true", &local_buf);14421443    const conf_path = try config.configPath(gpa, environ);1444    defer gpa.free(conf_path);1445    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);14461447    // `flake` is a top-level config field, so it must precede the [machine] block.1448    const flake_line = if (use_flakes) "flake = true\n" else "";1449    var content_buf: [1024]u8 = undefined;1450    const content = try std.fmt.bufPrint(1451        &content_buf,1452        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = {s}\n",1453        .{ flake_line, machine_name, config_path, local_str },1454    );14551456    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1457        errors.error_info.setMessage("could not write {s}", .{conf_path});1458        return error.Internal;1459    };1460    defer file.close(io);1461    file.writePositionalAll(io, content, 0) catch {1462        errors.error_info.setMessage("could not write {s}", .{conf_path});1463        return error.Internal;1464    };14651466    output.firstRunWritten(conf_path);1467}14681469pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1470    // Create the config first if it doesn't exist. This makes `nina setup`1471    // a complete onboarding command — not just a nix-features check. Any legacy1472    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.1473    config.migrateLegacyConfig(gpa, io, environ);1474    if (config.configPath(gpa, environ)) |conf_path| {1475        defer gpa.free(conf_path);1476        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1477            f.close(io);1478        } else |_| {1479            try firstRunWizard(gpa, io, environ);1480            errors.error_info.reset();1481        }1482    } else |_| {}14831484    output.setupCheck();1485    const status = exec.checkNixFeatures(gpa, io, environ);1486    output.setupFeatures(status.nix_command, status.flakes);14871488    if (status.allEnabled()) {1489        output.setupAllSet();1490        api.ensureRegistryPinned(gpa, io, environ);1491        return;1492    }14931494    // On NixOS the features belong in configuration.nix (the declarative,1495    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;1496    // the user runs the rebuild. We don't pin the registry here because the1497    // features aren't live until that rebuild lands.1498    if (exec.isNixOS(io)) {1499        const conf_path = "/etc/nixos/configuration.nix";1500        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1501            output.setupNixosNeedsRebuild(conf_path);1502            return;1503        }1504        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1505        if (output.confirmDefaultNo("add it now?")) {1506            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1507                output.setupNixosWrote(conf_path);1508            } else |_| {1509                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1510            }1511        } else {1512            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1513        }1514        return;1515    }15161517    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.1518    output.setupEnabling();1519    const path = try exec.enableNixFeatures(gpa, io, environ);1520    defer gpa.free(path);15211522    output.setupDone(path);1523    api.ensureRegistryPinned(gpa, io, environ);1524}15251526// --- Log helper ---15271528fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1529    var ts_buf: [32]u8 = undefined;1530    const ts = nowIso(ctx.io, &ts_buf);1531    var buf: [256]u8 = undefined;1532    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1533        ts, ctx.machine.name, action, gen,1534    }) catch return;1535    exec.appendNinaLog(ctx.io, ctx.environ, entry);1536}15371538// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);1539// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.1540fn nowIso(io: std.Io, buf: []u8) []const u8 {1541    const fallback = "1970-01-01T00:00:00Z";1542    const ns = std.Io.Clock.real.now(io).toNanoseconds();1543    if (ns <= 0) return fallback;1544    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1545    const es = std.time.epoch.EpochSeconds{ .secs = secs };1546    const ed = es.getEpochDay();1547    const yd = ed.calculateYearDay();1548    const md = yd.calculateMonthDay();1549    const ds = es.getDaySeconds();1550    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", .{1551        yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1552        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1553    }) catch return fallback;1554}