Skip to main content

logicaffeine_cli/
ui.rs

1//! Terminal output substrate for `largo`.
2//!
3//! Central home for everything user-facing that is not command logic:
4//! the [`CliError`] type rendered by the binary's `main`, the process
5//! exit-code conventions, the color/verbosity state shared by every
6//! command, and the clap help palette.
7//!
8//! All commands construct [`CliError`] (directly or via [`CliError::new`] /
9//! [`CliError::with_hint`]) instead of ad-hoc string errors when they want
10//! a hint line or a non-default exit code. Plain `String` errors continue
11//! to work through `Box<dyn Error>` and render without a hint.
12//!
13//! Every user-visible print goes through [`anstream`], so ANSI styling is
14//! automatically stripped on pipes, honored under `--color always`, and
15//! silenced by `NO_COLOR` — including styling embedded in engine-rendered
16//! messages that pass through here.
17
18use std::fmt;
19use std::sync::atomic::{AtomicBool, AtomicU8, Ordering};
20
21use anstyle::{AnsiColor, Style};
22use clap::builder::Styles;
23
24/// Process exit code for success.
25pub const EXIT_OK: i32 = 0;
26/// Process exit code for a command failure (build error, proof failure,
27/// dirty `fmt --check`, parse error, ...).
28pub const EXIT_FAILURE: i32 = 1;
29/// Process exit code for a usage error (bad arguments, reserved verb).
30/// Matches clap's own convention for argument errors.
31pub const EXIT_USAGE: i32 = 2;
32
33/// Bold red — the `error:` prefix.
34pub const ERROR_STYLE: Style = AnsiColor::Red.on_default().bold();
35/// Bold cyan — the `help:` prefix.
36pub const HELP_STYLE: Style = AnsiColor::Cyan.on_default().bold();
37/// Bold green — phase headers (`Compiling`, `Finished`, ...), cargo-style.
38pub const PHASE_STYLE: Style = AnsiColor::Green.on_default().bold();
39/// Bold yellow — the `warning:` prefix.
40pub const WARN_STYLE: Style = AnsiColor::Yellow.on_default().bold();
41
42/// The cargo help palette for clap: bold-green headers/usage, bold-cyan
43/// literals, cyan placeholders.
44pub const CLAP_STYLES: Styles = Styles::styled()
45    .header(AnsiColor::Green.on_default().bold())
46    .usage(AnsiColor::Green.on_default().bold())
47    .literal(AnsiColor::Cyan.on_default().bold())
48    .placeholder(AnsiColor::Cyan.on_default());
49
50/// The `--color` mode selected on the command line.
51#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, clap::ValueEnum)]
52pub enum ColorMode {
53    /// Color when stdout/stderr is a terminal and `NO_COLOR` is unset.
54    #[default]
55    Auto,
56    /// Always emit ANSI, even into pipes (CI logs, `less -R`).
57    Always,
58    /// Never emit ANSI.
59    Never,
60}
61
62static QUIET: AtomicBool = AtomicBool::new(false);
63static VERBOSITY: AtomicU8 = AtomicU8::new(0);
64
65/// Install the global output state from the parsed CLI flags.
66///
67/// Called once by `run_cli` before dispatch: records `--quiet`/`--verbose`
68/// and sets the process-wide [`anstream`] color choice so every subsequent
69/// print (ours or an engine message routed through anstream) obeys the
70/// user's `--color` selection.
71pub fn init(color: ColorMode, quiet: bool, verbosity: u8) {
72    QUIET.store(quiet, Ordering::Relaxed);
73    VERBOSITY.store(verbosity, Ordering::Relaxed);
74    let choice = match color {
75        ColorMode::Auto => anstream::ColorChoice::Auto,
76        ColorMode::Always => anstream::ColorChoice::Always,
77        ColorMode::Never => anstream::ColorChoice::Never,
78    };
79    choice.write_global();
80}
81
82/// Whether `--quiet` was passed: informational output should be suppressed.
83pub fn is_quiet() -> bool {
84    QUIET.load(Ordering::Relaxed)
85}
86
87/// The `-v` count: `0` normal, `1+` increasingly chatty.
88pub fn verbosity() -> u8 {
89    VERBOSITY.load(Ordering::Relaxed)
90}
91
92/// Print an informational line to stdout unless `--quiet` is active.
93pub fn info(msg: impl fmt::Display) {
94    if !is_quiet() {
95        anstream::println!("{msg}");
96    }
97}
98
99/// Print a note to stderr unless `--quiet` is active — the line that accompanies
100/// an artifact on stdout (which lane, which chip) without polluting a redirect.
101pub fn note(msg: impl fmt::Display) {
102    if !is_quiet() {
103        anstream::eprintln!("{msg}");
104    }
105}
106
107/// Print a cargo-style phase header (right-aligned bold-green verb) to
108/// stderr unless `--quiet` is active.
109///
110/// ```text
111///    Compiling hello v0.1.0 (LOGOS → Rust)
112///     Finished dev profile in 3.2s
113/// ```
114pub fn phase(verb: &str, rest: impl fmt::Display) {
115    if !is_quiet() {
116        anstream::eprintln!("{PHASE_STYLE}{verb:>12}{PHASE_STYLE:#} {rest}");
117    }
118}
119
120/// Print one `error:` block to stderr — for a command that reports several errors before it
121/// returns the last as its own.
122pub fn error(msg: impl fmt::Display) {
123    anstream::eprintln!("{ERROR_STYLE}error:{ERROR_STYLE:#} {msg}");
124}
125
126/// Print one `warning:` block to stderr unless `--quiet` is active.
127pub fn warning(msg: impl fmt::Display) {
128    if !is_quiet() {
129        anstream::eprintln!("{WARN_STYLE}warning:{WARN_STYLE:#} {msg}");
130    }
131}
132
133/// A user-facing CLI error: a message, an optional `help:` hint, and the
134/// exit code the process should terminate with.
135///
136/// The `largo` binary downcasts `Box<dyn Error>` values to this type and
137/// renders them as:
138///
139/// ```text
140/// error: <message>
141/// help: <hint>
142/// ```
143#[derive(Debug)]
144pub struct CliError {
145    /// The primary error message (rendered after `error:`).
146    pub message: String,
147    /// An optional actionable hint (rendered after `help:`).
148    pub hint: Option<String>,
149    /// The process exit code to terminate with.
150    pub exit_code: i32,
151}
152
153impl CliError {
154    /// Create an error with the default failure exit code and no hint.
155    pub fn new(message: impl Into<String>) -> Self {
156        Self {
157            message: message.into(),
158            hint: None,
159            exit_code: EXIT_FAILURE,
160        }
161    }
162
163    /// Create an error carrying an actionable `help:` hint.
164    pub fn with_hint(message: impl Into<String>, hint: impl Into<String>) -> Self {
165        Self {
166            message: message.into(),
167            hint: Some(hint.into()),
168            exit_code: EXIT_FAILURE,
169        }
170    }
171
172    /// Override the exit code (builder style).
173    pub fn exit_code(mut self, code: i32) -> Self {
174        self.exit_code = code;
175        self
176    }
177}
178
179impl fmt::Display for CliError {
180    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
181        write!(f, "{}", self.message)
182    }
183}
184
185impl std::error::Error for CliError {}
186
187/// Render any top-level error to stderr in the `error:`/`help:` style and
188/// return the exit code the process should use.
189///
190/// [`CliError`] values carry their own hint and exit code; every other error
191/// renders as a bare `error:` line with [`EXIT_FAILURE`].
192pub fn render_error(e: &(dyn std::error::Error + 'static)) -> i32 {
193    if let Some(cli_err) = e.downcast_ref::<CliError>() {
194        anstream::eprint!("{}", error_block(&cli_err.message, cli_err.hint.as_deref()));
195        cli_err.exit_code
196    } else {
197        anstream::eprint!("{}", error_block(&e.to_string(), None));
198        EXIT_FAILURE
199    }
200}
201
202/// The `error:` line and the optional `help:` line, styled for a terminal (anstream drops the styles when
203/// the stream is not one).
204pub(crate) fn error_block(message: &str, hint: Option<&str>) -> String {
205    let mut out = format!("{ERROR_STYLE}error:{ERROR_STYLE:#} {message}\n");
206    if let Some(hint) = hint {
207        out.push_str(&format!("{HELP_STYLE}help:{HELP_STYLE:#} {hint}\n"));
208    }
209    out
210}
211
212/// `styled` with its terminal styles removed: what a stream that is not a terminal receives.
213pub(crate) fn plain(styled: &str) -> String {
214    anstream::adapter::strip_str(styled).to_string()
215}
216
217#[cfg(test)]
218#[path = "../../../crates/logicaffeine_tests/unit/logicaffeine_cli/ui/tests.rs"]
219mod tests;