Skip to main content

Command

Struct Command 

Source
pub struct Command<Out, Err, In> { /* private fields */ }
Available on crate feature process only.
Expand description

Builder for spawning a child process.

You can use the command() function on Path or PathBuf to create a CommandBuilder.

use std::path::Path;

use cu::pre::*;

let path = Path::new("ls");
path.command().all_null().wait_nz()?;

§Configuration

Configuring a cu::Command is much like configuring Command from std or tokio. Notable features are:

  • Use cu::args and cu::envs macro to enable adding multiple args or envs of different type in the same call. Without the macro, args/envs only accept iterators that yield the same types.
  • current_dir() will be normalized based on current process, before the child is spawned. std recommends this, but not enforced. Here it’s always done if set
  • name() sets an identifier for the process to be passed to IO handlers. See below for more info about IO.

§Input-Output (IO)

IO is the most important part of dealing with child processes. After all, you would want some information out of the process that you spawned.

Unlike Command in the standard library or tokio, CommandBuilder does not have “default” IO behavior. You cannot spawn the child until you configured how you’d like stdout, stderr, and stdin to behave.

See pio (Process IO) for configuration IO.

§Spawning

See spawn and co_spawn.

Implementations§

Source§

impl Command<(), (), ()>

Source

pub fn new(bin: impl AsRef<OsStr>) -> Self

Start building a command. If the arg is a Path or PathBuf, you can also call .command() on it (remember to import prelude)

use cu::pre::*;

let command = cu::CommandBuilder::new("git");
// or:
let command = std::path::Path::new("git").command();
// even better, find the executable in PATH using the crate's
// binary registry
let command = cu::which("git")?.command();
Source§

impl<Out, Err, In> Command<Out, Err, In>

Source

pub fn arg(self, arg: impl AsRef<OsStr>) -> Self

Add one argument

Use Self::args or args macro to add more than one arguments in one call.

Source

pub fn args<I: IntoIterator<Item = S>, S: AsRef<OsStr>>(self, args: I) -> Self

Add multiple arguments

This only accepts iterators of a single type, which forces you to call .as_ref() if the input has multiple types. To workaround this, use the args shorthand.

Source

pub fn env_clear(self) -> Self

Clear the environment variables, which will prevent inheriting environment variables from the parent (this process)

Source

pub fn env_remove(self, env: impl AsRef<OsStr>) -> Self

Remove an environment variable

Source

pub fn env(self, k: impl AsRef<OsStr>, v: impl AsRef<OsStr>) -> Self

Set a single environment variable

Source

pub fn envs<I: IntoIterator<Item = (K, V)>, K: AsRef<OsStr>, V: AsRef<OsStr>>( self, envs: I, ) -> Self

Set multiple environment variables

This only accepts iterators of a single type, which forces you to call .as_ref() if the input has multiple types. To workaround this, use the envs macro shorthand.

Source

pub fn add(self, config: impl Config) -> Self

Add more configuration. See args! and envs!.

Source

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

Set the current working directory for the child process.

Unlike std/tokio implementation, where canonicalizing the current dir is recommended, we always canonicalize the input here based on this process before spawning the child.

Source

pub fn name(self, name: impl Into<String>) -> Self

Set the name of this command, which maybe used by output config to print in the terminal

Source

pub fn stdin<T: ChildInConfig>(self, config: T) -> Command<Out, Err, T>

Configure child’s standard input stream

Source

pub fn stdin_null(self) -> Command<Out, Err, Null>

Configure child’s standard input stream as pio::null()

Source

pub fn stdin_inherit(self) -> Command<Out, Err, Inherit>

Configure child’s standard input stream to inherit from parent (pio::inherit())

Source

pub fn stdout<T: ChildOutConfig>(self, config: T) -> Command<T, Err, In>

Configure child’s standard output stream

Source

pub fn stdout_inherit(self) -> Command<Inherit, Err, In>

Configure child’s standard output stream to inherit from parent (pio::inherit())

Source

pub fn stderr<T: ChildOutConfig>(self, config: T) -> Command<Out, T, In>

Configure child’s standard error stream

Source

pub fn stderr_inherit(self) -> Command<Out, Inherit, In>

Configure child’s standard output stream to inherit from parent (pio::inherit())

Source

pub fn stdoe<T: ChildOutConfig + Clone>(self, config: T) -> Command<T, T, In>

Configure child’s both standard output and standard error with the same config

Source

pub fn stdout_null(self) -> Command<Null, Err, In>

Configure child’s standard output stream as pio::null()

Source

pub fn stderr_null(self) -> Command<Out, Null, In>

Configure child’s standard error stream as pio::null()

Source

pub fn stdoe_null(self) -> Command<Null, Null, In>

Configure both child’s standard output and error streams as pio::null()

Source

pub fn stdie_null(self) -> Command<Out, Null, Null>

Configure both child’s standard input and error streams as pio::null()

Source

pub fn stdio_null(self) -> Command<Null, Err, Null>

Configure both child’s standard input and output streams as pio::null()

Source

pub fn all_null(self) -> Command<Null, Null, Null>

Configure all standard input, output and error streams as pio::null()

Source

