1use std::fmt;
21use std::io::Write;
22use std::path::Path;
23use std::process::Stdio;
24
25use async_trait::async_trait;
26use gadk_platform::env::EnvProvider;
27use gadk_platform::{go_path_join, go_quote};
28use tokio::io::{AsyncRead, AsyncReadExt};
29
30const ERR_NOT_FOUND: &str = "executable file not found in $PATH";
32const ERR_DOT: &str = "cannot run executable found relative to current directory";
34
35#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum Exit {
38 Code(i32),
40 Signal(i32),
42}
43
44impl Exit {
45 pub fn success(self) -> bool {
47 self == Exit::Code(0)
48 }
49
50 pub fn go_error(self) -> String {
53 match self {
54 Exit::Code(code) => format!("exit status {code}"),
55 Exit::Signal(sig) => format!("signal: {}", signal_name(sig)),
56 }
57 }
58}
59
60fn signal_name(sig: i32) -> String {
63 let name = match sig {
64 1 => "hangup",
65 2 => "interrupt",
66 3 => "quit",
67 4 => "illegal instruction",
68 #[cfg(target_os = "linux")]
69 6 => "aborted",
70 #[cfg(not(target_os = "linux"))]
71 6 => "abort trap",
72 8 => "floating point exception",
73 9 => "killed",
74 11 => "segmentation fault",
75 13 => "broken pipe",
76 14 => "alarm clock",
77 15 => "terminated",
78 _ => return format!("signal {sig}"),
79 };
80 name.to_string()
81}
82
83#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct CmdOutput {
87 pub exit: Exit,
89 pub stdout: Vec<u8>,
91 pub stderr: Vec<u8>,
93}
94
95#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct Cmd {
98 pub path: String,
100 pub args: Vec<String>,
102 pub dir: String,
104 pub err: Option<String>,
106}
107
108impl Cmd {
109 pub fn new(env: &dyn EnvProvider, cwd: &Path, name: &str, args: &[&str]) -> Cmd {
113 let mut cmd = Cmd {
114 path: name.to_string(),
115 args: std::iter::once(name)
116 .chain(args.iter().copied())
117 .map(str::to_string)
118 .collect(),
119 dir: String::new(),
120 err: None,
121 };
122 if !name.contains('/') {
123 let path_var = env.var("PATH").unwrap_or_default();
124 let (lp, err) = look_path(&path_var, cwd, name);
125 if !lp.is_empty() {
126 cmd.path = lp;
127 }
128 cmd.err = err;
129 }
130 cmd
131 }
132
133 pub fn with_dir(mut self, dir: impl Into<String>) -> Cmd {
135 self.dir = dir.into();
136 self
137 }
138}
139
140impl fmt::Display for Cmd {
143 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
144 if self.err.is_some() {
145 return f.write_str(&self.args.join(" "));
146 }
147 f.write_str(&self.path)?;
148 for a in self.args.iter().skip(1) {
149 write!(f, " {a}")?;
150 }
151 Ok(())
152 }
153}
154
155fn look_path(path_var: &str, cwd: &Path, file: &str) -> (String, Option<String>) {
159 let exec_error = |e: &str| Some(format!("exec: {}: {e}", go_quote(file)));
160 if matches!(file, "" | "." | "..") {
161 return (String::new(), exec_error(ERR_NOT_FOUND));
162 }
163 let dirs: Vec<&str> = if path_var.is_empty() {
165 Vec::new()
166 } else {
167 path_var.split(':').collect()
168 };
169 for dir in dirs {
170 let dir = if dir.is_empty() { "." } else { dir };
171 let path = go_path_join(&[dir, file]);
172 if is_executable(&cwd.join(&path)) {
173 if !path.starts_with('/') {
174 return (path, exec_error(ERR_DOT));
175 }
176 return (path, None);
177 }
178 }
179 (String::new(), exec_error(ERR_NOT_FOUND))
180}
181
182fn is_executable(p: &Path) -> bool {
184 let Ok(meta) = std::fs::metadata(p) else {
185 return false;
186 };
187 if meta.is_dir() {
188 return false;
189 }
190 #[cfg(unix)]
191 {
192 use std::os::unix::fs::PermissionsExt;
193 meta.permissions().mode() & 0o111 != 0
194 }
195 #[cfg(not(unix))]
196 {
197 true
198 }
199}
200
201#[async_trait]
205pub trait CommandRunner: Send + Sync {
206 async fn run(
209 &self,
210 cmd: &Cmd,
211 stdout: &mut (dyn Write + Send),
212 stderr: &mut (dyn Write + Send),
213 ) -> Result<Exit, String>;
214
215 async fn output(&self, cmd: &Cmd) -> Result<CmdOutput, String>;
217}
218
219#[derive(Debug, Clone, Copy, Default)]
221pub struct TokioRunner;
222
223impl TokioRunner {
224 fn command(cmd: &Cmd) -> Result<tokio::process::Command, String> {
225 if let Some(err) = &cmd.err {
226 return Err(err.clone());
227 }
228 let mut c = tokio::process::Command::new(&cmd.path);
229 c.args(cmd.args.iter().skip(1)).stdin(Stdio::null());
230 if !cmd.dir.is_empty() {
231 c.current_dir(&cmd.dir);
232 }
233 Ok(c)
234 }
235}
236
237#[async_trait]
238impl CommandRunner for TokioRunner {
239 async fn run(
240 &self,
241 cmd: &Cmd,
242 stdout: &mut (dyn Write + Send),
243 stderr: &mut (dyn Write + Send),
244 ) -> Result<Exit, String> {
245 let mut c = TokioRunner::command(cmd)?;
246 c.stdout(Stdio::piped()).stderr(Stdio::piped());
247 let mut child = c.spawn().map_err(|e| e.to_string())?;
249 let (out_pipe, err_pipe) = (child.stdout.take(), child.stderr.take());
250 let (copied_out, copied_err) =
251 tokio::join!(copy_to(out_pipe, stdout), copy_to(err_pipe, stderr));
252 let status = child.wait().await.map_err(|e| e.to_string())?;
253 copied_out.map_err(|e| e.to_string())?;
254 copied_err.map_err(|e| e.to_string())?;
255 Ok(exit_of(status))
256 }
257
258 async fn output(&self, cmd: &Cmd) -> Result<CmdOutput, String> {
259 let mut c = TokioRunner::command(cmd)?;
260 let out = c.output().await.map_err(|e| e.to_string())?;
261 Ok(CmdOutput {
262 exit: exit_of(out.status),
263 stdout: out.stdout,
264 stderr: out.stderr,
265 })
266 }
267}
268
269async fn copy_to<R: AsyncRead + Unpin>(
271 pipe: Option<R>,
272 w: &mut (dyn Write + Send),
273) -> std::io::Result<()> {
274 let Some(mut pipe) = pipe else {
275 return Ok(());
276 };
277 let mut buf = vec![0u8; 32 * 1024];
278 loop {
279 let n = pipe.read(&mut buf).await?;
280 if n == 0 {
281 return Ok(());
282 }
283 w.write_all(&buf[..n])?;
284 w.flush()?;
285 }
286}
287
288fn exit_of(status: std::process::ExitStatus) -> Exit {
289 if let Some(code) = status.code() {
290 return Exit::Code(code);
291 }
292 #[cfg(unix)]
293 {
294 use std::os::unix::process::ExitStatusExt;
295 if let Some(sig) = status.signal() {
296 return Exit::Signal(sig);
297 }
298 }
299 Exit::Code(-1)
300}
301
302#[cfg(test)]
303mod tests {
304 use std::collections::HashMap;
305 use std::path::Path;
306
307 use gadk_platform::env::MapEnv;
308 use pretty_assertions::assert_eq;
309
310 use super::*;
311
312 fn env_with_path(path: &str) -> MapEnv {
313 MapEnv(HashMap::from([("PATH".to_string(), path.to_string())]))
314 }
315
316 fn executable(dir: &Path, name: &str) -> String {
317 let p = dir.join(name);
318 std::fs::write(&p, "#!/bin/sh\nexit 0\n").unwrap();
319 #[cfg(unix)]
320 {
321 use std::os::unix::fs::PermissionsExt;
322 std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
323 }
324 p.display().to_string()
325 }
326
327 #[test]
328 fn exit_texts_are_go_process_state_strings() {
329 assert_eq!(Exit::Code(1).go_error(), "exit status 1");
330 assert_eq!(Exit::Code(127).go_error(), "exit status 127");
331 assert_eq!(Exit::Signal(9).go_error(), "signal: killed");
332 assert_eq!(Exit::Signal(2).go_error(), "signal: interrupt");
333 assert_eq!(Exit::Signal(15).go_error(), "signal: terminated");
334 assert_eq!(Exit::Signal(64).go_error(), "signal: signal 64");
335 assert!(Exit::Code(0).success());
336 assert!(!Exit::Code(2).success());
337 assert!(!Exit::Signal(9).success());
338 }
339
340 #[test]
341 fn command_resolves_the_first_executable_on_path() {
342 let a = tempfile::tempdir().unwrap();
343 let b = tempfile::tempdir().unwrap();
344 std::fs::write(a.path().join("gcloud"), "").unwrap();
346 std::fs::create_dir(b.path().join("gcloud")).unwrap();
347 let c = tempfile::tempdir().unwrap();
348 let want = executable(c.path(), "gcloud");
349 let path = format!(
350 "{}:{}:{}",
351 a.path().display(),
352 b.path().display(),
353 c.path().display()
354 );
355 let cmd = Cmd::new(
356 &env_with_path(&path),
357 Path::new("/"),
358 "gcloud",
359 &["run", "x"],
360 )
361 .with_dir("/tmp/d");
362 assert_eq!(cmd.path, want);
363 assert_eq!(cmd.args, ["gcloud", "run", "x"]);
364 assert_eq!(cmd.dir, "/tmp/d");
365 assert_eq!(cmd.err, None);
366 assert_eq!(cmd.to_string(), format!("{want} run x"));
367 }
368
369 #[test]
370 fn a_failed_lookup_keeps_the_name_and_prints_the_args() {
371 let cmd = Cmd::new(
372 &env_with_path("/nonexistent"),
373 Path::new("/"),
374 "gcloud",
375 &["a"],
376 );
377 assert_eq!(cmd.path, "gcloud");
378 assert_eq!(
379 cmd.err.as_deref(),
380 Some(r#"exec: "gcloud": executable file not found in $PATH"#)
381 );
382 assert_eq!(cmd.to_string(), "gcloud a");
383 let cmd = Cmd::new(&MapEnv::default(), Path::new("/"), "gcloud", &[]);
385 assert_eq!(
386 cmd.err.as_deref(),
387 Some(r#"exec: "gcloud": executable file not found in $PATH"#)
388 );
389 }
390
391 #[test]
392 fn a_relative_path_entry_is_go_err_dot() {
393 let cwd = tempfile::tempdir().unwrap();
394 std::fs::create_dir(cwd.path().join("bin")).unwrap();
395 executable(&cwd.path().join("bin"), "tool");
396 let cmd = Cmd::new(&env_with_path("bin"), cwd.path(), "tool", &["x"]);
397 assert_eq!(cmd.path, "bin/tool");
398 assert_eq!(
399 cmd.err.as_deref(),
400 Some(r#"exec: "tool": cannot run executable found relative to current directory"#)
401 );
402 assert_eq!(cmd.to_string(), "tool x");
403 executable(cwd.path(), "dot");
405 let cmd = Cmd::new(&env_with_path(":/nonexistent"), cwd.path(), "dot", &[]);
406 assert_eq!(cmd.path, "dot");
407 assert!(cmd.err.as_deref().unwrap_or_default().contains("relative"));
408 }
409
410 #[test]
411 fn a_name_with_a_slash_is_not_looked_up() {
412 let cmd = Cmd::new(&MapEnv::default(), Path::new("/"), "./gadk", &["x"]);
413 assert_eq!((cmd.path.as_str(), cmd.err), ("./gadk", None));
414 let cmd = Cmd::new(&MapEnv::default(), Path::new("/"), "", &[]);
415 assert_eq!(
416 cmd.err.as_deref(),
417 Some(r#"exec: "": executable file not found in $PATH"#)
418 );
419 }
420
421 #[cfg(unix)]
424 #[tokio::test]
425 async fn tokio_runner_streams_output_and_reports_the_exit() {
426 let dir = tempfile::tempdir().unwrap();
427 let dir_s = dir.path().canonicalize().unwrap().display().to_string();
428 let script = "pwd; printf err >&2; read x || printf eof; exit 3";
429 let cmd = Cmd::new(
430 &MapEnv::default(),
431 Path::new("/"),
432 "/bin/sh",
433 &["-c", script],
434 )
435 .with_dir(dir_s.clone());
436 let (mut out, mut err) = (Vec::new(), Vec::new());
437 let got = TokioRunner.run(&cmd, &mut out, &mut err).await;
438 assert_eq!(got, Ok(Exit::Code(3)));
439 assert_eq!(String::from_utf8(out).unwrap(), format!("{dir_s}\neof"));
440 assert_eq!(String::from_utf8(err).unwrap(), "err");
441
442 let got = TokioRunner.output(&cmd).await.unwrap();
443 assert_eq!(got.exit, Exit::Code(3));
444 assert_eq!(
445 String::from_utf8(got.stdout).unwrap(),
446 format!("{dir_s}\neof")
447 );
448 assert_eq!(got.stderr, b"err");
449 }
450
451 #[tokio::test]
452 async fn tokio_runner_returns_the_lookup_error_without_starting() {
453 let cmd = Cmd::new(&MapEnv::default(), Path::new("/"), "gcloud", &[]);
454 let (mut out, mut err) = (Vec::new(), Vec::new());
455 let got = TokioRunner.run(&cmd, &mut out, &mut err).await;
456 assert_eq!(
457 got,
458 Err(r#"exec: "gcloud": executable file not found in $PATH"#.to_string())
459 );
460 assert_eq!(
461 TokioRunner.output(&cmd).await,
462 Err(r#"exec: "gcloud": executable file not found in $PATH"#.to_string())
463 );
464 }
465}