Skip to main content

lean_ctx/core/
portable_binary.rs

1pub fn resolve_portable_binary() -> String {
2    let which_cmd = if cfg!(windows) { "where" } else { "which" };
3    if let Ok(output) = std::process::Command::new(which_cmd)
4        .arg("lean-ctx")
5        .stderr(std::process::Stdio::null())
6        .output()
7    {
8        if output.status.success() {
9            let raw = String::from_utf8_lossy(&output.stdout).trim().to_string();
10            if !raw.is_empty() {
11                let path = pick_best_binary_line(&raw);
12                return sanitize_exe_path(&path);
13            }
14        }
15    }
16    let path = std::env::current_exe().map_or_else(
17        |_| "lean-ctx".to_string(),
18        |p| p.to_string_lossy().to_string(),
19    );
20    sanitize_exe_path(&path)
21}
22
23/// On Windows, `where lean-ctx` returns multiple lines (e.g. `lean-ctx` and
24/// `lean-ctx.cmd`). Pick the `.cmd`/`.exe` variant if available, otherwise
25/// the first line.
26fn pick_best_binary_line(raw: &str) -> String {
27    let lines: Vec<&str> = raw
28        .lines()
29        .map(str::trim)
30        .filter(|l| !l.is_empty())
31        .collect();
32    if lines.len() <= 1 {
33        return lines.first().unwrap_or(&"lean-ctx").to_string();
34    }
35    if cfg!(windows) {
36        if let Some(cmd) = lines.iter().find(|l| {
37            std::path::Path::new(*l).extension().is_some_and(|ext| {
38                ext.eq_ignore_ascii_case("cmd") || ext.eq_ignore_ascii_case("exe")
39            })
40        }) {
41            return cmd.to_string();
42        }
43    }
44    lines[0].to_string()
45}
46
47fn sanitize_exe_path(path: &str) -> String {
48    path.trim_end_matches(" (deleted)").to_string()
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54
55    #[test]
56    fn single_line_returns_as_is() {
57        assert_eq!(
58            pick_best_binary_line("/usr/bin/lean-ctx"),
59            "/usr/bin/lean-ctx"
60        );
61    }
62
63    #[test]
64    fn multiline_returns_first_line() {
65        let raw = "/usr/bin/lean-ctx\n/usr/local/bin/lean-ctx";
66        let result = pick_best_binary_line(raw);
67        assert_eq!(result, "/usr/bin/lean-ctx");
68    }
69
70    #[test]
71    fn empty_returns_fallback() {
72        assert_eq!(pick_best_binary_line(""), "lean-ctx");
73    }
74
75    #[test]
76    fn sanitize_removes_deleted_suffix() {
77        assert_eq!(
78            sanitize_exe_path("/usr/bin/lean-ctx (deleted)"),
79            "/usr/bin/lean-ctx"
80        );
81    }
82
83    #[test]
84    fn whitespace_lines_are_filtered() {
85        let raw = "  /usr/bin/lean-ctx  \n  \n  /usr/local/bin/lean-ctx  ";
86        assert_eq!(pick_best_binary_line(raw), "/usr/bin/lean-ctx");
87    }
88}