53 lines
1.3 KiB
Rust
53 lines
1.3 KiB
Rust
use std::process::{Command, Stdio};
|
|
use std::io::Read;
|
|
|
|
use tempfile::NamedTempFile;
|
|
|
|
use crate::error::{Error::*, Result};
|
|
|
|
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);
|
|
};
|
|
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);
|
|
};
|
|
|
|
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()))?;
|
|
|
|
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(),
|
|
})?
|
|
.status;
|
|
|
|
if status.success() {
|
|
let mut note = String::new();
|
|
|
|
tmpfile.read_to_string(&mut note).map_err(|e| CouldntReadTmpFile(e.to_string()))?;
|
|
|
|
Ok(note)
|
|
} else {
|
|
Err(EditorFailed { editor: note_editor.clone(), error: status.to_string() })
|
|
}
|
|
}
|