use crate::{
capturing_executor::CapturingExecutor,
error::Error,
lookup::{Binary, Shell},
transparent_executor::TransparentExecutor,
};
use std::{ffi::OsStr, iter, path::Path, process::Command};
#[derive(Debug)]
pub struct ExecBuilder {
command: Command,
}
impl ExecBuilder {
pub fn with_path<B, A, AS>(binary: B, args: A) -> Result<Self, Error>
where
B: AsRef<Path>,
A: IntoIterator<Item = AS>,
AS: AsRef<OsStr>,
{
let binary = Binary::new(binary)?;
let mut command = Command::new(binary);
command.args(args);
Ok(Self { command })
}
pub fn with_name<B, A, AS>(binary: B, args: A) -> Result<Self, Error>
where
B: AsRef<str>,
A: IntoIterator<Item = AS>,
AS: AsRef<OsStr>,
{
let binary = Binary::find(binary)?;
let mut command = Command::new(binary);
command.args(args);
Ok(Self { command })
}
pub fn with_shell<P>(command: P) -> Result<Self, Error>
where
P: AsRef<str>,
{
let shell = Shell::find()?;
let execstring_args = shell.execstring_args()?;
let command = command.as_ref();
let args = execstring_args.iter().chain(iter::once(&command));
Self::with_path(shell, args)
}
pub fn set_pwd<P>(&mut self, pwd: P) -> &mut Self
where
P: AsRef<Path>,
{
self.command.current_dir(pwd);
self
}
pub fn set_envs<I, K, V>(&mut self, envs: I) -> &mut Self
where
I: IntoIterator<Item = (K, V)>,
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.command.envs(envs);
self
}
pub fn set_env<K, V>(&mut self, key: K, value: V) -> &mut Self
where
K: AsRef<OsStr>,
V: AsRef<OsStr>,
{
self.command.env(key, value);
self
}
pub fn spawn_captured(&mut self) -> Result<CapturingExecutor, Error> {
CapturingExecutor::new(&mut self.command)
}
pub fn spawn_transparent(&mut self) -> Result<TransparentExecutor, Error> {
TransparentExecutor::new(&mut self.command)
}
}