forked from getzola/zola
-
Notifications
You must be signed in to change notification settings - Fork 0
/
prompt.rs
51 lines (44 loc) · 1.42 KB
/
prompt.rs
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
use std::io::{self, BufRead, Write};
use libs::url::Url;
use errors::{anyhow, Result};
/// Wait for user input and return what they typed
fn read_line() -> Result<String> {
let stdin = io::stdin();
let stdin = stdin.lock();
let mut lines = stdin.lines();
lines
.next()
.and_then(|l| l.ok())
.ok_or_else(|| anyhow!("unable to read from stdin for confirmation"))
}
/// Ask a yes/no question to the user
pub fn ask_bool(question: &str, default: bool) -> Result<bool> {
print!("{} {}: ", question, if default { "[Y/n]" } else { "[y/N]" });
let _ = io::stdout().flush();
let input = read_line()?;
match &*input {
"y" | "Y" | "yes" | "YES" | "true" => Ok(true),
"n" | "N" | "no" | "NO" | "false" => Ok(false),
"" => Ok(default),
_ => {
println!("Invalid choice: '{}'", input);
ask_bool(question, default)
}
}
}
/// Ask a question to the user where they can write a URL
pub fn ask_url(question: &str, default: &str) -> Result<String> {
print!("{} ({}): ", question, default);
let _ = io::stdout().flush();
let input = read_line()?;
match &*input {
"" => Ok(default.to_string()),
_ => match Url::parse(&input) {
Ok(_) => Ok(input),
Err(_) => {
println!("Invalid URL: '{}'", input);
ask_url(question, default)
}
},
}
}