diff options
| author | 魏曹先生 <1992414357@qq.com> | 2025-10-29 15:27:11 +0800 |
|---|---|---|
| committer | 魏曹先生 <1992414357@qq.com> | 2025-10-29 15:27:11 +0800 |
| commit | ed027187568c91a14c545c1962a219552e4654e7 (patch) | |
| tree | e8dbc06d1cea4dce8b025eee8af27ea690068020 /src/utils | |
| parent | 40551da6ec3cc29de0c94f600b2fe55dd0749ef8 (diff) | |
Add input utility functions for user confirmation
Diffstat (limited to 'src/utils')
| -rw-r--r-- | src/utils/input.rs | 52 |
1 files changed, 52 insertions, 0 deletions
diff --git a/src/utils/input.rs b/src/utils/input.rs new file mode 100644 index 0000000..217cede --- /dev/null +++ b/src/utils/input.rs @@ -0,0 +1,52 @@ +/// Confirm the current operation +/// Waits for user input of 'y' or 'n' +pub async fn confirm_hint(text: impl Into<String>) -> bool { + use tokio::io::{self, AsyncBufReadExt, AsyncWriteExt, BufReader}; + + let prompt = text.into().trim().to_string(); + + let mut stdout = io::stdout(); + let mut stdin = BufReader::new(io::stdin()); + + stdout + .write_all(prompt.as_bytes()) + .await + .expect("Failed to write prompt"); + stdout.flush().await.expect("Failed to flush stdout"); + + let mut input = String::new(); + stdin + .read_line(&mut input) + .await + .expect("Failed to read input"); + + input.trim().eq_ignore_ascii_case("y") +} + +/// Confirm the current operation, or execute a closure if rejected +/// Waits for user input of 'y' or 'n' +/// If 'n' is entered, executes the provided closure and returns false +pub async fn confirm_hint_or<F>(text: impl Into<String>, on_reject: F) -> bool +where + F: FnOnce(), +{ + let confirmed = confirm_hint(text).await; + if !confirmed { + on_reject(); + } + confirmed +} + +/// Confirm the current operation, and execute a closure if confirmed +/// Waits for user input of 'y' or 'n' +/// If 'y' is entered, executes the provided closure and returns true +pub async fn confirm_hint_then<F>(text: impl Into<String>, on_confirm: F) -> bool +where + F: FnOnce(), +{ + let confirmed = confirm_hint(text).await; + if confirmed { + on_confirm(); + } + confirmed +} |
