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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
//! Terminal capability detection implemented with the Rust standard library.

use std::env;

/// The detected terminal capabilities for a stream.
///
/// Use this when choosing whether to emit ANSI control sequences, how wide a
/// progress bar should be, or whether output is likely running in CI.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct TerminalInfo {
    /// Whether the file descriptor appears to be a TTY.
    pub is_tty: bool,
    /// The detected terminal width in columns.
    pub width: usize,
    /// The detected terminal height in rows.
    pub height: usize,
    /// The best detected color capability.
    pub color_support: ColorSupport,
    /// Whether common CI environment variables are present.
    pub is_ci: bool,
}

/// Terminal color support level.
///
/// The value is inferred from `NO_COLOR`, `COLORTERM`, `TERM_PROGRAM`, `TERM`,
/// and common CI environment variables.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ColorSupport {
    /// ANSI colors should not be emitted.
    None,
    /// Basic sixteen-color ANSI support.
    Ansi16,
    /// ANSI 256-color support.
    Ansi256,
    /// ANSI true-color support.
    TrueColor,
}

impl TerminalInfo {
    /// Detects terminal information for standard output.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let info = loaders::terminal::detect::TerminalInfo::detect();
    /// assert!(info.width > 0);
    /// ```
    pub fn detect() -> Self {
        Self::detect_for_fd(1)
    }

    /// Detects terminal information for a numeric file descriptor.
    ///
    /// # Examples
    ///
    /// ```rust
    /// let info = loaders::terminal::detect::TerminalInfo::detect_for_fd(1);
    /// assert!(info.height > 0);
    /// ```
    pub fn detect_for_fd(fd: i32) -> Self {
        Self {
            is_tty: is_tty(fd),
            width: terminal_width_for_fd(fd),
            height: terminal_height_for_fd(fd),
            color_support: color_support(),
            is_ci: is_ci_environment(),
        }
    }
}

/// Returns the detected terminal width, falling back to `80`.
///
/// # Examples
///
/// ```rust
/// assert!(loaders::terminal::detect::terminal_width() > 0);
/// ```
pub fn terminal_width() -> usize {
    terminal_width_for_fd(1)
}

/// Returns the detected terminal width for a file descriptor, falling back to
/// `80`.
///
/// # Examples
///
/// ```rust
/// assert!(loaders::terminal::detect::terminal_width_for_fd(1) > 0);
/// ```
pub fn terminal_width_for_fd(fd: i32) -> usize {
    if let Some(width) = env_usize("COLUMNS") {
        return width.max(1);
    }

    #[cfg(unix)]
    {
        if let Some(width) = unix_terminal_size(fd).map(|(w, _)| w) {
            return width.max(1);
        }
    }

    #[cfg(windows)]
    {
        if let Some((width, _)) = windows_terminal_size(fd) {
            return width.max(1);
        }
    }

    80
}

/// Returns the detected terminal height, falling back to `24`.
///
/// # Examples
///
/// ```rust
/// assert!(loaders::terminal::detect::terminal_height() > 0);
/// ```
pub fn terminal_height() -> usize {
    terminal_height_for_fd(1)
}

/// Returns the detected terminal height for a file descriptor, falling back to
/// `24`.
///
/// # Examples
///
/// ```rust
/// assert!(loaders::terminal::detect::terminal_height_for_fd(1) > 0);
/// ```
pub fn terminal_height_for_fd(fd: i32) -> usize {
    if let Some(height) = env_usize("LINES") {
        return height.max(1);
    }

    #[cfg(unix)]
    {
        if let Some(height) = unix_terminal_size(fd).map(|(_, h)| h) {
            return height.max(1);
        }
    }

    #[cfg(windows)]
    {
        if let Some((_, height)) = windows_terminal_size(fd) {
            return height.max(1);
        }
    }

    24
}

/// Returns whether a file descriptor is attached to a terminal.
///
/// # Examples
///
/// ```rust
/// let _ = loaders::terminal::detect::is_tty(1);
/// ```
#[cfg(unix)]
pub fn is_tty(fd: i32) -> bool {
    unsafe extern "C" {
        fn isatty(fd: std::os::raw::c_int) -> std::os::raw::c_int;
    }

    // SAFETY: `isatty` does not take ownership of the descriptor and is safe to
    // call with any integer file descriptor value.
    unsafe { isatty(fd as std::os::raw::c_int) == 1 }
}

