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 isCommand<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 disablestderr
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 likefn 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§
- The captured stdout and stderr.
- Capturing of stdout/err converted from bytes to strings.
- A alternative to
std::process::Command
see module level documentation. - Type used for
exec_replacement_callback
to return mocked output and exit status. - Maps the captured stderr with given function if the process exited successfully.
- Like
MapStderr
but converts the captured stdout to an string before mapping. - Maps the captured stdout with given function if the process exited successfully.
- Maps the captured stdout and stderr with given function if the process exited successfully.
- Like
MapStdoutAndErr
but converts the captured stdout and stderr to strings before mapping. - Like
MapStdout
but converts the captured stdout to an string before mapping. - A platform specific opaque exit status.
- Return
()
if the program successfully exits. - Returns a
Vec<u8>
of the captured stderr if the process exits successfully. - Returns the captured stderr as string, if the process succeeds.
- Returns a
Vec<u8>
of the captured stdout if the process exits successfully. - Returns a
Vec<u8>
of the captured stderr and stdout if the process exits successfully. - Returns the captured stdout and stderr as strings, if the process succeeds.
- Returns the captured stdout as string, if the process succeeds.
- The command failed due to an unexpected exit status.
Enums§
- Error used by various
OutputMapping
implementations. - Error from running a command which maps (some) outputs to strings.
- Used to determine how a env variable should be updated.
- A ExitStatus type similar to
std::process::ExitStatus
but which can be created (e.g. for testing).
Traits§
- Trait used to configure what
Command::run()
returns.