Skip to main content

option_sdk/
term.rs

1//! Minimal ANSI styling for terminal output.
2//!
3//! [`Style::stdout`] / [`Style::stderr`] pick up color support from
4//! [`crate::color_on_stdout`] / [`crate::color_on_stderr`] (`NO_COLOR`,
5//! `TERM=dumb`, and TTY detection). When color is off every method returns
6//! the input unchanged, so output is always safe to print.
7
8use crate::App;
9
10const RESET: &str = "\x1b[0m";
11
12/// Whether ANSI color is enabled, plus the escape helpers.
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub struct Style {
15    color: bool,
16}
17
18impl Style {
19    /// Color when stdout is a terminal and `NO_COLOR` / `TERM=dumb` are unset.
20    pub fn stdout() -> Self {
21        Self::new(crate::color_on_stdout())
22    }
23
24    /// Color when stderr is a terminal and `NO_COLOR` / `TERM=dumb` are unset.
25    pub fn stderr() -> Self {
26        Self::new(crate::color_on_stderr())
27    }
28
29    /// Never emit ANSI escapes.
30    pub fn plain() -> Self {
31        Self::new(false)
32    }
33
34    pub fn new(color: bool) -> Self {
35        Self { color }
36    }
37
38    /// Whether this style emits ANSI escapes.
39    pub fn enabled(&self) -> bool {
40        self.color
41    }
42
43    pub fn bold(&self, s: &str) -> String {
44        self.wrap("\x1b[1m", s)
45    }
46
47    pub fn dim(&self, s: &str) -> String {
48        self.wrap("\x1b[2m", s)
49    }
50
51    /// Green — success.
52    pub fn ok(&self, s: &str) -> String {
53        self.wrap("\x1b[32m", s)
54    }
55
56    /// Yellow — warning.
57    pub fn warn(&self, s: &str) -> String {
58        self.wrap("\x1b[33m", s)
59    }
60
61    /// Red — error.
62    pub fn err(&self, s: &str) -> String {
63        self.wrap("\x1b[31m", s)
64    }
65
66    /// `<mark> <text>` with the app mark in bold, e.g. `◆ opsh doctor`.
67    pub fn mark_line(&self, app: &App, text: &str) -> String {
68        format!("{} {text}", self.bold(app.mark()))
69    }
70
71    fn wrap(&self, code: &str, s: &str) -> String {
72        if self.color {
73            format!("{code}{s}{RESET}")
74        } else {
75            s.to_string()
76        }
77    }
78}
79
80#[cfg(test)]
81mod tests {
82    use super::*;
83
84    #[test]
85    fn plain_has_no_escapes() {
86        let style = Style::plain();
87        assert!(!style.enabled());
88        assert_eq!(style.bold("x"), "x");
89        assert_eq!(style.dim("x"), "x");
90        assert_eq!(style.ok("x"), "x");
91        assert_eq!(style.warn("x"), "x");
92        assert_eq!(style.err("x"), "x");
93        assert!(!style.bold("x").contains('\x1b'));
94    }
95
96    #[test]
97    fn wraps_with_ansi() {
98        let style = Style::new(true);
99        assert!(style.enabled());
100        assert_eq!(style.bold("x"), "\x1b[1mx\x1b[0m");
101        assert_eq!(style.dim("x"), "\x1b[2mx\x1b[0m");
102        assert_eq!(style.ok("x"), "\x1b[32mx\x1b[0m");
103        assert_eq!(style.warn("x"), "\x1b[33mx\x1b[0m");
104        assert_eq!(style.err("x"), "\x1b[31mx\x1b[0m");
105    }
106
107    #[test]
108    fn mark_line_plain() {
109        let style = Style::plain();
110        assert_eq!(style.mark_line(&App::OPSH, "opsh doctor"), "❯ opsh doctor");
111    }
112
113    #[test]
114    fn mark_line_color() {
115        let style = Style::new(true);
116        assert_eq!(
117            style.mark_line(&App::OPSH, "doctor"),
118            "\x1b[1m❯\x1b[0m doctor"
119        );
120    }
121}