Skip to main content

base/interface/exec/in_process/
process.rs

1//! Processes that were decided in advance.
2
3use std::collections::BTreeMap;
4use std::sync::{Arc, Mutex};
5
6use futures::future::BoxFuture;
7use futures::stream::BoxStream;
8use futures::StreamExt;
9use tokio_util::sync::CancellationToken;
10
11use crate::interface::exec::{
12    ExecError, ExitStatus, OutputChunk, OutputStream, Process, ProcessHandle, ProcessSpec,
13};
14
15/// What a scripted command answers with.
16#[derive(Debug, Clone, Default, PartialEq, Eq)]
17pub struct ScriptedRun {
18    pub stdout: String,
19    pub stderr: String,
20    pub code: i32,
21}
22
23impl ScriptedRun {
24    pub fn ok(stdout: impl Into<String>) -> Self {
25        Self {
26            stdout: stdout.into(),
27            stderr: String::new(),
28            code: 0,
29        }
30    }
31
32    pub fn failing(code: i32, stderr: impl Into<String>) -> Self {
33        Self {
34            stdout: String::new(),
35            stderr: stderr.into(),
36            code,
37        }
38    }
39}
40
41/// A process provider whose answers are written down beforehand.
42///
43/// Matched on the whole argv joined by spaces, which is crude and deliberate:
44/// a matcher with globs or regexes is a small language, and a test that needs
45/// one is usually testing the matcher.
46///
47/// A command with no entry fails rather than succeeding quietly — an
48/// unscripted command in a test is a gap in the test, and returning empty
49/// success would hide it.
50#[derive(Clone, Default)]
51pub struct ScriptedProcess {
52    runs: Arc<Mutex<BTreeMap<String, ScriptedRun>>>,
53    seen: Arc<Mutex<Vec<String>>>,
54}
55
56impl ScriptedProcess {
57    pub fn new() -> Self {
58        Self::default()
59    }
60
61    pub fn with(self, argv: impl Into<String>, run: ScriptedRun) -> Self {
62        self.runs
63            .lock()
64            .unwrap_or_else(std::sync::PoisonError::into_inner)
65            .insert(argv.into(), run);
66        self
67    }
68
69    /// Every command that was asked for, in order — including the ones with
70    /// no entry.
71    pub fn seen(&self) -> Vec<String> {
72        self.seen
73            .lock()
74            .unwrap_or_else(std::sync::PoisonError::into_inner)
75            .clone()
76    }
77
78    fn key(spec: &ProcessSpec) -> String {
79        std::iter::once(spec.program.clone())
80            .chain(spec.args.iter().cloned())
81            .collect::<Vec<_>>()
82            .join(" ")
83    }
84}
85
86#[async_trait::async_trait]
87impl Process for ScriptedProcess {
88    async fn spawn(
89        &self,
90        spec: ProcessSpec,
91        _cancel: CancellationToken,
92    ) -> Result<Box<dyn ProcessHandle>, ExecError> {
93        let key = Self::key(&spec);
94        self.seen
95            .lock()
96            .unwrap_or_else(std::sync::PoisonError::into_inner)
97            .push(key.clone());
98        let run = self
99            .runs
100            .lock()
101            .unwrap_or_else(std::sync::PoisonError::into_inner)
102            .get(&key)
103            .cloned();
104        let Some(run) = run else {
105            return Err(ExecError::failed(format!("nothing scripted for `{key}`")));
106        };
107        Ok(Box::new(ScriptedHandle {
108            run: Some(run),
109            taken: false,
110        }))
111    }
112}
113
114struct ScriptedHandle {
115    run: Option<ScriptedRun>,
116    taken: bool,
117}
118
119impl ProcessHandle for ScriptedHandle {
120    fn output(&mut self) -> Option<BoxStream<'static, Result<OutputChunk, ExecError>>> {
121        if self.taken {
122            return None;
123        }
124        self.taken = true;
125        let run = self.run.clone().unwrap_or_default();
126        let mut chunks = Vec::new();
127        if !run.stdout.is_empty() {
128            chunks.push(Ok(OutputChunk {
129                stream: OutputStream::Stdout,
130                bytes: run.stdout.into_bytes(),
131            }));
132        }
133        if !run.stderr.is_empty() {
134            chunks.push(Ok(OutputChunk {
135                stream: OutputStream::Stderr,
136                bytes: run.stderr.into_bytes(),
137            }));
138        }
139        Some(futures::stream::iter(chunks).boxed())
140    }
141
142    fn kill(&mut self) -> BoxFuture<'_, ()> {
143        Box::pin(async {})
144    }
145
146    fn wait(&mut self) -> BoxFuture<'_, Result<ExitStatus, ExecError>> {
147        let code = self.run.as_ref().map(|r| r.code).unwrap_or(0);
148        Box::pin(async move {
149            Ok(ExitStatus {
150                code: Some(code),
151                success: code == 0,
152            })
153        })
154    }
155}