gilt 0.5.0

A fast, rich terminal formatting library — Rust port of Python's rich
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
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
//! Status indicator with a spinner animation.
//!
//! Port of Python rich's `status.py`. Displays a status message alongside a
//! spinning animation, using a [`Live`] display for in-place terminal updates.
//!
//! # Examples
//!
//! ```
//! use gilt::status::Status;
//!
//! let mut status = Status::new("Loading...");
//! status.start();
//! status.update().status("Processing...").apply();
//! status.stop();
//! ```

use crate::console::Console;
use crate::live::{ConsoleRef, Live};
use crate::spinner::{Spinner, SpinnerError};
use crate::style::Style;
use crate::text::Text;

// ---------------------------------------------------------------------------
// StatusError
// ---------------------------------------------------------------------------

/// Error returned by Status operations.
#[derive(Debug)]
pub enum StatusError {
    /// The requested spinner name was not found.
    Spinner(SpinnerError),
}

impl std::fmt::Display for StatusError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            StatusError::Spinner(e) => write!(f, "status spinner error: {}", e),
        }
    }
}

impl std::error::Error for StatusError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            StatusError::Spinner(e) => Some(e),
        }
    }
}

impl From<SpinnerError> for StatusError {
    fn from(e: SpinnerError) -> Self {
        StatusError::Spinner(e)
    }
}

// ---------------------------------------------------------------------------
// StatusUpdate builder
// ---------------------------------------------------------------------------

/// A builder for applying selective updates to a [`Status`].
///
/// Obtained via [`Status::update`]. Call setter methods to stage changes,
/// then [`apply`](StatusUpdate::apply) to commit them.
pub struct StatusUpdate<'a> {
    status: &'a mut Status,
    new_status: Option<String>,
    new_spinner: Option<String>,
    new_spinner_style: Option<Style>,
    new_speed: Option<f64>,
}

impl<'a> StatusUpdate<'a> {
    /// Set a new status text.
    #[must_use]
    pub fn status(mut self, status: &str) -> Self {
        self.new_status = Some(status.to_string());
        self
    }

    /// Set a new spinner animation by name.
    #[must_use]
    pub fn spinner(mut self, name: &str) -> Self {
        self.new_spinner = Some(name.to_string());
        self
    }

    /// Set a new spinner style.
    #[must_use]
    pub fn spinner_style(mut self, style: Style) -> Self {
        self.new_spinner_style = Some(style);
        self
    }

    /// Set a new speed multiplier.
    #[must_use]
    pub fn speed(mut self, speed: f64) -> Self {
        self.new_speed = Some(speed);
        self
    }

    /// Apply the staged updates. Returns `Ok(())` on success, or an error
    /// if a new spinner name was invalid.
    pub fn apply(self) -> Result<(), StatusError> {
        // Apply simple property changes first.
        if let Some(ref text) = self.new_status {
            self.status.status_text = text.clone();
        }
        if let Some(style) = self.new_spinner_style {
            self.status.spinner_style = style;
        }
        if let Some(speed) = self.new_speed {
            self.status.speed = speed;
        }

        if let Some(ref spinner_name) = self.new_spinner {
            // Create a brand new spinner with the current properties.
            let mut spinner = Spinner::new(spinner_name)?;
            spinner = spinner
                .with_text(Text::new(&self.status.status_text, Style::null()))
                .with_style(self.status.spinner_style.clone())
                .with_speed(self.status.speed);
            self.status.spinner = spinner;

            // Push the new renderable to the live display.
            let text = render_spinner_snapshot(&self.status.spinner);
            self.status.live.update_renderable(text, true);
        } else {
            // Update the existing spinner in place.
            self.status.spinner.update(
                Some(Text::new(&self.status.status_text, Style::null())),
                Some(self.status.spinner_style.clone()),
                Some(self.status.speed),
            );
        }

        Ok(())
    }
}

