cli-engine 0.9.3

Rust CLI framework for consistent command modules
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
use std::collections::BTreeSet;
use std::io::IsTerminal;

use clap::{Arg, ArgAction, ArgMatches, Command, builder::ValueParser};

/// Returns `true` when the process appears to be running interactively:
/// stdin and stderr are both TTYs.
///
/// Checking stdin ensures that piped input (`echo "" | gddy ...`) is detected
/// as non-interactive. Checking stderr ensures prompts can be displayed (since
/// `inquire` renders to stderr). Stdout is intentionally not checked — a user
/// piping output (`gddy ... | jq`) still has an interactive terminal for
/// prompts.
///
/// Used as the default for `GlobalFlags::interactive` when the user does not
/// pass `--interactive` or `--non-interactive` explicitly.
#[must_use]
pub fn detect_interactive() -> bool {
    std::io::stdin().is_terminal() && std::io::stderr().is_terminal()
}

/// Interactivity mode for a CLI invocation.
///
/// Commands and middleware can inspect this to decide whether to prompt for
/// missing inputs, display progress spinners, or fall back to error messages
/// suitable for scripts and CI.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum InteractivityMode {
    /// The user explicitly requested interactive prompts (`--interactive`), or
    /// the process is running in a TTY without CI indicators.
    Interactive,
    /// The user explicitly disabled prompts (`--non-interactive`), or the
    /// process is running in a non-TTY / CI context.
    NonInteractive,
}

impl InteractivityMode {
    /// Returns `true` when prompts and interactive flows are appropriate.
    #[must_use]
    pub fn is_interactive(self) -> bool {
        self == Self::Interactive
    }
}

impl From<bool> for InteractivityMode {
    fn from(interactive: bool) -> Self {
        if interactive {
            Self::Interactive
        } else {
            Self::NonInteractive
        }
    }
}

/// Parsed framework-global flags.
///
/// Applications can add their own global flags, but these are the built-in
/// controls understood by middleware and the output pipeline.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct GlobalFlags {
    /// Output format: `json`, `human`, or `toon`.
    pub output_format: String,
    /// Metadata verbosity selector.
    pub verbose: String,
    /// Whether mutating commands should short-circuit.
    pub dry_run: bool,
    /// Field projection.
    pub fields: String,
    /// Whether `fields` came from an explicit `--fields` flag on the command
    /// line, rather than clap filling in a command's `default_fields` (a
    /// command with `default_fields` set registers it as that flag's native
    /// default, so `fields` is non-empty even when the user never typed
    /// `--fields` — this is the only reliable way to tell the two apart).
    pub fields_explicit: bool,
    /// JMESPath per-item filter.
    pub filter: String,
    /// JMESPath whole-result expression.
    pub expr: String,
    /// Whether schema rendering was requested.
    pub schema: bool,
    /// User-provided command reason.
    pub reason: String,
    /// Raw timeout string.
    pub timeout: String,
    /// Debug selector.
    pub debug: String,
    /// Credential storage override from `--credential-store`, if supplied.
    pub credential_store: Option<crate::config::CredentialStore>,
    /// Interactivity mode: `true` enables prompts for missing inputs,
    /// `false` disables them. Auto-detected from TTY when neither flag is given.
    pub interactive: bool,
}

impl Default for GlobalFlags {
    fn default() -> Self {
        Self {
            output_format: "json".to_owned(),
            verbose: String::new(),
            dry_run: false,
            fields: String::new(),
            fields_explicit: false,
            filter: String::new(),
            expr: String::new(),
            schema: false,
            reason: String::new(),
            timeout: "0s".to_owned(),
            debug: String::new(),
            credential_store: None,
            interactive: detect_interactive(),
        }
    }
}

