1use 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
36pub const STRAY_ARGS: &str = "args";
38
39pub fn pflag_command(name: &'static str) -> Command {
43 Command::new(name)
44 .args_override_self(true)
45 .disable_help_subcommand(true)
46}
47
48fn 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 .hide_default_value(default == zero);
68 if let Some(c) = short {
69 arg = arg.short(c);
70 }
71 arg
72}
73
74pub 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
84pub 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
95pub 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
107pub 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
123pub fn stray_args() -> Arg {
126 Arg::new(STRAY_ARGS)
127 .num_args(0..)
128 .action(ArgAction::Append)
129 .hide(true)
130}
131
132pub fn passed(m: &ArgMatches, id: &str) -> bool {
134 matches!(m.value_source(id), Some(ValueSource::CommandLine))
135}
136
137pub 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
146pub 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
155pub 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
164pub 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
180fn 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
191fn 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
199pub 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 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 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
272fn 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 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 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 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 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 #[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}