rich_rust 0.2.1

A Rust port of Python's Rich library for beautiful terminal output
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
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
//! Platform-specific test utilities and fixtures.
//!
//! This module provides utilities for handling platform-specific differences
//! in terminal output, line endings, and box-drawing characters.
//!
//! # Platform Differences
//!
//! - **Line Endings**: Windows uses `\r\n`, Unix uses `\n`
//! - **Box Drawing**: Some Windows terminals may not support Unicode box chars
//! - **Colors**: Color support varies by terminal emulator
//! - **Unicode Width**: CJK characters may render differently on some platforms
//!
//! # Example
//!
//! ```rust,ignore
//! use common::platform::*;
//!
//! #[test]
//! fn test_cross_platform() {
//!     let output = render_something();
//!     let normalized = normalize_line_endings(&output);
//!     assert_eq!(normalized, expected_output());
//! }
//! ```

// Environment variable manipulation requires unsafe in Rust 2024 edition.
// This is test-only code running in single-threaded contexts.
#![allow(dead_code)]

use std::borrow::Cow;

// =============================================================================
// Platform Detection
// =============================================================================

/// Current platform information.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct PlatformInfo {
    /// Operating system name.
    pub os: &'static str,
    /// Architecture.
    pub arch: &'static str,
    /// Whether this is Windows.
    pub is_windows: bool,
    /// Whether this is macOS.
    pub is_macos: bool,
    /// Whether this is Linux.
    pub is_linux: bool,
    /// Whether Unicode is likely well-supported.
    pub unicode_likely: bool,
}

impl PlatformInfo {
    /// Get current platform info.
    #[must_use]
    pub fn current() -> Self {
        Self {
            os: std::env::consts::OS,
            arch: std::env::consts::ARCH,
            is_windows: cfg!(target_os = "windows"),
            is_macos: cfg!(target_os = "macos"),
            is_linux: cfg!(target_os = "linux"),
            // Unicode is well-supported on modern macOS and Linux
            // Windows support depends on terminal, but modern Windows Terminal is good
            unicode_likely: !cfg!(target_os = "windows")
                || std::env::var("WT_SESSION").is_ok()
                || std::env::var("TERM_PROGRAM").is_ok_and(|v| v.contains("vscode")),
        }
    }

    /// Check if running in CI environment.
    #[must_use]
    pub fn is_ci() -> bool {
        std::env::var("CI").is_ok()
            || std::env::var("GITHUB_ACTIONS").is_ok()
            || std::env::var("TRAVIS").is_ok()
            || std::env::var("CIRCLECI").is_ok()
            || std::env::var("GITLAB_CI").is_ok()
    }

    /// Get a suffix for platform-specific snapshot files.
    #[must_use]
    pub fn snapshot_suffix(&self) -> &'static str {
        if self.is_windows {
            "windows"
        } else if self.is_macos {
            "macos"
        } else {
            "linux"
        }
    }
}

impl Default for PlatformInfo {
    fn default() -> Self {
        Self::current()
    }
}

// =============================================================================
// Line Ending Normalization
// =============================================================================

/// Normalize line endings to Unix-style (`\n`).
///
/// Converts all `\r\n` (Windows) and standalone `\r` (old Mac) to `\n`.
///
/// # Example
///
/// ```rust,ignore
/// let text = "line1\r\nline2\rline3\n";
/// let normalized = normalize_line_endings(text);
/// assert_eq!(normalized, "line1\nline2\nline3\n");
/// ```
#[must_use]
pub fn normalize_line_endings(s: &str) -> Cow<'_, str> {
    if !s.contains('\r') {
        return Cow::Borrowed(s);
    }
    Cow::Owned(s.replace("\r\n", "\n").replace('\r', "\n"))
}

/// Convert to platform-native line endings.
///
/// On Windows, converts `\n` to `\r\n`.
/// On Unix, returns unchanged.
#[must_use]
pub fn to_native_line_endings(s: &str) -> Cow<'_, str> {
    #[cfg(target_os = "windows")]
    {
        if !s.contains('\n') || s.contains("\r\n") {
            return Cow::Borrowed(s);
        }
        // Replace \n with \r\n, but not if already \r\n
        let mut result = String::with_capacity(s.len() + s.matches('\n').count());
        let mut chars = s.chars().peekable();
        while let Some(c) = chars.next() {
            if c == '\n' {
                result.push_str("\r\n");
            } else {
                result.push(c);
            }
        }
        Cow::Owned(result)
    }

    #[cfg(not(target_os = "windows"))]
    {
        Cow::Borrowed(s)
    }
}

