commands.zig

24.4 KB · raw

1// commands.zig — all command handlers2// Orchestrates exec/api/output. Zero direct stdout writes.3const std = @import("std");4const types = @import("types.zig");5const errors = @import("errors.zig");6const config = @import("config.zig");7const output = @import("output.zig");8const exec = @import("exec.zig");9const api = @import("api.zig");10const search_tui = @import("search.zig");1112pub const Ctx = struct {13    gpa: std.mem.Allocator,14    io: std.Io,15    environ: *const std.process.Environ.Map,16    machine: types.Machine,17    cfg: types.NinaConfig,18    args: []const []const u8,   // positional args after subcommand19    sub: []const u8,            // subcommand (e.g. "list" in "service list")20    dry: bool,21    check: bool,22    no_apply: bool,23    all: bool,24    last: u32,25    json: bool,26};2728pub fn apply(ctx: Ctx) !void {29    if (ctx.dry) {30        output.applyDry(ctx.machine.name);31        const code = try exec.nixosRebuildDryActivate(ctx.io, &ctx.machine, ctx.gpa);32        if (code != 0) return error.BuildFailed;33        output.applyDryDone();34        return;35    }36    if (ctx.check) {37        return check(ctx);38    }3940    output.applyStart(ctx.machine.name);41    const start = std.Io.Clock.awake.now(ctx.io);4243    const code = exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa) catch |e| {44        output.applyFailed("");45        return e;46    };4748    if (code != 0) {49        output.applyFailed("");50        return error.BuildFailed;51    }5253    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());54    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));55    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;56    output.applyDone(gen, elapsed);57    logAction(ctx, "apply", gen);58}5960pub fn check(ctx: Ctx) !void {61    output.checkStart(ctx.machine.name);62    const code = try exec.nixosRebuildBuild(ctx.io, &ctx.machine, ctx.gpa);63    if (code != 0) {64        output.checkFailed("");65        return error.BuildFailed;66    }67    output.checkOk();68}6970pub fn back(ctx: Ctx) !void {71    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);72    defer ctx.gpa.free(gens);7374    var current: u32 = 0;75    for (gens) |g| if (g.current) { current = g.number; };76    const prev = if (current > 1) current - 1 else current;7778    output.backStart(ctx.machine.name, current, prev);79    if (ctx.cfg.confirm and !output.confirm("")) return;8081    const code = try exec.rollback(ctx.io, &ctx.machine, ctx.gpa);82    if (code != 0) return error.BuildFailed;83    output.generationDone(prev);84}8586pub fn go(ctx: Ctx) !void {87    if (ctx.args.len == 0) return error.Internal;88    const target = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;89    const current = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);9091    output.goStart(ctx.machine.name, current, target);92    if (ctx.cfg.confirm and !output.confirm("")) return;9394    const code = try exec.switchGeneration(ctx.io, &ctx.machine, ctx.gpa, target);95    if (code != 0) return error.ProcessFailed;96    output.generationDone(target);97}9899pub fn history(ctx: Ctx) !void {100    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);101    defer ctx.gpa.free(gens);102    output.historyHeader(ctx.machine.name);103    for (gens) |g| output.historyRow(g);104}105106pub fn genCmd(ctx: Ctx) !void {107    if (std.mem.eql(u8, ctx.sub, "list")) return history(ctx);108    if (std.mem.eql(u8, ctx.sub, "current")) {109        const n = try exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine);110        output.genCurrent(n);111        return;112    }113    if (std.mem.eql(u8, ctx.sub, "delete")) {114        if (ctx.args.len == 0) return error.Internal;115        if (std.mem.eql(u8, ctx.args[0], "old")) {116            if (ctx.cfg.confirm and !output.confirm("")) return;117            _ = try exec.deleteOldGenerations(ctx.io, &ctx.machine, ctx.gpa);118        } else {119            const n = std.fmt.parseInt(u32, ctx.args[0], 10) catch return error.Internal;120            if (ctx.cfg.confirm and !output.confirm("")) return;121            _ = try exec.deleteGeneration(ctx.io, &ctx.machine, ctx.gpa, n);122        }123        output.done();124        return;125    }126    return error.Internal;127}128129pub fn clean(ctx: Ctx) !void {130    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);131    defer ctx.gpa.free(gens);132    output.cleanStart(ctx.machine.name, ctx.cfg.generations, @intCast(gens.len));133    if (ctx.cfg.confirm and !output.confirm("removing — cannot be undone")) return;134    const all = ctx.all or std.mem.eql(u8, ctx.sub, "all");135    _ = try exec.collectGarbage(ctx.io, &ctx.machine, ctx.gpa, all, ctx.cfg.generations);136    output.cleanDone("?");137}138139pub fn statusCmd(ctx: Ctx) !void {140    output.statusHeader();141    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;142    output.statusRow(ctx.machine.name, gen, "", "", true);143}144145pub fn diff(ctx: Ctx) !void {146    const gens = try exec.getGenerations(ctx.gpa, ctx.io, &ctx.machine);147    defer ctx.gpa.free(gens);148    var current: u32 = 0;149    var prev: u32 = 0;150    for (gens) |g| {151        if (g.current) current = g.number;152        if (!g.current and g.number > prev and g.number < current) prev = g.number;153    }154    if (ctx.args.len >= 2) {155        const a = std.fmt.parseInt(u32, ctx.args[0], 10) catch current - 1;156        const b = std.fmt.parseInt(u32, ctx.args[1], 10) catch current;157        output.diffHeader(a, b, ctx.machine.name);158        _ = try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, a, b);159    } else {160        output.diffHeader(if (prev > 0) prev else current - 1, current, ctx.machine.name);161        _ = try exec.diffClosures(ctx.io, &ctx.machine, ctx.gpa, if (prev > 0) prev else current - 1, current);162    }163}164165pub fn doctor(ctx: Ctx) !void {166    output.doctorHeader(ctx.machine.name);167    const checks = try exec.runDoctorChecks(ctx.gpa, ctx.io, &ctx.machine);168    defer ctx.gpa.free(checks);169    var warnings: u32 = 0;170    var failures: u32 = 0;171    for (checks) |ch| {172        output.doctorRow(ch);173        if (ch.status == .warn) warnings += 1;174        if (ch.status == .fail) failures += 1;175    }176    output.doctorSummary(warnings, failures);177}178179pub fn update(ctx: Ctx) !void {180    output.updateStart(ctx.machine.name);181    _ = try exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa);182    output.updateDone();183}184185pub fn upgrade(ctx: Ctx) !void {186    output.upgradeStart(ctx.machine.name);187    output.printSubstep("updating channels", .{});188    _ = exec.channelUpdate(ctx.io, &ctx.machine, ctx.gpa) catch {};189    output.printSubstep("rebuilding", .{});190    const start = std.Io.Clock.awake.now(ctx.io);191    const code = try exec.nixosRebuildSwitch(ctx.io, &ctx.machine, ctx.gpa);192    if (code != 0) {193        output.applyFailed("");194        return error.BuildFailed;195    }196    const elapsed_ns = @max(0, start.untilNow(ctx.io, .awake).toNanoseconds());197    const elapsed: u64 = @intCast(@divFloor(elapsed_ns, 1_000_000));198    const gen = exec.getCurrentGeneration(ctx.gpa, ctx.io, &ctx.machine) catch 0;199    output.applyDone(gen, elapsed);200}201202pub fn log(ctx: Ctx) !void {203    output.logHeader(ctx.machine.name);204    const content = exec.readNinaLog(ctx.gpa, ctx.io, ctx.environ, ctx.last) catch {205        // No log yet — that's fine206        return;207    };208    defer ctx.gpa.free(content);209    var lines = std.mem.splitScalar(u8, content, '\n');210    while (lines.next()) |line| {211        if (line.len == 0) continue;212        var parts = std.mem.tokenizeScalar(u8, line, '\t');213        const date = parts.next() orelse continue;214        const time = parts.next() orelse "";215        const action = parts.next() orelse "";216        const detail = parts.next() orelse "";217        output.logRow(date, time, action, detail);218    }219}220221pub fn edit(ctx: Ctx) !void {222    const hardware = ctx.args.len > 0 and std.mem.eql(u8, ctx.args[0], "hardware");223    const filename = if (hardware) "hardware-configuration.nix" else "configuration.nix";224    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/{s}", .{ ctx.machine.config_path, filename });225    defer ctx.gpa.free(path);226    output.editOpen(path, ctx.cfg.editor);227    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, path, null);228}229230pub fn fmt(ctx: Ctx) !void {231    const path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});232    defer ctx.gpa.free(path);233    if (ctx.check) {234        const code = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, true);235        if (code != 0) output.fmtNeedsFormat() else output.fmtDone();236        return;237    }238    output.fmtStart(path);239    _ = try exec.nixpkgsFmt(ctx.io, &ctx.machine, ctx.gpa, path, false);240    output.fmtDone();241}242243pub fn repl(ctx: Ctx) !void {244    output.replStart();245    _ = try exec.nixRepl(ctx.io, &ctx.machine, ctx.gpa);246}247248pub fn develop(ctx: Ctx) !void {249    if (std.mem.eql(u8, ctx.sub, "show")) {250        _ = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, null);251        return;252    }253    const run_cmd: ?[]const u8 = if (ctx.args.len > 0 and std.mem.eql(u8, ctx.sub, "run"))254        ctx.args[0]255    else256        null;257    output.developStart(&.{});258    _ = try exec.nixDevelop(ctx.io, &ctx.machine, ctx.gpa, run_cmd);259    output.developDone();260}261262pub fn info(ctx: Ctx) !void {263    output.infoHeader(ctx.machine.name);264    const nixos_ver = exec.systemInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");265    defer ctx.gpa.free(nixos_ver);266    output.infoRow("nixos", std.mem.trim(u8, nixos_ver, " \t\n\r"));267268    const kernel = exec.kernelInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");269    defer ctx.gpa.free(kernel);270    output.infoRow("kernel", std.mem.trim(u8, kernel, " \t\n\r"));271272    const uptime = exec.uptimeInfo(ctx.gpa, ctx.io, &ctx.machine) catch try ctx.gpa.dupe(u8, "unknown");273    defer ctx.gpa.free(uptime);274    output.infoRow("uptime", std.mem.trim(u8, uptime, " \t\n\r"));275}276277pub fn boot(ctx: Ctx) !void {278    output.bootHeader(ctx.machine.name);279    const entries = exec.bootEntries(ctx.gpa, ctx.io, &ctx.machine) catch &.{};280    defer ctx.gpa.free(entries);281    for (entries, 0..) |entry, i| output.bootEntry(entry, i);282}283284pub fn searchCmd(ctx: Ctx) !void {285    const query = if (ctx.args.len > 0) ctx.args[0] else "";286    const result = try search_tui.run(ctx.gpa, ctx.io, query, .packages);287    if (result) |r| {288        installFromResult(ctx, r) catch |e| return e;289    }290}291292pub fn optionCmd(ctx: Ctx) !void {293    const query = if (ctx.args.len > 0) ctx.args[0] else "";294    _ = try search_tui.run(ctx.gpa, ctx.io, query, .options);295}296297pub fn install(ctx: Ctx) !void {298    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;299300    // Search for the package to get the attr301    const pkgs = api.searchPackages(ctx.gpa, ctx.io, pkg_name) catch {302        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});303        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});304        return error.PackageNotFound;305    };306    defer ctx.gpa.free(pkgs);307308    if (pkgs.len == 0) {309        errors.error_info.setMessage("'{s}' not found in nixpkgs", .{pkg_name});310        errors.error_info.setSuggestion("nina search {s}", .{pkg_name});311        return error.PackageNotFound;312    }313314    const found = pkgs[0];315    output.installSelectPrompt(found.pname, found.version);316317    var choice_buf: [8]u8 = undefined;318    var choice_len: usize = 0;319    while (choice_len < choice_buf.len) {320        const n = std.posix.read(std.posix.STDIN_FILENO, choice_buf[choice_len .. choice_len + 1]) catch break;321        if (n == 0) break;322        if (choice_buf[choice_len] == '\n') break;323        choice_len += 1;324    }325    const choice = std.mem.trim(u8, choice_buf[0..choice_len], " \t");326327    if (choice.len == 0 or choice[0] == 'i' or choice[0] == 'I') {328        try profileInstallPkg(ctx, found);329    } else if (choice[0] == 's' or choice[0] == 'S') {330        try systemInstallPkg(ctx, found);331    } else if (choice[0] == 't' or choice[0] == 'T') {332        try tryPkg(ctx, found);333    }334}335336fn installFromResult(ctx: Ctx, result: types.SearchResult) !void {337    switch (result.action) {338        .profile => try profileInstallPkg(ctx, result.package),339        .system => try systemInstallPkg(ctx, result.package),340    }341}342343fn profileInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {344    output.installStart(npkg.pname, .profile);345    output.printSubstep("nix profile install nixpkgs#{s}", .{npkg.attr});346    output.printTeach(try std.fmt.allocPrint(ctx.gpa, "nix profile install nixpkgs#{s}", .{npkg.attr}));347    const code = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);348    if (code != 0) return error.ProcessFailed;349    output.installDone(npkg.pname);350}351352fn systemInstallPkg(ctx: Ctx, npkg: types.NixPackage) !void {353    const config_path = try std.fmt.allocPrint(ctx.gpa, "{s}/configuration.nix", .{ctx.machine.config_path});354    defer ctx.gpa.free(config_path);355    const line = api.findSystemPackagesLine(ctx.io, config_path) orelse 1;356    output.installEditorPrompt(npkg.pname, config_path, line, ctx.cfg.editor);357    _ = try exec.openEditor(ctx.io, ctx.gpa, ctx.cfg.editor, config_path, line);358    if (ctx.cfg.confirm) {359        if (output.confirm("apply now? ")) {360            try apply(ctx);361        }362    }363}364365fn tryPkg(ctx: Ctx, npkg: types.NixPackage) !void {366    output.tryStart(npkg.pname);367    output.printSubstep("nix shell nixpkgs#{s}", .{npkg.attr});368    _ = try exec.nixShell(ctx.io, &ctx.machine, ctx.gpa, npkg.attr);369    output.tryDone();370}371372pub fn remove(ctx: Ctx) !void {373    const pkg_name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;374    output.installStart(pkg_name, .profile); // reuse installStart for remove UI375    const code = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, pkg_name);376    if (code != 0) return error.ProcessFailed;377    output.done();378}379380pub fn list(ctx: Ctx) !void {381    output.listHeader();382    const profile_out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;383    if (profile_out) |out| {384        defer ctx.gpa.free(out);385        output.listSection("profile");386        var lines = std.mem.splitScalar(u8, out, '\n');387        while (lines.next()) |line| {388            const t = std.mem.trim(u8, line, " \t\r");389            if (t.len == 0) continue;390            output.listPkg(t, "");391        }392    }393}394395pub fn tryCmd(ctx: Ctx) !void {396    const pkg_name_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;397    const shell_pkg = types.NixPackage{ .attr = pkg_name_arg, .pname = pkg_name_arg, .version = "", .description = "" };398    try tryPkg(ctx, shell_pkg);399}400401// --- Service commands ---402403pub fn service(ctx: Ctx) !void {404    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {405        output.serviceListHeader(ctx.machine.name);406        const svcs = exec.serviceList(ctx.gpa, ctx.io, &ctx.machine) catch &.{};407        defer ctx.gpa.free(svcs);408        for (svcs) |s| output.serviceRow(s);409        return;410    }411    if (std.mem.eql(u8, ctx.sub, "logs")) {412        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;413        const follow = ctx.args.len > 1 and std.mem.eql(u8, ctx.args[1], "-f");414        output.serviceLogsHeader(name, ctx.last, ctx.machine.name);415        _ = try exec.serviceLogs(ctx.io, &ctx.machine, ctx.gpa, name, ctx.last, follow);416        return;417    }418    if (std.mem.eql(u8, ctx.sub, "status")) {419        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;420        output.serviceVerb("status", name, ctx.machine.name);421        _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, "status", name);422        return;423    }424    // start/stop/restart/enable/disable425    const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;426    if (ctx.cfg.confirm and (std.mem.eql(u8, ctx.sub, "stop") or std.mem.eql(u8, ctx.sub, "disable"))) {427        if (!output.confirm("")) return;428    }429    output.serviceVerb(ctx.sub, name, ctx.machine.name);430    _ = try exec.serviceCtl(ctx.io, &ctx.machine, ctx.gpa, ctx.sub, name);431    output.serviceDone();432}433434// --- Flake commands ---435436pub fn flake(ctx: Ctx) !void {437    if (std.mem.eql(u8, ctx.sub, "update")) {438        output.flakeUpdateStart();439        const input: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;440        _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);441        output.flakeLockWritten();442        return;443    }444    if (std.mem.eql(u8, ctx.sub, "check")) {445        output.flakeCheckStart();446        const code = try exec.flakeCheck(ctx.io, &ctx.machine, ctx.gpa);447        if (code == 0) output.flakeValid() else output.checkFailed("");448        return;449    }450    if (std.mem.eql(u8, ctx.sub, "show")) {451        const json_out = exec.flakeShow(ctx.gpa, ctx.io, &ctx.machine) catch null;452        if (json_out) |j| {453            defer ctx.gpa.free(j);454            output.flakeShowHeader(".");455            // Parse and display the flake outputs456            const parsed = std.json.parseFromSlice(std.json.Value, ctx.gpa, j, .{}) catch return;457            defer parsed.deinit();458            if (parsed.value == .object) {459                var it = parsed.value.object.iterator();460                while (it.next()) |entry| {461                    if (entry.value_ptr.* == .object) {462                        var inner = entry.value_ptr.object.iterator();463                        while (inner.next()) |e2| {464                            const desc = if (e2.value_ptr.* == .object)465                                if (e2.value_ptr.object.get("description")) |d|466                                    if (d == .string) d.string else ""467                                else ""468                            else "";469                            output.flakeShowEntry(entry.key_ptr.*, e2.key_ptr.*, desc);470                        }471                    }472                }473            }474        }475        return;476    }477    if (std.mem.eql(u8, ctx.sub, "init")) {478        _ = try exec.flakeInit(ctx.io, &ctx.machine, ctx.gpa);479        return;480    }481    if (std.mem.eql(u8, ctx.sub, "lock")) {482        _ = try exec.flakeLock(ctx.io, &ctx.machine, ctx.gpa);483        return;484    }485    if (std.mem.eql(u8, ctx.sub, "clone")) {486        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;487        _ = try exec.flakeClone(ctx.io, &ctx.machine, ctx.gpa, url);488        return;489    }490}491492// --- Store commands ---493494pub fn store(ctx: Ctx) !void {495    if (std.mem.eql(u8, ctx.sub, "gc")) {496        _ = try exec.storeGc(ctx.io, &ctx.machine, ctx.gpa);497        return;498    }499    if (std.mem.eql(u8, ctx.sub, "verify")) {500        output.storeVerifyStart();501        _ = try exec.storeVerify(ctx.io, &ctx.machine, ctx.gpa);502        return;503    }504    if (std.mem.eql(u8, ctx.sub, "repair")) {505        if (ctx.cfg.confirm and !output.confirm("")) return;506        output.storeRepairStart();507        _ = try exec.storeRepair(ctx.io, &ctx.machine, ctx.gpa);508        return;509    }510    if (std.mem.eql(u8, ctx.sub, "info")) {511        const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);512        output.storeInfo(si);513        return;514    }515    if (std.mem.eql(u8, ctx.sub, "path")) {516        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;517        const path = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, attr);518        defer ctx.gpa.free(path);519        output.storePath(path);520        return;521    }522    // default: info523    const si = try exec.storeInfo(ctx.gpa, ctx.io, &ctx.machine);524    output.storeInfo(si);525}526527// --- Channel commands ---528529pub fn channel(ctx: Ctx) !void {530    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {531        output.channelListHeader(ctx.machine.name);532        const chans = try exec.channelList(ctx.gpa, ctx.io, &ctx.machine);533        defer ctx.gpa.free(chans);534        for (chans) |ch| output.channelRow(ch);535        return;536    }537    if (std.mem.eql(u8, ctx.sub, "add")) {538        const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;539        const name = if (ctx.args.len > 1) ctx.args[1] else "";540        _ = try exec.channelAdd(ctx.io, &ctx.machine, ctx.gpa, url, name);541        output.channelDone();542        return;543    }544    if (std.mem.eql(u8, ctx.sub, "remove")) {545        const name = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;546        _ = try exec.channelRemove(ctx.io, &ctx.machine, ctx.gpa, name);547        output.channelDone();548        return;549    }550    if (std.mem.eql(u8, ctx.sub, "update")) {551        return update(ctx);552    }553}554555// --- Profile commands ---556557pub fn profile(ctx: Ctx) !void {558    if (std.mem.eql(u8, ctx.sub, "list") or ctx.sub.len == 0) {559        output.profileListHeader();560        const out = exec.profileList(ctx.gpa, ctx.io, &ctx.machine) catch null;561        if (out) |o| {562            defer ctx.gpa.free(o);563            var lines = std.mem.splitScalar(u8, o, '\n');564            while (lines.next()) |line| {565                const t = std.mem.trim(u8, line, " \t\r");566                if (t.len == 0) continue;567                output.profileRow(t, "", "");568            }569        }570        return;571    }572    if (std.mem.eql(u8, ctx.sub, "install")) {573        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;574        _ = try exec.profileInstall(ctx.io, &ctx.machine, ctx.gpa, attr);575        output.done();576        return;577    }578    if (std.mem.eql(u8, ctx.sub, "remove")) {579        const attr = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;580        _ = try exec.profileRemove(ctx.io, &ctx.machine, ctx.gpa, attr);581        output.done();582        return;583    }584    if (std.mem.eql(u8, ctx.sub, "upgrade")) {585        _ = try exec.profileUpgrade(ctx.io, &ctx.machine, ctx.gpa);586        output.done();587        return;588    }589}590591// --- Pkg commands ---592593pub fn pkg(ctx: Ctx) !void {594    const name = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;595    if (std.mem.eql(u8, ctx.sub, "why")) {596        _ = try exec.pkgWhy(ctx.io, &ctx.machine, ctx.gpa, name);597        return;598    }599    if (std.mem.eql(u8, ctx.sub, "deps")) {600        _ = try exec.pkgDeps(ctx.io, &ctx.machine, ctx.gpa, name);601        return;602    }603    if (std.mem.eql(u8, ctx.sub, "size")) {604        const s = exec.pkgSize(ctx.gpa, ctx.io, &ctx.machine, name) catch null;605        if (s) |sz| {606            defer ctx.gpa.free(sz);607            output.pkgResult("size", sz);608        }609        return;610    }611    if (std.mem.eql(u8, ctx.sub, "path")) {612        const p = try exec.storePath(ctx.gpa, ctx.io, &ctx.machine, name);613        defer ctx.gpa.free(p);614        output.pkgResult("path", p);615        return;616    }617    if (std.mem.eql(u8, ctx.sub, "closure")) {618        _ = try exec.pkgClosure(ctx.io, &ctx.machine, ctx.gpa, name);619        return;620    }621}622623// --- Pin / Unpin ---624625pub fn pin(ctx: Ctx) !void {626    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;627    const commit = if (ctx.args.len > 1) ctx.args[1] else return error.Internal;628    exec.editFlakeLock(ctx.gpa, input, commit) catch return error.ProcessFailed;629    output.pinDone(input, commit);630}631632pub fn unpin(ctx: Ctx) !void {633    const input = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;634    _ = try exec.flakeUpdate(ctx.io, &ctx.machine, ctx.gpa, input);635    output.unpinDone(input);636}637638// --- Hash / Fetch ---639640pub fn hash(ctx: Ctx) !void {641    const path = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;642    const h = try exec.nixHash(ctx.gpa, ctx.io, &ctx.machine, path);643    defer ctx.gpa.free(h);644    output.hashResult(std.mem.trim(u8, h, " \t\n\r"));645}646647pub fn fetch(ctx: Ctx) !void {648    const url = if (ctx.args.len > 0) ctx.args[0] else return error.Internal;649    const h = try exec.nixFetch(ctx.gpa, ctx.io, &ctx.machine, url);650    defer ctx.gpa.free(h);651    output.fetchResult(std.mem.trim(u8, h, " \t\n\r"), url);652}653654// --- Build / Run ---655656pub fn build(ctx: Ctx) !void {657    const attr: ?[]const u8 = if (ctx.args.len > 0) ctx.args[0] else null;658    output.buildStart(attr orelse "default");659    const code = try exec.nixBuild(ctx.io, &ctx.machine, ctx.gpa, attr);660    if (code != 0) return error.BuildFailed;661    output.buildDone();662}663664pub fn runCmd(ctx: Ctx) !void {665    const pkg_arg = if (ctx.args.len > 0) ctx.args[0] else return error.PackageNotFound;666    output.runStart(pkg_arg);667    _ = try exec.nixRun(ctx.io, &ctx.machine, ctx.gpa, pkg_arg);668}669670// --- Hello ---671672pub fn hello(ctx: Ctx) !void {673    output.hello(ctx.cfg.machines);674}675676// --- Log helper ---677678fn logAction(ctx: Ctx, action: []const u8, gen: u32) void {679    var buf: [128]u8 = undefined;680    const entry = std.fmt.bufPrint(&buf, "{s}\t{s}\t{s}\tgen {d}\n", .{681        "2026", "00:00", action, gen,682    }) catch return;683    exec.appendNinaLog(ctx.io, ctx.environ, entry);684}