/// Explicit `--help` display-order values for the engine's own global flags,
/// numbered in the order they're registered below — which is meant to read
/// as their relative importance, most-used first.
///
/// Without this, every global flag would collide with command-specific
/// ones: clap auto-assigns each unset `display_order` as "the Nth argument
/// added to this `Command`," starting the count over at 0 on every
/// `Command` it's called on — the root (where these are declared) and each
/// subcommand alike. A subcommand's own `CommandSpec::with_arg` args get
/// low counter values (0, 1, 2, ... in declaration order) from their own
/// `Command`; a global flag propagated onto that subcommand keeps the low
/// counter value it got on the *root*. Mix the two and `--help` interleaves
/// them instead of showing command-specific flags first, as a block, in the
/// order they were declared. Parking every global flag comfortably above
/// any realistic per-command arg count keeps that from happening.
///
/// `FIELDS`, `FILTER`, and `EXPR` are `pub(crate)` because `cli.rs`
/// re-registers those three per-command (see `apply_fields_arg` and
/// `apply_filter_and_expr_examples`) with contextual help text; they must
/// reuse these same values or the override would drift out of position.
///
/// `LIMIT` and `OFFSET` are never registered by [`register_global_flags`]
/// itself — unlike every other value here, `--limit`/`--offset` are not
/// framework-global at all; `cli.rs` registers them directly on a single
/// command's own `Command` (see `apply_pagination_args`), and only for a
/// command that opted in via `CommandSpec::with_pagination`. These two
/// constants exist purely so that per-command registration still parks the
/// flags in the same relative `--help` position other engine flags occupy.
///
/// `REASON` and `ENV` cover the two global flags `Cli::new` registers
/// directly (conditionally, outside `register_global_flags`) rather than
/// this module's own function — `--reason` when an authorizer/auditor/
/// activity emitter is configured, `--env` when `CliConfig.environments` is
/// set. Both are just as subject to the collision this module exists to
/// prevent, so both need an explicit value here too.
pub(crate) mod global_flag_order {
    pub(crate) const HELP: usize = 1000;
    pub(crate) const OUTPUT: usize = 1001;
    pub(crate) const VERBOSE: usize = 1002;
    pub(crate) const DRY_RUN: usize = 1003;
    pub(crate) const FIELDS: usize = 1004;
    pub(crate) const FILTER: usize = 1005;
    pub(crate) const EXPR: usize = 1006;
    pub(crate) const LIMIT: usize = 1007;
    pub(crate) const OFFSET: usize = 1008;
    pub(crate) const SCHEMA: usize = 1009;
    pub(crate) const TIMEOUT: usize = 1010;
    pub(crate) const DEBUG: usize = 1011;
    pub(crate) const CREDENTIAL_STORE: usize = 1012;
    pub(crate) const JSON: usize = 1013;
    pub(crate) const TOON: usize = 1014;
    pub(crate) const HUMAN: usize = 1015;
    pub(crate) const INTERACTIVE: usize = 1016;
    pub(crate) const REASON: usize = 1017;
    pub(crate) const ENV: usize = 1018;
}

