richrs 0.2.1

A Rust port of the Rich Python 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
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
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
//! User prompts with validation and styling.
//!
//! This module provides various prompt types for getting user input
//! with optional validation, default values, and styled output.
//!
//! # Example
//!
//! ```ignore
//! use richrs::prelude::*;
//! use richrs::prompt::{Prompt, Confirm};
//!
//! let name = Prompt::new("What is your name?").ask()?;
//! let confirmed = Confirm::new("Are you sure?").ask()?;
//! ```

use crate::errors::Result;
use crate::style::Style;
use std::io::{self, BufRead, Write};

/// A text prompt for getting user input.
#[derive(Debug, Clone)]
pub struct Prompt {
    /// The prompt message.
    message: String,
    /// Default value if user presses enter.
    default: Option<String>,
    /// Valid choices (if restricted).
    choices: Option<Vec<String>>,
    /// Whether choices are case-sensitive.
    case_sensitive: bool,
    /// Whether to show the default value.
    show_default: bool,
    /// Whether to show available choices.
    show_choices: bool,
    /// Whether input should be hidden (for passwords).
    password: bool,
    /// Style for the prompt.
    prompt_style: Option<Style>,
}

impl Prompt {
    /// Creates a new Prompt with the given message.
    #[must_use]
    #[inline]
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            default: None,
            choices: None,
            case_sensitive: true,
            show_default: true,
            show_choices: true,
            password: false,
            prompt_style: None,
        }
    }

    /// Sets the default value.
    #[must_use]
    #[inline]
    pub fn default(mut self, default: impl Into<String>) -> Self {
        self.default = Some(default.into());
        self
    }

    /// Sets valid choices.
    #[must_use]
    pub fn choices<I, S>(mut self, choices: I) -> Self
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        self.choices = Some(choices.into_iter().map(Into::into).collect());
        self
    }

    /// Sets whether choices are case-sensitive.
    #[must_use]
    #[inline]
    pub const fn case_sensitive(mut self, sensitive: bool) -> Self {
        self.case_sensitive = sensitive;
        self
    }

    /// Sets whether to show the default value.
    #[must_use]
    #[inline]
    pub const fn show_default(mut self, show: bool) -> Self {
        self.show_default = show;
        self
    }

    /// Sets whether to show available choices.
    #[must_use]
    #[inline]
    pub const fn show_choices(mut self, show: bool) -> Self {
        self.show_choices = show;
        self
    }

    /// Sets whether input should be hidden (for passwords).
    #[must_use]
    #[inline]
    pub const fn password(mut self, is_password: bool) -> Self {
        self.password = is_password;
        self
    }

    /// Sets the style for the prompt.
    #[must_use]
    #[inline]
    pub fn style(mut self, style: Style) -> Self {
        self.prompt_style = Some(style);
        self
    }

    /// Builds the full prompt string.
    fn build_prompt(&self) -> String {
        let mut prompt = self.message.clone();

        if self.show_choices {
            if let Some(ref choices) = self.choices {
                prompt.push_str(&format!(" [{}]", choices.join("/")));
            }
        }

        if self.show_default {
            if let Some(ref default) = self.default {
                prompt.push_str(&format!(" ({})", default));
            }
        }

        prompt.push_str(": ");
        prompt
    }

    /// Validates the input against choices if present.
    fn validate(&self, input: &str) -> bool {
        if let Some(ref choices) = self.choices {
            if self.case_sensitive {
                choices.iter().any(|c| c == input)
            } else {
                let lower = input.to_lowercase();
                choices.iter().any(|c| c.to_lowercase() == lower)
            }
        } else {
            true
        }
    }

    /// Asks the user for input.
    ///
    /// # Errors
    ///
    /// Returns an error if reading from stdin fails or if validation fails
    /// after multiple invalid attempts.
    pub fn ask(&self) -> Result<String> {
        let prompt = self.build_prompt();
        let stdin = io::stdin();
        let mut stdout = io::stdout();

        loop {
            // Print prompt
            if let Some(ref style) = self.prompt_style {
                eprint!("{}", style.to_ansi());
            }
            eprint!("{}", prompt);
            if self.prompt_style.is_some() {
                eprint!("\x1b[0m");
            }
            stdout.flush()?;

            // Read input
            // Note: For password input, we'd ideally disable echo
            // For now, just read normally (crossterm could be used for proper password input)
            let mut input = String::new();
            stdin.lock().read_line(&mut input)?;

            let input = input.trim().to_string();

            // Handle empty input
            if input.is_empty() {
                if let Some(ref default) = self.default {
                    return Ok(default.clone());
                }
            }

            // Validate
            if self.validate(&input) {
                return Ok(input);
            }

            // Invalid choice
            eprintln!(
                "Invalid choice. Please select from: {}",
                self.choices
                    .as_ref()
                    .map(|c| c.join(", "))
                    .unwrap_or_default()
            );
        }
    }
}

