Skip to main content

cargo/util/
process_builder.rs

1use std::collections::HashMap;
2use std::env;
3use std::ffi::{OsStr, OsString};
4use std::fmt;
5use std::path::Path;
6use std::process::{Command, Output, Stdio};
7
8use failure::Fail;
9use jobserver::Client;
10use shell_escape::escape;
11
12use crate::util::{process_error, read2, CargoResult, CargoResultExt};
13
14/// A builder object for an external process, similar to `std::process::Command`.
15#[derive(Clone, Debug)]
16pub struct ProcessBuilder {
17    /// The program to execute.
18    program: OsString,
19    /// A list of arguments to pass to the program.
20    args: Vec<OsString>,
21    /// Any environment variables that should be set for the program.
22    env: HashMap<String, Option<OsString>>,
23    /// Which directory to run the program from.
24    cwd: Option<OsString>,
25    /// The `make` jobserver. See the [jobserver crate][jobserver_docs] for
26    /// more information.
27    ///
28    /// [jobserver_docs]: https://docs.rs/jobserver/0.1.6/jobserver/
29    jobserver: Option<Client>,
30}
31
32impl fmt::Display for ProcessBuilder {
33    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
34        write!(f, "`{}", self.program.to_string_lossy())?;
35
36        for arg in &self.args {
37            write!(f, " {}", escape(arg.to_string_lossy()))?;
38        }
39
40        write!(f, "`")
41    }
42}
43
44impl ProcessBuilder {
45    /// (chainable) Set the executable for the process.
46    pub fn program<T: AsRef<OsStr>>(&mut self, program: T) -> &mut ProcessBuilder {
47        self.program = program.as_ref().to_os_string();
48        self
49    }
50
51    /// (chainable) Add an arg to the args list.
52    pub fn arg<T: AsRef<OsStr>>(&mut self, arg: T) -> &mut ProcessBuilder {
53        self.args.push(arg.as_ref().to_os_string());
54        self
55    }
56
57    /// (chainable) Add many args to the args list.
58    pub fn args<T: AsRef<OsStr>>(&mut self, arguments: &[T]) -> &mut ProcessBuilder {
59        self.args
60            .extend(arguments.iter().map(|t| t.as_ref().to_os_string()));
61        self
62    }
63
64    /// (chainable) Replace args with new args list
65    pub fn args_replace<T: AsRef<OsStr>>(&mut self, arguments: &[T]) -> &mut ProcessBuilder {
66        self.args = arguments
67            .iter()
68            .map(|t| t.as_ref().to_os_string())
69            .collect();
70        self
71    }
72
73    /// (chainable) Set the current working directory of the process
74    pub fn cwd<T: AsRef<OsStr>>(&mut self, path: T) -> &mut ProcessBuilder {
75        self.cwd = Some(path.as_ref().to_os_string());
76        self
77    }
78
79    /// (chainable) Set an environment variable for the process.
80    pub fn env<T: AsRef<OsStr>>(&mut self, key: &str, val: T) -> &mut ProcessBuilder {
81        self.env
82            .insert(key.to_string(), Some(val.as_ref().to_os_string()));
83        self
84    }
85
86    /// (chainable) Unset an environment variable for the process.
87    pub fn env_remove(&mut self, key: &str) -> &mut ProcessBuilder {
88        self.env.insert(key.to_string(), None);
89        self
90    }
91
92    /// Get the executable name.
93    pub fn get_program(&self) -> &OsString {
94        &self.program
95    }
96
97    /// Get the program arguments
98    pub fn get_args(&self) -> &[OsString] {
99        &self.args
100    }
101
102    /// Get the current working directory for the process
103    pub fn get_cwd(&self) -> Option<&Path> {
104        self.cwd.as_ref().map(Path::new)
105    }
106
107    /// Get an environment variable as the process will see it (will inherit from environment
108    /// unless explicitally unset).
109    pub fn get_env(&self, var: &str) -> Option<OsString> {
110        self.env
111            .get(var)
112            .cloned()
113            .or_else(|| Some(env::var_os(var)))
114            .and_then(|s| s)
115    }
116
117    /// Get all environment variables explicitly set or unset for the process (not inherited
118    /// vars).
119    pub fn get_envs(&self) -> &HashMap<String, Option<OsString>> {
120        &self.env
121    }
122
123    /// Set the `make` jobserver. See the [jobserver crate][jobserver_docs] for
124    /// more information.
125    ///
126    /// [jobserver_docs]: https://docs.rs/jobserver/0.1.6/jobserver/
127    pub fn inherit_jobserver(&mut self, jobserver: &Client) -> &mut Self {
128        self.jobserver = Some(jobserver.clone());
129        self
130    }
131
132    /// Run the process, waiting for completion, and mapping non-success exit codes to an error.
133    pub fn exec(&self) -> CargoResult<()> {
134        let mut command = self.build_command();
135        let exit = command.status().chain_err(|| {
136            process_error(&format!("could not execute process {}", self), None, None)
137        })?;
138
139        if exit.success() {
140            Ok(())
141        } else {
142            Err(process_error(
143                &format!("process didn't exit successfully: {}", self),
144                Some(exit),
145                None,
146            )
147            .into())
148        }
149    }
150
151    /// Replaces the current process with the target process.
152    ///
153    /// On Unix, this executes the process using the unix syscall `execvp`, which will block
154    /// this process, and will only return if there is an error.
155    ///
156    /// On Windows this isn't technically possible. Instead we emulate it to the best of our
157    /// ability. One aspect we fix here is that we specify a handler for the ctrl-c handler.
158    /// In doing so (and by effectively ignoring it) we should emulate proxying ctrl-c
159    /// handling to the application at hand, which will either terminate or handle it itself.
160    /// According to microsoft's documentation at:
161    /// https://docs.microsoft.com/en-us/windows/console/ctrl-c-and-ctrl-break-signals
162    /// the ctrl-c signal is sent to all processes attached to a terminal, which should
163    /// include our child process. If the child terminates then we'll reap them in Cargo
164    /// pretty quickly, and if the child handles the signal then we won't terminate
165    /// (and we shouldn't!) until the process itself later exits.
166    pub fn exec_replace(&self) -> CargoResult<()> {
167        imp::exec_replace(self)
168    }
169
170    /// Execute the process, returning the stdio output, or an error if non-zero exit status.
171    pub fn exec_with_output(&self) -> CargoResult<Output> {
172        let mut command = self.build_command();
173
174        let output = command.output().chain_err(|| {
175            process_error(&format!("could not execute process {}", self), None, None)
176        })?;
177
178        if output.status.success() {
179            Ok(output)
180        } else {
181            Err(process_error(
182                &format!("process didn't exit successfully: {}", self),
183                Some(output.status),
184                Some(&output),
185            )
186            .into())
187        }
188    }
189
190    /// Execute a command, passing each line of stdout and stderr to the supplied callbacks, which
191    /// can mutate the string data.
192    ///
193    /// If any invocations of these function return an error, it will be propagated.
194    ///
195    /// Optionally, output can be passed to errors using `print_output`
196    pub fn exec_with_streaming(
197        &self,
198        on_stdout_line: &mut dyn FnMut(&str) -> CargoResult<()>,
199        on_stderr_line: &mut dyn FnMut(&str) -> CargoResult<()>,
200        capture_output: bool,
201    ) -> CargoResult<Output> {
202        let mut stdout = Vec::new();
203        let mut stderr = Vec::new();
204
205        let mut cmd = self.build_command();
206        cmd.stdout(Stdio::piped())
207            .stderr(Stdio::piped())
208            .stdin(Stdio::null());
209
210        let mut callback_error = None;
211        let status = (|| {
212            let mut child = cmd.spawn()?;
213            let out = child.stdout.take().unwrap();
214            let err = child.stderr.take().unwrap();
215            read2(out, err, &mut |is_out, data, eof| {
216                let idx = if eof {
217                    data.len()
218                } else {
219                    match data.iter().rposition(|b| *b == b'\n') {
220                        Some(i) => i + 1,
221                        None => return,
222                    }
223                };
224                {
225                    // scope for new_lines
226                    let new_lines = if capture_output {
227                        let dst = if is_out { &mut stdout } else { &mut stderr };
228                        let start = dst.len();
229                        let data = data.drain(..idx);
230                        dst.extend(data);
231                        &dst[start..]
232                    } else {
233                        &data[..idx]
234                    };
235                    for line in String::from_utf8_lossy(new_lines).lines() {
236                        if callback_error.is_some() {
237                            break;
238                        }
239                        let callback_result = if is_out {
240                            on_stdout_line(line)
241                        } else {
242                            on_stderr_line(line)
243                        };
244                        if let Err(e) = callback_result {
245                            callback_error = Some(e);
246                        }
247                    }
248                }
249                if !capture_output {
250                    data.drain(..idx);
251                }
252            })?;
253            child.wait()
254        })()
255        .chain_err(|| process_error(&format!("could not execute process {}", self), None, None))?;
256        let output = Output {
257            stdout,
258            stderr,
259            status,
260        };
261
262        {
263            let to_print = if capture_output { Some(&output) } else { None };
264            if let Some(e) = callback_error {
265                let cx = process_error(
266                    &format!("failed to parse process output: {}", self),
267                    Some(output.status),
268                    to_print,
269                );
270                return Err(cx.context(e).into());
271            } else if !output.status.success() {
272                return Err(process_error(
273                    &format!("process didn't exit successfully: {}", self),
274                    Some(output.status),
275                    to_print,
276                )
277                .into());
278            }
279        }
280
281        Ok(output)
282    }
283
284    /// Converts ProcessBuilder into a `std::process::Command`, and handles the jobserver if
285    /// present.
286    pub fn build_command(&self) -> Command {
287        let mut command = Command::new(&self.program);
288        if let Some(cwd) = self.get_cwd() {
289            command.current_dir(cwd);
290        }
291        for arg in &self.args {
292            command.arg(arg);
293        }
294        for (k, v) in &self.env {
295            match *v {
296                Some(ref v) => {
297                    command.env(k, v);
298                }
299                None => {
300                    command.env_remove(k);
301                }
302            }
303        }
304        if let Some(ref c) = self.jobserver {
305            c.configure(&mut command);
306        }
307        command
308    }
309}
310
311/// A helper function to create a `ProcessBuilder`.
312pub fn process<T: AsRef<OsStr>>(cmd: T) -> ProcessBuilder {
313    ProcessBuilder {
314        program: cmd.as_ref().to_os_string(),
315        args: Vec::new(),
316        cwd: None,
317        env: HashMap::new(),
318        jobserver: None,
319    }
320}
321
322#[cfg(unix)]
323mod imp {
324    use crate::util::{process_error, ProcessBuilder};
325    use crate::CargoResult;
326    use std::os::unix::process::CommandExt;
327
328    pub fn exec_replace(process_builder: &ProcessBuilder) -> CargoResult<()> {
329        let mut command = process_builder.build_command();
330        let error = command.exec();
331        Err(failure::Error::from(error)
332            .context(process_error(
333                &format!("could not execute process {}", process_builder),
334                None,
335                None,
336            ))
337            .into())
338    }
339}
340
341#[cfg(windows)]
342mod imp {
343    use crate::util::{process_error, ProcessBuilder};
344    use crate::CargoResult;
345    use winapi::shared::minwindef::{BOOL, DWORD, FALSE, TRUE};
346    use winapi::um::consoleapi::SetConsoleCtrlHandler;
347
348    unsafe extern "system" fn ctrlc_handler(_: DWORD) -> BOOL {
349        // Do nothing. Let the child process handle it.
350        TRUE
351    }
352
353    pub fn exec_replace(process_builder: &ProcessBuilder) -> CargoResult<()> {
354        unsafe {
355            if SetConsoleCtrlHandler(Some(ctrlc_handler), TRUE) == FALSE {
356                return Err(process_error("Could not set Ctrl-C handler.", None, None).into());
357            }
358        }
359
360        // Just exec the process as normal.
361        process_builder.exec()
362    }
363}