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
/* Copyright (c) 2018 - Mathieu Bridon <bochecha@daitauha.fr>
 *
 * This file is part of Plume
 *
 * Plume is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * Plume is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser General Public License
 * along with Plume.  If not, see <http://www.gnu.org/licenses/>.
 */

#[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");
    }
}