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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
// Copyright (c) 2021 Xu Shaohua <shaohua@biofan.org>. All rights reserved.
// Use of this source is governed by Apache-2.0 License that can be found
// in the LICENSE file.

use std::path::PathBuf;

use crate::error::{Error, ErrorKind};

/// Locate a command.
pub fn which(command: &str) -> Result<Option<PathBuf>, Error> {
    if command.starts_with("/") {
        return Err(Error::from_string(
            ErrorKind::ParameterError,
            format!("Invalid command: {}", command),
        ));
    }
    let paths = std::env::var("PATH")
        .map_err(|_err| Error::new(ErrorKind::IoError, "`PATH` does not exist in environment!"))?;

    let paths: Vec<PathBuf> = paths.split(':').map(|s| PathBuf::from(s)).collect();
    for mut path in paths {
        path.push(command);
        if nc::faccessat(nc::AT_FDCWD, path.as_path(), nc::F_OK | nc::R_OK | nc::X_OK).is_ok() {
            return Ok(Some(path));
        }
    }

    Ok(None)
}

/// Locate a command, returns all available path.
pub fn which_all(command: &str) -> Result<Vec<PathBuf>, Error> {
    if command.starts_with("/") {
        return Err(Error::from_string(
            ErrorKind::ParameterError,
            format!("Invalid command: {}", command),
        ));
    }

    let paths = std::env::var("PATH")
        .map_err(|_err| Error::new(ErrorKind::IoError, "`PATH` does not exist in environment!"))?;

    let paths: Vec<PathBuf> = paths.split(':').map(|s| PathBuf::from(s)).collect();
    let mut result = Vec::new();
    for mut path in paths {
        path.push(command);
        if nc::faccessat(nc::AT_FDCWD, path.as_path(), nc::F_OK | nc::R_OK | nc::X_OK).is_ok() {
            result.push(path);
        }
    }

    Ok(result)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_which() {
        let p = which("bash");
        assert!(p.is_ok());
        let p = p.unwrap();
        assert!(p.is_some());
    }

    #[test]
    fn test_which_all() {
        let list = which_all("bash");
        assert!(list.is_ok());
        let list = list.unwrap();
        assert!(!list.is_empty());
    }
}