/// Registers framework-global flags on a `clap` command.
pub fn register_global_flags(command: Command) -> Command {
    command
        .disable_help_flag(true)
        .arg(
            // clap's default help arg shows an abbreviated summary for `-h`
            // and the full help text for `--help`. Override it so both
            // flags print the same full help everywhere; `disable_help_flag`
            // propagates to every subcommand.
            Arg::new("help")
                .short('h')
                .long("help")
                .action(ArgAction::HelpLong)
                .global(true)
                .display_order(global_flag_order::HELP)
                .help("Print help"),
        )
        .arg(
            Arg::new("output")
                .long("output")
                .short('o')
                .global(true)
                .display_order(global_flag_order::OUTPUT)
                .value_name("FORMAT")
                // This default is cosmetic, not authoritative: it's never
                // actually read as a value — `global_flags_from_matches` only
                // consults this arg when it was given on the command line,
                // falling back to `resolve_default_output_format`'s full
                // env/config/TTY precedence the rest of the time. But since
                // `--help` runs in this same process, this process's own
                // stdout TTY-ness is already known and stable for the whole
                // run, so mirroring that one signal here (skipping the
                // env-var/config-file tiers, which aren't available until a
                // command actually executes) keeps what `--help` shows honest
                // in the common case instead of a hardcoded, often-wrong
                // `[default: json]`.
                .default_value(if std::io::stdout().is_terminal() {
                    "human"
                } else {
                    "json"
                })
                // Only conflicts when *explicitly* given: clap's conflict
                // checks ignore an arg's default value, so a bare `--json`
                // with no `--output` at all is unaffected.
                .conflicts_with_all(["json", "toon", "human"])
                .help(
                    "Output format: toon|json|human (shorthand: --json, --toon, --human); \
                     defaults to human in an interactive terminal, json otherwise",
                ),
        )
        .arg(
            Arg::new("verbose")
                .long("verbose")
                .global(true)
                .num_args(0..=1)
                .default_missing_value("all")
                .value_name("FIELDS")
                .display_order(global_flag_order::VERBOSE)
                .help("Include metadata in output (all, or comma-separated: system,duration,args,env,identity,command,effective_args,timestamp)"),
        )
        .arg(
            Arg::new("dry-run")
                .long("dry-run")
                .global(true)
                .num_args(0..=1)
                .require_equals(true)
                .default_missing_value("true")
                .default_value("false")
                .value_parser(compat_bool_value_parser())
                .display_order(global_flag_order::DRY_RUN)
                .help("Preview mutations without executing"),
        )
        .arg(
            Arg::new("fields")
                .long("fields")
                .global(true)
                .value_name("FIELDS")
                .display_order(global_flag_order::FIELDS)
                .help("Comma-separated fields to include in output (use 'all' or '*' for everything)"),
        )
        .arg(
            Arg::new("filter")
                .long("filter")
                .global(true)
                .value_name("EXPR")
                .display_order(global_flag_order::FILTER)
                .help("Per-item JMESPath predicate for list data"),
        )
        .arg(
            Arg::new("expr")
                .long("expr")
                .global(true)
                .value_name("EXPR")
                .display_order(global_flag_order::EXPR)
                .help("JMESPath query applied to the whole result"),
        )
        .arg(
            Arg::new("schema")
                .long("schema")
                .global(true)
                .num_args(0..=1)
                .require_equals(true)
                .default_missing_value("true")
                .default_value("false")
                .value_parser(compat_bool_value_parser())
                .display_order(global_flag_order::SCHEMA)
                .help("Dump output field metadata instead of running the command"),
        )
        .arg(
            Arg::new("timeout")
                .long("timeout")
                .global(true)
                .allow_hyphen_values(true)
                .default_value("0s")
                .value_name("DURATION")
                .display_order(global_flag_order::TIMEOUT)
                .help("Overall command timeout (e.g. 60s, 5m); default 0s = no timeout"),
        )
        .arg(
            Arg::new("debug")
                .long("debug")
                .global(true)
                .num_args(0..=1)
                .default_missing_value("*")
                .value_name("PATTERN")
                .display_order(global_flag_order::DEBUG)
                .help("Enable debug logging (comma-separated component patterns, e.g. *, transport, *,-auth)"),
        )
        .arg(
            Arg::new("credential-store")
                .long("credential-store")
                .display_order(global_flag_order::CREDENTIAL_STORE)
                .global(true)
                .value_name("MODE")
                .value_parser(|s: &str| s.parse::<crate::config::CredentialStore>())
                .help("Credential storage: auto|keyring|file (overrides env and config)"),
        )
        .arg(
            Arg::new("interactive")
                .long("interactive")
                .short('i')
                .global(true)
                .action(ArgAction::SetTrue)
                .conflicts_with("non-interactive")
                .display_order(global_flag_order::INTERACTIVE)
                .help("Force interactive prompts for missing inputs (default when TTY is detected)"),
        )
        .arg(
            Arg::new("non-interactive")
                .long("non-interactive")
                .global(true)
                .action(ArgAction::SetTrue)
                .conflicts_with("interactive")
                .hide(true)
                .display_order(global_flag_order::INTERACTIVE)
                .help("Disable interactive prompts; fail on missing required inputs"),
        )
        .arg(
            Arg::new("json")
                .long("json")
                .global(true)
                .action(ArgAction::SetTrue)
                // Mutually exclusive with the other format selectors, so
                // e.g. `--json --human` together is a usage error rather
                // than one silently overriding the other.
                .conflicts_with_all(["toon", "human"])
                // Documented on `--output` instead of taking their own line
                // in every command's already-long options list.
                .hide(true)
                .display_order(global_flag_order::JSON)
                .help("Shorthand for --output json"),
        )
        .arg(
            Arg::new("toon")
                .long("toon")
                .global(true)
                .action(ArgAction::SetTrue)
                .conflicts_with_all(["json", "human"])
                .hide(true)
                .display_order(global_flag_order::TOON)
                .help("Shorthand for --output toon"),
        )
        .arg(
            Arg::new("human")
                .long("human")
                .global(true)
                .action(ArgAction::SetTrue)
                .conflicts_with_all(["json", "toon"])
                .hide(true)
                .display_order(global_flag_order::HUMAN)
                .help("Shorthand for --output human"),
        )
}

