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    pub fn stdin_file(&mut self, file: File) -> &mut Self {
78        self.inner.stdin(Stdio::from(file));
79        self
80    }
81
82    pub fn stdin_piped(&mut self) -> &mut Self {
83        self.inner.stdin(Stdio::piped());
84        self
85    }
86
87    pub fn stdout_piped(&mut self) -> &mut Self {
88        self.inner.stdout(Stdio::piped());
89        self
90    }
91
92    pub fn stderr_piped(&mut self) -> &mut Self {
93        self.inner.stderr(Stdio::piped());
94        self
95    }
96
97    pub fn current_dir(&mut self, dir: impl AsRef<Path>) -> &mut Self {
98        let path = dir.as_ref();
99        self.inner.current_dir(path);
100        self.cwd = Some(path.to_path_buf());
101        self
102    }
103
104    pub fn status(&mut self) -> Result<ExitStatus> {
105        #[cfg(miri)]
106        {
107            let snap = self.snapshot();
108            synthetic_status(&snap)
109        }
110
111        #[cfg(not(miri))]
112        {
113            let desc = format!("{:?}", self.inner);
114            let status = self
115                .inner
116                .status()
117                .with_context(|| format!("failed to run {desc}"))?;
118            Ok(status)
119        }
120    }
121
122    pub fn output(&mut self) -> Result<CommandOutput> {
123        #[cfg(miri)]
124        {
125            let snap = self.snapshot();
126            synthetic_output(&snap)
127        }
128
129        #[cfg(not(miri))]
130        {
131            let desc = format!("{:?}", self.inner);
132            let out = self
133                .inner
134                .output()
135                .with_context(|| format!("failed to run {desc}"))?;
136            Ok(CommandOutput::from(out))
137        }
138    }
139
140    pub fn spawn(&mut self) -> Result<ChildHandle> {
141        #[cfg(miri)]
142        {
143            bail!("spawn is not supported under Miri synthetic process backend")
144        }
145
146        #[cfg(not(miri))]
147        {
148            let desc = format!("{:?}", self.inner);
149            let child = self
150                .inner
151                .spawn()
152                .with_context(|| format!("failed to spawn {desc}"))?;
153            Ok(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) -> Result<PipedChild> {
165        #[cfg(miri)]
166        {
167            let _ = self;
168            bail!("spawn is not supported under Miri synthetic process backend")
169        }
170
171        #[cfg(not(miri))]
172        {
173            self.inner.stdin(Stdio::piped());
174            self.inner.stdout(Stdio::piped());
175            let desc = format!("{:?}", self.inner);
176            let mut child = self
177                .inner
178                .spawn()
179                .with_context(|| format!("failed to spawn {desc}"))?;
180            let stdin = child
181                .stdin
182                .take()
183                .with_context(|| format!("spawned process has no piped stdin: {desc}"))?;
184            let stdout = child
185                .stdout
186                .take()
187                .with_context(|| format!("spawned process has no piped stdout: {desc}"))?;
188            Ok(PipedChild {
189                handle: ChildHandle::new(child, None, Vec::new()),
190                stdin,
191                stdout,
192            })
193        }
194    }
195
196    /// Return a lightweight snapshot of the command configuration for testing.
197    pub fn snapshot(&self) -> CommandSnapshot {
198        CommandSnapshot {
199            program: self.program.clone(),
200            args: self.args.clone(),
201            envs: self.envs.clone(),
202            cwd: self.cwd.clone(),
203        }
204    }
205}
206
207#[derive(Clone, Debug, PartialEq, Eq)]
208#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
209pub struct CommandSnapshot {
210    pub program: OsString,
211    pub args: Vec<OsString>,
212    pub envs: Vec<(OsString, OsString)>,
213    pub cwd: Option<PathBuf>,
214}
215
216/// A spawned child with its stdio halves detached for frame pumps.
217/// Dropping `stdin`/`stdout` closes the pipes; `handle` keeps kill-on-drop
218/// and reaping semantics. Only constructed by
219/// [`CommandBuilder::spawn_piped`].
220#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
221pub struct PipedChild {
222    pub handle: ChildHandle,
223    pub stdin: std::process::ChildStdin,
224    pub stdout: std::process::ChildStdout,
225}
226
227pub struct CommandOutput {
228    pub status: ExitStatus,
229    pub stdout: Vec<u8>,
230    pub stderr: Vec<u8>,
231}
232
233impl CommandOutput {
234    pub fn success(&self) -> bool {
235        self.status.success()
236    }
237}
238
239#[allow(clippy::disallowed_types)]
240impl From<StdOutput> for CommandOutput {
241    fn from(value: StdOutput) -> Self {
242        Self {
243            status: value.status,
244            stdout: value.stdout,
245            stderr: value.stderr,
246        }
247    }
248}
249
250#[cfg(miri)]
251use crate::synthetic::{synthetic_output, synthetic_status};
252
253#[allow(clippy::disallowed_types, clippy::disallowed_methods)]
254#[cfg(test)]
255mod tests {
256    use super::*;
257    use oxdock_fs::GuardedPath;
258
259    #[test]
260    fn command_builder_snapshot_tracks_configuration() {
261        let temp = GuardedPath::tempdir().expect("tempdir");
262        let dir = temp.as_guarded_path().display().to_string();
263
264        let mut builder = CommandBuilder::new("prog");
265        builder.arg("a").args(["b", "c"]);
266        builder.env("K", "V");
267        builder.env("K", "V2"); // re-set replaces the earlier entry
268        builder.env("GONE", "x");
269        builder.env_remove("GONE");
270        builder.current_dir(&dir);
271
272        let snap = builder.snapshot();
273        assert_eq!(snap.program, OsString::from("prog"));
274        assert_eq!(
275            snap.args,
276            vec![
277                OsString::from("a"),
278                OsString::from("b"),
279                OsString::from("c")
280            ]
281        );
282        assert!(
283            snap.envs
284                .contains(&(OsString::from("K"), OsString::from("V2")))
285        );
286        assert!(
287            !snap.envs.iter().any(|(k, _)| k == "GONE"),
288            "env_remove must drop tracked entries"
289        );
290        assert_eq!(snap.cwd.as_deref(), Some(std::path::Path::new(&dir)));
291    }
292}