open_editor/
lib.rs

1use std::env::temp_dir;
2
3use crate::{editor_call_builder::EditorCallBuilder, errors::OpenEditorError};
4
5mod editor;
6pub mod editor_call_builder;
7mod editor_kind;
8pub mod errors;
9
10/// Open the default editor and allows editing of a string.
11///
12/// # Errors
13/// This function will return an error if the editor call fails, if the file cannot be read, or if the temporary file cleanup fails.
14pub fn edit_in_editor(string: &str) -> Result<String, OpenEditorError> {
15    let mut filename = temp_dir();
16    filename.push(String::from("open_editor_tmp_file"));
17
18    // Write the initial content to the temporary file
19    std::fs::write(&filename, string).map_err(OpenEditorError::FileManipulationFail)?;
20
21    EditorCallBuilder::new(filename.clone())?.call_editor()?;
22    let result =
23        std::fs::read_to_string(&filename).map_err(OpenEditorError::FileManipulationFail)?;
24
25    // Clean up the temporary file after reading
26    std::fs::remove_file(&filename).map_err(|_| {
27        OpenEditorError::TempFileCleanupFail(filename.to_string_lossy().into_owned())
28    })?;
29
30    Ok(result)
31}
32/// Open the default editor and allows editing of a mutable string.
33///
34/// # Errors
35///
36/// This function will return an error if the editor call fails, if the file cannot be read, or if the temporary file cleanup fails.
37pub fn edit_mut_in_editor(string: &mut String) -> Result<(), OpenEditorError> {
38    *string = edit_in_editor(string)?;
39    Ok(())
40}
41/// Open the default editor and returns what was written in it.
42/// # Errors
43/// If the editor call fails, or if the file cannot be read, an error will be returned.
44pub fn open_editor() -> Result<String, OpenEditorError> {
45    edit_in_editor("")
46}