/// A yes/no confirmation prompt.
#[derive(Debug, Clone)]
pub struct Confirm {
    /// The prompt message.
    message: String,
    /// Default value if user presses enter.
    default: Option<bool>,
    /// Style for the prompt.
    prompt_style: Option<Style>,
}

impl Confirm {
    /// Creates a new Confirm prompt with the given message.
    #[must_use]
    #[inline]
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            default: None,
            prompt_style: None,
        }
    }

    /// Sets the default value (true for yes, false for no).
    #[must_use]
    #[inline]
    pub const fn default(mut self, default: bool) -> Self {
        self.default = Some(default);
        self
    }

    /// Sets the style for the prompt.
    #[must_use]
    #[inline]
    pub fn style(mut self, style: Style) -> Self {
        self.prompt_style = Some(style);
        self
    }

    /// Asks the user for confirmation.
    ///
    /// # Errors
    ///
    /// Returns an error if reading from stdin fails.
    pub fn ask(&self) -> Result<bool> {
        let choices = match self.default {
            Some(true) => "[Y/n]",
            Some(false) => "[y/N]",
            None => "[y/n]",
        };

        let prompt = format!("{} {}: ", self.message, choices);
        let stdin = io::stdin();
        let mut stdout = io::stdout();

        loop {
            // Print prompt
            if let Some(ref style) = self.prompt_style {
                eprint!("{}", style.to_ansi());
            }
            eprint!("{}", prompt);
            if self.prompt_style.is_some() {
                eprint!("\x1b[0m");
            }
            stdout.flush()?;

            // Read input
            let mut input = String::new();
            stdin.lock().read_line(&mut input)?;

            let input = input.trim().to_lowercase();

            // Handle empty input
            if input.is_empty() {
                if let Some(default) = self.default {
                    return Ok(default);
                }
                eprintln!("Please enter y or n");
                continue;
            }

            // Parse response
            match input.as_str() {
                "y" | "yes" | "true" | "1" => return Ok(true),
                "n" | "no" | "false" | "0" => return Ok(false),
                _ => {
                    eprintln!("Please enter y or n");
                }
            }
        }
    }
}

/// An integer input prompt.
#[derive(Debug, Clone)]
pub struct IntPrompt {
    /// The prompt message.
    message: String,
    /// Default value.
    default: Option<i64>,
    /// Minimum value.
    min: Option<i64>,
    /// Maximum value.
    max: Option<i64>,
    /// Style for the prompt.
    prompt_style: Option<Style>,
}

impl IntPrompt {
    /// Creates a new IntPrompt with the given message.
    #[must_use]
    #[inline]
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            default: None,
            min: None,
            max: None,
            prompt_style: None,
        }
    }

    /// Sets the default value.
    #[must_use]
    #[inline]
    pub const fn default(mut self, default: i64) -> Self {
        self.default = Some(default);
        self
    }

    /// Sets the minimum allowed value.
    #[must_use]
    #[inline]
    pub const fn min(mut self, min: i64) -> Self {
        self.min = Some(min);
        self
    }

    /// Sets the maximum allowed value.
    #[must_use]
    #[inline]
    pub const fn max(mut self, max: i64) -> Self {
        self.max = Some(max);
        self
    }

    /// Sets the style for the prompt.
    #[must_use]
    #[inline]
    pub fn style(mut self, style: Style) -> Self {
        self.prompt_style = Some(style);
        self
    }

    /// Asks the user for an integer.
    ///
    /// # Errors
    ///
    /// Returns an error if reading from stdin fails.
    pub fn ask(&self) -> Result<i64> {
        let mut prompt = self.message.clone();

        if let Some(default) = self.default {
            prompt.push_str(&format!(" ({})", default));
        }

        prompt.push_str(": ");

        let stdin = io::stdin();
        let mut stdout = io::stdout();

        loop {
            // Print prompt
            if let Some(ref style) = self.prompt_style {
                eprint!("{}", style.to_ansi());
            }
            eprint!("{}", prompt);
            if self.prompt_style.is_some() {
                eprint!("\x1b[0m");
            }
            stdout.flush()?;

            // Read input
            let mut input = String::new();
            stdin.lock().read_line(&mut input)?;

            let input = input.trim();

            // Handle empty input
            if input.is_empty() {
                if let Some(default) = self.default {
                    return Ok(default);
                }
                eprintln!("Please enter a number");
                continue;
            }

            // Parse number
            match input.parse::<i64>() {
                Ok(n) => {
                    // Validate range
                    if let Some(min) = self.min {
                        if n < min {
                            eprintln!("Value must be at least {}", min);
                            continue;
                        }
                    }
                    if let Some(max) = self.max {
                        if n > max {
                            eprintln!("Value must be at most {}", max);
                            continue;
                        }
                    }
                    return Ok(n);
                }
                Err(_) => {
                    eprintln!("Please enter a valid integer");
                }
            }
        }
    }
}

