Skip to main content

command_extra/
lib.rs

1use std::{
2    ffi::OsStr,
3    path::Path,
4    process::{Command, Stdio},
5};
6
7pub trait CommandExtra: Sized {
8    fn with_current_dir(self, dir: impl AsRef<Path>) -> Self;
9    fn with_env(self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> Self;
10    fn without_env(self, key: impl AsRef<OsStr>) -> Self;
11    fn with_no_env(self) -> Self;
12    fn with_arg(self, arg: impl AsRef<OsStr>) -> Self;
13    fn with_stdin(self, stdio: Stdio) -> Self;
14    fn with_stdout(self, stdio: Stdio) -> Self;
15    fn with_stderr(self, stdio: Stdio) -> Self;
16
17    fn with_args<Args>(self, args: Args) -> Self
18    where
19        Args: IntoIterator,
20        Args::Item: AsRef<OsStr>,
21    {
22        args.into_iter().fold(self, |cmd, arg| cmd.with_arg(arg))
23    }
24
25    fn with_envs<Envs, Key, Value>(self, envs: Envs) -> Self
26    where
27        Envs: IntoIterator<Item = (Key, Value)>,
28        Key: AsRef<OsStr>,
29        Value: AsRef<OsStr>,
30    {
31        envs.into_iter()
32            .fold(self, |cmd, (key, value)| cmd.with_env(key, value))
33    }
34}
35
36impl CommandExtra for Command {
37    fn with_current_dir(mut self, dir: impl AsRef<Path>) -> Self {
38        self.current_dir(dir);
39        self
40    }
41
42    fn with_env(mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> Self {
43        self.env(key, value);
44        self
45    }
46
47    fn without_env(mut self, key: impl AsRef<OsStr>) -> Self {
48        self.env_remove(key);
49        self
50    }
51
52    fn with_no_env(mut self) -> Self {
53        self.env_clear();
54        self
55    }
56
57    fn with_arg(mut self, arg: impl AsRef<OsStr>) -> Self {
58        self.arg(arg);
59        self
60    }
61
62    fn with_stdin(mut self, stdio: Stdio) -> Self {
63        self.stdin(stdio);
64        self
65    }
66
67    fn with_stdout(mut self, stdio: Stdio) -> Self {
68        self.stdout(stdio);
69        self
70    }
71
72    fn with_stderr(mut self, stdio: Stdio) -> Self {
73        self.stderr(stdio);
74        self
75    }
76}