Skip to main content

oxdock_process/
builder.rs

1use std::{
2    ffi::{OsStr, OsString},
3    iter::IntoIterator,
4};
5
6#[cfg(not(miri))]
7use anyhow::Context;
8use anyhow::Result;
9#[cfg(miri)]
10use anyhow::bail;
11#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
12use std::fs::File;
13#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
14use std::path::{Path, PathBuf};
15#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
16use std::process::{Command as ProcessCommand, ExitStatus, Output as StdOutput, Stdio};
17
18use crate::child::ChildHandle;
19
20/// Builder wrapper that centralizes direct usages of `std::process::Command`.
21#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
22pub struct CommandBuilder {
23    inner: ProcessCommand,
24    program: OsString,
25    args: Vec<OsString>,
26    envs: Vec<(OsString, OsString)>,
27    cwd: Option<PathBuf>,
28}
29
30#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
31impl CommandBuilder {
32    pub fn new(program: impl AsRef<OsStr>) -> Self {
33        let prog = program.as_ref().to_os_string();
34        Self {
35            inner: ProcessCommand::new(&prog),
36            program: prog,
37            args: Vec::new(),
38            envs: Vec::new(),
39            cwd: None,
40        }
41    }
42
43    pub fn arg(&mut self, arg: impl AsRef<OsStr>) -> &mut Self {
44        let val = arg.as_ref().to_os_string();
45        self.inner.arg(&val);
46        self.args.push(val);
47        self
48    }
49
50    pub fn args<S, I>(&mut self, args: I) -> &mut Self
51    where
52        S: AsRef<OsStr>,
53        I: IntoIterator<Item = S>,
54    {
55        for arg in args {
56            self.arg(arg);
57        }
58        self
59    }
60
61    pub fn env(&mut self, key: impl AsRef<OsStr>, value: impl AsRef<OsStr>) -> &mut Self {
62        let key = key.as_ref().to_os_string();
63        let value = value.as_ref().to_os_string();
64        self.inner.env(&key, &value);
65        self.envs.retain(|(k, _)| k != &key);
66        self.envs.push((key, value));
67        self
68    }
69
70    pub fn env_remove(&mut self, key: impl AsRef<OsStr>) -> &mut Self {
71        let key = key.as_ref();
72        self.inner.env_remove(key);
73        self.envs.retain(|(k, _)| k != key);
74        self
75    }
76
77    /// Clear the inherited host environment, so staged script env is the
78    /// whole child env. Mirrors `std::process::Command::env_clear` while
79    /// keeping the snapshot consistent for diagnostics.
80    pub fn env_clear(&mut self) -> &mut Self {
81        self.inner.env_clear();
82        self.envs.clear();
83        self
84    }
85
86    pub fn stdin_file(&mut self, file: File) -> &mut Self {
87        self.inner.stdin(Stdio::from(file));
88        self
89    }
90
91    pub fn stdin_piped(&mut self) -> &mut Self {
92        self.inner.stdin(Stdio::piped());
93        self
94    }
95
96    pub fn stdout_piped(&mut self) -> &mut Self {
97        self.inner.stdout(Stdio::piped());
98        self
99    }
100
101    pub fn stderr_piped(&mut self) -> &mut Self {
102        self.inner.stderr(Stdio::piped());
103        self
104    }
105
106    pub fn current_dir(&mut self, dir: impl AsRef<Path>) -> &mut Self {
107        let path = dir.as_ref();
108        self.inner.current_dir(path);
109        self.cwd = Some(path.to_path_buf());
110        self
111    }
112
113    pub fn status(&mut self) -> Result<ExitStatus> {
114        #[cfg(miri)]
115        {
116            let snap = self.snapshot();
117            synthetic_status(&snap)
118        }
119
120        #[cfg(not(miri))]
121        {
122            let desc = format!("{:?}", self.inner);
123            let status = self
124                .inner
125                .status()
126                .with_context(|| format!("failed to run {desc}"))?;
127            Ok(status)
128        }
129    }
130
131    pub fn output(&mut self) -> Result<CommandOutput> {
132        #[cfg(miri)]
133        {
134            let snap = self.snapshot();
135            synthetic_output(&snap)
136        }
137
138        #[cfg(not(miri))]
139        {
140            let desc = format!("{:?}", self.inner);
141            let out = self
142                .inner
143                .output()
144                .with_context(|| format!("failed to run {desc}"))?;
145            Ok(CommandOutput::from(out))
146        }
147    }
148
149    pub fn spawn(&mut self) -> Result<ChildHandle> {
150        #[cfg(miri)]
151        {
152            bail!("spawn is not supported under Miri synthetic process backend")
153        }
154
155        #[cfg(not(miri))]
156        {
157            let desc = format!("{:?}", self.inner);
158            let child = self
159                .inner
160                .spawn()
161                .with_context(|| format!("failed to spawn {desc}"))?;
162            ChildHandle::new(child, None, Vec::new())
163        }
164    }
165
166    /// Spawn with piped stdio halves handed back for frame pumps: stdin and
167    /// stdout are forced to pipes (stderr keeps whatever was configured,
168    /// usually inherited for diagnostics). The remaining child is wrapped
169    /// in a [`ChildHandle`] so kill-on-drop and reaping behave identically
170    /// to [`spawn`](Self::spawn). Sessions own the halves and join their
171    /// pump threads; dropping the halves closes the pipes.
172    #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
173    pub fn spawn_piped(&mut self) -> Result<PipedChild> {
174        #[cfg(miri)]
175        {
176            let _ = self;
177            bail!("spawn is not supported under Miri synthetic process backend")
178        }
179
180        #[cfg(not(miri))]
181        {
182            self.inner.stdin(Stdio::piped());
183            self.inner.stdout(Stdio::piped());
184            let desc = format!("{:?}", self.inner);
185            let mut child = self
186                .inner
187                .spawn()
188                .with_context(|| format!("failed to spawn {desc}"))?;
189            let stdin = child
190                .stdin
191                .take()
192                .with_context(|| format!("spawned process has no piped stdin: {desc}"))?;
193            let stdout = child
194                .stdout
195                .take()
196                .with_context(|| format!("spawned process has no piped stdout: {desc}"))?;
197            let handle = ChildHandle::new(child, None, Vec::new())?;
198            Ok(PipedChild {
199                handle,
200                stdin,
201                stdout,
202                stderr: None,
203            })
204        }
205    }
206
207    /// Like [`spawn_piped`](Self::spawn_piped), but stderr is also piped
208    /// and handed back: binary-safe sessions keep diagnostics off stdout
209    /// and route them to their own pipe. Dropping the half closes it.
210    #[allow(clippy::disallowed_types, clippy::disallowed_methods)]
211    pub fn spawn_piped_with_stderr(&mut self) -> Result<PipedChild> {
212        #[cfg(miri)]
213        {
214            let _ = self;
215            bail!("spawn is not supported under Miri synthetic process backend")
216        }
217
218        #[cfg(not(miri))]
219        {
220            self.inner.stdin(Stdio::piped());
221            self.inner.stdout(Stdio::piped());
222            self.inner.stderr(Stdio::piped());
223            let desc = format!("{:?}", self.inner);
224            let mut child = self
225                .inner
226                .spawn()
227                .with_context(|| format!("failed to spawn {desc}"))?;
228            let stdin = child
229                .stdin
230                .take()
231                .with_context(|| format!("spawned process has no piped stdin: {desc}"))?;
232            let stdout = child
233                .stdout
234                .take()
235                .with_context(|| format!("spawned process has no piped stdout: {desc}"))?;
236            let stderr = child
237                .stderr
238                .take()
239                .with_context(|| format!("spawned process has no piped stderr: {desc}"))?;
240            let handle = ChildHandle::new(child, None, Vec::new())?;
241            Ok(PipedChild {
242                handle,
243                stdin,
244                stdout,
245                stderr: Some(stderr),
246            })
247        }
248    }
249
250    /// Return a lightweight snapshot of the command configuration for testing.
251    pub fn snapshot(&self) -> CommandSnapshot {
252        CommandSnapshot {
253            program: self.program.clone(),
254            args: self.args.clone(),
255            envs: self.envs.clone(),
256            cwd: self.cwd.clone(),
257        }
258    }
259}
260
261#[derive(Clone, Debug, PartialEq, Eq)]
262#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
263pub struct CommandSnapshot {
264    pub program: OsString,
265    pub args: Vec<OsString>,
266    pub envs: Vec<(OsString, OsString)>,
267    pub cwd: Option<PathBuf>,
268}
269
270/// A spawned child with its stdio halves detached for frame pumps.
271/// Dropping `stdin`/`stdout`/`stderr` closes the pipes; `handle` keeps
272/// kill-on-drop and reaping semantics. Only constructed by
273/// [`CommandBuilder::spawn_piped`] (stderr stays inherited there) and
274/// [`CommandBuilder::spawn_piped_with_stderr`].
275#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
276pub struct PipedChild {
277    pub handle: ChildHandle,
278    pub stdin: std::process::ChildStdin,
279    pub stdout: std::process::ChildStdout,
280    pub stderr: Option<std::process::ChildStderr>,
281}
282
283pub struct CommandOutput {
284    pub status: ExitStatus,
285    pub stdout: Vec<u8>,
286    pub stderr: Vec<u8>,
287}
288
289impl CommandOutput {
290    pub fn success(&self) -> bool {
291        self.status.success()
292    }
293}
294
295#[allow(clippy::disallowed_types)]
296impl From<StdOutput> for CommandOutput {
297    fn from(value: StdOutput) -> Self {
298        Self {
299            status: value.status,
300            stdout: value.stdout,
301            stderr: value.stderr,
302        }
303    }
304}
305
306#[cfg(miri)]
307use crate::synthetic::{synthetic_output, synthetic_status};
308
309#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
310#[cfg(test)]
311mod tests {
312    use super::*;
313    use oxdock_fs::GuardedPath;
314
315    #[test]
316    fn command_builder_snapshot_tracks_configuration() {
317        let temp = GuardedPath::tempdir().expect("tempdir");
318        let dir = temp.as_guarded_path().display().to_string();
319
320        let mut builder = CommandBuilder::new("prog");
321        builder.arg("a").args(["b", "c"]);
322        builder.env("K", "V");
323        builder.env("K", "V2"); // re-set replaces the earlier entry
324        builder.env("GONE", "x");
325        builder.env_remove("GONE");
326        builder.current_dir(&dir);
327
328        let snap = builder.snapshot();
329        assert_eq!(snap.program, OsString::from("prog"));
330        assert_eq!(
331            snap.args,
332            vec![
333                OsString::from("a"),
334                OsString::from("b"),
335                OsString::from("c")
336            ]
337        );
338        assert!(
339            snap.envs
340                .contains(&(OsString::from("K"), OsString::from("V2")))
341        );
342        assert!(
343            !snap.envs.iter().any(|(k, _)| k == "GONE"),
344            "env_remove must drop tracked entries"
345        );
346        assert_eq!(snap.cwd.as_deref(), Some(std::path::Path::new(&dir)));
347    }
348}