ninja_files_data2/command/
builder.rs

1use crate::{Arg, Command, InvalidArg, InvalidProcess, Process};
2
3pub struct CommandBuilder {
4    command: Option<Command>,
5    errors: Vec<CommandBuilderError>,
6}
7#[derive(Clone, Debug)]
8pub enum CommandBuilderError {
9    InvalidProcess(InvalidProcess),
10    InvalidArg(InvalidArg),
11}
12
13impl CommandBuilder {
14    pub fn new<P>(process: P) -> Self
15    where
16        P: TryInto<Process, Error = InvalidProcess>,
17    {
18        let mut command = None;
19        let mut errors = vec![];
20        match Command::try_create(process) {
21            Ok(com) => command = Some(com),
22            Err(err) => errors.push(CommandBuilderError::InvalidProcess(err)),
23        };
24        CommandBuilder { command, errors }
25    }
26
27    pub fn build(&self) -> Result<Command, Vec<CommandBuilderError>> {
28        if !self.errors.is_empty() {
29            return Err(self.errors.clone());
30        }
31        if let Some(command) = self.command.clone() {
32            return Ok(command);
33        }
34        //If we get here, its a bug
35        Err(self.errors.clone())
36    }
37
38    pub fn arg<A>(mut self, arg: A) -> Self
39    where
40        A: TryInto<Arg, Error = InvalidArg>,
41    {
42        let arg: Result<Arg, InvalidArg> = arg.try_into();
43
44        if let Some(err) = arg.clone().err() {
45            self.errors.push(CommandBuilderError::InvalidArg(err));
46            return self;
47        }
48        let arg = arg.unwrap();
49
50        if let Some(command) = self.command.as_mut() {
51            command.args.push(arg)
52        }
53
54        self
55    }
56
57    pub fn env<K, V>(mut self, key: K, value: V) -> Self
58    where
59        K: AsRef<str>,
60        V: AsRef<str>,
61    {
62        if let Some(command) = self.command.as_mut() {
63            command
64                .env
65                .insert(String::from(key.as_ref()), String::from(value.as_ref()));
66        }
67        self
68    }
69
70    pub fn cwd<S>(mut self, cwd: Option<S>) -> Self
71    where
72        S: Into<String>,
73    {
74        if let Some(command) = self.command.as_mut() {
75            command.cwd = cwd.map(|c| c.into());
76        }
77        self
78    }
79}
80
81impl From<Command> for CommandBuilder {
82    fn from(command: Command) -> Self {
83        CommandBuilder {
84            command: Some(command),
85            errors: vec![],
86        }
87    }
88}