Merging dialogs.rs with question.rs
[ouch.git] / src / utils / question.rs
blob01bff855ae10491b9e6fdf644aa333f7428a127d
1 //! Utils related to asking [Y/n] questions to the user.
2 //!
3 //! Example:
4 //!   "Do you want to overwrite 'archive.tar.gz'? [Y/n]"
6 use std::{
7     borrow::Cow,
8     io::{self, Write},
9     path::Path,
12 use fs_err as fs;
14 use super::{strip_cur_dir, to_utf};
15 use crate::{
16     error::{Error, Result},
17     utils::colors,
20 #[derive(Debug, PartialEq, Clone, Copy)]
21 /// Determines if overwrite questions should be skipped or asked to the user
22 pub enum QuestionPolicy {
23     /// Ask the user every time
24     Ask,
25     /// Set by `--yes`, will say 'Y' to all overwrite questions
26     AlwaysYes,
27     /// Set by `--no`, will say 'N' to all overwrite questions
28     AlwaysNo,
31 /// Check if QuestionPolicy flags were set, otherwise, ask user if they want to overwrite.
32 pub fn user_wants_to_overwrite(path: &Path, question_policy: QuestionPolicy) -> crate::Result<bool> {
33     match question_policy {
34         QuestionPolicy::AlwaysYes => Ok(true),
35         QuestionPolicy::AlwaysNo => Ok(false),
36         QuestionPolicy::Ask => {
37             let path = to_utf(strip_cur_dir(path));
38             let path = Some(path.as_str());
39             let placeholder = Some("FILE");
40             Confirmation::new("Do you want to overwrite 'FILE'?", placeholder).ask(path)
41         }
42     }
45 /// Create the file if it doesn't exist and if it does then ask to overwrite it.
46 /// If the user doesn't want to overwrite then we return [`Ok(None)`]
47 pub fn create_or_ask_overwrite(path: &Path, question_policy: QuestionPolicy) -> Result<Option<fs::File>> {
48     match fs::OpenOptions::new().write(true).create_new(true).open(path) {
49         Ok(w) => Ok(Some(w)),
50         Err(e) if e.kind() == std::io::ErrorKind::AlreadyExists => {
51             if user_wants_to_overwrite(path, question_policy)? {
52                 if path.is_dir() {
53                     // We can't just use `fs::File::create(&path)` because it would return io::ErrorKind::IsADirectory
54                     // ToDo: Maybe we should emphasise that `path` is a directory and everything inside it will be gone?
55                     fs::remove_dir_all(path)?;
56                 }
57                 Ok(Some(fs::File::create(path)?))
58             } else {
59                 Ok(None)
60             }
61         }
62         Err(e) => Err(Error::from(e)),
63     }
66 /// Check if QuestionPolicy flags were set, otherwise, ask the user if they want to continue decompressing.
67 pub fn user_wants_to_continue_decompressing(path: &Path, question_policy: QuestionPolicy) -> crate::Result<bool> {
68     match question_policy {
69         QuestionPolicy::AlwaysYes => Ok(true),
70         QuestionPolicy::AlwaysNo => Ok(false),
71         QuestionPolicy::Ask => {
72             let path = to_utf(strip_cur_dir(path));
73             let path = Some(path.as_str());
74             let placeholder = Some("FILE");
75             Confirmation::new("Do you want to continue decompressing 'FILE'?", placeholder).ask(path)
76         }
77     }
80 /// Confirmation dialog for end user with [Y/n] question.
81 ///
82 /// If the placeholder is found in the prompt text, it will be replaced to form the final message.
83 pub struct Confirmation<'a> {
84     /// The message to be displayed with the placeholder text in it.
85     /// e.g.: "Do you want to overwrite 'FILE'?"
86     pub prompt: &'a str,
88     /// The placeholder text that will be replaced in the `ask` function:
89     /// e.g.: Some("FILE")
90     pub placeholder: Option<&'a str>,
93 impl<'a> Confirmation<'a> {
94     /// Creates a new Confirmation.
95     pub const fn new(prompt: &'a str, pattern: Option<&'a str>) -> Self {
96         Self { prompt, placeholder: pattern }
97     }
99     /// Creates user message and receives a boolean input to be used on the program
100     pub fn ask(&self, substitute: Option<&'a str>) -> crate::Result<bool> {
101         let message = match (self.placeholder, substitute) {
102             (None, _) => Cow::Borrowed(self.prompt),
103             (Some(_), None) => unreachable!("dev error, should be reported, we checked this won't happen"),
104             (Some(placeholder), Some(subs)) => Cow::Owned(self.prompt.replace(placeholder, subs)),
105         };
107         // Ask the same question to end while no valid answers are given
108         loop {
109             print!("{} [{}Y{}/{}n{}] ", message, *colors::GREEN, *colors::RESET, *colors::RED, *colors::RESET);
110             io::stdout().flush()?;
112             let mut answer = String::new();
113             io::stdin().read_line(&mut answer)?;
115             answer.make_ascii_lowercase();
116             match answer.trim() {
117                 "" | "y" | "yes" => return Ok(true),
118                 "n" | "no" => return Ok(false),
119                 _ => continue, // Try again
120             }
121         }
122     }