Skip to main content

ados_term/
exec.rs

1//! The single shell-out primitive.
2//!
3//! Every external command a step-graph tool runs goes through [`run`] (or one
4//! of its variants) so command execution is logged + classified in one place.
5//! A sequential orchestrator gains nothing from async here, so this is
6//! deliberately synchronous `std::process`, which keeps step bodies plain.
7//!
8//! Hang protection: commands that can block indefinitely on the network (curl)
9//! pass their own bounding flags (`--max-time`, `--connect-timeout`).
10//!
11//! Long steps (package installs, clones, builds) also have a streaming
12//! variant, [`run_streamed`], which pipes the child's stdout+stderr and hands
13//! each line to a callback as it arrives so a live UI can show real activity
14//! instead of a bare spinner. The plain [`run`] stays for the many short
15//! commands where all-at-once capture is simpler. [`run_cmd`] and
16//! [`run_streamed_cmd`] take a pre-built [`Command`] for callers that set a
17//! working directory or environment.
18
19use std::collections::VecDeque;
20use std::io::Read;
21use std::process::{Command, Stdio};
22use std::sync::mpsc;
23
24/// Outcome of one external command. `code` is `None` when the process could not
25/// be spawned at all (binary missing on PATH); `spawned` distinguishes that
26/// from a non-zero exit.
27#[derive(Debug, Clone)]
28pub struct CmdResult {
29    /// Process exit code, or `None` if the spawn itself failed.
30    pub code: Option<i32>,
31    /// Captured stdout (lossy UTF-8).
32    pub stdout: String,
33    /// Captured stderr (lossy UTF-8).
34    pub stderr: String,
35    /// True once the process was spawned (regardless of its exit code).
36    pub spawned: bool,
37}
38
39impl CmdResult {
40    /// True iff the process spawned and exited 0.
41    pub fn success(&self) -> bool {
42        self.code == Some(0)
43    }
44}
45
46/// Run `program args...`, capturing stdout/stderr. Never panics: a spawn
47/// failure (missing binary) yields a `CmdResult { code: None, spawned: false }`
48/// rather than an error, so callers decide whether a missing tool is fatal.
49pub fn run(program: &str, args: &[&str]) -> CmdResult {
50    tracing::debug!(program, ?args, "exec");
51    match Command::new(program).args(args).output() {
52        Ok(out) => {
53            let res = CmdResult {
54                code: out.status.code(),
55                stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
56                stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
57                spawned: true,
58            };
59            tracing::debug!(program, code = ?res.code, "exec done");
60            res
61        }
62        Err(e) => {
63            tracing::warn!(program, error = %e, "exec spawn failed");
64            CmdResult {
65                code: None,
66                stdout: String::new(),
67                stderr: e.to_string(),
68                spawned: false,
69            }
70        }
71    }
72}
73
74/// Like [`run`] but takes a pre-built [`Command`] (so the caller can set the
75/// working directory + environment) and captures the FULL stdout/stderr with no
76/// line cap: use when the output is parsed and may be long (e.g. a PEM key),
77/// unlike the streaming runners which keep only a bounded tail.
78pub fn run_cmd(mut cmd: Command) -> CmdResult {
79    let program = cmd.get_program().to_string_lossy().into_owned();
80    tracing::debug!(program, args = ?cmd.get_args().collect::<Vec<_>>(), "exec");
81    match cmd.output() {
82        Ok(out) => CmdResult {
83            code: out.status.code(),
84            stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
85            stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
86            spawned: true,
87        },
88        Err(e) => {
89            tracing::warn!(program, error = %e, "exec spawn failed");
90            CmdResult {
91                code: None,
92                stdout: String::new(),
93                stderr: e.to_string(),
94                spawned: false,
95            }
96        }
97    }
98}
99
100/// Run `program args...` with `input` written to its stdin, capturing
101/// stdout/stderr like [`run`]. For secrets a command can read from stdin (a
102/// Wi-Fi passphrase), so they never appear in the process argv (readable by
103/// every local user through `/proc/<pid>/cmdline`) or in this module's logs:
104/// `input` is never logged.
105pub fn run_with_stdin(program: &str, args: &[&str], input: &[u8]) -> CmdResult {
106    use std::io::Write;
107
108    tracing::debug!(program, ?args, "exec (stdin input withheld)");
109    let spawned = Command::new(program)
110        .args(args)
111        .stdin(Stdio::piped())
112        .stdout(Stdio::piped())
113        .stderr(Stdio::piped())
114        .spawn();
115    let mut child = match spawned {
116        Ok(c) => c,
117        Err(e) => {
118            tracing::warn!(program, error = %e, "exec spawn failed");
119            return CmdResult {
120                code: None,
121                stdout: String::new(),
122                stderr: e.to_string(),
123                spawned: false,
124            };
125        }
126    };
127    if let Some(mut stdin) = child.stdin.take() {
128        // A child that exits before reading closes the pipe; its exit status
129        // reports the real outcome, so a write error here is not one.
130        let _ = stdin.write_all(input);
131    }
132    match child.wait_with_output() {
133        Ok(out) => {
134            let res = CmdResult {
135                code: out.status.code(),
136                stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
137                stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
138                spawned: true,
139            };
140            tracing::debug!(program, code = ?res.code, "exec done");
141            res
142        }
143        Err(e) => CmdResult {
144            code: None,
145            stdout: String::new(),
146            stderr: e.to_string(),
147            spawned: true,
148        },
149    }
150}
151
152/// Convenience: run and report only whether it exited 0. Use for best-effort
153/// commands where the output is not needed.
154pub fn run_ok(program: &str, args: &[&str]) -> bool {
155    run(program, args).success()
156}
157
158/// Run a command that MUST succeed; returns the captured result or an error
159/// carrying the trimmed stderr. Use inside Required steps.
160pub fn run_checked(program: &str, args: &[&str]) -> anyhow::Result<CmdResult> {
161    let res = run(program, args);
162    if res.success() {
163        Ok(res)
164    } else if !res.spawned {
165        anyhow::bail!("`{program}` could not be spawned: {}", res.stderr.trim());
166    } else {
167        anyhow::bail!("`{program}` exited {:?}: {}", res.code, res.stderr.trim());
168    }
169}
170
171/// Which stream a captured line came from (kept separate so an error message
172/// carries the stderr tail, matching [`run`]'s split).
173#[derive(Debug, Clone, Copy)]
174enum StreamKind {
175    Out,
176    Err,
177}
178
179/// How many trailing lines of each stream we retain for the returned
180/// `CmdResult` (enough for a failure message; the full record is in the
181/// journal). Long builds emit thousands of lines — we never buffer them all.
182const STREAM_TAIL_CAP: usize = 120;
183/// Hard cap on a single captured line (a `\r`-only progress line, or a runaway
184/// log line, must not blow up the channel or the frame).
185const MAX_LINE_CHARS: usize = 500;
186
187/// Read `reader` to EOF, splitting on BOTH `\n` and `\r` (git/curl/make emit
188/// carriage-return progress with no newline), and forward each non-empty line
189/// on `tx`. Runs on its own thread so stdout + stderr are drained concurrently
190/// (a child that fills one pipe while we block on the other would deadlock).
191fn pump<R: Read>(mut reader: R, kind: StreamKind, tx: mpsc::Sender<(StreamKind, String)>) {
192    let mut buf = [0u8; 4096];
193    let mut line: Vec<u8> = Vec::with_capacity(256);
194    let emit = |line: &mut Vec<u8>| -> bool {
195        if line.is_empty() {
196            return true;
197        }
198        let s: String = String::from_utf8_lossy(line)
199            .chars()
200            .take(MAX_LINE_CHARS)
201            .collect();
202        line.clear();
203        tx.send((kind, s)).is_ok()
204    };
205    loop {
206        match reader.read(&mut buf) {
207            Ok(0) => break,
208            Ok(n) => {
209                for &b in &buf[..n] {
210                    if b == b'\n' || b == b'\r' {
211                        if !emit(&mut line) {
212                            return;
213                        }
214                    } else {
215                        line.push(b);
216                    }
217                }
218            }
219            Err(_) => break,
220        }
221    }
222    let _ = emit(&mut line);
223}
224
225/// Run `program args...`, streaming each stdout/stderr line to `on_line` as it
226/// arrives. Returns the same [`CmdResult`] shape as [`run`], but `stdout` /
227/// `stderr` carry only the trailing 120 lines of each stream (so an
228/// `anyhow::bail!(…, res.stderr.trim())` caller still reports the real error).
229/// `on_line` runs on the calling thread, so it can borrow non-`Send` state
230/// (the progress sink) freely.
231pub fn run_streamed<F: FnMut(&str)>(program: &str, args: &[&str], on_line: F) -> CmdResult {
232    let mut cmd = Command::new(program);
233    cmd.args(args);
234    run_streamed_cmd(cmd, on_line)
235}
236
237/// Like [`run_streamed`] but takes a pre-built [`Command`], so the caller can
238/// set the working directory + environment. Streams stdout/stderr lines to
239/// `on_line` on the calling thread.
240pub fn run_streamed_cmd<F: FnMut(&str)>(mut cmd: Command, mut on_line: F) -> CmdResult {
241    let program = cmd.get_program().to_string_lossy().into_owned();
242    tracing::debug!(program, args = ?cmd.get_args().collect::<Vec<_>>(), "exec-streamed");
243    let mut child = match cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
244        Ok(c) => c,
245        Err(e) => {
246            tracing::warn!(program, error = %e, "exec spawn failed");
247            return CmdResult {
248                code: None,
249                stdout: String::new(),
250                stderr: e.to_string(),
251                spawned: false,
252            };
253        }
254    };
255
256    // `take` the pipes so the reader threads own them; both are `Send`.
257    let stdout = child.stdout.take().expect("piped stdout present");
258    let stderr = child.stderr.take().expect("piped stderr present");
259    let (tx, rx) = mpsc::channel::<(StreamKind, String)>();
260    let tx_err = tx.clone();
261    let h_out = std::thread::spawn(move || pump(stdout, StreamKind::Out, tx));
262    let h_err = std::thread::spawn(move || pump(stderr, StreamKind::Err, tx_err));
263
264    // Both senders are owned by the threads; when they finish the channel
265    // closes and this drain loop ends. All UI emission happens right here on
266    // the caller thread.
267    let mut out_tail: VecDeque<String> = VecDeque::with_capacity(STREAM_TAIL_CAP);
268    let mut err_tail: VecDeque<String> = VecDeque::with_capacity(STREAM_TAIL_CAP);
269    for (kind, line) in rx {
270        on_line(&line);
271        let tail = match kind {
272            StreamKind::Out => &mut out_tail,
273            StreamKind::Err => &mut err_tail,
274        };
275        if tail.len() == STREAM_TAIL_CAP {
276            tail.pop_front();
277        }
278        tail.push_back(line);
279    }
280    let _ = h_out.join();
281    let _ = h_err.join();
282
283    let code = child.wait().ok().and_then(|s| s.code());
284    tracing::debug!(program, code = ?code, "exec-streamed done");
285    CmdResult {
286        code,
287        stdout: Vec::from(out_tail).join("\n"),
288        stderr: Vec::from(err_tail).join("\n"),
289        spawned: true,
290    }
291}
292
293#[cfg(test)]
294mod tests {
295    use super::*;
296
297    #[test]
298    fn run_captures_stdout_of_true_echo() {
299        // `echo` is on PATH on every CI runner + dev host.
300        let r = run("echo", &["hello"]);
301        assert!(r.success());
302        assert_eq!(r.stdout.trim(), "hello");
303    }
304
305    #[test]
306    fn run_reports_spawn_failure_without_panicking() {
307        let r = run("definitely-not-a-real-binary-xyz", &["--nope"]);
308        assert!(!r.spawned);
309        assert_eq!(r.code, None);
310        assert!(!r.success());
311    }
312
313    #[test]
314    fn run_checked_errors_on_nonzero() {
315        // `false` exits 1.
316        let err = run_checked("false", &[]).unwrap_err();
317        assert!(err.to_string().contains("exited"));
318    }
319
320    #[test]
321    fn run_streamed_delivers_each_line_and_keeps_the_tail() {
322        let mut lines = Vec::new();
323        let r = run_streamed("sh", &["-c", "printf 'a\\nb\\nc\\n'"], |l| {
324            lines.push(l.to_string())
325        });
326        assert!(r.success());
327        assert_eq!(lines, vec!["a", "b", "c"]);
328        assert_eq!(r.stdout, "a\nb\nc");
329    }
330
331    #[test]
332    fn run_streamed_splits_carriage_returns() {
333        // Progress output uses bare `\r` with no newline; each segment is a line.
334        let mut lines = Vec::new();
335        let r = run_streamed("sh", &["-c", "printf 'x\\ry\\rz'"], |l| {
336            lines.push(l.to_string())
337        });
338        assert!(r.success());
339        assert_eq!(lines, vec!["x", "y", "z"]);
340    }
341
342    #[test]
343    fn run_streamed_captures_stderr_tail_for_errors() {
344        let mut count = 0usize;
345        let r = run_streamed("sh", &["-c", "echo boom 1>&2; exit 3"], |_| count += 1);
346        assert!(!r.success());
347        assert_eq!(r.code, Some(3));
348        assert!(r.stderr.contains("boom"));
349        assert_eq!(count, 1);
350    }
351
352    #[test]
353    fn run_streamed_reports_spawn_failure() {
354        let r = run_streamed("definitely-not-a-real-binary-xyz", &[], |_| {});
355        assert!(!r.spawned);
356        assert_eq!(r.code, None);
357    }
358
359    #[test]
360    fn command_runners_honor_the_working_directory() {
361        let dir = std::env::temp_dir();
362        let want = dir.canonicalize().unwrap();
363        let mut cmd = Command::new("sh");
364        cmd.args(["-c", "pwd -P"]).current_dir(&dir);
365        let r = run_cmd(cmd);
366        assert!(r.success());
367        assert_eq!(std::path::Path::new(r.stdout.trim()), want);
368
369        let mut cmd = Command::new("sh");
370        cmd.args(["-c", "pwd -P"]).current_dir(&dir);
371        let mut lines = Vec::new();
372        let r = run_streamed_cmd(cmd, |l| lines.push(l.to_string()));
373        assert!(r.success());
374        assert_eq!(lines.len(), 1);
375        assert_eq!(std::path::Path::new(&lines[0]), want);
376    }
377}