[pbs-devel] [PATCH v4 proxmox 1/2] router: cli: added `ask_for_confirmation` helper

Gabriel Goller g.goller at proxmox.com
Thu Dec 7 13:51:25 CET 2023


Added `ask_for_confirmation` helper that outputs a prompt and
lets the user confirm or deny it.
Implemented to close #4763.

Signed-off-by: Gabriel Goller <g.goller at proxmox.com>
---
 proxmox-router/Cargo.toml     |  1 +
 proxmox-router/src/cli/mod.rs | 46 ++++++++++++++++++++++++++++++++++-
 2 files changed, 46 insertions(+), 1 deletion(-)

diff --git a/proxmox-router/Cargo.toml b/proxmox-router/Cargo.toml
index c53ccd0..cd9140d 100644
--- a/proxmox-router/Cargo.toml
+++ b/proxmox-router/Cargo.toml
@@ -19,6 +19,7 @@ percent-encoding.workspace = true
 serde_json.workspace = true
 serde.workspace = true
 unicode-width ="0.1.8"
+regex.workspace = true
 
 # cli:
 tokio = { workspace = true, features = [], optional = true }
diff --git a/proxmox-router/src/cli/mod.rs b/proxmox-router/src/cli/mod.rs
index 208df4a..2628538 100644
--- a/proxmox-router/src/cli/mod.rs
+++ b/proxmox-router/src/cli/mod.rs
@@ -12,7 +12,10 @@
 //! - Ability to create interactive commands (using ``rustyline``)
 //! - Supports complex/nested commands
 
-use std::collections::HashMap;
+use std::{
+    collections::HashMap,
+    io::{self, Write},
+};
 
 use crate::ApiMethod;
 
@@ -62,6 +65,47 @@ pub fn init_cli_logger(env_var_name: &str, default_log_level: &str) {
     .init();
 }
 
+pub enum DefaultAnswer {
+    Yes,
+    No,
+}
+
+/// Prints a prompt to ask for confirmation
+pub fn ask_for_confirmation(query: String, default: DefaultAnswer) -> Result<bool, io::Error> {
+    let yesnoprompt: (char, char) = match default {
+        DefaultAnswer::Yes => ('Y', 'n'),
+        DefaultAnswer::No => ('y', 'N'),
+    };
+    print!("{query} [{}/{}]: ", yesnoprompt.0, yesnoprompt.1);
+
+    io::stdout().flush()?;
+    let stdin = io::stdin();
+    let mut line = String::new();
+    stdin.read_line(&mut line)?;
+
+    use regex::Regex;
+    match default {
+        DefaultAnswer::Yes => {
+            // unwrap is okay, because this regex is correct
+            let no_regex: Regex = Regex::new("^[nN]").unwrap();
+            if no_regex.is_match(line.trim()) {
+                Ok(false)
+            } else {
+                Ok(true)
+            }
+        }
+        DefaultAnswer::No => {
+            // unwrap is okay, because this regex is coorrect
+            let yes_regex: Regex = Regex::new("^[yY]").unwrap();
+            if yes_regex.is_match(line.trim()) {
+                Ok(true)
+            } else {
+                Ok(false)
+            }
+        }
+    }
+}
+
 /// Define a simple CLI command.
 pub struct CliCommand {
     /// The Schema definition.
-- 
2.39.2





More information about the pbs-devel mailing list