Skip to main content

gadk_cli/
lib.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//! gadk-cli: the `gadk` deploy CLI (`gadk deploy cloudrun`, `gadk deploy agentengine`) and its
17//! helper text and console utilities. Its flags, checks, generated Dockerfile `CMD`, `gcloud`
18//! invocations and console output follow ADK's deploy CLI.
19//!
20//! The binary `gadk` deploys a gadk agent (a Cargo binary target) to Cloud Run or Vertex AI
21//! Agent Engine. Everything a command touches outside the process (child processes, stdout and
22//! stderr, the working directory, the environment, the clock) goes through [`Env`], so tests
23//! never spawn `gcloud` or `cargo`, never read the process environment and never change the
24//! current directory.
25
26pub mod deploy;
27pub mod flags;
28pub mod root;
29pub mod runner;
30pub mod stage;
31pub mod target;
32pub mod util;
33
34#[cfg(test)]
35mod parity_tests;
36#[cfg(test)]
37pub(crate) mod testutil;
38
39use std::ffi::OsString;
40use std::fmt;
41use std::io::{self, Write};
42use std::path::PathBuf;
43use std::process::ExitCode;
44use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
45
46use chrono::Utc;
47use gadk_platform::TimeProvider;
48use gadk_platform::env::{EnvProvider, ProcessEnv};
49use gadk_platform::{go_path_clean, go_path_join};
50use gadk_vertexai::reasoning_engine::ReasoningEngineOptions;
51
52use crate::runner::{Cmd, CommandRunner, TokioRunner};
53
54/// A cloneable, shared output stream (the commands' stdout and stderr):
55/// every clone writes to the same underlying writer, one `write` call at a time.
56#[derive(Clone)]
57pub struct SharedWriter(Arc<Mutex<dyn Write + Send>>);
58
59impl SharedWriter {
60    /// Wraps `w`.
61    pub fn new(w: impl Write + Send + 'static) -> SharedWriter {
62        SharedWriter(Arc::new(Mutex::new(w)))
63    }
64
65    /// Shares an existing writer (a test keeps its own handle to read what was written).
66    pub fn from_shared(w: Arc<Mutex<dyn Write + Send>>) -> SharedWriter {
67        SharedWriter(w)
68    }
69
70    /// Writes `s`, ignoring a write error.
71    pub fn write_str(&self, s: &str) {
72        let mut w = self.lock();
73        let _ = w.write_all(s.as_bytes());
74        let _ = w.flush();
75    }
76
77    fn lock(&self) -> MutexGuard<'_, dyn Write + Send + 'static> {
78        self.0.lock().unwrap_or_else(PoisonError::into_inner)
79    }
80}
81
82impl Write for SharedWriter {
83    fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
84        self.lock().write(buf)
85    }
86
87    fn flush(&mut self) -> io::Result<()> {
88        self.lock().flush()
89    }
90}
91
92impl fmt::Debug for SharedWriter {
93    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
94        f.write_str("SharedWriter")
95    }
96}
97
98/// Everything a command reads or writes outside the process (stdout, stderr, the working
99/// directory, the environment, the clock and child processes).
100pub struct Env {
101    /// Launches child processes (`gcloud`, `cargo metadata`).
102    pub runner: Arc<dyn CommandRunner>,
103    /// Standard output: step banners, printer lines and child output.
104    pub out: SharedWriter,
105    /// Standard error: the `Error:` line and usage.
106    pub err: SharedWriter,
107    /// The working directory: relative paths resolve against it.
108    pub cwd: PathBuf,
109    /// The environment (`PATH` for command lookup, `TMPDIR` for the temp dir).
110    pub env: Arc<dyn EnvProvider>,
111    /// The clock.
112    pub time: Arc<dyn TimeProvider>,
113    /// How `gadk deploy agentengine` reaches Vertex AI (endpoint, credentials and HTTP client are
114    /// injectable for tests). An unset
115    /// [`ReasoningEngineOptions::env`] means [`Env::env`].
116    pub vertex: ReasoningEngineOptions,
117}
118
119impl Env {
120    /// An `Env` from its parts, with default Vertex options (tests set [`Env::vertex`] on the
121    /// built value). Outside this file an `Env` is built only here, by [`Env::process`] or by
122    /// the test builder, never by a struct literal.
123    pub fn new(
124        runner: Arc<dyn CommandRunner>,
125        out: SharedWriter,
126        err: SharedWriter,
127        cwd: PathBuf,
128        env: Arc<dyn EnvProvider>,
129        time: Arc<dyn TimeProvider>,
130    ) -> Env {
131        Env {
132            runner,
133            out,
134            err,
135            cwd,
136            env,
137            time,
138            vertex: ReasoningEngineOptions::default(),
139        }
140    }
141
142    /// The production environment: real processes, stdout/stderr, the current directory (empty
143    /// when it cannot be read), the process environment, the system clock and Vertex AI at
144    /// its regional endpoint with Application Default Credentials.
145    pub fn process() -> Env {
146        Env::new(
147            Arc::new(TokioRunner),
148            SharedWriter::new(io::stdout()),
149            SharedWriter::new(io::stderr()),
150            std::env::current_dir().unwrap_or_default(),
151            Arc::new(ProcessEnv),
152            Arc::new(Utc::now),
153        )
154    }
155
156    /// Resolves `path` against [`Env::cwd`]: an absolute `path` is cleaned, a relative
157    /// one is joined to the working directory and cleaned; `""` is the working directory.
158    pub fn abs(&self, path: &str) -> PathBuf {
159        if path.starts_with('/') {
160            return PathBuf::from(go_path_clean(path));
161        }
162        let cwd = self.cwd.to_string_lossy();
163        PathBuf::from(go_path_join(&[cwd.as_ref(), path]))
164    }
165
166    /// The temp dir on Unix: `$TMPDIR`, else `/tmp`.
167    pub fn temp_dir(&self) -> PathBuf {
168        match self.env.var("TMPDIR") {
169            Some(dir) if !dir.is_empty() => PathBuf::from(dir),
170            _ => PathBuf::from("/tmp"),
171        }
172    }
173
174    /// A command for `name` with `args`, looked up in `PATH` read from [`Env::env`].
175    pub fn command(&self, name: &str, args: &[&str]) -> Cmd {
176        Cmd::new(self.env.as_ref(), &self.cwd, name, args)
177    }
178}
179
180/// Runs the `gadk` command line (`args` includes the program name, as `std::env::args_os`) and
181/// returns the process exit code: 0, or 1 when a command failed.
182pub async fn run<I, T>(args: I, env: &Env) -> ExitCode
183where
184    I: IntoIterator<Item = T>,
185    T: Into<OsString>,
186{
187    let args: Vec<OsString> = args.into_iter().map(Into::into).collect();
188    ExitCode::from(root::execute(args, env).await)
189}
190
191#[cfg(test)]
192mod tests {
193    use std::collections::HashMap;
194    use std::path::{Path, PathBuf};
195
196    use pretty_assertions::assert_eq;
197
198    use crate::testutil::TestEnv;
199
200    #[test]
201    fn abs_resolves_against_the_working_directory_like_go_filepath_abs() {
202        let t = TestEnv::builder("/work/space").build();
203        assert_eq!(t.env.abs(""), PathBuf::from("/work/space"));
204        assert_eq!(t.env.abs("."), PathBuf::from("/work/space"));
205        assert_eq!(t.env.abs("agent"), PathBuf::from("/work/space/agent"));
206        assert_eq!(t.env.abs("../x/./y/"), PathBuf::from("/work/x/y"));
207        assert_eq!(t.env.abs("/abs//p/../q"), PathBuf::from("/abs/q"));
208    }
209
210    #[test]
211    fn temp_dir_is_go_os_temp_dir() {
212        let t = TestEnv::builder("/w").build();
213        assert_eq!(t.env.temp_dir(), PathBuf::from("/tmp"));
214        let t = TestEnv::builder("/w").var("TMPDIR", "").build();
215        assert_eq!(t.env.temp_dir(), PathBuf::from("/tmp"));
216        let t = TestEnv::builder("/w").var("TMPDIR", "/var/tmp/x").build();
217        assert_eq!(t.env.temp_dir(), PathBuf::from("/var/tmp/x"));
218    }
219
220    #[test]
221    fn command_looks_the_program_up_through_the_injected_path() {
222        let dir = tempfile::tempdir().unwrap();
223        let bin = dir.path().join("gcloud");
224        std::fs::write(&bin, "#!/bin/sh\n").unwrap();
225        make_executable(&bin);
226        let path = format!("/nonexistent:{}", dir.path().display());
227        let t = TestEnv::builder("/w")
228            .vars(HashMap::from([("PATH".to_string(), path)]))
229            .build();
230        let cmd = t.env.command("gcloud", &["run", "deploy"]);
231        assert_eq!(cmd.path, bin.display().to_string());
232        assert_eq!(cmd.err, None);
233        assert_eq!(cmd.to_string(), format!("{} run deploy", bin.display()));
234    }
235
236    #[cfg(unix)]
237    fn make_executable(p: &Path) {
238        use std::os::unix::fs::PermissionsExt;
239        std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o755)).unwrap();
240    }
241
242    #[cfg(not(unix))]
243    fn make_executable(_: &Path) {}
244
245    /// `build.rs` stores the second word of `$RUSTC --version` (R5).
246    #[test]
247    fn build_script_captures_the_compiling_rustc_version() {
248        let v = crate::target::COMPILED_RUSTC_VERSION;
249        // e.g. `1.99.1` (from `rustc 1.99.1 (…)`) or `1.100.0-nightly`.
250        assert!(
251            v.starts_with(|c: char| c.is_ascii_digit()) && v.contains('.'),
252            "unexpected rustc version {v:?}"
253        );
254    }
255
256    /// Plan D3: `Env::new` (and so the test builder) starts from the default Vertex options:
257    /// the regional endpoint, Application Default Credentials, reqwest, [`Env::env`].
258    #[test]
259    fn env_vertex_defaults_to_the_regional_endpoint_and_adc() {
260        let t = TestEnv::builder("/w").build();
261        let v = &t.env.vertex;
262        assert_eq!(v.endpoint, None);
263        assert!(v.credentials.is_none());
264        assert!(!v.without_authentication);
265        assert!(v.http_client.is_none());
266        assert!(v.env.is_none());
267    }
268
269    #[test]
270    fn shared_writer_clones_write_to_one_buffer() {
271        use std::io::Write;
272        let t = TestEnv::builder("/w").build();
273        let mut a = t.env.out.clone();
274        a.write_all(b"one ").unwrap();
275        t.env.out.write_str("two");
276        assert_eq!(t.out.text(), "one two");
277        assert_eq!(t.err.text(), "");
278    }
279}