1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#[macro_use]
extern crate failure;
extern crate tempfile;
use std::env;
use std::io::prelude::*;
use std::io::SeekFrom;
use std::path::Path;
use std::process::Command;
use failure::Error;
use tempfile::NamedTempFile;
static KNOWN_EDITORS: &[&str; 3] = &["/usr/bin/nano", "/usr/bin/vim", "/usr/bin/vi"];
fn get_editor() -> Result<String, Error> {
env::var("EDITOR").or_else(|_| {
for editor in KNOWN_EDITORS {
if Path::new(editor).exists() {
return Ok(editor.to_owned().to_string());
}
}
bail!("Could not find a suitable text editor; Set the EDITOR environment variable")
})
}
pub fn get_text() -> Result<String, Error> {
let mut tmp_file = NamedTempFile::new()?;
let tmp_path = match tmp_file.path().to_str() {
Some(ref s) => s.to_owned().to_string(),
None => bail!("Invalid temporary file path: {:?}", tmp_file),
};
let editor = get_editor()?;
let status = Command::new(&editor).arg(&tmp_path).spawn()?.wait()?;
if !status.success() {
bail!(
"Could not launch editor: {} returned {:?}",
editor,
status.code()
)
}
tmp_file.seek(SeekFrom::Start(0))?;
let mut text = String::new();
tmp_file.read_to_string(&mut text)?;
tmp_file.close()?;
Ok(text)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn editor_from_environment() {
env::set_var("EDITOR", "/plume/test");
let editor = get_editor().unwrap();
assert_eq!(editor, "/plume/test");
}
}