// ---------------------------------------------------------------------------
// Status
// ---------------------------------------------------------------------------

/// Displays a status indicator with a spinner animation.
///
/// `Status` combines a [`Spinner`] with a [`Live`] display to show an
/// animated status message in the terminal. The spinner and status text
/// can be updated at any time.
///
/// # RAII
///
/// `Status` implements [`Drop`], which calls [`stop`](Status::stop) to
/// ensure the live display is cleanly shut down when the value goes out
/// of scope.
///
/// # Examples
///
/// ```
/// use gilt::status::Status;
///
/// let mut status = Status::new("Downloading...");
/// status.start();
/// // ... do work ...
/// status.update().status("Compiling...").apply().unwrap();
/// // ... do more work ...
/// status.stop();
/// ```
pub struct Status {
    /// The current status text.
    pub status_text: String,
    /// The style applied to the spinner frame.
    pub spinner_style: Style,
    /// The speed multiplier for the spinner.
    pub speed: f64,
    /// The spinner animation.
    spinner: Spinner,
    /// The live display that handles in-place terminal rendering.
    live: Live,
}

/// Render a spinner at time 0 to produce a `Text` snapshot for the live display.
fn render_spinner_snapshot(spinner: &Spinner) -> Text {
    let mut spinner_clone = Spinner::new(&spinner.name).unwrap();
    spinner_clone = spinner_clone.with_speed(spinner.speed);
    if let Some(ref text) = spinner.text {
        spinner_clone = spinner_clone.with_text(text.clone());
    }
    if let Some(ref style) = spinner.style {
        spinner_clone = spinner_clone.with_style(style.clone());
    }
    spinner_clone.render(0.0)
}

impl Status {
    /// Create a new `Status` with default settings.
    ///
    /// Defaults:
    /// - Spinner: `"dots"`
    /// - Speed: `1.0`
    /// - Refresh per second: `12.5`
    /// - Spinner style: `Style::null()` (no special styling)
    ///
    /// # Panics
    ///
    /// Panics if the default spinner `"dots"` is not found in the spinner
    /// registry (this should never happen).
    pub fn new(status: &str) -> Self {
        Self::try_new(status, "dots", Style::null(), 1.0, 12.5)
            .expect("default spinner 'dots' must exist")
    }

    /// Try to create a new `Status`, returning an error if the spinner
    /// name is invalid.
    fn try_new(
        status: &str,
        spinner_name: &str,
        spinner_style: Style,
        speed: f64,
        refresh_per_second: f64,
    ) -> Result<Self, StatusError> {
        let spinner = Spinner::new(spinner_name)?
            .with_text(Text::new(status, Style::null()))
            .with_style(spinner_style.clone())
            .with_speed(speed);

        let renderable_text = render_spinner_snapshot(&spinner);
        let live = Live::new(renderable_text)
            .with_refresh_per_second(refresh_per_second)
            .with_transient(true);

        Ok(Status {
            status_text: status.to_string(),
            spinner_style,
            speed,
            spinner,
            live,
        })
    }

    /// Builder method: set the spinner animation by name.
    ///
    /// # Errors
    ///
    /// Returns `StatusError::Spinner` if the name is not found.
    pub fn with_spinner(mut self, name: &str) -> Result<Self, StatusError> {
        let spinner = Spinner::new(name)?
            .with_text(Text::new(&self.status_text, Style::null()))
            .with_style(self.spinner_style.clone())
            .with_speed(self.speed);
        self.spinner = spinner;
        let text = render_spinner_snapshot(&self.spinner);
        self.live.update_renderable(text, false);
        Ok(self)
    }

    /// Builder method: set the spinner style.
    #[must_use]
    pub fn with_spinner_style(mut self, style: Style) -> Self {
        self.spinner_style = style.clone();
        self.spinner =
            std::mem::replace(&mut self.spinner, Spinner::new("dots").unwrap()).with_style(style);
        self
    }

