commands.zig

49.6 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};3233pub fn apply(ctx: Ctx) !void {34    if (ctx.dry) {35        output.applyDry(ctx.machine.name);36        const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);37        if (code != 0) return error.BuildFailed;38        output.applyDryDone();39        return;40    }41    if (ctx.check) {42        return check(ctx);43    }4445    output.applyStart(ctx.machine.name);46    const start = std.Io.Clock.awake.now(ctx.io);4748    const code = exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa) catch |e| {49        exec.markApplyFailed(ctx.io, ctx.environ);50        output.applyFailed("");51        return e;52    };5354    if (code != 0) {55        exec.markApplyFailed(ctx.io, ctx.environ);56        output.applyFailed("");57        return error.BuildFailed;58    }5960    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());61    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));62    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;63    const after_failure = exec.takeApplyFailed(ctx.io, ctx.environ);64    output.applyDone(gen, elapsed, after_failure);65    logAction(ctx, "apply", gen);66}6768pub fn check(ctx: Ctx) !void {69    output.checkStart(ctx.machine.name);70    const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);71    if (code != 0) {72        output.checkFailed("");73        return error.BuildFailed;74    }75    output.checkOk();76}7778pub fn back(ctx: Ctx) !void {79    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);80    defer ctx.gpa.free(gens);8182    var current: u32 = 0;83    for (gens) |g| if (g.current) { current = g.number; };8485    // Newest generation older than current. If there is none, we're already at the86    // oldest — stop cleanly instead of letting rollback fail with 'build failed'.87    var prev: u32 = 0;88    var has_prev = false;89    for (gens) |g| {90        if (g.number < current and (!has_prev or g.number > prev)) {91            prev = g.number;92            has_prev = true;93        }94    }95    if (!has_prev) {96        output.alreadyOldest();97        return;98    }99100    output.backStart(ctx.machine.name, current, prev);101    if (ctx.cfg.confirm and !output.confirm("")) return;102103    const code = try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);104    if (code != 0) return error.BuildFailed;105    output.backDone(prev);106}107108pub fn go(ctx: Ctx) !void {109    if (ctx.args.len == 0) return error.Internal;110    const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;111    const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);112113    output.goStart(ctx.machine.name, current, target);114    if (ctx.cfg.confirm and !output.confirm("")) return;115116    const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);117    if (code != 0) return error.ProcessFailed;118    output.generationDone(target);119}120121pub fn history(ctx: Ctx) !void {122    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);123    defer ctx.gpa.free(gens);124    output.historyHeader(ctx.machine.name);125    for (gens) |g| output.historyRow(g);126}127128const gen_help = [_][2][]const u8{129    .{ "list", "list generations" },130    .{ "current", "show current generation" },131    .{ "delete <n>", "delete generation n" },132    .{ "delete old", "delete old generations" },133};134135pub fn genCmd(ctx: Ctx) !void {136    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("gen", &gen_help, null);137    if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);138    if (std.mem.eql(u8, ctx.sub, "current")) {139        const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);140        output.genCurrent(n);141        return;142    }143    if (std.mem.eql(u8, ctx.sub, "delete")) {144        if (ctx.args.len == 0) return error.Internal;145        if (std.mem.eql(u8, ctx.args[0], "old")) {146            if (ctx.cfg.confirm and !output.confirm("")) return;147            _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);148        } else {149            const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;150            if (ctx.cfg.confirm and !output.confirm("")) return;151            _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);152        }153        output.done();154        return;155    }156    return error.Internal;157}158159pub fn clean(ctx: Ctx) !void {160    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);161    defer ctx.gpa.free(gens);162    const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");163    const total: u32 = @intCast(gens.len);164    // `clean all` keeps only the current generation; otherwise keep the configured165    // count. With nothing older than the keep limit, there's nothing to collect.166    const keep: u32 = if (all) 1 else ctx.cfg.generations;167    if (total <= keep) {168        output.cleanNothing(ctx.machine.name, total);169        return;170    }171    output.cleanStart(ctx.machine.name, keep, total);172    if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;173    _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);174    output.cleanDone();175}176177pub fn statusCmd(ctx: Ctx) !void {178    output.statusHeader();179    // --all renders every configured machine; remotes route through the same SSH180    // path as exec.capture. An unreachable machine is shown in red, not fatal.181    if (ctx.all and ctx.cfg.machines.len > 0) {182        for (ctx.cfg.machines) |m| statusRowFor(ctx, &m);183        return;184    }185    statusRowFor(ctx, &ctx.machine);186}187188fn statusRowFor(ctx: Ctx, machine: *const types.Machine) void {189    // A failure to read the current generation means we couldn't reach or query190    // the machine — mark it unreachable rather than reporting a bogus gen 0.191    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, machine) catch {192        output.statusRow(machine.name, 0, "", "", false);193        return;194    };195    const st = exec.systemStatus(ctx.gpa, ctx.io, machine);196    defer ctx.gpa.free(st.size);197    defer ctx.gpa.free(st.age);198    output.statusRow(machine.name, gen, st.age, st.size, true);199}200201pub fn diff(ctx: Ctx) !void {202    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);203    defer ctx.gpa.free(gens);204    var current: u32 = 0;205    var prev: u32 = 0;206    for (gens) |g| {207        if (g.current) current = g.number;208        if (!g.current and g.number > prev and g.number < current) prev = g.number;209    }210    if (ctx.args.len >= 2) {211        const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;212        const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;213        output.diffHeader(a, b, ctx.machine.name);214        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b) != 0) return error.ProcessFailed;215    } else {216        output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);217        if (try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current) != 0) return error.ProcessFailed;218    }219}220221pub fn mood(ctx: Ctx) !void {222    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;223    const st = exec.systemStatus(ctx.gpa, ctx.io, &ctx.machine);224    defer ctx.gpa.free(st.size);225    defer ctx.gpa.free(st.age);226    const state = exec.systemRunningState(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");227    defer ctx.gpa.free(state);228    output.mood(ctx.machine.name, state, gen, st.age, st.size);229}230231pub fn doctor(ctx: Ctx) !void {232    output.doctorHeader(ctx.machine.name);233    const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);234    defer ctx.gpa.free(checks);235    var warnings: u32 = 0;236    var failures: u32 = 0;237    for (checks) |ch| {238        output.doctorRow(ch);239        if (ch.status == .warn) warnings += 1;240        if (ch.status == .fail) failures += 1;241    }242    output.doctorSummary(warnings, failures);243}244245// nina update — kepr self-update for the nina binary itself.246pub fn update(ctx: Ctx) !void {247    output.updateSelfStart();248249    if (comptime std.mem.eql(u8, version.PLATFORM, "unsupported")) {250        output.updateSelfNoPlatform(@tagName(builtin.cpu.arch) ++ "-" ++ @tagName(builtin.os.tag));251        return error.Internal;252    }253254    const env_url = ctx.environ.get("NINA_UPDATE_SOURCE");255    const source_url = env_url orelse UPDATE_URL;256257    const body = exec.fetchUrl(ctx.gpa, ctx.io, source_url) catch |e| switch (e) {258        error.NetworkError, error.HttpError => {259            output.updateSelfNetworkError();260            return;261        },262        else => return e,263    };264    defer ctx.gpa.free(body);265266    const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, body, .{}) catch {267        output.printWarning("could not parse release metadata");268        return;269    };270    defer parsed.deinit();271272    const root = parsed.value;273    if (root != .object) { output.printWarning("malformed release metadata"); return; }274275    const remote_ver = blk: {276        const v = root.object.get("version") orelse { output.printWarning("malformed release metadata"); return; };277        break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };278    };279280    if (std.mem.eql(u8, remote_ver, version.VERSION)) {281        output.updateSelfCurrent(version.VERSION);282        return;283    }284285    output.updateSelfAvailable(version.VERSION, remote_ver);286    if (ctx.check) return;287288    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;289    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {290        errors.error_info.setMessage("could not determine install path", .{});291        return error.Internal;292    };293294    // When running from the nix store, defer to nix profile upgrade so nix295    // manages the transition (the store is read-only; binary replacement fails).296    // A NixOS system install also resolves into the store but isn't a profile297    // element, so check the profile to avoid a no-op `upgrade` — it updates with298    // the next nixos-rebuild instead.299    if (std.mem.startsWith(u8, install_path, "/nix/store/")) {300        const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);301        defer {302            if (nina_element) |n| ctx.gpa.free(n);303        }304        if (nina_element == null) {305            output.updateSelfNotInProfile();306            return;307        }308        const element = nina_element.?;309        output.updateSelfNixManaged(remote_ver);310        if (ctx.cfg.confirm and !output.confirm("")) return;311        const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "upgrade", element }) catch {312            output.updateSelfNixFailed();313            return;314        };315        if (ec != 0) output.updateSelfNixFailed();316        return;317    }318319    const plat_info = blk: {320        const pv = root.object.get("platforms") orelse break :blk null;321        if (pv != .object) break :blk null;322        break :blk pv.object.get(version.PLATFORM);323    };324    if (plat_info == null) { output.updateSelfNoPlatform(version.PLATFORM); return; }325326    const dl_url = blk: {327        const v = plat_info.?.object.get("url") orelse { output.printWarning("malformed release metadata"); return; };328        break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };329    };330331    const raw_cksum = blk: {332        if (plat_info.?.object.get("blake3")) |v|333            break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };334        if (plat_info.?.object.get("checksum")) |v|335            break :blk switch (v) { .string => |s| s, else => { output.printWarning("malformed release metadata"); return; } };336        output.printWarning("missing checksum in release metadata");337        return;338    };339    const expected_hex = if (std.mem.startsWith(u8, raw_cksum, "blake3:")) raw_cksum["blake3:".len..] else raw_cksum;340341    if (ctx.cfg.confirm and !output.confirm("")) return;342343    output.updateSelfDownloading(remote_ver, version.PLATFORM);344    const tmp_path = exec.downloadToTemp(ctx.gpa, ctx.io, dl_url) catch {345        output.printWarning("download failed — check your connection and try again");346        return;347    };348    defer ctx.gpa.free(tmp_path);349350    output.updateSelfVerifying();351    exec.verifyAndInstall(ctx.gpa, ctx.io, tmp_path, expected_hex, install_path) catch |e| switch (e) {352        error.ChecksumMismatch => { output.updateSelfChecksumFailed(); return; },353        else => return e,354    };355356    output.updateSelfDone(version.VERSION, remote_ver);357}358359// nina goodbye — clean uninstall. Three install paths:360// - nix profile (binary in nix store with a profile element) → nix profile remove361// - koh build or source build (plain binary on PATH) → delete the file362pub fn goodbye(ctx: Ctx) !void {363    output.goodbyeStart();364365    var exe_buf: [std.Io.Dir.max_path_bytes]u8 = undefined;366    const install_path = exec.selfExePath(ctx.io, &exe_buf) catch {367        errors.error_info.setMessage("could not determine install path", .{});368        return error.Internal;369    };370371    // A binary outside the nix store is a koh build or source build — delete it.372    if (!std.mem.startsWith(u8, install_path, "/nix/store/")) {373        output.goodbyeFile(install_path);374        if (ctx.cfg.confirm and !output.confirm("")) return;375        std.Io.Dir.deleteFileAbsolute(ctx.io, install_path) catch |e| {376            errors.error_info.setMessage("could not remove {s}", .{install_path});377            return e;378        };379        output.goodbyeDone();380        return;381    }382383    // Binary is in the nix store — find and remove the profile element.384    const nina_element = exec.profileNinaElement(ctx.gpa, ctx.io, &ctx.machine);385    defer {386        if (nina_element) |n| ctx.gpa.free(n);387    }388389    if (nina_element == null) {390        errors.error_info.setMessage("nina not found in nix profile — was it installed via 'nix profile add'?", .{});391        return error.Internal;392    }393394    output.goodbyeNix();395    if (ctx.cfg.confirm and !output.confirm("")) return;396    const ec = exec.streamLocal(ctx.io, &.{ "nix", "profile", "remove", nina_element.? }) catch {397        output.goodbyeFailed("nix profile remove failed");398        return;399    };400    if (ec != 0) {401        output.goodbyeFailed("nix profile remove failed");402        return;403    }404    output.goodbyeDone();405}406407fn channelUpdateCmd(ctx: Ctx) !void {408    output.updateStart(ctx.machine.name);409    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);410    output.updateDone();411}412413pub fn upgrade(ctx: Ctx) !void {414    output.upgradeStart(ctx.machine.name);415    output.printSubstep("updating channels", .{});416    _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};417    output.printSubstep("rebuilding", .{});418    const start = std.Io.Clock.awake.now(ctx.io);419    const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);420    if (code != 0) {421        output.applyFailed("");422        return error.BuildFailed;423    }424    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());425    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));426    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;427    output.applyDone(gen, elapsed, false);428}429430pub fn log(ctx: Ctx) !void {431    output.logHeader(ctx.machine.name);432    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {433        // No log yet — that's fine434        return;435    };436    defer ctx.gpa.free(content);437    var lines = std.mem.splitScalar(u8, content, '\n');438    while (lines.next()) |line| {439        const t = std.mem.trim(u8, line, " \t\r");440        if (t.len == 0) continue;441        if (t[0] == '{') {442            renderJsonLogLine(ctx.gpa, t);443        } else {444            // legacy tab-separated format445            var parts = std.mem.tokenizeScalar(u8, t, '\t');446            const date = parts.next() orelse continue;447            const time = parts.next() orelse "";448            const action = parts.next() orelse "";449            const detail = parts.next() orelse "";450            output.logRow(date, time, action, detail);451        }452    }453}454455// The on-disk log is JSON Lines: {"ts","machine","command","outcome","gen_after",...}.456// Render ts -> date/time columns, command -> action, outcome(+gen) -> detail.457fn renderJsonLogLine(gpa: std.mem.Allocator, line: []const u8) void {458    const parsed = std.json.parseFromSlice(std.json.Value, gpa, line, .{}) catch {459        output.logRow(line, "", "", ""); // unparseable — show raw rather than drop460        return;461    };462    defer parsed.deinit();463    if (parsed.value != .object) return;464    const o = parsed.value.object;465466    const ts = jsonStr(o, "ts");467    const date = if (ts.len >= 10) ts[0..10] else ts;468    const time = if (ts.len >= 16) ts[11..16] else "";469    const action = jsonStr(o, "command");470    const outcome = jsonStr(o, "outcome");471472    var buf: [160]u8 = undefined;473    var detail: []const u8 = outcome;474    if (o.get("gen_after")) |g| {475        if (g == .integer) {476            detail = std.fmt.bufPrint(&buf, "{s}   -> gen {d}", .{ outcome, g.integer }) catch outcome;477        }478    }479    output.logRow(date, time, action, detail);480}481482fn jsonStr(o: std.json.ObjectMap, key: []const u8) []const u8 {483    if (o.get(key)) |v| {484        if (v == .string) return v.string;485    }486    return "";487}488489pub fn edit(ctx: Ctx) !void {490    const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");491    const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";492    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });493    defer ctx.gpa.free(path);494    output.editOpen(path, ctx.cfg.editor);495    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);496}497498pub fn fmt(ctx: Ctx) !void {499    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});500    defer ctx.gpa.free(path);501    if (ctx.check) {502        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);503        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();504        return;505    }506    output.fmtStart(path);507    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);508    output.fmtDone();509}510511pub fn repl(ctx: Ctx) !void {512    output.replStart();513    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);514}515516pub fn develop(ctx: Ctx) !void {517    if (std.mem.eql(u8, ctx.sub, "show")) {518        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);519        return;520    }521    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))522        ctx.args[0]523    else524        null;525    output.developStart(&.{});526    _ = try exec.nixDevelopPs1(ctx.io, &ctx.machine, ctx.gpa, run_cmd, ctx.environ);527    output.developDone();528}529530pub fn info(ctx: Ctx) !void {531    output.infoHeader(ctx.machine.name);532    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");533    defer ctx.gpa.free(nixos_ver);534    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));535536    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");537    defer ctx.gpa.free(kernel);538    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));539540    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");541    defer ctx.gpa.free(uptime);542    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));543}544545pub fn boot(ctx: Ctx) !void {546    output.bootHeader(ctx.machine.name);547    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};548    defer ctx.gpa.free(entries);549    for (entries, 0..) |entry, i| output.bootEntry(entry, i);550}551552pub fn searchCmd(ctx: Ctx) !void {553    const query = if (ctx.args.len > 0) ctx.args[0] else "";554    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);555    const selected = try search_tui.run(ctx.gpa, ctx.io, query, .packages);556    if (selected) |npkg| try selectAndInstall(ctx, npkg);557}558559pub fn optionCmd(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    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);563}564565pub fn install(ctx: Ctx) !void {566    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;567568    api.ensureRegistryPinned(ctx.gpa, ctx.io, ctx.environ);569570    // Search for the package to get the attr571    const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {572        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});573        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});574        return error.PackageNotFound;575    };576577    if (pkgs.len == 0) {578        // No matches — likely a typo. Suggest the closest real package and offer it.579        if (closestPackage(ctx, pkg_name)) |sugg| {580            output.didYouMean(pkg_name, sugg.pname);581            if (output.confirm("")) try selectAndInstall(ctx, sugg);582            return;583        }584        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});585        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});586        return error.PackageNotFound;587    }588589    // Prefer an exact name match over the first search result — `install ripgrep`590    // must pick "ripgrep", not the alphabetically-first match like "repgrep".591    var found = pkgs[0];592    for (pkgs) |p| {593        if (std.mem.eql(u8, p.pname, pkg_name)) {594            found = p;595            break;596        }597    }598    try selectAndInstall(ctx, found);599}600601// Find the real package whose name is closest to a not-found query (typo help).602// Typos usually keep the leading characters, so gather candidates with a prefix603// search and rank by edit distance; return the best only if it's typo-close.604fn closestPackage(ctx: Ctx, query: []const u8) ?types.NixPackage {605    if (query.len < 2) return null;606    var candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..@min(query.len, 4)]) catch &.{};607    if (candidates.len == 0 and query.len > 2) {608        candidates = api.searchPackages(ctx.gpa, ctx.io, query[0..2]) catch &.{};609    }610    if (candidates.len == 0) return null;611612    var best: ?types.NixPackage = null;613    var best_dist: usize = std.math.maxInt(usize);614    for (candidates) |p| {615        const d = editDistance(query, p.pname);616        if (d > 0 and d < best_dist) {617            best_dist = d;618            best = p;619        }620    }621    // Only suggest a genuinely close name, scaled to query length.622    const threshold = @max(@as(usize, 2), query.len / 3);623    return if (best_dist <= threshold) best else null;624}625626// Case-insensitive Levenshtein distance. Names longer than the row buffer are627// treated as far away (never suggested).628fn editDistance(a: []const u8, b: []const u8) usize {629    const n = b.len;630    if (a.len == 0) return n;631    if (n == 0) return a.len;632    if (n + 1 > 128) return std.math.maxInt(usize);633    var prev: [128]usize = undefined;634    var curr: [128]usize = undefined;635    var j: usize = 0;636    while (j <= n) : (j += 1) prev[j] = j;637    var i: usize = 1;638    while (i <= a.len) : (i += 1) {639        curr[0] = i;640        j = 1;641        while (j <= n) : (j += 1) {642            const cost: usize = if (std.ascii.toLower(a[i - 1]) == std.ascii.toLower(b[j - 1])) 0 else 1;643            curr[j] = @min(prev[j] + 1, @min(curr[j - 1] + 1, prev[j - 1] + cost));644        }645        @memcpy(prev[0 .. n + 1], curr[0 .. n + 1]);646    }647    return prev[n];648}649650test "editDistance is case-insensitive Levenshtein" {651    try std.testing.expectEqual(@as(usize, 1), editDistance("firefux", "firefox"));652    try std.testing.expectEqual(@as(usize, 0), editDistance("git", "GIT"));653    try std.testing.expectEqual(@as(usize, 2), editDistance("fierfox", "firefox"));654    try std.testing.expectEqual(@as(usize, 7), editDistance("", "firefox"));655}656657// Prompt for the install method (profile / system / try) and dispatch. Shared by658// `nina install <pkg>` and the search widget's Enter-to-select — the letter keys659// are read here, after the search widget's raw mode is gone, so they don't660// collide with typing a query.661fn selectAndInstall(ctx: Ctx, npkg: types.NixPackage) !void {662    output.installSelectPrompt(npkg.pname, npkg.version);663664    var choice_buf: [8]u8 = undefined;665    var choice_len: usize = 0;666    while (choice_len < choice_buf.len) {667        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;668        if (n == 0) break;669        if (choice_buf[choice_len] == '\n') break;670        choice_len += 1;671    }672    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");673674    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {675        try profileInstallPkg(ctx, npkg);676    } else if (choice[0] == 's' or choice[0] == 'S') {677        try systemInstallPkg(ctx, npkg);678    } else if (choice[0] == 't' or choice[0] == 'T') {679        try tryPkg(ctx, npkg);680    }681}682683fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {684    output.installStart(npkg.pname, .profile);685    output.printSubstep("nix profile add nixpkgs#{s}", .{npkg.attr});686    output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile add nixpkgs#{s}", .{npkg.attr}));687    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);688    if (code != 0) return error.ProcessFailed;689    output.installDone(npkg.pname);690}691692fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {693    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});694    defer ctx.gpa.free(config_path);695    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;696    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);697    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);698    if (ctx.cfg.confirm) {699        if (output.confirm("apply now? ")) {700            try apply(ctx);701        }702    }703}704705fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {706    output.tryStart(npkg.pname);707    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});708    output.tryExitHint();709    _ = try exec.nixShellPs1(ctx.io, &ctx.machine, ctx.gpa, npkg.attr, ctx.environ);710    output.tryDone();711}712713pub fn remove(ctx: Ctx) !void {714    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;715    output.removeStart(pkg_name);716    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);717    if (code != 0) return error.ProcessFailed;718    output.done();719}720721pub fn list(ctx: Ctx) !void {722    output.listHeader(ctx.machine.name);723724    // Profile packages: parse `nix profile list --json` into clean name+version725    // rows instead of dumping nix's verbose multi-line "Name:/Flake attribute:"726    // blocks.727    if (exec.profileListJson(ctx.gpa, ctx.io, &ctx.machine) catch null) |json| {728        defer ctx.gpa.free(json);729        output.listSection("profile");730        renderProfileJson(ctx.gpa, json);731    }732733    // System packages: the references of /run/current-system/sw, each a734    // <hash>-<name>-<version> store path.735    if (exec.systemPackagePaths(ctx.gpa, ctx.io, &ctx.machine) catch null) |paths| {736        defer ctx.gpa.free(paths);737        output.blankLine();738        output.listSection("system");739        var lines = std.mem.splitScalar(u8, paths, '\n');740        while (lines.next()) |line| {741            const t = std.mem.trim(u8, line, " \t\r");742            if (t.len == 0) continue;743            const row = pkgFromStorePath(t);744            // Skip support paths with no parseable version (man pages, wrappers).745            if (row.version.len == 0) continue;746            output.listPkg(row.name, row.version);747        }748    }749}750751const PkgRow = struct { name: []const u8, version: []const u8 };752753// Split a nix store path basename (<hash>-<name>-<version>) into name + version.754// Version begins at the first '-' followed by a digit, which reliably lands on755// the name/version boundary since the 32-char hash and package names start with756// non-digits.757fn pkgFromStorePath(path: []const u8) PkgRow {758    const base = std.fs.path.basename(path);759    const after_hash = if (base.len > 33 and base[32] == '-') base[33..] else base;760    var i: usize = 0;761    while (i + 1 < after_hash.len) : (i += 1) {762        if (after_hash[i] == '-' and std.ascii.isDigit(after_hash[i + 1])) {763            return .{ .name = after_hash[0..i], .version = stripOutputSuffix(after_hash[i + 1 ..]) };764        }765    }766    return .{ .name = after_hash, .version = "" };767}768769// Multi-output derivations append the output name to the store path (e.g.770// curl-8.20.0-bin, less-692-man). Strip that suffix so the version column reads771// as just the version.772fn stripOutputSuffix(ver: []const u8) []const u8 {773    const suffixes = [_][]const u8{ "-bin", "-man", "-dev", "-doc", "-lib", "-info", "-out", "-static", "-devdoc" };774    for (suffixes) |s| {775        if (std.mem.endsWith(u8, ver, s)) return ver[0 .. ver.len - s.len];776    }777    return ver;778}779780test "pkgFromStorePath splits name and version at first dash-digit" {781    const a = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-ripgrep-15.1.0");782    try std.testing.expectEqualStrings("ripgrep", a.name);783    try std.testing.expectEqualStrings("15.1.0", a.version);784785    const b = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-helix-25.01");786    try std.testing.expectEqualStrings("helix", b.name);787    try std.testing.expectEqualStrings("25.01", b.version);788789    // multi-output store paths drop their output-name suffix790    const c = pkgFromStorePath("/nix/store/abcdefghijklmnopqrstuvwxyz012345-curl-8.20.0-bin");791    try std.testing.expectEqualStrings("curl", c.name);792    try std.testing.expectEqualStrings("8.20.0", c.version);793}794795fn firstStorePath(el: std.json.Value) ?[]const u8 {796    if (el != .object) return null;797    const sp = el.object.get("storePaths") orelse return null;798    if (sp != .array or sp.array.items.len == 0) return null;799    const first = sp.array.items[0];800    return if (first == .string) first.string else null;801}802803// `nix profile list --json` has two shapes across nix versions: newer keys each804// element by name (object), older lists them positionally (array). Handle both.805fn renderProfileJson(gpa: std.mem.Allocator, json: []const u8) void {806    const parsed = std.json.parseFromSlice(std.json.Value, gpa, json, .{}) catch return;807    defer parsed.deinit();808    if (parsed.value != .object) return;809    const elements = parsed.value.object.get("elements") orelse return;810    switch (elements) {811        .object => |obj| {812            var it = obj.iterator();813            while (it.next()) |entry| {814                const ver = if (firstStorePath(entry.value_ptr.*)) |p| pkgFromStorePath(p).version else "";815                output.listPkg(entry.key_ptr.*, ver);816            }817        },818        .array => |arr| {819            for (arr.items) |el| {820                const path = firstStorePath(el) orelse continue;821                const row = pkgFromStorePath(path);822                output.listPkg(row.name, row.version);823            }824        },825        else => {},826    }827}828829pub fn tryCmd(ctx: Ctx) !void {830    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;831    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };832    try tryPkg(ctx, shell_pkg);833}834835// --- Service commands ---836837const service_help = [_][2][]const u8{838    .{ "list", "list running services" },839    .{ "logs <svc>", "show service logs" },840    .{ "status <svc>", "service status" },841    .{ "start <svc>", "start a service" },842    .{ "stop <svc>", "stop a service" },843    .{ "restart <svc>", "restart a service" },844    .{ "enable <svc>", "enable at boot" },845    .{ "disable <svc>", "disable at boot" },846};847848pub fn service(ctx: Ctx) !void {849    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");850    if (std.mem.eql(u8, ctx.sub, "list")) {851        output.serviceListHeader(ctx.machine.name);852        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine, ctx.user) catch &.{};853        defer ctx.gpa.free(svcs);854        for (svcs) |s| output.serviceRow(s);855        return;856    }857    if (std.mem.eql(u8, ctx.sub, "logs")) {858        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;859        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");860        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);861        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow, ctx.user);862        return;863    }864    if (std.mem.eql(u8, ctx.sub, "status")) {865        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;866        output.serviceVerb("status", name, ctx.machine.name);867        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name, ctx.user);868        return;869    }870    // start/stop/restart/enable/disable871    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;872    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {873        if (!output.confirm("")) return;874    }875    output.serviceVerb(ctx.sub, name, ctx.machine.name);876    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name, ctx.user);877    output.serviceDone();878}879880// --- Flake commands ---881882const flake_help = [_][2][]const u8{883    .{ "init", "create a new flake.nix" },884    .{ "update", "update flake inputs" },885    .{ "update <in>", "update a specific input" },886    .{ "check", "validate the flake" },887    .{ "show", "inspect flake outputs" },888    .{ "lock", "regenerate flake.lock" },889    .{ "clone <url>", "clone a flake repository" },890};891892pub fn flake(ctx: Ctx) !void {893    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("flake", &flake_help, null);894    if (std.mem.eql(u8, ctx.sub, "update")) {895        output.flakeUpdateStart();896        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;897        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);898        output.flakeLockWritten();899        return;900    }901    if (std.mem.eql(u8, ctx.sub, "check")) {902        output.flakeCheckStart();903        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);904        if (code == 0) output.flakeValid() else output.checkFailed("");905        return;906    }907    if (std.mem.eql(u8, ctx.sub, "show")) {908        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;909        if (json_out) |j| {910            defer ctx.gpa.free(j);911            output.flakeShowHeader("flake outputs");912            // Parse and display the flake outputs913            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;914            defer parsed.deinit();915            if (parsed.value == .object) {916                var it = parsed.value.object.iterator();917                while (it.next()) |entry| {918                    if (entry.value_ptr.* == .object) {919                        var inner = entry.value_ptr.object.iterator();920                        while (inner.next()) |e2| {921                            const desc = if (e2.value_ptr.* == .object)922                                if (e2.value_ptr.object.get("description")) |d|923                                    if (d == .string) d.string else ""924                                else ""925                            else "";926                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);927                        }928                    }929                }930            }931        }932        return;933    }934    if (std.mem.eql(u8, ctx.sub, "init")) {935        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);936        return;937    }938    if (std.mem.eql(u8, ctx.sub, "lock")) {939        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);940        return;941    }942    if (std.mem.eql(u8, ctx.sub, "clone")) {943        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;944        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);945        return;946    }947}948949// --- Store commands ---950951const store_help = [_][2][]const u8{952    .{ "info", "store size and counts" },953    .{ "path <attr>", "store path of a package" },954    .{ "gc", "collect garbage" },955    .{ "verify", "verify store integrity" },956    .{ "repair", "repair corrupted paths" },957};958959pub fn store(ctx: Ctx) !void {960    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("store", &store_help, null);961    if (std.mem.eql(u8, ctx.sub, "gc")) {962        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);963        return;964    }965    if (std.mem.eql(u8, ctx.sub, "verify")) {966        output.storeVerifyStart();967        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);968        return;969    }970    if (std.mem.eql(u8, ctx.sub, "repair")) {971        if (ctx.cfg.confirm and !output.confirm("")) return;972        output.storeRepairStart();973        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);974        return;975    }976    if (std.mem.eql(u8, ctx.sub, "info")) {977        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);978        output.storeInfo(si);979        return;980    }981    if (std.mem.eql(u8, ctx.sub, "path")) {982        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;983        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);984        defer ctx.gpa.free(path);985        output.storePath(path);986        return;987    }988    // default: info989    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);990    output.storeInfo(si);991}992993// --- Channel commands ---994995const channel_help = [_][2][]const u8{996    .{ "list", "list channels" },997    .{ "add <url> [name]", "add a channel" },998    .{ "remove <name>", "remove a channel" },999    .{ "update", "update all channels" },1000};10011002pub fn channel(ctx: Ctx) !void {1003    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("channel", &channel_help, null);1004    // On a flake-managed system, nix-channel operations generally don't apply.1005    if (ctx.cfg.flake) output.flakeChannelNote();1006    if (std.mem.eql(u8, ctx.sub, "list")) {1007        output.channelListHeader(ctx.machine.name);1008        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);1009        defer ctx.gpa.free(chans);1010        for (chans) |ch| output.channelRow(ch);1011        return;1012    }1013    if (std.mem.eql(u8, ctx.sub, "add")) {1014        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1015        const name = if (ctx.args.len > 1) ctx.args[1] else "";1016        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);1017        output.channelDone();1018        return;1019    }1020    if (std.mem.eql(u8, ctx.sub, "remove")) {1021        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1022        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);1023        output.channelDone();1024        return;1025    }1026    if (std.mem.eql(u8, ctx.sub, "update")) {1027        return channelUpdateCmd(ctx);1028    }1029}10301031// --- Profile commands ---10321033pub fn profile(ctx: Ctx) !void {1034    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {1035        output.profileListHeader();1036        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;1037        if (out) |o| {1038            defer ctx.gpa.free(o);1039            var lines = std.mem.splitScalar(u8, o, '\n');1040            while (lines.next()) |line| {1041                const t = std.mem.trim(u8, line, " \t\r");1042                if (t.len == 0) continue;1043                output.profileRow(t, "", "");1044            }1045        }1046        return;1047    }1048    if (std.mem.eql(u8, ctx.sub, "install")) {1049        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1050        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);1051        output.done();1052        return;1053    }1054    if (std.mem.eql(u8, ctx.sub, "remove")) {1055        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1056        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);1057        output.done();1058        return;1059    }1060    if (std.mem.eql(u8, ctx.sub, "upgrade")) {1061        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);1062        output.done();1063        return;1064    }1065}10661067// --- Pkg commands ---10681069const pkg_help = [_][2][]const u8{1070    .{ "why <pkg>", "what pulled it in" },1071    .{ "deps <pkg>", "direct dependencies" },1072    .{ "size <pkg>", "closure size" },1073    .{ "path <pkg>", "store path" },1074    .{ "closure <pkg>", "full closure" },1075};10761077pub fn pkg(ctx: Ctx) !void {1078    if (ctx.sub.len == 0 or std.mem.eql(u8, ctx.sub, "help")) return output.subcommandHelp("pkg", &pkg_help, null);1079    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1080    if (std.mem.eql(u8, ctx.sub, "why")) {1081        _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);1082        return;1083    }1084    if (std.mem.eql(u8, ctx.sub, "deps")) {1085        _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);1086        return;1087    }1088    if (std.mem.eql(u8, ctx.sub, "size")) {1089        const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;1090        if (s) |sz| {1091            defer ctx.gpa.free(sz);1092            output.pkgResult("size", sz);1093        }1094        return;1095    }1096    if (std.mem.eql(u8, ctx.sub, "path")) {1097        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);1098        defer ctx.gpa.free(p);1099        output.pkgResult("path", p);1100        return;1101    }1102    if (std.mem.eql(u8, ctx.sub, "closure")) {1103        _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);1104        return;1105    }1106}11071108// --- Pin / Unpin ---11091110pub fn pin(ctx: Ctx) !void {1111    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1112    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;1113    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;1114    output.pinDone(input, commit);1115}11161117pub fn unpin(ctx: Ctx) !void {1118    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1119    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);1120    output.unpinDone(input);1121}11221123// --- Hash / Fetch ---11241125pub fn hash(ctx: Ctx) !void {1126    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1127    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);1128    defer ctx.gpa.free(h);1129    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));1130}11311132pub fn fetch(ctx: Ctx) !void {1133    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;1134    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);1135    defer ctx.gpa.free(h);1136    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);1137}11381139// --- Build / Run ---11401141pub fn build(ctx: Ctx) !void {1142    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;1143    output.buildStart(attr orelse "default");1144    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);1145    if (code != 0) return error.BuildFailed;1146    output.buildDone();1147}11481149pub fn runCmd(ctx: Ctx) !void {1150    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;1151    output.runStart(pkg_arg);1152    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);1153}11541155// --- Hello ---11561157pub fn hello(ctx: Ctx) !void {1158    output.hello(ctx.cfg.machines);1159}11601161// Runs when ~/.nina.conf is absent on first invocation (interactive TTY only).1162// Prompts for machine name, config path, and local flag, then writes the file.1163pub fn firstRunWizard(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1164    output.firstRunBanner();1165    output.firstRunNoConfig();11661167    var name_buf: [256]u8 = undefined;1168    var path_buf: [256]u8 = undefined;1169    var local_buf: [256]u8 = undefined;11701171    const machine_name = output.firstRunPrompt("machine name", "my-machine", &name_buf);11721173    // Flake-based systems don't have a traditional /etc/nixos/configuration.nix —1174    // their config lives wherever flake.nix is. Ask, then prompt for the right1175    // path and record `flake = true` so channel commands can warn appropriately.1176    const use_flakes = output.firstRunManageType();1177    const config_path = if (use_flakes)1178        output.firstRunPrompt("flake directory", "~/nixos-config", &path_buf)1179    else1180        output.firstRunPrompt("config path", "/etc/nixos", &path_buf);1181    const local_str = output.firstRunPrompt("local", "true", &local_buf);11821183    const conf_path = try config.configPath(gpa, environ);1184    defer gpa.free(conf_path);1185    if (std.fs.path.dirname(conf_path)) |dir| exec.ensureDir(gpa, io, dir);11861187    // `flake` is a top-level config field, so it must precede the [machine] block.1188    const flake_line = if (use_flakes) "flake = true\n" else "";1189    var content_buf: [1024]u8 = undefined;1190    const content = try std.fmt.bufPrint(1191        &content_buf,1192        "{s}[machine]\nname = {s}\nconfig = {s}\nlocal = {s}\n",1193        .{ flake_line, machine_name, config_path, local_str },1194    );11951196    const file = std.Io.Dir.createFile(.cwd(), io, conf_path, .{}) catch {1197        errors.error_info.setMessage("could not write {s}", .{conf_path});1198        return error.Internal;1199    };1200    defer file.close(io);1201    file.writePositionalAll(io, content, 0) catch {1202        errors.error_info.setMessage("could not write {s}", .{conf_path});1203        return error.Internal;1204    };12051206    output.firstRunWritten(conf_path);1207}12081209pub fn setup(gpa: std.mem.Allocator, io: std.Io, environ: *const std.process.Environ.Map) !void {1210    // Create the config first if it doesn't exist. This makes `nina setup`1211    // a complete onboarding command — not just a nix-features check. Any legacy1212    // ~/.nina.conf is migrated to the XDG path before we decide to run the wizard.1213    config.migrateLegacyConfig(gpa, io, environ);1214    if (config.configPath(gpa, environ)) |conf_path| {1215        defer gpa.free(conf_path);1216        if (std.Io.Dir.openFile(.cwd(), io, conf_path, .{})) |f| {1217            f.close(io);1218        } else |_| {1219            try firstRunWizard(gpa, io, environ);1220            errors.error_info.reset();1221        }1222    } else |_| {}12231224    output.setupCheck();1225    const status = exec.checkNixFeatures(gpa, io, environ);1226    output.setupFeatures(status.nix_command, status.flakes);12271228    if (status.allEnabled()) {1229        output.setupAllSet();1230        api.ensureRegistryPinned(gpa, io, environ);1231        return;1232    }12331234    // On NixOS the features belong in configuration.nix (the declarative,1235    // permanent home), not ~/.config/nix/nix.conf. Offer to add the one line;1236    // the user runs the rebuild. We don't pin the registry here because the1237    // features aren't live until that rebuild lands.1238    if (exec.isNixOS(io)) {1239        const conf_path = "/etc/nixos/configuration.nix";1240        if (exec.nixosConfigEnablesFeatures(gpa, io, conf_path)) {1241            output.setupNixosNeedsRebuild(conf_path);1242            return;1243        }1244        output.setupNixosOffer(exec.NIXOS_FEATURES_LINE, conf_path);1245        if (output.confirmDefaultNo("add it now?")) {1246            if (exec.appendFeaturesToNixosConfig(gpa, io, environ, conf_path)) |_| {1247                output.setupNixosWrote(conf_path);1248            } else |_| {1249                output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1250            }1251        } else {1252            output.setupNixosManual(exec.NIXOS_FEATURES_LINE, conf_path);1253        }1254        return;1255    }12561257    // Non-NixOS: a user-level nix.conf takes effect immediately, no sudo needed.1258    output.setupEnabling();1259    const path = try exec.enableNixFeatures(gpa, io, environ);1260    defer gpa.free(path);12611262    output.setupDone(path);1263    api.ensureRegistryPinned(gpa, io, environ);1264}12651266// --- Log helper ---12671268fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {1269    var ts_buf: [32]u8 = undefined;1270    const ts = nowIso(ctx.io, &ts_buf);1271    var buf: [256]u8 = undefined;1272    const entry = std.fmt.bufPrint(&buf, "{{\"ts\":\"{s}\",\"machine\":\"{s}\",\"command\":\"{s}\",\"outcome\":\"success\",\"gen_before\":null,\"gen_after\":{d},\"duration_ms\":0}}\n", .{1273        ts, ctx.machine.name, action, gen,1274    }) catch return;1275    exec.appendNinaLog(ctx.io, ctx.environ, entry);1276}12771278// Wall-clock UTC as ISO-8601. Uses Io.Clock.real (the settable Unix-epoch clock);1279// Io.Clock.awake is monotonic and unsuitable for timestamps. Falls back to epoch 0.1280fn nowIso(io: std.Io, buf: []u8) []const u8 {1281    const fallback = "1970-01-01T00:00:00Z";1282    const ns = std.Io.Clock.real.now(io).toNanoseconds();1283    if (ns <= 0) return fallback;1284    const secs: u64 = @intCast(@divFloor(ns, 1_000_000_000));1285    const es = std.time.epoch.EpochSeconds{ .secs = secs };1286    const ed = es.getEpochDay();1287    const yd = ed.calculateYearDay();1288    const md = yd.calculateMonthDay();1289    const ds = es.getDaySeconds();1290    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", .{1291        yd.year, md.month.numeric(), @as(u32, md.day_index) + 1,1292        ds.getHoursIntoDay(), ds.getMinutesIntoHour(), ds.getSecondsIntoMinute(),1293    }) catch return fallback;1294}