loaders 0.0.0

A fully-featured, customisable progress bar and loading indicator library for Rust CLI and terminal applications
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
//! ANSI color support implemented without external dependencies.

use crate::terminal::detect::{ColorSupport, color_support};

/// An ANSI foreground or background color.
///
/// Use the named variants for portable sixteen-color output, `Color256` for
/// indexed color, or `Rgb` for true color capable terminals.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub enum Color {
    /// ANSI black.
    Black,
    /// ANSI red.
    Red,
    /// ANSI green.
    Green,
    /// ANSI yellow.
    Yellow,
    /// ANSI blue.
    Blue,
    /// ANSI magenta.
    Magenta,
    /// ANSI cyan.
    Cyan,
    /// ANSI white.
    White,
    /// Bright black / gray.
    BrightBlack,
    /// Bright red.
    BrightRed,
    /// Bright green.
    BrightGreen,
    /// Bright yellow.
    BrightYellow,
    /// Bright blue.
    BrightBlue,
    /// Bright magenta.
    BrightMagenta,
    /// Bright cyan.
    BrightCyan,
    /// Bright white.
    BrightWhite,
    /// ANSI 256-color palette index.
    Color256(u8),
    /// True-color RGB.
    Rgb(u8, u8, u8),
}

impl Color {
    /// Renders this color as a foreground ANSI code.
    ///
    /// # Examples
    ///
    /// ```rust
    /// assert_eq!(loaders::Color::Red.render_fg(), "\x1b[31m");
    /// ```
    pub fn render_fg(&self) -> String {
        match self {
            Self::Black => "\x1b[30m".to_string(),
            Self::Red => "\x1b[31m".to_string(),
            Self::Green => "\x1b[32m".to_string(),
            Self::Yellow => "\x1b[33m".to_string(),
            Self::Blue => "\x1b[34m".to_string(),
            Self::Magenta => "\x1b[35m".to_string(),
            Self::Cyan => "\x1b[36m".to_string(),
            Self::White => "\x1b[37m".to_string(),
            Self::BrightBlack => "\x1b[90m".to_string(),
            Self::BrightRed => "\x1b[91m".to_string(),
            Self::BrightGreen => "\x1b[92m".to_string(),
            Self::BrightYellow => "\x1b[93m".to_string(),
            Self::BrightBlue => "\x1b[94m".to_string(),
            Self::BrightMagenta => "\x1b[95m".to_string(),
            Self::BrightCyan => "\x1b[96m".to_string(),
            Self::BrightWhite => "\x1b[97m".to_string(),
            Self::Color256(n) => format!("\x1b[38;5;{n}m"),
            Self::Rgb(r, g, b) => format!("\x1b[38;2;{r};{g};{b}m"),
        }
    }

    /// Renders this color as a background ANSI code.
    ///
    /// # Examples
    ///
    /// ```rust
    /// assert_eq!(loaders::Color::Blue.render_bg(), "\x1b[44m");
    /// ```
    pub fn render_bg(&self) -> String {
        match self {
            Self::Black => "\x1b[40m".to_string(),
            Self::Red => "\x1b[41m".to_string(),
            Self::Green => "\x1b[42m".to_string(),
            Self::Yellow => "\x1b[43m".to_string(),
            Self::Blue => "\x1b[44m".to_string(),
            Self::Magenta => "\x1b[45m".to_string(),
            Self::Cyan => "\x1b[46m".to_string(),
            Self::White => "\x1b[47m".to_string(),
            Self::BrightBlack => "\x1b[100m".to_string(),
            Self::BrightRed => "\x1b[101m".to_string(),
            Self::BrightGreen => "\x1b[102m".to_string(),
            Self::BrightYellow => "\x1b[103m".to_string(),
            Self::BrightBlue => "\x1b[104m".to_string(),
            Self::BrightMagenta => "\x1b[105m".to_string(),
            Self::BrightCyan => "\x1b[106m".to_string(),
            Self::BrightWhite => "\x1b[107m".to_string(),
            Self::Color256(n) => format!("\x1b[48;5;{n}m"),
            Self::Rgb(r, g, b) => format!("\x1b[48;2;{r};{g};{b}m"),
        }
    }
}

