1use std::collections::VecDeque;
20use std::io::Read;
21use std::process::{Command, Stdio};
22use std::sync::mpsc;
23
24#[derive(Debug, Clone)]
28pub struct CmdResult {
29 pub code: Option<i32>,
31 pub stdout: String,
33 pub stderr: String,
35 pub spawned: bool,
37}
38
39impl CmdResult {
40 pub fn success(&self) -> bool {
42 self.code == Some(0)
43 }
44}
45
46pub fn run(program: &str, args: &[&str]) -> CmdResult {
50 tracing::debug!(program, ?args, "exec");
51 match Command::new(program).args(args).output() {
52 Ok(out) => {
53 let res = CmdResult {
54 code: out.status.code(),
55 stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
56 stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
57 spawned: true,
58 };
59 tracing::debug!(program, code = ?res.code, "exec done");
60 res
61 }
62 Err(e) => {
63 tracing::warn!(program, error = %e, "exec spawn failed");
64 CmdResult {
65 code: None,
66 stdout: String::new(),
67 stderr: e.to_string(),
68 spawned: false,
69 }
70 }
71 }
72}
73
74pub fn run_cmd(mut cmd: Command) -> CmdResult {
79 let program = cmd.get_program().to_string_lossy().into_owned();
80 tracing::debug!(program, args = ?cmd.get_args().collect::<Vec<_>>(), "exec");
81 match cmd.output() {
82 Ok(out) => CmdResult {
83 code: out.status.code(),
84 stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
85 stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
86 spawned: true,
87 },
88 Err(e) => {
89 tracing::warn!(program, error = %e, "exec spawn failed");
90 CmdResult {
91 code: None,
92 stdout: String::new(),
93 stderr: e.to_string(),
94 spawned: false,
95 }
96 }
97 }
98}
99
100pub fn run_with_stdin(program: &str, args: &[&str], input: &[u8]) -> CmdResult {
106 use std::io::Write;
107
108 tracing::debug!(program, ?args, "exec (stdin input withheld)");
109 let spawned = Command::new(program)
110 .args(args)
111 .stdin(Stdio::piped())
112 .stdout(Stdio::piped())
113 .stderr(Stdio::piped())
114 .spawn();
115 let mut child = match spawned {
116 Ok(c) => c,
117 Err(e) => {
118 tracing::warn!(program, error = %e, "exec spawn failed");
119 return CmdResult {
120 code: None,
121 stdout: String::new(),
122 stderr: e.to_string(),
123 spawned: false,
124 };
125 }
126 };
127 if let Some(mut stdin) = child.stdin.take() {
128 let _ = stdin.write_all(input);
131 }
132 match child.wait_with_output() {
133 Ok(out) => {
134 let res = CmdResult {
135 code: out.status.code(),
136 stdout: String::from_utf8_lossy(&out.stdout).into_owned(),
137 stderr: String::from_utf8_lossy(&out.stderr).into_owned(),
138 spawned: true,
139 };
140 tracing::debug!(program, code = ?res.code, "exec done");
141 res
142 }
143 Err(e) => CmdResult {
144 code: None,
145 stdout: String::new(),
146 stderr: e.to_string(),
147 spawned: true,
148 },
149 }
150}
151
152pub fn run_ok(program: &str, args: &[&str]) -> bool {
155 run(program, args).success()
156}
157
158pub fn run_checked(program: &str, args: &[&str]) -> anyhow::Result<CmdResult> {
161 let res = run(program, args);
162 if res.success() {
163 Ok(res)
164 } else if !res.spawned {
165 anyhow::bail!("`{program}` could not be spawned: {}", res.stderr.trim());
166 } else {
167 anyhow::bail!("`{program}` exited {:?}: {}", res.code, res.stderr.trim());
168 }
169}
170
171#[derive(Debug, Clone, Copy)]
174enum StreamKind {
175 Out,
176 Err,
177}
178
179const STREAM_TAIL_CAP: usize = 120;
183const MAX_LINE_CHARS: usize = 500;
186
187fn pump<R: Read>(mut reader: R, kind: StreamKind, tx: mpsc::Sender<(StreamKind, String)>) {
192 let mut buf = [0u8; 4096];
193 let mut line: Vec<u8> = Vec::with_capacity(256);
194 let emit = |line: &mut Vec<u8>| -> bool {
195 if line.is_empty() {
196 return true;
197 }
198 let s: String = String::from_utf8_lossy(line)
199 .chars()
200 .take(MAX_LINE_CHARS)
201 .collect();
202 line.clear();
203 tx.send((kind, s)).is_ok()
204 };
205 loop {
206 match reader.read(&mut buf) {
207 Ok(0) => break,
208 Ok(n) => {
209 for &b in &buf[..n] {
210 if b == b'\n' || b == b'\r' {
211 if !emit(&mut line) {
212 return;
213 }
214 } else {
215 line.push(b);
216 }
217 }
218 }
219 Err(_) => break,
220 }
221 }
222 let _ = emit(&mut line);
223}
224
225pub fn run_streamed<F: FnMut(&str)>(program: &str, args: &[&str], on_line: F) -> CmdResult {
232 let mut cmd = Command::new(program);
233 cmd.args(args);
234 run_streamed_cmd(cmd, on_line)
235}
236
237pub fn run_streamed_cmd<F: FnMut(&str)>(mut cmd: Command, mut on_line: F) -> CmdResult {
241 let program = cmd.get_program().to_string_lossy().into_owned();
242 tracing::debug!(program, args = ?cmd.get_args().collect::<Vec<_>>(), "exec-streamed");
243 let mut child = match cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).spawn() {
244 Ok(c) => c,
245 Err(e) => {
246 tracing::warn!(program, error = %e, "exec spawn failed");
247 return CmdResult {
248 code: None,
249 stdout: String::new(),
250 stderr: e.to_string(),
251 spawned: false,
252 };
253 }
254 };
255
256 let stdout = child.stdout.take().expect("piped stdout present");
258 let stderr = child.stderr.take().expect("piped stderr present");
259 let (tx, rx) = mpsc::channel::<(StreamKind, String)>();
260 let tx_err = tx.clone();
261 let h_out = std::thread::spawn(move || pump(stdout, StreamKind::Out, tx));
262 let h_err = std::thread::spawn(move || pump(stderr, StreamKind::Err, tx_err));
263
264 let mut out_tail: VecDeque<String> = VecDeque::with_capacity(STREAM_TAIL_CAP);
268 let mut err_tail: VecDeque<String> = VecDeque::with_capacity(STREAM_TAIL_CAP);
269 for (kind, line) in rx {
270 on_line(&line);
271 let tail = match kind {
272 StreamKind::Out => &mut out_tail,
273 StreamKind::Err => &mut err_tail,
274 };
275 if tail.len() == STREAM_TAIL_CAP {
276 tail.pop_front();
277 }
278 tail.push_back(line);
279 }
280 let _ = h_out.join();
281 let _ = h_err.join();
282
283 let code = child.wait().ok().and_then(|s| s.code());
284 tracing::debug!(program, code = ?code, "exec-streamed done");
285 CmdResult {
286 code,
287 stdout: Vec::from(out_tail).join("\n"),
288 stderr: Vec::from(err_tail).join("\n"),
289 spawned: true,
290 }
291}
292
293#[cfg(test)]
294mod tests {
295 use super::*;
296
297 #[test]
298 fn run_captures_stdout_of_true_echo() {
299 let r = run("echo", &["hello"]);
301 assert!(r.success());
302 assert_eq!(r.stdout.trim(), "hello");
303 }
304
305 #[test]
306 fn run_reports_spawn_failure_without_panicking() {
307 let r = run("definitely-not-a-real-binary-xyz", &["--nope"]);
308 assert!(!r.spawned);
309 assert_eq!(r.code, None);
310 assert!(!r.success());
311 }
312
313 #[test]
314 fn run_checked_errors_on_nonzero() {
315 let err = run_checked("false", &[]).unwrap_err();
317 assert!(err.to_string().contains("exited"));
318 }
319
320 #[test]
321 fn run_streamed_delivers_each_line_and_keeps_the_tail() {
322 let mut lines = Vec::new();
323 let r = run_streamed("sh", &["-c", "printf 'a\\nb\\nc\\n'"], |l| {
324 lines.push(l.to_string())
325 });
326 assert!(r.success());
327 assert_eq!(lines, vec!["a", "b", "c"]);
328 assert_eq!(r.stdout, "a\nb\nc");
329 }
330
331 #[test]
332 fn run_streamed_splits_carriage_returns() {
333 let mut lines = Vec::new();
335 let r = run_streamed("sh", &["-c", "printf 'x\\ry\\rz'"], |l| {
336 lines.push(l.to_string())
337 });
338 assert!(r.success());
339 assert_eq!(lines, vec!["x", "y", "z"]);
340 }
341
342 #[test]
343 fn run_streamed_captures_stderr_tail_for_errors() {
344 let mut count = 0usize;
345 let r = run_streamed("sh", &["-c", "echo boom 1>&2; exit 3"], |_| count += 1);
346 assert!(!r.success());
347 assert_eq!(r.code, Some(3));
348 assert!(r.stderr.contains("boom"));
349 assert_eq!(count, 1);
350 }
351
352 #[test]
353 fn run_streamed_reports_spawn_failure() {
354 let r = run_streamed("definitely-not-a-real-binary-xyz", &[], |_| {});
355 assert!(!r.spawned);
356 assert_eq!(r.code, None);
357 }
358
359 #[test]
360 fn command_runners_honor_the_working_directory() {
361 let dir = std::env::temp_dir();
362 let want = dir.canonicalize().unwrap();
363 let mut cmd = Command::new("sh");
364 cmd.args(["-c", "pwd -P"]).current_dir(&dir);
365 let r = run_cmd(cmd);
366 assert!(r.success());
367 assert_eq!(std::path::Path::new(r.stdout.trim()), want);
368
369 let mut cmd = Command::new("sh");
370 cmd.args(["-c", "pwd -P"]).current_dir(&dir);
371 let mut lines = Vec::new();
372 let r = run_streamed_cmd(cmd, |l| lines.push(l.to_string()));
373 assert!(r.success());
374 assert_eq!(lines.len(), 1);
375 assert_eq!(std::path::Path::new(&lines[0]), want);
376 }
377}