Skip to main content

gadk_platform/
go_flag.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//! A command-line flag parser: a [`FlagSet`] that reports errors instead of exiting, with
17//! string, int, int64, bool, duration, func and bool-func flags. The flag-parsing rules and
18//! error texts, the usage message written on failure and the `print_defaults` layout are
19//! byte-identical to an ADK launcher's.
20
21use std::collections::{BTreeMap, BTreeSet};
22use std::fmt;
23use std::io::Write;
24use std::sync::{Arc, Mutex, MutexGuard, PoisonError};
25
26use crate::{GoDuration, go_format_duration, go_parse_duration, go_quote};
27
28/// Text of the error returned for `-h`/`-help`.
29const ERR_HELP: &str = "flag: help requested";
30/// Text of a malformed-value error.
31const ERR_PARSE: &str = "parse error";
32/// Text of an out-of-range-value error.
33const ERR_RANGE: &str = "value out of range";
34
35/// A registered flag's current value, readable after `parse` (cheap clone; shared with the set).
36#[derive(Clone)]
37pub struct Flag<T> {
38    value: Arc<Mutex<T>>,
39}
40
41impl<T: Clone> Flag<T> {
42    /// The flag's current value: its default until `parse` sets it.
43    pub fn get(&self) -> T {
44        lock(&self.value).clone()
45    }
46}
47
48impl<T: Clone + fmt::Debug> fmt::Debug for Flag<T> {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        f.debug_tuple("Flag").field(&self.get()).finish()
51    }
52}
53
54impl<T> Flag<T> {
55    fn new(value: T) -> Flag<T> {
56        Flag {
57            value: Arc::new(Mutex::new(value)),
58        }
59    }
60
61    fn set(&self, value: T) {
62        *lock(&self.value) = value;
63    }
64}
65
66/// A parse failure; `Display` is the message that [`FlagSet::parse`] reports.
67#[derive(Debug, Clone, PartialEq, Eq)]
68pub struct FlagError {
69    /// The error text, e.g. `flag: help requested` or `invalid value "v" for flag -name: ...`.
70    pub message: String,
71}
72
73impl FlagError {
74    /// True for the help-requested error (`flag: help requested`).
75    pub fn is_help(&self) -> bool {
76        self.message == ERR_HELP
77    }
78}
79
80impl fmt::Display for FlagError {
81    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
82        f.write_str(&self.message)
83    }
84}
85
86impl std::error::Error for FlagError {}
87
88/// A func flag's callback: `Err(text)` becomes `invalid value "v" for flag -name: text`.
89pub type FlagFunc = Box<dyn FnMut(&str) -> Result<(), String> + Send>;
90
91/// The value behind a flag: bool, int, int64, string, duration, func or bool-func.
92enum Value {
93    Bool(Flag<bool>),
94    Int(Flag<i64>),
95    Int64(Flag<i64>),
96    String(Flag<String>),
97    Duration(Flag<GoDuration>),
98    Func(FlagFunc),
99    BoolFunc(FlagFunc),
100}
101
102impl Value {
103    /// Sets the value from `s`; `Err` is the error's text.
104    fn set(&mut self, s: &str) -> Result<(), String> {
105        match self {
106            Value::Bool(v) => {
107                let parsed = parse_bool(s);
108                v.set(parsed.unwrap_or(false));
109                parsed.map(|_| ()).ok_or_else(|| ERR_PARSE.to_string())
110            }
111            Value::Int(v) | Value::Int64(v) => match parse_int(s) {
112                Ok(n) => {
113                    v.set(n);
114                    Ok(())
115                }
116                Err(IntError::Syntax) => {
117                    v.set(0);
118                    Err(ERR_PARSE.to_string())
119                }
120                Err(IntError::Range(n)) => {
121                    v.set(n);
122                    Err(ERR_RANGE.to_string())
123                }
124            },
125            Value::String(v) => {
126                v.set(s.to_string());
127                Ok(())
128            }
129            Value::Duration(v) => {
130                let parsed = go_parse_duration(s);
131                v.set(parsed.clone().unwrap_or_default());
132                parsed.map(|_| ()).map_err(|_| ERR_PARSE.to_string())
133            }
134            Value::Func(f) | Value::BoolFunc(f) => f(s),
135        }
136    }
137
138    /// The value rendered as text.
139    fn string(&self) -> String {
140        match self {
141            Value::Bool(v) => v.get().to_string(),
142            Value::Int(v) | Value::Int64(v) => v.get().to_string(),
143            Value::String(v) => v.get(),
144            Value::Duration(v) => go_format_duration(v.get()),
145            Value::Func(_) | Value::BoolFunc(_) => String::new(),
146        }
147    }
148
149    /// The text of the type's zero value, used to decide whether a default is printed.
150    fn zero_string(&self) -> &'static str {
151        match self {
152            Value::Bool(_) => "false",
153            Value::Int(_) | Value::Int64(_) => "0",
154            Value::Duration(_) => "0s",
155            Value::String(_) | Value::Func(_) | Value::BoolFunc(_) => "",
156        }
157    }
158
159    /// True for flags that may be given without a value.
160    fn is_bool_flag(&self) -> bool {
161        matches!(self, Value::Bool(_) | Value::BoolFunc(_))
162    }
163
164    /// The placeholder `UnquoteUsage` derives from the value's type.
165    fn type_name(&self) -> &'static str {
166        match self {
167            Value::Bool(_) | Value::BoolFunc(_) => "",
168            Value::Duration(_) => "duration",
169            Value::Int(_) | Value::Int64(_) => "int",
170            Value::String(_) => "string",
171            Value::Func(_) => "value",
172        }
173    }
174}
175
176/// A defined flag: its name, usage text, value and default.
177struct FlagDef {
178    name: String,
179    usage: String,
180    value: Value,
181    def_value: String,
182}
183
184/// A set of flags that reports parse failures as errors (the only mode the launcher uses).
185pub struct FlagSet {
186    name: String,
187    parsed: bool,
188    actual: BTreeSet<String>,
189    formal: BTreeMap<String, FlagDef>,
190    args: Vec<String>,
191    output: Arc<Mutex<dyn Write + Send>>,
192}
193
194impl fmt::Debug for FlagSet {
195    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
196        f.debug_struct("FlagSet")
197            .field("name", &self.name)
198            .field("parsed", &self.parsed)
199            .field("flags", &self.formal.keys().collect::<Vec<_>>())
200            .field("args", &self.args)
201            .finish()
202    }
203}
204
205impl FlagSet {
206    /// An empty flag set named `name`; output goes to stderr.
207    pub fn new(name: &str) -> FlagSet {
208        FlagSet {
209            name: name.to_string(),
210            parsed: false,
211            actual: BTreeSet::new(),
212            formal: BTreeMap::new(),
213            args: Vec::new(),
214            output: Arc::new(Mutex::new(std::io::stderr())),
215        }
216    }
217
218    /// The name of the flag set.
219    pub fn name(&self) -> &str {
220        &self.name
221    }
222
223    /// Defines a string flag.
224    pub fn string(&mut self, name: &str, value: &str, usage: &str) -> Flag<String> {
225        let flag = Flag::new(value.to_string());
226        self.var(Value::String(flag.clone()), name, usage);
227        flag
228    }
229
230    /// Defines an int flag (64 bits on every platform gadk supports).
231    pub fn int(&mut self, name: &str, value: i64, usage: &str) -> Flag<i64> {
232        let flag = Flag::new(value);
233        self.var(Value::Int(flag.clone()), name, usage);
234        flag
235    }
236
237    /// Defines an int64 flag.
238    pub fn int64(&mut self, name: &str, value: i64, usage: &str) -> Flag<i64> {
239        let flag = Flag::new(value);
240        self.var(Value::Int64(flag.clone()), name, usage);
241        flag
242    }
243
244    /// Defines a bool flag.
245    pub fn bool(&mut self, name: &str, value: bool, usage: &str) -> Flag<bool> {
246        let flag = Flag::new(value);
247        self.var(Value::Bool(flag.clone()), name, usage);
248        flag
249    }
250
251    /// Defines a duration flag.
252    pub fn duration(&mut self, name: &str, value: GoDuration, usage: &str) -> Flag<GoDuration> {
253        let flag = Flag::new(value);
254        self.var(Value::Duration(flag.clone()), name, usage);
255        flag
256    }
257
258    /// Defines a func flag: `f` is called with the value each time the flag is seen.
259    pub fn func(&mut self, name: &str, usage: &str, f: FlagFunc) {
260        self.var(Value::Func(f), name, usage);
261    }
262
263    /// Defines a bool-func flag: like [`FlagSet::func`], but the flag takes no value (`-name`
264    /// calls `f` with `"true"`; `-name=v` with `v`).
265    pub fn bool_func(&mut self, name: &str, usage: &str, f: FlagFunc) {
266        self.var(Value::BoolFunc(f), name, usage);
267    }
268
269    /// Registers a flag. A name that begins with `-`, contains `=` or is already defined gets
270    /// its message written to the output; the definition is then ignored (the returned handle
271    /// keeps its default).
272    fn var(&mut self, value: Value, name: &str, usage: &str) {
273        let problem = if name.starts_with('-') {
274            Some(format!("flag {} begins with -", go_quote(name)))
275        } else if name.contains('=') {
276            Some(format!("flag {} contains =", go_quote(name)))
277        } else if self.formal.contains_key(name) {
278            Some(if self.name.is_empty() {
279                format!("flag redefined: {name}")
280            } else {
281                format!("{} flag redefined: {name}", self.name)
282            })
283        } else {
284            None
285        };
286        if let Some(msg) = problem {
287            self.write(&format!("{msg}\n"));
288            return;
289        }
290        let def_value = value.string();
291        self.formal.insert(
292            name.to_string(),
293            FlagDef {
294                name: name.to_string(),
295                usage: usage.to_string(),
296                value,
297                def_value,
298            },
299        );
300    }
301
302    /// Parses `args`. On failure writes the error line, then `Usage of <name>:` and
303    /// `print_defaults()` to the output sink, and returns the error; `-h`/`-help` writes the
304    /// usage and returns `flag: help requested`.
305    pub fn parse(&mut self, args: &[String]) -> Result<(), FlagError> {
306        self.parsed = true;
307        self.args = args.to_vec();
308        while self.parse_one()? {}
309        Ok(())
310    }
311
312    /// Parses one flag and reports whether a flag was seen.
313    fn parse_one(&mut self) -> Result<bool, FlagError> {
314        let Some(s) = self.args.first().cloned() else {
315            return Ok(false);
316        };
317        let bytes = s.as_bytes();
318        if bytes.len() < 2 || bytes[0] != b'-' {
319            return Ok(false);
320        }
321        let mut num_minuses = 1;
322        if bytes[1] == b'-' {
323            num_minuses += 1;
324            if bytes.len() == 2 {
325                // "--" terminates the flags.
326                self.args.remove(0);
327                return Ok(false);
328            }
329        }
330        let mut name = &s[num_minuses..];
331        if name.is_empty() || name.starts_with('-') || name.starts_with('=') {
332            return Err(self.failf(format!("bad flag syntax: {s}")));
333        }
334
335        // It's a flag. Does it have an argument? ('=' cannot be first.)
336        self.args.remove(0);
337        let mut value: Option<String> = None;
338        if let Some(i) = name.bytes().skip(1).position(|c| c == b'=') {
339            let eq = i + 1;
340            value = Some(name[eq + 1..].to_string());
341            name = &name[..eq];
342        }
343        let name = name.to_string();
344
345        let Some(mut flag) = self.formal.remove(&name) else {
346            if name == "help" || name == "h" {
347                // Special case for a nice help message.
348                self.usage();
349                return Err(FlagError {
350                    message: ERR_HELP.to_string(),
351                });
352            }
353            return Err(self.failf(format!("flag provided but not defined: -{name}")));
354        };
355        let result = if flag.value.is_bool_flag() {
356            // Special case: doesn't need an argument.
357            match value {
358                Some(value) => flag.value.set(&value).map_err(|err| {
359                    format!(
360                        "invalid boolean value {} for -{name}: {err}",
361                        go_quote(&value)
362                    )
363                }),
364                None => flag
365                    .value
366                    .set("true")
367                    .map_err(|err| format!("invalid boolean flag {name}: {err}")),
368            }
369        } else {
370            // It must have a value, which might be the next argument.
371            if value.is_none() && !self.args.is_empty() {
372                value = Some(self.args.remove(0));
373            }
374            match value {
375                None => Err(format!("flag needs an argument: -{name}")),
376                Some(value) => flag.value.set(&value).map_err(|err| {
377                    format!("invalid value {} for flag -{name}: {err}", go_quote(&value))
378                }),
379            }
380        };
381        self.formal.insert(name.clone(), flag);
382        match result {
383            Ok(()) => {
384                self.actual.insert(name);
385                Ok(true)
386            }
387            Err(msg) => Err(self.failf(msg)),
388        }
389    }
390
391    /// Whether [`FlagSet::parse`] has been called.
392    pub fn parsed(&self) -> bool {
393        self.parsed
394    }
395
396    /// The arguments after the flags.
397    pub fn args(&self) -> Vec<String> {
398        self.args.clone()
399    }
400
401    /// Whether the flag was set on the command line.
402    pub fn is_set(&self, name: &str) -> bool {
403        self.actual.contains(name)
404    }
405
406    /// Replaces the output sink; the default is stderr.
407    pub fn set_output(&mut self, out: Arc<Mutex<dyn Write + Send>>) {
408        self.output = out;
409    }
410
411    /// The defaults listing as a string: one entry per flag in name order,
412    /// `  -name placeholder` (the placeholder from a back-quoted word in the usage, else the
413    /// value type; none for a bool), the usage on the same line after a tab for a one-letter
414    /// bool flag and on the next line after four spaces and a tab otherwise, and
415    /// ` (default v)` (string defaults quoted) when the default is not the type's zero value.
416    pub fn print_defaults(&self) -> String {
417        let mut out = String::new();
418        for flag in self.formal.values() {
419            let mut b = format!("  -{}", flag.name);
420            let (name, usage) = unquote_usage(flag);
421            if !name.is_empty() {
422                b.push(' ');
423                b.push_str(&name);
424            }
425            // Boolean flags of one ASCII letter are so common that their usage goes on the same
426            // line.
427            if b.len() <= 4 {
428                b.push('\t');
429            } else {
430                b.push_str("\n    \t");
431            }
432            b.push_str(&usage.replace('\n', "\n    \t"));
433            if flag.def_value != flag.value.zero_string() {
434                if matches!(flag.value, Value::String(_)) {
435                    b.push_str(&format!(" (default {})", go_quote(&flag.def_value)));
436                } else {
437                    b.push_str(&format!(" (default {})", flag.def_value));
438                }
439            }
440            out.push_str(&b);
441            out.push('\n');
442        }
443        out
444    }
445
446    /// Writes the message and the usage, and returns the message as the error.
447    fn failf(&self, message: String) -> FlagError {
448        self.write(&format!("{message}\n"));
449        self.usage();
450        FlagError { message }
451    }
452
453    /// Writes the default usage message.
454    fn usage(&self) {
455        let header = if self.name.is_empty() {
456            "Usage:\n".to_string()
457        } else {
458            format!("Usage of {}:\n", self.name)
459        };
460        self.write(&header);
461        self.write(&self.print_defaults());
462    }
463
464    /// Writes to the output sink; write errors are ignored.
465    fn write(&self, s: &str) {
466        let mut out = lock(&self.output);
467        let _ = out.write_all(s.as_bytes());
468        let _ = out.flush();
469    }
470}
471
472/// The placeholder for a flag: the first back-quoted word of the usage (the back quotes are
473/// removed from the usage), else the value type's name.
474fn unquote_usage(flag: &FlagDef) -> (String, String) {
475    let usage = &flag.usage;
476    // With only one back quote, the type name is used.
477    if let Some(i) = usage.find('`')
478        && let Some(len) = usage[i + 1..].find('`')
479    {
480        let j = i + 1 + len;
481        let name = &usage[i + 1..j];
482        return (
483            name.to_string(),
484            format!("{}{name}{}", &usage[..i], &usage[j + 1..]),
485        );
486    }
487    (flag.value.type_name().to_string(), usage.clone())
488}
489
490/// Parses a bool: `1`, `t`, `T`, `TRUE`, `true`, `True` and the false spellings.
491fn parse_bool(s: &str) -> Option<bool> {
492    match s {
493        "1" | "t" | "T" | "true" | "TRUE" | "True" => Some(true),
494        "0" | "f" | "F" | "false" | "FALSE" | "False" => Some(false),
495        _ => None,
496    }
497}
498
499/// Parses a bool; `Err` is the parse error text (`parsing "<s>" as a boolean: invalid syntax`),
500/// the message for an invalid bool flag value.
501pub fn go_parse_bool(s: &str) -> Result<bool, String> {
502    parse_bool(s).ok_or_else(|| num_error("a boolean", s, "invalid syntax"))
503}
504
505/// Parses an int64 (optional sign, base prefix `0x`/`0o`/`0b`/`0`, underscores); `Err` is
506/// the parse error text (`parsing "<s>" as an integer: invalid syntax` or `…: value out of
507/// range`), the messages for an invalid int flag value.
508pub fn go_parse_int(s: &str) -> Result<i64, String> {
509    parse_int(s).map_err(|e| match e {
510        IntError::Syntax => num_error("an integer", s, "invalid syntax"),
511        IntError::Range(_) => num_error("an integer", s, "value out of range"),
512    })
513}
514
515/// The text `parsing <quoted num> as <what>: <err>`.
516fn num_error(what: &str, num: &str, err: &str) -> String {
517    format!("parsing {} as {what}: {err}", go_quote(num))
518}
519
520/// An integer-parse failure.
521enum IntError {
522    /// Malformed number (the `parse error` text).
523    Syntax,
524    /// Out of range (the `value out of range` text), with the clamped value that is stored.
525    Range(i64),
526}
527
528/// Parses an int64 with a base prefix (`0x`, `0o`, `0b`, `0`) and underscores.
529fn parse_int(s: &str) -> Result<i64, IntError> {
530    let (neg, digits) = match s.as_bytes().first() {
531        None => return Err(IntError::Syntax),
532        Some(b'+') => (false, &s[1..]),
533        Some(b'-') => (true, &s[1..]),
534        Some(_) => (false, s),
535    };
536    let un = parse_uint(digits)?;
537    const CUTOFF: u64 = 1 << 63;
538    match un {
539        None if neg => Err(IntError::Range(i64::MIN)),
540        None => Err(IntError::Range(i64::MAX)),
541        Some(un) if !neg && un >= CUTOFF => Err(IntError::Range(i64::MAX)),
542        Some(un) if neg && un > CUTOFF => Err(IntError::Range(i64::MIN)),
543        Some(un) if neg => Ok(0i64.wrapping_sub_unsigned(un)),
544        // un < 2^63 here.
545        Some(un) => i64::try_from(un).map_err(|_| IntError::Range(i64::MAX)),
546    }
547}
548
549/// Parses a u64 with a base prefix and underscores: `Ok(None)` is out of range (the value
550/// overflows `u64`).
551fn parse_uint(s0: &str) -> Result<Option<u64>, IntError> {
552    let b = s0.as_bytes();
553    if b.is_empty() {
554        return Err(IntError::Syntax);
555    }
556    let lower = |c: u8| c | (b'x' - b'X');
557    // Look for an octal, hex or binary prefix.
558    let (base, digits): (u64, &[u8]) = if b[0] == b'0' {
559        match b.get(1).map(|&c| lower(c)) {
560            Some(b'b') if b.len() >= 3 => (2, &b[2..]),
561            Some(b'o') if b.len() >= 3 => (8, &b[2..]),
562            Some(b'x') if b.len() >= 3 => (16, &b[2..]),
563            _ => (8, &b[1..]),
564        }
565    } else {
566        (10, b)
567    };
568    let cutoff = u64::MAX / base + 1;
569    let mut underscores = false;
570    let mut n: u64 = 0;
571    for &c in digits {
572        let d = match c {
573            b'_' => {
574                underscores = true;
575                continue;
576            }
577            b'0'..=b'9' => c - b'0',
578            _ if lower(c).is_ascii_lowercase() => lower(c) - b'a' + 10,
579            _ => return Err(IntError::Syntax),
580        };
581        if u64::from(d) >= base {
582            return Err(IntError::Syntax);
583        }
584        if n >= cutoff {
585            // n * base overflows.
586            return Ok(None);
587        }
588        n *= base;
589        match n.checked_add(u64::from(d)) {
590            Some(n1) => n = n1,
591            None => return Ok(None),
592        }
593    }
594    if underscores && !underscore_ok(s0) {
595        return Err(IntError::Syntax);
596    }
597    Ok(Some(n))
598}
599
600/// True when underscores appear only between digits (or after the base prefix).
601fn underscore_ok(s: &str) -> bool {
602    let mut s = s.as_bytes();
603    let lower = |c: u8| c | (b'x' - b'X');
604    // saw: b'^' beginning of number, b'0' digit or base prefix, b'_' underscore, b'!' other.
605    let mut saw = b'^';
606    let mut i = 0;
607    if let Some(b'-' | b'+') = s.first() {
608        s = &s[1..];
609    }
610    let mut hex = false;
611    if s.len() >= 2 && s[0] == b'0' && matches!(lower(s[1]), b'b' | b'o' | b'x') {
612        i = 2;
613        saw = b'0';
614        hex = lower(s[1]) == b'x';
615    }
616    while i < s.len() {
617        let c = s[i];
618        i += 1;
619        if c.is_ascii_digit() || hex && (b'a'..=b'f').contains(&lower(c)) {
620            saw = b'0';
621            continue;
622        }
623        if c == b'_' {
624            if saw != b'0' {
625                return false;
626            }
627            saw = b'_';
628            continue;
629        }
630        if saw == b'_' {
631            return false;
632        }
633        saw = b'!';
634    }
635    saw != b'_'
636}
637
638/// Locks `m`, recovering the data of a poisoned lock.
639fn lock<T: ?Sized>(m: &Mutex<T>) -> MutexGuard<'_, T> {
640    m.lock().unwrap_or_else(PoisonError::into_inner)
641}