Skip to main content

kaish_tool_api/
global_flags.rs

1//! Global flags shared by every builtin via `#[command(flatten)]`.
2//!
3//! Today this is just `--json`. Every builtin flattens `GlobalFlags` into its
4//! own clap struct and calls `parsed.global.apply(ctx)` after parsing; the
5//! kernel reads the output format the flag set (via
6//! [`ToolCtx::set_output_format`](crate::ToolCtx::set_output_format)) after
7//! `execute()` returns and applies it.
8
9use clap::Args;
10
11use kaish_types::{OutputFormat, Value};
12
13use crate::ctx::ToolCtx;
14use kaish_types::ToolArgs;
15
16/// Flags injected into every migrated builtin via `#[command(flatten)] global: GlobalFlags`.
17///
18/// Builtins call `parsed.global.apply(ctx)` after their own argv parse so the
19/// dispatcher can read the output format post-execute and apply it.
20#[derive(Args, Debug, Clone, Default)]
21pub struct GlobalFlags {
22    /// Render structured output as JSON.
23    #[arg(long)]
24    pub json: bool,
25}
26
27impl GlobalFlags {
28    /// Apply the flags to `ctx` so the dispatcher can pick them up after the
29    /// builtin's `execute()` returns.
30    pub fn apply(&self, ctx: &mut dyn ToolCtx) {
31        if self.json {
32            ctx.set_output_format(OutputFormat::Json);
33        }
34    }
35
36    /// Honor `--json` straight off `ToolArgs` before any per-builtin clap parse.
37    ///
38    /// The kernel calls this just before `tool.execute()` so the format is set
39    /// even when a builtin's own `try_parse_from` rejects argv and returns
40    /// before `parsed.global.apply(ctx)` would have run. Idempotent with the
41    /// per-builtin apply: both writing `OutputFormat::Json` yields the same
42    /// state.
43    ///
44    /// `raw_argv` is [`ToolSchema::raw_argv`](kaish_types::ToolSchema::raw_argv)
45    /// for the tool being dispatched, and it decides whether `positional` is
46    /// searched at all. Only a `raw_argv` tool keeps `--json` — and the `--`
47    /// marker that bounds it — among its positionals. For every other tool a
48    /// positional `--json` got there by being an operand after `--`, where the
49    /// binder drops the marker, so searching would read the operand back as
50    /// the kernel's flag and `echo -- --json hi` would answer in JSON.
51    pub fn apply_from_args(args: &ToolArgs, raw_argv: bool, ctx: &mut dyn ToolCtx) {
52        if args.has_flag("json") || (raw_argv && positional_json_flag(args)) {
53            ctx.set_output_format(OutputFormat::Json);
54        }
55    }
56}
57
58/// `--json`/`--json=VALUE` surviving as a literal string in `args.positional`
59/// is the `raw_argv` case (GH #198): a `raw_argv` tool's binder deliberately
60/// does not lift ANY flag out of source order (that's the whole point — see
61/// `ToolSchema::raw_argv`), so `--json` lands in `positional` instead of
62/// `flags`. Without this, a raw_argv builtin (`test`, and now `kill`) would
63/// silently ignore `--json` — a real, user-visible regression discovered
64/// while adding `kill`'s signal shorthand.
65///
66/// Stops scanning at a literal `"--"` token: a real end-of-options marker
67/// makes every following token an operand, not a flag — for `raw_argv` tools
68/// that's `kill -- --json foo` (foo is a job/PID literally spelled
69/// `--json`); for a NORMAL (non-raw_argv) tool it's the pre-existing case of
70/// a post-`--` `--json` operand (`echo -- --json`), which the ordinary
71/// binder already relegates to `positional` too (`past_double_dash` in
72/// `bind_tool_args`). Without this boundary, the scan would reinterpret that
73/// literal operand as the global JSON flag for every builtin, not just
74/// raw_argv ones — a real regression this comment exists to prevent
75/// reintroducing.
76///
77/// `--json=VALUE`'s truthiness comes from
78/// [`global_flag_value_is_truthy`](kaish_types::global_flag_value_is_truthy),
79/// the one rule the typed and verbatim binders also ask, so every path agrees
80/// on what counts as "on".
81fn positional_json_flag(args: &ToolArgs) -> bool {
82    args.positional
83        .iter()
84        .take_while(|v| !matches!(v, Value::String(s) if s == "--"))
85        .any(|v| {
86            let Value::String(s) = v else { return false };
87            if s == "--json" {
88                return true;
89            }
90            // raw_argv keeps every word as written, so the value arrives as
91            // text and is judged as text.
92            s.strip_prefix("--json=").is_some_and(|val| {
93                kaish_types::global_flag_value_is_truthy(&Value::String(val.to_string()))
94            })
95        })
96}