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
use std::fmt::Display;
use std::str::FromStr;

use anyhow::Result;
use dialoguer::theme::{ColorfulTheme, Theme};
use dialoguer::Input;
use once_cell::sync::Lazy;

static THEME: Lazy<ColorfulTheme> = Lazy::new(ColorfulTheme::default);

/// Returns the theme to use.
pub fn get_theme() -> &'static dyn Theme {
    &*THEME
}

/// Prompts for a value that has a default.
pub fn prompt_value<V: FromStr + Display>(name: &str, v: &mut V) -> Result<()>
where
    <V as FromStr>::Err: Display,
{
    loop {
        let s = Input::with_theme(get_theme())
            .with_prompt(name)
            .default(v.to_string())
            .interact()?;
        match s.parse() {
            Ok(value) => {
                *v = value;
                return Ok(());
            }
            Err(err) => {
                println!("  invalid input: {err}");
                continue;
            }
        }
    }
}

/// Prompts for a value without a default.
pub fn prompt_value_no_default<V: FromStr + Display>(name: &str) -> Result<V>
where
    <V as FromStr>::Err: Display,
{
    loop {
        let s: String = Input::with_theme(get_theme())
            .with_prompt(name)
            .interact()?;
        match s.parse() {
            Ok(value) => {
                return Ok(value);
            }
            Err(err) => {
                println!("  invalid input: {err}");
                continue;
            }
        }
    }
}