// =============================================================================
// Box Drawing Character Handling
// =============================================================================

/// Box drawing character sets.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum BoxCharSet {
    /// Unicode box-drawing characters (default).
    #[default]
    Unicode,
    /// ASCII-safe characters for legacy terminals.
    Ascii,
}

impl BoxCharSet {
    /// Select character set based on platform capabilities.
    #[must_use]
    pub fn for_platform() -> Self {
        let info = PlatformInfo::current();
        if info.unicode_likely {
            Self::Unicode
        } else {
            Self::Ascii
        }
    }

    /// Get horizontal line character.
    #[must_use]
    pub fn horizontal(self) -> char {
        match self {
            Self::Unicode => '',
            Self::Ascii => '-',
        }
    }

    /// Get vertical line character.
    #[must_use]
    pub fn vertical(self) -> char {
        match self {
            Self::Unicode => '',
            Self::Ascii => '|',
        }
    }

    /// Get top-left corner character.
    #[must_use]
    pub fn top_left(self) -> char {
        match self {
            Self::Unicode => '',
            Self::Ascii => '+',
        }
    }

    /// Get top-right corner character.
    #[must_use]
    pub fn top_right(self) -> char {
        match self {
            Self::Unicode => '',
            Self::Ascii => '+',
        }
    }

    /// Get bottom-left corner character.
    #[must_use]
    pub fn bottom_left(self) -> char {
        match self {
            Self::Unicode => '',
            Self::Ascii => '+',
        }
    }

    /// Get bottom-right corner character.
    #[must_use]
    pub fn bottom_right(self) -> char {
        match self {
            Self::Unicode => '',
            Self::Ascii => '+',
        }
    }
}

/// Convert Unicode box-drawing characters to ASCII equivalents.
///
/// Useful for comparing output across platforms with different Unicode support.
#[must_use]
pub fn unicode_to_ascii_boxes(s: &str) -> String {
    s.chars()
        .map(|c| match c {
            '' | '' | '' => '-',
            '' | '' | '' => '|',
            '' | '' | '' | '' => '+',
            '' | '' | '' | '' => '+',
            '' | '' | '' | '' => '+',
            '' | '' | '' | '' => '+',
            '' | '' | '' => '+',
            '' | '' | '' => '+',
            '' | '' | '' => '+',
            '' | '' | '' => '+',
            '' | '' | '' => '+',
            _ => c,
        })
        .collect()
}

// =============================================================================
// Platform-Specific Assertions
// =============================================================================

/// Compare strings with normalized line endings.
///
/// Useful for cross-platform snapshot comparisons.
#[track_caller]
pub fn assert_eq_normalized(context: &str, actual: &str, expected: &str) {
    let actual_norm = normalize_line_endings(actual);
    let expected_norm = normalize_line_endings(expected);

    if actual_norm != expected_norm {
        panic!(
            "{context}: strings differ after line ending normalization.\n\
             Expected:\n{expected_norm:?}\n\
             Actual:\n{actual_norm:?}"
        );
    }
}

/// Compare strings with normalized line endings and box characters.
///
/// Converts both to ASCII boxes for maximum compatibility.
#[track_caller]
pub fn assert_eq_platform_agnostic(context: &str, actual: &str, expected: &str) {
    let actual_norm = unicode_to_ascii_boxes(&normalize_line_endings(actual));
    let expected_norm = unicode_to_ascii_boxes(&normalize_line_endings(expected));

    if actual_norm != expected_norm {
        panic!(
            "{context}: strings differ after platform normalization.\n\
             Expected:\n{expected_norm:?}\n\
             Actual:\n{actual_norm:?}"
        );
    }
}

/// Skip test if not on expected platform.
///
/// Use this to skip platform-specific tests on other platforms.
///
/// # Example
///
/// ```rust,ignore
/// #[test]
/// fn test_windows_specific() {
///     skip_unless_windows();
///     // Windows-only test code...
/// }
/// ```
#[track_caller]
pub fn skip_unless_windows() {
    if !cfg!(target_os = "windows") {
        eprintln!("Skipping test: Windows-only");
    }
}

/// Skip test if not on Unix-like platform.
#[track_caller]
pub fn skip_unless_unix() {
    if cfg!(target_os = "windows") {
        eprintln!("Skipping test: Unix-only");
    }
}

/// Skip test if not in CI environment.
#[track_caller]
pub fn skip_unless_ci() {
    if !PlatformInfo::is_ci() {
        eprintln!("Skipping test: CI-only");
    }
}

