output.zig

33.9 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// --- Diff ---308309pub fn diffHeader(a: u32, b: u32, machine: []const u8) void {310    p("{s}gen {d} -> gen {d}  {s}\n\n", .{ hdr(), a, b, machine });311}312313pub fn diffRow(entry: types.DiffEntry) void {314    switch (entry.op) {315        .add => p("   {s}+{s} {s}   {s}\n", .{ c(GREEN), c(RESET), entry.package, entry.new_version orelse "" }),316        .remove => p("   {s}-{s} {s}   {s}\n", .{ c(RED), c(RESET), entry.package, entry.old_version orelse "" }),317        .change => p("   {s}^{s} {s}   {s} -> {s}\n", .{ c(CYAN), c(RESET), entry.package, entry.old_version orelse "", entry.new_version orelse "" }),318    }319}320321// --- Doctor ---322323pub fn doctorHeader(machine: []const u8) void {324    p("{s}diagnosing  {s}\n\n", .{ hdr(), machine });325}326327pub fn doctorRow(check: types.DoctorCheck) void {328    const status_str = switch (check.status) {329        .ok => if (color_enabled) GREEN ++ "ok" ++ RESET else "ok",330        .warn => if (color_enabled) YELLOW ++ "warn" ++ RESET else "warn",331        .fail => if (color_enabled) RED ++ "fail" ++ RESET else "fail",332    };333    const note_str = check.note orelse "";334    p("   {s:<16}  {s}   {s}\n", .{ check.name, status_str, note_str });335}336337pub fn doctorSummary(warnings: u32, failures: u32) void {338    if (failures > 0) {339        p("{s}{d} problems\n", .{ hdr(), failures });340    } else if (warnings > 0) {341        p("{s}{d} warnings\n", .{ hdr(), warnings });342    } else {343        p("{s}{s}{s}all good{s}\n", .{ KAO_HAPPY, hdr(), c(GREEN), c(RESET) });344    }345}346347// --- Update ---348349pub fn updateStart(machine: []const u8) void {350    p("{s}updating channels  {s}\n\n", .{ hdr(), machine });351}352353pub fn updateChannel(name: []const u8, old: ?[]const u8, new: ?[]const u8) void {354    if (old != null and new != null and !std.mem.eql(u8, old.?, new.?)) {355        p("   {s}   {s} -> {s}\n", .{ name, old.?, new.? });356    } else {357        p("   {s}   {s}no change{s}\n", .{ name, c(DIM), c(RESET) });358    }359}360361pub fn updateDone() void {362    p("\n{s}done\n", .{hdr()});363}364365// --- Upgrade ---366367pub fn upgradeStart(machine: []const u8) void {368    p("{s}upgrading  {s}\n", .{ hdr(), machine });369}370371// --- Log ---372373pub fn logHeader(machine: []const u8) void {374    p("{s}history  {s}\n\n", .{ hdr(), machine });375}376377pub fn logRow(date: []const u8, time: []const u8, action: []const u8, detail: []const u8) void {378    p("   {s}{s}  {s}{s}   {s:<16}  {s}\n", .{ c(DIM), date, time, c(RESET), action, detail });379}380381// --- Edit ---382383pub fn editOpen(path: []const u8, editor: []const u8) void {384    p("{s}opening {s}\n", .{ hdr(), path });385    printSubstep("{s}", .{editor});386    p("\n   {s}run nina check to validate before applying{s}\n", .{ c(DIM), c(RESET) });387}388389// --- Fmt ---390391pub fn fmtStart(path: []const u8) void {392    p("{s}formatting  {s}\n", .{ hdr(), path });393}394395pub fn fmtDone() void {396    p("{s}done\n", .{hdr()});397}398399pub fn fmtNeedsFormat() void {400    p("{s}needs formatting  {s}run nina fmt to fix{s}\n", .{ hdr(), c(DIM), c(RESET) });401}402403// --- Repl ---404405pub fn replStart() void {406    p("{s}nix repl  {s}nixpkgs loaded{s}  :q to exit\n", .{ hdr(), c(DIM), c(RESET) });407}408409// --- Develop ---410411pub fn developStart(pkgs: []const []const u8) void {412    p("{s}entering dev shell\n\n   ", .{hdr()});413    for (pkgs, 0..) |pkg, i| {414        if (i > 0) p("  ", .{});415        p("{s}", .{pkg});416    }417    p("\n\n   {s}-> type 'exit' to return{s}\n\n", .{ c(DIM), c(RESET) });418}419420pub fn developDone() void {421    p("{s}{s}back\n", .{ KAO_SLEEPY, hdr() });422}423424// --- Info ---425426pub fn infoHeader(machine: []const u8) void {427    p("{s}{s}\n\n", .{ hdr(), machine });428}429430pub fn infoRow(key: []const u8, val: []const u8) void {431    p("   {s:<12}  {s}\n", .{ key, val });432}433434// --- Boot ---435436pub fn bootHeader(machine: []const u8) void {437    p("{s}boot entries  {s}\n\n", .{ hdr(), machine });438}439440pub fn bootEntry(entry: types.BootEntry, idx: usize) void {441    if (entry.current) {442        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) });443    } else {444        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) });445    }446    _ = idx;447}448449// --- Service ---450451pub fn serviceListHeader(machine: []const u8) void {452    p("{s}services  {s}\n\n", .{ hdr(), machine });453}454455pub fn serviceRow(svc: types.ServiceInfo) void {456    const state_str = switch (svc.state) {457        .active => if (color_enabled) GREEN ++ "active" ++ RESET else "active",458        .failed => if (color_enabled) RED ++ "failed" ++ RESET else "failed",459        .inactive => "inactive",460        .unknown => "unknown",461    };462    const uptime = svc.uptime orelse "";463    p("   {s:<24}  {s:<14}  {s}\n", .{ svc.name, state_str, uptime });464}465466pub fn serviceVerb(verb: []const u8, name: []const u8, machine: []const u8) void {467    p("{s}{s} {s}  {s}\n", .{ hdr(), verb, name, machine });468}469470pub fn serviceDone() void {471    p("{s}done\n", .{hdr()});472}473474pub fn serviceLogsHeader(name: []const u8, n: u32, machine: []const u8) void {475    p("{s}{s}  last {d} lines  {s}\n\n", .{ hdr(), name, n, machine });476}477478// --- Store ---479480pub fn storeInfo(info: types.StoreInfo) void {481    p("{s}store\n\n", .{hdr()});482    p("   {s:<16}  {s}\n", .{ "total", info.total_size });483    p("   {s:<16}  {d} paths\n", .{ "live", info.live_paths });484    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) });485}486487// --- Channel ---488489pub fn channelListHeader(machine: []const u8) void {490    p("{s}channels  {s}\n\n", .{ hdr(), machine });491}492493pub fn channelRow(ch: types.ChannelInfo) void {494    p("   {s:<16}  {s}\n", .{ ch.name, ch.url });495}496497// --- Flake ---498499pub fn flakeUpdateStart() void {500    p("{s}updating inputs\n\n", .{hdr()});501}502503pub fn flakeInput(input: types.FlakeInput) void {504    if (input.changed) {505        const old = if (input.old_rev) |r| r[0..@min(7, r.len)] else "?";506        const new = if (input.new_rev) |r| r[0..@min(7, r.len)] else "?";507        p("   {s:<20}  {s} -> {s}\n", .{ input.name, old, new });508    } else {509        p("   {s:<20}  {s}no change{s}\n", .{ input.name, c(DIM), c(RESET) });510    }511}512513pub fn flakeLockWritten() void {514    p("\n{s}flake.lock written\n", .{hdr()});515}516517pub fn flakeValid() void {518    p("{s}{s}valid{s}\n", .{ hdr(), c(GREEN), c(RESET) });519}520521pub fn flakeCheckStart() void {522    p("{s}checking flake\n", .{hdr()});523}524525// --- Profile ---526527pub fn profileListHeader() void {528    p("{s}profile packages\n\n", .{hdr()});529}530531pub fn profileRow(attr: []const u8, pkg_version: []const u8, description: []const u8) void {532    p("   {s:<24}  {s:<12}  {s}\n", .{ attr, pkg_version, description });533}534535// --- Install / Remove / Try ---536537// Typo help for install: the query matched nothing, so suggest the closest real538// package name (pink) and let the caller confirm.539pub fn didYouMean(query: []const u8, suggestion: []const u8) void {540    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) });541}542543pub fn installStart(pkg: []const u8, path: types.InstallPath) void {544    const path_str = switch (path) {545        .profile => "profile",546        .system => "system",547    };548    p("{s}installing {s}{s}{s}  {s}\n", .{ hdr(), c(PINK), pkg, c(RESET), path_str });549}550551pub fn installDone(pkg: []const u8) void {552    p("{s}{s}{s}{s} installed  {s}available now{s}\n", .{ hdr(), c(PINK), pkg, c(RESET), c(DIM), c(RESET) });553}554555pub fn removeStart(pkg: []const u8) void {556    p("{s}removing {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });557}558559// Plain-language health summary. No kaomoji, no hearts — just the facts.560pub fn mood(machine: []const u8, state: []const u8, gen: u32, age: []const u8, size: []const u8) void {561    const healthy = std.mem.eql(u8, state, "running");562    const verdict = if (healthy) "all good" else state;563    const color = if (healthy) GREEN else YELLOW;564    const face = if (healthy) KAO_HAPPY else "";565    p("{s}{s}{s}  {s}{s}{s}\n", .{ face, hdr(), machine, c(color), verdict, c(RESET) });566    if (age.len > 0 or size.len > 0) {567        p("   generation {d}, last applied {s}, {s} system closure\n", .{ gen, age, size });568    } else {569        p("   generation {d}\n", .{gen});570    }571}572573pub fn installEditorPrompt(pkg: []const u8, config_path: []const u8, line: u32, editor: []const u8) void {574    p("{s}opening {s}  add {s}{s}{s} to systemPackages\n", .{ hdr(), config_path, c(PINK), pkg, c(RESET) });575    const cmd = std.fmt.allocPrint(std.heap.page_allocator, "{s} {s} +{d}", .{ editor, config_path, line }) catch editor;576    printSubstep("{s}", .{cmd});577    p("\n   {s}save and close when done{s}\n\n", .{ c(DIM), c(RESET) });578}579580pub fn installSelectPrompt(pkg: []const u8, pkg_version: []const u8) void {581    p("{s}{s}{s}{s}  {s}\n\n", .{ hdr(), c(PINK), pkg, c(RESET), pkg_version });582    p("   [i] profile install    {s}instant  no rebuild{s}\n", .{ c(DIM), c(RESET) });583    p("   [s] system install     {s}opens editor  requires apply{s}\n", .{ c(DIM), c(RESET) });584    p("   [t] try now            {s}exits when done{s}\n\n", .{ c(DIM), c(RESET) });585    p("   > ", .{});586    flush();587}588589pub fn tryStart(pkg: []const u8) void {590    p("{s}trying {s}{s}{s}  exit when done\n", .{ hdr(), c(PINK), pkg, c(RESET) });591}592593pub fn tryExitHint() void {594    p("   {s}-> type 'exit' to return{s}\n", .{ c(DIM), c(RESET) });595}596597pub fn tryDone() void {598    p("{s}{s}back\n", .{ KAO_SLEEPY, hdr() });599}600601// --- List ---602603pub fn listHeader(machine: []const u8) void {604    p("{s}packages  {s}\n\n", .{ hdr(), machine });605}606607pub fn listSection(title: []const u8) void {608    p("   {s}{s}{s}\n", .{ c(DIM), title, c(RESET) });609}610611// Padded name so the version column lines up into a clean two-column table.612pub fn listPkg(name: []const u8, pkg_version: []const u8) void {613    p("   {s}{s:<16}{s}  {s}{s}{s}\n", .{ c(PINK), name, c(RESET), c(DIM), pkg_version, c(RESET) });614}615616pub fn blankLine() void {617    p("\n", .{});618}619620// --- Hello ---621622pub fn hello(machines: []const types.Machine) void {623    p("{s}{s}nina\n\n", .{ KAO_FACE, hdr() });624    for (machines) |m| {625        const kind = if (m.local) "local" else "ssh";626        const detail = if (m.local) "default" else m.host orelse "";627        p("   {s}{s}{s}   {s}   {s}\n", .{ c(DIM), m.name, c(RESET), kind, detail });628    }629    p("\n", .{});630    const quick = [_][2][]const u8{631        .{ "apply",         "rebuild and switch" },632        .{ "search <q>",    "find packages" },633        .{ "install <pkg>", "add to profile or system" },634        .{ "status",        "machine health" },635        .{ "back",          "roll back one generation" },636        .{ "update",        "refresh channels" },637    };638    for (quick) |cmd| {639        p("   {s:<16}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });640    }641    p("\n", .{});642}643644// --- Help ---645646pub fn help() void {647    p("{s}nina  {s}NixOS Intuitive Navigation Assistant by Asha Software{s}\n\n", .{ hdr(), c(DIM), c(RESET) });648    const cmds = [_][2][]const u8{649        .{ "apply", "rebuild and switch" },650        .{ "back", "roll back one generation" },651        .{ "go <n>", "switch to generation n" },652        .{ "history", "list all generations" },653        .{ "clean", "remove old generations" },654        .{ "search <q>", "find packages" },655        .{ "install <pkg>", "add to profile or system" },656        .{ "remove <pkg>", "remove from profile or system" },657        .{ "try <pkg>", "test without installing" },658        .{ "list", "show installed packages" },659        .{ "edit", "open configuration.nix" },660        .{ "check", "validate config" },661        .{ "diff", "changes between generations" },662        .{ "status", "machine health" },663        .{ "update", "refresh channels" },664        .{ "upgrade", "update and rebuild" },665        .{ "log", "operation history" },666        .{ "doctor", "diagnose issues" },667        .{ "mood", "plain-language health" },668        .{ "develop", "enter dev shell" },669        .{ "flake", "flake management" },670        .{ "build", "build a package" },671        .{ "run", "run without installing" },672        .{ "service", "manage services" },673        .{ "store", "nix store tools" },674        .{ "channel", "manage channels" },675        .{ "profile", "user profile packages" },676        .{ "info", "system information" },677        .{ "boot", "boot entries" },678        .{ "fmt", "format configuration.nix" },679        .{ "repl", "nix repl with nixpkgs" },680        .{ "option <q>", "search nixos options" },681        .{ "pkg", "inspect packages" },682        .{ "pin", "pin flake inputs" },683        .{ "hash", "compute nix hash" },684        .{ "fetch", "fetch and hash a url" },685        .{ "goodbye",       "uninstall nina" },686        .{ "hello",        "list machines" },687        .{ "help",         "this message" },688    };689    for (cmds) |cmd| {690        p("   {s:<18}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });691    }692    p("\n   {s}flags: --on <machine>  --dry  --check  --no-apply  --last <n>  --all  --json{s}\n", .{ c(DIM), c(RESET) });693}694695// Render a grouped command's subcommand list, shown when the group is invoked696// with no subcommand or an explicit `help`. Rows are {invocation, description}.697pub fn subcommandHelp(group: []const u8, rows: []const [2][]const u8) void {698    p("{s}{s} subcommands\n\n", .{ hdr(), group });699    for (rows) |row| {700        p("   {s:<16}  {s}{s}{s}\n", .{ row[0], c(DIM), row[1], c(RESET) });701    }702    p("\n   nina {s} help  {s}for this message{s}\n", .{ group, c(DIM), c(RESET) });703}704705pub fn version() void {706    p("{s}nina  v{s}  zig 0.16  zero dependencies\n", .{ hdr(), nina_version.VERSION });707}708709// --- Search (text output before TUI) ---710711pub fn searchResult(pkg: types.NixPackage) void {712    p("   {s}{s}{s}   {s}{s}{s}   {s}\n", .{ c(PINK), pkg.pname, c(RESET), c(DIM), pkg.version, c(RESET), pkg.description });713}714715pub fn searchHeader(query: []const u8, count: usize) void {716    p("{s}search nixpkgs {s}  {s}{d} results{s}\n\n", .{ hdr(), query, c(DIM), count, c(RESET) });717}718719// --- Gen commands ---720721pub fn genCurrent(n: u32) void {722    p("{d}\n", .{n});723}724725pub fn done() void {726    p("{s}done\n", .{hdr()});727}728729pub fn runStart(pkg: []const u8) void {730    p("{s}running {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });731}732733pub fn buildStart(attr: []const u8) void {734    p("{s}building {s}\n", .{ hdr(), attr });735}736737pub fn buildDone() void {738    p("{s}done\n", .{hdr()});739}740741// --- Self-update (nina update) ---742743pub fn updateSelfStart() void {744    p("{s}checking for updates\n", .{hdr()});745}746747pub fn updateSelfCurrent(ver: []const u8) void {748    p("{s}{s}nina {s} is up to date{s}\n", .{ hdr(), c(GREEN), ver, c(RESET) });749}750751pub fn updateSelfAvailable(current: []const u8, latest: []const u8) void {752    p("{s}current  {s}\n", .{ step(), current });753    p("{s}latest   {s}{s}{s}\n", .{ step(), c(BOLD), latest, c(RESET) });754}755756pub fn updateSelfDownloading(ver: []const u8, platform: []const u8) void {757    p("{s}downloading nina {s} for {s}\n", .{ step(), ver, platform });758}759760pub fn updateSelfVerifying() void {761    p("{s}verifying checksum\n", .{step()});762}763764pub fn updateSelfInstalling(install_path: []const u8) void {765    p("{s}installing to {s}\n", .{ step(), install_path });766}767768pub fn updateSelfDone(old_ver: []const u8, new_ver: []const u8) void {769    p("{s}updated  {s} {s}→{s} {s}\n", .{ hdr(), old_ver, c(DIM), c(RESET), new_ver });770}771772pub fn updateSelfNoPlatform(platform: []const u8) void {773    p("{s}no pre-built binary for {s}\n", .{ hdr(), platform });774    p("{s}check kepr.uk/nina/releases for available platforms\n", .{step()});775}776777pub fn updateSelfNetworkError() void {778    p("{s}{s}\n", .{ if (color_enabled) WARN_C else WARN_P, "could not reach kepr.uk — check your connection" });779}780781pub fn updateSelfChecksumFailed() void {782    p("{s}checksum mismatch — download may be corrupt\n", .{if (color_enabled) ERR_C else ERR_P});783    p("{s}try again or download manually from kepr.uk/nina/releases\n", .{step()});784}785786pub fn updateSelfNixManaged(new_ver: []const u8) void {787    p("{s}upgrading to {s}{s}{s} via nix profile\n", .{ step(), c(BOLD), new_ver, c(RESET) });788}789790pub fn updateSelfNixFailed() void {791    p("{s}nix profile upgrade failed\n", .{if (color_enabled) ERR_C else ERR_P});792    p("{s}try manually: nix profile upgrade '.*nina.*'\n", .{step()});793}794795pub fn updateSelfNotInProfile() void {796    p("{s}nina is in the nix store but not found as a profile element\n", .{hdr()});797    p("{s}reinstall via 'nix profile add' to enable self-update\n", .{step()});798}799800// --- Goodbye / uninstall ---801802pub fn goodbyeStart() void {803    p("{s}uninstalling nina\n", .{hdr()});804}805806pub fn goodbyeFile(path: []const u8) void {807    p("{s}will remove {s}\n", .{ step(), path });808}809810pub fn goodbyeNix() void {811    p("{s}will remove nina from nix profile\n", .{step()});812    p("{s}command: nix profile remove nina\n", .{step()});813}814815pub fn goodbyeDone() void {816    p("{s}goodbye! see kepr.uk/nina to reinstall\n", .{hdr()});817}818819pub fn goodbyeFailed(msg: []const u8) void {820    p("{s}{s}\n", .{ if (color_enabled) ERR_C else ERR_P, msg });821}822823// --- Setup ---824825pub fn setupCheck() void {826    p("{s}checking nix features\n", .{hdr()});827}828829pub fn setupFeatures(nix_command: bool, flakes: bool) void {830    p("{s}nix-command  {s}{s}{s}\n", .{831        step(),832        if (nix_command) c(GREEN) else "",833        if (nix_command) "enabled" else "not enabled",834        if (nix_command) c(RESET) else "",835    });836    p("{s}flakes       {s}{s}{s}\n", .{837        step(),838        if (flakes) c(GREEN) else "",839        if (flakes) "enabled" else "not enabled",840        if (flakes) c(RESET) else "",841    });842}843844pub fn setupAllSet() void {845    p("{s}all set\n", .{hdr()});846}847848// Printed once, before the first search, when the nixpkgs registry still points849// at a remote URL. Flush so it lands before `nix registry pin` and any results.850pub fn pinningRegistry() void {851    p("{s}pinning nixpkgs for fast local search...\n", .{hdr()});852    flush();853}854855// --- Plain (non-tty) search rendering ---856// Color-gated equivalents of the raw-ANSI TUI widget, for piped/scripted search.857// Using the gated header + c() keeps ANSI out of non-tty output (NO_COLOR / pipes).858859pub fn searchPlainHeader(mode_str: []const u8, query: []const u8, count: u64) void {860    p("{s}search {s} {s}  {s}{d} results{s}\n", .{ hdr(), mode_str, query, c(DIM), count, c(RESET) });861}862863pub fn searchPlainNoResults() void {864    p("   no results\n", .{});865}866867pub fn searchPlainPackage(pname: []const u8, pkg_version: []const u8, description: []const u8, unfree: bool) void {868    if (unfree) {869        p("   {s}   {s}{s}{s}   {s}unfree{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), c(YELLOW), c(RESET), description });870    } else {871        p("   {s}   {s}{s}{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), description });872    }873}874875pub fn searchPlainOption(name: []const u8, type_str: []const u8) void {876    p("   {s}   {s}{s}{s}\n", .{ name, c(DIM), type_str, c(RESET) });877}878879pub fn searchEmptyQuery() void {880    p("{s}search needs a query  {s}e.g. nina search firefox{s}\n", .{ hdr(), c(DIM), c(RESET) });881}882883pub fn setupEnabling() void {884    p("{s}enabling experimental features\n", .{hdr()});885}886887pub fn setupDone(path: []const u8) void {888    p("{s}wrote {s}\n", .{ step(), path });889    p("{s}done  open a new shell to pick up the change\n", .{hdr()});890}891892// --- NixOS setup (declarative configuration.nix) ---893894pub fn setupNixosOffer(features_line: []const u8, conf_path: []const u8) void {895    p("{s}on NixOS these go in your system config\n", .{hdr()});896    p("   nina can add this line to {s}{s}{s}:\n\n", .{ c(DIM), conf_path, c(RESET) });897    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });898}899900pub fn setupNixosWrote(conf_path: []const u8) void {901    p("{s}added the line to {s}  {s}(backup: {s}.nina-bak){s}\n", .{ step(), conf_path, c(DIM), conf_path, c(RESET) });902    p("{s}now run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ hdr(), c(BOLD), c(RESET) });903}904905pub fn setupNixosManual(features_line: []const u8, conf_path: []const u8) void {906    p("{s}no problem — add this line inside the {s}{{ }}{s} in {s}:\n\n", .{ hdr(), c(DIM), c(RESET), conf_path });907    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });908    p("   then run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ c(BOLD), c(RESET) });909}910911pub fn setupNixosNeedsRebuild(conf_path: []const u8) void {912    p("{s}already declared in {s}\n", .{ hdr(), conf_path });913    p("   just run {s}sudo nixos-rebuild switch{s} to activate it\n", .{ c(BOLD), c(RESET) });914}915916pub fn pinDone(input: []const u8, commit: []const u8) void {917    p("{s}pinned {s} -> {s}\n", .{ hdr(), input, commit });918}919920pub fn unpinDone(input: []const u8) void {921    p("{s}unpinned {s}\n", .{ hdr(), input });922}923924pub fn hashResult(hash: []const u8) void {925    p("{s}\n", .{hash});926}927928pub fn fetchResult(hash: []const u8, url: []const u8) void {929    _ = url;930    p("{s}\n", .{hash});931}932933pub fn storeRepairStart() void {934    p("{s}repairing store\n", .{hdr()});935}936937pub fn storeVerifyStart() void {938    p("{s}verifying store\n", .{hdr()});939}940941pub fn storeGcDone(freed: []const u8) void {942    p("{s}freed {s}\n", .{ hdr(), freed });943}944945pub fn storePath(path: []const u8) void {946    p("{s}\n", .{path});947}948949pub fn pkgResult(key: []const u8, val: []const u8) void {950    p("   {s:<16}  {s}\n", .{ key, val });951}952953pub fn channelDone() void {954    p("{s}done\n", .{hdr()});955}956957pub fn flakeShowHeader(name: []const u8) void {958    p("{s}{s}\n\n", .{ hdr(), name });959}960961pub fn flakeShowEntry(kind: []const u8, name: []const u8, desc: []const u8) void {962    p("   {s:<12}  {s:<24}  {s}\n", .{ kind, name, desc });963}964965// --- First-run wizard ---966967pub fn firstRunBanner() void {968    p("{s}{s}nina \u{2014} first run\n\n", .{ KAO_FACE, hdr() });969}970971pub fn firstRunNoConfig() void {972    p("   no config found. let me get set up.\n\n", .{});973}974975// Print a prompt line and read the user's answer. Returns the default if the976// user presses Enter without typing anything. buf must be at least 256 bytes.977// Returns a slice into buf (or default if empty input).978pub fn firstRunPrompt(label: []const u8, default: []const u8, buf: []u8) []const u8 {979    p("   {s:<14} {s}> {s}", .{ label, c(DIM), c(RESET) });980    flush();981    var i: usize = 0;982    while (i < buf.len - 1) {983        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;984        if (n == 0) break;985        if (buf[i] == '\n') break;986        i += 1;987    }988    const input = std.mem.trim(u8, buf[0..i], " \t\r");989    if (input.len == 0) {990        // Echo the default so the output shows what was chosen991        p("{s}{s}{s}\n", .{ c(DIM), default, c(RESET) });992        flush();993        return default;994    }995    return input;996}997998// Ask whether the system is flake-based or channel-based. Returns true for999// flakes. Defaults to channels (Enter or anything but '2'), echoing the choice.1000pub fn firstRunManageType() bool {1001    p("\n   how do you manage your system?\n", .{});1002    p("   {s}[1]{s} nixos channels (classic)\n", .{ c(DIM), c(RESET) });1003    p("   {s}[2]{s} nix flakes\n\n", .{ c(DIM), c(RESET) });1004    p("   {s}> {s}", .{ c(DIM), c(RESET) });1005    flush();1006    var buf: [64]u8 = undefined;1007    var i: usize = 0;1008    while (i < buf.len - 1) {1009        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;1010        if (n == 0) break;1011        if (buf[i] == '\n') break;1012        i += 1;1013    }1014    const input = std.mem.trim(u8, buf[0..i], " \t\r");1015    const flakes = input.len > 0 and input[0] == '2';1016    p("{s}{s}{s}\n", .{ c(DIM), if (flakes) "nix flakes" else "nixos channels", c(RESET) });1017    return flakes;1018}10191020// Shown before channel operations on a flake-managed system, where nix-channel1021// commands generally don't apply.1022pub fn flakeChannelNote() void {1023    p("{s}{s}note: using a flake system — channel commands may not apply{s}\n", .{ hdr(), c(DIM), c(RESET) });1024}10251026pub fn firstRunWritten(path: []const u8) void {1027    p("\n   {s}written to {s}{s}\n\n", .{ c(DIM), path, c(RESET) });1028}10291030pub fn firstRunSkipped() void {1031    p("\n   {s}skipping setup in non-interactive mode{s}\n", .{ c(DIM), c(RESET) });1032}