change-user-run 0.1.2

Run commands as other users and create users
Documentation
//! Utility functionality.

use std::path::PathBuf;

use which::which;

use crate::Error;

/// Returns the path to a `command`.
///
/// # Errors
///
/// Returns an error if `command` can not be found in PATH.
pub fn get_command(command: &str) -> Result<PathBuf, Error> {
    which(command).map_err(|source| Error::ExecutableNotFound {
        command: command.to_string(),
        source,
    })
}

#[cfg(test)]
#[cfg(target_os = "linux")]
mod tests {
    use rstest::rstest;
    use testresult::TestResult;

    use super::*;

    /// Ensures that the [whoami] executable can be found on a Linux system.
    ///
    /// [whoami]: https://man.archlinux.org/man/whoami.1
    #[rstest]
    #[case("whoami")]
    #[case("/usr/bin/whoami")]
    fn get_command_succeeds(#[case] cmd: &str) -> TestResult {
        get_command(cmd)?;
        Ok(())
    }

    /// Ensures that a bogus executable cannot be found on a Linux system.
    #[test]
    fn get_command_fails() -> TestResult {
        let bogus_cmd = "d202d7951df2c4b711ca44b4bcc9d7b363fa4252127e058c1a910ec05b6cd038d71cc21221c031c0359f993e746b07f5965cf8c5c3746a58337ad9ab65278e77";

        if let Ok(path) = get_command(bogus_cmd) {
            panic!("The command {bogus_cmd} shouldn't exist, but {path:?} is found!");
        }

        Ok(())
    }
}