diff options
| author | 魏曹先生 <1992414357@qq.com> | 2025-10-29 16:34:43 +0800 |
|---|---|---|
| committer | 魏曹先生 <1992414357@qq.com> | 2025-10-29 16:34:43 +0800 |
| commit | 251218ed09d640d7af44f26c6917d8fdb90fc263 (patch) | |
| tree | 4b73b21ad0d8041f3a8f081686bf222f12712f2a /src/utils | |
| parent | 0c0499abfb94d57d9b81c63b3df6e7e5e42a570d (diff) | |
Add input_with_editor function for text editing
This function opens the system editor with default text in a cache file,
reads back the modified content after editing, and removes comment
lines.
Diffstat (limited to 'src/utils')
| -rw-r--r-- | src/utils/input.rs | 53 |
1 files changed, 53 insertions, 0 deletions
diff --git a/src/utils/input.rs b/src/utils/input.rs index 217cede..a728c77 100644 --- a/src/utils/input.rs +++ b/src/utils/input.rs @@ -1,3 +1,5 @@ +use tokio::{fs, process::Command}; + /// Confirm the current operation /// Waits for user input of 'y' or 'n' pub async fn confirm_hint(text: impl Into<String>) -> bool { @@ -50,3 +52,54 @@ where } confirmed } + +/// Input text using the system editor +/// Opens the system editor (from EDITOR environment variable) with default text in a cache file, +/// then reads back the modified content after the editor closes, removing comment lines +pub async fn input_with_editor( + default_text: impl AsRef<str>, + cache_file: impl AsRef<std::path::Path>, + comment_char: impl AsRef<str>, +) -> Result<String, std::io::Error> { + let cache_path = cache_file.as_ref(); + let default_content = default_text.as_ref(); + let comment_prefix = comment_char.as_ref(); + + // Write default text to cache file + fs::write(cache_path, default_content).await?; + + // Get editor from environment variable + let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vi".to_string()); + + // Open editor with cache file + let status = Command::new(editor).arg(cache_path).status().await?; + + if !status.success() { + return Err(std::io::Error::new( + std::io::ErrorKind::Other, + "Editor exited with non-zero status", + )); + } + + // Read the modified content + let content = fs::read_to_string(cache_path).await?; + + // Remove comment lines and trim + let processed_content: String = content + .lines() + .filter_map(|line| { + let trimmed = line.trim(); + if trimmed.starts_with(comment_prefix) { + None + } else { + Some(line) + } + }) + .collect::<Vec<&str>>() + .join("\n"); + + // Delete the cache file + let _ = fs::remove_file(cache_path).await; + + Ok(processed_content) +} |