    /// Builder method: set the speed multiplier.
    #[must_use]
    pub fn with_speed(mut self, speed: f64) -> Self {
        self.speed = speed;
        self.spinner =
            std::mem::replace(&mut self.spinner, Spinner::new("dots").unwrap()).with_speed(speed);
        self
    }

    /// Builder method: set a custom console for the live display.
    #[must_use]
    pub fn with_console(mut self, console: Console) -> Self {
        // Rebuild live with the new console, preserving other settings.
        let renderable_text = render_spinner_snapshot(&self.spinner);
        self.live = Live::new(renderable_text)
            .with_console(console)
            .with_refresh_per_second(self.live.refresh_per_second)
            .with_transient(self.live.transient);
        self
    }

    /// Builder method: set the refresh rate (refreshes per second).
    #[must_use]
    pub fn with_refresh_per_second(mut self, rate: f64) -> Self {
        let renderable_text = render_spinner_snapshot(&self.spinner);
        self.live = Live::new(renderable_text)
            .with_refresh_per_second(rate)
            .with_transient(self.live.transient);
        self
    }

    /// Get a reference to the spinner.
    pub fn renderable(&self) -> &Spinner {
        &self.spinner
    }

    /// Get a reference to the console (from the live display).
    pub fn console(&self) -> ConsoleRef<'_> {
        self.live.console()
    }

    /// Begin an update to the status. Returns a builder that can change
    /// the status text, spinner, style, and speed.
    ///
    /// Call `.apply()` on the returned builder to commit the changes.
    pub fn update(&mut self) -> StatusUpdate<'_> {
        StatusUpdate {
            status: self,
            new_status: None,
            new_spinner: None,
            new_spinner_style: None,
            new_speed: None,
        }
    }

    /// Start the live display.
    pub fn start(&mut self) {
        self.live.start();
    }

    /// Stop the live display.
    pub fn stop(&mut self) {
        self.live.stop();
    }

    /// Check if the live display has been started.
    pub fn is_started(&self) -> bool {
        self.live.is_started()
    }
}

impl Drop for Status {
    fn drop(&mut self) {
        self.stop();
    }
}

// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------

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

    // -- Default construction -----------------------------------------------

    #[test]
    fn test_default_construction() {
        let status = Status::new("Loading...");
        assert_eq!(status.status_text, "Loading...");
        assert!(status.spinner_style.is_null());
        assert_eq!(status.speed, 1.0);
        assert!(!status.is_started());
    }

    #[test]
    fn test_default_spinner_is_dots() {
        let status = Status::new("test");
        assert_eq!(status.spinner.name, "dots");
    }

    #[test]
    fn test_default_spinner_has_text() {
        let status = Status::new("Working");
        assert!(status.spinner.text.is_some());
        assert_eq!(status.spinner.text.as_ref().unwrap().plain(), "Working");
    }

    // -- Builder methods ----------------------------------------------------

    #[test]
    fn test_with_spinner() {
        let status = Status::new("test").with_spinner("line").unwrap();
        assert_eq!(status.spinner.name, "line");
    }

    #[test]
    fn test_with_spinner_invalid() {
        let result = Status::new("test").with_spinner("nonexistent_xyz");
        assert!(result.is_err());
    }

    #[test]
    fn test_with_spinner_preserves_text() {
        let status = Status::new("my status").with_spinner("line").unwrap();
        assert!(status.spinner.text.is_some());
        assert_eq!(status.spinner.text.as_ref().unwrap().plain(), "my status");
    }

    #[test]
    fn test_with_spinner_style() {
        let style = Style::parse("bold red").unwrap();
        let status = Status::new("test").with_spinner_style(style.clone());
        assert_eq!(status.spinner_style, style);
        assert_eq!(status.spinner.style, Some(style));
    }

    #[test]
    fn test_with_speed() {
        let status = Status::new("test").with_speed(2.0);
        assert_eq!(status.speed, 2.0);
        assert_eq!(status.spinner.speed, 2.0);
    }

    #[test]
    fn test_with_console() {
        let console = Console::builder().width(120).build();
        let status = Status::new("test").with_console(console);
        assert_eq!(status.console().width(), 120);
    }

    #[test]
    fn test_with_refresh_per_second() {
        let status = Status::new("test").with_refresh_per_second(30.0);
        assert_eq!(status.live.refresh_per_second, 30.0);
    }

    #[test]
    fn test_builder_chaining() {
        let style = Style::parse("bold").unwrap();
        let status = Status::new("test")
            .with_spinner_style(style.clone())
            .with_speed(3.0)
            .with_spinner("line")
            .unwrap();

        assert_eq!(status.spinner.name, "line");
        assert_eq!(status.spinner_style, style);
        assert_eq!(status.speed, 3.0);
    }

    // -- Update with new status text ----------------------------------------

    #[test]
    fn test_update_status_text() {
        let mut status = Status::new("old text");
        status.update().status("new text").apply().unwrap();
        assert_eq!(status.status_text, "new text");
        // Spinner text should also be updated
        assert_eq!(status.spinner.text.as_ref().unwrap().plain(), "new text");
    }

    #[test]
    fn test_update_status_text_preserves_spinner() {
        let mut status = Status::new("test").with_spinner("line").unwrap();
        status.update().status("changed").apply().unwrap();
        assert_eq!(status.spinner.name, "line");
        assert_eq!(status.status_text, "changed");
    }

    // -- Update with new spinner name ---------------------------------------

    #[test]
    fn test_update_spinner_name() {
        let mut status = Status::new("test");
        assert_eq!(status.spinner.name, "dots");
        status.update().spinner("line").apply().unwrap();
        assert_eq!(status.spinner.name, "line");
    }

    #[test]
    fn test_update_spinner_name_preserves_text() {
        let mut status = Status::new("keep me");
        status.update().spinner("line").apply().unwrap();
        assert!(status.spinner.text.is_some());
        assert_eq!(status.spinner.text.as_ref().unwrap().plain(), "keep me");
    }

    #[test]
    fn test_update_spinner_invalid_name() {
        let mut status = Status::new("test");
        let result = status.update().spinner("nonexistent_xyz").apply();
        assert!(result.is_err());
        // Spinner should remain unchanged on error
        assert_eq!(status.spinner.name, "dots");
    }

    // -- Update with new style ---------------------------------------------

    #[test]
    fn test_update_style() {
        let mut status = Status::new("test");
        let style = Style::parse("bold green").unwrap();
        status
            .update()
            .spinner_style(style.clone())
            .apply()
            .unwrap();
        assert_eq!(status.spinner_style, style);
    }

    #[test]
    fn test_update_style_applied_to_spinner_update() {
        let mut status = Status::new("test");
        let style = Style::parse("italic").unwrap();
        status
            .update()
            .spinner_style(style.clone())
            .apply()
            .unwrap();
        // The spinner's update method was called with the new style
        assert_eq!(status.spinner_style, style);
    }

    // -- Update with new speed ---------------------------------------------

    #[test]
    fn test_update_speed() {
        let mut status = Status::new("test");
        assert_eq!(status.speed, 1.0);
        status.update().speed(5.0).apply().unwrap();
        assert_eq!(status.speed, 5.0);
    }

    // -- Combined updates --------------------------------------------------

    #[test]
    fn test_update_multiple_fields() {
        let mut status = Status::new("original");
        let style = Style::parse("bold").unwrap();
        status
            .update()
            .status("changed")
            .speed(2.5)
            .spinner_style(style.clone())
            .apply()
            .unwrap();

        assert_eq!(status.status_text, "changed");
        assert_eq!(status.speed, 2.5);
        assert_eq!(status.spinner_style, style);
    }

    #[test]
    fn test_update_all_with_new_spinner() {
        let mut status = Status::new("original");
        let style = Style::parse("underline").unwrap();
        status
            .update()
            .status("new status")
            .spinner("line")
            .spinner_style(style.clone())
            .speed(4.0)
            .apply()
            .unwrap();

        assert_eq!(status.status_text, "new status");
        assert_eq!(status.spinner.name, "line");
        assert_eq!(status.spinner_style, style);
        assert_eq!(status.speed, 4.0);
        assert_eq!(status.spinner.text.as_ref().unwrap().plain(), "new status");
    }

    // -- Start/stop lifecycle ----------------------------------------------

    #[test]
    fn test_start_stop() {
        let mut status = Status::new("test");
        assert!(!status.is_started());
        status.start();
        assert!(status.is_started());
        status.stop();
        assert!(!status.is_started());
    }

    #[test]
    fn test_start_idempotent() {
        let mut status = Status::new("test");
        status.start();
        status.start(); // should not panic
        assert!(status.is_started());
        status.stop();
    }

    #[test]
    fn test_stop_idempotent() {
        let mut status = Status::new("test");
        status.stop(); // not started, should not panic
        assert!(!status.is_started());
    }

    #[test]
    fn test_stop_after_start() {
        let mut status = Status::new("test");
        status.start();
        assert!(status.is_started());
        status.stop();
        assert!(!status.is_started());
    }

    // -- Drop calls stop ---------------------------------------------------

    #[test]
    fn test_drop_calls_stop() {
        let mut status = Status::new("test");
        status.start();
        assert!(status.is_started());
        // Drop triggers stop via the Drop impl
        drop(status);
        // If we get here without panicking, drop worked correctly.
    }

    #[test]
    fn test_drop_when_not_started() {
        let status = Status::new("test");
        // Should not panic on drop when not started
        drop(status);
    }

    // -- Renderable accessor -----------------------------------------------

    #[test]
    fn test_renderable_returns_spinner() {
        let status = Status::new("test");
        let spinner = status.renderable();
        assert_eq!(spinner.name, "dots");
    }

    // -- Console accessor --------------------------------------------------

    #[test]
    fn test_console_accessor() {
        let status = Status::new("test");
        let _console = status.console();
    }

    #[test]
    fn test_console_from_builder() {
        let console = Console::builder().width(100).build();
        let status = Status::new("test").with_console(console);
        assert_eq!(status.console().width(), 100);
    }

    // -- Error display -----------------------------------------------------

    #[test]
    fn test_status_error_display() {
        let err = StatusError::Spinner(SpinnerError("test error".to_string()));
        let msg = format!("{}", err);
        assert!(msg.contains("test error"));
    }

    #[test]
    fn test_status_error_source() {
        let inner = SpinnerError("inner".to_string());
        let err = StatusError::Spinner(inner);
        let source = std::error::Error::source(&err);
        assert!(source.is_some());
    }

    // -- try_new -----------------------------------------------------------

    #[test]
    fn test_try_new_invalid_spinner() {
        let result = Status::try_new("test", "nonexistent_xyz", Style::null(), 1.0, 12.5);
        assert!(result.is_err());
    }

    #[test]
    fn test_try_new_valid_spinner() {
        let result = Status::try_new("test", "line", Style::null(), 1.0, 12.5);
        assert!(result.is_ok());
        let status = result.unwrap();
        assert_eq!(status.spinner.name, "line");
    }

    // -- Update does not crash when started --------------------------------

    #[test]
    fn test_update_while_started() {
        let mut status = Status::new("running");
        status.start();
        status.update().status("still running").apply().unwrap();
        assert_eq!(status.status_text, "still running");
        status.stop();
    }

    #[test]
    fn test_update_spinner_while_started() {
        let mut status = Status::new("running");
        status.start();
        status.update().spinner("line").apply().unwrap();
        assert_eq!(status.spinner.name, "line");
        status.stop();
    }
}