pub fn all_inherit(self) -> Command<Inherit, Inherit, Inherit>

Configure all standard input, output and error streams as pio::inherit()

Source

pub fn preset<P: Preset>(self, preset: P) -> P::Output

Apply a preset for the child command’s input and output.

See pio for available IO presets.

Source

pub fn spawn(self) -> Result<EitherOf<Child, (Child, Out, Err)>>

Spawn the child and run the child’s IO tasks in the background. Note that you have to configure all 3 of stdin, stdout and stderr, before you can spawn the child. Otherwise, you will get a compile error that spawn is not defined

§Blocking

Use co_spawn if you are within an async context.

§Return Value

The return type shown above is a placeholder. The actual return value depends on the configuration for stdout and stderr, specifically, whether they have a handle to access the output. For example pio::inherit() or pio::spinner() don’t have handles, because the output is directly printed, whereas pio::pipe() or pio::string() has handles for reading the output.

  • If both stdout and stderr don’t have handle, then the output is Child
use cu::pre::*; // The prelude import is required for `spawn`

let child = cu::which("echo")?.command()
   .arg("Hello, world!")
   .stdout(cu::lv::I) // print stdout as info level log messages
   .stdie_null()
   .spawn()?;
  • If only stdout has a handle but not stderr, then the output is a 2-tuple (Child, Stdout), where Stdout` is the respective handle type for the configured output.
use cu::pre::*; // The prelude import is required for `spawn`

let (child, lines) = cu::which("bash")?.command()
   .args(["-c", r#"for i in {1..5}; do echo "Line $i"; sleep 1; done"# ])
   .stdout(cu::pio::lines())
   .stdie_null()
   .spawn()?;
  • Otherwise, the output is a 3-tuple (Child, Stdout, Stderr), where Stdout and Stderr are the respective handle type for the output configured, and Stdout might be () if it does not have a handle
use cu::pre::*; // The prelude import is required for `spawn`

let (child, lines, err) = cu::which("bash")?.command()
   .args(["-c", r#"for i in {1..5}; do echo "Line $i"; sleep 1; done"# ])
   .stdout(cu::pio::lines())
   .stderr(cu::pio::string())
   .stdin_null()
   .spawn()?;
Source

pub async fn co_spawn(self) -> Result<EitherOf<Child, (Child, Out, Err)>>

Spawn the child and run the child’s IO tasks in the background. Note that you have to configure all 3 of stdin, stdout and stderr, before you can spawn the child. Otherwise, you will get a compile error that co_spawn is not defined

Note that the child’s IO are still drived by the background context. This is to prevent errors where blocking the current-thread runtime unexpectedly block the child’s IO, even when the child’s IO tasks are running on the background thread.

§Return value

See spawn

Source§

impl<Out: ChildOutConfig<__Null = __OCNull>, Err: ChildOutConfig<__Null = __OCNull>, In: ChildInConfig> Command<Out, Err, In>

Implementation only applies if the child has no output handles (see spawn for more details)

Source

pub fn wait_nz(self) -> Result<()>

Spawn and wait for child to exit with non-zero status code.

This is equivalent to calling spawn(), then wait_nz() on the Child.

Source

pub fn wait(self) -> Result<ExitStatus>

Spawn and wait for child to exit, returning its ExitStatus code

This is equivalent to calling spawn(), then wait() on the Child.

Source

pub async fn co_wait_nz(self) -> Result<()>

Spawn and wait for child to exit with non-zero status code, using the current tokio runtime context.

This is equivalent to calling co_spawn(), then co_wait_nz() on the Child.

Source

pub async fn co_wait(self) -> Result<ExitStatus>

Spawn and wait for child to exit, returning its ExitStatus code, using the current tokio runtime context.

This is equivalent to calling co_spawn(), then co_wait() on the Child.

Auto Trait Implementations§

§

impl<Out, Err, In> !RefUnwindSafe for Command<Out, Err, In>

§

impl<Out, Err, In> !UnwindSafe for Command<Out, Err, In>

§

impl<Out, Err, In> Freeze for Command<Out, Err, In>
where Out: Freeze, Err: Freeze, In: Freeze,

§

impl<Out, Err, In> Send for Command<Out, Err, In>
where Out: Send, Err: Send, In: Send,

§

impl<Out, Err, In> Sync for Command<Out, Err, In>
where Out: Sync, Err: Sync, In: Sync,

§

impl<Out, Err, In> Unpin for Command<Out, Err, In>
where Out: Unpin, Err: Unpin, In: Unpin,

§

impl<Out, Err, In> UnsafeUnpin for Command<Out, Err, In>
where Out: UnsafeUnpin, Err: UnsafeUnpin, In: UnsafeUnpin,

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> 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.

§

impl<T> Pointable for T

§

const ALIGN: usize

The alignment of pointer.
§

type Init = T

The type for initializers.
§

unsafe fn init(init: <T as Pointable>::Init) -> usize

Initializes a with the given initializer. Read more
§

unsafe fn deref<'a>(ptr: usize) -> &'a T

Dereferences the given pointer. Read more
§

unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T

Mutably dereferences the given pointer. Read more
§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. Read more
Source§

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

Source§

type Error = !

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.