Struct Cmd

Source
pub struct Cmd(/* private fields */);
Expand description

More convenient version of std::process::Command. Allows for spawning child processes with or without capturing their stdout. It also comes with inbuilt logging of the invocations via log crate.

All the methods for invoking a Cmd:

For more laconic usage see cmd and other macros.

Example:

let mut cmd = Cmd::new("cargo");
cmd
    // `arg*()` methods append arguments
    .arg("metadata")
    .arg2("--color", "never")
    .args(&["--verbose", "--no-deps", "--all-features"])
    .replace_arg(3, "--quiet")
    // These are at `debug` and `error` level by default, `None` disables logging
    .log_cmd(None)
    .log_err(log::Level::Warn)
    // repetated `stdin*()` calls overwrite previous ones
    .stdin("Hi")
    .stdin_bytes(vec![0, 1, 2]);

let () = cmd.run()?;
let output: String = cmd.read()?;
let output: Vec<u8> = cmd.read_bytes()?;
let process: Child = cmd.spawn()?;

Implementations§

Source§

impl Cmd

Source

pub fn new(bin: impl Into<PathBuf>) -> Self

Returns a command builder that invokes the binary at bin. You should also be able to pass the command by name if it is in PATH.

Does not verify that the binary is actually available at the given path. If it isn’t, then an error will be returned when executing the command.

Source

pub fn try_at(bin_path: impl Into<PathBuf>) -> Option<Self>

Returns a command builder if there is some file available at bin_path. If there is no file at the given path returns None. Beware that this won’t take PATH env variable into account. This function expects a relative or absolute filesystem path to the binary, and tries to check if there is some file there (retrying with .exe extension on windows).

If you want to find a binary through PATH, you should use Cmd::lookup_in_path()

Source

pub fn lookup_in_path(bin_name: &str) -> Option<Self>

Returns a command builder for the given bin_name only if this bin_name is accessible trough PATH env variable, otherwise returns None

Source

pub fn bin(&mut self, bin: impl Into<PathBuf>) -> &mut Self

Set binary path, overwrites the path that was set before.

Source

pub fn get_bin(&self) -> &Path

Retuns the currently configured binary path.

Source

pub fn current_dir(&mut self, dir: impl Into<PathBuf>) -> &mut Self

Set the current directory for the child process.

Inherits this process current dir by default.

Source

pub fn get_current_dir(&self) -> Option<&Path>

Returns the currently configured current process directory path

Source

pub fn log_cmd(&mut self, level: impl Into<Option<Level>>) -> &mut Self

When set to some log::Level the command with its arguments and output will be logged via log crate.

Note that this method is independent from Cmd::log_err().

Default: Some(log::Level::Debug)

Source

pub fn log_err(&mut self, level: impl Into<Option<Level>>) -> &mut Self

When set to some log::Level the invocation error will be logged. Set it to None or log::Level::Trace if non-zero exit code is an expected/recoverable error which doesn’t need to be logged.

Note that this method is independent from Cmd::log_cmd().

Default: Some(log::Level::Error)

Source

pub fn stdin(&mut self, stdin: impl Into<String>) -> &mut Self

Sets the string input passed to child process’s stdin. This overwrites the previous value.

Use Cmd::stdin_bytes() if you need to pass non-utf8 byte sequences.

Nothing is written to stdin by default.

Source

pub fn stdin_bytes(&mut self, stdin: Vec<u8>) -> &mut Self

Sets the bytes input passed to child process’s stdin. This overwrites the previous value.

Nothing is written to stdin by default.

Source

pub fn arg2( &mut self, arg1: impl Into<OsString>, arg2: impl Into<OsString>, ) -> &mut Self

Same as cmd.arg(arg1).arg(arg2). This is just a convenient shortcut mostly used to lexically group related arguments (for example named arguments).

Source

pub fn arg(&mut self, arg: impl Into<OsString>) -> &mut Self

Appends a single argument to the list of arguments passed to the child process.

Source

pub fn replace_arg(&mut self, idx: usize, arg: impl Into<OsString>) -> &mut Self

Replaces the argument at the given index with a new value.

§Panics

Panics if the given index is out of range of the arguments already set on this command builder.

Source

pub fn args<I>(&mut self, args: I) -> &mut Self
where I: IntoIterator, I::Item: Into<OsString>,

Extends the array of arguments passed to the child process with args.

Source

pub fn get_args(&self) -> &[OsString]

Returns the currently configured list of command line arguments

Source

pub fn env( &mut self, key: impl Into<OsString>, val: impl Into<OsString>, ) -> &mut Self

Inserts or updates an environment variable mapping.

Note that environment variable names are case-insensitive (but case-preserving) on Windows, and case-sensitive on all other platforms.

Source

pub fn run(&self) -> Result<()>

Same as cmd.spawn()?.wait() See Child::wait() for details.

Source

pub fn read(&self) -> Result<String>

Same as cmd.spawn_piped()?.read() See Child::read() for details.

Source

pub fn read_bytes(&self) -> Result<Vec<u8>>

Same as cmd.spawn_piped()?.read_bytes() See Child::read_bytes() for details.

Source

pub fn spawn(&self) -> Result<Child>

Spawns a child process returning a handle to it. The child inherits both stdout and stderr. See the docs for Child for more details. Note that reading the child process output streams will panic! If you want to read the output, see Cmd::spawn_piped()

Source

pub fn spawn_piped(&self) -> Result<Child>

Spawns a child process returning a handle to it. Child’s stdout will be piped for further reading from it, but stderr will be inherited. See the docs for Child for more details.

Source

pub fn spawn_with(&self, stdout: Stdio, stderr: Stdio) -> Result<Child>

More flexible version of spawn methods that allows you to specify any combination of stdout and stderr conifigurations.

Trait Implementations§

Source§

impl Clone for Cmd

Source§

fn clone(&self) -> Cmd

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Cmd

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl Display for Cmd

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more

Auto Trait Implementations§

§

impl Freeze for Cmd

§

impl RefUnwindSafe for Cmd

§

impl Send for Cmd

§

impl Sync for Cmd

§

impl Unpin for Cmd

§

impl UnwindSafe for Cmd

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T> ToString for T
where T: Display + ?Sized,

Source§

fn to_string(&self) -> String

Converts the given value to a String. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.