tiempo-rs/src/editor.rs

53 lines
1.3 KiB
Rust
Raw Normal View History

2021-07-20 22:08:07 -05:00
use std::process::{Command, Stdio};
use std::io::Read;
2021-06-18 11:27:19 -05:00
2021-07-20 22:08:07 -05:00
use tempfile::NamedTempFile;
use crate::error::{Error::*, Result};
2021-07-20 22:08:07 -05:00
pub fn get_string(note_editor: Option<&String>) -> Result<String> {
let note_editor = if let Some(note_editor) = note_editor {
note_editor
} else {
return Err(EditorIsEmpty);
2021-07-20 22:08:07 -05:00
};
let parts: Vec<_> = note_editor.split(" ").filter(|p| p.len() > 0).collect();
let editor = if let Some(name) = parts.get(0) {
name.to_owned()
} else {
return Err(EditorIsEmpty);
2021-07-20 22:08:07 -05:00
};
let mut c = Command::new(editor);
if parts.len() > 1 {
for part in &parts[1..] {
c.arg(part);
}
}
let mut tmpfile = NamedTempFile::new().map_err(|e| NoTmpFile(e.to_string()))?;
2021-07-20 22:08:07 -05:00
c.arg(tmpfile.as_ref());
let status = c
.stdin(Stdio::inherit())
.stdout(Stdio::inherit())
.stderr(Stdio::inherit())
.output().map_err(|e| EditorFailed {
editor: note_editor.clone(),
error: e.to_string(),
})?
2021-07-20 22:08:07 -05:00
.status;
if status.success() {
let mut note = String::new();
tmpfile.read_to_string(&mut note).map_err(|e| CouldntReadTmpFile(e.to_string()))?;
2021-07-20 22:08:07 -05:00
Ok(note)
} else {
Err(EditorFailed { editor: note_editor.clone(), error: status.to_string() })
2021-07-20 22:08:07 -05:00
}
2021-06-18 11:27:19 -05:00
}