change_user_run/
utils.rs

1//! Utility functionality.
2
3use std::path::PathBuf;
4
5use which::which;
6
7use crate::Error;
8
9/// Returns the path to a `command`.
10///
11/// # Errors
12///
13/// Returns an error if `command` can not be found in PATH.
14pub fn get_command(command: &str) -> Result<PathBuf, Error> {
15    which(command).map_err(|source| Error::ExecutableNotFound {
16        command: command.to_string(),
17        source,
18    })
19}
20
21#[cfg(test)]
22#[cfg(target_os = "linux")]
23mod tests {
24    use testresult::TestResult;
25
26    use super::*;
27
28    /// Ensures that the [whoami] executable can be found on a Linux system.
29    ///
30    /// [whoami]: https://man.archlinux.org/man/whoami.1
31    #[test]
32    fn get_command_succeeds() -> TestResult {
33        get_command("whoami")?;
34        Ok(())
35    }
36
37    /// Ensures that a bogus executable cannot be found on a Linux system.
38    #[test]
39    fn get_command_fails() -> TestResult {
40        let bogus_cmd = "d202d7951df2c4b711ca44b4bcc9d7b363fa4252127e058c1a910ec05b6cd038d71cc21221c031c0359f993e746b07f5965cf8c5c3746a58337ad9ab65278e77";
41
42        if let Ok(path) = get_command(bogus_cmd) {
43            panic!("The command {bogus_cmd} shouldn't exist, but {path:?} is found!");
44        }
45
46        Ok(())
47    }
48}