aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/mozart-vcs/src/process.rs
blob: 8ccc11dbeaf6724ca1e9bb6cf4c2c0b85d19d7bd (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
use indexmap::IndexMap;
use std::path::Path;
use std::process::Command;
use std::time::{Duration, Instant};

use anyhow::{Result, bail};

/// Output from a process execution.
#[derive(Debug, Clone)]
pub struct ProcessOutput {
    pub status: i32,
    pub stdout: String,
    pub stderr: String,
}

/// Wrapper around `std::process::Command` for executing external programs.
///
/// Corresponds to Composer's `ProcessExecutor`.
pub struct ProcessExecutor {
    timeout: Option<Duration>,
    env_overrides: IndexMap<String, Option<String>>,
}

impl Default for ProcessExecutor {
    fn default() -> Self {
        Self::new()
    }
}

impl ProcessExecutor {
    pub fn new() -> Self {
        Self {
            timeout: None,
            env_overrides: IndexMap::new(),
        }
    }

    pub fn with_timeout(secs: u64) -> Self {
        Self {
            timeout: Some(Duration::from_secs(secs)),
            env_overrides: IndexMap::new(),
        }
    }

    /// Set an environment variable override for all subsequent executions.
    pub fn set_env(&mut self, key: impl Into<String>, value: impl Into<String>) {
        self.env_overrides.insert(key.into(), Some(value.into()));
    }

    /// Remove an environment variable for all subsequent executions.
    pub fn remove_env(&mut self, key: impl Into<String>) {
        self.env_overrides.insert(key.into(), None);
    }

    /// Execute a command. Does not error on non-zero exit status.
    pub fn execute(&self, args: &[&str], cwd: Option<&Path>) -> Result<ProcessOutput> {
        if args.is_empty() {
            bail!("No command specified");
        }

        let mut cmd = Command::new(args[0]);
        if args.len() > 1 {
            cmd.args(&args[1..]);
        }
        if let Some(dir) = cwd {
            cmd.current_dir(dir);
        }

        for (key, value) in &self.env_overrides {
            match value {
                Some(v) => {
                    cmd.env(key, v);
                }
                None => {
                    cmd.env_remove(key);
                }
            }
        }

        if let Some(timeout) = self.timeout {
            let mut child = cmd
                .stdout(std::process::Stdio::piped())
                .stderr(std::process::Stdio::piped())
                .spawn()?;

            let start = Instant::now();
            loop {
                match child.try_wait()? {
                    Some(status) => {
                        let mut stdout = String::new();
                        let mut stderr = String::new();
                        if let Some(ref mut out) = child.stdout {
                            std::io::Read::read_to_string(out, &mut stdout)?;
                        }
                        if let Some(ref mut err) = child.stderr {
                            std::io::Read::read_to_string(err, &mut stderr)?;
                        }
                        return Ok(ProcessOutput {
                            status: status.code().unwrap_or(-1),
                            stdout,
                            stderr,
                        });
                    }
                    None => {
                        if start.elapsed() > timeout {
                            let _ = child.kill();
                            bail!("Process timed out after {} seconds", timeout.as_secs());
                        }
                        std::thread::sleep(Duration::from_millis(50));
                    }
                }
            }
        } else {
            let output = cmd.output()?;
            Ok(ProcessOutput {
                status: output.status.code().unwrap_or(-1),
                stdout: String::from_utf8_lossy(&output.stdout).into_owned(),
                stderr: String::from_utf8_lossy(&output.stderr).into_owned(),
            })
        }
    }

    /// Execute a command, returning an error if the exit status is non-zero.
    pub fn execute_checked(&self, args: &[&str], cwd: Option<&Path>) -> Result<ProcessOutput> {
        let output = self.execute(args, cwd)?;
        if output.status != 0 {
            bail!(
                "Command `{}` failed with exit code {}\nstdout: {}\nstderr: {}",
                args.join(" "),
                output.status,
                output.stdout.trim(),
                output.stderr.trim(),
            );
        }
        Ok(output)
    }

    /// Split output into non-empty lines.
    pub fn split_lines(output: &str) -> Vec<&str> {
        output.lines().filter(|l| !l.is_empty()).collect()
    }
}