/// A complete ANSI style specification.
///
/// Styles are builder-friendly and can be applied to arbitrary text with
/// `render`.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct ColorSpec {
    /// Optional foreground color.
    pub fg: Option<Color>,
    /// Optional background color.
    pub bg: Option<Color>,
    /// Bold text.
    pub bold: bool,
    /// Dim text.
    pub dim: bool,
    /// Italic text.
    pub italic: bool,
    /// Underlined text.
    pub underline: bool,
    /// Blinking text.
    pub blink: bool,
    /// Reverse foreground and background.
    pub reverse: bool,
    /// Strikethrough text.
    pub strikethrough: bool,
}

impl ColorSpec {
    /// Creates an empty color specification.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let spec = loaders::ColorSpec::new();
    /// assert_eq!(spec.fg, None);
    /// ```
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the foreground color.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let spec = loaders::ColorSpec::new().set_fg(loaders::Color::Cyan);
    /// assert_eq!(spec.fg, Some(loaders::Color::Cyan));
    /// ```
    pub fn set_fg(mut self, color: Color) -> Self {
        self.fg = Some(color);
        self
    }

    /// Sets the background color.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let spec = loaders::ColorSpec::new().set_bg(loaders::Color::Black);
    /// assert_eq!(spec.bg, Some(loaders::Color::Black));
    /// ```
    pub fn set_bg(mut self, color: Color) -> Self {
        self.bg = Some(color);
        self
    }

    /// Enables or disables bold text.
    ///
    /// # Examples
    ///
    /// ```rust
    /// assert!(loaders::ColorSpec::new().set_bold(true).bold);
    /// ```
    pub fn set_bold(mut self, val: bool) -> Self {
        self.bold = val;
        self
    }

    /// Enables or disables dim text.
    ///
    /// # Examples
    ///
    /// ```rust
    /// assert!(loaders::ColorSpec::new().set_dim(true).dim);
    /// ```
    pub fn set_dim(mut self, val: bool) -> Self {
        self.dim = val;
        self
    }

    /// Enables or disables italic text.
    ///
    /// # Examples
    ///
    /// ```rust
    /// assert!(loaders::ColorSpec::new().set_italic(true).italic);
    /// ```
    pub fn set_italic(mut self, val: bool) -> Self {
        self.italic = val;
        self
    }

    /// Enables or disables underline text.
    ///
    /// # Examples
    ///
    /// ```rust
    /// assert!(loaders::ColorSpec::new().set_underline(true).underline);
    /// ```
    pub fn set_underline(mut self, val: bool) -> Self {
        self.underline = val;
        self
    }

    /// Enables or disables blinking text.
    ///
    /// # Examples
    ///
    /// ```rust
    /// assert!(loaders::ColorSpec::new().set_blink(true).blink);
    /// ```
    pub fn set_blink(mut self, val: bool) -> Self {
        self.blink = val;
        self
    }

    /// Enables or disables reverse video text.
    ///
    /// # Examples
    ///
    /// ```rust
    /// assert!(loaders::ColorSpec::new().set_reverse(true).reverse);
    /// ```
    pub fn set_reverse(mut self, val: bool) -> Self {
        self.reverse = val;
        self
    }

    /// Enables or disables strikethrough text.
    ///
    /// # Examples
    ///
    /// ```rust
    /// assert!(loaders::ColorSpec::new().set_strikethrough(true).strikethrough);
    /// ```
    pub fn set_strikethrough(mut self, val: bool) -> Self {
        self.strikethrough = val;
        self
    }

