Skip to main content

pacsea/install/
utils.rs

1#[cfg(target_os = "windows")]
2/// What: Resolve an executable on `PATH` (Windows).
3///
4/// Input:
5/// - `cmd`: Executable name to probe.
6///
7/// Output:
8/// - `Some(path)` when `which` resolves the command; otherwise `None`.
9///
10/// Details:
11/// - Uses the `which` crate so `PATHEXT` and Windows search rules match `command_on_path`.
12#[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/// What: Determine whether a command is available on the Windows `PATH`.
19///
20/// Input:
21/// - `cmd`: Executable name to probe.
22///
23/// Output:
24/// - `true` when the command resolves via the `which` crate; otherwise `false`.
25///
26/// Details:
27/// - Delegates to `resolve_command_on_path` so presence matches actual resolution.
28#[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")]
34/// What: Check if `PowerShell` is available on Windows.
35///
36/// Output:
37/// - `true` when `PowerShell` can be found on PATH; otherwise `false`.
38///
39/// Details:
40/// - Checks for `powershell.exe` or `pwsh.exe` (`PowerShell` Core) on the system.
41pub fn is_powershell_available() -> bool {
42    command_on_path("powershell.exe") || command_on_path("pwsh.exe")
43}
44
45#[cfg(target_os = "windows")]
46/// What: Build a safe `cmd.exe` echo command for arbitrary text.
47///
48/// Inputs:
49/// - `msg`: Message text displayed by `cmd /K`.
50///
51/// Output:
52/// - A command string beginning with `echo(` and escaped for `cmd.exe`.
53///
54/// Details:
55/// - Escapes command metacharacters so text cannot break out of the echo context.
56/// - Doubles `%` to prevent environment-variable expansion.
57/// - Escapes `!` to avoid delayed-expansion surprises.
58/// - Converts newline boundaries into chained `echo(` calls.
59#[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/// What: Return whether `p` is a regular file with at least one executable bit set (Unix).
80///
81/// Input:
82/// - `p`: Filesystem path to inspect.
83///
84/// Output:
85/// - `true` when the path is a file and mode includes any execute bit; otherwise `false`.
86///
87/// Details:
88/// - Used by `resolve_command_on_path` and terminal discovery so “on PATH” matches the shell.
89#[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/// What: Resolve an executable on `PATH` or by explicit path (Unix).
107///
108/// Input:
109/// - `cmd`: Program basename or path containing `MAIN_SEPARATOR`.
110///
111/// Output:
112/// - `Some(path)` for the first executable match; otherwise `None`.
113///
114/// Details:
115/// - Honour Unix permission bits so a non-executable file on `PATH` is not treated as a tool.
116#[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/// What: Determine whether a command is available on the Unix `PATH`.
137///
138/// Input:
139/// - `cmd`: Program name or explicit path to inspect.
140///
141/// Output:
142/// - `true` when an executable file is found and marked executable.
143///
144/// Details:
145/// - Same rules as `resolve_command_on_path`; kept as a convenience for boolean checks.
146#[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"))]
152/// What: Locate the first available terminal executable from a preference list.
153///
154/// Input:
155/// - `terms`: Tuples of `(binary, args, needs_xfce_command)` ordered by preference.
156///
157/// Output:
158/// - `Some(index)` pointing into `terms` when a binary is found; otherwise `None`.
159///
160/// Details:
161/// - Iterates directories in `PATH`, favouring the earliest match respecting executable bits.
162pub 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/// What: Safely single-quote an arbitrary string for POSIX shells.
177///
178/// Input:
179/// - `s`: Text to quote.
180///
181/// Output:
182/// - New string wrapped in single quotes, escaping embedded quotes via the `'
183///   '"'"'` sequence.
184///
185/// Details:
186/// - Returns `''` for empty input so the shell treats it as an empty argument.
187#[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"))]
206/// Fallback message when no terminal editor is found. Must not contain single quotes (used inside `echo '...'` in shell).
207/// Reusable for i18n or logging if needed.
208const 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/// What: Build a shell command string that opens a config file in the user's preferred terminal editor.
212///
213/// Inputs:
214/// - `path`: Path to the config file to open.
215///
216/// Output:
217/// - A single shell expression that tries, in order: `$VISUAL`, `$EDITOR`, then the built-in
218///   fallback chain (nvim, vim, hx, helix, emacsclient, emacs, nano), and finally a fallback
219///   message with `read -rn1 -s _`.
220///
221/// Details:
222/// - The script expects `VISUAL`/`EDITOR` to be runnable commands that accept a file path.
223/// - The path is passed through `shell_single_quote` so paths with spaces or single quotes are safe.
224/// - Order: VISUAL then EDITOR then nvim → vim → hx → helix → emacsclient -t → emacs -nw → nano.
225#[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    // path_quoted is already single-quoted, so the full argument to echo is one safe string.
230    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    /// What: Validate that `command_on_path` recognises executables present on the customised `PATH`.
248    ///
249    /// Inputs:
250    /// - Temporary directory containing a shim `mycmd` script made executable.
251    /// - Environment `PATH` overridden to reference only the temp directory.
252    ///
253    /// Output:
254    /// - Returns `true` for `mycmd` and `false` for a missing binary, confirming detection logic.
255    ///
256    /// Details:
257    /// - Restores the original `PATH` and cleans up the temporary directory after assertions.
258    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    /// What: Ensure a non-executable file on `PATH` is not resolved as a command.
304    ///
305    /// Inputs:
306    /// - Temporary directory with a `stub` file mode `0o644` prepended to `PATH`.
307    ///
308    /// Output:
309    /// - `command_on_path` is `false` and `resolve_command_on_path` is `None`.
310    ///
311    /// Details:
312    /// - Guards parity with shell behaviour for PKGBUILD check tool discovery.
313    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    /// What: Ensure `choose_terminal_index_prefer_path` honours the preference ordering when multiple terminals exist.
353    ///
354    /// Inputs:
355    /// - Temporary directory with an executable `kitty` shim placed on `PATH`.
356    /// - Preference list where `gnome-terminal` precedes `kitty` but is absent.
357    ///
358    /// Output:
359    /// - Function returns index `1`, selecting `kitty`, the first available terminal in the list.
360    ///
361    /// Details:
362    /// - Saves and restores the `PATH` environment variable while ensuring the temp directory is removed.
363    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    /// What: Check that `shell_single_quote` escapes edge cases safely.
405    ///
406    /// Inputs:
407    /// - Three sample strings: empty, plain ASCII, and text containing a single quote.
408    ///
409    /// Output:
410    /// - Returns properly quoted strings, using `''` for empty and the standard POSIX escape for embedded quotes.
411    ///
412    /// Details:
413    /// - Covers representative cases without filesystem interaction to guard future regressions.
414    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    /// What: Assert that `editor_open_config_command` builds a command with VISUAL then EDITOR then fallbacks.
422    ///
423    /// Inputs:
424    /// - A dummy path (e.g. `/tmp/settings.conf`).
425    ///
426    /// Output:
427    /// - The returned string contains VISUAL branch before EDITOR branch before nvim fallback.
428    ///
429    /// Details:
430    /// - Shell-only implementation; order is fixed in the string regardless of env.
431    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    /// What: Assert that `editor_open_config_command` includes the full fallback chain and final message.
449    ///
450    /// Inputs:
451    /// - A dummy path.
452    ///
453    /// Output:
454    /// - The returned string contains nvim, vim, hx, helix, emacsclient, emacs, nano and "No terminal editor found".
455    ///
456    /// Details:
457    /// - Validates the built-in fallback list and fallback message without executing shell.
458    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    /// What: Assert that the path in `editor_open_config_command` is shell-single-quoted.
480    ///
481    /// Inputs:
482    /// - A path containing a single quote (e.g. `/tmp/foo'bar.conf`).
483    ///
484    /// Output:
485    /// - The returned string contains the safely quoted path (single-quote escape sequence), not raw path.
486    ///
487    /// Details:
488    /// - Paths with single quotes must be quoted via `shell_single_quote` so the shell sees one argument.
489    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        // Raw unquoted path with single quote would break shell; must not appear as '/tmp/foo'bar.conf'
500        assert!(
501            !cmd.contains("/tmp/foo'bar.conf"),
502            "command must not contain raw path with unescaped single quote"
503        );
504    }
505}