/// Registers the `--reason` flag on a `clap` command.
///
/// Not part of [`register_global_flags`]: `--reason` is only meaningful when an
/// app has registered an [`Authorizer`](crate::middleware::Authorizer),
/// [`Auditor`](crate::middleware::Auditor), or
/// [`ActivityEmitter`](crate::middleware::ActivityEmitter) to consume it (see
/// `Cli::new`'s conditional call to this function). Apps with none of those
/// configured never register this flag at all, rather than exposing a flag
/// that nothing reads. `Cli::new` only checks the eager `authz`/`auditor`/
/// `activity` fields on `CliConfig`; installing one of these later via
/// `init_deps` does not register `--reason`, since flag registration happens
/// before `init_deps` runs.
pub fn register_reason_flag(command: Command) -> Command {
    command.arg(
        Arg::new("reason")
            .long("reason")
            .global(true)
            .value_name("TEXT")
            .display_order(global_flag_order::REASON)
            .help("Short explanation of why this command is being run (forwarded to your authorizer, auditor, or activity emitter)"),
    )
}

/// Registers `--limit`/`--offset` directly on one command's own `clap`
/// `Command`, for a command whose [`CommandSpec`](crate::CommandSpec) opted
/// into pagination via `with_pagination`.
pub(crate) fn apply_pagination_args(
    command: Command,
    default_limit: i64,
    max_limit: i64,
) -> Command {
    command
        .arg(
            Arg::new("limit")
                .long("limit")
                .value_parser(pagination_limit_value_parser(max_limit))
                .allow_hyphen_values(true)
                .default_value(default_limit.to_string())
                .display_order(global_flag_order::LIMIT)
                .help(pagination_limit_help(default_limit, max_limit)),
        )
        .arg(
            Arg::new("offset")
                .long("offset")
                .value_parser(pagination_offset_value_parser())
                .allow_hyphen_values(true)
                .default_value("0")
                .display_order(global_flag_order::OFFSET)
                .help("Skip N items before applying limit"),
        )
}

fn pagination_limit_help(default_limit: i64, max_limit: i64) -> String {
    let mut help = format!("Max items to return (client-side, 0=all, default {default_limit}");
    if max_limit > 0 {
        help.push_str(&format!(", max {max_limit}"));
    }
    help.push(')');
    help
}

fn pagination_limit_value_parser(max_limit: i64) -> ValueParser {
    ValueParser::new(move |raw: &str| -> Result<i64, String> {
        let value = raw
            .parse::<i64>()
            .map_err(|_| format!("invalid limit value {raw:?}"))?;
        if max_limit > 0 && value > max_limit {
            return Err(format!("limit {value} exceeds the maximum of {max_limit}"));
        }
        Ok(value)
    })
}

/// Rejects a negative `--offset` at parse time — a `clap` usage error — rather
/// than letting it reach `apply_pagination` in `output/pipeline.rs`, which
/// already rejects one, but only once the command has otherwise fully run.
fn pagination_offset_value_parser() -> ValueParser {
    ValueParser::new(|raw: &str| -> Result<i64, String> {
        let value = raw
            .parse::<i64>()
            .map_err(|_| format!("invalid offset value {raw:?}"))?;
        if value < 0 {
            return Err(format!("offset {value} must be non-negative"));
        }
        Ok(value)
    })
}

/// Resolves the default output format when the user gave no explicit format.
///
/// Precedence: `env_override`, then `config_override` (the `[output].format`
/// key in `config.toml`), then a TTY policy — an interactive terminal gets
/// human-friendly output, everything else (pipes, files, CI, most agents)
/// gets machine-readable JSON. Pure so it can be unit-tested without a real
/// terminal or config file.
#[must_use]
pub fn resolve_default_output_format(
    env_override: Option<&str>,
    config_override: Option<&str>,
    is_tty: bool,
) -> String {
    // Normalize case (env vars and config values are commonly upper/mixed
    // case) and ignore blank or unrecognized values, so a stray or miscased
    // override can't break all command output — only a valid format is
    // honored, and an invalid one falls through to the next tier.
    for candidate in [env_override, config_override].into_iter().flatten() {
        let normalized = candidate.trim().to_ascii_lowercase();
        if crate::output::is_valid_output_format(&normalized) {
            return normalized;
        }
    }
    if is_tty { "human" } else { "json" }.to_owned()
}

