Skip to main content

CmdLineRunner

Struct CmdLineRunner 

Source
pub struct CmdLineRunner { /* private fields */ }
Expand description

A builder for executing external commands with advanced output handling.

CmdLineRunner provides a fluent API for configuring and executing external commands. It supports output capture, secret redaction, progress bar integration, and cancellation.

§Example

use ensembler::CmdLineRunner;

#[tokio::main]
async fn main() -> ensembler::Result<()> {
    let result = CmdLineRunner::new("ls")
        .arg("-la")
        .current_dir("/tmp")
        .execute()
        .await?;

    println!("{}", result.stdout);
    Ok(())
}

Implementations§

Source§

impl CmdLineRunner

Source

pub fn new<P: AsRef<OsStr>>(program: P) -> Self

Creates a new command runner for the given program.

On Windows, commands are automatically wrapped with cmd.exe /c. The command is configured with piped stdout/stderr and null stdin by default.

Source

pub fn kill_all(signal: Signal)

Sends a signal to all running child process groups.

Each child is placed in its own process group at spawn time, so this kills the entire process tree (not just the direct child). This is useful for graceful shutdown scenarios.

Source

pub fn stdin<T: Into<Stdio>>(self, cfg: T) -> Self

Configures stdin handling for the command.

Source

pub fn stdout<T: Into<Stdio>>(self, cfg: T) -> Self

Configures stdout handling for the command.

Source

pub fn stderr<T: Into<Stdio>>(self, cfg: T) -> Self

Configures stderr handling for the command.

Source

pub fn redact(self, redactions: impl IntoIterator<Item = String>) -> Self

Adds strings to redact from command output.

Any occurrence of these strings in stdout or stderr will be replaced with [redacted]. This is useful for hiding sensitive data like API keys or passwords.

§Example
use ensembler::CmdLineRunner;

let result = CmdLineRunner::new("echo")
    .arg("secret-api-key")
    .redact(vec!["secret-api-key".to_string()])
    .execute()
    .await?;

assert_eq!(result.stdout.trim(), "[redacted]");
Source

pub fn with_pr(self, pr: Arc<ProgressJob>) -> Self

Attaches a progress bar to display command status.

The progress bar will be updated with the command being run and its output. Uses the clx crate’s progress bar system.

This method is only available when the progress feature is enabled.

Source

pub fn with_cancel_token(self, cancel: CancellationToken) -> Self

Sets a cancellation token for the command.

When the token is cancelled, the running process will be killed.

Source

pub fn show_stderr_on_error(self, show: bool) -> Self

Controls whether stderr is displayed when the command fails.

Defaults to true.

This method is only available when the progress feature is enabled.

Source

pub fn stderr_to_progress(self, enable: bool) -> Self

Routes stderr to the progress bar instead of printing it directly.

When enabled, stderr lines update the progress bar’s status. When disabled (default), stderr is printed above the progress bar.

This method is only available when the progress feature is enabled.

Source

pub fn allow_non_zero(self, allow: bool) -> Self

Allows the command to exit with a non-zero status without returning an error.

When enabled, the command result is returned even if the exit code is non-zero. This is useful when you need to capture output from commands that may fail but still produce useful output.

§Example
use ensembler::CmdLineRunner;

let result = CmdLineRunner::new("bash")
    .arg("-c")
    .arg("echo 'output'; exit 1")
    .allow_non_zero(true)
    .execute()
    .await?;

// Command succeeded (no error) even though exit code was 1
assert_eq!(result.status.code(), Some(1));
assert_eq!(result.stdout.trim(), "output");
Source

pub fn timeout(self, duration: Duration) -> Self

Sets a timeout for the command.

If the command does not complete within the specified duration, it will be killed and [Error::TimedOut] will be returned.

§Example
use ensembler::CmdLineRunner;
use std::time::Duration;

let result = CmdLineRunner::new("sleep")
    .arg("60")
    .timeout(Duration::from_secs(1))
    .execute()
    .await;

assert!(result.is_err()); // TimedOut error
Source

pub fn current_dir<P: AsRef<Path>>(self, dir: P) -> Self

Sets the working directory for the command.

Source

pub fn env_clear(self) -> Self

Clears all environment variables for the command.

Source

pub fn env<K, V>(self, key: K, val: V) -> Self
where K: AsRef<OsStr>, V: AsRef<OsStr>,

Sets an environment variable for the command.

Source

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

Sets multiple environment variables for the command.

Source

pub fn opt_arg<S: AsRef<OsStr>>(self, arg: Option<S>) -> Self

Adds an optional argument to the command.

If arg is None, no argument is added.

Source

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

Adds a single argument to the command.

Source

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

Adds multiple arguments to the command.

Source

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

Pipes a string to the command’s stdin.

This automatically configures stdin to be piped.

Source

pub async fn execute(self) -> Result<CmdResult>

Executes the command and waits for it to complete.

Returns CmdResult containing captured stdout, stderr, and exit status on success. Returns an error if the command fails to start or exits with a non-zero status.

§Errors
  • [Error::Io] if the command fails to start
  • [Error::ScriptFailed] if the command exits with a non-zero status

Trait Implementations§

Source§

impl Debug for CmdLineRunner

Source§

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

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

impl Display for CmdLineRunner

Source§

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

Formats the value using the given formatter. Read more

Auto Trait Implementations§

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.

Source§

impl<T> Pointable for T

Source§

const ALIGN: usize

The alignment of pointer.
Source§

type Init = T

The type for initializers.
Source§

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

Initializes a with the given initializer. Read more
Source§

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

Dereferences the given pointer. Read more
Source§

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

Mutably dereferences the given pointer. Read more
Source§

unsafe fn drop(ptr: usize)

Drops the object pointed to by the given pointer. 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.
Source§

impl<V, T> VZip<V> for T
where V: MultiLane<T>,

Source§

fn vzip(self) -> V