output.zig

32.1 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}135136pub fn printTeach(cmd: []const u8) void {137    if (teach_enabled) p("{s}{s}{s}\n", .{ teach_pfx(), cmd, c(RESET) });138}139140pub fn printSubstep(comptime fmt: []const u8, args: anytype) void {141    p("{s}", .{step()});142    p(fmt, args);143    p("\n", .{});144}145146// --- Confirmation prompt (returns true = yes) ---147148pub fn confirm(prompt: []const u8) bool {149    p("   {s}continue? [Y/n]  ", .{prompt});150    flush();151    var buf: [64]u8 = undefined;152    var i: usize = 0;153    while (i < buf.len) {154        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;155        if (n == 0) break;156        if (buf[i] == '\n') break;157        i += 1;158    }159    const input = std.mem.trim(u8, buf[0..i], " \t");160    if (input.len == 0) return true;161    return input[0] != 'n' and input[0] != 'N';162}163164// Like confirm, but defaults to NO on an empty answer — for prompts that touch165// system files, where a stray Enter should never trigger the action.166pub fn confirmDefaultNo(question: []const u8) bool {167    p("   {s} [y/N]  ", .{question});168    flush();169    var buf: [64]u8 = undefined;170    var i: usize = 0;171    while (i < buf.len) {172        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;173        if (n == 0) break;174        if (buf[i] == '\n') break;175        i += 1;176    }177    const input = std.mem.trim(u8, buf[0..i], " \t");178    if (input.len == 0) return false;179    return input[0] == 'y' or input[0] == 'Y';180}181182// --- Apply / rebuild ---183184pub fn applyStart(machine: []const u8) void {185    p("{s}{s}rebuilding {s}...\n", .{ KAO_COZY, hdr(), machine });186}187188// after_failure: true only when the previous apply this session failed and this189// one succeeded — the one moment that earns the excited kaomoji. Routine190// successes show no kaomoji.191pub fn applyDone(gen: u32, elapsed_ms: u64, after_failure: bool) void {192    const face = if (after_failure) KAO_EXCITED else "";193    const secs = @as(f64, @floatFromInt(elapsed_ms)) / 1000.0;194    if (elapsed_ms >= 1000) {195        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) });196    } else {197        p("{s}{s}generation {s}{d}{s}\n", .{ face, hdr(), c(BOLD), gen, c(RESET) });198    }199}200201pub fn applyFailed(translated: []const u8) void {202    p("{s}build failed\n", .{if (color_enabled) ERR_C else ERR_P});203    if (translated.len > 0) p("   {s}{s}{s}\n", .{ c(DIM), translated, c(RESET) });204    p("   {s}-> nina doctor{s}\n", .{ c(DIM), c(RESET) });205}206207pub fn applyDry(machine: []const u8) void {208    p("{s}dry run  {s}\n", .{ hdr(), machine });209}210211pub fn applyDryDone() void {212    p("{s}no changes applied\n", .{hdr()});213}214215// --- Check ---216217pub fn checkStart(machine: []const u8) void {218    p("{s}checking {s}...\n", .{ hdr(), machine });219}220221pub fn checkOk() void {222    p("{s}{s}ok{s}\n", .{ hdr(), c(GREEN), c(RESET) });223}224225pub fn checkFailed(msg: []const u8) void {226    p("{s}config invalid\n", .{if (color_enabled) ERR_C else ERR_P});227    if (msg.len > 0) p("   {s}{s}{s}\n", .{ c(DIM), msg, c(RESET) });228}229230// --- Back / go ---231232pub fn backStart(machine: []const u8, from: u32, to: u32) void {233    p("{s}rolling back  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, from, to });234}235236pub fn goStart(machine: []const u8, current: u32, target: u32) void {237    p("{s}switching  {s}  gen {d} -> gen {d}\n", .{ hdr(), machine, current, target });238}239240pub fn generationDone(n: u32) void {241    p("{s}done  gen {s}{d}{s}\n", .{ hdr(), c(BOLD), n, c(RESET) });242}243244// `back` has nothing older to roll back to. This is a clean stop, not a build245// failure — the rollback would otherwise surface nixos-rebuild's confusing246// 'no profile version older than the current' as a fake build error.247pub fn alreadyOldest() void {248    p("{s}already at the oldest generation\n", .{if (color_enabled) ERR_C else ERR_P});249}250251// Like generationDone but for `back` specifically — a successful rollback earns252// the gentle kaomoji. `go` keeps the plain generationDone line.253pub fn backDone(n: u32) void {254    p("{s}{s}done  gen {s}{d}{s}\n", .{ KAO_GENTLE, hdr(), c(BOLD), n, c(RESET) });255}256257// --- History ---258259pub fn historyHeader(machine: []const u8) void {260    p("{s}generations  {s}\n\n", .{ hdr(), machine });261}262263pub fn historyRow(gen: types.GenerationInfo) void {264    if (gen.current) {265        p("   {s}{d}{s}   {s}   {s}   {s}current{s}\n", .{ c(BOLD), gen.number, c(RESET), gen.date, gen.time, c(BOLD), c(RESET) });266    } else {267        p("   {s}{d}   {s}   {s}{s}\n", .{ c(DIM), gen.number, gen.date, gen.time, c(RESET) });268    }269}270271// --- Clean ---272273pub fn cleanStart(machine: []const u8, keep: u32, total: u32) void {274    p("{s}cleaning  {s}  keeping {d} of {d}\n", .{ hdr(), machine, keep, total });275}276277// Fewer generations than the keep limit — there's nothing to collect. Avoids the278// nonsensical 'keeping 5 of 1'.279pub fn cleanNothing(machine: []const u8, total: u32) void {280    p("{s}cleaning  {s}\n\n", .{ hdr(), machine });281    p("   only {d} generation{s} — nothing to remove.\n", .{ total, if (total == 1) "" else "s" });282}283284pub fn cleanDone() void {285    p("{s}{s}done\n", .{ KAO_CONTENT, hdr() });286}287288// --- Status ---289290pub fn statusHeader() void {291    p("{s}status\n\n", .{hdr()});292}293294pub fn statusRow(machine: []const u8, gen: u32, time: []const u8, size: []const u8, ok: bool) void {295    if (ok) {296        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) });297    } else {298        p("   {s}{s}   {s}unreachable{s}\n", .{ c(RED), machine, "", c(RESET) });299    }300}301302// --- Diff ---303304pub fn diffHeader(a: u32, b: u32, machine: []const u8) void {305    p("{s}gen {d} -> gen {d}  {s}\n\n", .{ hdr(), a, b, machine });306}307308pub fn diffRow(entry: types.DiffEntry) void {309    switch (entry.op) {310        .add => p("   {s}+{s} {s}   {s}\n", .{ c(GREEN), c(RESET), entry.package, entry.new_version orelse "" }),311        .remove => p("   {s}-{s} {s}   {s}\n", .{ c(RED), c(RESET), entry.package, entry.old_version orelse "" }),312        .change => p("   {s}^{s} {s}   {s} -> {s}\n", .{ c(CYAN), c(RESET), entry.package, entry.old_version orelse "", entry.new_version orelse "" }),313    }314}315316// --- Doctor ---317318pub fn doctorHeader(machine: []const u8) void {319    p("{s}diagnosing  {s}\n\n", .{ hdr(), machine });320}321322pub fn doctorRow(check: types.DoctorCheck) void {323    const status_str = switch (check.status) {324        .ok => if (color_enabled) GREEN ++ "ok" ++ RESET else "ok",325        .warn => if (color_enabled) YELLOW ++ "warn" ++ RESET else "warn",326        .fail => if (color_enabled) RED ++ "fail" ++ RESET else "fail",327    };328    const note_str = check.note orelse "";329    p("   {s:<16}  {s}   {s}\n", .{ check.name, status_str, note_str });330}331332pub fn doctorSummary(warnings: u32, failures: u32) void {333    if (failures > 0) {334        p("{s}{d} problems\n", .{ hdr(), failures });335    } else if (warnings > 0) {336        p("{s}{d} warnings\n", .{ hdr(), warnings });337    } else {338        p("{s}{s}{s}all good{s}\n", .{ KAO_HAPPY, hdr(), c(GREEN), c(RESET) });339    }340}341342// --- Update ---343344pub fn updateStart(machine: []const u8) void {345    p("{s}updating channels  {s}\n\n", .{ hdr(), machine });346}347348pub fn updateChannel(name: []const u8, old: ?[]const u8, new: ?[]const u8) void {349    if (old != null and new != null and !std.mem.eql(u8, old.?, new.?)) {350        p("   {s}   {s} -> {s}\n", .{ name, old.?, new.? });351    } else {352        p("   {s}   {s}no change{s}\n", .{ name, c(DIM), c(RESET) });353    }354}355356pub fn updateDone() void {357    p("\n{s}done\n", .{hdr()});358}359360// --- Upgrade ---361362pub fn upgradeStart(machine: []const u8) void {363    p("{s}upgrading  {s}\n", .{ hdr(), machine });364}365366// --- Log ---367368pub fn logHeader(machine: []const u8) void {369    p("{s}history  {s}\n\n", .{ hdr(), machine });370}371372pub fn logRow(date: []const u8, time: []const u8, action: []const u8, detail: []const u8) void {373    p("   {s}{s}  {s}{s}   {s:<16}  {s}\n", .{ c(DIM), date, time, c(RESET), action, detail });374}375376// --- Edit ---377378pub fn editOpen(path: []const u8, editor: []const u8) void {379    p("{s}opening {s}\n", .{ hdr(), path });380    printSubstep("{s}", .{editor});381    p("\n   {s}run nina check to validate before applying{s}\n", .{ c(DIM), c(RESET) });382}383384// --- Fmt ---385386pub fn fmtStart(path: []const u8) void {387    p("{s}formatting  {s}\n", .{ hdr(), path });388}389390pub fn fmtDone() void {391    p("{s}done\n", .{hdr()});392}393394pub fn fmtNeedsFormat() void {395    p("{s}needs formatting  {s}run nina fmt to fix{s}\n", .{ hdr(), c(DIM), c(RESET) });396}397398// --- Repl ---399400pub fn replStart() void {401    p("{s}nix repl  {s}nixpkgs loaded{s}  :q to exit\n", .{ hdr(), c(DIM), c(RESET) });402}403404// --- Develop ---405406pub fn developStart(pkgs: []const []const u8) void {407    p("{s}entering dev shell\n\n   ", .{hdr()});408    for (pkgs, 0..) |pkg, i| {409        if (i > 0) p("  ", .{});410        p("{s}", .{pkg});411    }412    p("\n\n   {s}-> type 'exit' to return{s}\n\n", .{ c(DIM), c(RESET) });413}414415pub fn developDone() void {416    p("{s}{s}back\n", .{ KAO_SLEEPY, hdr() });417}418419// --- Info ---420421pub fn infoHeader(machine: []const u8) void {422    p("{s}{s}\n\n", .{ hdr(), machine });423}424425pub fn infoRow(key: []const u8, val: []const u8) void {426    p("   {s:<12}  {s}\n", .{ key, val });427}428429// --- Boot ---430431pub fn bootHeader(machine: []const u8) void {432    p("{s}boot entries  {s}\n\n", .{ hdr(), machine });433}434435pub fn bootEntry(entry: types.BootEntry, idx: usize) void {436    if (entry.current) {437        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) });438    } else {439        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) });440    }441    _ = idx;442}443444// --- Service ---445446pub fn serviceListHeader(machine: []const u8) void {447    p("{s}services  {s}\n\n", .{ hdr(), machine });448}449450pub fn serviceRow(svc: types.ServiceInfo) void {451    const state_str = switch (svc.state) {452        .active => if (color_enabled) GREEN ++ "active" ++ RESET else "active",453        .failed => if (color_enabled) RED ++ "failed" ++ RESET else "failed",454        .inactive => "inactive",455        .unknown => "unknown",456    };457    const uptime = svc.uptime orelse "";458    p("   {s:<24}  {s:<14}  {s}\n", .{ svc.name, state_str, uptime });459}460461pub fn serviceVerb(verb: []const u8, name: []const u8, machine: []const u8) void {462    p("{s}{s} {s}  {s}\n", .{ hdr(), verb, name, machine });463}464465pub fn serviceDone() void {466    p("{s}done\n", .{hdr()});467}468469pub fn serviceLogsHeader(name: []const u8, n: u32, machine: []const u8) void {470    p("{s}{s}  last {d} lines  {s}\n\n", .{ hdr(), name, n, machine });471}472473// --- Store ---474475pub fn storeInfo(info: types.StoreInfo) void {476    p("{s}store\n\n", .{hdr()});477    p("   {s:<16}  {s}\n", .{ "total", info.total_size });478    p("   {s:<16}  {d} paths\n", .{ "live", info.live_paths });479    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) });480}481482// --- Channel ---483484pub fn channelListHeader(machine: []const u8) void {485    p("{s}channels  {s}\n\n", .{ hdr(), machine });486}487488pub fn channelRow(ch: types.ChannelInfo) void {489    p("   {s:<16}  {s}\n", .{ ch.name, ch.url });490}491492// --- Flake ---493494pub fn flakeUpdateStart() void {495    p("{s}updating inputs\n\n", .{hdr()});496}497498pub fn flakeInput(input: types.FlakeInput) void {499    if (input.changed) {500        const old = if (input.old_rev) |r| r[0..@min(7, r.len)] else "?";501        const new = if (input.new_rev) |r| r[0..@min(7, r.len)] else "?";502        p("   {s:<20}  {s} -> {s}\n", .{ input.name, old, new });503    } else {504        p("   {s:<20}  {s}no change{s}\n", .{ input.name, c(DIM), c(RESET) });505    }506}507508pub fn flakeLockWritten() void {509    p("\n{s}flake.lock written\n", .{hdr()});510}511512pub fn flakeValid() void {513    p("{s}{s}valid{s}\n", .{ hdr(), c(GREEN), c(RESET) });514}515516pub fn flakeCheckStart() void {517    p("{s}checking flake\n", .{hdr()});518}519520// --- Profile ---521522pub fn profileListHeader() void {523    p("{s}profile packages\n\n", .{hdr()});524}525526pub fn profileRow(attr: []const u8, pkg_version: []const u8, description: []const u8) void {527    p("   {s:<24}  {s:<12}  {s}\n", .{ attr, pkg_version, description });528}529530// --- Install / Remove / Try ---531532// Typo help for install: the query matched nothing, so suggest the closest real533// package name (pink) and let the caller confirm.534pub fn didYouMean(query: []const u8, suggestion: []const u8) void {535    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) });536}537538pub fn installStart(pkg: []const u8, path: types.InstallPath) void {539    const path_str = switch (path) {540        .profile => "profile",541        .system => "system",542    };543    p("{s}installing {s}{s}{s}  {s}\n", .{ hdr(), c(PINK), pkg, c(RESET), path_str });544}545546pub fn installDone(pkg: []const u8) void {547    p("{s}{s}{s}{s} installed  {s}available now{s}\n", .{ hdr(), c(PINK), pkg, c(RESET), c(DIM), c(RESET) });548}549550pub fn removeStart(pkg: []const u8) void {551    p("{s}removing {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });552}553554// Plain-language health summary. No kaomoji, no hearts — just the facts.555pub fn mood(machine: []const u8, state: []const u8, gen: u32, age: []const u8, size: []const u8) void {556    const healthy = std.mem.eql(u8, state, "running");557    const verdict = if (healthy) "all good" else state;558    const color = if (healthy) GREEN else YELLOW;559    const face = if (healthy) KAO_HAPPY else "";560    p("{s}{s}{s}  {s}{s}{s}\n", .{ face, hdr(), machine, c(color), verdict, c(RESET) });561    if (age.len > 0 or size.len > 0) {562        p("   generation {d}, last applied {s}, {s} system closure\n", .{ gen, age, size });563    } else {564        p("   generation {d}\n", .{gen});565    }566}567568pub fn installEditorPrompt(pkg: []const u8, config_path: []const u8, line: u32, editor: []const u8) void {569    p("{s}opening {s}  add {s}{s}{s} to systemPackages\n", .{ hdr(), config_path, c(PINK), pkg, c(RESET) });570    const cmd = std.fmt.allocPrint(std.heap.page_allocator, "{s} {s} +{d}", .{ editor, config_path, line }) catch editor;571    printSubstep("{s}", .{cmd});572    p("\n   {s}save and close when done{s}\n\n", .{ c(DIM), c(RESET) });573}574575pub fn installSelectPrompt(pkg: []const u8, pkg_version: []const u8) void {576    p("{s}{s}{s}{s}  {s}\n\n", .{ hdr(), c(PINK), pkg, c(RESET), pkg_version });577    p("   [i] profile install    {s}instant  no rebuild{s}\n", .{ c(DIM), c(RESET) });578    p("   [s] system install     {s}opens editor  requires apply{s}\n", .{ c(DIM), c(RESET) });579    p("   [t] try now            {s}exits when done{s}\n\n", .{ c(DIM), c(RESET) });580    p("   > ", .{});581    flush();582}583584pub fn tryStart(pkg: []const u8) void {585    p("{s}trying {s}{s}{s}  exit when done\n", .{ hdr(), c(PINK), pkg, c(RESET) });586}587588pub fn tryExitHint() void {589    p("   {s}-> type 'exit' to return{s}\n", .{ c(DIM), c(RESET) });590}591592pub fn tryDone() void {593    p("{s}{s}back\n", .{ KAO_SLEEPY, hdr() });594}595596// --- List ---597598pub fn listHeader(machine: []const u8) void {599    p("{s}packages  {s}\n\n", .{ hdr(), machine });600}601602pub fn listSection(title: []const u8) void {603    p("   {s}{s}{s}\n", .{ c(DIM), title, c(RESET) });604}605606// Padded name so the version column lines up into a clean two-column table.607pub fn listPkg(name: []const u8, pkg_version: []const u8) void {608    p("   {s}{s:<16}{s}  {s}{s}{s}\n", .{ c(PINK), name, c(RESET), c(DIM), pkg_version, c(RESET) });609}610611pub fn blankLine() void {612    p("\n", .{});613}614615// --- Hello ---616617pub fn hello(machines: []const types.Machine) void {618    p("{s}{s}nina\n\n", .{ KAO_FACE, hdr() });619    for (machines) |m| {620        const kind = if (m.local) "local" else "ssh";621        const detail = if (m.local) "default" else m.host orelse "";622        p("   {s}{s}{s}   {s}   {s}\n", .{ c(DIM), m.name, c(RESET), kind, detail });623    }624    p("\n", .{});625    const quick = [_][2][]const u8{626        .{ "apply",         "rebuild and switch" },627        .{ "search <q>",    "find packages" },628        .{ "install <pkg>", "add to profile or system" },629        .{ "status",        "machine health" },630        .{ "back",          "roll back one generation" },631        .{ "update",        "refresh channels" },632    };633    for (quick) |cmd| {634        p("   {s:<16}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });635    }636    p("\n", .{});637}638639// --- Help ---640641pub fn help() void {642    p("{s}nina  {s}NixOS Intuitive Navigation Assistant by Asha Software{s}\n\n", .{ hdr(), c(DIM), c(RESET) });643    const cmds = [_][2][]const u8{644        .{ "apply", "rebuild and switch" },645        .{ "back", "roll back one generation" },646        .{ "go <n>", "switch to generation n" },647        .{ "history", "list all generations" },648        .{ "clean", "remove old generations" },649        .{ "search <q>", "find packages" },650        .{ "install <pkg>", "add to profile or system" },651        .{ "remove <pkg>", "remove from profile or system" },652        .{ "try <pkg>", "test without installing" },653        .{ "list", "show installed packages" },654        .{ "edit", "open configuration.nix" },655        .{ "check", "validate config" },656        .{ "diff", "changes between generations" },657        .{ "status", "machine health" },658        .{ "update", "refresh channels" },659        .{ "upgrade", "update and rebuild" },660        .{ "log", "operation history" },661        .{ "doctor", "diagnose issues" },662        .{ "mood", "plain-language health" },663        .{ "develop", "enter dev shell" },664        .{ "flake", "flake management" },665        .{ "build", "build a package" },666        .{ "run", "run without installing" },667        .{ "service", "manage services" },668        .{ "store", "nix store tools" },669        .{ "channel", "manage channels" },670        .{ "profile", "user profile packages" },671        .{ "info", "system information" },672        .{ "boot", "boot entries" },673        .{ "fmt", "format configuration.nix" },674        .{ "repl", "nix repl with nixpkgs" },675        .{ "option <q>", "search nixos options" },676        .{ "pkg", "inspect packages" },677        .{ "pin", "pin flake inputs" },678        .{ "hash", "compute nix hash" },679        .{ "fetch", "fetch and hash a url" },680        .{ "goodbye",       "uninstall nina" },681        .{ "hello",        "list machines" },682        .{ "help",         "this message" },683    };684    for (cmds) |cmd| {685        p("   {s:<18}  {s}{s}{s}\n", .{ cmd[0], c(DIM), cmd[1], c(RESET) });686    }687    p("\n   {s}flags: --on <machine>  --dry  --check  --no-apply  --last <n>  --all  --json{s}\n", .{ c(DIM), c(RESET) });688}689690pub fn version() void {691    p("{s}nina  v{s}  zig 0.16  zero dependencies\n", .{ hdr(), nina_version.VERSION });692}693694// --- Search (text output before TUI) ---695696pub fn searchResult(pkg: types.NixPackage) void {697    p("   {s}{s}{s}   {s}{s}{s}   {s}\n", .{ c(PINK), pkg.pname, c(RESET), c(DIM), pkg.version, c(RESET), pkg.description });698}699700pub fn searchHeader(query: []const u8, count: usize) void {701    p("{s}search nixpkgs {s}  {s}{d} results{s}\n\n", .{ hdr(), query, c(DIM), count, c(RESET) });702}703704// --- Gen commands ---705706pub fn genCurrent(n: u32) void {707    p("{d}\n", .{n});708}709710pub fn done() void {711    p("{s}done\n", .{hdr()});712}713714pub fn runStart(pkg: []const u8) void {715    p("{s}running {s}{s}{s}\n", .{ hdr(), c(PINK), pkg, c(RESET) });716}717718pub fn buildStart(attr: []const u8) void {719    p("{s}building {s}\n", .{ hdr(), attr });720}721722pub fn buildDone() void {723    p("{s}done\n", .{hdr()});724}725726// --- Self-update (nina update) ---727728pub fn updateSelfStart() void {729    p("{s}checking for updates\n", .{hdr()});730}731732pub fn updateSelfCurrent(ver: []const u8) void {733    p("{s}{s}nina {s} is up to date{s}\n", .{ hdr(), c(GREEN), ver, c(RESET) });734}735736pub fn updateSelfAvailable(current: []const u8, latest: []const u8) void {737    p("{s}current  {s}\n", .{ step(), current });738    p("{s}latest   {s}{s}{s}\n", .{ step(), c(BOLD), latest, c(RESET) });739}740741pub fn updateSelfDownloading(ver: []const u8, platform: []const u8) void {742    p("{s}downloading nina {s} for {s}\n", .{ step(), ver, platform });743}744745pub fn updateSelfVerifying() void {746    p("{s}verifying checksum\n", .{step()});747}748749pub fn updateSelfInstalling(install_path: []const u8) void {750    p("{s}installing to {s}\n", .{ step(), install_path });751}752753pub fn updateSelfDone(old_ver: []const u8, new_ver: []const u8) void {754    p("{s}updated  {s} {s}→{s} {s}\n", .{ hdr(), old_ver, c(DIM), c(RESET), new_ver });755}756757pub fn updateSelfNoPlatform(platform: []const u8) void {758    p("{s}no pre-built binary for {s}\n", .{ hdr(), platform });759    p("{s}check kepr.uk/nina/releases for available platforms\n", .{step()});760}761762pub fn updateSelfNetworkError() void {763    p("{s}{s}\n", .{ if (color_enabled) WARN_C else WARN_P, "could not reach kepr.uk — check your connection" });764}765766pub fn updateSelfChecksumFailed() void {767    p("{s}checksum mismatch — download may be corrupt\n", .{if (color_enabled) ERR_C else ERR_P});768    p("{s}try again or download manually from kepr.uk/nina/releases\n", .{step()});769}770771pub fn updateSelfNixManaged(new_ver: []const u8) void {772    p("{s}upgrading to {s}{s}{s} via nix profile\n", .{ step(), c(BOLD), new_ver, c(RESET) });773}774775pub fn updateSelfNixFailed() void {776    p("{s}nix profile upgrade failed\n", .{if (color_enabled) ERR_C else ERR_P});777    p("{s}try manually: nix profile upgrade '.*nina.*'\n", .{step()});778}779780pub fn updateSelfNotInProfile() void {781    p("{s}nina is in the nix store but not found as a profile element\n", .{hdr()});782    p("{s}reinstall via 'nix profile add' to enable self-update\n", .{step()});783}784785// --- Goodbye / uninstall ---786787pub fn goodbyeStart() void {788    p("{s}uninstalling nina\n", .{hdr()});789}790791pub fn goodbyeFile(path: []const u8) void {792    p("{s}will remove {s}\n", .{ step(), path });793}794795pub fn goodbyeNix() void {796    p("{s}will remove nina from nix profile\n", .{step()});797    p("{s}command: nix profile remove nina\n", .{step()});798}799800pub fn goodbyeDone() void {801    p("{s}goodbye! see kepr.uk/nina to reinstall\n", .{hdr()});802}803804pub fn goodbyeFailed(msg: []const u8) void {805    p("{s}{s}\n", .{ if (color_enabled) ERR_C else ERR_P, msg });806}807808// --- Setup ---809810pub fn setupCheck() void {811    p("{s}checking nix features\n", .{hdr()});812}813814pub fn setupFeatures(nix_command: bool, flakes: bool) void {815    p("{s}nix-command  {s}{s}{s}\n", .{816        step(),817        if (nix_command) c(GREEN) else "",818        if (nix_command) "enabled" else "not enabled",819        if (nix_command) c(RESET) else "",820    });821    p("{s}flakes       {s}{s}{s}\n", .{822        step(),823        if (flakes) c(GREEN) else "",824        if (flakes) "enabled" else "not enabled",825        if (flakes) c(RESET) else "",826    });827}828829pub fn setupAllSet() void {830    p("{s}all set\n", .{hdr()});831}832833// Printed once, before the first search, when the nixpkgs registry still points834// at a remote URL. Flush so it lands before `nix registry pin` and any results.835pub fn pinningRegistry() void {836    p("{s}pinning nixpkgs for fast local search...\n", .{hdr()});837    flush();838}839840// --- Plain (non-tty) search rendering ---841// Color-gated equivalents of the raw-ANSI TUI widget, for piped/scripted search.842// Using the gated header + c() keeps ANSI out of non-tty output (NO_COLOR / pipes).843844pub fn searchPlainHeader(mode_str: []const u8, query: []const u8, count: u64) void {845    p("{s}search {s} {s}  {s}{d} results{s}\n", .{ hdr(), mode_str, query, c(DIM), count, c(RESET) });846}847848pub fn searchPlainNoResults() void {849    p("   no results\n", .{});850}851852pub fn searchPlainPackage(pname: []const u8, pkg_version: []const u8, description: []const u8, unfree: bool) void {853    if (unfree) {854        p("   {s}   {s}{s}{s}   {s}unfree{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), c(YELLOW), c(RESET), description });855    } else {856        p("   {s}   {s}{s}{s}   {s}\n", .{ pname, c(CYAN), pkg_version, c(RESET), description });857    }858}859860pub fn searchPlainOption(name: []const u8, type_str: []const u8) void {861    p("   {s}   {s}{s}{s}\n", .{ name, c(DIM), type_str, c(RESET) });862}863864pub fn searchEmptyQuery() void {865    p("{s}search needs a query  {s}e.g. nina search firefox{s}\n", .{ hdr(), c(DIM), c(RESET) });866}867868pub fn setupEnabling() void {869    p("{s}enabling experimental features\n", .{hdr()});870}871872pub fn setupDone(path: []const u8) void {873    p("{s}wrote {s}\n", .{ step(), path });874    p("{s}done  open a new shell to pick up the change\n", .{hdr()});875}876877// --- NixOS setup (declarative configuration.nix) ---878879pub fn setupNixosOffer(features_line: []const u8, conf_path: []const u8) void {880    p("{s}on NixOS these go in your system config\n", .{hdr()});881    p("   nina can add this line to {s}{s}{s}:\n\n", .{ c(DIM), conf_path, c(RESET) });882    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });883}884885pub fn setupNixosWrote(conf_path: []const u8) void {886    p("{s}added the line to {s}  {s}(backup: {s}.nina-bak){s}\n", .{ step(), conf_path, c(DIM), conf_path, c(RESET) });887    p("{s}now run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ hdr(), c(BOLD), c(RESET) });888}889890pub fn setupNixosManual(features_line: []const u8, conf_path: []const u8) void {891    p("{s}no problem — add this line inside the {s}{{ }}{s} in {s}:\n\n", .{ hdr(), c(DIM), c(RESET), conf_path });892    p("       {s}{s}{s}\n\n", .{ c(CYAN), features_line, c(RESET) });893    p("   then run {s}sudo nixos-rebuild switch{s} — then nina's ready\n", .{ c(BOLD), c(RESET) });894}895896pub fn setupNixosNeedsRebuild(conf_path: []const u8) void {897    p("{s}already declared in {s}\n", .{ hdr(), conf_path });898    p("   just run {s}sudo nixos-rebuild switch{s} to activate it\n", .{ c(BOLD), c(RESET) });899}900901pub fn pinDone(input: []const u8, commit: []const u8) void {902    p("{s}pinned {s} -> {s}\n", .{ hdr(), input, commit });903}904905pub fn unpinDone(input: []const u8) void {906    p("{s}unpinned {s}\n", .{ hdr(), input });907}908909pub fn hashResult(hash: []const u8) void {910    p("{s}\n", .{hash});911}912913pub fn fetchResult(hash: []const u8, url: []const u8) void {914    _ = url;915    p("{s}\n", .{hash});916}917918pub fn storeRepairStart() void {919    p("{s}repairing store\n", .{hdr()});920}921922pub fn storeVerifyStart() void {923    p("{s}verifying store\n", .{hdr()});924}925926pub fn storeGcDone(freed: []const u8) void {927    p("{s}freed {s}\n", .{ hdr(), freed });928}929930pub fn storePath(path: []const u8) void {931    p("{s}\n", .{path});932}933934pub fn pkgResult(key: []const u8, val: []const u8) void {935    p("   {s:<16}  {s}\n", .{ key, val });936}937938pub fn channelDone() void {939    p("{s}done\n", .{hdr()});940}941942pub fn flakeShowHeader(name: []const u8) void {943    p("{s}{s}\n\n", .{ hdr(), name });944}945946pub fn flakeShowEntry(kind: []const u8, name: []const u8, desc: []const u8) void {947    p("   {s:<12}  {s:<24}  {s}\n", .{ kind, name, desc });948}949950// --- First-run wizard ---951952pub fn firstRunBanner() void {953    p("{s}{s}nina \u{2014} first run\n\n", .{ KAO_FACE, hdr() });954}955956pub fn firstRunNoConfig() void {957    p("   no config found. let me get set up.\n\n", .{});958}959960// Print a prompt line and read the user's answer. Returns the default if the961// user presses Enter without typing anything. buf must be at least 256 bytes.962// Returns a slice into buf (or default if empty input).963pub fn firstRunPrompt(label: []const u8, default: []const u8, buf: []u8) []const u8 {964    p("   {s:<14} {s}> {s}", .{ label, c(DIM), c(RESET) });965    flush();966    var i: usize = 0;967    while (i < buf.len - 1) {968        const n = std.posix.read(std.posix.STDIN_FILENO, buf[i .. i + 1]) catch break;969        if (n == 0) break;970        if (buf[i] == '\n') break;971        i += 1;972    }973    const input = std.mem.trim(u8, buf[0..i], " \t\r");974    if (input.len == 0) {975        // Echo the default so the output shows what was chosen976        p("{s}{s}{s}\n", .{ c(DIM), default, c(RESET) });977        flush();978        return default;979    }980    return input;981}982983pub fn firstRunWritten(path: []const u8) void {984    p("\n   {s}written to {s}{s}\n\n", .{ c(DIM), path, c(RESET) });985}986987pub fn firstRunSkipped() void {988    p("\n   {s}skipping setup in non-interactive mode{s}\n", .{ c(DIM), c(RESET) });989}