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,
88 pub stdout: Vec<u8>,
89 pub stderr: Vec<u8>,
90}
91
92#[derive(Debug, Clone, PartialEq, Eq)]
94pub struct Cmd {
95 pub path: String,
97 pub args: Vec<String>,
99 pub dir: String,
101 pub err: Option<String>,
103}
104
105impl Cmd {
106 pub fn new(env: &dyn EnvProvider, cwd: &Path, name: &str, args: &[&str]) -> Cmd {
110 let mut cmd = Cmd {
111 path: name.to_string(),
112 args: std::iter::once(name)
113 .chain(args.iter().copied())
114 .map(str::to_string)
115 .collect(),
116 dir: String::new(),
117 err: None,
118 };
119 if !name.contains('/') {
120 let path_var = env.var("PATH").unwrap_or_default();
121 let (lp, err) = look_path(&path_var, cwd, name);
122 if !lp.is_empty() {
123 cmd.path = lp;
124 }
125 cmd.err = err;
126 }
127 cmd
128 }
129
130 pub fn with_dir(mut self, dir: impl Into<String>) -> Cmd {
132 self.dir = dir.into();
133 self
134 }
135}
136
137impl fmt::Display for Cmd {
140 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
141 if self.err.is_some() {
142 return f.write_str(&self.args.join(" "));
143 }
144 f.write_str(&self.path)?;
145 for a in self.args.iter().skip(1) {
146 write!(f, " {a}")?;
147 }
148 Ok(())
149 }
150}
151
152fn look_path(path_var: &str, cwd: &Path, file: &str) -> (String, Option<String>) {
156 let exec_error = |e: &str| Some(format!("exec: {}: {e}", go_quote(file)));
157 if matches!(file, "" | "." | "..") {
158 return (String::new(), exec_error(ERR_NOT_FOUND));
159 }
160 let dirs: Vec<&str> = if path_var.is_empty() {
162 Vec::new()
163 } else {
164 path_var.split(':').collect()
165 };
166 for dir in dirs {
167 let dir = if dir.is_empty() { "." } else { dir };
168 let path = go_path_join(&[dir, file]);
169 if is_executable(&cwd.join(&path)) {
170 if !path.starts_with('/') {
171 return (path, exec_error(ERR_DOT));
172 }
173 return (path, None);
174 }
175 }
176 (String::new(), exec_error(ERR_NOT_FOUND))
177}
178
179fn is_executable(p: &Path) -> bool {
181 let Ok(meta) = std::fs::metadata(p) else {
182 return false;
183 };
184 if meta.is_dir() {
185 return false;
186 }
187 #[cfg(unix)]
188 {
189 use std::os::unix::fs::PermissionsExt;
190 meta.permissions().mode() & 0o111 != 0
191 }
192 #[cfg(not(unix))]
193 {
194 true
195 }
196}
197
198#[async_trait]
202pub trait CommandRunner: Send + Sync {
203 async fn run(
206 &self,
207 cmd: &Cmd,
208 stdout: &mut (dyn Write + Send),
209 stderr: &mut (dyn Write + Send),
210 ) -> Result<Exit, String>;
211
212 async fn output(&self, cmd: &Cmd) -> Result<CmdOutput, String>;
214}
215
216#[derive(Debug, Clone, Copy, Default)]
218pub struct TokioRunner;
219
220impl TokioRunner {
221 fn command(cmd: &Cmd) -> Result<tokio::process::Command, String> {
222 if let Some(err) = &cmd.err {
223 return Err(err.clone());
224 }
225 let mut c = tokio::process::Command::new(&cmd.path);
226 c.args(cmd.args.iter().skip(1)).stdin(Stdio::null());
227 if !cmd.dir.is_empty() {
228 c.current_dir(&cmd.dir);
229 }
230 Ok(c)
231 }
232}
233
234#[async_trait]
235impl CommandRunner for TokioRunner {
236 async fn run(
237 &self,
238 cmd: &Cmd,
239 stdout: &mut (dyn Write + Send),
240 stderr: &mut (dyn Write + Send),
241 ) -> Result<Exit, String> {
242 let mut c = TokioRunner::command(cmd)?;
243 c.stdout(Stdio::piped()).stderr(Stdio::piped());
244 let mut child = c.spawn().map_err(|e| e.to_string())?;
246 let (out_pipe, err_pipe) = (child.stdout.take(), child.stderr.take());
247 let (copied_out, copied_err) =
248 tokio::join!(copy_to(out_pipe, stdout), copy_to(err_pipe, stderr));
249 let status = child.wait().await.map_err(|e| e.to_string())?;
250 copied_out.map_err(|e| e.to_string())?;
251 copied_err.map_err(|e| e.to_string())?;
252 Ok(exit_of(status))
253 }
254
255 async fn output(&self, cmd: &Cmd) -> Result<CmdOutput, String> {
256 let mut c = TokioRunner::command(cmd)?;
257 let out = c.output().await.map_err(|e| e.to_string())?;
258 Ok(CmdOutput {
259 exit: exit_of(out.status),
260 stdout: out.stdout,
261 stderr: out.stderr,
262 })
263 }
264}
265
266async fn copy_to<R: AsyncRead + Unpin>(
268 pipe: Option<R>,
269 w: &mut (dyn Write + Send),
270) -> std::io::Result<()> {
271 let Some(mut pipe) = pipe else {
272 return Ok(());
273 };
274 let mut buf = vec![0u8; 32 * 1024];
275 loop {
276 let n = pipe.read(&mut buf).await?;
277 if n == 0 {
278 return Ok(());
279 }
280 w.write_all(&buf[..n])?;
281 w.flush()?;
282 }
283}
284
285fn exit_of(status: std::process::ExitStatus) -> Exit {
286 if let Some(code) = status.code() {
287 return Exit::Code(code);
288 }
289 #[cfg(unix)]
290 {
291 use std::os::unix::process::ExitStatusExt;
292 if let Some(sig) = status.signal() {
293 return Exit::Signal(sig);
294 }
295 }
296 Exit::Code(-1)
297}
298
299#[cfg(test)]
300mod tests {
301 use std::collections::HashMap;
302 use std::path::Path;
303
304 use gadk_platform::env::MapEnv;
305 use pretty_assertions::assert_eq;
306
307 use super::*;
308
309 fn env_with_path(path: &str) -> MapEnv {
310 MapEnv(HashMap::from([("PATH".to_string(), path.to_string())]))
311 }
312
313 fn executable(dir: &Path, name: &str) -> String {
314 let p = dir.join(name);
315 std::fs::write(&p, "#!/bin/sh\nexit 0\n").unwrap();
316 #[cfg(unix)]
317 {
318 use std::os::unix::fs::PermissionsExt;
319 std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o755)).unwrap();
320 }
321 p.display().to_string()
322 }
323
324 #[test]
325 fn exit_texts_are_go_process_state_strings() {
326 assert_eq!(Exit::Code(1).go_error(), "exit status 1");
327 assert_eq!(Exit::Code(127).go_error(), "exit status 127");
328 assert_eq!(Exit::Signal(9).go_error(), "signal: killed");
329 assert_eq!(Exit::Signal(2).go_error(), "signal: interrupt");
330 assert_eq!(Exit::Signal(15).go_error(), "signal: terminated");
331 assert_eq!(Exit::Signal(64).go_error(), "signal: signal 64");
332 assert!(Exit::Code(0).success());
333 assert!(!Exit::Code(2).success());
334 assert!(!Exit::Signal(9).success());
335 }
336
337 #[test]
338 fn command_resolves_the_first_executable_on_path() {
339 let a = tempfile::tempdir().unwrap();
340 let b = tempfile::tempdir().unwrap();
341 std::fs::write(a.path().join("gcloud"), "").unwrap();
343 std::fs::create_dir(b.path().join("gcloud")).unwrap();
344 let c = tempfile::tempdir().unwrap();
345 let want = executable(c.path(), "gcloud");
346 let path = format!(
347 "{}:{}:{}",
348 a.path().display(),
349 b.path().display(),
350 c.path().display()
351 );
352 let cmd = Cmd::new(
353 &env_with_path(&path),
354 Path::new("/"),
355 "gcloud",
356 &["run", "x"],
357 )
358 .with_dir("/tmp/d");
359 assert_eq!(cmd.path, want);
360 assert_eq!(cmd.args, ["gcloud", "run", "x"]);
361 assert_eq!(cmd.dir, "/tmp/d");
362 assert_eq!(cmd.err, None);
363 assert_eq!(cmd.to_string(), format!("{want} run x"));
364 }
365
366 #[test]
367 fn a_failed_lookup_keeps_the_name_and_prints_the_args() {
368 let cmd = Cmd::new(
369 &env_with_path("/nonexistent"),
370 Path::new("/"),
371 "gcloud",
372 &["a"],
373 );
374 assert_eq!(cmd.path, "gcloud");
375 assert_eq!(
376 cmd.err.as_deref(),
377 Some(r#"exec: "gcloud": executable file not found in $PATH"#)
378 );
379 assert_eq!(cmd.to_string(), "gcloud a");
380 let cmd = Cmd::new(&MapEnv::default(), Path::new("/"), "gcloud", &[]);
382 assert_eq!(
383 cmd.err.as_deref(),
384 Some(r#"exec: "gcloud": executable file not found in $PATH"#)
385 );
386 }
387
388 #[test]
389 fn a_relative_path_entry_is_go_err_dot() {
390 let cwd = tempfile::tempdir().unwrap();
391 std::fs::create_dir(cwd.path().join("bin")).unwrap();
392 executable(&cwd.path().join("bin"), "tool");
393 let cmd = Cmd::new(&env_with_path("bin"), cwd.path(), "tool", &["x"]);
394 assert_eq!(cmd.path, "bin/tool");
395 assert_eq!(
396 cmd.err.as_deref(),
397 Some(r#"exec: "tool": cannot run executable found relative to current directory"#)
398 );
399 assert_eq!(cmd.to_string(), "tool x");
400 executable(cwd.path(), "dot");
402 let cmd = Cmd::new(&env_with_path(":/nonexistent"), cwd.path(), "dot", &[]);
403 assert_eq!(cmd.path, "dot");
404 assert!(cmd.err.as_deref().unwrap_or_default().contains("relative"));
405 }
406
407 #[test]
408 fn a_name_with_a_slash_is_not_looked_up() {
409 let cmd = Cmd::new(&MapEnv::default(), Path::new("/"), "./gadk", &["x"]);
410 assert_eq!((cmd.path.as_str(), cmd.err), ("./gadk", None));
411 let cmd = Cmd::new(&MapEnv::default(), Path::new("/"), "", &[]);
412 assert_eq!(
413 cmd.err.as_deref(),
414 Some(r#"exec: "": executable file not found in $PATH"#)
415 );
416 }
417
418 #[cfg(unix)]
421 #[tokio::test]
422 async fn tokio_runner_streams_output_and_reports_the_exit() {
423 let dir = tempfile::tempdir().unwrap();
424 let dir_s = dir.path().canonicalize().unwrap().display().to_string();
425 let script = "pwd; printf err >&2; read x || printf eof; exit 3";
426 let cmd = Cmd::new(
427 &MapEnv::default(),
428 Path::new("/"),
429 "/bin/sh",
430 &["-c", script],
431 )
432 .with_dir(dir_s.clone());
433 let (mut out, mut err) = (Vec::new(), Vec::new());
434 let got = TokioRunner.run(&cmd, &mut out, &mut err).await;
435 assert_eq!(got, Ok(Exit::Code(3)));
436 assert_eq!(String::from_utf8(out).unwrap(), format!("{dir_s}\neof"));
437 assert_eq!(String::from_utf8(err).unwrap(), "err");
438
439 let got = TokioRunner.output(&cmd).await.unwrap();
440 assert_eq!(got.exit, Exit::Code(3));
441 assert_eq!(
442 String::from_utf8(got.stdout).unwrap(),
443 format!("{dir_s}\neof")
444 );
445 assert_eq!(got.stderr, b"err");
446 }
447
448 #[tokio::test]
449 async fn tokio_runner_returns_the_lookup_error_without_starting() {
450 let cmd = Cmd::new(&MapEnv::default(), Path::new("/"), "gcloud", &[]);
451 let (mut out, mut err) = (Vec::new(), Vec::new());
452 let got = TokioRunner.run(&cmd, &mut out, &mut err).await;
453 assert_eq!(
454 got,
455 Err(r#"exec: "gcloud": executable file not found in $PATH"#.to_string())
456 );
457 assert_eq!(
458 TokioRunner.output(&cmd).await,
459 Err(r#"exec: "gcloud": executable file not found in $PATH"#.to_string())
460 );
461 }
462}