1use std::path::Path;
4use std::process::Stdio;
5
6use serde::{Deserialize, Serialize};
7
8use crate::program::split_words;
9
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
12#[serde(rename_all = "kebab-case")]
13pub enum Editor {
14 #[default]
15 VsCode,
16 PhpStorm,
17 Zed,
18 Custom,
20}
21
22impl Editor {
23 pub fn command(self) -> Option<&'static str> {
26 match self {
27 Editor::VsCode => Some("code --goto {file}:{line}"),
28 Editor::PhpStorm => Some("phpstorm --line {line} {file}"),
29 Editor::Zed => Some("zed {file}:{line}"),
30 Editor::Custom => None,
31 }
32 }
33}
34
35#[derive(Debug, thiserror::Error)]
38#[error("{program}: {message}")]
39pub struct EditorError {
40 pub program: String,
41 pub message: String,
42}
43
44pub fn editor_arguments(command: &str, file: &Path, line: u32) -> Vec<String> {
49 let file = file.to_string_lossy();
50 split_words(command)
51 .into_iter()
52 .map(|word| {
53 word.replace("{file}", &file)
54 .replace("{line}", &line.to_string())
55 })
56 .collect()
57}
58
59pub fn open_in_editor(command: &str, file: &Path, line: u32) -> Result<(), EditorError> {
61 let mut words = editor_arguments(command, file, line).into_iter();
62 let program = words.next().unwrap_or_default();
63 crate::program::command(&program)
64 .args(words)
65 .stdout(Stdio::null())
66 .stderr(Stdio::null())
67 .spawn()
68 .map(|_| ())
69 .map_err(|error| EditorError {
70 program,
71 message: error.to_string(),
72 })
73}
74
75#[cfg(test)]
76mod tests {
77 use super::*;
78
79 #[test]
80 fn the_file_and_the_line_are_put_into_the_command() {
81 let file = Path::new("/code/shop api/Modules/Billing/app/Models/Invoice.php");
82 assert_eq!(
83 editor_arguments(Editor::VsCode.command().unwrap(), file, 12),
84 [
85 "code",
86 "--goto",
87 "/code/shop api/Modules/Billing/app/Models/Invoice.php:12"
88 ]
89 );
90 assert_eq!(
91 editor_arguments(Editor::PhpStorm.command().unwrap(), file, 7),
92 [
93 "phpstorm",
94 "--line",
95 "7",
96 "/code/shop api/Modules/Billing/app/Models/Invoice.php"
97 ]
98 );
99 assert_eq!(
100 editor_arguments(
101 r#""/Applications/My Editor/bin/edit" -l {line} {file}"#,
102 Path::new("a.php"),
103 3
104 ),
105 ["/Applications/My Editor/bin/edit", "-l", "3", "a.php"]
106 );
107 assert!(editor_arguments(" ", file, 1).is_empty());
108 }
109
110 #[test]
111 fn an_editor_that_is_not_there_gives_its_name_and_the_systems_message() {
112 let error =
113 open_in_editor("mortise-no-such-editor {file}", Path::new("a.php"), 1).unwrap_err();
114 assert_eq!(error.program, "mortise-no-such-editor");
115 assert!(!error.message.is_empty());
116 assert!(error.to_string().starts_with("mortise-no-such-editor: "));
117 }
118}