Skip to main content

gadk_cli/
flags.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//! Command-line flag helpers for clap: the flag kinds the `gadk deploy` commands register
17//! (string, int, duration and bool flags) as clap builder [`Arg`]s that parse like ADK's CLI
18//! flags, the value readers, [`passed`] (the flag was on the command line) and the mapping of
19//! clap's parse errors to ADK's error texts ([`pflag_error`]).
20//!
21//! Rules reproduced: `--f=v` and `--f v`, `-f v`, `-fv` and `-f=v`; a value-taking flag
22//! takes the next argument even when it starts with `-`; a bool flag takes a value only as
23//! `--b=v`, so `--b v` sets it true and leaves `v` as an argument; a
24//! repeated flag keeps its last value; ints are parsed with the base chosen by the prefix
25//! (`0x`, `0o`, `0b`, a leading `0` for octal, else decimal) into an `i64`, bools accept
26//! `1 t T TRUE true True 0 f F FALSE false False`, and durations are signed sequences of
27//! decimal numbers with unit suffixes (`ns`, `us`, `ms`, `s`, `m`, `h`) such as `2h45m`; stray
28//! positional arguments are accepted and ignored.
29
30use clap::error::{ContextKind, ContextValue, ErrorKind};
31use clap::parser::ValueSource;
32use clap::{Arg, ArgAction, ArgMatches, Command};
33use gadk_platform::go_flag::{go_parse_bool, go_parse_int};
34use gadk_platform::{GoDuration, go_parse_duration, go_quote};
35
36/// The id of the hidden trailing positional that swallows stray arguments.
37pub const STRAY_ARGS: &str = "args";
38
39/// A subcommand whose flags are POSIX-style: a repeated flag overrides the
40/// earlier value instead of being a clap error, and there is no `help`
41/// subcommand (only the root has one).
42pub fn pflag_command(name: &'static str) -> Command {
43    Command::new(name)
44        .args_override_self(true)
45        .disable_help_subcommand(true)
46}
47
48/// A value-taking flag: exactly one value, which may start with `-` (the next
49/// argument is taken whatever it is).
50fn value_flag(
51    long: &'static str,
52    short: Option<char>,
53    default: &'static str,
54    help: &'static str,
55    value_name: &'static str,
56    zero: &'static str,
57) -> Arg {
58    let mut arg = Arg::new(long)
59        .long(long)
60        .help(help)
61        .value_name(value_name)
62        .action(ArgAction::Set)
63        .num_args(1)
64        .allow_hyphen_values(true)
65        .default_value(default)
66        // A `(default …)` is shown only for a non-zero default.
67        .hide_default_value(default == zero);
68    if let Some(c) = short {
69        arg = arg.short(c);
70    }
71    arg
72}
73
74/// A string flag.
75pub fn string_flag(
76    long: &'static str,
77    short: Option<char>,
78    default: &'static str,
79    help: &'static str,
80) -> Arg {
81    value_flag(long, short, default, help, "string", "")
82}
83
84/// An int flag: the value is an `i64` with the base chosen by its prefix (`0x`, `0o`, `0b`, a
85/// leading `0` for octal, else decimal).
86pub fn int_flag(
87    long: &'static str,
88    short: Option<char>,
89    default: &'static str,
90    help: &'static str,
91) -> Arg {
92    value_flag(long, short, default, help, "int", "0").value_parser(go_parse_int)
93}
94
95/// A duration flag: the value is a signed sequence of decimal numbers with unit suffixes
96/// (`ns`, `us`, `ms`, `s`, `m`, `h`); `default` is the text form of the default
97/// (e.g. `1s`, `8760h0m0s`).
98pub fn duration_flag(
99    long: &'static str,
100    short: Option<char>,
101    default: &'static str,
102    help: &'static str,
103) -> Arg {
104    value_flag(long, short, default, help, "duration", "0s").value_parser(go_parse_duration)
105}
106
107/// A bool flag: `--b` is true, `--b=<v>` takes a bool value (`1 t T TRUE true True 0 f F FALSE
108/// false False`); a value is never taken from the next argument.
109pub fn bool_flag(long: &'static str, default: bool, help: &'static str) -> Arg {
110    Arg::new(long)
111        .long(long)
112        .help(help)
113        .value_name("bool")
114        .action(ArgAction::Set)
115        .num_args(0..=1)
116        .require_equals(true)
117        .default_missing_value("true")
118        .default_value(if default { "true" } else { "false" })
119        .hide_default_value(!default)
120        .value_parser(go_parse_bool)
121}
122
123/// The hidden trailing positional: commands without a positional-argument validator accept and
124/// ignore positional arguments.
125pub fn stray_args() -> Arg {
126    Arg::new(STRAY_ARGS)
127        .num_args(0..)
128        .action(ArgAction::Append)
129        .hide(true)
130}
131
132/// Whether the flag was on the command line.
133pub fn passed(m: &ArgMatches, id: &str) -> bool {
134    matches!(m.value_source(id), Some(ValueSource::CommandLine))
135}
136
137/// A [`string_flag`]'s value (its default when absent).
138pub fn string_value(m: &ArgMatches, id: &str) -> String {
139    m.try_get_one::<String>(id)
140        .ok()
141        .flatten()
142        .cloned()
143        .unwrap_or_default()
144}
145
146/// An [`int_flag`]'s value.
147pub fn int_value(m: &ArgMatches, id: &str) -> i64 {
148    m.try_get_one::<i64>(id)
149        .ok()
150        .flatten()
151        .copied()
152        .unwrap_or_default()
153}
154
155/// A [`duration_flag`]'s value.
156pub fn duration_value(m: &ArgMatches, id: &str) -> GoDuration {
157    m.try_get_one::<GoDuration>(id)
158        .ok()
159        .flatten()
160        .copied()
161        .unwrap_or_default()
162}
163
164/// A [`bool_flag`]'s value.
165pub fn bool_value(m: &ArgMatches, id: &str) -> bool {
166    m.try_get_one::<bool>(id)
167        .ok()
168        .flatten()
169        .copied()
170        .unwrap_or_default()
171}
172
173fn context_str(e: &clap::Error, kind: ContextKind) -> Option<&str> {
174    match e.get(kind) {
175        Some(ContextValue::String(s)) => Some(s.as_str()),
176        _ => None,
177    }
178}
179
180/// A rune quoted with single quotes, as in `'x'`.
181fn quote_rune(c: char) -> String {
182    let q = go_quote(&c.to_string());
183    let inner = &q[1..q.len() - 1];
184    let inner = if inner == "\\\"" { "\"" } else { inner };
185    if inner == "'" {
186        return "'\\''".to_string();
187    }
188    format!("'{inner}'")
189}
190
191/// The long name in clap's rendering of an argument (`--region <string>`,
192/// `--a2a[=<bool>]`).
193fn long_name(rendered: &str) -> &str {
194    let s = rendered.trim_start_matches('-');
195    let end = s.find([' ', '[', '=']).unwrap_or(s.len());
196    &s[..end]
197}
198
199/// ADK's error text for clap's parse error `e` on `cmd` (the subcommand being parsed);
200/// `raw` are the command-line arguments, used where clap does not keep what ADK's text reports
201/// (the token an unknown shorthand came from, whether a value-less flag was written short).
202/// Errors with no ADK text keep clap's message.
203pub fn pflag_error(e: &clap::Error, cmd: &Command, raw: &[String]) -> String {
204    match e.kind() {
205        ErrorKind::UnknownArgument => {
206            let arg = context_str(e, ContextKind::InvalidArg).unwrap_or_default();
207            if let Some(name) = arg.strip_prefix("--") {
208                if name.is_empty() || name.starts_with(['-', '=']) {
209                    return format!("bad flag syntax: {arg}");
210                }
211                let name = name.split('=').next().unwrap_or(name);
212                return format!("unknown flag: --{name}");
213            }
214            if let Some(c) = arg.strip_prefix('-').and_then(|s| s.chars().next()) {
215                // ADK names the shorthands left in the token from the unknown one on; an
216                // unknown shorthand is always first in its token here (every gadk shorthand
217                // takes a value, which swallows the rest of its token).
218                let start = format!("-{c}");
219                let shorthands = raw
220                    .iter()
221                    .find(|t| t.starts_with(&start) && !t.starts_with("--"))
222                    .map(|t| &t[1..])
223                    .unwrap_or(&arg[1..]);
224                return format!("unknown shorthand flag: {} in -{shorthands}", quote_rune(c));
225            }
226            clap_message(e)
227        }
228        ErrorKind::InvalidValue
229            if context_str(e, ContextKind::InvalidValue) == Some("")
230                && std::error::Error::source(e).is_none() =>
231        {
232            // A value-taking flag was the last argument (any later one would be its value).
233            match raw.last() {
234                Some(last) if last.starts_with("--") => {
235                    format!(
236                        "flag needs an argument: {}",
237                        last.split('=').next().unwrap_or(last)
238                    )
239                }
240                Some(last) if last.starts_with('-') => {
241                    let c = last.chars().last().unwrap_or('-');
242                    format!("flag needs an argument: {} in -{c}", quote_rune(c))
243                }
244                _ => clap_message(e),
245            }
246        }
247        ErrorKind::ValueValidation => {
248            let rendered = context_str(e, ContextKind::InvalidArg).unwrap_or_default();
249            let long = long_name(rendered);
250            let short = cmd
251                .get_arguments()
252                .find(|a| a.get_long() == Some(long))
253                .and_then(Arg::get_short);
254            let flag = match short {
255                Some(s) => format!("-{s}, --{long}"),
256                None => format!("--{long}"),
257            };
258            let value = context_str(e, ContextKind::InvalidValue).unwrap_or_default();
259            let cause = std::error::Error::source(e)
260                .map(ToString::to_string)
261                .unwrap_or_default();
262            format!(
263                "invalid argument {} for {} flag: {cause}",
264                go_quote(value),
265                go_quote(&flag)
266            )
267        }
268        _ => clap_message(e),
269    }
270}
271
272/// clap's own message for `e`: its first line without the `error: ` prefix.
273fn clap_message(e: &clap::Error) -> String {
274    let rendered = e.render().to_string();
275    let first = rendered.lines().next().unwrap_or_default();
276    first.strip_prefix("error: ").unwrap_or(first).to_string()
277}
278
279#[cfg(test)]
280mod tests {
281    use pretty_assertions::assert_eq;
282
283    use super::*;
284
285    fn cmd() -> Command {
286        pflag_command("t")
287            .arg(string_flag("region", Some('r'), "", "GCP Region"))
288            .arg(string_flag("pubsub_oidc_audience", None, "", "aud"))
289            .arg(string_flag("eventarc_oidc_audience", None, "", "aud"))
290            .arg(string_flag(
291                "a2a_agent_url",
292                Some('a'),
293                "http://127.0.0.1:8081",
294                "url",
295            ))
296            .arg(int_flag("server_port", None, "8080", "port"))
297            .arg(duration_flag("mem_ttl", None, "8760h0m0s", "ttl"))
298            .arg(bool_flag("a2a", true, "Enable A2A"))
299            .arg(bool_flag("pubsub", false, "Enable PubSub"))
300            .arg(stray_args())
301    }
302
303    fn parse(args: &[&str]) -> Result<ArgMatches, String> {
304        let raw: Vec<String> = std::iter::once("t")
305            .chain(args.iter().copied())
306            .map(str::to_string)
307            .collect();
308        let c = cmd();
309        c.clone()
310            .try_get_matches_from(&raw)
311            .map_err(|e| pflag_error(&e, &c, &raw[1..]))
312    }
313
314    fn stray(m: &ArgMatches) -> Vec<String> {
315        m.get_many::<String>(STRAY_ARGS)
316            .map(|v| v.cloned().collect())
317            .unwrap_or_default()
318    }
319
320    #[test]
321    fn defaults_are_go_defaults_and_not_passed() {
322        let m = parse(&[]).unwrap();
323        assert_eq!(string_value(&m, "region"), "");
324        assert_eq!(string_value(&m, "a2a_agent_url"), "http://127.0.0.1:8081");
325        assert_eq!(int_value(&m, "server_port"), 8080);
326        assert_eq!(
327            duration_value(&m, "mem_ttl"),
328            GoDuration(8760 * 3600 * 1_000_000_000)
329        );
330        assert!(bool_value(&m, "a2a"));
331        assert!(!bool_value(&m, "pubsub"));
332        for id in [
333            "region",
334            "a2a_agent_url",
335            "server_port",
336            "mem_ttl",
337            "a2a",
338            "pubsub",
339        ] {
340            assert!(!passed(&m, id), "{id}");
341        }
342        assert_eq!(stray(&m), Vec::<String>::new());
343    }
344
345    #[test]
346    fn bool_flags_take_a_value_only_after_equals() {
347        let m = parse(&["--a2a=false"]).unwrap();
348        assert!(!bool_value(&m, "a2a"));
349        assert!(passed(&m, "a2a"));
350        let m = parse(&["--pubsub"]).unwrap();
351        assert!(bool_value(&m, "pubsub"));
352        assert!(passed(&m, "pubsub"));
353        // pflag: `--a2a false` is `--a2a` (true) and a stray `false`.
354        let m = parse(&["--a2a", "false"]).unwrap();
355        assert!(bool_value(&m, "a2a"));
356        assert_eq!(stray(&m), ["false"]);
357        for (v, want) in [
358            ("1", true),
359            ("t", true),
360            ("TRUE", true),
361            ("0", false),
362            ("F", false),
363        ] {
364            let m = parse(&[&format!("--pubsub={v}")]).unwrap();
365            assert_eq!(bool_value(&m, "pubsub"), want, "{v}");
366        }
367        // The last occurrence wins.
368        let m = parse(&["--a2a", "--a2a=false"]).unwrap();
369        assert!(!bool_value(&m, "a2a"));
370    }
371
372    #[test]
373    fn value_flags_accept_every_pflag_spelling() {
374        for args in [
375            &["-r", "x"][..],
376            &["-rx"],
377            &["-r=x"],
378            &["--region", "x"],
379            &["--region=x"],
380            &["-r", "y", "--region", "x"],
381        ] {
382            let m = parse(args).unwrap();
383            assert_eq!(string_value(&m, "region"), "x", "{args:?}");
384            assert!(passed(&m, "region"), "{args:?}");
385        }
386        // The next argument is the value even when it starts with `-`.
387        for args in [&["--region", "-y"][..], &["--region=-y"], &["-r", "-y"]] {
388            assert_eq!(
389                string_value(&parse(args).unwrap(), "region"),
390                "-y",
391                "{args:?}"
392            );
393        }
394        let m = parse(&[
395            "--pubsub_oidc_audience",
396            "--eventarc_oidc_audience",
397            "https://svc.run.app",
398        ])
399        .unwrap();
400        assert_eq!(
401            string_value(&m, "pubsub_oidc_audience"),
402            "--eventarc_oidc_audience"
403        );
404        assert!(!passed(&m, "eventarc_oidc_audience"));
405        assert_eq!(stray(&m), ["https://svc.run.app"]);
406        // An explicitly empty value is passed.
407        let m = parse(&["--region="]).unwrap();
408        assert_eq!(string_value(&m, "region"), "");
409        assert!(passed(&m, "region"));
410    }
411
412    #[test]
413    fn ints_are_go_parse_int_base_0() {
414        for (v, want) in [
415            ("9090", 9090),
416            ("0x10", 16),
417            ("010", 8),
418            ("0o10", 8),
419            ("0b1", 1),
420            ("1_000", 1000),
421            ("-1", -1),
422            ("+7", 7),
423        ] {
424            let m = parse(&["--server_port", v]).unwrap();
425            assert_eq!(int_value(&m, "server_port"), want, "{v}");
426        }
427    }
428
429    #[test]
430    fn durations_are_go_parse_duration() {
431        for (v, want) in [
432            ("1s", 1_000_000_000),
433            ("1h30m", 5_400_000_000_000),
434            ("1.5s", 1_500_000_000),
435            ("300ms", 300_000_000),
436            ("0", 0),
437            ("-2m", -120_000_000_000),
438        ] {
439            let m = parse(&[&format!("--mem_ttl={v}")]).unwrap();
440            assert_eq!(duration_value(&m, "mem_ttl"), GoDuration(want), "{v}");
441        }
442    }
443
444    #[test]
445    fn stray_positionals_are_accepted_and_ignored() {
446        let m = parse(&["a", "-r", "x", "b", "--", "--c", "-"]).unwrap();
447        assert_eq!(string_value(&m, "region"), "x");
448        assert_eq!(stray(&m), ["a", "b", "--c", "-"]);
449    }
450
451    /// pflag's error texts (`errors.go`; the cause is the value's Go parse error).
452    #[test]
453    fn parse_errors_are_pflag_texts() {
454        let cases: &[(&[&str], &str)] = &[
455            (&["--nope"], "unknown flag: --nope"),
456            (&["--nope=3"], "unknown flag: --nope"),
457            (&["-r", "x", "-x"], "unknown shorthand flag: 'x' in -x"),
458            (&["-xyz"], "unknown shorthand flag: 'x' in -xyz"),
459            (&["---x"], "bad flag syntax: ---x"),
460            (&["--region"], "flag needs an argument: --region"),
461            (&["-r"], "flag needs an argument: 'r' in -r"),
462            (&["--a2a", "-a"], "flag needs an argument: 'a' in -a"),
463            (
464                &["--server_port=x"],
465                r#"invalid argument "x" for "--server_port" flag: strconv.ParseInt: parsing "x": invalid syntax"#,
466            ),
467            (
468                &["--server_port", "99999999999999999999"],
469                r#"invalid argument "99999999999999999999" for "--server_port" flag: strconv.ParseInt: parsing "99999999999999999999": value out of range"#,
470            ),
471            (
472                &["--a2a=x"],
473                r#"invalid argument "x" for "--a2a" flag: strconv.ParseBool: parsing "x": invalid syntax"#,
474            ),
475            (
476                &["--a2a="],
477                r#"invalid argument "" for "--a2a" flag: strconv.ParseBool: parsing "": invalid syntax"#,
478            ),
479            (
480                &["--mem_ttl", "1d"],
481                r#"invalid argument "1d" for "--mem_ttl" flag: time: unknown unit "d" in duration "1d""#,
482            ),
483        ];
484        for (args, want) in cases {
485            assert_eq!(parse(args).unwrap_err(), *want, "{args:?}");
486        }
487    }
488
489    #[test]
490    fn invalid_value_of_a_flag_with_a_shorthand_names_both() {
491        let c = pflag_command("t").arg(
492            Arg::new("port")
493                .long("port")
494                .short('p')
495                .num_args(1)
496                .value_parser(go_parse_int),
497        );
498        let raw = vec!["t".to_string(), "-p".to_string(), "x".to_string()];
499        let e = c.clone().try_get_matches_from(&raw).unwrap_err();
500        assert_eq!(
501            pflag_error(&e, &c, &raw[1..]),
502            r#"invalid argument "x" for "-p, --port" flag: strconv.ParseInt: parsing "x": invalid syntax"#
503        );
504    }
505
506    #[test]
507    fn quote_rune_is_go_percent_q_of_a_rune() {
508        assert_eq!(quote_rune('x'), "'x'");
509        assert_eq!(quote_rune('é'), "'é'");
510        assert_eq!(quote_rune('\''), "'\\''");
511        assert_eq!(quote_rune('"'), "'\"'");
512    }
513}