/// Sanitizes an app id into an environment-variable prefix: ASCII alphanumerics
/// are uppercased and every other character becomes `_`, e.g. `godaddy` ->
/// `GODADDY`, `my-cli` -> `MY_CLI`.
///
/// Shared by the framework's app-scoped env vars (for example
/// [`output_env_var`] and `${PREFIX}_CREDENTIAL_STORE`) so they derive the same
/// prefix from a given app id.
#[must_use]
pub fn app_id_env_prefix(app_id: &str) -> String {
    app_id
        .chars()
        .map(|c| {
            if c.is_ascii_alphanumeric() {
                c.to_ascii_uppercase()
            } else {
                '_'
            }
        })
        .collect()
}

/// Derives the per-application output-format override env var from an app id,
/// e.g. `godaddy` -> `GODADDY_OUTPUT`, `gdx` -> `GDX_OUTPUT`.
#[must_use]
pub fn output_env_var(app_id: &str) -> String {
    format!("{}_OUTPUT", app_id_env_prefix(app_id))
}

/// Derives the per-application global minimum-stage override env var from an
/// app id, e.g. `godaddy` -> `GODADDY_MIN_STAGE`, `gdx` -> `GDX_MIN_STAGE`.
#[must_use]
pub fn min_stage_env_var(app_id: &str) -> String {
    format!("{}_MIN_STAGE", app_id_env_prefix(app_id))
}

/// Computes the default output format for `app_id`, consulting the
/// `${APP_ID}_OUTPUT` env override, the `[output].format` key in
/// `config.toml`, and whether stdout is an interactive terminal. Used as the
/// fallback when no explicit `--output`/`--json`/`--toon`/`--human` is given.
///
/// **Blocking**: this loads `config.toml` (see
/// [`ConfigFile::load`](crate::config::ConfigFile::load)), performing
/// synchronous filesystem I/O. `Cli` itself never calls this — it resolves
/// the default from the config already loaded once at `Cli::new` time
/// instead — but a consumer calling this function directly should avoid
/// doing so from a hot path or within an async executor without
/// `spawn_blocking`.
#[must_use]
pub fn default_output_format(app_id: &str) -> String {
    let env = std::env::var(output_env_var(app_id)).ok();
    let file = crate::config::load(app_id);
    resolve_default_output_format(
        env.as_deref(),
        file.output.format.as_deref(),
        std::io::stdout().is_terminal(),
    )
}

#[must_use]
/// Extracts framework-global flags from parsed `clap` matches, falling back to
/// `default_format` when the user gave no explicit output format.
pub fn global_flags_from_matches(
    matches: &ArgMatches,
    default_format: &str,
    auto_interactive: bool,
) -> GlobalFlags {
    let output_format = if matches.get_flag("toon") {
        "toon".to_owned()
    } else if matches.get_flag("human") {
        "human".to_owned()
    } else if matches.get_flag("json") {
        "json".to_owned()
    } else if matches.value_source("output") == Some(clap::parser::ValueSource::CommandLine) {
        matches
            .get_one::<String>("output")
            .cloned()
            .unwrap_or_else(|| default_format.to_owned())
    } else {
        default_format.to_owned()
    };

    GlobalFlags {
        output_format,
        verbose: matches
            .get_one::<String>("verbose")
            .cloned()
            .unwrap_or_default(),
        dry_run: matches.get_one::<bool>("dry-run").copied().unwrap_or(false),
        fields: matches
            .get_one::<String>("fields")
            .cloned()
            .unwrap_or_default(),
        fields_explicit: matches.value_source("fields")
            == Some(clap::parser::ValueSource::CommandLine),
        filter: matches
            .get_one::<String>("filter")
            .cloned()
            .unwrap_or_default(),
        expr: matches
            .get_one::<String>("expr")
            .cloned()
            .unwrap_or_default(),
        schema: matches.get_one::<bool>("schema").copied().unwrap_or(false),
        // `--reason` is only registered when an authorizer/auditor/activity
        // emitter is configured.
        reason: matches
            .try_get_one::<String>("reason")
            .ok()
            .flatten()
            .cloned()
            .unwrap_or_default(),
        timeout: matches
            .get_one::<String>("timeout")
            .cloned()
            .unwrap_or_else(|| "0s".to_owned()),
        debug: matches
            .get_one::<String>("debug")
            .cloned()
            .unwrap_or_default(),
        credential_store: matches
            .get_one::<crate::config::CredentialStore>("credential-store")
            .copied(),
        interactive: if matches.get_flag("non-interactive") {
            false
        } else if matches.get_flag("interactive") {
            true
        } else if auto_interactive {
            detect_interactive()
        } else {
            false
        },
    }
}

