Skip to main content

gadk_cli/
root.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 root command and its dispatch: the command tree `gadk` → `deploy` →
17//! {`agentengine`, `cloudrun`}, and the error reporting (`Error: <msg>` and the failing
18//! command's usage on stderr, exit 1).
19
20use std::ffi::OsString;
21
22use clap::Command;
23use clap::error::{ContextKind, ContextValue, ErrorKind};
24use gadk_platform::go_quote;
25
26use crate::Env;
27use crate::deploy::{self, agentengine, cloudrun};
28use crate::flags::{STRAY_ARGS, pflag_error};
29
30/// The root command's name.
31pub const NAME: &str = "gadk";
32// The root texts name gadk, not ADK's own tool.
33/// The root command's short description.
34pub const SHORT: &str = "CLI tool for use with gadk";
35/// The root command's long description.
36pub const LONG: &str =
37    "gadk is a CLI tool which allows developer to quickly deploy and test an agentic application";
38
39/// The root command with `deploy` added.
40// There is no `completion` command; clap's `help` subcommand is the only extra one.
41pub fn command() -> Command {
42    Command::new(NAME)
43        .about(SHORT)
44        .long_about(LONG)
45        .subcommand(deploy::command())
46}
47
48/// Parses `args` (program name first), runs the selected command and
49/// returns the exit code (0, or 1 after printing the error).
50pub async fn execute(args: Vec<OsString>, env: &Env) -> u8 {
51    let raw: Vec<String> = args
52        .iter()
53        .skip(1)
54        .map(|a| a.to_string_lossy().into_owned())
55        .collect();
56    let (path, rest) = match cobra_find(&raw) {
57        Found::Command { path, rest } => (path, rest),
58        Found::UnknownCommand(name) => return unknown_command(&name, env),
59    };
60    // clap parses the found command's own arguments: flags written before a subcommand name
61    // move after it, so every remaining argument is parsed with the found command's flags.
62    let argv: Vec<OsString> = args
63        .iter()
64        .take(1)
65        .cloned()
66        .chain(path.iter().map(OsString::from))
67        .chain(rest.iter().map(|&i| args[i + 1].clone()))
68        .collect();
69    let parsed: Vec<String> = rest.iter().map(|&i| raw[i].clone()).collect();
70    // A non-UTF-8 argument is a clap parse error.
71    let matches = match command().try_get_matches_from(&argv) {
72        Ok(m) => m,
73        Err(e) => return report_parse_error(&e, &path, &parsed, env),
74    };
75    let Some(("deploy", deploy_m)) = matches.subcommand() else {
76        // The root command is not runnable, so the help is printed.
77        env.out.write_str(&help(&[]));
78        return 0;
79    };
80    let result = match deploy_m.subcommand() {
81        Some(("cloudrun", m)) => {
82            let mut flags = cloudrun::from_matches(m);
83            (flags.deploy_on_cloud_run(env).await, "cloudrun")
84        }
85        Some(("agentengine", m)) => {
86            let result = match agentengine::validate_args(m) {
87                Ok(()) => {
88                    agentengine::from_matches(m)
89                        .deploy_on_agent_engine(env)
90                        .await
91                }
92                Err(e) => Err(e),
93            };
94            (result, "agentengine")
95        }
96        _ => {
97            // `deploy` prints its help when there are no arguments, else nothing.
98            if deploy_m.get_many::<String>(STRAY_ARGS).is_none() {
99                env.out.write_str(&help(&["deploy"]));
100            }
101            return 0;
102        }
103    };
104    match result {
105        (Ok(()), _) => 0,
106        (Err(err), sub) => report(env, &err, &["deploy", sub]),
107    }
108}
109
110/// The error report: `Error: <msg>`, then the command's usage and an empty line.
111fn report(env: &Env, msg: &str, path: &[&str]) -> u8 {
112    env.err.write_str(&format!("Error: {msg}\n"));
113    env.err.write_str(&format!("{}\n", usage(path)));
114    1
115}
116
117fn report_parse_error(e: &clap::Error, path: &[&str], args: &[String], env: &Env) -> u8 {
118    match e.kind() {
119        ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => {
120            env.out.write_str(&e.render().to_string());
121            0
122        }
123        ErrorKind::InvalidSubcommand => {
124            // clap's `help` subcommand naming an unknown command.
125            let name = match e.get(ContextKind::InvalidSubcommand) {
126                Some(ContextValue::String(s)) => s.clone(),
127                _ => args.first().cloned().unwrap_or_default(),
128            };
129            unknown_command(&name, env)
130        }
131        _ => {
132            let msg = pflag_error(e, &find(path), args);
133            report(env, &msg, path)
134        }
135    }
136}
137
138/// An unknown command at the root: the error, suggestions, and a pointer to
139/// `--help` instead of the usage.
140fn unknown_command(name: &str, env: &Env) -> u8 {
141    env.err.write_str(&format!(
142        "Error: unknown command {} for {}{}\n",
143        go_quote(name),
144        go_quote(NAME),
145        suggestions(name)
146    ));
147    env.err
148        .write_str(&format!("Run '{NAME} --help' for usage.\n"));
149    1
150}
151
152/// What the command search selects for the arguments after the program name.
153#[derive(Debug, PartialEq, Eq)]
154enum Found {
155    /// The command at `path`, to be parsed from the arguments at the indices `rest` (the
156    /// arguments without the subcommand names, in their original order).
157    Command {
158        path: Vec<&'static str>,
159        rest: Vec<usize>,
160    },
161    /// The first non-flag argument left at the root names no command.
162    UnknownCommand(String),
163}
164
165// Finds the command for the arguments. At each
166// level the first argument that is not a flag or a flag's value names the next subcommand,
167// and that one occurrence is removed. Neither `gadk` nor `deploy` has a flag at that point
168// (`-h/--help` is added to the found command only, later), so every `--x` and `-x`
169// written without `=` takes the next argument as its value: `gadk deploy -r x cloudrun` runs
170// cloudrun with region x, and `gadk -h deploy agentengine` is an unknown command
171// "agentengine".
172fn cobra_find(raw: &[String]) -> Found {
173    let mut path: Vec<&'static str> = Vec::new();
174    let mut rest: Vec<usize> = (0..raw.len()).collect();
175    let mut cmd = command();
176    loop {
177        let args: Vec<&str> = rest.iter().map(|&i| raw[i].as_str()).collect();
178        let Some(next) = strip_flags(&args).first().map(|s| s.to_string()) else {
179            break;
180        };
181        let Some(sub) = cmd
182            .get_subcommands()
183            .find(|s| s.get_name() == next)
184            .cloned()
185        else {
186            if !path.is_empty() {
187                break;
188            }
189            if next == "help" {
190                // clap's `help` subcommand parses the arguments as
191                // given.
192                return Found::Command {
193                    path,
194                    rest: (0..raw.len()).collect(),
195                };
196            }
197            return Found::UnknownCommand(next);
198        };
199        let name = match sub.get_name() {
200            "deploy" => "deploy",
201            "cloudrun" => "cloudrun",
202            "agentengine" => "agentengine",
203            _ => break,
204        };
205        if let Some(pos) = position_of_first(&args, name) {
206            rest.remove(pos);
207        }
208        path.push(name);
209        cmd = sub;
210    }
211    if path.is_empty() {
212        // The root is not runnable; the arguments after `--` are left alone and the
213        // help is printed (the root has no positional arguments in clap).
214        if let Some(end) = rest.iter().position(|&i| raw[i] == "--") {
215            rest.truncate(end);
216        }
217    }
218    Found::Command { path, rest }
219}
220
221/// Strips the flags from the arguments of a command without flags: `--x`/`-x` (no `=`) take the
222/// next argument, `--` ends the flags, and the other non-flag arguments are returned.
223fn strip_flags<'a>(args: &[&'a str]) -> Vec<&'a str> {
224    let mut commands = Vec::new();
225    let mut i = 0;
226    while i < args.len() {
227        let s = args[i];
228        i += 1;
229        if s == "--" {
230            break;
231        }
232        if takes_next(s) {
233            i += 1;
234        } else if !s.is_empty() && !s.starts_with('-') {
235            commands.push(s);
236        }
237    }
238    commands
239}
240
241/// The position of the first argument equal to `x` that is not a flag or
242/// a flag's value, before any `--`.
243fn position_of_first(args: &[&str], x: &str) -> Option<usize> {
244    let mut pos = 0;
245    while pos < args.len() {
246        let s = args[pos];
247        if s == "--" {
248            return None;
249        }
250        if takes_next(s) {
251            pos += 2;
252            continue;
253        }
254        if !s.starts_with('-') && s == x {
255            return Some(pos);
256        }
257        pos += 1;
258    }
259    None
260}
261
262/// A flag that takes the next argument during the command search: `--x` or a two-byte `-x`,
263/// without `=` (no flag of `gadk` or `deploy` has a no-option default at `Find` time).
264fn takes_next(s: &str) -> bool {
265    !s.contains('=') && (s.starts_with("--") || (s.starts_with('-') && s.len() == 2))
266}
267
268/// The built (`gadk deploy …`-named) subcommand at `path`.
269fn find(path: &[&str]) -> Command {
270    let mut cmd = command();
271    cmd.build();
272    for name in path {
273        let Some(sub) = cmd.find_subcommand(name).cloned() else {
274            break;
275        };
276        cmd = sub;
277    }
278    cmd
279}
280
281/// The usage string in clap's layout: the usage line and the argument list.
282// The layout is clap's.
283fn usage(path: &[&str]) -> String {
284    find(path)
285        .help_template("{usage-heading} {usage}\n\n{all-args}")
286        .render_help()
287        .to_string()
288}
289
290/// The help for the command at `path` in clap's layout.
291fn help(path: &[&str]) -> String {
292    find(path).render_long_help().to_string()
293}
294
295/// Suggestions for an unknown command at the root: each available subcommand within Levenshtein
296/// distance 2 (case-insensitive) of `typed`, or that `typed` prefixes.
297fn suggestions(typed: &str) -> String {
298    let names: Vec<String> = command()
299        .get_subcommands()
300        .map(|s| s.get_name().to_string())
301        .filter(|name| {
302            levenshtein_ignore_case(typed, name) <= 2
303                || name.to_lowercase().starts_with(&typed.to_lowercase())
304        })
305        .collect();
306    if names.is_empty() {
307        return String::new();
308    }
309    let mut s = String::from("\n\nDid you mean this?\n");
310    for name in names {
311        s.push_str(&format!("\t{name}\n"));
312    }
313    s
314}
315
316/// Byte-wise Levenshtein distance of the lowercased strings.
317fn levenshtein_ignore_case(s: &str, t: &str) -> usize {
318    let (s, t) = (s.to_lowercase().into_bytes(), t.to_lowercase().into_bytes());
319    let mut prev: Vec<usize> = (0..=t.len()).collect();
320    for (i, &sc) in s.iter().enumerate() {
321        let mut cur = vec![i + 1; t.len() + 1];
322        for (j, &tc) in t.iter().enumerate() {
323            cur[j + 1] = if sc == tc {
324                prev[j]
325            } else {
326                1 + prev[j].min(prev[j + 1]).min(cur[j])
327            };
328        }
329        prev = cur;
330    }
331    prev[t.len()]
332}
333
334#[cfg(test)]
335mod tests {
336    use pretty_assertions::assert_eq;
337
338    use super::*;
339    use crate::testutil::TestEnv;
340
341    async fn run(args: &[&str]) -> (u8, String, String) {
342        let t = TestEnv::builder("/w").build();
343        let args: Vec<OsString> = std::iter::once("gadk")
344            .chain(args.iter().copied())
345            .map(OsString::from)
346            .collect();
347        let code = execute(args, &t.env).await;
348        assert!(
349            t.runner.calls().is_empty(),
350            "a parse-only path ran a command"
351        );
352        (code, t.out.text(), t.err.text())
353    }
354
355    #[test]
356    fn the_tree_is_gadk_deploy_agentengine_cloudrun_with_go_texts() {
357        let root = command();
358        assert_eq!(root.get_name(), "gadk");
359        assert_eq!(
360            root.get_about().map(ToString::to_string).as_deref(),
361            Some(SHORT)
362        );
363        let deploy = root.find_subcommand("deploy").unwrap();
364        assert_eq!(
365            deploy.get_about().map(ToString::to_string).as_deref(),
366            Some("Makes deployment to various platforms easy")
367        );
368        assert_eq!(
369            deploy.get_long_about().map(ToString::to_string).as_deref(),
370            Some("Please see subcommands for details")
371        );
372        let subs: Vec<&str> = deploy.get_subcommands().map(Command::get_name).collect();
373        assert_eq!(subs, ["agentengine", "cloudrun"]);
374        assert_eq!(
375            deploy
376                .find_subcommand("cloudrun")
377                .unwrap()
378                .get_about()
379                .map(ToString::to_string)
380                .as_deref(),
381            Some("Deploys the application to cloudrun.")
382        );
383        assert_eq!(
384            deploy
385                .find_subcommand("agentengine")
386                .unwrap()
387                .get_about()
388                .map(ToString::to_string)
389                .as_deref(),
390            Some("Deploys the application to Agent Engine.")
391        );
392        root.debug_assert();
393    }
394
395    /// Every Go flag with Go's name, shorthand and default, plus gadk's `--bin`.
396    #[test]
397    fn deploy_subcommands_register_go_flags() {
398        let flags = |c: Command| -> Vec<(String, Option<char>, String)> {
399            c.get_arguments()
400                .filter(|a| a.get_long().is_some() && a.get_id() != "help")
401                .map(|a| {
402                    (
403                        a.get_long().unwrap_or_default().to_string(),
404                        a.get_short(),
405                        a.get_default_values()
406                            .iter()
407                            .map(|v| v.to_string_lossy().into_owned())
408                            .collect::<Vec<_>>()
409                            .join(","),
410                    )
411                })
412                .collect()
413        };
414        let own = |v: &[(&str, Option<char>, &str)]| -> Vec<(String, Option<char>, String)> {
415            v.iter()
416                .map(|(l, s, d)| (l.to_string(), *s, d.to_string()))
417                .collect()
418        };
419        assert_eq!(
420            flags(cloudrun::command()),
421            own(&[
422                ("region", Some('r'), ""),
423                ("project_name", Some('p'), ""),
424                ("service_name", Some('s'), ""),
425                ("temp_dir", Some('t'), ""),
426                ("proxy_port", None, "8081"),
427                ("server_port", None, "8080"),
428                ("entry_point_path", Some('e'), ""),
429                ("a2a", None, "true"),
430                ("a2a_agent_url", Some('a'), "http://127.0.0.1:8081"),
431                ("api", None, "true"),
432                ("debug_api", None, "false"),
433                ("webui", None, "true"),
434                ("pubsub", None, "false"),
435                ("pubsub_max_retries", None, "3"),
436                ("pubsub_base_delay", None, "1s"),
437                ("pubsub_max_delay", None, "10s"),
438                ("pubsub_max_concurrent_runs", None, "100"),
439                ("pubsub_oidc_audience", None, ""),
440                ("pubsub_oidc_service_accounts", None, ""),
441                ("eventarc", None, "false"),
442                ("eventarc_max_retries", None, "3"),
443                ("eventarc_base_delay", None, "1s"),
444                ("eventarc_max_delay", None, "10s"),
445                ("eventarc_max_concurrent_runs", None, "100"),
446                ("eventarc_oidc_audience", None, ""),
447                ("eventarc_oidc_service_accounts", None, ""),
448                ("bin", None, ""),
449            ])
450        );
451        assert_eq!(
452            flags(agentengine::command()),
453            own(&[
454                ("region", Some('r'), ""),
455                ("project_name", Some('p'), ""),
456                ("name", Some('s'), ""),
457                ("temp_dir", Some('t'), ""),
458                ("server_port", None, "8080"),
459                ("entry_point_path", Some('e'), ""),
460                ("source_dir", Some('d'), ""),
461                ("agent_engine_id", None, ""),
462                ("mem_deploy", None, "false"),
463                ("mem_model", None, ""),
464                ("mem_ttl", None, "8760h0m0s"),
465                ("env", None, ""),
466                ("default_env", None, "true"),
467                ("bin", None, ""),
468            ])
469        );
470    }
471
472    #[tokio::test]
473    async fn bare_gadk_and_bare_deploy_print_help_and_succeed() {
474        let (code, out, err) = run(&[]).await;
475        assert_eq!((code, err.as_str()), (0, ""));
476        assert!(out.contains(LONG), "{out}");
477        assert!(out.contains("deploy"), "{out}");
478
479        let (code, out, err) = run(&["deploy"]).await;
480        assert_eq!((code, err.as_str()), (0, ""));
481        assert!(out.contains("Please see subcommands for details"), "{out}");
482        assert!(
483            out.contains("agentengine") && out.contains("cloudrun"),
484            "{out}"
485        );
486    }
487
488    /// Go `DeployCmd.RunE` returns nil without printing when it has arguments.
489    #[tokio::test]
490    async fn deploy_with_a_stray_argument_does_nothing() {
491        assert_eq!(
492            run(&["deploy", "foo"]).await,
493            (0, String::new(), String::new())
494        );
495        assert_eq!(
496            run(&["deploy", "foo", "cloudrun"]).await,
497            (0, String::new(), String::new())
498        );
499    }
500
501    #[tokio::test]
502    async fn help_flags_print_help_to_stdout() {
503        let (code, out, err) = run(&["deploy", "cloudrun", "--help"]).await;
504        assert_eq!((code, err.as_str()), (0, ""));
505        assert!(out.contains("--entry_point_path"), "{out}");
506        assert!(out.contains("Usage: gadk deploy cloudrun"), "{out}");
507        let (code, out, _) = run(&["deploy", "agentengine", "-h"]).await;
508        assert_eq!(code, 0);
509        assert!(out.contains("--mem_ttl"), "{out}");
510    }
511
512    /// cobra: `Error: <pflag text>`, then the failing command's usage and an empty line, all
513    /// on stderr; exit 1.
514    #[tokio::test]
515    async fn parse_errors_print_error_and_usage_to_stderr() {
516        let (code, out, err) = run(&["deploy", "cloudrun", "--nope"]).await;
517        assert_eq!((code, out.as_str()), (1, ""));
518        let cloudrun_usage = usage(&["deploy", "cloudrun"]);
519        assert!(
520            cloudrun_usage.starts_with("Usage: gadk deploy cloudrun [OPTIONS]"),
521            "{cloudrun_usage}"
522        );
523        assert!(
524            cloudrun_usage.contains("--service_name"),
525            "{cloudrun_usage}"
526        );
527        assert_eq!(
528            err,
529            format!("Error: unknown flag: --nope\n{cloudrun_usage}\n")
530        );
531
532        let (code, _, err) = run(&["deploy", "agentengine", "--server_port=x"]).await;
533        assert_eq!(code, 1);
534        assert_eq!(
535            err,
536            format!(
537                "Error: invalid argument \"x\" for \"--server_port\" flag: strconv.ParseInt: parsing \"x\": invalid syntax\n{}\n",
538                usage(&["deploy", "agentengine"])
539            )
540        );
541
542        let (code, _, err) = run(&["deploy", "cloudrun", "-r"]).await;
543        assert_eq!(code, 1);
544        assert!(
545            err.starts_with(
546                "Error: flag needs an argument: 'r' in -r\nUsage: gadk deploy cloudrun"
547            ),
548            "{err}"
549        );
550
551        // Go: cobra Find/stripFlags. A flag before the subcommand name swallows the name as its
552        // value, so the parent command is found and fails on the flag.
553        for flag in ["--nope", "--a2a", "--region"] {
554            let (code, out, err) = run(&["deploy", flag, "cloudrun"]).await;
555            assert_eq!((code, out.as_str()), (1, ""));
556            assert_eq!(
557                err,
558                format!("Error: unknown flag: {flag}\n{}\n", usage(&["deploy"]))
559            );
560        }
561        let (code, _, err) = run(&["--region", "x"]).await;
562        assert_eq!(code, 1);
563        assert_eq!(
564            err,
565            format!("Error: unknown flag: --region\n{}\n", usage(&[]))
566        );
567        let (code, _, err) = run(&["-x", "deploy"]).await;
568        assert_eq!(code, 1);
569        assert_eq!(
570            err,
571            format!("Error: unknown shorthand flag: 'x' in -x\n{}\n", usage(&[]))
572        );
573    }
574
575    /// The arguments clap parses for `args` after cobra's `Find`: the command path, then the
576    /// remaining arguments in their original order.
577    fn found_argv(args: &[&str]) -> Vec<String> {
578        let raw: Vec<String> = args.iter().map(|s| s.to_string()).collect();
579        match cobra_find(&raw) {
580            Found::Command { path, rest } => path
581                .iter()
582                .map(|p| p.to_string())
583                .chain(rest.iter().map(|&i| raw[i].clone()))
584                .collect(),
585            Found::UnknownCommand(name) => panic!("unknown command {name:?}"),
586        }
587    }
588
589    /// Go: cobra Find/stripFlags. Flags written before a subcommand name are parsed by the
590    /// found subcommand (cobra v1.10.2: `adkgo deploy --region x cloudrun`, `adkgo --region x
591    /// deploy cloudrun` and `adkgo deploy -r x cloudrun` all run cloudrun with region "x").
592    #[test]
593    fn flags_before_the_subcommand_name_reach_the_subcommand() {
594        for args in [
595            &["deploy", "--region", "x", "cloudrun"][..],
596            &["--region", "x", "deploy", "cloudrun"],
597            &["deploy", "-r", "x", "cloudrun"],
598            &["-r", "x", "deploy", "cloudrun"],
599        ] {
600            let argv = found_argv(args);
601            assert_eq!(argv[..2], ["deploy", "cloudrun"], "{args:?}");
602            let m = command()
603                .try_get_matches_from(std::iter::once("gadk".to_string()).chain(argv))
604                .unwrap_or_else(|e| panic!("{args:?}: {e}"));
605            let (_, deploy_m) = m.subcommand().unwrap();
606            let (name, leaf) = deploy_m.subcommand().unwrap();
607            assert_eq!(name, "cloudrun");
608            assert_eq!(crate::flags::string_value(leaf, "region"), "x", "{args:?}");
609        }
610        // The flag's value may itself be a subcommand name; the next occurrence is the command.
611        assert_eq!(
612            found_argv(&[
613                "--region",
614                "cloudrun",
615                "deploy",
616                "cloudrun",
617                "--server_port",
618                "9"
619            ]),
620            [
621                "deploy",
622                "cloudrun",
623                "--region",
624                "cloudrun",
625                "--server_port",
626                "9"
627            ]
628        );
629        assert_eq!(
630            found_argv(&["deploy", "--server_port=9", "agentengine", "x"]),
631            ["deploy", "agentengine", "--server_port=9", "x"]
632        );
633        assert_eq!(
634            found_argv(&["deploy", "-rx", "cloudrun"]),
635            ["deploy", "cloudrun", "-rx"]
636        );
637    }
638
639    /// cobra registers `-h/--help` only on the found command, so during `Find` it swallows the
640    /// next argument like any other flag (cobra v1.10.2 output).
641    #[tokio::test]
642    async fn a_help_flag_before_the_subcommand_name_is_a_flag_of_the_parent() {
643        let (code, out, err) = run(&["-h", "deploy", "agentengine"]).await;
644        assert_eq!((code, out.as_str()), (1, ""));
645        assert_eq!(
646            err,
647            "Error: unknown command \"agentengine\" for \"gadk\"\nRun 'gadk --help' for usage.\n"
648        );
649        let (code, out, err) = run(&["deploy", "-h", "cloudrun"]).await;
650        assert_eq!((code, err.as_str()), (0, ""));
651        assert!(out.contains("Usage: gadk deploy [COMMAND]"), "{out}");
652        let (code, out, err) = run(&["-h", "foo"]).await;
653        assert_eq!((code, err.as_str()), (0, ""));
654        assert!(out.contains("Usage: gadk [COMMAND]"), "{out}");
655        let (code, out, err) = run(&["--", "foo"]).await;
656        assert_eq!((code, err.as_str()), (0, ""));
657        assert!(out.contains(LONG), "{out}");
658        let (code, _, err) = run(&["--region", "x", "foo"]).await;
659        assert_eq!(code, 1);
660        assert!(
661            err.starts_with("Error: unknown command \"foo\" for \"gadk\"\n"),
662            "{err}"
663        );
664    }
665
666    /// cobra `legacyArgs` on the root: no usage, a pointer to `--help`, suggestions when close.
667    #[tokio::test]
668    async fn an_unknown_root_command_is_cobra_unknown_command() {
669        let (code, out, err) = run(&["foo"]).await;
670        assert_eq!((code, out.as_str()), (1, ""));
671        assert_eq!(
672            err,
673            "Error: unknown command \"foo\" for \"gadk\"\nRun 'gadk --help' for usage.\n"
674        );
675        let (_, _, err) = run(&["deplo"]).await;
676        assert_eq!(
677            err,
678            "Error: unknown command \"deplo\" for \"gadk\"\n\nDid you mean this?\n\tdeploy\n\nRun 'gadk --help' for usage.\n"
679        );
680        let (_, _, err) = run(&["DEP"]).await;
681        assert!(err.contains("Did you mean this?\n\tdeploy\n"), "{err}");
682    }
683
684    #[test]
685    fn levenshtein_matches_cobra_ld() {
686        assert_eq!(levenshtein_ignore_case("deplo", "deploy"), 1);
687        assert_eq!(levenshtein_ignore_case("DEPLOY", "deploy"), 0);
688        assert_eq!(levenshtein_ignore_case("dpeloy", "deploy"), 2);
689        assert_eq!(levenshtein_ignore_case("", "abc"), 3);
690        assert_eq!(levenshtein_ignore_case("kitten", "sitting"), 3);
691    }
692
693    #[test]
694    fn cobra_find_follows_cobra() {
695        let f = |a: &[&str]| cobra_find(&a.iter().map(|s| s.to_string()).collect::<Vec<_>>());
696        let cmd = |path: &[&'static str], rest: &[usize]| Found::Command {
697            path: path.to_vec(),
698            rest: rest.to_vec(),
699        };
700        assert_eq!(
701            f(&["deploy", "cloudrun", "--x"]),
702            cmd(&["deploy", "cloudrun"], &[2])
703        );
704        assert_eq!(
705            f(&["-h", "deploy", "agentengine"]),
706            Found::UnknownCommand("agentengine".into())
707        );
708        assert_eq!(f(&["deploy", "x", "cloudrun"]), cmd(&["deploy"], &[1, 2]));
709        assert_eq!(f(&["deploy", "--", "cloudrun"]), cmd(&["deploy"], &[1, 2]));
710        assert_eq!(f(&["deploy", "-h", "cloudrun"]), cmd(&["deploy"], &[1, 2]));
711        assert_eq!(f(&["--", "deploy"]), cmd(&[], &[]));
712        assert_eq!(f(&["help", "deploy"]), cmd(&[], &[0, 1]));
713        assert_eq!(f(&["nope"]), Found::UnknownCommand("nope".into()));
714        assert_eq!(f(&[]), cmd(&[], &[]));
715    }
716}