/// Returns whether a file descriptor is attached to a terminal.
///
/// Uses Win32 console mode checks while keeping the crate dependency-free.
#[cfg(windows)]
pub fn is_tty(fd: i32) -> bool {
    let Some(handle) = windows_output_handle(fd) else {
        return false;
    };
    console_mode(handle).is_some()
}

/// Returns whether a stream supports interactive cursor-based rendering.
///
/// On Windows this also enables virtual terminal processing when available so
/// ANSI cursor controls can update progress on the same line.
#[cfg(unix)]
pub fn supports_interactive_output(fd: i32) -> bool {
    is_tty(fd)
}

/// Returns whether a stream supports interactive cursor-based rendering.
///
/// On Windows this also enables virtual terminal processing when available so
/// ANSI cursor controls can update progress on the same line.
#[cfg(windows)]
pub fn supports_interactive_output(fd: i32) -> bool {
    let Some(handle) = windows_output_handle(fd) else {
        return false;
    };
    let Some(mode) = console_mode(handle) else {
        return false;
    };

    const ENABLE_VIRTUAL_TERMINAL_PROCESSING: u32 = 0x0004;
    if mode & ENABLE_VIRTUAL_TERMINAL_PROCESSING != 0 {
        return true;
    }

    // SAFETY: `handle` was retrieved from `GetStdHandle` and remains owned by
    // the process. `SetConsoleMode` updates console flags in place.
    unsafe { set_console_mode(handle, mode | ENABLE_VIRTUAL_TERMINAL_PROCESSING) != 0 }
}

/// Returns true when common CI environment variables are present.
///
/// # Examples
///
/// ```rust
/// let _ = loaders::terminal::detect::is_ci_environment();
/// ```
pub fn is_ci_environment() -> bool {
    [
        "CI",
        "GITHUB_ACTIONS",
        "GITLAB_CI",
        "CIRCLECI",
        "TRAVIS",
        "JENKINS_URL",
        "BUILDKITE",
        "TF_BUILD",
        "TEAMCITY_VERSION",
    ]
    .iter()
    .any(|key| env::var_os(key).is_some())
}

/// Detects color support from standard terminal environment variables.
///
/// # Examples
///
/// ```rust
/// let _support = loaders::terminal::detect::color_support();
/// ```
pub fn color_support() -> ColorSupport {
    if env::var_os("NO_COLOR").is_some() {
        return ColorSupport::None;
    }

    if let Ok(colorterm) = env::var("COLORTERM") {
        let lower = colorterm.to_ascii_lowercase();
        if lower == "truecolor" || lower == "24bit" {
            return ColorSupport::TrueColor;
        }
    }

    if let Ok(program) = env::var("TERM_PROGRAM")
        && (program == "iTerm.app" || program == "Hyper")
    {
        return ColorSupport::TrueColor;
    }

    if let Ok(term) = env::var("TERM") {
        let lower = term.to_ascii_lowercase();
        if lower.contains("256color") {
            return ColorSupport::Ansi256;
        }
        if lower.contains("xterm") || lower.contains("ansi") || lower.contains("screen") {
            return ColorSupport::Ansi16;
        }
        if lower == "dumb" {
            return ColorSupport::None;
        }
    }

    if is_ci_environment() {
        ColorSupport::None
    } else {
        ColorSupport::Ansi16
    }
}

fn env_usize(key: &str) -> Option<usize> {
    env::var(key)
        .ok()
        .and_then(|value| value.parse::<usize>().ok())
}

#[cfg(windows)]
type Handle = *mut std::ffi::c_void;

#[cfg(windows)]
const STD_OUTPUT_HANDLE: u32 = -11i32 as u32;
#[cfg(windows)]
const STD_ERROR_HANDLE: u32 = -12i32 as u32;
#[cfg(windows)]
const INVALID_HANDLE_VALUE: Handle = -1isize as Handle;

