Skip to main content

didbot/
path.rs

1//! Finding binaries on `PATH`.
2
3use std::collections::BTreeMap;
4use std::path::PathBuf;
5
6/// The prefix every verb binary carries.
7const PREFIX: &str = "didbot-";
8
9/// The first executable named `name` on `PATH`, if there is one.
10pub fn find(name: &str) -> Option<PathBuf> {
11    let path = std::env::var_os("PATH")?;
12    std::env::split_paths(&path)
13        .map(|dir| dir.join(name))
14        .find(|candidate| executable(candidate))
15}
16
17/// Every `didbot-*` on `PATH`, by name, the first on `PATH` winning — the
18/// same one [`find`] would run.
19pub fn installed() -> BTreeMap<String, PathBuf> {
20    let mut found = BTreeMap::new();
21    let Some(path) = std::env::var_os("PATH") else {
22        return found;
23    };
24    for dir in std::env::split_paths(&path) {
25        let Ok(entries) = std::fs::read_dir(&dir) else {
26            continue;
27        };
28        for entry in entries.flatten() {
29            let name = entry.file_name().to_string_lossy().into_owned();
30            if name.len() > PREFIX.len() && name.starts_with(PREFIX) && executable(&entry.path()) {
31                found.entry(name).or_insert_with(|| entry.path());
32            }
33        }
34    }
35    found
36}
37
38/// A regular file this process may run.
39fn executable(candidate: &std::path::Path) -> bool {
40    let Ok(metadata) = std::fs::metadata(candidate) else {
41        return false;
42    };
43    if !metadata.is_file() {
44        return false;
45    }
46    #[cfg(unix)]
47    {
48        use std::os::unix::fs::PermissionsExt;
49        metadata.permissions().mode() & 0o111 != 0
50    }
51    #[cfg(not(unix))]
52    {
53        true
54    }
55}