zen_console_input/
lib.rs

1//! ZenConsoleInput: A simple, cross-platform console input library for Rust.
2//!
3//! This library provides an easy-to-use interface for getting various types of
4//! user input from the console, including single-line input, multiline input,
5//! password input, and selection from a list of options.
6
7mod input;
8mod password;
9mod selection;
10
11pub use input::Input;
12pub use password::Password;
13pub use selection::Selection;
14
15/// The main struct for ZenConsoleInput.
16///
17/// Use this struct to create new input, password, or selection prompts.
18pub struct ZenConsoleInput;
19
20impl ZenConsoleInput {
21    /// Creates a new ZenConsoleInput instance.
22    pub fn new() -> Self {
23        ZenConsoleInput
24    }
25
26    /// Creates a new Input instance for text input.
27    pub fn input(&self) -> Input {
28        Input::new()
29    }
30
31    /// Creates a new Selection instance for choosing from a list of options.
32    pub fn selection(&self) -> Selection {
33        Selection::new()
34    }
35
36    /// Creates a new Password instance for password input.
37    pub fn password(&self) -> Password {
38        Password::new()
39    }
40
41    /// Opens the user's default text editor to edit the given content.
42    ///
43    /// This function is only available when the "editor" feature is enabled.
44    #[cfg(feature = "editor")]
45    pub(crate) fn edit_in_external_editor(initial_content: &str) -> std::io::Result<String> {
46        use std::fs::File;
47        use std::io::{self, Read, Write};
48        use std::process::Command;
49        use tempfile::NamedTempFile;
50
51        let mut temp_file = NamedTempFile::new()?;
52        write!(temp_file, "{}", initial_content)?;
53
54        let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vi".to_string());
55        let status = Command::new(editor).arg(temp_file.path()).status()?;
56
57        if !status.success() {
58            return Err(io::Error::new(
59                io::ErrorKind::Other,
60                "Editor exited with non-zero status",
61            ));
62        }
63
64        let mut content = String::new();
65        File::open(temp_file.path())?.read_to_string(&mut content)?;
66        Ok(content)
67    }
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    #[test]
75    fn test_zen_console_input_creation() {
76        let _zci = ZenConsoleInput::new();
77    }
78}