1#[cfg(target_os = "windows")]
2#[must_use]
13pub fn resolve_command_on_path(cmd: &str) -> Option<std::path::PathBuf> {
14 which::which(cmd).ok()
15}
16
17#[cfg(target_os = "windows")]
18#[must_use]
29pub fn command_on_path(cmd: &str) -> bool {
30 resolve_command_on_path(cmd).is_some()
31}
32
33#[cfg(target_os = "windows")]
34pub fn is_powershell_available() -> bool {
42 command_on_path("powershell.exe") || command_on_path("pwsh.exe")
43}
44
45#[cfg(target_os = "windows")]
46#[must_use]
60pub fn cmd_echo_command(msg: &str) -> String {
61 let mut out = String::from("echo(");
62 for ch in msg.chars() {
63 match ch {
64 '\r' => {}
65 '\n' => out.push_str(" & echo("),
66 '^' | '&' | '|' | '<' | '>' | '(' | ')' => {
67 out.push('^');
68 out.push(ch);
69 }
70 '%' => out.push_str("%%"),
71 '!' => out.push_str("^!"),
72 _ => out.push(ch),
73 }
74 }
75 out
76}
77
78#[cfg(not(target_os = "windows"))]
79#[must_use]
90fn path_is_executable(p: &std::path::Path) -> bool {
91 if !p.is_file() {
92 return false;
93 }
94 #[cfg(unix)]
95 {
96 use std::os::unix::fs::PermissionsExt;
97 std::fs::metadata(p).is_ok_and(|meta| meta.permissions().mode() & 0o111 != 0)
98 }
99 #[cfg(not(unix))]
100 {
101 true
102 }
103}
104
105#[cfg(not(target_os = "windows"))]
106#[must_use]
117pub fn resolve_command_on_path(cmd: &str) -> Option<std::path::PathBuf> {
118 use std::path::Path;
119
120 if cmd.contains(std::path::MAIN_SEPARATOR) {
121 let p = Path::new(cmd);
122 return path_is_executable(p).then(|| p.to_path_buf());
123 }
124
125 let paths = std::env::var_os("PATH")?;
126 for dir in std::env::split_paths(&paths) {
127 let candidate = dir.join(cmd);
128 if path_is_executable(&candidate) {
129 return Some(candidate);
130 }
131 }
132 None
133}
134
135#[cfg(not(target_os = "windows"))]
136#[must_use]
147pub fn command_on_path(cmd: &str) -> bool {
148 resolve_command_on_path(cmd).is_some()
149}
150
151#[cfg(not(target_os = "windows"))]
152pub fn choose_terminal_index_prefer_path(terms: &[(&str, &[&str], bool)]) -> Option<usize> {
163 if let Some(paths) = std::env::var_os("PATH") {
164 for dir in std::env::split_paths(&paths) {
165 for (i, (name, _args, _hold)) in terms.iter().enumerate() {
166 let candidate = dir.join(name);
167 if path_is_executable(&candidate) {
168 return Some(i);
169 }
170 }
171 }
172 }
173 None
174}
175
176#[must_use]
188pub fn shell_single_quote(s: &str) -> String {
189 if s.is_empty() {
190 return "''".to_string();
191 }
192 let mut out = String::with_capacity(s.len() + 2);
193 out.push('\'');
194 for ch in s.chars() {
195 if ch == '\'' {
196 out.push_str("'\"'\"'");
197 } else {
198 out.push(ch);
199 }
200 }
201 out.push('\'');
202 out
203}
204
205#[cfg(not(target_os = "windows"))]
206const EDITOR_FALLBACK_MESSAGE: &str = "No terminal editor found (nvim/vim/emacsclient/emacs/hx/helix/nano). Set VISUAL or EDITOR to use your preferred editor.";
209
210#[cfg(not(target_os = "windows"))]
211#[must_use]
226pub fn editor_open_config_command(path: &std::path::Path) -> String {
227 let path_str = path.display().to_string();
228 let path_quoted = shell_single_quote(&path_str);
229 format!(
231 "( [ -n \"${{VISUAL}}\" ] && command -v \"${{VISUAL%% *}}\" >/dev/null 2>&1 && eval \"${{VISUAL}}\" {path_quoted} ) || \
232 ( [ -n \"${{EDITOR}}\" ] && command -v \"${{EDITOR%% *}}\" >/dev/null 2>&1 && eval \"${{EDITOR}}\" {path_quoted} ) || \
233 ((command -v nvim >/dev/null 2>&1 || pacman -Qi neovim >/dev/null 2>&1) && nvim {path_quoted}) || \
234 ((command -v vim >/dev/null 2>&1 || pacman -Qi vim >/dev/null 2>&1) && vim {path_quoted}) || \
235 ((command -v hx >/dev/null 2>&1 || pacman -Qi helix >/dev/null 2>&1) && hx {path_quoted}) || \
236 ((command -v helix >/dev/null 2>&1 || pacman -Qi helix >/dev/null 2>&1) && helix {path_quoted}) || \
237 ((command -v emacsclient >/dev/null 2>&1 || pacman -Qi emacs >/dev/null 2>&1) && emacsclient -t {path_quoted}) || \
238 ((command -v emacs >/dev/null 2>&1 || pacman -Qi emacs >/dev/null 2>&1) && emacs -nw {path_quoted}) || \
239 ((command -v nano >/dev/null 2>&1 || pacman -Qi nano >/dev/null 2>&1) && nano {path_quoted}) || \
240 (echo '{EDITOR_FALLBACK_MESSAGE}'; echo 'File: {path_quoted}'; read -rn1 -s _ || true)"
241 )
242}
243
244#[cfg(all(test, not(target_os = "windows")))]
245mod tests {
246 #[test]
247 fn utils_command_on_path_detects_executable() {
259 use std::fs;
260 use std::os::unix::fs::PermissionsExt;
261 use std::path::PathBuf;
262
263 let mut dir: PathBuf = std::env::temp_dir();
264 dir.push(format!(
265 "pacsea_test_utils_path_{}_{}",
266 std::process::id(),
267 std::time::SystemTime::now()
268 .duration_since(std::time::UNIX_EPOCH)
269 .expect("System time is before UNIX epoch")
270 .as_nanos()
271 ));
272 let _ = fs::create_dir_all(&dir);
273 let mut cmd_path = dir.clone();
274 cmd_path.push("mycmd");
275 fs::write(&cmd_path, b"#!/bin/sh\nexit 0\n").expect("Failed to write test command script");
276 let mut perms = fs::metadata(&cmd_path)
277 .expect("Failed to read test command script metadata")
278 .permissions();
279 perms.set_mode(0o755);
280 fs::set_permissions(&cmd_path, perms)
281 .expect("Failed to set test command script permissions");
282
283 let orig_path = std::env::var_os("PATH");
284 unsafe { std::env::set_var("PATH", dir.display().to_string()) };
285 assert!(super::command_on_path("mycmd"));
286 assert_eq!(
287 super::resolve_command_on_path("mycmd").as_deref(),
288 Some(cmd_path.as_path())
289 );
290 assert!(!super::command_on_path("notexist"));
291 assert!(super::resolve_command_on_path("notexist").is_none());
292 unsafe {
293 if let Some(v) = orig_path {
294 std::env::set_var("PATH", v);
295 } else {
296 std::env::remove_var("PATH");
297 }
298 }
299 let _ = fs::remove_dir_all(&dir);
300 }
301
302 #[test]
303 fn utils_resolve_command_on_path_skips_non_executable_file() {
314 use std::fs;
315 use std::os::unix::fs::PermissionsExt;
316 use std::path::PathBuf;
317
318 let mut dir: PathBuf = std::env::temp_dir();
319 dir.push(format!(
320 "pacsea_test_utils_notexec_{}_{}",
321 std::process::id(),
322 std::time::SystemTime::now()
323 .duration_since(std::time::UNIX_EPOCH)
324 .expect("System time is before UNIX epoch")
325 .as_nanos()
326 ));
327 let _ = fs::create_dir_all(&dir);
328 let mut stub = dir.clone();
329 stub.push("stub");
330 fs::write(&stub, b"not runnable\n").expect("Failed to write stub file");
331 let mut perms = fs::metadata(&stub)
332 .expect("Failed to read stub metadata")
333 .permissions();
334 perms.set_mode(0o644);
335 fs::set_permissions(&stub, perms).expect("Failed to set non-executable permissions");
336
337 let orig_path = std::env::var_os("PATH");
338 unsafe { std::env::set_var("PATH", dir.display().to_string()) };
339 assert!(!super::command_on_path("stub"));
340 assert!(super::resolve_command_on_path("stub").is_none());
341 unsafe {
342 if let Some(v) = orig_path {
343 std::env::set_var("PATH", v);
344 } else {
345 std::env::remove_var("PATH");
346 }
347 }
348 let _ = fs::remove_dir_all(&dir);
349 }
350
351 #[test]
352 fn utils_choose_terminal_index_prefers_first_present_in_terms_order() {
364 use std::fs;
365 use std::os::unix::fs::PermissionsExt;
366 use std::path::PathBuf;
367
368 let mut dir: PathBuf = std::env::temp_dir();
369 dir.push(format!(
370 "pacsea_test_utils_terms_{}_{}",
371 std::process::id(),
372 std::time::SystemTime::now()
373 .duration_since(std::time::UNIX_EPOCH)
374 .expect("System time is before UNIX epoch")
375 .as_nanos()
376 ));
377 let _ = fs::create_dir_all(&dir);
378 let mut kitty = dir.clone();
379 kitty.push("kitty");
380 fs::write(&kitty, b"#!/bin/sh\nexit 0\n").expect("Failed to write test kitty script");
381 let mut perms = fs::metadata(&kitty)
382 .expect("Failed to read test kitty script metadata")
383 .permissions();
384 perms.set_mode(0o755);
385 fs::set_permissions(&kitty, perms).expect("Failed to set test kitty script permissions");
386
387 let terms: &[(&str, &[&str], bool)] =
388 &[("gnome-terminal", &[], false), ("kitty", &[], false)];
389 let orig_path = std::env::var_os("PATH");
390 unsafe { std::env::set_var("PATH", dir.display().to_string()) };
391 let idx = super::choose_terminal_index_prefer_path(terms).expect("index");
392 assert_eq!(idx, 1);
393 unsafe {
394 if let Some(v) = orig_path {
395 std::env::set_var("PATH", v);
396 } else {
397 std::env::remove_var("PATH");
398 }
399 }
400 let _ = fs::remove_dir_all(&dir);
401 }
402
403 #[test]
404 fn utils_shell_single_quote_handles_edges() {
415 assert_eq!(super::shell_single_quote(""), "''");
416 assert_eq!(super::shell_single_quote("abc"), "'abc'");
417 assert_eq!(super::shell_single_quote("a'b"), "'a'\"'\"'b'");
418 }
419
420 #[test]
421 fn utils_editor_open_config_command_order_visual_then_editor_then_fallbacks() {
432 use std::path::Path;
433 let path = Path::new("/tmp/settings.conf");
434 let cmd = super::editor_open_config_command(path);
435 let idx_visual = cmd.find("VISUAL").expect("command must mention VISUAL");
436 let idx_editor = cmd.find("EDITOR").expect("command must mention EDITOR");
437 let idx_nvim = cmd
438 .find("nvim")
439 .expect("command must mention nvim fallback");
440 assert!(idx_visual < idx_editor, "VISUAL must appear before EDITOR");
441 assert!(
442 idx_editor < idx_nvim,
443 "EDITOR must appear before nvim fallback"
444 );
445 }
446
447 #[test]
448 fn utils_editor_open_config_command_contains_fallback_chain_and_message() {
459 use std::path::Path;
460 let path = Path::new("/tmp/theme.conf");
461 let cmd = super::editor_open_config_command(path);
462 assert!(cmd.contains("nvim"), "fallback chain must include nvim");
463 assert!(cmd.contains("vim"), "fallback chain must include vim");
464 assert!(cmd.contains("hx"), "fallback chain must include hx");
465 assert!(cmd.contains("helix"), "fallback chain must include helix");
466 assert!(
467 cmd.contains("emacsclient"),
468 "fallback chain must include emacsclient"
469 );
470 assert!(cmd.contains("emacs"), "fallback chain must include emacs");
471 assert!(cmd.contains("nano"), "fallback chain must include nano");
472 assert!(
473 cmd.contains("No terminal editor found"),
474 "command must include fallback message"
475 );
476 }
477
478 #[test]
479 fn utils_editor_open_config_command_path_is_shell_single_quoted() {
490 use std::path::Path;
491 let path_with_quote = Path::new("/tmp/foo'bar.conf");
492 let path_str = path_with_quote.display().to_string();
493 let path_quoted = super::shell_single_quote(&path_str);
494 let cmd = super::editor_open_config_command(path_with_quote);
495 assert!(
496 cmd.contains(&path_quoted),
497 "command must contain shell-single-quoted path, got quoted: {path_quoted:?}"
498 );
499 assert!(
501 !cmd.contains("/tmp/foo'bar.conf"),
502 "command must not contain raw path with unescaped single quote"
503 );
504 }
505}