#[must_use]
/// Extracts output format from raw args.
///
/// Recognizes `--output <format>` / `-o <format>` / `--output=<format>`,
/// plus `--json`, `--toon`, and `--human` as shorthand for their respective
/// formats. Falls back to `default_format` when none is present.
pub fn extract_output_format(args: &[impl AsRef<str>], default_format: &str) -> String {
    for index in 0..args.len() {
        let arg = args[index].as_ref();
        if arg == "--output" || arg == "-o" {
            return args.get(index + 1).map_or_else(
                || default_format.to_owned(),
                |value| value.as_ref().to_owned(),
            );
        }
        if let Some(value) = arg.strip_prefix("--output=") {
            return value.to_owned();
        }
        if arg == "--json" {
            return "json".to_owned();
        }
        if arg == "--toon" {
            return "toon".to_owned();
        }
        if arg == "--human" {
            return "human".to_owned();
        }
    }
    default_format.to_owned()
}

#[must_use]
/// Extracts a colon-separated command path from raw args.
pub fn extract_command_path(
    args: &[impl AsRef<str>],
    bool_flags: &BTreeSet<String>,
    value_flags: &BTreeSet<String>,
) -> String {
    let mut parts = Vec::new();
    let mut index = 1;
    while index < args.len() {
        let arg = args[index].as_ref();
        if arg == "--schema" {
            index += 1;
            continue;
        }
        if arg.starts_with('-') {
            if bool_flags.contains(arg) || arg.contains('=') {
                index += 1;
                continue;
            }
            if value_flags.contains(arg)
                || (index + 1 < args.len() && !args[index + 1].as_ref().starts_with('-'))
            {
                index += 2;
                continue;
            }
            index += 1;
            continue;
        }
        parts.push(arg.to_owned());
        index += 1;
    }
    parts.join(":")
}

#[must_use]
/// Reports whether raw args contain a true `--schema` flag.
pub fn has_true_schema_flag(args: &[impl AsRef<str>]) -> bool {
    for arg in args {
        let arg = arg.as_ref();
        if arg == "--schema" {
            return true;
        }
        if let Some(value) = arg.strip_prefix("--schema=") {
            return parse_compat_bool(value).unwrap_or(false);
        }
    }
    false
}

pub(crate) fn compat_bool_value_parser() -> ValueParser {
    ValueParser::new(parse_compat_bool)
}

fn parse_compat_bool(raw: &str) -> Result<bool, String> {
    match raw {
        "1" | "t" | "T" | "TRUE" | "true" | "True" => Ok(true),
        "0" | "f" | "F" | "FALSE" | "false" | "False" => Ok(false),
        _ => Err(format!("invalid boolean value {raw:?}")),
    }
}

#[must_use]
/// Derives flag names that do not consume the following token.
pub fn derive_bool_flags(command: &Command) -> BTreeSet<String> {
    let mut flags = BTreeSet::from([
        "--help".to_owned(),
        "-h".to_owned(),
        "--verbose".to_owned(),
        "--debug".to_owned(),
    ]);
    collect_flag_names(command, &mut |arg, name| {
        if !arg_requires_value(arg) {
            flags.insert(name);
        }
    });
    flags
}

#[must_use]
/// Derives flag names that consume the following token.
pub fn derive_value_flags(command: &Command) -> BTreeSet<String> {
    let mut flags = BTreeSet::new();
    collect_flag_names(command, &mut |arg, name| {
        if arg_requires_value(arg) {
            flags.insert(name);
        }
    });
    flags
}

fn collect_flag_names(command: &Command, visit: &mut impl FnMut(&Arg, String)) {
    for arg in command.get_arguments() {
        if arg.is_positional() {
            continue;
        }
        if let Some(long) = arg.get_long() {
            visit(arg, format!("--{long}"));
        }
        if let Some(short) = arg.get_short() {
            visit(arg, format!("-{short}"));
        }
    }
    for child in command.get_subcommands() {
        collect_flag_names(child, visit);
    }
}

