OXYGENHUB
# d2e3c39da1b1 oxygen / src / cli / ui.rs
7.6 KiB · Rust · last changed Unbound hosted repositories adopt the first pusher's id 1 month ago source blame history raw
1
//! Terminal presentation: colour, emphasis, and a live spinner while a
2
//! command works. Everything degrades to plain text when stdout is not a
3
//! terminal, when `NO_COLOR` is set, or with `--plain`.
4
5
use console::{style, StyledObject, Term};
6
use indicatif::{ProgressBar, ProgressStyle};
7
use std::sync::atomic::{AtomicBool, Ordering};
8
use std::time::Duration;
9
10
static PLAIN: AtomicBool = AtomicBool::new(false);
11
static UNICODE: AtomicBool = AtomicBool::new(false);
12
static INIT: std::sync::Once = std::sync::Once::new();
13
14
/// Decide once whether to use colour, glyphs, and animation.
15
pub fn init(plain_flag: bool) {
16
    INIT.call_once(|| {
17
        let no_color = std::env::var_os("NO_COLOR").is_some();
18
        let tty = Term::stdout().features().is_attended();
19
        let plain = plain_flag || no_color || !tty;
20
        PLAIN.store(plain, Ordering::Relaxed);
21
        console::set_colors_enabled(!plain);
22
        let utf8 = ["LC_ALL", "LC_CTYPE", "LANG"]
23
            .iter()
24
            .filter_map(|k| std::env::var(k).ok())
25
            .find(|v| !v.is_empty())
26
            .map(|v| {
27
                v.to_ascii_uppercase().contains("UTF-8") || v.to_ascii_uppercase().contains("UTF8")
28
            })
29
            .unwrap_or(false);
30
        UNICODE.store(!plain && utf8, Ordering::Relaxed);
31
    });
32
}
33
34
pub fn plain() -> bool {
35
    PLAIN.load(Ordering::Relaxed)
36
}
37
38
/// Whether the terminal takes Unicode glyphs (a UTF-8 locale, not `--plain`).
39
pub fn unicode() -> bool {
40
    UNICODE.load(Ordering::Relaxed)
41
}
42
43
/// A glyph with an ASCII fallback for plain output and non-UTF-8 locales.
44
pub fn glyph<'a>(fancy: &'a str, ascii: &'a str) -> &'a str {
45
    if unicode() {
46
        fancy
47
    } else {
48
        ascii
49
    }
50
}
51
52
/// A finished action: a tick and the verb in green.
53
pub fn done<T: std::fmt::Display>(v: T) -> String {
54
    format!("{} {}", ok(glyph("✔", "*")), ok(v))
55
}
56
57
/// A warning line prefix.
58
pub fn caution() -> String {
59
    warn(glyph("⚠", "!"))
60
}
61
62
/// An informational note prefix.
63
pub fn note() -> String {
64
    dim(glyph("ℹ", "i"))
65
}
66
67
/// A section title.
68
pub fn section<T: std::fmt::Display>(v: T) -> String {
69
    format!("{} {}", s(glyph("▍", "#")).cyan(), s(v).bold())
70
}
71
72
/// `  key   value`, with the key dimmed and padded.
73
pub fn kv<T: std::fmt::Display>(key: &str, value: T) -> String {
74
    format!("  {} {value}", dim(format!("{key:<8}")))
75
}
76
77
/// An author name.
78
pub fn author<T: std::fmt::Display>(v: T) -> String {
79
    s(v).magenta().to_string()
80
}
81
82
/// A bookmark or reference name.
83
pub fn bookmark<T: std::fmt::Display>(v: T) -> String {
84
    s(v).green().bold().to_string()
85
}
86
87
/// The subject line of a message.
88
pub fn subject<T: std::fmt::Display>(v: T) -> String {
89
    s(v).bold().to_string()
90
}
91
92
/// A dimmed separator between the parts of a metadata line.
93
pub fn sep() -> String {
94
    dim(format!(" {} ", glyph("·", "-")))
95
}
96
97
/// Milliseconds since the epoch as a relative time ("3 minutes ago"), or the
98
/// date when older than a month.
99
pub fn ago(ms: u64) -> String {
100
    let now = std::time::SystemTime::now()
101
        .duration_since(std::time::UNIX_EPOCH)
102
        .map(|d| d.as_millis() as u64)
103
        .unwrap_or(0);
104
    let secs = now.saturating_sub(ms) / 1000;
105
    let unit = |n: u64, w: &str| format!("{n} {w}{} ago", if n == 1 { "" } else { "s" });
106
    match secs {
107
        0..=44 => "just now".into(),
108
        45..=89 => "a minute ago".into(),
109
        90..=2_699 => unit(secs.div_ceil(60), "minute"),
110
        2_700..=5_399 => "an hour ago".into(),
111
        5_400..=79_199 => unit(secs.div_ceil(3_600), "hour"),
112
        79_200..=129_599 => "yesterday".into(),
113
        129_600..=2_591_999 => unit(secs.div_ceil(86_400), "day"),
114
        _ => super::format::when(ms)
115
            .split(' ')
116
            .next()
117
            .unwrap_or("")
118
            .to_string(),
119
    }
120
}
121
122
/// The bullet for a log entry: the working copy, a head, or an ordinary change.
123
pub fn log_bullet(working_copy: bool, head: bool, conflicted: bool) -> String {
124
    if working_copy {
125
        s(glyph("◉", "@")).cyan().bold().to_string()
126
    } else if conflicted {
127
        err(glyph("✱", "!"))
128
    } else if head {
129
        ok(glyph("●", "*"))
130
    } else {
131
        dim(glyph("○", "o"))
132
    }
133
}
134
135
/// The vertical rail joining log entries.
136
pub fn rail() -> String {
137
    dim(glyph("│", "|"))
138
}
139
140
/// A status glyph and word for a working-copy change.
141
pub fn status_mark(tag: &str) -> String {
142
    let (g, a, word) = match tag {
143
        "A" => ("✚", "+", "added"),
144
        "M" => ("✎", "~", "modified"),
145
        "D" => ("✖", "-", "removed"),
146
        "X" => ("⚙", "x", "mode"),
147
        "C!" => ("‼", "!", "markers"),
148
        "R" => ("➜", ">", "renamed"),
149
        "V" => ("✔", "r", "resolved"),
150
        _ => ("?", "?", "unknown"),
151
    };
152
    let text = format!("{} {word:<9}", glyph(g, a));
153
    self::tag_style(tag, &text)
154
}
155
156
fn tag_style(t: &str, text: &str) -> String {
157
    match t {
158
        "A" | "V" => s(text).green().to_string(),
159
        "R" => s(text).cyan().to_string(),
160
        "M" | "X" => s(text).yellow().to_string(),
161
        "D" | "C!" => s(text).red().to_string(),
162
        _ => text.to_string(),
163
    }
164
}
165
166
fn s<T: std::fmt::Display>(v: T) -> StyledObject<T> {
167
    style(v)
168
}
169
170
/// A ChangeId prefix.
171
pub fn id<T: std::fmt::Display>(v: T) -> String {
172
    s(v).cyan().bold().to_string()
173
}
174
/// A hash prefix.
175
pub fn hash<T: std::fmt::Display>(v: T) -> String {
176
    s(v).dim().to_string()
177
}
178
pub fn path<T: std::fmt::Display>(v: T) -> String {
179
    s(v).bold().to_string()
180
}
181
pub fn ok<T: std::fmt::Display>(v: T) -> String {
182
    s(v).green().to_string()
183
}
184
pub fn warn<T: std::fmt::Display>(v: T) -> String {
185
    s(v).yellow().to_string()
186
}
187
pub fn err<T: std::fmt::Display>(v: T) -> String {
188
    s(v).red().bold().to_string()
189
}
190
pub fn dim<T: std::fmt::Display>(v: T) -> String {
191
    s(v).dim().to_string()
192
}
193
pub fn heading<T: std::fmt::Display>(v: T) -> String {
194
    s(v).bold().underlined().to_string()
195
}
196
/// A live spinner with a message, shown only on a terminal. Drop or call
197
/// `done` to clear it; `done` prints the final line in its place.
198
pub struct Spinner {
199
    bar: Option<ProgressBar>,
200
}
201
202
pub fn spinner(msg: &str) -> Spinner {
203
    if plain() {
204
        return Spinner { bar: None };
205
    }
206
    let bar = ProgressBar::new_spinner();
207
    bar.set_style(
208
        ProgressStyle::with_template("{spinner:.cyan} {msg}")
209
            .unwrap()
210
            .tick_strings(&["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏", "✔"]),
211
    );
212
    bar.set_message(msg.to_string());
213
    bar.enable_steady_tick(Duration::from_millis(80));
214
    Spinner { bar: Some(bar) }
215
}
216
217
impl Spinner {
218
    /// Replace the spinner with a final line (or print it plainly).
219
    pub fn done(self, msg: &str) {
220
        match &self.bar {
221
            Some(b) => b.finish_with_message(msg.to_string()),
222
            None => println!("{msg}"),
223
        }
224
    }
225
    /// Clear the spinner without printing.
226
    pub fn clear(self) {
227
        if let Some(b) = &self.bar {
228
            b.finish_and_clear();
229
        }
230
    }
231
}
232
233
#[cfg(test)]
234
mod tests {
235
    use super::*;
236
237
    #[test]
238
    fn relative_times() {
239
        let now = std::time::SystemTime::now()
240
            .duration_since(std::time::UNIX_EPOCH)
241
            .unwrap()
242
            .as_millis() as u64;
243
        assert_eq!(ago(now), "just now");
244
        assert_eq!(ago(now - 60_000), "a minute ago");
245
        assert_eq!(ago(now - 5 * 60_000), "5 minutes ago");
246
        assert_eq!(ago(now - 3 * 3_600_000), "3 hours ago");
247
        assert_eq!(ago(now - 25 * 3_600_000), "yesterday");
248
        assert_eq!(ago(now - 4 * 86_400_000), "4 days ago");
249
        assert_eq!(ago(0), "1970-01-01");
250
        assert_eq!(glyph("✔", "*"), if unicode() { "✔" } else { "*" });
251
    }
252
}