1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
use std::path::PathBuf;

/// uses the PATH environment variable to search
/// for a filename matching the specified name.
/// if a matching filename is not found, it
/// will check for the existence of name.exe
/// and name.bat
pub fn which(name: &str) -> Option<PathBuf> {
    let extensions = vec!["", ".exe", ".bat"];
    for ext in extensions.iter() {
        let exe_name = format!("{}{}", name, ext);
        match which_exact(&exe_name) {
            Some(path) => {
                return Some(path);
            }
            None => {}
        }
    }
    None
}

fn which_exact(name: &str) -> Option<PathBuf> {
    std::env::var_os("PATH").and_then(|paths| {
        std::env::split_paths(&paths)
            .filter_map(|dir| {
                let full_path = dir.join(&name);
                if full_path.is_file() {
                    Some(full_path)
                } else {
                    None
                }
            })
            .next()
    })
}