Skip to main content

robonix_cli/
output.rs

1// SPDX-License-Identifier: MulanPSL-2.0
2// Output Module
3//
4// Output formatting and display utilities for robonix-cli
5
6use colored::*;
7use std::io::{self, Write};
8use std::sync::OnceLock;
9use std::sync::atomic::{AtomicBool, Ordering};
10use std::time::Instant;
11
12/// Monotonic origin for `[ssss.mmm]` boot-line timestamps. Initialised on
13/// the first call to `boot_now()` (i.e. when the user actually starts a
14/// boot run); subsequent calls measure from that origin so the log reads
15/// like a kernel ring buffer / dmesg trace.
16static BOOT_T0: OnceLock<Instant> = OnceLock::new();
17static BOOT_VERBOSE: AtomicBool = AtomicBool::new(false);
18
19pub fn set_boot_verbose(verbose: bool) {
20    BOOT_VERBOSE.store(verbose, Ordering::Relaxed);
21}
22
23pub fn boot_verbose() -> bool {
24    BOOT_VERBOSE.load(Ordering::Relaxed)
25}
26
27fn clear_progress_prefix() -> &'static str {
28    if boot_verbose() { "" } else { "\r\x1b[K" }
29}
30
31/// Formatted `[ssss.mmm]` prefix relative to BOOT_T0. Width is fixed at
32/// 12 chars (`[1234.567]`) — five-digit boots are unrealistic and we'd
33/// rather wrap than re-jitter the column on long deploys.
34fn boot_now() -> String {
35    let t0 = BOOT_T0.get_or_init(Instant::now);
36    let elapsed = t0.elapsed().as_secs_f64();
37    format!("[{elapsed:>8.3}]")
38}
39
40/// Force-init BOOT_T0 to "now" so subsequent boot lines time from this
41/// instant. Call once at the top of a deploy/boot run, before any
42/// `boot_*` line, otherwise the first such call lazily wins.
43pub fn boot_reset_clock() {
44    let _ = BOOT_T0.set(Instant::now());
45}
46
47/// Print a main action header (e.g., "Installing", "Registering")
48pub fn action(action: &str, target: &str) {
49    println!("{} {}", format!("[{}]", action).green().bold(), target);
50}
51
52/// Print a success completion message
53pub fn success(message: &str) {
54    println!("{} {}", "✓".green().bold(), message.green());
55}
56
57/// Print an info message
58pub fn info(message: &str) {
59    println!("{}", message);
60}
61
62/// Print a warning message
63pub fn warning(message: &str) {
64    println!("{} {}", "⚠".yellow().bold(), message.yellow());
65}
66
67/// Print an error message
68pub fn error(message: &str) {
69    eprintln!("{} {}", "✗".red().bold(), message.red());
70}
71
72/// Print a step message (like "Validating", "Processing", etc.)
73pub fn step(action: &str, target: &str) {
74    println!("  {} {}", format!("-> {}", action).cyan(), target);
75}
76
77/// Print a sub-step message (indented detail)
78pub fn sub_step(message: &str) {
79    println!("    {}", message);
80}
81
82/// Print a checkmark success message for individual items
83pub fn check(message: &str) {
84    println!("  {} {}", "✓".green(), message);
85}
86
87/// Print a cross error message for individual items
88pub fn cross(message: &str) {
89    eprintln!("  {} {}", "✗".red(), message);
90}
91
92/// Print a summary line
93pub fn summary(message: &str) {
94    println!("\n{}", message.dimmed());
95}
96
97/// Abbreviate a full git SHA for display.
98pub fn short_sha(sha: &str) -> &str {
99    sha.get(..8).unwrap_or(sha)
100}
101
102// ── Boot-log helpers (FreeBSD / dmesg style) ────────────────────────
103//
104// Each boot line carries a monotonic `[ssss.mmm]` timestamp prefix and
105// a fixed-width status badge — same layout the BSD/Linux kernels print
106// at boot, so a robonix bring-up reads like a real OS init log instead
107// of a generic "deploying ..." trace.
108//
109// IMPORTANT: rust's `{:<N}` formatter pads to N BYTES, not visible
110// chars. `colored` returns strings with ANSI escape sequences embedded
111// (`"[ OK ]".green()` is ~13 bytes for 6 visible chars), so a naive
112// `{:<7}` against a colored string produces no padding (already past
113// 7 bytes). Every badge below is exactly 6 visible chars (`[ OK ]`,
114// `[FAIL]`, `[SKIP]`, `[ →  ]`, `[ ⠙ ]`, …) so no badge-side
115// alignment is needed; two spaces separate it from the name, and the
116// padding lives between the (uncolored) name and the detail.
117
118const W_NAME: usize = 18;
119
120/// Print the ASCII banner at the very top of a boot run. Called once
121/// from `rbnx boot` before any `[ ssss.mmm ]` line. Layout mimics the
122/// kernel's "Linux version ..." splash: name + version + git sha,
123/// builder, build time, compiler, target. All facts come from build.rs
124/// via compile-time env vars; missing values gracefully render as
125/// "unknown" so a tarball / sandboxed build still prints a banner.
126pub fn boot_banner() {
127    let info = crate::build_info::BuildInfo::get();
128    let dirty = if info.git_dirty == Some(true) {
129        "+"
130    } else {
131        ""
132    };
133    let sha = info.git_sha.map_or("unknown".to_string(), |sha| {
134        format!("{}{dirty}", short_sha(sha))
135    });
136    let builder = option_env!("ROBONIX_BUILDER").unwrap_or("unknown");
137    let build_time = option_env!("ROBONIX_BUILD_TIME").unwrap_or("unknown");
138    let rustc = format!("rustc {}", info.rustc.unwrap_or("unknown"));
139    let target = info.target.unwrap_or("unknown");
140
141    let lines = [
142        "    ____        __                 _      ",
143        "   / __ \\____  / /_  ____  ____  (_)  __ ",
144        "  / /_/ / __ \\/ __ \\/ __ \\/ __ \\/ / |/_/",
145        " / _, _/ /_/ / /_/ / /_/ / / / / />  <   ",
146        "/_/ |_|\\____/_.___/\\____/_/ /_/_/_/|_|   ",
147    ];
148    println!();
149    for line in &lines {
150        println!("{}", line.cyan().bold());
151    }
152    println!("{}", "        Embodied AI Operating System".dimmed(),);
153    println!();
154    // Body block. Bullet-aligned, dimmed value column — readable but
155    // visually distinct from the per-component boot lines below.
156    let label_w = 9;
157    let row = |k: &str, v: &str| {
158        println!(
159            "  {:label_w$} {}",
160            format!("{k}:").bold(),
161            v.dimmed(),
162            label_w = label_w
163        );
164    };
165    row("version", &format!("v{} ({sha})", info.version));
166    row("built", &format!("{build_time} on {builder}"));
167    row("compiler", &rustc);
168    row("target", target);
169    println!();
170}
171
172/// Single-line "we are now booting X" announcement, the dmesg-style
173/// banner that follows `boot_banner` and precedes the per-component
174/// `[ ssss.mmm ]` log. Resets the boot clock so timestamps below count
175/// from this point.
176pub fn boot_start(deploy_name: &str, manifest_path: &str) {
177    boot_reset_clock();
178    println!(
179        "{} booting {}",
180        boot_now().cyan(),
181        deploy_name.bold().green(),
182    );
183    println!("{} manifest {}", boot_now().cyan(), manifest_path.dimmed(),);
184}
185
186/// `[  ssss.mmm] [ OK ] name              detail` — component came up.
187/// Leading `\r\x1b[K` clears any in-place spinner line so the final
188/// result lands cleanly without a trailing fragment of "registering…".
189pub fn boot_ok(name: &str, detail: &str) {
190    println!(
191        "{}{} {}  {:<width$}  {}",
192        clear_progress_prefix(),
193        boot_now().cyan(),
194        "[ OK ]".green().bold(),
195        name,
196        detail.dimmed(),
197        width = W_NAME,
198    );
199}
200
201/// `[  ssss.mmm] [FAIL] name              detail` — failed to come up.
202pub fn boot_fail(name: &str, detail: &str) {
203    eprintln!(
204        "{}{} {}  {:<width$}  {}",
205        clear_progress_prefix(),
206        boot_now().cyan(),
207        "[FAIL]".red().bold(),
208        name,
209        detail.red(),
210        width = W_NAME,
211    );
212}
213
214/// `[  ssss.mmm] [SKIP] name              detail` — declared in manifest
215/// but skipped (not installed / disabled / out-of-scope on this host).
216pub fn boot_skip(name: &str, detail: &str) {
217    println!(
218        "{}{} {}  {:<width$}  {}",
219        clear_progress_prefix(),
220        boot_now().cyan(),
221        "[SKIP]".yellow(),
222        name,
223        detail.dimmed(),
224        width = W_NAME,
225    );
226}
227
228/// `[  ssss.mmm] [ →  ] name              detail` — informational note
229/// (cache hit, fetched a remote package, …). Neither up nor skipped.
230pub fn boot_note(name: &str, detail: &str) {
231    println!(
232        "{}{} {}  {:<width$}  {}",
233        clear_progress_prefix(),
234        boot_now().cyan(),
235        "[ →  ]".cyan(),
236        name,
237        detail.dimmed(),
238        width = W_NAME,
239    );
240}
241
242/// `[  ssss.mmm] [ ↑ ] name              detail` — an update is available.
243/// Leading `\r\x1b[K` clears the in-place `boot_progress` spinner so the
244/// verdict lands cleanly. Yellow `↑` distinguishes "needs update" from the
245/// green `[ OK ]` "up to date" verdict.
246pub fn boot_update_avail(name: &str, detail: &str) {
247    println!(
248        "{}{} {}  {:<width$}  {}",
249        clear_progress_prefix(),
250        boot_now().cyan(),
251        "[ ↑  ]".yellow().bold(),
252        name,
253        detail.dimmed(),
254        width = W_NAME,
255    );
256}
257
258/// `[  ssss.mmm] [....] name              detail` — component is starting.
259pub fn boot_wait(name: &str, detail: &str) {
260    println!(
261        "{}{} {}  {:<width$}  {}",
262        clear_progress_prefix(),
263        boot_now().cyan(),
264        "[....]".cyan(),
265        name,
266        detail.dimmed(),
267        width = W_NAME,
268    );
269}
270
271/// Group header above a run of boot lines. FreeBSD-rc-style ":: stage ::".
272pub fn boot_section(label: &str) {
273    println!(
274        "{}\n{} {} {} {}",
275        clear_progress_prefix(),
276        boot_now().cyan(),
277        "::".dimmed(),
278        label.bold().yellow(),
279        "::".dimmed(),
280    );
281}
282
283/// In-place spinner frame. Renders to stdout with `\r` (no newline) and
284/// flushes; caller overwrites with boot_ok / boot_fail to finalize.
285/// Frames cycle through Braille dots — the systemd spinner most users
286/// recognise from Linux init logs.
287pub fn boot_progress(name: &str, detail: &str, frame: usize) {
288    if boot_verbose() {
289        return;
290    }
291    const GLYPHS: &[char] = &['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
292    let g = GLYPHS[frame % GLYPHS.len()];
293    print!(
294        "\r\x1b[K{} {}  {:<width$}  {}",
295        boot_now().cyan(),
296        format!("[ {g} ]").cyan(),
297        name,
298        detail.dimmed(),
299        width = W_NAME,
300    );
301    let _ = io::stdout().flush();
302}
303
304/// Final boot summary line — total elapsed + component tally.
305pub fn boot_summary(ok: usize, total: usize, hint: &str) {
306    let elapsed = BOOT_T0
307        .get()
308        .map(|t| t.elapsed().as_secs_f64())
309        .unwrap_or(0.0);
310    let badge = if ok == total {
311        "OK".green().bold()
312    } else {
313        "DEGRADED".yellow().bold()
314    };
315    println!();
316    println!(
317        "[ {badge} ] robonix up — {ok}/{total} components in {elapsed:.3}s   {}",
318        hint.dimmed()
319    );
320}
321
322/// Spinner for animated progress indication
323pub struct Spinner {
324    message: String,
325    frames: Vec<char>,
326    handle: Option<tokio::task::JoinHandle<()>>,
327}
328
329impl Spinner {
330    /// Create a new spinner with a message
331    pub fn new(message: String) -> Self {
332        Self {
333            message,
334            frames: vec!['|', '/', '-', '\\'],
335            handle: None,
336        }
337    }
338
339    /// Start the spinner animation (spawns background task)
340    pub fn start(&mut self) {
341        let message = self.message.clone();
342        let mut frame = 0;
343        let frames = self.frames.clone();
344
345        let handle = tokio::spawn(async move {
346            loop {
347                let spinner_char = frames[frame % frames.len()];
348                let line = format!("  {} {}", spinner_char, message);
349                print!("\r{}", line);
350                let _ = io::stdout().flush();
351                frame += 1;
352                tokio::time::sleep(tokio::time::Duration::from_millis(100)).await;
353            }
354        });
355
356        self.handle = Some(handle);
357    }
358
359    /// Stop the spinner and show success message
360    pub fn finish_success(&mut self, final_message: &str) {
361        if let Some(handle) = self.handle.take() {
362            handle.abort();
363        }
364        // Clear the line first (using ANSI escape code)
365        print!("\r\x1b[K");
366        let line = format!("  {} {}", "✓".green(), final_message.green());
367        println!("{}", line);
368        let _ = io::stdout().flush();
369    }
370
371    /// Stop the spinner and show error message
372    pub fn finish_error(&mut self, final_message: &str) {
373        if let Some(handle) = self.handle.take() {
374            handle.abort();
375        }
376        // Clear the line first (using ANSI escape code)
377        print!("\r\x1b[K");
378        let line = format!("  {} {}", "✗".red(), final_message.red());
379        println!("{}", line);
380        let _ = io::stdout().flush();
381    }
382}
383
384impl Drop for Spinner {
385    fn drop(&mut self) {
386        if let Some(handle) = self.handle.take() {
387            handle.abort();
388        }
389    }
390}
浙ICP备2023005800号-2 浙公网安备33010902005384号