output.zig

36.6 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        .{ "why <pkg>", "what pulled a package in" },683        .{ "pin", "pin flake inputs" },684        .{ "hash", "compute nix hash" },685        .{ "fetch", "fetch and hash a url" },686        .{ "goodbye",       "uninstall nina" },687        .{ "hello",        "list machines" },688        .{ "help",         "this message" },689    };690    for (cmds) |cmd| {691        p("   {s:<18}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });692    }693    p("\n   {s}flags: --on <machine>  --dry  --check  --no-apply  --last <n>  --all  --json{s}\n", .{ c(DIM), c(RESET) });694}695696// Render a grouped command's subcommand list, shown when the group is invoked697// with no subcommand or an explicit `help`. Rows are {invocation, description}.698pub fn subcommandHelp(group: []const u8, rows: []const [2][]const u8, footer: ?[]const u8) void {699    p("{s}{s} subcommands\n\n", .{ hdr(), group });700    for (rows) |row| {701        p("   {s:<16}  {s}{s}{s}\n", .{ row[0], c(DIM), row[1], c(RESET) });702    }703    if (footer) |f| p("\n   {s}{s}{s}\n", .{ c(DIM), f, c(RESET) });704    p("\n   nina {s} help  {s}for this message{s}\n", .{ group, c(DIM), c(RESET) });705}706707pub fn version() void {708    p("{s}nina  v{s}  zig 0.16  zero dependencies\n", .{ hdr(), nina_version.VERSION });709}710711// --- Search (text output before TUI) ---712713pub fn searchResult(pkg: types.NixPackage) void {714    p("   {s}{s}{s}   {s}{s}{s}   {s}\n", .{ c(PINK), pkg.pname, c(RESET), c(DIM), pkg.version, c(RESET), pkg.description });715}716717pub fn searchHeader(query: []const u8, count: usize) void {718    p("{s}search nixpkgs {s}  {s}{d} results{s}\n\n", .{ hdr(), query, c(DIM), count, c(RESET) });719}720721// --- Gen commands ---722723pub fn genCurrent(n: u32) void {724    p("{d}\n", .{n});725}726727pub fn done() void {728    p("{s}done\n", .{hdr()});729}730731pub fn runStart(pkg: []const u8) void {732    p("{s}running {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });733}734735pub fn buildStart(attr: []const u8) void {736    p("{s}building {s}\n", .{ hdr(), attr });737}738739pub fn buildDone() void {740    p("{s}done\n", .{hdr()});741}742743// --- Self-update (nina update) ---744745pub fn updateSelfStart() void {746    p("{s}checking for updates\n", .{hdr()});747}748749pub fn updateSelfCurrent(ver: []const u8) void {750    p("{s}{s}nina {s} is up to date{s}\n", .{ hdr(), c(GREEN), ver, c(RESET) });751}752753pub fn updateSelfAvailable(current: []const u8, latest: []const u8) void {754    p("{s}current  {s}\n", .{ step(), current });755    p("{s}latest   {s}{s}{s}\n", .{ step(), c(BOLD), latest, c(RESET) });756}757758pub fn updateSelfDownloading(ver: []const u8, platform: []const u8) void {759    p("{s}downloading nina {s} for {s}\n", .{ step(), ver, platform });760}761762pub fn updateSelfVerifying() void {763    p("{s}verifying checksum\n", .{step()});764}765766pub fn updateSelfInstalling(install_path: []const u8) void {767    p("{s}installing to {s}\n", .{ step(), install_path });768}769770pub fn updateSelfDone(old_ver: []const u8, new_ver: []const u8) void {771    p("{s}updated  {s} {s}→{s} {s}\n", .{ hdr(), old_ver, c(DIM), c(RESET), new_ver });772}773774pub fn updateSelfNoPlatform(platform: []const u8) void {775    p("{s}no pre-built binary for {s}\n", .{ hdr(), platform });776    p("{s}check kepr.uk/nina/releases for available platforms\n", .{step()});777}778779pub fn updateSelfNetworkError() void {780    p("{s}{s}\n", .{ if (color_enabled) WARN_C else WARN_P, "could not reach kepr.uk — check your connection" });781}782783pub fn updateSelfChecksumFailed() void {784    p("{s}checksum mismatch — download may be corrupt\n", .{if (color_enabled) ERR_C else ERR_P});785    p("{s}try again or download manually from kepr.uk/nina/releases\n", .{step()});786}787788pub fn updateSelfNixManaged(new_ver: []const u8) void {789    p("{s}upgrading to {s}{s}{s} via nix profile\n", .{ step(), c(BOLD), new_ver, c(RESET) });790}791792pub fn updateSelfNixFailed() void {793    p("{s}nix profile upgrade failed\n", .{if (color_enabled) ERR_C else ERR_P});794    p("{s}try manually: nix profile upgrade '.*nina.*'\n", .{step()});795}796797pub fn updateSelfNotInProfile() void {798    p("{s}nina is in the nix store but not found as a profile element\n", .{hdr()});799    p("{s}reinstall via 'nix profile add' to enable self-update\n", .{step()});800}801802// --- Goodbye / uninstall ---803804pub fn goodbyeStart() void {805    p("{s}uninstalling nina\n", .{hdr()});806}807808pub fn goodbyeFile(path: []const u8) void {809    p("{s}will remove {s}\n", .{ step(), path });810}811812pub fn goodbyeNix() void {813    p("{s}will remove nina from nix profile\n", .{step()});814    p("{s}command: nix profile remove nina\n", .{step()});815}816817pub fn goodbyeDone() void {818    p("{s}goodbye! see kepr.uk/nina to reinstall\n", .{hdr()});819}820821pub fn goodbyeFailed(msg: []const u8) void {822    p("{s}{s}\n", .{ if (color_enabled) ERR_C else ERR_P, msg });823}824825// --- Setup ---826827pub fn setupCheck() void {828    p("{s}checking nix features\n", .{hdr()});829}830831pub fn setupFeatures(nix_command: bool, flakes: bool) void {832    p("{s}nix-command  {s}{s}{s}\n", .{833        step(),834        if (nix_command) c(GREEN) else "",835        if (nix_command) "enabled" else "not enabled",836        if (nix_command) c(RESET) else "",837    });838    p("{s}flakes       {s}{s}{s}\n", .{839        step(),840        if (flakes) c(GREEN) else "",841        if (flakes) "enabled" else "not enabled",842        if (flakes) c(RESET) else "",843    });844}845846pub fn setupAllSet() void {847    p("{s}all set\n", .{hdr()});848}849850// Printed once, before the first search, when the nixpkgs registry still points851// at a remote URL. Flush so it lands before `nix registry pin` and any results.852pub fn pinningRegistry() void {853    p("{s}pinning nixpkgs for fast local search...\n", .{hdr()});854    flush();855}856857// --- Plain (non-tty) search rendering ---858// Color-gated equivalents of the raw-ANSI TUI widget, for piped/scripted search.859// Using the gated header + c() keeps ANSI out of non-tty output (NO_COLOR / pipes).860861pub fn searchPlainHeader(mode_str: []const u8, query: []const u8, count: u64) void {862    p("{s}search {s} {s}  {s}{d} results{s}\n", .{ hdr(), mode_str, query, c(DIM), count, c(RESET) });863}864865pub fn searchPlainNoResults() void {866    p("   no results\n", .{});867}868869pub fn searchPlainPackage(pname: []const u8, pkg_version: []const u8, description: []const u8, unfree: bool) void {870    if (unfree) {871        p("   {s}   {s}{s}{s}   {s}unfree{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), c(YELLOW), c(RESET), description });872    } else {873        p("   {s}   {s}{s}{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), description });874    }875}876877pub fn searchPlainOption(name: []const u8, type_str: []const u8) void {878    p("   {s}   {s}{s}{s}\n", .{ name, c(DIM), type_str, c(RESET) });879}880881pub fn searchEmptyQuery() void {882    p("{s}search needs a query  {s}e.g. nina search firefox{s}\n", .{ hdr(), c(DIM), c(RESET) });883}884885pub fn setupEnabling() void {886    p("{s}enabling experimental features\n", .{hdr()});887}888889pub fn setupDone(path: []const u8) void {890    p("{s}wrote {s}\n", .{ step(), path });891    p("{s}done  open a new shell to pick up the change\n", .{hdr()});892}893894// --- NixOS setup (declarative configuration.nix) ---895896pub fn setupNixosOffer(features_line: []const u8, conf_path: []const u8) void {897    p("{s}on NixOS these go in your system config\n", .{hdr()});898    p("   nina can add this line to {s}{s}{s}:\n\n", .{ c(DIM), conf_path, c(RESET) });899    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });900}901902pub fn setupNixosWrote(conf_path: []const u8) void {903    p("{s}added the line to {s}  {s}(backup: {s}.nina-bak){s}\n", .{ step(), conf_path, c(DIM), conf_path, c(RESET) });904    p("{s}now run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ hdr(), c(BOLD), c(RESET) });905}906907pub fn setupNixosManual(features_line: []const u8, conf_path: []const u8) void {908    p("{s}no problem — add this line inside the {s}{{ }}{s} in {s}:\n\n", .{ hdr(), c(DIM), c(RESET), conf_path });909    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });910    p("   then run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ c(BOLD), c(RESET) });911}912913pub fn setupNixosNeedsRebuild(conf_path: []const u8) void {914    p("{s}already declared in {s}\n", .{ hdr(), conf_path });915    p("   just run {s}sudo nixos-rebuild switch{s} to activate it\n", .{ c(BOLD), c(RESET) });916}917918pub fn pinDone(input: []const u8, commit: []const u8) void {919    p("{s}pinned {s} -> {s}\n", .{ hdr(), input, commit });920}921922pub fn unpinDone(input: []const u8) void {923    p("{s}unpinned {s}\n", .{ hdr(), input });924}925926pub fn hashResult(hash: []const u8) void {927    p("{s}\n", .{hash});928}929930pub fn fetchResult(hash: []const u8, url: []const u8) void {931    _ = url;932    p("{s}\n", .{hash});933}934935pub fn storeRepairStart() void {936    p("{s}repairing store\n", .{hdr()});937}938939pub fn storeVerifyStart() void {940    p("{s}verifying store\n", .{hdr()});941}942943pub fn storeGcDone(freed: []const u8) void {944    p("{s}freed {s}\n", .{ hdr(), freed });945}946947pub fn storePath(path: []const u8) void {948    p("{s}\n", .{path});949}950951pub fn pkgResult(key: []const u8, val: []const u8) void {952    p("   {s:<16}  {s}\n", .{ key, val });953}954955pub fn channelDone() void {956    p("{s}done\n", .{hdr()});957}958959pub fn flakeShowHeader(name: []const u8) void {960    p("{s}{s}\n\n", .{ hdr(), name });961}962963pub fn flakeShowEntry(kind: []const u8, name: []const u8, desc: []const u8) void {964    p("   {s:<12}  {s:<24}  {s}\n", .{ kind, name, desc });965}966967// --- Home Manager ---968969pub fn homeNotInstalled() void {970    p("{s}home manager not detected  {s}nothing to do{s}\n", .{ hdr(), c(DIM), c(RESET) });971}972973// HM is a NixOS/flake module — rebuilt by nixos-rebuild, not the standalone CLI.974pub fn homeModuleManaged() void {975    p("{s}home manager is managed by your system config\n", .{hdr()});976    p("   {s}-> run {s}nina apply{s}{s} to rebuild both together{s}\n", .{ c(CYAN), c(BOLD), c(RESET), c(CYAN), c(RESET) });977}978979pub fn homeApplyStart(machine: []const u8) void {980    p("{s}{s}applying home config  {s}\n", .{ KAO_COZY, hdr(), machine });981}982983pub fn homeApplyDone(gen: u32, elapsed_ms: u64) void {984    const secs = @as(f64, @floatFromInt(elapsed_ms)) / 1000.0;985    if (elapsed_ms >= 1000) {986        p("{s}generation {s}{d}{s}  {s}[{d:.1}s]{s}\n", .{ hdr(), c(BOLD), gen, c(RESET), c(DIM), secs, c(RESET) });987    } else {988        p("{s}generation {s}{d}{s}\n", .{ hdr(), c(BOLD), gen, c(RESET) });989    }990}991992pub fn homeApplyDry(machine: []const u8) void {993    p("{s}home dry run  {s}\n", .{ hdr(), machine });994}995996pub fn homeApplyDryDone() void {997    p("{s}{s}ok{s}  no changes applied\n", .{ hdr(), c(GREEN), c(RESET) });998}9991000pub fn homeBackStart(machine: []const u8, from: u32, to: u32) void {1001    p("{s}rolling back home config  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, from, to });1002}10031004pub fn homeBackDone(n: u32) void {1005    p("{s}{s}done  gen {s}{d}{s}\n", .{ KAO_GENTLE, hdr(), c(BOLD), n, c(RESET) });1006}10071008pub fn homeHistoryHeader(machine: []const u8) void {1009    p("{s}home generations  {s}\n\n", .{ hdr(), machine });1010}10111012pub fn homeHistoryRow(number: u32, date: []const u8, time: []const u8, current: bool) void {1013    if (current) {1014        p("   {s}{d}{s}   {s}   {s}   {s}current{s}\n", .{ c(BOLD), number, c(RESET), date, time, c(BOLD), c(RESET) });1015    } else {1016        p("   {s}{d}   {s}   {s}{s}\n", .{ c(DIM), number, date, time, c(RESET) });1017    }1018}10191020pub fn homeEditOpen(path: []const u8, editor: []const u8) void {1021    p("{s}opening {s}\n", .{ hdr(), path });1022    printSubstep("{s}", .{editor});1023}10241025pub fn homeCheckStart(machine: []const u8) void {1026    p("{s}checking home config  {s}\n", .{ hdr(), machine });1027}10281029pub fn homeCheckOk() void {1030    p("{s}{s}ok{s}\n", .{ hdr(), c(GREEN), c(RESET) });1031}10321033pub fn homeDiffHeader(a: u32, b: u32, machine: []const u8) void {1034    p("{s}home gen {d} -> gen {d}  {s}\n\n", .{ hdr(), a, b, machine });1035}10361037pub fn homePackagesHeader(machine: []const u8) void {1038    p("{s}home packages  {s}\n\n", .{ hdr(), machine });1039}10401041// --- First-run wizard ---10421043pub fn firstRunBanner() void {1044    p("{s}{s}nina \u{2014} first run\n\n", .{ KAO_FACE, hdr() });1045}10461047pub fn firstRunNoConfig() void {1048    p("   no config found. let me get set up.\n\n", .{});1049}10501051// Print a prompt line and read the user's answer. Returns the default if the1052// user presses Enter without typing anything. buf must be at least 256 bytes.1053// Returns a slice into buf (or default if empty input).1054pub fn firstRunPrompt(label: []const u8, default: []const u8, buf: []u8) []const u8 {1055    p("   {s:<14} {s}> {s}", .{ label, c(DIM), c(RESET) });1056    flush();1057    var i: usize = 0;1058    while (i < buf.len - 1) {1059        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;1060        if (n == 0) break;1061        if (buf[i] == '\n') break;1062        i += 1;1063    }1064    const input = std.mem.trim(u8, buf[0..i], " \t\r");1065    if (input.len == 0) {1066        // Echo the default so the output shows what was chosen1067        p("{s}{s}{s}\n", .{ c(DIM), default, c(RESET) });1068        flush();1069        return default;1070    }1071    return input;1072}10731074// Ask whether the system is flake-based or channel-based. Returns true for1075// flakes. Defaults to channels (Enter or anything but '2'), echoing the choice.1076pub fn firstRunManageType() bool {1077    p("\n   how do you manage your system?\n", .{});1078    p("   {s}[1]{s} nixos channels (classic)\n", .{ c(DIM), c(RESET) });1079    p("   {s}[2]{s} nix flakes\n\n", .{ c(DIM), c(RESET) });1080    p("   {s}> {s}", .{ c(DIM), c(RESET) });1081    flush();1082    var buf: [64]u8 = undefined;1083    var i: usize = 0;1084    while (i < buf.len - 1) {1085        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;1086        if (n == 0) break;1087        if (buf[i] == '\n') break;1088        i += 1;1089    }1090    const input = std.mem.trim(u8, buf[0..i], " \t\r");1091    const flakes = input.len > 0 and input[0] == '2';1092    p("{s}{s}{s}\n", .{ c(DIM), if (flakes) "nix flakes" else "nixos channels", c(RESET) });1093    return flakes;1094}10951096// Shown before channel operations on a flake-managed system, where nix-channel1097// commands generally don't apply.1098pub fn flakeChannelNote() void {1099    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) });1100}11011102pub fn firstRunWritten(path: []const u8) void {1103    p("\n   {s}written to {s}{s}\n\n", .{ c(DIM), path, c(RESET) });1104}11051106pub fn firstRunSkipped() void {1107    p("\n   {s}skipping setup in non-interactive mode{s}\n", .{ c(DIM), c(RESET) });1108}