#[cfg(windows)]
fn windows_output_handle(fd: i32) -> Option<Handle> {
    let std_handle = match fd {
        1 => STD_OUTPUT_HANDLE,
        2 => STD_ERROR_HANDLE,
        _ => return None,
    };

    // SAFETY: `GetStdHandle` reads process-owned standard handles and does not
    // take ownership.
    let handle = unsafe { get_std_handle(std_handle) };
    if handle.is_null() || handle == INVALID_HANDLE_VALUE {
        return None;
    }
    Some(handle)
}

#[cfg(windows)]
fn console_mode(handle: Handle) -> Option<u32> {
    let mut mode = 0u32;
    // SAFETY: `handle` is expected to be a valid console handle and `mode`
    // points to writable memory for the duration of the call.
    let ok = unsafe { get_console_mode(handle, &mut mode) };
    if ok == 0 { None } else { Some(mode) }
}

#[cfg(windows)]
fn windows_terminal_size(fd: i32) -> Option<(usize, usize)> {
    let handle = windows_output_handle(fd)?;
    let info = console_screen_buffer_info(handle)?;
    let width = i32::from(info.sr_window.right) - i32::from(info.sr_window.left) + 1;
    let height = i32::from(info.sr_window.bottom) - i32::from(info.sr_window.top) + 1;
    if width > 0 && height > 0 {
        Some((width as usize, height as usize))
    } else {
        None
    }
}

#[cfg(windows)]
fn console_screen_buffer_info(handle: Handle) -> Option<ConsoleScreenBufferInfo> {
    let mut info = ConsoleScreenBufferInfo::default();
    // SAFETY: `handle` is expected to be a valid console handle and `info`
    // points to writable memory for the duration of the call.
    let ok = unsafe { get_console_screen_buffer_info(handle, &mut info) };
    if ok == 0 { None } else { Some(info) }
}

#[cfg(windows)]
#[derive(Clone, Copy, Default)]
#[repr(C)]
struct Coord {
    x: i16,
    y: i16,
}

#[cfg(windows)]
#[derive(Clone, Copy, Default)]
#[repr(C)]
struct SmallRect {
    left: i16,
    top: i16,
    right: i16,
    bottom: i16,
}

#[cfg(windows)]
#[derive(Clone, Copy, Default)]
#[repr(C)]
struct ConsoleScreenBufferInfo {
    dw_size: Coord,
    dw_cursor_position: Coord,
    w_attributes: u16,
    sr_window: SmallRect,
    dw_maximum_window_size: Coord,
}

#[cfg(windows)]
unsafe fn get_std_handle(std_handle: u32) -> Handle {
    unsafe extern "system" {
        fn GetStdHandle(nStdHandle: u32) -> Handle;
    }
    // SAFETY: delegated to Win32 API contract.
    unsafe { GetStdHandle(std_handle) }
}

#[cfg(windows)]
unsafe fn get_console_mode(handle: Handle, mode: *mut u32) -> i32 {
    unsafe extern "system" {
        fn GetConsoleMode(hConsoleHandle: Handle, lpMode: *mut u32) -> i32;
    }
    // SAFETY: delegated to Win32 API contract.
    unsafe { GetConsoleMode(handle, mode) }
}

#[cfg(windows)]
unsafe fn set_console_mode(handle: Handle, mode: u32) -> i32 {
    unsafe extern "system" {
        fn SetConsoleMode(hConsoleHandle: Handle, dwMode: u32) -> i32;
    }
    // SAFETY: delegated to Win32 API contract.
    unsafe { SetConsoleMode(handle, mode) }
}

#[cfg(windows)]
unsafe fn get_console_screen_buffer_info(
    handle: Handle,
    info: *mut ConsoleScreenBufferInfo,
) -> i32 {
    unsafe extern "system" {
        fn GetConsoleScreenBufferInfo(
            hConsoleOutput: Handle,
            lpConsoleScreenBufferInfo: *mut ConsoleScreenBufferInfo,
        ) -> i32;
    }
    // SAFETY: delegated to Win32 API contract.
    unsafe { GetConsoleScreenBufferInfo(handle, info) }
}

