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
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
#![forbid(unsafe_code)]

use std::borrow::Cow;
use std::convert::AsRef;
use core::fmt;
use std::env::{self, VarError};
use std::process::{Command, ExitStatus};

/// Get the default editor for the current environment
// orignally taken from the crate `default-editor`
pub fn get_editor(override_editor: Option<Cow<str>>) -> Result<Cow<str>, VarError> {
    if let Some(z) = override_editor {
        return Ok(z);
    }

    match env::var("VISUAL") {
        Ok(result) => return Ok(result.into()),
        Err(VarError::NotPresent) => {},
        Err(error) => return Err(error),
    }

    match env::var("EDITOR") {
        Ok(result) => return Ok(result.into()),
        Err(VarError::NotPresent) => {},
        Err(error) => return Err(error),
    }

    Ok("vi".into())
}

#[derive(Debug)]
pub enum SEError {
    Process(std::io::Error),
    Var(VarError),
}

impl std::error::Error for SEError {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            SEError::Process(source) => Some(&*source),
            SEError::Var(source) => Some(&*source),
        }
    }
}

impl fmt::Display for SEError {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        match self {
            SEError::Process(_) => {
                formatter.write_str("editor spawning/waiting failed")
            }
            SEError::Var(_) => {
                formatter.write_str("got invalid environment variable")
            }
        }
    }
}

type SEResult = Result<ExitStatus, SEError>;

/// This function either uses the `override_editor` argument as an editor
/// or tries to get this information from the environment variables.
/// A file to edit can be provided via `extra_args`
///
/// Example usage:
/// ```no_run
/// spawn_editor::spawn_editor(Some("nano"), &["src/lib.rs"]);
/// ```
pub fn spawn_editor(override_editor: Option<&str>, extra_args: &[&str]) -> SEResult {
    let editor: std::borrow::Cow<str> = get_editor(override_editor.map(Into::into)).map_err(SEError::Var)?;

    Ok(Command::new(&*editor)
        .args(extra_args)
        .spawn()
        .and_then(|mut c| c.wait())
        .map_err(SEError::Process)?)
}

/// This function is a convenient wrapper around [`spawn_editor`],
/// in case that the arguments aren't simple string slices
pub fn spawn_editor_generic<Ta, Tb>(override_editor: Option<Ta>, extra_args: &[Tb]) -> SEResult
where
    Ta: AsRef<str>,
    Tb: AsRef<str>,
{
    let real_oore = override_editor.as_ref().map(|x| x.as_ref());
    let xar: Vec<_> = extra_args.iter().map(|x| x.as_ref()).collect();
    spawn_editor(real_oore, &xar[..])
}

/// This function is a convenient wrapper around [`spawn_editor_generic`],
/// in case that `override_editor == None`
///
/// Example usage:
/// ```no_run
/// spawn_editor::spawn_editor_with_args(&["src/lib.rs"]);
/// ```
#[inline]
pub fn spawn_editor_with_args<Tb: AsRef<str>>(extra_args: &[Tb]) -> SEResult {
    spawn_editor_generic::<&str, Tb>(None, extra_args)
}

#[cfg(test)]
mod tests {
    use super::*;

    // tests taken from `default-editor v0.1.0`
    mod default_editor {
        use std::env;

        fn it_falls_back_to_vi() {
            env::remove_var("VISUAL");
            env::remove_var("EDITOR");

            assert_eq!(crate::get_editor(None), Ok("vi".into()));
        }

        fn it_returns_visual() {
            env::set_var("VISUAL", "test1");
            env::remove_var("EDITOR");

            assert_eq!(crate::get_editor(None), Ok("test1".to_string().into()));
        }

        fn it_returns_editor() {
            env::remove_var("VISUAL");
            env::set_var("EDITOR", "test2");

            assert_eq!(crate::get_editor(None), Ok("test2".to_string().into()));
        }

        fn it_returns_visual_before_editor() {
            env::set_var("VISUAL", "test3");
            env::set_var("EDITOR", "test4");

            assert_eq!(crate::get_editor(None), Ok("test3".to_string().into()));
        }

        #[test]
        fn all_tests() {
            // Wrap all tests in another function since they cannot be run in parallel
            it_falls_back_to_vi();
            it_returns_visual();
            it_returns_editor();
            it_returns_visual_before_editor();
        }
    }

    #[test]
    #[ignore]
    fn testit() {
        let _ = spawn_editor_with_args(&["src/lib.rs"]);
    }
}