use crate::{Arg, Command, InvalidArg, InvalidProcess, Process};
pub struct CommandBuilder {
command: Option<Command>,
errors: Vec<CommandBuilderError>,
}
#[derive(Clone, Debug)]
pub enum CommandBuilderError {
InvalidProcess(InvalidProcess),
InvalidArg(InvalidArg),
}
impl CommandBuilder {
pub fn new<P>(process: P) -> Self
where
P: TryInto<Process, Error = InvalidProcess>,
{
let mut command = None;
let mut errors = vec![];
match Command::try_create(process) {
Ok(com) => command = Some(com),
Err(err) => errors.push(CommandBuilderError::InvalidProcess(err)),
};
CommandBuilder { command, errors }
}
pub fn build(&self) -> Result<Command, Vec<CommandBuilderError>> {
if !self.errors.is_empty() {
return Err(self.errors.clone());
}
if let Some(command) = self.command.clone() {
return Ok(command);
}
Err(self.errors.clone())
}
pub fn arg<A>(mut self, arg: A) -> Self
where
A: TryInto<Arg, Error = InvalidArg>,
{
let arg: Result<Arg, InvalidArg> = arg.try_into();
if let Some(err) = arg.clone().err() {
self.errors.push(CommandBuilderError::InvalidArg(err));
return self;
}
let arg = arg.unwrap();
if let Some(command) = self.command.as_mut() {
command.args.push(arg)
}
self
}
pub fn env<K, V>(mut self, key: K, value: V) -> Self
where
K: AsRef<str>,
V: AsRef<str>,
{
if let Some(command) = self.command.as_mut() {
command
.env
.insert(String::from(key.as_ref()), String::from(value.as_ref()));
}
self
}
}
impl From<Command> for CommandBuilder {
fn from(command: Command) -> Self {
CommandBuilder {
command: Some(command),
errors: vec![],
}
}
}