Crate mapped_command

Source
Expand description

A std::process::Command replacement which is a bit more flexible and testable.

For now this is focused on cases which wait until the subprocess is completed and then map the output (or do not care about the output).

  • by default check the exit status

  • bundle a mapping of the captured stdout/stderr to an result into the command, i.e. the Command type is Command<Output, Error> e.g. Command<Vec<String>, Error>.

  • implicitly define if stdout/stderr needs to be captured to prevent mistakes wrt. this, this is done through through the same mechanism which is used to define how the output is mapped, e.g. Command::new("ls", ReturnStdoutString) will implicitly enabled stdout capturing and disable stderr capturing.

  • allow replacing command execution with an callback, this is mainly used to allow mocking the command.

  • besides allowing to decide weather the sub-process should inherit the environment and which variables get removed/set/overwritten this type also allows you to whitelist which env variables should be inherited.

  • do not have &mut self pass through based API. This makes it more bothersome to create functions which create and return commands, which this types intents to make simple so that you can e.g. have a function like fn ls_command() -> Command<Vec<String>, Error> which returns a command which if run runs the ls command and returns a vector of string (or an error if spawning, running or utf8 validation fails).

  • be generic over Output and Error type but dynamic over how the captured stdout/err is mapped to the given Result<Output, Error>. This allows you to e.g. at runtime switch between different function which create a command with the same output but on different ways (i.e. with different called programs and output mapping, e.g. based on a config setting).

§Basic Examples

use mapped_command::{Command, MapStdoutString, ReturnStdoutString, ExecResult, CommandExecutionWithStringOutputError as Error};

/// Usage: `echo().run()`.
fn echo() -> Command<String, Error> {
    // implicitly enables stdout capturing but not stderr capturing
    // and converts the captured bytes to string
    Command::new("echo", ReturnStdoutString)
}

/// Usage: `ls_command().run()`.
fn ls_command() -> Command<Vec<String>, Error> {
    Command::new("ls", MapStdoutString(|out| {
        let lines = out.lines().map(Into::into).collect::<Vec<_>>();
        Ok(lines)
    }))
}

fn main() {
    let res = ls_command()
        //mock
        .with_exec_replacement_callback(|_cmd, _rs| {
            Ok(ExecResult {
                exit_status: 0.into(),
                // Some indicates in the mock that stdout was captured, None would mean it was not.
                stdout: Some("foo\nbar\ndoor\n".to_owned().into()),
                ..Default::default()
            })
        })
        // run, check exit status and map captured outputs
        .run()
        .unwrap();

    assert_eq!(res, vec!["foo", "bar", "door"]);

    let err = ls_command()
        //mock
        .with_exec_replacement_callback(|_cmd, _rs| {
            Ok(ExecResult {
                exit_status: 1.into(),
                stdout: Some("foo\nbar\ndoor\n".to_owned().into()),
                ..Default::default()
            })
        })
        .run()
        .unwrap_err();

    assert_eq!(err.to_string(), "Unexpected exit status. Got: 0x1, Expected: 0x0");
}

§Handling arguments and environment variables

use mapped_command::{Command,ReturnStdoutString, EnvChange};
std::env::set_var("FOOBAR", "the foo");
std::env::set_var("DODO", "no no");
let echoed = Command::new("bash", ReturnStdoutString)
    .with_arguments(&["-c", "echo $0 ${DODO:-yo} $FOOBAR $BARFOOT $(pwd)", "arg1"])
    .with_inherit_env(false)
    .with_env_update("BARFOOT", "the bar")
    //inherit this even if env inheritance is disabled (it is see above)
    .with_env_update("FOOBAR", EnvChange::Inherit)
    .with_working_directory_override(Some("/usr"))
    .run()
    .unwrap();

assert_eq!(echoed, "arg1 yo the foo the bar /usr\n");

Structs§

Enums§

Traits§