inquire/prompts/
confirm.rs

1use crate::{
2    config::get_configuration,
3    error::{InquireError, InquireResult},
4    formatter::{BoolFormatter, DEFAULT_BOOL_FORMATTER},
5    parser::{BoolParser, DEFAULT_BOOL_PARSER},
6    terminal::{get_default_terminal, Terminal},
7    ui::{Backend, RenderConfig},
8    CustomType,
9};
10
11/// Prompt to ask the user for simple yes/no questions, commonly known by asking the user displaying the `(y/n)` text.
12///
13/// This prompt is basically a wrapper around the behavior of `CustomType` prompts, providing a sensible set of defaults to ask for simple `true/false` questions, such as confirming an action.
14///
15/// Default values are formatted with the given value in uppercase, e.g. `(Y/n)` or `(y/N)`. The `bool` parser accepts by default only the following inputs (case-insensitive): `y`, `n`, `yes` and `no`. If the user input does not match any of them, the following error message is displayed by default:
16/// - `# Invalid answer, try typing 'y' for yes or 'n' for no`.
17///
18/// Finally, once the answer is submitted, [`Confirm`] prompts display the bool value formatted as either "Yes", if a `true` value was parsed, or "No" otherwise.
19///
20/// The Confirm prompt does not support custom validators because of the nature of the prompt. The user input is always parsed to true or false. If one of the two alternatives is invalid, a Confirm prompt that only allows yes or no answers does not make a lot of sense to me, but if someone provides a clear use-case I will reconsider.
21///
22/// Confirm prompts provide several options of configuration:
23///
24/// - **Prompt message**: Required when creating the prompt.
25/// - **Default value**: Default value returned when the user submits an empty response.
26/// - **Placeholder**: Short hint that describes the expected value of the input.
27/// - **Help message**: Message displayed at the line below the prompt.
28/// - **Formatter**: Custom formatter in case you need to pre-process the user input before showing it as the final answer.
29///   - Formats `true` to "Yes" and `false` to "No", by default.
30/// - **Parser**: Custom parser for user inputs.
31///   - The default `bool` parser returns `true` if the input is either `"y"` or `"yes"`, in a case-insensitive comparison. Similarly, the parser returns `false` if the input is either `"n"` or `"no"`.
32/// - **Default value formatter**: Function that formats how the default value is displayed to the user.
33///   - By default, displays "y/n" with the default value capitalized, e.g. "y/N".
34/// - **Error message**: Error message to display when a value could not be parsed from the input.
35///   - Set to "Invalid answer, try typing 'y' for yes or 'n' for no" by default.
36///
37/// # Example
38///
39/// ```no_run
40/// use inquire::Confirm;
41///
42/// let ans = Confirm::new("Do you live in Brazil?")
43///     .with_default(false)
44///     .with_help_message("This data is stored for good reasons")
45///     .prompt();
46///
47/// match ans {
48///     Ok(true) => println!("That's awesome!"),
49///     Ok(false) => println!("That's too bad, I've heard great things about it."),
50///     Err(_) => println!("Error with questionnaire, try again later"),
51/// }
52/// ```
53///
54/// [`Confirm`]: crate::Confirm
55#[derive(Clone)]
56pub struct Confirm<'a> {
57    /// Message to be presented to the user.
58    pub message: &'a str,
59
60    /// Default value, returned when the user input is empty.
61    pub default: Option<bool>,
62
63    /// Short hint that describes the expected value of the input.
64    pub placeholder: Option<&'a str>,
65
66    /// Help message to be presented to the user.
67    pub help_message: Option<&'a str>,
68
69    /// Function that formats the user input and presents it to the user as the final rendering of the prompt.
70    pub formatter: BoolFormatter<'a>,
71
72    /// Function that parses the user input and returns the result value.
73    pub parser: BoolParser<'a>,
74
75    /// Function that formats the default value to be presented to the user
76    pub default_value_formatter: BoolFormatter<'a>,
77
78    /// Error message displayed when a value could not be parsed from input.
79    pub error_message: String,
80
81    /// RenderConfig to apply to the rendered interface.
82    ///
83    /// Note: The default render config considers if the NO_COLOR environment variable
84    /// is set to decide whether to render the colored config or the empty one.
85    ///
86    /// When overriding the config in a prompt, NO_COLOR is no longer considered and your
87    /// config is treated as the only source of truth. If you want to customize colors
88    /// and still suport NO_COLOR, you will have to do this on your end.
89    pub render_config: RenderConfig,
90}
91
92impl<'a> Confirm<'a> {
93    /// Default formatter, set to [DEFAULT_BOOL_FORMATTER](crate::formatter::DEFAULT_BOOL_FORMATTER)
94    pub const DEFAULT_FORMATTER: BoolFormatter<'a> = DEFAULT_BOOL_FORMATTER;
95
96    /// Default input parser.
97    pub const DEFAULT_PARSER: BoolParser<'a> = DEFAULT_BOOL_PARSER;
98
99    /// Default formatter for default values, mapping [true] to ["Y/n"] and
100    /// [false] to ["y/N"]
101    pub const DEFAULT_DEFAULT_VALUE_FORMATTER: BoolFormatter<'a> = &|ans| match ans {
102        true => String::from("Y/n"),
103        false => String::from("y/N"),
104    };
105
106    /// Default error message displayed when parsing fails.
107    pub const DEFAULT_ERROR_MESSAGE: &'a str =
108        "Invalid answer, try typing 'y' for yes or 'n' for no";
109
110    /// Creates a [Confirm] with the provided message and default configuration values.
111    pub fn new(message: &'a str) -> Self {
112        Self {
113            message,
114            default: None,
115            placeholder: None,
116            help_message: None,
117            formatter: Self::DEFAULT_FORMATTER,
118            parser: Self::DEFAULT_PARSER,
119            default_value_formatter: Self::DEFAULT_DEFAULT_VALUE_FORMATTER,
120            error_message: String::from(Self::DEFAULT_ERROR_MESSAGE),
121            render_config: get_configuration(),
122        }
123    }
124
125    /// Sets the default input.
126    pub fn with_default(mut self, default: bool) -> Self {
127        self.default = Some(default);
128        self
129    }
130
131    /// Sets the placeholder.
132    pub fn with_placeholder(mut self, placeholder: &'a str) -> Self {
133        self.placeholder = Some(placeholder);
134        self
135    }
136
137    /// Sets the help message of the prompt.
138    pub fn with_help_message(mut self, message: &'a str) -> Self {
139        self.help_message = Some(message);
140        self
141    }
142
143    /// Sets the formatter.
144    pub fn with_formatter(mut self, formatter: BoolFormatter<'a>) -> Self {
145        self.formatter = formatter;
146        self
147    }
148
149    /// Sets the parser.
150    pub fn with_parser(mut self, parser: BoolParser<'a>) -> Self {
151        self.parser = parser;
152        self
153    }
154
155    /// Sets a custom error message displayed when a submission could not be parsed to a value.
156    pub fn with_error_message(mut self, error_message: &'a str) -> Self {
157        self.error_message = String::from(error_message);
158        self
159    }
160
161    /// Sets the default value formatter
162    pub fn with_default_value_formatter(mut self, formatter: BoolFormatter<'a>) -> Self {
163        self.default_value_formatter = formatter;
164        self
165    }
166
167    /// Sets the provided color theme to this prompt.
168    ///
169    /// Note: The default render config considers if the NO_COLOR environment variable
170    /// is set to decide whether to render the colored config or the empty one.
171    ///
172    /// When overriding the config in a prompt, NO_COLOR is no longer considered and your
173    /// config is treated as the only source of truth. If you want to customize colors
174    /// and still suport NO_COLOR, you will have to do this on your end.
175    pub fn with_render_config(mut self, render_config: RenderConfig) -> Self {
176        self.render_config = render_config;
177        self
178    }
179
180    /// Parses the provided behavioral and rendering options and prompts
181    /// the CLI user for input according to the defined rules.
182    ///
183    /// This method is intended for flows where the user skipping/cancelling
184    /// the prompt - by pressing ESC - is considered normal behavior. In this case,
185    /// it does not return `Err(InquireError::OperationCanceled)`, but `Ok(None)`.
186    ///
187    /// Meanwhile, if the user does submit an answer, the method wraps the return
188    /// type with `Some`.
189    pub fn prompt_skippable(self) -> InquireResult<Option<bool>> {
190        match self.prompt() {
191            Ok(answer) => Ok(Some(answer)),
192            Err(InquireError::OperationCanceled) => Ok(None),
193            Err(err) => Err(err),
194        }
195    }
196
197    /// Parses the provided behavioral and rendering options and prompts
198    /// the CLI user for input according to the defined rules.
199    pub fn prompt(self) -> InquireResult<bool> {
200        let terminal = get_default_terminal()?;
201        let mut backend = Backend::new(terminal, self.render_config)?;
202        self.prompt_with_backend(&mut backend)
203    }
204
205    pub(crate) fn prompt_with_backend<T: Terminal>(
206        self,
207        backend: &mut Backend<T>,
208    ) -> InquireResult<bool> {
209        CustomType::from(self).prompt_with_backend(backend)
210    }
211}
212
213impl<'a> From<&'a str> for Confirm<'a> {
214    fn from(val: &'a str) -> Self {
215        Confirm::new(val)
216    }
217}
218
219impl<'a> From<Confirm<'a>> for CustomType<'a, bool> {
220    fn from(co: Confirm<'a>) -> Self {
221        Self {
222            message: co.message,
223            default: co.default,
224            default_value_formatter: co.default_value_formatter,
225            placeholder: co.placeholder,
226            help_message: co.help_message,
227            formatter: co.formatter,
228            parser: co.parser,
229            validators: vec![],
230            error_message: co.error_message,
231            render_config: co.render_config,
232        }
233    }
234}