// =============================================================================
// Environment Helpers
// =============================================================================

/// Temporarily set an environment variable for the duration of a closure.
///
/// The original value is restored after the closure completes.
///
/// # Safety
///
/// This function modifies environment variables, which is inherently unsafe
/// in multi-threaded programs. Only use in single-threaded test contexts.
pub fn with_env_var<F, R>(key: &str, value: &str, f: F) -> R
where
    F: FnOnce() -> R,
{
    let original = std::env::var(key).ok();
    // SAFETY: Test-only code, running in single-threaded test context
    unsafe { std::env::set_var(key, value) };

    let result = f();

    // SAFETY: Test-only code, running in single-threaded test context
    match original {
        Some(v) => unsafe { std::env::set_var(key, v) },
        None => unsafe { std::env::remove_var(key) },
    }

    result
}

/// Temporarily remove an environment variable for the duration of a closure.
///
/// # Safety
///
/// This function modifies environment variables, which is inherently unsafe
/// in multi-threaded programs. Only use in single-threaded test contexts.
pub fn without_env_var<F, R>(key: &str, f: F) -> R
where
    F: FnOnce() -> R,
{
    let original = std::env::var(key).ok();
    // SAFETY: Test-only code, running in single-threaded test context
    unsafe { std::env::remove_var(key) };

    let result = f();

    if let Some(v) = original {
        // SAFETY: Test-only code, running in single-threaded test context
        unsafe { std::env::set_var(key, v) };
    }

    result
}

// =============================================================================
// Terminal Environment Simulation
// =============================================================================

/// Simulated terminal environment for testing.
#[derive(Debug, Clone)]
pub struct TerminalEnv {
    /// TERM environment variable value.
    pub term: Option<String>,
    /// COLORTERM environment variable value.
    pub colorterm: Option<String>,
    /// NO_COLOR environment variable (if set).
    pub no_color: bool,
    /// FORCE_COLOR environment variable (if set).
    pub force_color: bool,
    /// Terminal width hint.
    pub columns: Option<u16>,
    /// Terminal height hint.
    pub lines: Option<u16>,
}

impl TerminalEnv {
    /// Create a default terminal environment.
    #[must_use]
    pub fn new() -> Self {
        Self {
            term: Some("xterm-256color".to_string()),
            colorterm: Some("truecolor".to_string()),
            no_color: false,
            force_color: false,
            columns: Some(80),
            lines: Some(24),
        }
    }

    /// Create a dumb terminal (no colors, no features).
    #[must_use]
    pub fn dumb() -> Self {
        Self {
            term: Some("dumb".to_string()),
            colorterm: None,
            no_color: false,
            force_color: false,
            columns: Some(80),
            lines: Some(24),
        }
    }

    /// Create a no-color environment.
    #[must_use]
    pub fn no_color() -> Self {
        Self {
            term: Some("xterm-256color".to_string()),
            colorterm: None,
            no_color: true,
            force_color: false,
            columns: Some(80),
            lines: Some(24),
        }
    }

    /// Apply this environment and run a closure.
    ///
    /// # Safety
    ///
    /// This function modifies environment variables, which is inherently unsafe
    /// in multi-threaded programs. Only use in single-threaded test contexts.
    pub fn apply<F, R>(&self, f: F) -> R
    where
        F: FnOnce() -> R,
    {
        // Save originals
        let orig_term = std::env::var("TERM").ok();
        let orig_colorterm = std::env::var("COLORTERM").ok();
        let orig_no_color = std::env::var("NO_COLOR").ok();
        let orig_force_color = std::env::var("FORCE_COLOR").ok();
        let orig_columns = std::env::var("COLUMNS").ok();
        let orig_lines = std::env::var("LINES").ok();

        // SAFETY: Test-only code, running in single-threaded test context
        unsafe {
            // Set new values
            match &self.term {
                Some(v) => std::env::set_var("TERM", v),
                None => std::env::remove_var("TERM"),
            }
            match &self.colorterm {
                Some(v) => std::env::set_var("COLORTERM", v),
                None => std::env::remove_var("COLORTERM"),
            }
            if self.no_color {
                std::env::set_var("NO_COLOR", "1");
            } else {
                std::env::remove_var("NO_COLOR");
            }
            if self.force_color {
                std::env::set_var("FORCE_COLOR", "1");
            } else {
                std::env::remove_var("FORCE_COLOR");
            }
            if let Some(cols) = self.columns {
                std::env::set_var("COLUMNS", cols.to_string());
            } else {
                std::env::remove_var("COLUMNS");
            }
            if let Some(lines) = self.lines {
                std::env::set_var("LINES", lines.to_string());
            } else {
                std::env::remove_var("LINES");
            }
        }

        // Run closure
        let result = f();

        // SAFETY: Test-only code, running in single-threaded test context
        unsafe {
            // Restore originals
            match orig_term {
                Some(v) => std::env::set_var("TERM", v),
                None => std::env::remove_var("TERM"),
            }
            match orig_colorterm {
                Some(v) => std::env::set_var("COLORTERM", v),
                None => std::env::remove_var("COLORTERM"),
            }
            match orig_no_color {
                Some(v) => std::env::set_var("NO_COLOR", v),
                None => std::env::remove_var("NO_COLOR"),
            }
            match orig_force_color {
                Some(v) => std::env::set_var("FORCE_COLOR", v),
                None => std::env::remove_var("FORCE_COLOR"),
            }
            match orig_columns {
                Some(v) => std::env::set_var("COLUMNS", v),
                None => std::env::remove_var("COLUMNS"),
            }
            match orig_lines {
                Some(v) => std::env::set_var("LINES", v),
                None => std::env::remove_var("LINES"),
            }
        }

        result
    }
}

