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
//! Functions for asking input from the user

use crate::debug_print::dprintln;
use std::io::{self, Write};
use url::Url;

/// Waits for user input and returns string
pub(super) fn get_input() -> String {
    let mut buf = String::new();
    let input = io::stdin().read_line(&mut buf);
    buf = buf.trim_end().to_string();
    match input {
        Ok(_) => dprintln!("Read \"{}\" from input", &buf),
        Err(e) => eprintln!("Error: {}", e),
    }
    buf
}

/// Asks the user a yes/no question
pub(super) fn inquire_yn(question: &str) -> bool {
    print!("{}? (y/n) ", question);
    let _ = io::stdout().flush();
    let input = get_input();
    match input.as_str() {
        "y" | "Y" | "Yes" | "yes" | "YES" | "true" => true,
        "n" | "N" | "No" | "no" | "NO" | "false" => false,
        _ => {
            println!("Invalid input: {}", input);
            inquire_yn(question)
        }
    }
}

/// Asks the user for a url
pub(super) fn inquire_url(question: &str) -> String {
    print!("{}? ", question);
    let _ = io::stdout().flush();
    let input = get_input();
    match Url::parse(&input) {
        Ok(_) => input,
        Err(_) => {
            println!("\"{}\" doesn't seem like a valid URL", input);
            match inquire_yn("Do you wish to retype it") {
                true => inquire_url(question),
                false => input,
            }
        }
    }
}