output.zig

37.7 KB · raw

1// output.zig — the only file that writes to stdout2// All ANSI codes live here. No raw escape sequences elsewhere.3const std = @import("std");4const types = @import("types.zig");5const nina_version = @import("version.zig");6const Io = std.Io;78// Color constants — all ANSI codes live here only9const PINK = "\x1b[38;2;255;183;197m";10const BOLD = "\x1b[1m";11const GREEN = "\x1b[32m";12const YELLOW = "\x1b[33m";13const RED = "\x1b[31m";14const CYAN = "\x1b[36m";15const DIM = "\x1b[2m";16const RESET = "\x1b[0m";1718// kaomoji constants — all kaomoji defined here, never inlined elsewhere. Rare19// and earned: each marks one genuine moment and never repeats in one output20// block. They are plain text, not ANSI, so they survive pipes and NO_COLOR.21const KAO_FACE = "(˶ᵔ ᵕ ᵔ˶)  "; // hello — her face22const KAO_COZY = "(っ˘ω˘ς)  "; // apply start23const KAO_EXCITED = "╰(*°▽°*)╯  "; // apply success after a failure this session24const KAO_GENTLE = "( ˘ᵕ˘ )  "; // back done25const KAO_CONTENT = "( ´ ∀ ` )  "; // clean freed26const KAO_HAPPY = "( ´ ▽ ` )  "; // doctor all clear / mood all good27const KAO_SLEEPY = "(˘ω˘ )  "; // try / develop exit28const KAO_SAD = "(;ω;)  "; // network or ssh errors only — never user typos2930// Exported for TUI use (search.zig references these to avoid \x1b in that file)31pub const C_PINK = PINK;32pub const C_BOLD = BOLD;33pub const C_GREEN = GREEN;34pub const C_YELLOW = YELLOW;35pub const C_RED = RED;36pub const C_CYAN = CYAN;37pub const C_DIM = DIM;38pub const C_RESET = RESET;39pub const C_CLEAR_EOL = "\x1b[K";40pub const C_CURSOR_UP_FMT = "\x1b[{d}A";4142// Precomputed prefix strings43const HDR_C = PINK ++ ":: " ++ RESET;44const HDR_P = ":: ";45const STEP_C = "   " ++ DIM ++ "-> " ++ RESET;46const STEP_P = "   -> ";47const TEACH_C = "   " ++ DIM ++ "= " ++ RESET;48const TEACH_P = "   = ";49const ERR_C = PINK ++ ":: " ++ RED ++ "error:" ++ RESET ++ " ";50const ERR_P = ":: error: ";51const WARN_C = PINK ++ ":: " ++ YELLOW ++ "warning:" ++ RESET ++ " ";52const WARN_P = ":: warning: ";5354var _fw: Io.File.Writer = undefined;55var _w: *Io.Writer = undefined;56var color_enabled: bool = true;57var teach_enabled: bool = false;5859pub fn init(writer: *Io.Writer, io: std.Io, environ: *const std.process.Environ.Map, color_config: bool) void {60    _w = writer;61    color_enabled = color_config and62        (std.Io.File.stdout().isTty(io) catch false) and63        !environ.contains("NO_COLOR");64}6566pub fn setTeach(enabled: bool) void {67    teach_enabled = enabled;68}6970pub fn flush() void {71    _w.flush() catch {};72}7374// Whether ANSI color is active (tty + config + no NO_COLOR). Callers spawning75// child processes that colorize their own output use this to gate the child.76pub fn colorEnabled() bool {77    return color_enabled;78}7980fn c(code: []const u8) []const u8 {81    return if (color_enabled) code else "";82}8384fn hdr() []const u8 {85    return if (color_enabled) HDR_C else HDR_P;86}8788fn step() []const u8 {89    return if (color_enabled) STEP_C else STEP_P;90}9192fn teach_pfx() []const u8 {93    return if (color_enabled) TEACH_C else TEACH_P;94}9596// Raw write — used by TUI97pub fn raw(bytes: []const u8) void {98    _w.writeAll(bytes) catch {};99}100101// Formatted print — used by TUI for in-place rendering102pub fn p(comptime fmt: []const u8, args: anytype) void {103    _w.print(fmt, args) catch {};104}105106pub fn cursorUp(n: usize) void {107    if (n > 0) p("\x1b[{d}A", .{n});108}109110pub fn clearLine() void {111    p("\r\x1b[K", .{});112}113114// --- Error and warning output ---115116pub fn printError(message: []const u8, detail: ?[]const u8, suggestion: ?[]const u8) void {117    p("{s}{s}\n", .{ if (color_enabled) ERR_C else ERR_P, message });118    if (detail) |d| p("   {s}{s}{s}\n", .{ c(DIM), d, c(RESET) });119    // Actionable suggestion in cyan — the next step should catch the eye.120    if (suggestion) |s| p("   {s}-> {s}{s}\n", .{ c(CYAN), s, c(RESET) });121}122123// Like printError, but for genuine system failures (network/ssh/search). The sad124// kaomoji signals "this is on the machine, not on you" — never used for typos or125// not-found errors, which go through printError.126pub fn printSystemError(message: []const u8, detail: ?[]const u8, suggestion: ?[]const u8) void {127    p("{s}{s}{s}\n", .{ KAO_SAD, if (color_enabled) ERR_C else ERR_P, message });128    if (detail) |d| p("   {s}{s}{s}\n", .{ c(DIM), d, c(RESET) });129    if (suggestion) |s| p("   {s}-> {s}{s}\n", .{ c(CYAN), s, c(RESET) });130}131132pub fn printWarning(message: []const u8) void {133    p("{s}{s}\n", .{ if (color_enabled) WARN_C else WARN_P, message });134}135136// One-time dim note when ~/.nina.conf is migrated to the XDG config path.137pub fn configMigrated(path: []const u8) void {138    p("{s}{s}config migrated to {s}{s}\n", .{ step(), c(DIM), path, c(RESET) });139}140141pub fn printTeach(cmd: []const u8) void {142    if (teach_enabled) p("{s}{s}{s}\n", .{ teach_pfx(), cmd, c(RESET) });143}144145pub fn printSubstep(comptime fmt: []const u8, args: anytype) void {146    p("{s}", .{step()});147    p(fmt, args);148    p("\n", .{});149}150151// --- Confirmation prompt (returns true = yes) ---152153pub fn confirm(prompt: []const u8) bool {154    p("   {s}continue? [Y/n]  ", .{prompt});155    flush();156    var buf: [64]u8 = undefined;157    var i: usize = 0;158    while (i < buf.len) {159        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;160        if (n == 0) break;161        if (buf[i] == '\n') break;162        i += 1;163    }164    const input = std.mem.trim(u8, buf[0..i], " \t");165    if (input.len == 0) return true;166    return input[0] != 'n' and input[0] != 'N';167}168169// Like confirm, but defaults to NO on an empty answer — for prompts that touch170// system files, where a stray Enter should never trigger the action.171pub fn confirmDefaultNo(question: []const u8) bool {172    p("   {s} [y/N]  ", .{question});173    flush();174    var buf: [64]u8 = undefined;175    var i: usize = 0;176    while (i < buf.len) {177        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;178        if (n == 0) break;179        if (buf[i] == '\n') break;180        i += 1;181    }182    const input = std.mem.trim(u8, buf[0..i], " \t");183    if (input.len == 0) return false;184    return input[0] == 'y' or input[0] == 'Y';185}186187// --- Apply / rebuild ---188189pub fn applyStart(machine: []const u8) void {190    p("{s}{s}rebuilding {s}...\n", .{ KAO_COZY, hdr(), machine });191}192193// after_failure: true only when the previous apply this session failed and this194// one succeeded — the one moment that earns the excited kaomoji. Routine195// successes show no kaomoji.196pub fn applyDone(gen: u32, elapsed_ms: u64, after_failure: bool) void {197    const face = if (after_failure) KAO_EXCITED else "";198    const secs = @as(f64, @floatFromInt(elapsed_ms)) / 1000.0;199    if (elapsed_ms >= 1000) {200        p("{s}{s}generation {s}{d}{s}  {s}[{d:.1}s]{s}\n", .{ face, hdr(), c(BOLD), gen, c(RESET), c(DIM), secs, c(RESET) });201    } else {202        p("{s}{s}generation {s}{d}{s}\n", .{ face, hdr(), c(BOLD), gen, c(RESET) });203    }204}205206pub fn applyFailed(translated: []const u8) void {207    p("{s}build failed\n", .{if (color_enabled) ERR_C else ERR_P});208    if (translated.len > 0) p("   {s}{s}{s}\n", .{ c(DIM), translated, c(RESET) });209    p("   {s}-> nina doctor{s}\n", .{ c(DIM), c(RESET) });210}211212pub fn applyDry(machine: []const u8) void {213    p("{s}dry run  {s}\n", .{ hdr(), machine });214}215216pub fn applyDryDone() void {217    p("{s}no changes applied\n", .{hdr()});218}219220// --- Check ---221222pub fn checkStart(machine: []const u8) void {223    p("{s}checking {s}...\n", .{ hdr(), machine });224}225226pub fn checkOk() void {227    p("{s}{s}ok{s}\n", .{ hdr(), c(GREEN), c(RESET) });228}229230pub fn checkFailed(msg: []const u8) void {231    p("{s}config invalid\n", .{if (color_enabled) ERR_C else ERR_P});232    if (msg.len > 0) p("   {s}{s}{s}\n", .{ c(DIM), msg, c(RESET) });233}234235// --- Back / go ---236237pub fn backStart(machine: []const u8, from: u32, to: u32) void {238    p("{s}rolling back  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, from, to });239}240241pub fn goStart(machine: []const u8, current: u32, target: u32) void {242    p("{s}switching  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, current, target });243}244245pub fn generationDone(n: u32) void {246    p("{s}done  gen {s}{d}{s}\n", .{ hdr(), c(BOLD), n, c(RESET) });247}248249// `back` has nothing older to roll back to. This is a clean stop, not a build250// failure — the rollback would otherwise surface nixos-rebuild's confusing251// 'no profile version older than the current' as a fake build error.252pub fn alreadyOldest() void {253    p("{s}already at the oldest generation\n", .{if (color_enabled) ERR_C else ERR_P});254}255256// Like generationDone but for `back` specifically — a successful rollback earns257// the gentle kaomoji. `go` keeps the plain generationDone line.258pub fn backDone(n: u32) void {259    p("{s}{s}done  gen {s}{d}{s}\n", .{ KAO_GENTLE, hdr(), c(BOLD), n, c(RESET) });260}261262// --- History ---263264pub fn historyHeader(machine: []const u8) void {265    p("{s}generations  {s}\n\n", .{ hdr(), machine });266}267268pub fn historyRow(gen: types.GenerationInfo) void {269    if (gen.current) {270        p("   {s}{d}{s}   {s}   {s}   {s}current{s}\n", .{ c(BOLD), gen.number, c(RESET), gen.date, gen.time, c(BOLD), c(RESET) });271    } else {272        p("   {s}{d}   {s}   {s}{s}\n", .{ c(DIM), gen.number, gen.date, gen.time, c(RESET) });273    }274}275276// --- Clean ---277278pub fn cleanStart(machine: []const u8, keep: u32, total: u32) void {279    p("{s}cleaning  {s}  keeping {d} of {d}\n", .{ hdr(), machine, keep, total });280}281282// Fewer generations than the keep limit — there's nothing to collect. Avoids the283// nonsensical 'keeping 5 of 1'.284pub fn cleanNothing(machine: []const u8, total: u32) void {285    p("{s}cleaning  {s}\n\n", .{ hdr(), machine });286    p("   only {d} generation{s} — nothing to remove.\n", .{ total, if (total == 1) "" else "s" });287}288289pub fn cleanDone() void {290    p("{s}{s}done\n", .{ KAO_CONTENT, hdr() });291}292293// --- Status ---294295pub fn statusHeader() void {296    p("{s}status\n\n", .{hdr()});297}298299pub fn statusRow(machine: []const u8, gen: u32, time: []const u8, size: []const u8, ok: bool) void {300    if (ok) {301        p("   {s}{s}{s}   gen {s}{d}{s}   {s}{s}   {s}{s}\n", .{ c(DIM), machine, c(RESET), c(BOLD), gen, c(RESET), c(DIM), time, size, c(RESET) });302    } else {303        p("   {s}{s}   {s}unreachable{s}\n", .{ c(RED), machine, "", c(RESET) });304    }305}306307// Dim Home Manager generation line, indented under the machine row. Only shown308// when standalone HM is detected; absent otherwise so the layout is unchanged.309pub fn statusHomeRow(gen: u32, detail: []const u8) void {310    if (detail.len > 0) {311        p("   {s}         hm  gen {d}   {s}{s}\n", .{ c(DIM), gen, detail, c(RESET) });312    } else {313        p("   {s}         hm  gen {d}{s}\n", .{ c(DIM), gen, c(RESET) });314    }315}316317// --- Diff ---318319pub fn diffHeader(a: u32, b: u32, machine: []const u8) void {320    p("{s}gen {d} -> gen {d}  {s}\n\n", .{ hdr(), a, b, machine });321}322323pub fn diffRow(entry: types.DiffEntry) void {324    switch (entry.op) {325        .add => p("   {s}+{s} {s}   {s}\n", .{ c(GREEN), c(RESET), entry.package, entry.new_version orelse "" }),326        .remove => p("   {s}-{s} {s}   {s}\n", .{ c(RED), c(RESET), entry.package, entry.old_version orelse "" }),327        .change => p("   {s}^{s} {s}   {s} -> {s}\n", .{ c(CYAN), c(RESET), entry.package, entry.old_version orelse "", entry.new_version orelse "" }),328    }329}330331// --- Doctor ---332333pub fn doctorHeader(machine: []const u8) void {334    p("{s}diagnosing  {s}\n\n", .{ hdr(), machine });335}336337pub fn doctorRow(check: types.DoctorCheck) void {338    const status_str = switch (check.status) {339        .ok => if (color_enabled) GREEN ++ "ok" ++ RESET else "ok",340        .warn => if (color_enabled) YELLOW ++ "warn" ++ RESET else "warn",341        .fail => if (color_enabled) RED ++ "fail" ++ RESET else "fail",342    };343    const note_str = check.note orelse "";344    p("   {s:<16}  {s}   {s}\n", .{ check.name, status_str, note_str });345}346347pub fn doctorSummary(warnings: u32, failures: u32) void {348    if (failures > 0) {349        p("{s}{d} problems\n", .{ hdr(), failures });350    } else if (warnings > 0) {351        p("{s}{d} warnings\n", .{ hdr(), warnings });352    } else {353        p("{s}{s}{s}all good{s}\n", .{ KAO_HAPPY, hdr(), c(GREEN), c(RESET) });354    }355}356357// --- Update ---358359pub fn updateStart(machine: []const u8) void {360    p("{s}updating channels  {s}\n\n", .{ hdr(), machine });361}362363pub fn updateChannel(name: []const u8, old: ?[]const u8, new: ?[]const u8) void {364    if (old != null and new != null and !std.mem.eql(u8, old.?, new.?)) {365        p("   {s}   {s} -> {s}\n", .{ name, old.?, new.? });366    } else {367        p("   {s}   {s}no change{s}\n", .{ name, c(DIM), c(RESET) });368    }369}370371pub fn updateDone() void {372    p("\n{s}done\n", .{hdr()});373}374375// --- Upgrade ---376377pub fn upgradeStart(machine: []const u8) void {378    p("{s}upgrading  {s}\n", .{ hdr(), machine });379}380381// --- Log ---382383pub fn logHeader(machine: []const u8) void {384    p("{s}history  {s}\n\n", .{ hdr(), machine });385}386387pub fn logRow(date: []const u8, time: []const u8, action: []const u8, detail: []const u8) void {388    p("   {s}{s}  {s}{s}   {s:<16}  {s}\n", .{ c(DIM), date, time, c(RESET), action, detail });389}390391// --- Edit ---392393pub fn editOpen(path: []const u8, editor: []const u8) void {394    p("{s}opening {s}\n", .{ hdr(), path });395    printSubstep("{s}", .{editor});396    p("\n   {s}run nina check to validate before applying{s}\n", .{ c(DIM), c(RESET) });397}398399// --- Fmt ---400401pub fn fmtStart(path: []const u8) void {402    p("{s}formatting  {s}\n", .{ hdr(), path });403}404405pub fn fmtDone() void {406    p("{s}done\n", .{hdr()});407}408409pub fn fmtNeedsFormat() void {410    p("{s}needs formatting  {s}run nina fmt to fix{s}\n", .{ hdr(), c(DIM), c(RESET) });411}412413// --- Repl ---414415pub fn replStart() void {416    p("{s}nix repl  {s}nixpkgs loaded{s}  :q to exit\n", .{ hdr(), c(DIM), c(RESET) });417}418419// --- Develop ---420421pub fn developStart(pkgs: []const []const u8) void {422    p("{s}entering dev shell\n\n   ", .{hdr()});423    for (pkgs, 0..) |pkg, i| {424        if (i > 0) p("  ", .{});425        p("{s}", .{pkg});426    }427    p("\n\n   {s}-> type 'exit' to return{s}\n\n", .{ c(DIM), c(RESET) });428}429430pub fn developDone() void {431    p("{s}{s}back\n", .{ KAO_SLEEPY, hdr() });432}433434// --- Info ---435436pub fn infoHeader(machine: []const u8) void {437    p("{s}{s}\n\n", .{ hdr(), machine });438}439440pub fn infoRow(key: []const u8, val: []const u8) void {441    p("   {s:<12}  {s}\n", .{ key, val });442}443444// --- Boot ---445446pub fn bootHeader(machine: []const u8) void {447    p("{s}boot entries  {s}\n\n", .{ hdr(), machine });448}449450pub fn bootEntry(entry: types.BootEntry, idx: usize) void {451    if (entry.current) {452        p("   {s}> {s}{s}{s}\n", .{ c(BOLD), entry.title, if (entry.date) |d| std.fmt.allocPrint(std.heap.page_allocator, "   {s}", .{d}) catch "   " else "", c(RESET) });453    } else {454        p("   {s}  {s}{s}{s}\n", .{ c(DIM), entry.title, if (entry.date) |d| std.fmt.allocPrint(std.heap.page_allocator, "   {s}", .{d}) catch "   " else "", c(RESET) });455    }456    _ = idx;457}458459// --- Service ---460461pub fn serviceListHeader(machine: []const u8) void {462    p("{s}services  {s}\n\n", .{ hdr(), machine });463}464465pub fn serviceRow(svc: types.ServiceInfo) void {466    const state_str = switch (svc.state) {467        .active => if (color_enabled) GREEN ++ "active" ++ RESET else "active",468        .failed => if (color_enabled) RED ++ "failed" ++ RESET else "failed",469        .inactive => "inactive",470        .unknown => "unknown",471    };472    const uptime = svc.uptime orelse "";473    p("   {s:<24}  {s:<14}  {s}\n", .{ svc.name, state_str, uptime });474}475476pub fn serviceVerb(verb: []const u8, name: []const u8, machine: []const u8) void {477    p("{s}{s} {s}  {s}\n", .{ hdr(), verb, name, machine });478}479480pub fn serviceDone() void {481    p("{s}done\n", .{hdr()});482}483484pub fn serviceLogsHeader(name: []const u8, n: u32, machine: []const u8) void {485    p("{s}{s}  last {d} lines  {s}\n\n", .{ hdr(), name, n, machine });486}487488// --- Store ---489490pub fn storeInfo(info: types.StoreInfo) void {491    p("{s}store\n\n", .{hdr()});492    p("   {s:<16}  {s}\n", .{ "total", info.total_size });493    p("   {s:<16}  {d} paths\n", .{ "live", info.live_paths });494    p("   {s:<16}  {s}{d} paths{s}   {s}run nina clean{s}\n", .{ "reclaimable", c(DIM), info.reclaimable_paths, c(RESET), c(CYAN), c(RESET) });495}496497// --- Channel ---498499pub fn channelListHeader(machine: []const u8) void {500    p("{s}channels  {s}\n\n", .{ hdr(), machine });501}502503pub fn channelRow(ch: types.ChannelInfo) void {504    p("   {s:<16}  {s}\n", .{ ch.name, ch.url });505}506507// --- Flake ---508509pub fn flakeUpdateStart() void {510    p("{s}updating inputs\n\n", .{hdr()});511}512513pub fn flakeInput(input: types.FlakeInput) void {514    if (input.changed) {515        const old = if (input.old_rev) |r| r[0..@min(7, r.len)] else "?";516        const new = if (input.new_rev) |r| r[0..@min(7, r.len)] else "?";517        p("   {s:<20}  {s} -> {s}\n", .{ input.name, old, new });518    } else {519        p("   {s:<20}  {s}no change{s}\n", .{ input.name, c(DIM), c(RESET) });520    }521}522523pub fn flakeLockWritten() void {524    p("\n{s}flake.lock written\n", .{hdr()});525}526527pub fn flakeValid() void {528    p("{s}{s}valid{s}\n", .{ hdr(), c(GREEN), c(RESET) });529}530531pub fn flakeCheckStart() void {532    p("{s}checking flake\n", .{hdr()});533}534535// --- Profile ---536537pub fn profileListHeader() void {538    p("{s}profile packages\n\n", .{hdr()});539}540541pub fn profileRow(attr: []const u8, pkg_version: []const u8, description: []const u8) void {542    p("   {s:<24}  {s:<12}  {s}\n", .{ attr, pkg_version, description });543}544545// --- Install / Remove / Try ---546547// Typo help for install: the query matched nothing, so suggest the closest real548// package name (pink) and let the caller confirm.549pub fn didYouMean(query: []const u8, suggestion: []const u8) void {550    p("{s}{s}'{s}' not found{s}  —  did you mean {s}{s}{s}?\n", .{ hdr(), c(DIM), query, c(RESET), c(PINK), suggestion, c(RESET) });551}552553pub fn installStart(pkg: []const u8, path: types.InstallPath) void {554    const path_str = switch (path) {555        .profile => "profile",556        .system => "system",557    };558    p("{s}installing {s}{s}{s}  {s}\n", .{ hdr(), c(PINK), pkg, c(RESET), path_str });559}560561pub fn installDone(pkg: []const u8) void {562    p("{s}{s}{s}{s} installed  {s}available now{s}\n", .{ hdr(), c(PINK), pkg, c(RESET), c(DIM), c(RESET) });563}564565pub fn removeStart(pkg: []const u8) void {566    p("{s}removing {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });567}568569// Plain-language health summary. No kaomoji, no hearts — just the facts.570pub fn mood(machine: []const u8, state: []const u8, gen: u32, age: []const u8, size: []const u8) void {571    const healthy = std.mem.eql(u8, state, "running");572    const verdict = if (healthy) "all good" else state;573    const color = if (healthy) GREEN else YELLOW;574    const face = if (healthy) KAO_HAPPY else "";575    p("{s}{s}{s}  {s}{s}{s}\n", .{ face, hdr(), machine, c(color), verdict, c(RESET) });576    if (age.len > 0 or size.len > 0) {577        p("   generation {d}, last applied {s}, {s} system closure\n", .{ gen, age, size });578    } else {579        p("   generation {d}\n", .{gen});580    }581}582583pub fn installEditorPrompt(pkg: []const u8, config_path: []const u8, line: u32, editor: []const u8) void {584    p("{s}opening {s}  add {s}{s}{s} to systemPackages\n", .{ hdr(), config_path, c(PINK), pkg, c(RESET) });585    const cmd = std.fmt.allocPrint(std.heap.page_allocator, "{s} {s} +{d}", .{ editor, config_path, line }) catch editor;586    printSubstep("{s}", .{cmd});587    p("\n   {s}save and close when done{s}\n\n", .{ c(DIM), c(RESET) });588}589590pub fn installSelectPrompt(pkg: []const u8, pkg_version: []const u8) void {591    p("{s}{s}{s}{s}  {s}\n\n", .{ hdr(), c(PINK), pkg, c(RESET), pkg_version });592    p("   [i] profile install    {s}instant  no rebuild{s}\n", .{ c(DIM), c(RESET) });593    p("   [s] system install     {s}opens editor  requires apply{s}\n", .{ c(DIM), c(RESET) });594    p("   [t] try now            {s}exits when done{s}\n\n", .{ c(DIM), c(RESET) });595    p("   > ", .{});596    flush();597}598599pub fn tryStart(pkg: []const u8) void {600    p("{s}trying {s}{s}{s}  exit when done\n", .{ hdr(), c(PINK), pkg, c(RESET) });601}602603pub fn tryExitHint() void {604    p("   {s}-> type 'exit' to return{s}\n", .{ c(DIM), c(RESET) });605}606607pub fn tryDone() void {608    p("{s}{s}back\n", .{ KAO_SLEEPY, hdr() });609}610611// --- List ---612613pub fn listHeader(machine: []const u8) void {614    p("{s}packages  {s}\n\n", .{ hdr(), machine });615}616617pub fn listSection(title: []const u8) void {618    p("   {s}{s}{s}\n", .{ c(DIM), title, c(RESET) });619}620621// Padded name so the version column lines up into a clean two-column table.622pub fn listPkg(name: []const u8, pkg_version: []const u8) void {623    p("   {s}{s:<16}{s}  {s}{s}{s}\n", .{ c(PINK), name, c(RESET), c(DIM), pkg_version, c(RESET) });624}625626pub fn blankLine() void {627    p("\n", .{});628}629630// --- Hello ---631632pub fn hello(machines: []const types.Machine) void {633    p("{s}{s}nina\n\n", .{ KAO_FACE, hdr() });634    for (machines) |m| {635        const kind = if (m.local) "local" else "ssh";636        const detail = if (m.local) "default" else m.host orelse "";637        p("   {s}{s}{s}   {s}   {s}\n", .{ c(DIM), m.name, c(RESET), kind, detail });638    }639    p("\n", .{});640    const quick = [_][2][]const u8{641        .{ "apply",         "rebuild and switch" },642        .{ "search <q>",    "find packages" },643        .{ "install <pkg>", "add to profile or system" },644        .{ "status",        "machine health" },645        .{ "back",          "roll back one generation" },646        .{ "update",        "refresh channels" },647    };648    for (quick) |cmd| {649        p("   {s:<16}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });650    }651    p("\n", .{});652}653654// --- Help ---655656pub fn help() void {657    p("{s}nina  {s}NixOS Intuitive Navigation Assistant by Asha Software{s}\n\n", .{ hdr(), c(DIM), c(RESET) });658    const cmds = [_][2][]const u8{659        .{ "apply", "rebuild and switch" },660        .{ "back", "roll back one generation" },661        .{ "go <n>", "switch to generation n" },662        .{ "history", "list all generations" },663        .{ "clean", "remove old generations" },664        .{ "search <q>", "find packages" },665        .{ "install <pkg>", "add to profile or system" },666        .{ "remove <pkg>", "remove from profile or system" },667        .{ "try <pkg>", "test without installing" },668        .{ "list", "show installed packages" },669        .{ "edit", "open configuration.nix" },670        .{ "check", "validate config" },671        .{ "diff", "changes between generations" },672        .{ "status", "machine health" },673        .{ "update", "refresh channels" },674        .{ "upgrade", "update and rebuild" },675        .{ "log", "operation history" },676        .{ "doctor", "diagnose issues" },677        .{ "mood", "plain-language health" },678        .{ "develop", "enter dev shell" },679        .{ "flake", "flake management" },680        .{ "build", "build a package" },681        .{ "run", "run without installing" },682        .{ "service", "manage services" },683        .{ "store", "nix store tools" },684        .{ "channel", "manage channels" },685        .{ "profile", "user profile packages" },686        .{ "info", "system information" },687        .{ "boot", "boot entries" },688        .{ "fmt", "format configuration.nix" },689        .{ "repl", "nix repl with nixpkgs" },690        .{ "option <q>", "search nixos options" },691        .{ "pkg", "inspect packages" },692        .{ "why <pkg>", "what pulled a package in" },693        .{ "pin", "pin flake inputs" },694        .{ "hash", "compute nix hash" },695        .{ "fetch", "fetch and hash a url" },696        .{ "goodbye",       "uninstall nina" },697        .{ "hello",        "list machines" },698        .{ "help",         "this message" },699    };700    for (cmds) |cmd| {701        p("   {s:<18}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });702    }703    p("\n   {s}flags: --on <machine>  --dry  --check  --no-apply  --last <n>  --all  --json{s}\n", .{ c(DIM), c(RESET) });704}705706// Render a grouped command's subcommand list, shown when the group is invoked707// with no subcommand or an explicit `help`. Rows are {invocation, description}.708pub fn subcommandHelp(group: []const u8, rows: []const [2][]const u8, footer: ?[]const u8) void {709    p("{s}{s} subcommands\n\n", .{ hdr(), group });710    for (rows) |row| {711        p("   {s:<16}  {s}{s}{s}\n", .{ row[0], c(DIM), row[1], c(RESET) });712    }713    if (footer) |f| p("\n   {s}{s}{s}\n", .{ c(DIM), f, c(RESET) });714    p("\n   nina {s} help  {s}for this message{s}\n", .{ group, c(DIM), c(RESET) });715}716717pub fn version() void {718    p("{s}nina  v{s}  zig 0.16  zero dependencies\n", .{ hdr(), nina_version.VERSION });719}720721// --- Search (text output before TUI) ---722723pub fn searchResult(pkg: types.NixPackage) void {724    p("   {s}{s}{s}   {s}{s}{s}   {s}\n", .{ c(PINK), pkg.pname, c(RESET), c(DIM), pkg.version, c(RESET), pkg.description });725}726727pub fn searchHeader(query: []const u8, count: usize) void {728    p("{s}search nixpkgs {s}  {s}{d} results{s}\n\n", .{ hdr(), query, c(DIM), count, c(RESET) });729}730731// --- Gen commands ---732733pub fn genCurrent(n: u32) void {734    p("{d}\n", .{n});735}736737pub fn done() void {738    p("{s}done\n", .{hdr()});739}740741pub fn runStart(pkg: []const u8) void {742    p("{s}running {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });743}744745pub fn buildStart(attr: []const u8) void {746    p("{s}building {s}\n", .{ hdr(), attr });747}748749pub fn buildDone() void {750    p("{s}done\n", .{hdr()});751}752753// --- Self-update (nina update) ---754755pub fn updateSelfStart() void {756    p("{s}checking for updates\n", .{hdr()});757}758759pub fn updateSelfCurrent(ver: []const u8) void {760    p("{s}{s}nina {s} is up to date{s}\n", .{ hdr(), c(GREEN), ver, c(RESET) });761}762763pub fn updateSelfAvailable(current: []const u8, latest: []const u8) void {764    p("{s}current  {s}\n", .{ step(), current });765    p("{s}latest   {s}{s}{s}\n", .{ step(), c(BOLD), latest, c(RESET) });766}767768pub fn updateSelfDownloading(ver: []const u8, platform: []const u8) void {769    p("{s}downloading nina {s} for {s}\n", .{ step(), ver, platform });770}771772pub fn updateSelfVerifying() void {773    p("{s}verifying checksum\n", .{step()});774}775776pub fn updateSelfInstalling(install_path: []const u8) void {777    p("{s}installing to {s}\n", .{ step(), install_path });778}779780pub fn updateSelfDone(old_ver: []const u8, new_ver: []const u8) void {781    p("{s}updated  {s} {s}→{s} {s}\n", .{ hdr(), old_ver, c(DIM), c(RESET), new_ver });782}783784pub fn updateSelfNoPlatform(platform: []const u8) void {785    p("{s}no pre-built binary for {s}\n", .{ hdr(), platform });786    p("{s}check kepr.uk/nina/releases for available platforms\n", .{step()});787}788789pub fn updateSelfNetworkError() void {790    p("{s}{s}\n", .{ if (color_enabled) WARN_C else WARN_P, "could not reach kepr.uk — check your connection" });791}792793pub fn updateSelfChecksumFailed() void {794    p("{s}checksum mismatch — download may be corrupt\n", .{if (color_enabled) ERR_C else ERR_P});795    p("{s}try again or download manually from kepr.uk/nina/releases\n", .{step()});796}797798pub fn updateSelfNixManaged(new_ver: []const u8) void {799    p("{s}upgrading to {s}{s}{s} via nix profile\n", .{ step(), c(BOLD), new_ver, c(RESET) });800}801802pub fn updateSelfNixFailed() void {803    p("{s}nix profile upgrade failed\n", .{if (color_enabled) ERR_C else ERR_P});804    p("{s}try manually: nix profile upgrade '.*nina.*'\n", .{step()});805}806807pub fn updateSelfNotInProfile() void {808    p("{s}nina is in the nix store but not found as a profile element\n", .{hdr()});809    p("{s}reinstall via 'nix profile add' to enable self-update\n", .{step()});810}811812// --- Goodbye / uninstall ---813814pub fn goodbyeStart() void {815    p("{s}uninstalling nina\n", .{hdr()});816}817818pub fn goodbyeFile(path: []const u8) void {819    p("{s}will remove {s}\n", .{ step(), path });820}821822pub fn goodbyeNix() void {823    p("{s}will remove nina from nix profile\n", .{step()});824    p("{s}command: nix profile remove nina\n", .{step()});825}826827pub fn goodbyeDone() void {828    p("{s}goodbye! see kepr.uk/nina to reinstall\n", .{hdr()});829}830831pub fn goodbyeFailed(msg: []const u8) void {832    p("{s}{s}\n", .{ if (color_enabled) ERR_C else ERR_P, msg });833}834835// --- Setup ---836837pub fn setupCheck() void {838    p("{s}checking nix features\n", .{hdr()});839}840841pub fn setupFeatures(nix_command: bool, flakes: bool) void {842    p("{s}nix-command  {s}{s}{s}\n", .{843        step(),844        if (nix_command) c(GREEN) else "",845        if (nix_command) "enabled" else "not enabled",846        if (nix_command) c(RESET) else "",847    });848    p("{s}flakes       {s}{s}{s}\n", .{849        step(),850        if (flakes) c(GREEN) else "",851        if (flakes) "enabled" else "not enabled",852        if (flakes) c(RESET) else "",853    });854}855856pub fn setupAllSet() void {857    p("{s}all set\n", .{hdr()});858}859860// Printed once, before the first search, when the nixpkgs registry still points861// at a remote URL. Flush so it lands before `nix registry pin` and any results.862pub fn pinningRegistry() void {863    p("{s}pinning nixpkgs for fast local search...\n", .{hdr()});864    flush();865}866867// --- Plain (non-tty) search rendering ---868// Color-gated equivalents of the raw-ANSI TUI widget, for piped/scripted search.869// Using the gated header + c() keeps ANSI out of non-tty output (NO_COLOR / pipes).870871pub fn searchPlainHeader(mode_str: []const u8, query: []const u8, count: u64) void {872    p("{s}search {s} {s}  {s}{d} results{s}\n", .{ hdr(), mode_str, query, c(DIM), count, c(RESET) });873}874875pub fn searchPlainNoResults() void {876    p("   no results\n", .{});877}878879pub fn searchPlainPackage(pname: []const u8, pkg_version: []const u8, description: []const u8, unfree: bool) void {880    if (unfree) {881        p("   {s}   {s}{s}{s}   {s}unfree{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), c(YELLOW), c(RESET), description });882    } else {883        p("   {s}   {s}{s}{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), description });884    }885}886887pub fn searchPlainOption(name: []const u8, type_str: []const u8) void {888    p("   {s}   {s}{s}{s}\n", .{ name, c(DIM), type_str, c(RESET) });889}890891pub fn searchEmptyQuery() void {892    p("{s}search needs a query  {s}e.g. nina search firefox{s}\n", .{ hdr(), c(DIM), c(RESET) });893}894895pub fn setupEnabling() void {896    p("{s}enabling experimental features\n", .{hdr()});897}898899pub fn setupDone(path: []const u8) void {900    p("{s}wrote {s}\n", .{ step(), path });901    p("{s}done  open a new shell to pick up the change\n", .{hdr()});902}903904// --- NixOS setup (declarative configuration.nix) ---905906pub fn setupNixosOffer(features_line: []const u8, conf_path: []const u8) void {907    p("{s}on NixOS these go in your system config\n", .{hdr()});908    p("   nina can add this line to {s}{s}{s}:\n\n", .{ c(DIM), conf_path, c(RESET) });909    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });910}911912pub fn setupNixosWrote(conf_path: []const u8) void {913    p("{s}added the line to {s}  {s}(backup: {s}.nina-bak){s}\n", .{ step(), conf_path, c(DIM), conf_path, c(RESET) });914    p("{s}now run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ hdr(), c(BOLD), c(RESET) });915}916917pub fn setupNixosManual(features_line: []const u8, conf_path: []const u8) void {918    p("{s}no problem — add this line inside the {s}{{ }}{s} in {s}:\n\n", .{ hdr(), c(DIM), c(RESET), conf_path });919    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });920    p("   then run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ c(BOLD), c(RESET) });921}922923pub fn setupNixosNeedsRebuild(conf_path: []const u8) void {924    p("{s}already declared in {s}\n", .{ hdr(), conf_path });925    p("   just run {s}sudo nixos-rebuild switch{s} to activate it\n", .{ c(BOLD), c(RESET) });926}927928pub fn pinDone(input: []const u8, commit: []const u8) void {929    p("{s}pinned {s} -> {s}\n", .{ hdr(), input, commit });930}931932pub fn unpinDone(input: []const u8) void {933    p("{s}unpinned {s}\n", .{ hdr(), input });934}935936pub fn hashResult(hash: []const u8) void {937    p("{s}\n", .{hash});938}939940pub fn fetchResult(hash: []const u8, url: []const u8) void {941    _ = url;942    p("{s}\n", .{hash});943}944945pub fn storeRepairStart() void {946    p("{s}repairing store\n", .{hdr()});947}948949pub fn storeVerifyStart() void {950    p("{s}verifying store\n", .{hdr()});951}952953pub fn storeGcDone(freed: []const u8) void {954    p("{s}freed {s}\n", .{ hdr(), freed });955}956957pub fn storePath(path: []const u8) void {958    p("{s}\n", .{path});959}960961pub fn pkgResult(key: []const u8, val: []const u8) void {962    p("   {s:<16}  {s}\n", .{ key, val });963}964965pub fn channelDone() void {966    p("{s}done\n", .{hdr()});967}968969pub fn flakeShowHeader(name: []const u8) void {970    p("{s}{s}\n\n", .{ hdr(), name });971}972973pub fn flakeShowEntry(kind: []const u8, name: []const u8, desc: []const u8) void {974    p("   {s:<12}  {s:<24}  {s}\n", .{ kind, name, desc });975}976977// --- Home Manager ---978979pub fn homeNotInstalled() void {980    p("{s}home manager not detected  {s}nothing to do{s}\n", .{ hdr(), c(DIM), c(RESET) });981}982983// HM is a NixOS/flake module — rebuilt by nixos-rebuild, not the standalone CLI.984pub fn homeModuleManaged() void {985    p("{s}home manager is managed by your system config\n", .{hdr()});986    p("   {s}-> run {s}nina apply{s}{s} to rebuild both together{s}\n", .{ c(CYAN), c(BOLD), c(RESET), c(CYAN), c(RESET) });987}988989pub fn homeApplyStart(machine: []const u8) void {990    p("{s}{s}applying home config  {s}\n", .{ KAO_COZY, hdr(), machine });991}992993pub fn homeApplyDone(gen: u32, elapsed_ms: u64) void {994    const secs = @as(f64, @floatFromInt(elapsed_ms)) / 1000.0;995    if (elapsed_ms >= 1000) {996        p("{s}generation {s}{d}{s}  {s}[{d:.1}s]{s}\n", .{ hdr(), c(BOLD), gen, c(RESET), c(DIM), secs, c(RESET) });997    } else {998        p("{s}generation {s}{d}{s}\n", .{ hdr(), c(BOLD), gen, c(RESET) });999    }1000}10011002pub fn homeApplyDry(machine: []const u8) void {1003    p("{s}home dry run  {s}\n", .{ hdr(), machine });1004}10051006pub fn homeApplyDryDone() void {1007    p("{s}{s}ok{s}  no changes applied\n", .{ hdr(), c(GREEN), c(RESET) });1008}10091010pub fn homeBackStart(machine: []const u8, from: u32, to: u32) void {1011    p("{s}rolling back home config  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, from, to });1012}10131014pub fn homeBackDone(n: u32) void {1015    p("{s}{s}done  gen {s}{d}{s}\n", .{ KAO_GENTLE, hdr(), c(BOLD), n, c(RESET) });1016}10171018pub fn homeHistoryHeader(machine: []const u8) void {1019    p("{s}home generations  {s}\n\n", .{ hdr(), machine });1020}10211022pub fn homeHistoryRow(number: u32, date: []const u8, time: []const u8, current: bool) void {1023    if (current) {1024        p("   {s}{d}{s}   {s}   {s}   {s}current{s}\n", .{ c(BOLD), number, c(RESET), date, time, c(BOLD), c(RESET) });1025    } else {1026        p("   {s}{d}   {s}   {s}{s}\n", .{ c(DIM), number, date, time, c(RESET) });1027    }1028}10291030pub fn homeEditOpen(path: []const u8, editor: []const u8) void {1031    p("{s}opening {s}\n", .{ hdr(), path });1032    printSubstep("{s}", .{editor});1033}10341035pub fn homeCheckStart(machine: []const u8) void {1036    p("{s}checking home config  {s}\n", .{ hdr(), machine });1037}10381039pub fn homeCheckOk() void {1040    p("{s}{s}ok{s}\n", .{ hdr(), c(GREEN), c(RESET) });1041}10421043pub fn homeDiffHeader(a: u32, b: u32, machine: []const u8) void {1044    p("{s}home gen {d} -> gen {d}  {s}\n\n", .{ hdr(), a, b, machine });1045}10461047pub fn homeNothingToDiff() void {1048    p("{s}only one home generation — nothing to diff yet\n", .{hdr()});1049}10501051pub fn homePackagesHeader(machine: []const u8) void {1052    p("{s}home packages  {s}\n\n", .{ hdr(), machine });1053}10541055// --- First-run wizard ---10561057pub fn firstRunBanner() void {1058    p("{s}{s}nina \u{2014} first run\n\n", .{ KAO_FACE, hdr() });1059}10601061pub fn firstRunNoConfig() void {1062    p("   no config found. let me get set up.\n\n", .{});1063}10641065// Print a prompt line and read the user's answer. Returns the default if the1066// user presses Enter without typing anything. buf must be at least 256 bytes.1067// Returns a slice into buf (or default if empty input).1068pub fn firstRunPrompt(label: []const u8, default: []const u8, buf: []u8) []const u8 {1069    p("   {s:<14} {s}> {s}", .{ label, c(DIM), c(RESET) });1070    flush();1071    var i: usize = 0;1072    while (i < buf.len - 1) {1073        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;1074        if (n == 0) break;1075        if (buf[i] == '\n') break;1076        i += 1;1077    }1078    const input = std.mem.trim(u8, buf[0..i], " \t\r");1079    if (input.len == 0) {1080        // Echo the default so the output shows what was chosen1081        p("{s}{s}{s}\n", .{ c(DIM), default, c(RESET) });1082        flush();1083        return default;1084    }1085    return input;1086}10871088pub fn firstRunScanning() void {1089    p("\n   {s}:: scanning for config...{s}\n", .{ c(DIM), c(RESET) });1090}10911092// Report what the scan found at /etc/nixos, noting flake vs channel.1093pub fn firstRunDetected(path: []const u8, is_flake: bool) void {1094    const kind = if (is_flake) "flake-based system" else "channel-based system";1095    p("   {s}-> found {s}{s}   {s}({s}){s}\n\n", .{ c(CYAN), path, c(RESET), c(DIM), kind, c(RESET) });1096}10971098pub fn firstRunNoneFound() void {1099    p("   {s}-> nothing found at /etc/nixos{s}\n\n", .{ c(DIM), c(RESET) });1100}11011102// Prompt with a pre-filled default shown in brackets. Empty input accepts the1103// default. When `detected` and a default is present, note that enter confirms.1104pub fn firstRunPromptDefault(label: []const u8, default: []const u8, detected: bool, buf: []u8) []const u8 {1105    if (default.len > 0) {1106        p("   {s:<14} {s}[{s}]{s} > ", .{ label, c(DIM), default, c(RESET) });1107        if (detected) p("{s}enter to confirm{s} ", .{ c(DIM), c(RESET) });1108    } else {1109        p("   {s:<14} {s}> {s}", .{ label, c(DIM), c(RESET) });1110    }1111    flush();1112    var i: usize = 0;1113    while (i < buf.len - 1) {1114        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;1115        if (n == 0) break;1116        if (buf[i] == '\n') break;1117        i += 1;1118    }1119    const input = std.mem.trim(u8, buf[0..i], " \t\r");1120    if (input.len == 0) {1121        p("{s}{s}{s}\n", .{ c(DIM), default, c(RESET) });1122        flush();1123        return default;1124    }1125    return input;1126}11271128// Shown before channel operations on a flake-managed system, where nix-channel1129// commands generally don't apply.1130pub fn flakeChannelNote() void {1131    p("{s}{s}note: flake-based system — use {s}nina flake update{s}{s} to update inputs{s}\n", .{ hdr(), c(DIM), c(CYAN), c(RESET), c(DIM), c(RESET) });1132}11331134pub fn firstRunWritten(path: []const u8) void {1135    p("\n   {s}written to {s}{s}\n\n", .{ c(DIM), path, c(RESET) });1136}11371138pub fn firstRunSkipped() void {1139    p("\n   {s}skipping setup in non-interactive mode{s}\n", .{ c(DIM), c(RESET) });1140}