Skip to main content

snip_sync/
editor.rs

1use std::path::Path;
2
3pub fn resolve_editor(editor: &str) -> Result<String, String> {
4    let editor_path = Path::new(editor);
5
6    if editor_path.is_absolute() {
7        if !editor_path.exists() {
8            return Err(format!(
9                "EDITOR '{}' does not exist. Set EDITOR to a valid editor path.",
10                editor
11            ));
12        }
13        if !editor_path.is_file() {
14            return Err(format!(
15                "EDITOR '{}' exists but is not a file (it may be a directory). \
16                 Set EDITOR to a valid editor executable.",
17                editor
18            ));
19        }
20        return Ok(editor.to_string());
21    }
22
23    if has_directory_component(editor) {
24        let cwd = std::env::current_dir()
25            .map_err(|e| format!("Cannot resolve relative editor path: {}", e))?;
26        let candidate = cwd.join(editor);
27        if !candidate.exists() {
28            return Err(format!(
29                "EDITOR '{}' does not exist relative to {}.",
30                editor,
31                cwd.display()
32            ));
33        }
34        if !candidate.is_file() {
35            return Err(format!(
36                "EDITOR '{}' exists but is not a file.",
37                candidate.display()
38            ));
39        }
40        let canonical = candidate.canonicalize().map_err(|e| {
41            format!(
42                "Cannot resolve editor path '{}': {}",
43                candidate.display(),
44                e
45            )
46        })?;
47        let canonical_cwd = cwd
48            .canonicalize()
49            .map_err(|e| format!("Cannot canonicalize CWD: {}", e))?;
50        if !canonical.starts_with(&canonical_cwd) {
51            return Err(format!(
52                "EDITOR '{}' resolves outside of current directory (possible symlink attack). Use an absolute path.",
53                editor
54            ));
55        }
56        return Ok(candidate.to_string_lossy().into_owned());
57    }
58
59    let path_var = std::env::var("PATH").unwrap_or_default();
60    let path_sep = if cfg!(windows) { ';' } else { ':' };
61    for dir in path_var.split(path_sep) {
62        if dir.is_empty() {
63            continue;
64        }
65        let candidate = Path::new(dir).join(editor);
66        if candidate.exists() && candidate.is_file() {
67            return Ok(candidate.to_string_lossy().into_owned());
68        }
69    }
70
71    Err(format!(
72        "EDITOR '{}' is not an absolute path and could not be found in PATH. \
73         Set EDITOR to an absolute path (e.g., /usr/bin/vim).",
74        editor
75    ))
76}
77
78fn has_directory_component(editor: &str) -> bool {
79    editor.contains('/') || (cfg!(windows) && editor.contains('\\')) || editor.starts_with('.')
80}
81
82pub fn get_editor() -> Result<String, String> {
83    let editor = std::env::var("EDITOR").unwrap_or_else(|_| "vim".to_string());
84    resolve_editor(&editor)
85}
86
87pub fn open_in_editor(path: &Path) -> Result<(), String> {
88    let editor = get_editor()?;
89    let status = std::process::Command::new(&editor)
90        .arg(path)
91        .status()
92        .map_err(|e| format!("Failed to run editor '{}': {}", editor, e))?;
93    if !status.success() {
94        return Err(format!(
95            "Editor '{}' exited with status: {}",
96            editor, status
97        ));
98    }
99    Ok(())
100}
101
102#[cfg(test)]
103mod tests {
104    use super::*;
105
106    #[test]
107    fn test_has_directory_component() {
108        assert!(has_directory_component("/usr/bin/vim"));
109        assert!(has_directory_component("./vim"));
110        assert!(has_directory_component("../vim"));
111        assert!(has_directory_component("path/to/vim"));
112        assert!(!has_directory_component("vim"));
113        assert!(!has_directory_component("nano"));
114    }
115
116    #[test]
117    fn test_resolve_editor_absolute_exists() {
118        let editor = if cfg!(windows) {
119            "C:\\Windows\\System32\\cmd.exe"
120        } else {
121            "/bin/sh"
122        };
123        let result = resolve_editor(editor);
124        assert!(result.is_ok(), "failed: {:?}", result.err());
125        assert_eq!(result.unwrap(), editor);
126    }
127
128    #[test]
129    fn test_resolve_editor_absolute_not_exists() {
130        let editor = if cfg!(windows) {
131            "C:\\nonexistent\\editor.exe"
132        } else {
133            "/nonexistent/editor"
134        };
135        let result = resolve_editor(editor);
136        assert!(result.is_err());
137        assert!(result.unwrap_err().contains("does not exist"));
138    }
139
140    #[test]
141    fn test_resolve_editor_absolute_is_dir() {
142        let editor = if cfg!(windows) {
143            "C:\\Windows"
144        } else {
145            "/usr/bin"
146        };
147        let result = resolve_editor(editor);
148        assert!(result.is_err());
149        assert!(result.unwrap_err().contains("is not a file"));
150    }
151
152    #[test]
153    fn test_resolve_editor_bare_in_path() {
154        let editor = if cfg!(windows) { "cmd.exe" } else { "sh" };
155        let result = resolve_editor(editor);
156        assert!(result.is_ok(), "failed: {:?}", result.err());
157        assert!(result.unwrap().ends_with(editor));
158    }
159
160    #[test]
161    fn test_resolve_editor_bare_not_in_path() {
162        let result = resolve_editor("nonexistent-editor-xyz-abc");
163        assert!(result.is_err());
164        assert!(result.unwrap_err().contains("could not be found in PATH"));
165    }
166}