diff options
Diffstat (limited to 'crates/mozart/src/console.rs')
| -rw-r--r-- | crates/mozart/src/console.rs | 81 |
1 files changed, 81 insertions, 0 deletions
diff --git a/crates/mozart/src/console.rs b/crates/mozart/src/console.rs index 43399a5..07eaf67 100644 --- a/crates/mozart/src/console.rs +++ b/crates/mozart/src/console.rs @@ -1,4 +1,5 @@ use colored::{ColoredString, Colorize}; +use dialoguer::{Confirm, Input}; /// `<info>` — green foreground pub fn info(message: &str) -> ColoredString { @@ -29,3 +30,83 @@ pub fn highlight(message: &str) -> ColoredString { pub fn warning(message: &str) -> ColoredString { message.black().on_yellow() } + +pub struct Console { + pub interactive: bool, + pub quiet: bool, +} + +impl Console { + pub fn new(no_interaction: bool, quiet: bool) -> Self { + Self { + interactive: !no_interaction, + quiet, + } + } + + pub fn info(&self, msg: &str) { + if !self.quiet { + eprintln!("{msg}"); + } + } + + pub fn error(&self, msg: &str) { + eprintln!("{}", console::error(msg)); + } + + pub fn ask(&self, prompt: &str, default: &str) -> String { + if !self.interactive { + return default.to_string(); + } + + Input::new() + .with_prompt(prompt) + .default(default.to_string()) + .allow_empty(true) + .interact_text() + .unwrap_or_else(|_| default.to_string()) + } + + pub fn ask_validated<F>( + &self, + prompt: &str, + default: &str, + validator: F, + ) -> Result<String, String> + where + F: Fn(&str) -> Result<(), String>, + { + if !self.interactive { + validator(default)?; + return Ok(default.to_string()); + } + + loop { + let input: String = Input::new() + .with_prompt(prompt) + .default(default.to_string()) + .allow_empty(true) + .interact_text() + .unwrap_or_else(|_| default.to_string()); + + match validator(&input) { + Ok(()) => return Ok(input), + Err(e) => { + self.error(&e); + } + } + } + } + + pub fn confirm(&self, prompt: &str) -> bool { + if !self.interactive { + return true; + } + + Confirm::new() + .with_prompt(prompt) + .default(true) + .interact() + .unwrap_or(true) + } +} |