/// A floating-point input prompt.
#[derive(Debug, Clone)]
pub struct FloatPrompt {
    /// The prompt message.
    message: String,
    /// Default value.
    default: Option<f64>,
    /// Minimum value.
    min: Option<f64>,
    /// Maximum value.
    max: Option<f64>,
    /// Style for the prompt.
    prompt_style: Option<Style>,
}

impl FloatPrompt {
    /// Creates a new FloatPrompt with the given message.
    #[must_use]
    #[inline]
    pub fn new(message: impl Into<String>) -> Self {
        Self {
            message: message.into(),
            default: None,
            min: None,
            max: None,
            prompt_style: None,
        }
    }

    /// Sets the default value.
    #[must_use]
    #[inline]
    pub fn default(mut self, default: f64) -> Self {
        self.default = Some(default);
        self
    }

    /// Sets the minimum allowed value.
    #[must_use]
    #[inline]
    pub fn min(mut self, min: f64) -> Self {
        self.min = Some(min);
        self
    }

    /// Sets the maximum allowed value.
    #[must_use]
    #[inline]
    pub fn max(mut self, max: f64) -> Self {
        self.max = Some(max);
        self
    }

    /// Sets the style for the prompt.
    #[must_use]
    #[inline]
    pub fn style(mut self, style: Style) -> Self {
        self.prompt_style = Some(style);
        self
    }

