git_command/
lib.rs

1//! Launch commands very similarly to `Command`, but with `git` specific capabilities and adjustments.
2#![deny(rust_2018_idioms, missing_docs)]
3#![forbid(unsafe_code)]
4
5use std::ffi::OsString;
6
7/// A structure to keep settings to use when invoking a command via [`spawn()`][Prepare::spawn()], after creating it with [`prepare()`].
8pub struct Prepare {
9    /// The command to invoke (either with or without shell depending on `use_shell`.
10    pub command: OsString,
11    /// The way standard input is configured.
12    pub stdin: std::process::Stdio,
13    /// The way standard output is configured.
14    pub stdout: std::process::Stdio,
15    /// The way standard error is configured.
16    pub stderr: std::process::Stdio,
17    /// The arguments to pass to the spawned process.
18    pub args: Vec<OsString>,
19    /// environment variables to set in the spawned process.
20    pub env: Vec<(OsString, OsString)>,
21    /// If `true`, we will use `sh` to execute the `command`.
22    pub use_shell: bool,
23}
24
25mod prepare {
26    use std::{
27        ffi::OsString,
28        process::{Command, Stdio},
29    };
30
31    use bstr::ByteSlice;
32
33    use crate::Prepare;
34
35    /// Builder
36    impl Prepare {
37        /// If called, the command will not be executed directly, but with `sh`.
38        ///
39        /// This also allows to pass shell scripts as command, or use commands that contain arguments which are subsequently
40        /// parsed by `sh`.
41        pub fn with_shell(mut self) -> Self {
42            self.use_shell = self.command.to_str().map_or(true, |cmd| {
43                cmd.as_bytes().find_byteset(b"|&;<>()$`\\\"' \t\n*?[#~=%").is_some()
44            });
45            self
46        }
47
48        /// Unconditionally turn off using the shell when spawning the command.
49        /// Note that not using the shell is the default so an effective use of this method
50        /// is some time after [`with_shell()`][Prepare::with_shell()] was called.
51        pub fn without_shell(mut self) -> Self {
52            self.use_shell = false;
53            self
54        }
55
56        /// Configure the process to use `stdio` for _stdin.
57        pub fn stdin(mut self, stdio: Stdio) -> Self {
58            self.stdin = stdio;
59            self
60        }
61        /// Configure the process to use `stdio` for _stdout_.
62        pub fn stdout(mut self, stdio: Stdio) -> Self {
63            self.stdout = stdio;
64            self
65        }
66        /// Configure the process to use `stdio` for _stderr.
67        pub fn stderr(mut self, stdio: Stdio) -> Self {
68            self.stderr = stdio;
69            self
70        }
71
72        /// Add `arg` to the list of arguments to call the command with.
73        pub fn arg(mut self, arg: impl Into<OsString>) -> Self {
74            self.args.push(arg.into());
75            self
76        }
77
78        /// Add `args` to the list of arguments to call the command with.
79        pub fn args(mut self, args: impl IntoIterator<Item = impl Into<OsString>>) -> Self {
80            self.args
81                .append(&mut args.into_iter().map(Into::into).collect::<Vec<_>>());
82            self
83        }
84
85        /// Add `key` with `value` to the environment of the spawned command.
86        pub fn env(mut self, key: impl Into<OsString>, value: impl Into<OsString>) -> Self {
87            self.env.push((key.into(), value.into()));
88            self
89        }
90    }
91
92    /// Finalization
93    impl Prepare {
94        /// Spawn the command as configured.
95        pub fn spawn(self) -> std::io::Result<std::process::Child> {
96            Command::from(self).spawn()
97        }
98    }
99
100    impl From<Prepare> for Command {
101        fn from(mut prep: Prepare) -> Command {
102            let mut cmd = if prep.use_shell {
103                let mut cmd = Command::new(if cfg!(windows) { "sh" } else { "/bin/sh" });
104                cmd.arg("-c");
105                if !prep.args.is_empty() {
106                    prep.command.push(" \"$@\"")
107                }
108                cmd.arg(prep.command);
109                cmd.arg("--");
110                cmd
111            } else {
112                Command::new(prep.command)
113            };
114            cmd.stdin(prep.stdin)
115                .stdout(prep.stdout)
116                .stderr(prep.stderr)
117                .envs(prep.env)
118                .args(prep.args);
119            cmd
120        }
121    }
122}
123
124/// Prepare `cmd` for [spawning][std::process::Command::spawn()] by configuring it with various builder methods.
125///
126/// Note that the default IO is configured for typical API usage, that is
127///
128/// - `stdin` is null to prevent blocking unexpectedly on consumption of stdin
129/// - `stdout` is captured for consumption by the caller
130/// - `stderr` is inherited to allow the command to provide context to the user
131pub fn prepare(cmd: impl Into<OsString>) -> Prepare {
132    Prepare {
133        command: cmd.into(),
134        stdin: std::process::Stdio::null(),
135        stdout: std::process::Stdio::piped(),
136        stderr: std::process::Stdio::inherit(),
137        args: Vec::new(),
138        env: Vec::new(),
139        use_shell: false,
140    }
141}