wasm_pack/
child.rs

1//! Utilities for managing child processes.
2//!
3//! This module helps us ensure that all child processes that we spawn get
4//! properly logged and their output is logged as well.
5
6use crate::install::Tool;
7use anyhow::{bail, Result};
8use log::info;
9use std::process::{Command, Stdio};
10
11/// Return a new Command object
12pub fn new_command(program: &str) -> Command {
13    // On Windows, initializes launching <program> as `cmd /c <program>`.
14    // Initializing only with `Command::new("npm")` will launch
15    //   `npm` with quotes, `"npm"`, causing a run-time error on Windows.
16    // See rustc: #42436, #42791, #44542
17
18    if cfg!(windows) {
19        let mut cmd = Command::new("cmd");
20        cmd.arg("/c").arg(program);
21        cmd
22    } else {
23        Command::new(program)
24    }
25}
26
27/// Run the given command and return on success.
28pub fn run(mut command: Command, command_name: &str) -> Result<()> {
29    info!("Running {:?}", command);
30
31    let status = command.status()?;
32
33    if status.success() {
34        Ok(())
35    } else {
36        bail!(
37            "failed to execute `{}`: exited with {}\n  full command: {:?}",
38            command_name,
39            status,
40            command,
41        )
42    }
43}
44
45/// Run the given command and return its stdout.
46pub fn run_capture_stdout(mut command: Command, command_name: &Tool) -> Result<String> {
47    info!("Running {:?}", command);
48
49    let output = command
50        .stderr(Stdio::inherit())
51        .stdin(Stdio::inherit())
52        .output()?;
53
54    if output.status.success() {
55        Ok(String::from_utf8_lossy(&output.stdout).into_owned())
56    } else {
57        bail!(
58            "failed to execute `{}`: exited with {}\n  full command: {:?}",
59            command_name,
60            output.status,
61            command,
62        )
63    }
64}