    /// Asks the user for a floating-point number.
    ///
    /// # Errors
    ///
    /// Returns an error if reading from stdin fails.
    pub fn ask(&self) -> Result<f64> {
        let mut prompt = self.message.clone();

        if let Some(default) = self.default {
            prompt.push_str(&format!(" ({})", default));
        }

        prompt.push_str(": ");

        let stdin = io::stdin();
        let mut stdout = io::stdout();

        loop {
            // Print prompt
            if let Some(ref style) = self.prompt_style {
                eprint!("{}", style.to_ansi());
            }
            eprint!("{}", prompt);
            if self.prompt_style.is_some() {
                eprint!("\x1b[0m");
            }
            stdout.flush()?;

            // Read input
            let mut input = String::new();
            stdin.lock().read_line(&mut input)?;

            let input = input.trim();

            // Handle empty input
            if input.is_empty() {
                if let Some(default) = self.default {
                    return Ok(default);
                }
                eprintln!("Please enter a number");
                continue;
            }

            // Parse number
            match input.parse::<f64>() {
                Ok(n) => {
                    // Validate range
                    if let Some(min) = self.min {
                        if n < min {
                            eprintln!("Value must be at least {}", min);
                            continue;
                        }
                    }
                    if let Some(max) = self.max {
                        if n > max {
                            eprintln!("Value must be at most {}", max);
                            continue;
                        }
                    }
                    return Ok(n);
                }
                Err(_) => {
                    eprintln!("Please enter a valid number");
                }
            }
        }
    }
}

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

    #[test]
    fn test_prompt_new() {
        let prompt = Prompt::new("Test?");
        assert_eq!(prompt.message, "Test?");
        assert!(prompt.default.is_none());
        assert!(prompt.choices.is_none());
        assert!(prompt.case_sensitive);
        assert!(prompt.show_default);
        assert!(prompt.show_choices);
        assert!(!prompt.password);
        assert!(prompt.prompt_style.is_none());
    }

    #[test]
    fn test_prompt_default() {
        let prompt = Prompt::new("Test?").default("foo");
        assert_eq!(prompt.default, Some("foo".to_string()));
    }

    #[test]
    fn test_prompt_choices() {
        let prompt = Prompt::new("Test?").choices(["a", "b", "c"]);
        assert!(prompt.choices.is_some());
        assert_eq!(prompt.choices.as_ref().map(Vec::len), Some(3));
    }

    #[test]
    fn test_prompt_case_sensitive() {
        let prompt = Prompt::new("Test?").case_sensitive(false);
        assert!(!prompt.case_sensitive);
    }

    #[test]
    fn test_prompt_show_default() {
        let prompt = Prompt::new("Test?").show_default(false);
        assert!(!prompt.show_default);
    }

    #[test]
    fn test_prompt_show_choices() {
        let prompt = Prompt::new("Test?").show_choices(false);
        assert!(!prompt.show_choices);
    }

    #[test]
    fn test_prompt_password() {
        let prompt = Prompt::new("Password?").password(true);
        assert!(prompt.password);
    }

    #[test]
    fn test_prompt_style() {
        let prompt = Prompt::new("Test?").style(Style::new().bold());
        assert!(prompt.prompt_style.is_some());
    }

    #[test]
    fn test_prompt_validate_with_choices() {
        let prompt = Prompt::new("Test?").choices(["yes", "no"]);
        assert!(prompt.validate("yes"));
        assert!(prompt.validate("no"));
        assert!(!prompt.validate("maybe"));
        assert!(!prompt.validate("YES")); // case sensitive by default
    }

    #[test]
    fn test_prompt_validate_case_insensitive() {
        let prompt = Prompt::new("Test?")
            .choices(["yes", "no"])
            .case_sensitive(false);
        assert!(prompt.validate("YES"));
        assert!(prompt.validate("Yes"));
        assert!(prompt.validate("yes"));
        assert!(prompt.validate("NO"));
        assert!(!prompt.validate("maybe"));
    }

    #[test]
    fn test_prompt_validate_no_choices() {
        let prompt = Prompt::new("Test?");
        assert!(prompt.validate("anything"));
        assert!(prompt.validate(""));
    }

    #[test]
    fn test_prompt_build_prompt() {
        let prompt = Prompt::new("Choose").choices(["a", "b"]).default("a");
        let built = prompt.build_prompt();
        assert!(built.contains("Choose"));
        assert!(built.contains("[a/b]"));
        assert!(built.contains("(a)"));
        assert!(built.ends_with(": "));
    }

    #[test]
    fn test_prompt_build_prompt_no_choices() {
        let prompt = Prompt::new("Name").default("John");
        let built = prompt.build_prompt();
        assert!(built.contains("Name"));
        assert!(built.contains("(John)"));
        assert!(!built.contains("["));
    }

    #[test]
    fn test_prompt_build_prompt_hide_default() {
        let prompt = Prompt::new("Name").default("John").show_default(false);
        let built = prompt.build_prompt();
        assert!(built.contains("Name"));
        assert!(!built.contains("(John)"));
    }

    #[test]
    fn test_prompt_build_prompt_hide_choices() {
        let prompt = Prompt::new("Choose")
            .choices(["a", "b"])
            .show_choices(false);
        let built = prompt.build_prompt();
        assert!(built.contains("Choose"));
        assert!(!built.contains("[a/b]"));
    }

    #[test]
    fn test_confirm_new() {
        let confirm = Confirm::new("Sure?");
        assert_eq!(confirm.message, "Sure?");
        assert!(confirm.default.is_none());
        assert!(confirm.prompt_style.is_none());
    }

    #[test]
    fn test_confirm_default_true() {
        let confirm = Confirm::new("Sure?").default(true);
        assert_eq!(confirm.default, Some(true));
    }

    #[test]
    fn test_confirm_default_false() {
        let confirm = Confirm::new("Sure?").default(false);
        assert_eq!(confirm.default, Some(false));
    }

    #[test]
    fn test_confirm_style() {
        let confirm = Confirm::new("Sure?").style(Style::new().bold());
        assert!(confirm.prompt_style.is_some());
    }

    #[test]
    fn test_int_prompt_new() {
        let prompt = IntPrompt::new("Number?");
        assert_eq!(prompt.message, "Number?");
        assert!(prompt.default.is_none());
        assert!(prompt.min.is_none());
        assert!(prompt.max.is_none());
        assert!(prompt.prompt_style.is_none());
    }

    #[test]
    fn test_int_prompt_default() {
        let prompt = IntPrompt::new("Number?").default(42);
        assert_eq!(prompt.default, Some(42));
    }

    #[test]
    fn test_int_prompt_range() {
        let prompt = IntPrompt::new("Number?").min(0).max(100);
        assert_eq!(prompt.min, Some(0));
        assert_eq!(prompt.max, Some(100));
    }

    #[test]
    fn test_int_prompt_style() {
        let prompt = IntPrompt::new("Number?").style(Style::new().bold());
        assert!(prompt.prompt_style.is_some());
    }

    #[test]
    fn test_float_prompt_new() {
        let prompt = FloatPrompt::new("Value?");
        assert_eq!(prompt.message, "Value?");
        assert!(prompt.default.is_none());
        assert!(prompt.min.is_none());
        assert!(prompt.max.is_none());
        assert!(prompt.prompt_style.is_none());
    }

    #[test]
    fn test_float_prompt_default() {
        let prompt = FloatPrompt::new("Value?").default(42.5);
        assert_eq!(prompt.default, Some(42.5));
    }

    #[test]
    fn test_float_prompt_range() {
        let prompt = FloatPrompt::new("Value?").min(0.0).max(1.0);
        assert_eq!(prompt.min, Some(0.0));
        assert_eq!(prompt.max, Some(1.0));
    }

    #[test]
    fn test_float_prompt_style() {
        let prompt = FloatPrompt::new("Value?").style(Style::new().bold());
        assert!(prompt.prompt_style.is_some());
    }
}