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
use atty::Stream;
use std::io::{self, Read};
pub fn get_user_input(prompt_string: &str) -> String {
println!("{}", prompt_string);
let mut input: String = read!("{}\n");
input = strip_trailing_whitespace(input);
input
}
pub fn get_user_input_multi_line(prompt_string: &str) -> String {
println!("{}", prompt_string);
let mut input = if atty::is(Stream::Stdin) {
read!("{}\n")
} else {
let mut tmp = String::new();
let _ = io::stdin().read_to_string(&mut tmp);
tmp
};
input = strip_trailing_whitespace(input);
input
}
fn strip_trailing_whitespace(mut input: String) -> String {
input.truncate(input.trim_end().len());
input
}
const INTERACTIVE_RESPONSE_LEN: usize = 1;
const YES: &str = "y";
const NO: &str = "n";
pub fn confirm(prompt_string: &str) -> Result<bool, failure::Error> {
println!("{} [y/n]", prompt_string);
let mut response: String = read!("{}\n");
response = response.split_whitespace().collect();
response.make_ascii_lowercase();
response.truncate(INTERACTIVE_RESPONSE_LEN);
match response.as_ref() {
YES => Ok(true),
NO => Ok(false),
_ => failure::bail!("Response must either be \"y\" for yes or \"n\" for no"),
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn it_trims_user_input_right_whitespace_chars() {
let test_str = "mysecret\r".to_string();
let truncated_str = strip_trailing_whitespace(test_str);
assert_eq!(truncated_str, "mysecret")
}
}