impl Default for TerminalEnv {
    fn default() -> Self {
        Self::new()
    }
}

// =============================================================================
// Tests
// =============================================================================

#[cfg(test)]
mod tests {
    use super::*;
    use serial_test::serial;

    #[test]
    fn test_platform_info() {
        let info = PlatformInfo::current();
        assert!(!info.os.is_empty());
        assert!(!info.arch.is_empty());
        // At least one platform flag should be true
        assert!(info.is_windows || info.is_macos || info.is_linux);
    }

    #[test]
    fn test_normalize_line_endings() {
        assert_eq!(normalize_line_endings("hello\nworld"), "hello\nworld");
        assert_eq!(normalize_line_endings("hello\r\nworld"), "hello\nworld");
        assert_eq!(normalize_line_endings("hello\rworld"), "hello\nworld");
        assert_eq!(normalize_line_endings("a\r\nb\rc\n"), "a\nb\nc\n");
    }

    #[test]
    fn test_unicode_to_ascii_boxes() {
        // Each box char converts 1:1
        assert_eq!(unicode_to_ascii_boxes("┌─┐"), "+-+");
        assert_eq!(unicode_to_ascii_boxes("│x│"), "|x|");
        assert_eq!(unicode_to_ascii_boxes("└─┘"), "+-+");
        assert_eq!(unicode_to_ascii_boxes("Hello"), "Hello");
        // Multiple horizontal chars
        assert_eq!(unicode_to_ascii_boxes("┌──┐"), "+--+");
    }

    #[test]
    fn test_box_char_set() {
        let unicode = BoxCharSet::Unicode;
        assert_eq!(unicode.horizontal(), '');
        assert_eq!(unicode.vertical(), '');

        let ascii = BoxCharSet::Ascii;
        assert_eq!(ascii.horizontal(), '-');
        assert_eq!(ascii.vertical(), '|');
    }

    #[test]
    #[serial]
    fn test_with_env_var() {
        let original = std::env::var("TEST_PLATFORM_VAR").ok();

        with_env_var("TEST_PLATFORM_VAR", "test_value", || {
            assert_eq!(std::env::var("TEST_PLATFORM_VAR").unwrap(), "test_value");
        });

        // Should be restored
        assert_eq!(std::env::var("TEST_PLATFORM_VAR").ok(), original);
    }

    #[test]
    #[serial]
    fn test_terminal_env_apply() {
        let env = TerminalEnv::dumb();
        env.apply(|| {
            assert_eq!(std::env::var("TERM").unwrap(), "dumb");
        });
    }

    #[test]
    #[serial]
    fn test_terminal_env_no_color() {
        let env = TerminalEnv::no_color();
        env.apply(|| {
            assert!(std::env::var("NO_COLOR").is_ok());
        });
    }

    #[test]
    fn test_assert_eq_normalized() {
        assert_eq_normalized("same content", "hello\nworld", "hello\nworld");
        assert_eq_normalized("crlf vs lf", "hello\nworld", "hello\r\nworld");
    }

    #[test]
    fn test_assert_eq_platform_agnostic() {
        assert_eq_platform_agnostic("same content", "hello", "hello");
        // Box chars convert 1:1
        assert_eq_platform_agnostic("box chars", "┌─┐", "+-+");
        assert_eq_platform_agnostic("box chars multi", "┌──┐", "+--+");
    }
}