mod action;
mod config;
mod prompt;
#[cfg(test)]
mod test;
pub use action::*;
use crate::{
config::get_configuration,
error::{InquireError, InquireResult},
formatter::{BoolFormatter, DEFAULT_BOOL_FORMATTER},
prompts::prompt::Prompt,
terminal::get_default_terminal,
ui::{Backend, ConfirmBackend, RenderConfig},
};
use self::prompt::ConfirmPrompt;
#[derive(Clone)]
pub struct Confirm<'a> {
pub message: &'a str,
pub default: Option<bool>,
pub help_message: Option<&'a str>,
pub formatter: BoolFormatter<'a>,
pub render_config: RenderConfig<'a>,
pub error_meesage: String,
}
impl<'a> Confirm<'a> {
pub const DEFAULT_FORMATTER: BoolFormatter<'a> = DEFAULT_BOOL_FORMATTER;
pub const DEFAULT_ERROR_MESSAGE: &'a str =
"Invalid answer, try typing 'y' for yes or 'n' for no";
pub fn new(message: &'a str) -> Self {
Self {
message,
default: None,
help_message: None,
formatter: Self::DEFAULT_FORMATTER,
render_config: get_configuration(),
error_meesage: String::from(Self::DEFAULT_ERROR_MESSAGE),
}
}
pub fn with_default(mut self, default: bool) -> Self {
self.default = Some(default);
self
}
pub fn with_help_message(mut self, message: &'a str) -> Self {
self.help_message = Some(message);
self
}
pub fn without_help_message(mut self) -> Self {
self.help_message = None;
self
}
pub fn with_formatter(mut self, formatter: BoolFormatter<'a>) -> Self {
self.formatter = formatter;
self
}
pub fn with_error_message(mut self, msg: &str) -> Self {
self.error_meesage = String::from(msg);
self
}
pub fn with_render_config(mut self, render_config: RenderConfig<'a>) -> Self {
self.render_config = render_config;
self
}
pub fn prompt_skippable(self) -> InquireResult<Option<bool>> {
match self.prompt() {
Ok(answer) => Ok(Some(answer)),
Err(InquireError::OperationCanceled) => Ok(None),
Err(err) => Err(err),
}
}
pub fn prompt(self) -> InquireResult<bool> {
let (input_reader, terminal) = get_default_terminal()?;
let mut backend = Backend::new(input_reader, terminal, self.render_config)?;
self.prompt_with_backend(&mut backend)
}
pub(crate) fn prompt_with_backend<B: ConfirmBackend>(
self,
backend: &mut B,
) -> InquireResult<bool> {
ConfirmPrompt::from(self).prompt(backend)
}
}
impl<'a> From<&'a str> for Confirm<'a> {
fn from(val: &'a str) -> Self {
Confirm::new(val)
}
}