pythonic_helper/
io.rs

1use std::io::{stdin, stdout, Write};
2
3
4/// Provides an easy-to-use way to receive input from the user (via standard input)
5///
6/// # Example
7/// ```no_run
8/// use pythonic_helper::io::input;
9/// 
10/// println!("Please enter your name");
11/// let name_result = input("> ");
12/// let name: String = name_result.unwrap_or("default".to_owned()); 
13/// ```
14pub fn input(prompt: &str) -> Result<String, String> {
15    let mut input: String = String::new();
16    print!("{}", prompt);
17    let _ = stdout().flush();
18    match stdin().read_line(&mut input) {
19        Ok(_) => Ok(input.trim().to_string()),
20        Err(e) => Err(e.to_string()),
21    }
22}
23
24/// A "yes-or-no" input. The function loops until the user inputs either "y" or "n"
25///
26/// # Example
27/// ```no_run
28/// use pythonic_helper::io::confirm;
29///
30/// if confirm("Do you want to continue?", None) {
31///     println!("Continuing...");
32/// } else {
33///     println!("No? Alright then.");   
34/// }
35/// ```
36pub fn confirm(prompt: &str, abort: Option<bool>) -> bool {
37    let real_prompt = prompt.to_string() + " [y/n]: ";
38
39    loop {
40        let input_attempt = input(&real_prompt);
41        if input_attempt.is_err() {
42            println!("Error: {}", input_attempt.unwrap_err());
43            continue;
44        }
45        let user_input = input_attempt.unwrap();
46        if !["y", "n"].contains(&user_input.to_lowercase().as_str()) {
47            println!("Error: Invalid input");
48            continue;
49        }
50
51        if abort.unwrap_or(false) {
52            eprintln!("Aborted.");
53            std::process::exit(1);
54        }
55
56        return user_input == "y";
57    }
58}