Skip to main content

gadk_cli/
runner.rs

1// Copyright 2026 Chris Olson
2// Portions derived from ADK-Go (https://github.com/google/adk-go), Copyright 2026 Google LLC.
3//
4// Licensed under the Apache License, Version 2.0 (the "License");
5// you may not use this file except in compliance with the License.
6// You may obtain a copy of the License at
7//
8//     http://www.apache.org/licenses/LICENSE-2.0
9//
10// Unless required by applicable law or agreed to in writing, software
11// distributed under the License is distributed on an "AS IS" BASIS,
12// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13// See the License for the specific language governing permissions and
14// limitations under the License.
15
16//! The process seam: [`Cmd`] is a command with its program looked up in `PATH` and a text form;
17//! a [`CommandRunner`] starts it. Production
18//! uses [`TokioRunner`]; tests inject a recording runner, so no test spawns `gcloud` or `cargo`.
19
20use 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
30/// The error text for a program not found in `PATH`, on Unix.
31const ERR_NOT_FOUND: &str = "executable file not found in $PATH";
32/// The error text for an executable found relative to the current directory.
33const ERR_DOT: &str = "cannot run executable found relative to current directory";
34
35/// How a child process ended.
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
37pub enum Exit {
38    /// It exited with this status.
39    Code(i32),
40    /// A signal (this number) terminated it.
41    Signal(i32),
42}
43
44impl Exit {
45    /// Whether the child exited with code 0.
46    pub fn success(self) -> bool {
47        self == Exit::Code(0)
48    }
49
50    /// The error text of a failed exit: `exit status 1` for an exit code,
51    /// `signal: killed` for a signal; the texts match ADK's deploy tool.
52    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
60/// The name of a signal, for the signals a deploy can meet; others are `signal <n>`.
61// Only the common signals are named and a core dump is never reported.
62fn 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/// A finished child's exit and captured output (including the stderr kept for a failed
84/// exit).
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct CmdOutput {
87    /// How the child exited.
88    pub exit: Exit,
89    /// The captured standard output.
90    pub stdout: Vec<u8>,
91    /// The captured standard error.
92    pub stderr: Vec<u8>,
93}
94
95/// A command: the fields the deploy commands use.
96#[derive(Debug, Clone, PartialEq, Eq)]
97pub struct Cmd {
98    /// The program that `PATH` lookup resolved, or the name as given.
99    pub path: String,
100    /// The name as given, then the arguments.
101    pub args: Vec<String>,
102    /// The child's working directory; empty for the caller's.
103    pub dir: String,
104    /// The `PATH` lookup failure, returned when run without starting anything.
105    pub err: Option<String>,
106}
107
108impl Cmd {
109    /// A command for `name`: a `name` without a `/` is looked up in
110    /// `PATH` as `env` holds it (an empty `PATH` element is `.`; relative elements are
111    /// checked against `cwd` and fail with the relative-executable error).
112    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    /// Sets the working directory.
134    pub fn with_dir(mut self, dir: impl Into<String>) -> Cmd {
135        self.dir = dir.into();
136        self
137    }
138}
139
140/// The command's text: the resolved path and the arguments, or (when the lookup failed) the
141/// name as given and the arguments, space-joined.
142impl 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
155/// Looks `file` up in `path_var` like a Unix shell, returning the `(path, err)` pair: `err` is
156/// the lookup error text (`exec: "<file>": <reason>`), and `path` is set when the match is found
157/// relative to the current directory.
158fn 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    // An empty `PATH` has no elements.
164    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
182/// Whether `p` is a non-directory with an execute permission bit.
183fn 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/// Starts processes. `Err` is the text of the error from starting the child (the lookup
202/// failure for a failed lookup, else the spawn failure); a started child that fails is an `Ok`
203/// [`Exit`].
204#[async_trait]
205pub trait CommandRunner: Send + Sync {
206    /// Runs `cmd` to completion with stdin
207    /// from the null device, copying its output to `stdout` and `stderr` as it arrives.
208    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    /// Runs `cmd` to completion with stdin from the null device and captures its output.
216    async fn output(&self, cmd: &Cmd) -> Result<CmdOutput, String>;
217}
218
219/// Spawns real processes with tokio.
220#[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        // A spawn failure other than the lookup reports Rust's `io::Error` text.
248        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
269/// Copies a child pipe to `w` until end of file.
270async 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        // A non-executable file and a directory of the same name are skipped, as in Go.
345        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        // An unset PATH is Go's empty `filepath.SplitList`.
384        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        // An empty element is ".".
404        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    /// A real child (`/bin/sh`, no lookup): output is streamed to the two writers, the working
422    /// directory and the exit status are honoured, stdin is the null device.
423    #[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}