#[cfg(unix)]
fn unix_terminal_size(fd: i32) -> Option<(usize, usize)> {
    #[repr(C)]
    struct WinSize {
        ws_row: u16,
        ws_col: u16,
        ws_xpixel: u16,
        ws_ypixel: u16,
    }

    unsafe extern "C" {
        fn ioctl(
            fd: std::os::raw::c_int,
            request: std::os::raw::c_ulong,
            ...
        ) -> std::os::raw::c_int;
    }

    #[cfg(any(target_os = "linux", target_os = "android"))]
    const TIOCGWINSZ: std::os::raw::c_ulong = 0x5413;
    #[cfg(any(target_os = "macos", target_os = "ios", target_os = "freebsd"))]
    const TIOCGWINSZ: std::os::raw::c_ulong = 0x4008_7468;
    #[cfg(not(any(
        target_os = "linux",
        target_os = "android",
        target_os = "macos",
        target_os = "ios",
        target_os = "freebsd"
    )))]
    const TIOCGWINSZ: std::os::raw::c_ulong = 0;

    if TIOCGWINSZ == 0 {
        return None;
    }

    let mut size = WinSize {
        ws_row: 0,
        ws_col: 0,
        ws_xpixel: 0,
        ws_ypixel: 0,
    };

    // SAFETY: `ioctl` writes into a properly aligned `WinSize` value owned by
    // this function and does not retain the pointer after returning.
    let result = unsafe { ioctl(fd as std::os::raw::c_int, TIOCGWINSZ, &mut size) };
    if result == 0 && size.ws_col > 0 && size.ws_row > 0 {
        Some((usize::from(size.ws_col), usize::from(size.ws_row)))
    } else {
        None
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    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_ci_detection_github_actions() {
        with_env_lock(|| {
            unsafe {
                env::set_var("GITHUB_ACTIONS", "true");
            }
            assert!(is_ci_environment());
            unsafe {
                env::remove_var("GITHUB_ACTIONS");
            }
        });
    }

    #[test]
    fn test_ci_detection_gitlab() {
        with_env_lock(|| {
            unsafe {
                env::set_var("GITLAB_CI", "true");
            }
            assert!(is_ci_environment());
            unsafe {
                env::remove_var("GITLAB_CI");
            }
        });
    }

    #[test]
    fn test_no_color_env() {
        with_env_lock(|| {
            unsafe {
                env::set_var("NO_COLOR", "1");
            }
            assert_eq!(color_support(), ColorSupport::None);
            unsafe {
                env::remove_var("NO_COLOR");
            }
        });
    }

    #[test]
    fn test_truecolor_detection() {
        with_env_lock(|| {
            unsafe {
                env::remove_var("NO_COLOR");
                env::set_var("COLORTERM", "truecolor");
            }
            assert_eq!(color_support(), ColorSupport::TrueColor);
            unsafe {
                env::remove_var("COLORTERM");
            }
        });
    }

    #[test]
    fn test_256_color_detection() {
        with_env_lock(|| {
            unsafe {
                env::remove_var("NO_COLOR");
                env::remove_var("COLORTERM");
                env::set_var("TERM", "xterm-256color");
            }
            assert_eq!(color_support(), ColorSupport::Ansi256);
            unsafe {
                env::remove_var("TERM");
            }
        });
    }

    #[test]
    fn test_fallback_width_is_80() {
        with_env_lock(|| {
            unsafe {
                env::remove_var("COLUMNS");
            }
            let width = terminal_width();
            assert!(width == 80 || width > 0);
        });
    }

    #[test]
    fn test_columns_env_var_respected() {
        with_env_lock(|| {
            unsafe {
                env::set_var("COLUMNS", "123");
            }
            assert_eq!(terminal_width(), 123);
            assert_eq!(terminal_width_for_fd(2), 123);
            unsafe {
                env::remove_var("COLUMNS");
            }
        });
    }

    #[test]
    fn test_invalid_fd_not_interactive() {
        assert!(!is_tty(-1));
        assert!(!supports_interactive_output(-1));
        assert!(terminal_width_for_fd(-1) > 0);
        assert!(terminal_height_for_fd(-1) > 0);
    }
}