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 rstest::rstest;
25    use testresult::TestResult;
26
27    use super::*;
28
29    /// Ensures that the [whoami] executable can be found on a Linux system.
30    ///
31    /// [whoami]: https://man.archlinux.org/man/whoami.1
32    #[rstest]
33    #[case("whoami")]
34    #[case("/usr/bin/whoami")]
35    fn get_command_succeeds(#[case] cmd: &str) -> TestResult {
36        get_command(cmd)?;
37        Ok(())
38    }
39
40    /// Ensures that a bogus executable cannot be found on a Linux system.
41    #[test]
42    fn get_command_fails() -> TestResult {
43        let bogus_cmd = "d202d7951df2c4b711ca44b4bcc9d7b363fa4252127e058c1a910ec05b6cd038d71cc21221c031c0359f993e746b07f5965cf8c5c3746a58337ad9ab65278e77";
44
45        if let Ok(path) = get_command(bogus_cmd) {
46            panic!("The command {bogus_cmd} shouldn't exist, but {path:?} is found!");
47        }
48
49        Ok(())
50    }
51}