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
use dialoguer::{Confirm, Input, Select};

pub trait Interactor {
    fn input(&self, prompt: &str) -> String;
    fn input_letter(&self, prompt: &str, choices: &str) -> String;
    fn select(&self, prompt: &str, choices: &[&str]) -> Option<usize>;
    fn confirm(&self, prompt: &str) -> bool;

    fn info(&self, message: &str) {
        println!("{}", message);
    }

    fn error(&self, message: &str) {
        eprintln!("{}", message);
    }
}

pub struct ConsoleInteractor;
impl Interactor for ConsoleInteractor {
    fn input(&self, prompt: &str) -> String {
        #[allow(clippy::unwrap_used)]
        Input::new()
            .with_prompt(prompt)
            .allow_empty(false)
            .interact()
            .unwrap()
    }

    fn input_letter(&self, prompt: &str, choices: &str) -> String {
        #[allow(clippy::unwrap_used)]
        Input::new()
            .with_prompt(prompt)
            .validate_with(|input: &String| -> Result<(), &str> {
                if choices.contains(input) {
                    Ok(())
                } else {
                    Err("invalid choice")
                }
            })
            .interact()
            .unwrap()
    }

    fn select(&self, prompt: &str, choices: &[&str]) -> Option<usize> {
        #[allow(clippy::unwrap_used)]
        Select::new()
            .with_prompt(prompt)
            .items(choices)
            .interact_opt()
            .unwrap()
    }

    fn info(&self, message: &str) {
        println!("{}", message);
    }

    fn confirm(&self, prompt: &str) -> bool {
        #[allow(clippy::unwrap_used)]
        Confirm::new().with_prompt(prompt).interact().unwrap()
    }

    fn error(&self, message: &str) {
        eprintln!("{}", message);
    }
}