    /// Applies this style to text.
    ///
    /// If ANSI output is disabled, the original text is returned unchanged.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let rendered = loaders::ColorSpec::new().set_bold(true).render("hi");
    /// assert!(rendered == "hi" || rendered.contains("hi"));
    /// ```
    pub fn render(&self, text: &str) -> String {
        if !ansi_enabled() {
            return text.to_string();
        }

        let mut out = String::new();
        if self.bold {
            out.push_str("\x1b[1m");
        }
        if self.dim {
            out.push_str("\x1b[2m");
        }
        if self.italic {
            out.push_str("\x1b[3m");
        }
        if self.underline {
            out.push_str("\x1b[4m");
        }
        if self.blink {
            out.push_str("\x1b[5m");
        }
        if self.reverse {
            out.push_str("\x1b[7m");
        }
        if self.strikethrough {
            out.push_str("\x1b[9m");
        }
        if let Some(fg) = &self.fg {
            out.push_str(&fg.render_fg());
        }
        if let Some(bg) = &self.bg {
            out.push_str(&bg.render_bg());
        }
        out.push_str(text);
        out.push_str(Self::reset_code());
        out
    }

    /// Returns the ANSI reset sequence.
    ///
    /// # Examples
    ///
    /// ```rust
    /// assert_eq!(loaders::ColorSpec::reset_code(), "\x1b[0m");
    /// ```
    pub fn reset_code() -> &'static str {
        "\x1b[0m"
    }
}

/// Returns whether ANSI output should be emitted.
///
/// The `NO_COLOR` environment variable disables ANSI output. CI environments
/// without explicit color support are treated as colorless.
///
/// # Examples
///
/// ```rust
/// let _ = loaders::style::color::ansi_enabled();
/// ```
pub fn ansi_enabled() -> bool {
    std::env::var_os("NO_COLOR").is_none() && color_support() != ColorSupport::None
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::env;
    use std::sync::Mutex;

    static ENV_LOCK: Mutex<()> = Mutex::new(());

    fn with_env_lock(f: impl FnOnce()) {
        match ENV_LOCK.lock() {
            Ok(_guard) => f(),
            Err(poisoned) => {
                let _guard = poisoned.into_inner();
                f();
            }
        }
    }

    #[test]
    fn test_color16_fg_code() {
        assert_eq!(Color::Red.render_fg(), "\x1b[31m");
    }

    #[test]
    fn test_color16_bg_code() {
        assert_eq!(Color::Blue.render_bg(), "\x1b[44m");
    }

    #[test]
    fn test_color256_fg_code() {
        assert_eq!(Color::Color256(42).render_fg(), "\x1b[38;5;42m");
    }

    #[test]
    fn test_rgb_fg_code() {
        assert_eq!(Color::Rgb(1, 2, 3).render_fg(), "\x1b[38;2;1;2;3m");
    }

    #[test]
    fn test_colorspec_bold() {
        let rendered = ColorSpec::new().set_bold(true).render("x");
        assert!(rendered == "x" || rendered.contains("\x1b[1m"));
    }

    #[test]
    fn test_colorspec_combined() {
        let spec = ColorSpec::new()
            .set_bold(true)
            .set_fg(Color::Cyan)
            .set_bg(Color::Black);
        let rendered = spec.render("x");
        assert!(rendered == "x" || rendered.contains("\x1b[36m"));
    }

    #[test]
    fn test_no_color_env_suppresses_ansi() {
        with_env_lock(|| {
            unsafe {
                env::set_var("NO_COLOR", "1");
            }
            assert_eq!(ColorSpec::new().set_bold(true).render("x"), "x");
            unsafe {
                env::remove_var("NO_COLOR");
            }
        });
    }

    #[test]
    fn test_render_wraps_text() {
        let rendered = ColorSpec::new().set_fg(Color::Green).render("ok");
        assert!(rendered == "ok" || rendered.ends_with("\x1b[0m"));
    }

    #[test]
    fn test_reset_code_value() {
        assert_eq!(ColorSpec::reset_code(), "\x1b[0m");
    }
}