Skip to main content

base/interface/exec/
capture.rs

1//! Running a process through the execution contract and keeping all of it.
2//!
3//! `Process` hands back a stream because a long command's output has to reach
4//! the user while it is still running. Most callers do not want that: they run
5//! `git`, wait, and parse what it printed. Those call sites drain the stream
6//! through here.
7
8use futures::StreamExt;
9use tokio_util::sync::CancellationToken;
10
11use super::{ExecError, ExitStatus, OutputStream, Process, ProcessSpec};
12
13#[derive(Debug)]
14pub struct Captured {
15    pub status: ExitStatus,
16    pub stdout: Vec<u8>,
17    pub stderr: Vec<u8>,
18}
19
20impl Captured {
21    pub fn stdout_lossy(&self) -> std::borrow::Cow<'_, str> {
22        String::from_utf8_lossy(&self.stdout)
23    }
24
25    pub fn stderr_lossy(&self) -> std::borrow::Cow<'_, str> {
26        String::from_utf8_lossy(&self.stderr)
27    }
28}
29
30pub async fn capture(
31    process: &dyn Process,
32    spec: ProcessSpec,
33    cancel: CancellationToken,
34) -> Result<Captured, ExecError> {
35    let mut child = process.spawn(spec, cancel).await?;
36    let mut stdout = Vec::new();
37    let mut stderr = Vec::new();
38    // Drained before waiting: a child that fills its output pipe blocks until
39    // someone reads it, so a `wait` first would deadlock on anything verbose.
40    if let Some(mut chunks) = child.output() {
41        while let Some(chunk) = chunks.next().await {
42            let chunk = chunk?;
43            match chunk.stream {
44                OutputStream::Stdout => stdout.extend_from_slice(&chunk.bytes),
45                OutputStream::Stderr => stderr.extend_from_slice(&chunk.bytes),
46            }
47        }
48    }
49    let status = child.wait().await?;
50    Ok(Captured {
51        status,
52        stdout,
53        stderr,
54    })
55}
56
57#[cfg(test)]
58mod tests {
59    use super::*;
60    use crate::interface::exec::in_process::{ScriptedProcess, ScriptedRun};
61
62    #[tokio::test]
63    async fn both_streams_and_the_status_are_kept_apart() {
64        let process = ScriptedProcess::new().with(
65            "git status",
66            ScriptedRun {
67                stdout: "out".into(),
68                stderr: "err".into(),
69                code: 2,
70            },
71        );
72        let out = capture(
73            &process,
74            ProcessSpec::new("git", "/").arg("status"),
75            CancellationToken::new(),
76        )
77        .await
78        .unwrap();
79        assert_eq!(out.stdout_lossy(), "out");
80        assert_eq!(out.stderr_lossy(), "err");
81        assert_eq!(out.status.code, Some(2));
82        assert!(!out.status.success);
83    }
84
85    #[tokio::test]
86    async fn a_spawn_failure_is_returned_as_is() {
87        let e = capture(
88            &ScriptedProcess::new(),
89            ProcessSpec::new("git", "/"),
90            CancellationToken::new(),
91        )
92        .await
93        .unwrap_err();
94        assert!(matches!(e, ExecError::Failed(_)), "{e:?}");
95    }
96}