/// Reports whether a `--debug` pattern enables a named component.
///
/// The pattern is a comma-separated list of tokens applied left to right, so
/// later tokens override earlier ones:
///
/// - `*` enables every component; `-*` disables every component.
/// - `name` enables that component; `-name` disables it.
/// - whitespace around tokens is ignored and matching is case-insensitive.
///
/// An empty pattern enables nothing. Tokens that name other components are
/// ignored for the queried `component`.
///
/// # Examples
///
/// ```
/// use cli_engine::debug_component_enabled;
///
/// assert!(debug_component_enabled("*", "transport"));
/// assert!(debug_component_enabled("transport", "transport"));
/// assert!(!debug_component_enabled("*,-transport", "transport"));
/// assert!(debug_component_enabled("*,-auth", "transport"));
/// assert!(!debug_component_enabled("", "transport"));
/// ```
#[must_use]
pub fn debug_component_enabled(pattern: &str, component: &str) -> bool {
    let component = component.trim().to_ascii_lowercase();
    // Fail closed: an empty component name is never enabled, not even by `*`.
    if component.is_empty() {
        return false;
    }
    let mut enabled = false;
    for raw in pattern.split(',') {
        let token = raw.trim();
        if token.is_empty() {
            continue;
        }
        let (negated, name) = token
            .strip_prefix('-')
            .map_or((false, token), |rest| (true, rest));
        let name = name.trim().to_ascii_lowercase();
        if name == "*" || name == component {
            enabled = !negated;
        }
    }
    enabled
}

fn arg_requires_value(arg: &Arg) -> bool {
    match arg.get_action() {
        ArgAction::Set | ArgAction::Append => arg
            .get_num_args()
            .is_none_or(|range| range.takes_values() && range.min_values() > 0),
        ArgAction::SetTrue
        | ArgAction::SetFalse
        | ArgAction::Count
        | ArgAction::Help
        | ArgAction::HelpShort
        | ArgAction::HelpLong
        | ArgAction::Version => false,
        _ => arg
            .get_num_args()
            .is_some_and(|range| range.takes_values() && range.min_values() > 0),
    }
}

#[cfg(test)]
mod tests {
    use clap::Command;

    use super::{
        debug_component_enabled, min_stage_env_var, output_env_var, register_global_flags,
        resolve_default_output_format,
    };

    #[test]
    fn debug_component_matcher_handles_wildcards_and_negation() {
        // Empty pattern enables nothing.
        assert!(!debug_component_enabled("", "transport"));
        // Wildcard enables everything.
        assert!(debug_component_enabled("*", "transport"));
        assert!(debug_component_enabled("*", "auth"));
        // Bare name enables only that component.
        assert!(debug_component_enabled("transport", "transport"));
        assert!(!debug_component_enabled("transport", "auth"));
        // Negation after a wildcard removes one component but keeps the rest.
        assert!(!debug_component_enabled("*,-transport", "transport"));
        assert!(debug_component_enabled("*,-auth", "transport"));
        // `-*` disables everything; later tokens still win.
        assert!(!debug_component_enabled("*,-*", "transport"));
        assert!(debug_component_enabled("-*,transport", "transport"));
        // Whitespace and case are ignored.
        assert!(debug_component_enabled(" Transport , -auth ", "transport"));
        // An empty component fails closed, even against a wildcard.
        assert!(!debug_component_enabled("*", ""));
        assert!(!debug_component_enabled("*", "   "));
    }

    #[test]
    fn default_output_format_follows_env_override_then_tty() {
        // TTY policy when no env or config override.
        assert_eq!(resolve_default_output_format(None, None, true), "human");
        assert_eq!(resolve_default_output_format(None, None, false), "json");
        // A valid env override wins over the TTY policy in both directions.
        assert_eq!(
            resolve_default_output_format(Some("json"), None, true),
            "json"
        );
        assert_eq!(
            resolve_default_output_format(Some("human"), None, false),
            "human"
        );
        // Env override is case-insensitive (env vars are commonly upper-cased).
        assert_eq!(
            resolve_default_output_format(Some("JSON"), None, true),
            "json"
        );
        assert_eq!(
            resolve_default_output_format(Some(" Human "), None, false),
            "human"
        );
        // Blank or unrecognized env overrides are ignored (fall back to TTY).
        assert_eq!(
            resolve_default_output_format(Some("   "), None, false),
            "json"
        );
        assert_eq!(resolve_default_output_format(Some(""), None, true), "human");
        assert_eq!(
            resolve_default_output_format(Some("yaml"), None, false),
            "json"
        );
        assert_eq!(
            resolve_default_output_format(Some("yaml"), None, true),
            "human"
        );
    }

