You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

54 lines
1.4KB

  1. use std::io::{self, Write, BufRead};
  2. use url::Url;
  3. use errors::Result;
  4. /// Wait for user input and return what they typed
  5. fn read_line() -> Result<String> {
  6. let stdin = io::stdin();
  7. let stdin = stdin.lock();
  8. let mut lines = stdin.lines();
  9. lines
  10. .next()
  11. .and_then(|l| l.ok())
  12. .ok_or_else(|| "unable to read from stdin for confirmation".into())
  13. }
  14. /// Ask a yes/no question to the user
  15. pub fn ask_bool(question: &str, default: bool) -> Result<bool> {
  16. print!("{} {}: ", question, if default { "[Y/n]" } else { "[y/N]" });
  17. let _ = io::stdout().flush();
  18. let input = read_line()?;
  19. match &*input {
  20. "y" | "Y" | "yes" | "YES" | "true" => Ok(true),
  21. "n" | "N" | "no" | "NO" | "false" => Ok(false),
  22. "" => Ok(default),
  23. _ => {
  24. println!("Invalid choice: '{}'", input);
  25. ask_bool(question, default)
  26. },
  27. }
  28. }
  29. /// Ask a question to the user where they can write a URL
  30. pub fn ask_url(question: &str, default: &str) -> Result<String> {
  31. print!("{} ({}): ", question, default);
  32. let _ = io::stdout().flush();
  33. let input = read_line()?;
  34. match &*input {
  35. "" => Ok(default.to_string()),
  36. _ => {
  37. match Url::parse(&input) {
  38. Ok(_) => Ok(input),
  39. Err(_) => {
  40. println!("Invalid URL: '{}'", input);
  41. ask_url(question, default)
  42. }
  43. }
  44. },
  45. }
  46. }