output.zig

38.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}-> press Ctrl+C or 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}-> press Ctrl+C or 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        .{ "home apply",    "apply home config" },647        .{ "home back",     "roll back home config" },648        .{ "home history",  "list home generations" },649    };650    for (quick) |cmd| {651        p("   {s:<16}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });652    }653    p("\n", .{});654}655656// --- Help ---657658pub fn help() void {659    p("{s}nina  {s}NixOS Intuitive Navigation Assistant by Asha Software{s}\n\n", .{ hdr(), c(DIM), c(RESET) });660    const cmds = [_][2][]const u8{661        .{ "apply", "rebuild and switch" },662        .{ "back", "roll back one generation" },663        .{ "go <n>", "switch to generation n" },664        .{ "history", "list all generations" },665        .{ "clean", "remove old generations" },666        .{ "search <q>", "find packages" },667        .{ "install <pkg>", "add to profile or system" },668        .{ "remove <pkg>", "remove from profile or system" },669        .{ "try <pkg>", "test without installing" },670        .{ "list", "show installed packages" },671        .{ "edit", "open configuration.nix" },672        .{ "check", "validate config" },673        .{ "diff", "changes between generations" },674        .{ "status", "machine health" },675        .{ "update", "refresh channels" },676        .{ "upgrade", "update and rebuild" },677        .{ "log", "operation history" },678        .{ "doctor", "diagnose issues" },679        .{ "mood", "plain-language health" },680        .{ "develop", "enter dev shell" },681        .{ "flake", "flake management" },682        .{ "build", "build a package" },683        .{ "run", "run without installing" },684        .{ "service", "manage services" },685        .{ "store", "nix store tools" },686        .{ "channel", "manage channels" },687        .{ "profile", "user profile packages" },688        .{ "home", "home manager subcommands" },689        .{ "info", "system information" },690        .{ "boot", "boot entries" },691        .{ "fmt", "format configuration.nix" },692        .{ "repl", "nix repl with nixpkgs" },693        .{ "option <q>", "search nixos options" },694        .{ "pkg", "inspect packages" },695        .{ "why <pkg>", "what pulled a package in" },696        .{ "pin", "pin flake inputs" },697        .{ "hash", "compute nix hash" },698        .{ "fetch", "fetch and hash a url" },699        .{ "goodbye",       "uninstall nina" },700        .{ "hello",        "list machines" },701        .{ "help",         "this message" },702    };703    for (cmds) |cmd| {704        p("   {s:<18}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });705    }706    p("\n   {s}flags: --on <machine>  --dry  --check  --no-apply  --last <n>  --all  --json{s}\n", .{ c(DIM), c(RESET) });707}708709// Render a grouped command's subcommand list, shown when the group is invoked710// with no subcommand or an explicit `help`. Rows are {invocation, description}.711pub fn subcommandHelp(group: []const u8, rows: []const [2][]const u8, footer: ?[]const u8) void {712    p("{s}{s} subcommands\n\n", .{ hdr(), group });713    for (rows) |row| {714        p("   {s:<16}  {s}{s}{s}\n", .{ row[0], c(DIM), row[1], c(RESET) });715    }716    if (footer) |f| p("\n   {s}{s}{s}\n", .{ c(DIM), f, c(RESET) });717    p("\n   nina {s} help  {s}for this message{s}\n", .{ group, c(DIM), c(RESET) });718}719720pub fn version() void {721    p("{s}nina  v{s}  zig 0.16  zero dependencies\n", .{ hdr(), nina_version.VERSION });722}723724// --- Search (text output before TUI) ---725726pub fn searchResult(pkg: types.NixPackage) void {727    p("   {s}{s}{s}   {s}{s}{s}   {s}\n", .{ c(PINK), pkg.pname, c(RESET), c(DIM), pkg.version, c(RESET), pkg.description });728}729730pub fn searchHeader(query: []const u8, count: usize) void {731    p("{s}search nixpkgs {s}  {s}{d} results{s}\n\n", .{ hdr(), query, c(DIM), count, c(RESET) });732}733734// --- Gen commands ---735736pub fn genCurrent(n: u32) void {737    p("{d}\n", .{n});738}739740pub fn done() void {741    p("{s}done\n", .{hdr()});742}743744pub fn runStart(pkg: []const u8) void {745    p("{s}running {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });746}747748pub fn buildStart(attr: []const u8) void {749    p("{s}building {s}\n", .{ hdr(), attr });750}751752pub fn buildDone() void {753    p("{s}done\n", .{hdr()});754}755756// --- Self-update (nina update) ---757758pub fn updateSelfStart() void {759    p("{s}checking for updates\n", .{hdr()});760}761762pub fn updateSelfCurrent(ver: []const u8) void {763    p("{s}{s}nina {s} is up to date{s}\n", .{ hdr(), c(GREEN), ver, c(RESET) });764}765766pub fn updateSelfAvailable(current: []const u8, latest: []const u8) void {767    p("{s}current  {s}\n", .{ step(), current });768    p("{s}latest   {s}{s}{s}\n", .{ step(), c(BOLD), latest, c(RESET) });769}770771pub fn updateSelfDownloading(ver: []const u8, platform: []const u8) void {772    p("{s}downloading nina {s} for {s}\n", .{ step(), ver, platform });773}774775pub fn updateSelfVerifying() void {776    p("{s}verifying checksum\n", .{step()});777}778779pub fn updateSelfInstalling(install_path: []const u8) void {780    p("{s}installing to {s}\n", .{ step(), install_path });781}782783pub fn updateSelfDone(old_ver: []const u8, new_ver: []const u8) void {784    p("{s}updated  {s} {s}→{s} {s}\n", .{ hdr(), old_ver, c(DIM), c(RESET), new_ver });785}786787pub fn updateSelfNoPlatform(platform: []const u8) void {788    p("{s}no pre-built binary for {s}\n", .{ hdr(), platform });789    p("{s}check kepr.uk/nina/releases for available platforms\n", .{step()});790}791792pub fn updateSelfNetworkError() void {793    p("{s}{s}\n", .{ if (color_enabled) WARN_C else WARN_P, "could not reach kepr.uk — check your connection" });794}795796pub fn updateSelfChecksumFailed() void {797    p("{s}checksum mismatch — download may be corrupt\n", .{if (color_enabled) ERR_C else ERR_P});798    p("{s}try again or download manually from kepr.uk/nina/releases\n", .{step()});799}800801pub fn updateSelfNixManaged(new_ver: []const u8) void {802    p("{s}upgrading to {s}{s}{s} via nix profile\n", .{ step(), c(BOLD), new_ver, c(RESET) });803}804805pub fn updateSelfNixFailed() void {806    p("{s}nix profile upgrade failed\n", .{if (color_enabled) ERR_C else ERR_P});807    p("{s}try manually: nix profile upgrade '.*nina.*'\n", .{step()});808}809810pub fn updateSelfNotInProfile() void {811    p("{s}nina is in the nix store but not found as a profile element\n", .{hdr()});812    p("{s}reinstall via 'nix profile add' to enable self-update\n", .{step()});813}814815// --- Goodbye / uninstall ---816817pub fn goodbyeStart() void {818    p("{s}uninstalling nina\n", .{hdr()});819}820821pub fn goodbyeFile(path: []const u8) void {822    p("{s}will remove {s}\n", .{ step(), path });823}824825pub fn goodbyeNix() void {826    p("{s}will remove nina from nix profile\n", .{step()});827    p("{s}command: nix profile remove nina\n", .{step()});828}829830pub fn goodbyeDone() void {831    p("{s}goodbye! see kepr.uk/nina to reinstall\n", .{hdr()});832}833834pub fn goodbyeFailed(msg: []const u8) void {835    p("{s}{s}\n", .{ if (color_enabled) ERR_C else ERR_P, msg });836}837838// --- Setup ---839840pub fn setupCheck() void {841    p("{s}checking nix features\n", .{hdr()});842}843844pub fn setupFeatures(nix_command: bool, flakes: bool) void {845    p("{s}nix-command  {s}{s}{s}\n", .{846        step(),847        if (nix_command) c(GREEN) else "",848        if (nix_command) "enabled" else "not enabled",849        if (nix_command) c(RESET) else "",850    });851    p("{s}flakes       {s}{s}{s}\n", .{852        step(),853        if (flakes) c(GREEN) else "",854        if (flakes) "enabled" else "not enabled",855        if (flakes) c(RESET) else "",856    });857}858859pub fn setupAllSet() void {860    p("{s}all set\n", .{hdr()});861}862863// Printed once, before the first search, when the nixpkgs registry still points864// at a remote URL. Flush so it lands before `nix registry pin` and any results.865pub fn pinningRegistry() void {866    p("{s}pinning nixpkgs for fast local search...\n", .{hdr()});867    flush();868}869870// --- Plain (non-tty) search rendering ---871// Color-gated equivalents of the raw-ANSI TUI widget, for piped/scripted search.872// Using the gated header + c() keeps ANSI out of non-tty output (NO_COLOR / pipes).873874pub fn searchPlainHeader(mode_str: []const u8, query: []const u8, count: u64) void {875    p("{s}search {s} {s}  {s}{d} results{s}\n", .{ hdr(), mode_str, query, c(DIM), count, c(RESET) });876}877878pub fn searchPlainNoResults() void {879    p("   no results\n", .{});880}881882pub fn searchPlainPackage(pname: []const u8, pkg_version: []const u8, description: []const u8, unfree: bool) void {883    if (unfree) {884        p("   {s}   {s}{s}{s}   {s}unfree{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), c(YELLOW), c(RESET), description });885    } else {886        p("   {s}   {s}{s}{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), description });887    }888}889890pub fn searchPlainOption(name: []const u8, type_str: []const u8) void {891    p("   {s}   {s}{s}{s}\n", .{ name, c(DIM), type_str, c(RESET) });892}893894pub fn searchEmptyQuery() void {895    p("{s}search needs a query  {s}e.g. nina search firefox{s}\n", .{ hdr(), c(DIM), c(RESET) });896}897898pub fn setupEnabling() void {899    p("{s}enabling experimental features\n", .{hdr()});900}901902pub fn setupDone(path: []const u8) void {903    p("{s}wrote {s}\n", .{ step(), path });904    p("{s}done  open a new shell to pick up the change\n", .{hdr()});905}906907// --- NixOS setup (declarative configuration.nix) ---908909pub fn setupNixosOffer(features_line: []const u8, conf_path: []const u8) void {910    p("{s}on NixOS these go in your system config\n", .{hdr()});911    p("   nina can add this line to {s}{s}{s}:\n\n", .{ c(DIM), conf_path, c(RESET) });912    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });913}914915pub fn setupNixosWrote(conf_path: []const u8) void {916    p("{s}added the line to {s}  {s}(backup: {s}.nina-bak){s}\n", .{ step(), conf_path, c(DIM), conf_path, c(RESET) });917    p("{s}now run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ hdr(), c(BOLD), c(RESET) });918}919920pub fn setupNixosManual(features_line: []const u8, conf_path: []const u8) void {921    p("{s}no problem — add this line inside the {s}{{ }}{s} in {s}:\n\n", .{ hdr(), c(DIM), c(RESET), conf_path });922    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });923    p("   then run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ c(BOLD), c(RESET) });924}925926pub fn setupNixosNeedsRebuild(conf_path: []const u8) void {927    p("{s}already declared in {s}\n", .{ hdr(), conf_path });928    p("   just run {s}sudo nixos-rebuild switch{s} to activate it\n", .{ c(BOLD), c(RESET) });929}930931pub fn pinDone(input: []const u8, commit: []const u8) void {932    p("{s}pinned {s} -> {s}\n", .{ hdr(), input, commit });933}934935pub fn unpinDone(input: []const u8) void {936    p("{s}unpinned {s}\n", .{ hdr(), input });937}938939pub fn hashResult(hash: []const u8) void {940    p("{s}\n", .{hash});941}942943pub fn fetchResult(hash: []const u8, url: []const u8) void {944    _ = url;945    p("{s}\n", .{hash});946}947948pub fn storeRepairStart() void {949    p("{s}repairing store\n", .{hdr()});950}951952pub fn storeVerifyStart() void {953    p("{s}verifying store\n", .{hdr()});954}955956pub fn storeGcDone(freed: []const u8) void {957    p("{s}freed {s}\n", .{ hdr(), freed });958}959960pub fn storePath(path: []const u8) void {961    p("{s}\n", .{path});962}963964pub fn pkgResult(key: []const u8, val: []const u8) void {965    p("   {s:<16}  {s}\n", .{ key, val });966}967968pub fn channelDone() void {969    p("{s}done\n", .{hdr()});970}971972pub fn flakeShowHeader(name: []const u8) void {973    p("{s}{s}\n\n", .{ hdr(), name });974}975976pub fn flakeShowEntry(kind: []const u8, name: []const u8, desc: []const u8) void {977    p("   {s:<12}  {s:<24}  {s}\n", .{ kind, name, desc });978}979980// --- Home Manager ---981982pub fn homeNotInstalled() void {983    p("{s}home manager not detected  {s}nothing to do{s}\n", .{ hdr(), c(DIM), c(RESET) });984}985986// HM is a NixOS/flake module — rebuilt by nixos-rebuild, not the standalone CLI.987pub fn homeModuleManaged() void {988    p("{s}home manager is managed by your system config\n", .{hdr()});989    p("   {s}-> run {s}nina apply{s}{s} to rebuild both together{s}\n", .{ c(CYAN), c(BOLD), c(RESET), c(CYAN), c(RESET) });990}991992pub fn homeApplyStart(machine: []const u8) void {993    p("{s}{s}applying home config  {s}\n", .{ KAO_COZY, hdr(), machine });994}995996pub fn homeApplyDone(gen: u32, elapsed_ms: u64) void {997    const secs = @as(f64, @floatFromInt(elapsed_ms)) / 1000.0;998    // gen 0 means the post-switch generation re-read failed — the switch itself999    // succeeded, so report success without a misleading "generation 0".1000    if (gen == 0) {1001        if (elapsed_ms >= 1000) {1002            p("{s}done  {s}[{d:.1}s]{s}\n", .{ hdr(), c(DIM), secs, c(RESET) });1003        } else {1004            p("{s}done\n", .{hdr()});1005        }1006        return;1007    }1008    if (elapsed_ms >= 1000) {1009        p("{s}generation {s}{d}{s}  {s}[{d:.1}s]{s}\n", .{ hdr(), c(BOLD), gen, c(RESET), c(DIM), secs, c(RESET) });1010    } else {1011        p("{s}generation {s}{d}{s}\n", .{ hdr(), c(BOLD), gen, c(RESET) });1012    }1013}10141015// `home` was invoked against a remote machine. Detection + flake-ref are1016// local-only, so we don't act on a remote — point the user at the local run.1017pub fn homeLocalOnly(machine: []const u8) void {1018    p("{s}home manager commands run on the local machine only\n", .{hdr()});1019    p("   {s}-> '{s}' is remote; run nina home on that machine directly{s}\n", .{ c(DIM), machine, c(RESET) });1020}10211022pub fn homeApplyDry(machine: []const u8) void {1023    p("{s}home dry run  {s}\n", .{ hdr(), machine });1024}10251026pub fn homeApplyDryDone() void {1027    p("{s}{s}ok{s}  no changes applied\n", .{ hdr(), c(GREEN), c(RESET) });1028}10291030pub fn homeBackStart(machine: []const u8, from: u32, to: u32) void {1031    p("{s}rolling back home config  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, from, to });1032}10331034pub fn homeBackDone(n: u32) void {1035    p("{s}{s}done  gen {s}{d}{s}\n", .{ KAO_GENTLE, hdr(), c(BOLD), n, c(RESET) });1036}10371038pub fn homeHistoryHeader(machine: []const u8) void {1039    p("{s}home generations  {s}\n\n", .{ hdr(), machine });1040}10411042pub fn homeHistoryRow(number: u32, date: []const u8, time: []const u8, current: bool) void {1043    if (current) {1044        p("   {s}{d}{s}   {s}   {s}   {s}current{s}\n", .{ c(BOLD), number, c(RESET), date, time, c(BOLD), c(RESET) });1045    } else {1046        p("   {s}{d}   {s}   {s}{s}\n", .{ c(DIM), number, date, time, c(RESET) });1047    }1048}10491050pub fn homeEditOpen(path: []const u8, editor: []const u8) void {1051    p("{s}opening {s}\n", .{ hdr(), path });1052    printSubstep("{s}", .{editor});1053}10541055pub fn homeCheckStart(machine: []const u8) void {1056    p("{s}checking home config  {s}\n", .{ hdr(), machine });1057}10581059pub fn homeCheckOk() void {1060    p("{s}{s}ok{s}\n", .{ hdr(), c(GREEN), c(RESET) });1061}10621063pub fn homeDiffHeader(a: u32, b: u32, machine: []const u8) void {1064    p("{s}home gen {d} -> gen {d}  {s}\n\n", .{ hdr(), a, b, machine });1065}10661067pub fn homeNothingToDiff() void {1068    p("{s}only one home generation — nothing to diff yet\n", .{hdr()});1069}10701071pub fn homePackagesHeader(machine: []const u8) void {1072    p("{s}home packages  {s}\n\n", .{ hdr(), machine });1073}10741075// --- First-run wizard ---10761077pub fn firstRunBanner() void {1078    p("{s}{s}nina \u{2014} first run\n\n", .{ KAO_FACE, hdr() });1079}10801081pub fn firstRunNoConfig() void {1082    p("   no config found. let me get set up.\n\n", .{});1083}10841085// Print a prompt line and read the user's answer. Returns the default if the1086// user presses Enter without typing anything. buf must be at least 256 bytes.1087// Returns a slice into buf (or default if empty input).1088pub fn firstRunPrompt(label: []const u8, default: []const u8, buf: []u8) []const u8 {1089    p("   {s:<14} {s}> {s}", .{ label, c(DIM), c(RESET) });1090    flush();1091    var i: usize = 0;1092    while (i < buf.len - 1) {1093        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;1094        if (n == 0) break;1095        if (buf[i] == '\n') break;1096        i += 1;1097    }1098    const input = std.mem.trim(u8, buf[0..i], " \t\r");1099    if (input.len == 0) {1100        // Echo the default so the output shows what was chosen1101        p("{s}{s}{s}\n", .{ c(DIM), default, c(RESET) });1102        flush();1103        return default;1104    }1105    return input;1106}11071108pub fn firstRunScanning() void {1109    p("\n   {s}:: scanning for config...{s}\n", .{ c(DIM), c(RESET) });1110}11111112// Report what the scan found at /etc/nixos, noting flake vs channel.1113pub fn firstRunDetected(path: []const u8, is_flake: bool) void {1114    const kind = if (is_flake) "flake-based system" else "channel-based system";1115    p("   {s}-> found {s}{s}   {s}({s}){s}\n\n", .{ c(CYAN), path, c(RESET), c(DIM), kind, c(RESET) });1116}11171118pub fn firstRunNoneFound() void {1119    p("   {s}-> nothing found at /etc/nixos{s}\n\n", .{ c(DIM), c(RESET) });1120}11211122// Prompt with a pre-filled default shown in brackets. Empty input accepts the1123// default. When `detected` and a default is present, note that enter confirms.1124pub fn firstRunPromptDefault(label: []const u8, default: []const u8, detected: bool, buf: []u8) []const u8 {1125    if (default.len > 0) {1126        p("   {s:<14} {s}[{s}]{s} > ", .{ label, c(DIM), default, c(RESET) });1127        if (detected) p("{s}enter to confirm{s} ", .{ c(DIM), c(RESET) });1128    } else {1129        p("   {s:<14} {s}> {s}", .{ label, c(DIM), c(RESET) });1130    }1131    flush();1132    var i: usize = 0;1133    while (i < buf.len - 1) {1134        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;1135        if (n == 0) break;1136        if (buf[i] == '\n') break;1137        i += 1;1138    }1139    const input = std.mem.trim(u8, buf[0..i], " \t\r");1140    if (input.len == 0) {1141        p("{s}{s}{s}\n", .{ c(DIM), default, c(RESET) });1142        flush();1143        return default;1144    }1145    return input;1146}11471148// Shown before channel operations on a flake-managed system, where nix-channel1149// commands generally don't apply.1150pub fn flakeChannelNote() void {1151    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) });1152}11531154pub fn firstRunWritten(path: []const u8) void {1155    p("\n   {s}written to {s}{s}\n\n", .{ c(DIM), path, c(RESET) });1156}11571158pub fn firstRunSkipped() void {1159    p("\n   {s}skipping setup in non-interactive mode{s}\n", .{ c(DIM), c(RESET) });1160}