cli_support/
prompt.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
4use std::io::{self, Write};
5
6pub fn prompt_string<S: AsRef<str>>(prompt: S) -> Option<String> {
7    print!("{}: ", prompt.as_ref());
8    let _ = io::stdout().flush(); // Don't care if flush fails really.
9    let mut s = String::new();
10    io::stdin()
11        .read_line(&mut s)
12        .expect("Failed to read line...");
13    if let Some('\n') = s.chars().next_back() {
14        s.pop();
15    }
16    if let Some('\r') = s.chars().next_back() {
17        s.pop();
18    }
19    if s.is_empty() {
20        None
21    } else {
22        Some(s)
23    }
24}
25
26pub fn prompt_password<S: AsRef<str>>(prompt: S) -> Option<String> {
27    rpassword::prompt_password(format!("{}: ", prompt.as_ref())).ok()
28}
29
30pub fn prompt_char(msg: &str) -> Option<char> {
31    prompt_string(msg).and_then(|r| r.chars().next())
32}
33
34pub fn prompt_usize<S: AsRef<str>>(prompt: S) -> Option<usize> {
35    if let Some(s) = prompt_string(prompt) {
36        match s.parse::<usize>() {
37            Ok(n) => Some(n),
38            Err(_) => {
39                println!("Couldn't parse!");
40                None
41            }
42        }
43    } else {
44        None
45    }
46}