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