use std::io::Write;
use std::path::Path;
use std::{env, process};
use inquire::error::InquireResult;
use tempfile::NamedTempFile;
pub struct FileEditor<'a> {
buf: String,
ext: &'a str,
}
impl<'a> FileEditor<'a> {
pub fn new(current: &str, ext: &'a str) -> Self {
Self {
buf: current.to_string(),
ext,
}
}
pub fn run(mut self) -> InquireResult<String> {
let tmp = self.init_tmp()?;
self.spawn_editor(tmp.path())?;
self.buf = std::fs::read_to_string(tmp.path())?;
Ok(self.buf)
}
fn init_tmp(&self) -> InquireResult<NamedTempFile> {
let mut tmp_file = tempfile::Builder::new()
.prefix("tmp-")
.suffix(&format!(".{}", self.ext))
.rand_bytes(10)
.tempfile()?;
tmp_file.write_all(self.buf.as_bytes())?;
tmp_file.flush()?;
Ok(tmp_file)
}
fn spawn_editor(&mut self, file: &Path) -> InquireResult<()> {
process::Command::new(Self::get_editor())
.arg(file)
.spawn()?
.wait()?;
Ok(())
}
fn get_editor() -> String {
let mut default_editor = String::from("nano");
if let Ok(editor) = env::var("EDITOR")
&& !editor.is_empty()
{
default_editor = editor;
}
if let Ok(editor) = env::var("VISUAL")
&& !editor.is_empty()
{
default_editor = editor;
}
default_editor
}
}