    #[test]
    fn default_output_format_config_override_wins_over_tty_but_not_env() {
        // Config override wins over the TTY policy when there's no env override.
        assert_eq!(
            resolve_default_output_format(None, Some("json"), true),
            "json"
        );
        assert_eq!(
            resolve_default_output_format(None, Some("human"), false),
            "human"
        );
        // Env override still wins over a config override.
        assert_eq!(
            resolve_default_output_format(Some("human"), Some("json"), false),
            "human"
        );
        // Blank or unrecognized config overrides are ignored (fall back to TTY).
        assert_eq!(
            resolve_default_output_format(None, Some("yaml"), true),
            "human"
        );
        assert_eq!(
            resolve_default_output_format(None, Some("yaml"), false),
            "json"
        );
    }

    #[test]
    fn output_env_var_is_derived_from_app_id() {
        assert_eq!(output_env_var("godaddy"), "GODADDY_OUTPUT");
        assert_eq!(output_env_var("gdx"), "GDX_OUTPUT");
        assert_eq!(output_env_var("my-cli"), "MY_CLI_OUTPUT");
    }

    #[test]
    fn min_stage_env_var_is_derived_from_app_id() {
        assert_eq!(min_stage_env_var("godaddy"), "GODADDY_MIN_STAGE");
        assert_eq!(min_stage_env_var("gdx"), "GDX_MIN_STAGE");
        assert_eq!(min_stage_env_var("my-cli"), "MY_CLI_MIN_STAGE");
    }

    #[test]
    fn short_and_long_help_flags_render_identical_output() {
        let build = || {
            register_global_flags(Command::new("testcli"))
                .subcommand(Command::new("sub").about("A subcommand"))
        };
        let help_text = |args: &[&str]| {
            build()
                .try_get_matches_from(args)
                .expect_err("help action short-circuits parsing")
                .to_string()
        };

        assert_eq!(
            help_text(&["testcli", "-h"]),
            help_text(&["testcli", "--help"])
        );
        assert_eq!(
            help_text(&["testcli", "sub", "-h"]),
            help_text(&["testcli", "sub", "--help"])
        );
    }

    #[test]
    fn interactivity_mode_from_bool() {
        use super::InteractivityMode;
        assert_eq!(
            InteractivityMode::from(true),
            InteractivityMode::Interactive
        );
        assert_eq!(
            InteractivityMode::from(false),
            InteractivityMode::NonInteractive
        );
        assert!(InteractivityMode::Interactive.is_interactive());
        assert!(!InteractivityMode::NonInteractive.is_interactive());
    }

    #[test]
    fn interactive_flag_parsing_explicit_interactive() {
        use super::global_flags_from_matches;
        let cmd = register_global_flags(Command::new("test"));
        let matches = cmd
            .try_get_matches_from(["test", "--interactive"])
            .expect("should parse");
        // --interactive works even when auto_interactive is false
        let flags = global_flags_from_matches(&matches, "json", false);
        assert!(flags.interactive);
    }

    #[test]
    fn interactive_flag_parsing_explicit_non_interactive() {
        use super::global_flags_from_matches;
        let cmd = register_global_flags(Command::new("test"));
        let matches = cmd
            .try_get_matches_from(["test", "--non-interactive"])
            .expect("should parse");
        // --non-interactive wins even when auto_interactive is true
        let flags = global_flags_from_matches(&matches, "json", true);
        assert!(!flags.interactive);
    }

    #[test]
    fn interactive_defaults_off_without_auto_interactive() {
        use super::global_flags_from_matches;
        let cmd = register_global_flags(Command::new("test"));
        let matches = cmd.try_get_matches_from(["test"]).expect("should parse");
        // No explicit flag + auto_interactive=false → not interactive
        let flags = global_flags_from_matches(&matches, "json", false);
        assert!(!flags.interactive);
    }

    #[test]
    fn interactive_flag_conflicts() {
        let cmd = register_global_flags(Command::new("test"));
        let result = cmd.try_get_matches_from(["test", "--interactive", "--non-interactive"]);
        assert!(result.is_err());
    }

    #[test]
    fn detect_interactive_is_consistent_with_tty_state() {
        // detect_interactive checks stdin + stderr TTY state.
        // In CI (no real TTY), both are typically non-terminals → false.
        // Locally in a real terminal, both are terminals → true.
        // Either way, it should not panic and should be consistent.
        let result = super::detect_interactive();
        let stdin_tty = std::io::IsTerminal::is_terminal(&std::io::stdin());
        let stderr_tty = std::io::IsTerminal::is_terminal(&std::io::stderr());
        assert_eq!(result, stdin_tty && stderr_tty);
    }
}