Skip to main content

oxdock_process/
builder.rs

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