Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_syntax/src/cli/editor.rs

18.1 KiB, 19 runs

created by r1870400018:65720, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! Resolving, and launching, an external editor.
2//!
3//! `fe2o3_syntax` knows the shape every caller shares -- an explicit flag beats an app-specific
4//! environment variable beats a config value beats `$VISUAL` beats `$EDITOR` beats a PATH probe,
5//! the child runs under `sh -c` so a value like `code --wait` or `emacsclient -t` needs no
6//! quoting, and a bare GUI editor name wants a flag added to make it block -- but it knows
7//! nothing about any one caller's flag name or config file. Those are supplied by the caller;
8//! this module only reads `$VISUAL`, `$EDITOR`, `$TERM`, `$DISPLAY`/`$WAYLAND_DISPLAY` and
9//! `$PATH`, which are the same for everyone.
10
11use oxedyne_fe2o3_core::prelude::*;
12
13use std::{
14 ffi::OsStr,
15 path::{Path, PathBuf},
16 process::{Command, ExitStatus},
17 time::{Duration, Instant},
18};
19
20/// Which precedence rung supplied the resolved editor command.
21#[derive(Clone, Debug, PartialEq, Eq)]
22pub enum Source {
23 Explicit, // --editor, or the caller's equivalent
24 EnvVar(String), // the app-specific env var name the caller asked about, e.g. "ORE_EDITOR"
25 Config, // the caller's own config value
26 Visual, // $VISUAL
27 Editor, // $EDITOR
28 Probe, // found on $PATH from the platform's fallback list
29}
30
31/// The winning editor command, exactly as its source wrote it (a probe result is the bare
32/// executable, plus any wait flag this module adds).
33#[derive(Clone, Debug, PartialEq, Eq)]
34pub struct Resolved {
35 pub command: String,
36 pub source: Source,
37}
38
39/// The parts of the standard environment that resolution and the platform probe need. A
40/// caller's own flag, env var and config value are not here: they have no standard shape for
41/// this module to read on the caller's behalf.
42#[derive(Clone, Debug)]
43pub struct StandardEnv {
44 pub visual: Option<String>,
45 pub editor: Option<String>,
46 pub tty: bool, // stdin is a terminal
47 pub term_dumb: bool, // $TERM == "dumb"
48 pub display: bool, // $DISPLAY or $WAYLAND_DISPLAY is set
49 pub path_dirs: Vec<PathBuf>,
50}
51
52impl StandardEnv {
53
54 /// Reads `$VISUAL`, `$EDITOR`, `$TERM`, `$DISPLAY`, `$WAYLAND_DISPLAY`, `$PATH` and stdin's
55 /// terminal-ness from the real process environment.
56 pub fn from_process() -> Self {
57 use std::io::IsTerminal;
58 let var = |name: &str| std::env::var(name).ok().filter(|v| !v.is_empty());
59 Self {
60 visual: var("VISUAL"),
61 editor: var("EDITOR"),
62 tty: std::io::stdin().is_terminal(),
63 term_dumb: var("TERM").as_deref() == Some("dumb"),
64 display: var("DISPLAY").is_some() || var("WAYLAND_DISPLAY").is_some(),
65 path_dirs: match std::env::var_os("PATH") {
66 Some(p) => std::env::split_paths(&p).collect(),
67 None => Vec::new(),
68 },
69 }
70 }
71}
72
73/// Resolves the editor to run, in order: `explicit`, then `app_env` (the caller's own
74/// environment variable, named and read by the caller), then `config` (the caller's own config
75/// value), then `$VISUAL` (only when the terminal can use it: a tty and `$TERM` is not
76/// `"dumb"`), then `$EDITOR`, then the platform's PATH probe. A bare known GUI editor name
77/// gains its wait flag (`code` -> `code --wait`, and so on) whichever rung supplied it; a value
78/// that already carries its own arguments is left exactly as written.
79pub fn resolve(
80 explicit: Option<&str>,
81 app_env: Option<(&str, &str)>, // (env var name, its value), when the caller found one set
82 config: Option<&str>,
83 env: &StandardEnv,
84) -> Outcome<Resolved> {
85 if let Some(cmd) = non_empty(explicit) {
86 return Ok(finish(cmd, Source::Explicit));
87 }
88 if let Some((name, val)) = app_env {
89 if let Some(cmd) = non_empty(Some(val)) {
90 return Ok(finish(cmd, Source::EnvVar(name.to_string())));
91 }
92 }
93 if let Some(cmd) = non_empty(config) {
94 return Ok(finish(cmd, Source::Config));
95 }
96 if env.tty && !env.term_dumb {
97 if let Some(cmd) = non_empty(env.visual.as_deref()) {
98 return Ok(finish(cmd, Source::Visual));
99 }
100 }
101 if let Some(cmd) = non_empty(env.editor.as_deref()) {
102 return Ok(finish(cmd, Source::Editor));
103 }
104 for probe in probe_list(env.tty, env.display) {
105 let exe = match probe.first() {
106 Some(exe) => *exe,
107 None => continue, // no executable named for this platform; nothing to look up
108 };
109 if find_on_path(exe, &env.path_dirs).is_some() {
110 return Ok(Resolved { command: probe.join(" "), source: Source::Probe });
111 }
112 }
113 Err(err!(
114 "No editor found: pass one explicitly, set {}, $VISUAL or $EDITOR, or install one of \
115 the usual editors on PATH.", app_env.map(|(n, _)| n).unwrap_or("$EDITOR");
116 Missing, Configuration))
117}
118
119fn non_empty(v: Option<&str>) -> Option<&str> {
120 v.map(str::trim).filter(|v| !v.is_empty())
121}
122
123fn finish(cmd: &str, source: Source) -> Resolved {
124 Resolved { command: apply_wait_flag(cmd), source }
125}
126
127// GUI editors that, run bare, open and return at once without blocking, and the flag that
128// makes each wait for the file to close. Verify a flag against a real binary before trusting
129// it; xed and pluma are not in this table because they were not checked.
130const WAIT_FLAGS: &[(&str, &str)] = &[
131 ("code", "--wait"),
132 ("codium", "--wait"),
133 ("cursor", "--wait"),
134 ("windsurf", "--wait"),
135 ("zed", "--wait"),
136 ("subl", "-w"),
137 ("mate", "-w"),
138 ("gvim", "-f"),
139 ("mvim", "-f"),
140 ("kate", "-b"),
141 ("gedit", "--wait"),
142 ("gnome-text-editor", "--standalone"),
143];
144
145/// Adds a known GUI editor's wait flag when `command` is a bare name with no arguments of its
146/// own; otherwise returns it unchanged.
147pub fn apply_wait_flag(command: &str) -> String {
148 let trimmed = command.trim();
149 if trimmed.split_whitespace().count() == 1 {
150 for (name, flag) in WAIT_FLAGS {
151 if trimmed == *name {
152 return format!("{} {}", trimmed, flag);
153 }
154 }
155 }
156 trimmed.to_string()
157}
158
159// Terminal editors
160// The program's name, and the flag its command must carry where the program has a window form as
161// well (empty where it has none). A caller refusing a terminal editor with no tty (§B2 of the CLI
162// plan), or telling one that has handed its file on from one that holds the terminal, checks its
163// resolved command against this before opening anything.
164pub const TERMINAL_EDITORS: &[(&str, &str)] = &[
165 ("editor", ""),
166 ("nano", ""),
167 ("nvim", ""),
168 ("vim", ""),
169 ("vi", ""),
170 ("emacs", "-nw"),
171 ("emacs", "--no-window-system"),
172 ("emacsclient", "-t"),
173 ("emacsclient", "-nw"),
174 ("emacsclient", "--tty"),
175 ("micro", ""),
176 ("hx", ""),
177 ("helix", ""),
178 ("kak", ""),
179 ("joe", ""),
180 ("ne", ""),
181 ("pico", ""),
182 ("view", ""),
183 ("ed", ""),
184];
185
186/// Does `command` run one of the [`TERMINAL_EDITORS`]?
187///
188/// The first word is matched by its file name, and where the program has a window form as well
189/// (`emacs`), only a command that carries the table's flag counts.
190pub fn is_known_terminal_editor(command: &str) -> bool {
191 let mut words = command.split_whitespace();
192 let first = match words.next() {
193 Some(word) => Path::new(word).file_name().and_then(OsStr::to_str).unwrap_or(word),
194 None => return false,
195 };
196 let rest: Vec<&str> = words.collect();
197 TERMINAL_EDITORS.iter().any(|(name, flag)| *name == first && (flag.is_empty() || rest.contains(flag)))
198}
199
200/// The platform's fallback probe order, first found on PATH wins. `tty` picks the terminal vs.
201/// GUI branch; `display` gates the Linux/BSD no-tty branch on `$DISPLAY`/`$WAYLAND_DISPLAY`
202/// being set, since a headless box with no display has nothing in that list to find.
203pub fn probe_list(tty: bool, display: bool) -> Vec<Vec<&'static str>> {
204 if cfg!(target_os = "windows") {
205 vec![vec!["code", "--wait"], vec!["notepad"]]
206 } else if cfg!(target_os = "macos") {
207 if tty {
208 vec![vec!["nano"], vec!["vim"], vec!["vi"]]
209 } else {
210 vec![vec!["open", "-W", "-n", "-t"]]
211 }
212 } else if tty {
213 vec![vec!["editor"], vec!["nano"], vec!["nvim"], vec!["vim"], vec!["vi"]]
214 } else if display {
215 vec![
216 vec!["gnome-text-editor", "--standalone"],
217 vec!["gedit", "--wait"],
218 vec!["kate", "--block"],
219 vec!["code", "--wait"],
220 vec!["gvim", "-f"],
221 ]
222 } else {
223 Vec::new()
224 }
225}
226
227/// The first directory in `dirs` holding an executable file named `name` (`name.exe` too, on
228/// Windows), or `None`.
229pub fn find_on_path(name: &str, dirs: &[PathBuf]) -> Option<PathBuf> {
230 for dir in dirs {
231 let candidate = dir.join(name);
232 if is_executable_file(&candidate) {
233 return Some(candidate);
234 }
235 if cfg!(target_os = "windows") {
236 let exe = dir.join(format!("{}.exe", name));
237 if exe.is_file() {
238 return Some(exe);
239 }
240 }
241 }
242 None
243}
244
245// A real `#[cfg(unix)]` split, not a runtime `if cfg!(unix)`: the unix branch names
246// `std::os::unix::fs::PermissionsExt`, which does not exist to name on a non-Unix target.
247#[cfg(unix)]
248fn is_executable_file(path: &Path) -> bool {
249 use std::os::unix::fs::PermissionsExt;
250 match std::fs::metadata(path) {
251 Ok(m) => m.is_file() && (m.permissions().mode() & 0o111 != 0),
252 Err(_) => false,
253 }
254}
255
256#[cfg(not(unix))]
257fn is_executable_file(path: &Path) -> bool {
258 path.is_file()
259}
260
261/// Builds the child command for `resolved`, following the file(s) as the last argument(s).
262/// On Unix this is `sh -c '<resolved> "$@"' <argv0> <paths...>`, so a value the person wrote
263/// with its own arguments (`code --wait`, `emacsclient -t`) needs no quoting or splitting by
264/// this crate, and a path holding spaces reaches the editor as one argument because `sh` never
265/// re-parses the positional parameters. On Windows, `resolved` is split on whitespace since cmd
266/// has no `sh -c` equivalent worth relying on. `argv0` is the caller's own program name, used
267/// only as `$0` inside the shell and otherwise invisible to the editor.
268pub fn build_command<P: AsRef<OsStr>>(resolved: &str, argv0: &str, paths: &[P]) -> Command {
269 if cfg!(target_os = "windows") {
270 let mut parts = resolved.split_whitespace();
271 let mut cmd = Command::new(parts.next().unwrap_or_default());
272 cmd.args(parts);
273 cmd.args(paths);
274 cmd
275 } else {
276 let mut cmd = Command::new("sh");
277 cmd.arg("-c");
278 cmd.arg(format!("{} \"$@\"", resolved));
279 cmd.arg(argv0);
280 cmd.args(paths);
281 cmd
282 }
283}
284
285/// Whether a finished editor was actually waited on, or handed the file to a window that was
286/// already open and returned at once.
287#[derive(Clone, Copy, Debug, PartialEq, Eq)]
288pub enum Verdict { Waited, Detached }
289
290/// The outcome of running an editor to completion.
291pub struct Run {
292 pub status: ExitStatus,
293 pub elapsed: Duration,
294 pub verdict: Verdict,
295}
296
297/// Runs `resolved` on `paths` and waits for it to exit, classifying a success that returned
298/// within `detach_after` as [`Verdict::Detached`] -- handed off to a window that was already
299/// running, rather than genuinely finished. A non-zero exit is reported as [`Verdict::Waited`]
300/// regardless of how quickly it happened, since a fast failure is not a detach; the caller
301/// decides what a failing editor means.
302pub fn run_and_classify<P: AsRef<OsStr>>(
303 resolved: &str,
304 argv0: &str,
305 paths: &[P],
306 detach_after: Duration,
307) -> Outcome<Run> {
308 let started = Instant::now();
309 let mut child = res!(build_command(resolved, argv0, paths).spawn(), IO, System, Init);
310 let status = res!(child.wait(), IO, System);
311 let elapsed = started.elapsed();
312 let verdict = if status.success() && elapsed < detach_after {
313 Verdict::Detached
314 } else {
315 Verdict::Waited
316 };
317 Ok(Run { status, elapsed, verdict })
318}
319
320#[cfg(test)]
321mod tests {
322 use super::*;
323
324 use std::fs;
325
326 fn stub_env(tty: bool, display: bool, path_dirs: Vec<PathBuf>) -> StandardEnv {
327 StandardEnv {
328 visual: None,
329 editor: None,
330 tty,
331 term_dumb: false,
332 display,
333 path_dirs,
334 }
335 }
336
337 #[cfg(unix)]
338 fn make_executable(p: &Path) {
339 use std::os::unix::fs::PermissionsExt;
340 fs::set_permissions(p, fs::Permissions::from_mode(0o755))
341 .expect("marking the fake executable +x");
342 }
343
344 #[cfg(not(unix))]
345 fn make_executable(_p: &Path) {}
346
347 // A directory of fake executables, one per name, each just `#!/bin/sh\ntrue`.
348 fn fake_path(dir: &Path, names: &[&str]) -> Vec<PathBuf> {
349 for name in names {
350 let p = dir.join(name);
351 fs::write(&p, "#!/bin/sh\ntrue\n").expect("writing a fake executable");
352 make_executable(&p);
353 }
354 vec![dir.to_path_buf()]
355 }
356
357 #[test]
358 fn precedence_explicit_beats_everything_00() -> Outcome<()> {
359 let env = StandardEnv {
360 visual: Some(fmt!("visual-editor")),
361 editor: Some(fmt!("editor-editor")),
362 ..stub_env(true, false, Vec::new())
363 };
364 let r = res!(resolve(
365 Some("explicit-editor"),
366 Some(("ORE_EDITOR", "env-editor")),
367 Some("config-editor"),
368 &env,
369 ));
370 req!(r.command, fmt!("explicit-editor"));
371 req!(r.source, Source::Explicit);
372 Ok(())
373 }
374
375 #[test]
376 fn precedence_app_env_beats_config_and_visual_01() -> Outcome<()> {
377 let env = StandardEnv {
378 visual: Some(fmt!("visual-editor")),
379 ..stub_env(true, false, Vec::new())
380 };
381 let r = res!(resolve(None, Some(("ORE_EDITOR", "env-editor")), Some("config-editor"), &env));
382 req!(r.command, fmt!("env-editor"));
383 req!(r.source, Source::EnvVar(fmt!("ORE_EDITOR")));
384 Ok(())
385 }
386
387 #[test]
388 fn precedence_config_beats_visual_and_editor_02() -> Outcome<()> {
389 let env = StandardEnv {
390 visual: Some(fmt!("visual-editor")),
391 editor: Some(fmt!("editor-editor")),
392 ..stub_env(true, false, Vec::new())
393 };
394 let r = res!(resolve(None, None, Some("config-editor"), &env));
395 req!(r.command, fmt!("config-editor"));
396 req!(r.source, Source::Config);
397 Ok(())
398 }
399
400 #[test]
401 fn visual_beats_editor_when_terminal_capable_03() -> Outcome<()> {
402 let env = StandardEnv {
403 visual: Some(fmt!("visual-editor")),
404 editor: Some(fmt!("editor-editor")),
405 ..stub_env(true, false, Vec::new())
406 };
407 let r = res!(resolve(None, None, None, &env));
408 req!(r.command, fmt!("visual-editor"));
409 req!(r.source, Source::Visual);
410 Ok(())
411 }
412
413 #[test]
414 fn visual_is_skipped_when_term_is_dumb_04() -> Outcome<()> {
415 let env = StandardEnv {
416 visual: Some(fmt!("visual-editor")),
417 editor: Some(fmt!("editor-editor")),
418 term_dumb: true,
419 ..stub_env(true, false, Vec::new())
420 };
421 let r = res!(resolve(None, None, None, &env));
422 req!(r.command, fmt!("editor-editor"));
423 req!(r.source, Source::Editor);
424 Ok(())
425 }
426
427 #[test]
428 fn visual_is_skipped_without_a_tty_05() -> Outcome<()> {
429 let env = StandardEnv {
430 visual: Some(fmt!("visual-editor")),
431 editor: Some(fmt!("editor-editor")),
432 ..stub_env(false, false, Vec::new())
433 };
434 let r = res!(resolve(None, None, None, &env));
435 req!(r.command, fmt!("editor-editor"));
436 req!(r.source, Source::Editor);
437 Ok(())
438 }
439
440 #[test]
441 fn probe_finds_first_available_on_a_scratch_path_06() -> Outcome<()> {
442 let dir = res!(oxedyne_fe2o3_test::scratch::scratch_dir("fe2o3_syntax_editor_probe_06"));
443 // nvim and vim exist, but nano does not -- nano still comes first in the probe list, so
444 // its absence must not stop nvim from being found.
445 let path_dirs = fake_path(&dir, &["nvim", "vim"]);
446 let env = stub_env(true, false, path_dirs);
447 let r = res!(resolve(None, None, None, &env));
448 req!(r.command, fmt!("nvim"));
449 req!(r.source, Source::Probe);
450 Ok(())
451 }
452
453 #[test]
454 fn probe_finds_nothing_returns_an_error_07() -> Outcome<()> {
455 let env = stub_env(true, false, Vec::new());
456 match resolve(None, None, None, &env) {
457 Err(_) => Ok(()),
458 Ok(r) => Err(err!("expected no editor to be found, got {:?}", r; Test)),
459 }
460 }
461
462 #[test]
463 fn wait_flag_added_to_a_bare_known_gui_name_08() -> Outcome<()> {
464 let env = stub_env(true, false, Vec::new());
465 let r = res!(resolve(Some("code"), None, None, &env));
466 req!(r.command, fmt!("code --wait"));
467 Ok(())
468 }
469
470 #[test]
471 fn wait_flag_not_added_when_the_value_has_its_own_arguments_09() -> Outcome<()> {
472 let env = stub_env(true, false, Vec::new());
473 let r = res!(resolve(Some("code --new-window"), None, None, &env));
474 req!(r.command, fmt!("code --new-window"));
475 Ok(())
476 }
477
478 #[test]
479 fn is_known_terminal_editor_matches_by_basename_10() -> Outcome<()> {
480 req!(is_known_terminal_editor("/usr/bin/vim"), true);
481 req!(is_known_terminal_editor("vi"), true);
482 req!(is_known_terminal_editor("code --wait"), false);
483 Ok(())
484 }
485
486 #[test]
487 fn a_terminal_editor_with_a_window_form_is_known_by_its_flag_14() -> Outcome<()> {
488 // The plain ones, by name and by path: every name the two lists held before they were merged.
489 for c in [
490 "editor", "nano", "nvim", "vim", "vi", "micro", "hx", "helix", "kak", "joe", "ne", "pico", "view", "ed",
491 "nano file.txt", "/usr/bin/nvim -u NONE", "/usr/bin/micro x",
492 ] {
493 req!(is_known_terminal_editor(c), true, "{}", c);
494 }
495 // One with a window form is a terminal editor only where its command asks for the terminal.
496 for c in ["emacs -nw", "emacs --no-window-system f", "emacsclient -t", "emacsclient --tty f", "/usr/bin/emacs a -nw"] {
497 req!(is_known_terminal_editor(c), true, "{}", c);
498 }
499 for c in ["emacs", "emacs file.txt", "emacs --nwfoo", "emacsclient", "emacsclient -c", "emacsclient -tab", "emacs-nw", "", " ", "code --wait", "gvim", "vimdiff"] {
500 req!(is_known_terminal_editor(c), false, "{}", c);
501 }
502 Ok(())
503 }
504
505 #[test]
506 fn build_command_carries_a_path_with_spaces_intact_11() -> Outcome<()> {
507 let dir = res!(oxedyne_fe2o3_test::scratch::scratch_dir("fe2o3_syntax_editor_spaces_11"));
508 let out = dir.join("argv.txt");
509 let script = dir.join("record-argv.sh");
510 res!(fs::write(&script, format!(
511 "#!/bin/sh\nfor a in \"$@\"; do printf '%s\\n' \"$a\" >> {}; done\n",
512 out.display(),
513 )), IO, File, Write);
514 make_executable(&script);
515 let weird_path = dir.join("a file with spaces.txt");
516 let paths = vec![weird_path.as_os_str().to_owned()];
517 let mut cmd = build_command(&script.display().to_string(), "test-argv0", &paths);
518 let status = res!(cmd.status(), IO, System);
519 req!(status.success(), true);
520 let recorded = res!(fs::read_to_string(&out), IO, File, Read);
521 req!(recorded.trim_end(), weird_path.display().to_string());
522 Ok(())
523 }
524
525 #[test]
526 fn run_and_classify_detects_a_child_that_exits_at_once_12() -> Outcome<()> {
527 let paths: Vec<&OsStr> = Vec::new();
528 let run = res!(run_and_classify("true", "test-argv0", &paths, Duration::from_secs(2)));
529 req!(run.status.success(), true);
530 req!(run.verdict, Verdict::Detached);
531 Ok(())
532 }
533
534 #[test]
535 fn run_and_classify_treats_a_slow_success_as_waited_13() -> Outcome<()> {
536 let paths: Vec<&OsStr> = Vec::new();
537 let run = res!(run_and_classify(
538 "sleep 0.3", "test-argv0", &paths, Duration::from_millis(50),
539 ));
540 req!(run.status.success(), true);
541 req!(run.verdict, Verdict::Waited);
542 Ok(())
543 }
544}