use crate::{InteractionContext, InteractionEnvironment, InteractionError};
pub struct Editor<'environment> {
environment: &'environment InteractionEnvironment,
extension: String,
executable: Option<String>,
}
impl<'environment> Editor<'environment> {
pub fn new(environment: &'environment InteractionEnvironment, extension: &str) -> Self {
Self {
environment,
extension: extension.to_string(),
executable: None,
}
}
#[must_use]
pub fn with_executable(mut self, executable: &str) -> Self {
self.executable = Some(executable.to_string());
self
}
pub fn edit(self, text: &str) -> Result<Option<String>, InteractionError> {
match self.environment.context {
InteractionContext::Terminal => {
let mut editor = dialoguer::Editor::new();
// Dialoguer just appends the extension to the file, so add a `.` to separate it
editor.extension(&format!(".{}", self.extension));
if let Some(executable) = &self.executable {
editor.executable(executable);
}
Ok(editor.edit(text)?)
}
InteractionContext::NonInteractive => Ok(None),
}
}
}