argx 0.2.1

Expressive command-line parsing and configuration for Rust.
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
//! Deterministic help rendering from static command metadata.
//!
//! Help is a projection of the same command tables used for parsing. In particular, named options
//! are resolved with the parser's lexical scoping rules before they are rendered, so descendant
//! help cannot advertise an ancestor spelling that would actually be shadowed at that scope.
//! Flattened help groups retain semantic identities to avoid duplicating arguments when the same
//! reusable declaration is mounted more than once.

use std::{fmt::Write as _, io::IsTerminal as _};

use crate::{
    __private::{
        Action, Arg, Command, Flag, HelpGroup, Key, Named, SCHEMA_ACTION, resolve_long,
        resolve_short,
    },
    error::display_bytes,
};

/// Renderable argument rows collected under one help section.
type HelpRows = Vec<(String, String)>;

/// Help sections paired with their rendered argument rows.
type GroupedHelp<'a> = Vec<(&'a str, HelpRows)>;

/// One flag as visible from the selected command scope.
struct VisibleFlag<'a> {
    /// Command-path scope where this visible occurrence is mounted.
    scope: usize,
    /// Original declaration metadata used for help text and value behavior.
    flag: &'a Flag<'a>,
    /// Long spellings that remain visible after lexical shadowing.
    longs: Vec<&'a str>,
    /// Short spellings that remain visible after lexical shadowing.
    shorts: Vec<u8>,
}

impl<'a> VisibleFlag<'a> {
    /// Resolves flags visible from the selected command using the parser's lexical scope rules.
    ///
    /// The resolver retains the command-path scope of each match so repeated mounts of one
    /// reusable `Args` declaration remain distinguishable even though they share static metadata
    /// pointers.
    fn collect(path: &[&'a Command<'a>]) -> Vec<Self> {
        let Some((&command, ancestors)) = path.split_last() else {
            return Vec::new();
        };
        let current = ancestors.len();

        let candidates = command.flags.iter().copied().map(|flag| (current, flag)).chain(
            ancestors.iter().enumerate().rev().flat_map(|(scope, command)| {
                command
                    .flags
                    .iter()
                    .copied()
                    .filter(|flag| flag.global)
                    .map(move |flag| (scope, flag))
            }),
        );

        candidates
            .filter_map(|(scope, flag)| {
                let longs = flag
                    .longs
                    .iter()
                    .copied()
                    .filter(|long| {
                        matches!(
                            resolve_long(command, ancestors, long.as_bytes()),
                            Some(Named::Flag { flag: resolved, scope: resolved_scope })
                                if resolved_scope == scope && std::ptr::eq(resolved, flag)
                        )
                    })
                    .collect::<Vec<_>>();
                let shorts = flag
                    .shorts
                    .iter()
                    .copied()
                    .filter(|short| {
                        matches!(
                            resolve_short(command, ancestors, *short),
                            Some(Named::Flag { flag: resolved, scope: resolved_scope })
                                if resolved_scope == scope && std::ptr::eq(resolved, flag)
                        )
                    })
                    .collect::<Vec<_>>();

                (!longs.is_empty() || !shorts.is_empty()).then_some(Self {
                    scope,
                    flag,
                    longs,
                    shorts,
                })
            })
            .collect()
    }
}

/// Amount of detail requested by the help spelling.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) enum HelpStyle {
    /// Compact `-h` output.
    Short,
    /// Expanded `--help` output.
    Long,
}

impl HelpStyle {
    /// Selects compact or expanded prose, falling back to compact prose for long help.
    fn text<'a>(self, short: Option<&'a str>, long: Option<&'a str>) -> Option<&'a str> {
        match self {
            Self::Short => short,
            Self::Long => long.or(short),
        }
    }

    /// Renders built-in action help with a hint for the alternate help spelling.
    fn action_help(self, action: &Action<'_>) -> String {
        if !matches!(action.kind, crate::__private::ActionKind::Help) {
            return action.help.to_owned();
        }
        match self {
            Self::Short => "Print help (see more with '--help')".to_owned(),
            Self::Long => "Print help (see a summary with '-h')".to_owned(),
        }
    }

    /// Renders one positional argument row.
    fn arg_row(self, arg: &Arg<'_>) -> (String, String) {
        (
            arg_usage(arg),
            metadata_help(self.text(arg.help, arg.long_help), arg.accepted_values, None, self),
        )
    }

    /// Renders one named flag row.
    fn flag_row(self, flag: &VisibleFlag<'_>) -> (String, String) {
        (
            spellings_label(
                &flag.shorts,
                &flag.longs,
                flag.flag.takes_value.then_some(flag.flag.name),
            ),
            metadata_help(
                self.text(flag.flag.help, flag.flag.long_help),
                flag.flag.accepted_values,
                flag.flag.default_value,
                self,
            ),
        )
    }
}

/// Renders help for one selected command path.
///
/// Required ancestor arguments remain attached to the scope where they must appear, while only the
/// selected command contributes positional rows and child-command listings.
#[cfg(test)]
pub(crate) fn render(path: &[&Command<'_>]) -> String {
    render_with_schema(path, false, HelpStyle::Short)
}

/// Renders help with the virtual schema action when discovery is enabled for the root parser.
pub(crate) fn render_with_schema(
    path: &[&Command<'_>],
    schema_enabled: bool,
    style: HelpStyle,
) -> String {
    let Some(&command) = path.last() else {
        return String::new();
    };

    let visible_flags = VisibleFlag::collect(path);
    let (grouped_keys, grouped_rows) = grouped_rows(path, &visible_flags, style);

    let mut output = String::new();
    let description = style.text(command.about, command.description);
    if let Some(description) = description.filter(|description| !description.is_empty()) {
        output.push_str(description);
        output.push_str("\n\n");
    }

    output.push_str("Usage: ");
    output.push_str(&render_usage(path));
    output.push('\n');

    let ungrouped_args = command
        .args
        .iter()
        .copied()
        .filter(|arg| !grouped_keys.contains(&arg.key))
        .collect::<Vec<_>>();
    if !ungrouped_args.is_empty() {
        output.push_str("\nArguments:\n");
        let rows = ungrouped_args.iter().map(|arg| style.arg_row(arg)).collect::<Vec<_>>();
        write_rows(&mut output, &rows, style);
    }

    if !command.subcommands.is_empty() {
        output.push_str("\nCommands:\n");
        let mut rows = command
            .subcommands
            .iter()
            .map(|command| {
                (display_bytes(command.name.as_bytes()), command.about.unwrap_or("").to_owned())
            })
            .collect::<Vec<_>>();
        if schema_enabled && path.len() == 1 {
            rows.push(("schema".to_owned(), "Print machine-readable schema".to_owned()));
        }
        // clap keeps command summaries compact even in expanded `--help`; only argument and
        // option rows switch to the long, vertically expanded layout.
        write_rows(&mut output, &rows, HelpStyle::Short);
    }

    output.push_str("\nOptions:\n");
    let mut rows = visible_flags
        .iter()
        .filter(|flag| !grouped_keys.contains(&flag.flag.key))
        .map(|flag| style.flag_row(flag))
        .collect::<Vec<_>>();
    rows.extend(command.actions.iter().map(|action| {
        (spellings_label(action.shorts, action.longs, None), style.action_help(action))
    }));
    if schema_enabled {
        rows.push((
            spellings_label(SCHEMA_ACTION.shorts, SCHEMA_ACTION.longs, None),
            style.action_help(&SCHEMA_ACTION),
        ));
    }
    write_rows(&mut output, &rows, style);

    for (heading, rows) in grouped_rows {
        output.push('\n');
        output.push_str(heading);
        output.push_str(":\n");
        write_rows(&mut output, &rows, style);
    }

    for section in command.help_sections {
        output.push('\n');
        output.push_str(section.heading);
        output.push_str(":\n");
        if !section.body.is_empty() {
            output.push_str(section.body);
            output.push('\n');
        }
    }

    if styling_enabled() { style_headings(&output) } else { output }
}

/// Whether interactive help should use minimal ANSI emphasis.
fn styling_enabled() -> bool {
    std::io::stdout().is_terminal() && std::env::var_os("NO_COLOR").is_none()
}

/// Applies emphasis to help headings and selectable command-line spellings without changing
/// layout or wrapping.
fn style_headings(help: &str) -> String {
    let mut styled = String::with_capacity(help.len() + 128);
    let mut commands = false;
    for line in help.split_inclusive('\n') {
        let bare = line.strip_suffix('\n').unwrap_or(line);
        if let Some(rest) = bare.strip_prefix("Usage:") {
            commands = false;
            styled.push_str("\x1b[1;4mUsage:\x1b[0m");
            styled.push_str(rest);
        } else if is_section_heading(bare) {
            commands = bare == "Commands:";
            styled.push_str("\x1b[1;4m");
            styled.push_str(bare);
            styled.push_str("\x1b[0m");
        } else if commands {
            style_command_row(&mut styled, bare);
        } else {
            style_flag_row(&mut styled, bare);
        }
        if line.ends_with('\n') {
            styled.push('\n');
        }
    }
    styled
}

/// Bolds the command name at the start of a command help row.
fn style_command_row(output: &mut String, line: &str) {
    let indent = line.len() - line.trim_start().len();
    let (prefix, rest) = line.split_at(indent);
    let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
    if end == 0 {
        output.push_str(line);
        return;
    }

    output.push_str(prefix);
    output.push_str("\x1b[1m");
    output.push_str(&rest[..end]);
    output.push_str("\x1b[0m");
    output.push_str(&rest[end..]);
}

/// Bolds leading short and long option spellings while leaving metavariables unstyled.
fn style_flag_row(output: &mut String, line: &str) {
    let Some(start) = line.find('-') else {
        output.push_str(line);
        return;
    };
    if start > 6 || !line[..start].chars().all(char::is_whitespace) {
        output.push_str(line);
        return;
    }

    output.push_str(&line[..start]);
    let mut rest = &line[start..];
    let mut styled_any = false;
    loop {
        let end = rest.find(char::is_whitespace).unwrap_or(rest.len());
        let token = &rest[..end];
        if token.len() == 1 || !token.starts_with('-') {
            break;
        }

        output.push_str("\x1b[1m");
        output.push_str(token);
        output.push_str("\x1b[0m");
        styled_any = true;
        rest = &rest[end..];

        let spaces = rest.len() - rest.trim_start().len();
        output.push_str(&rest[..spaces]);
        rest = &rest[spaces..];
    }

    if styled_any {
        output.push_str(rest);
    } else {
        output.push_str(&line[start..]);
    }
}

/// Recognizes generated and documentation-style section headings.
fn is_section_heading(line: &str) -> bool {
    matches!(line, "Arguments:" | "Commands:" | "Options:")
        || (line.ends_with(':')
            && !line.starts_with(' ')
            && !line.starts_with('\t')
            && !line.contains('`')
            && !line.contains("://"))
}

/// Builds documented flattened-group rows and the semantic keys claimed by those groups.
fn grouped_rows<'a>(
    path: &[&'a Command<'a>],
    visible_flags: &[VisibleFlag<'a>],
    style: HelpStyle,
) -> (Vec<Key>, GroupedHelp<'a>) {
    let Some(&selected) = path.last() else {
        return (Vec::new(), Vec::new());
    };
    let selected_scope = path.len() - 1;

    let mut grouped_keys = Vec::new();
    let mut sections = GroupedHelp::new();
    for (scope, command) in path.iter().enumerate().rev() {
        for group in command.help_groups.iter().copied() {
            if group.heading.is_empty() {
                continue;
            }
            let heading = group.heading;
            let mut rows = Vec::new();
            if scope == selected_scope {
                for arg in selected.args {
                    if group_contains_arg(group, arg) && !grouped_keys.contains(&arg.key) {
                        grouped_keys.push(arg.key);
                        rows.push(style.arg_row(arg));
                    }
                }
            }
            for flag in visible_flags {
                if flag.scope == scope
                    && group_contains_flag(group, flag.flag)
                    && !grouped_keys.contains(&flag.flag.key)
                {
                    grouped_keys.push(flag.flag.key);
                    rows.push(style.flag_row(flag));
                }
            }
            if rows.is_empty() {
                continue;
            }
            if let Some((_, existing)) =
                sections.iter_mut().find(|(existing, _)| *existing == heading)
            {
                existing.extend(rows);
            } else {
                sections.push((heading, rows));
            }
        }
    }

    (grouped_keys, sections)
}

/// Reports whether one help group contains a named argument.
fn group_contains_flag(group: &HelpGroup<'_>, flag: &Flag<'_>) -> bool {
    group.flags.iter().any(|candidate| std::ptr::eq(*candidate, flag))
}

/// Reports whether one help group contains a positional argument.
fn group_contains_arg(group: &HelpGroup<'_>, arg: &Arg<'_>) -> bool {
    group.args.iter().any(|candidate| std::ptr::eq(*candidate, arg))
}

/// Writes aligned help rows without terminal-width-dependent wrapping.
///
/// Long-only options reserve the same short-option column as rows such as `-h, --help`, matching
/// the conventional layout while commands and positional arguments retain two-space indent.
fn write_rows(output: &mut String, rows: &[(String, String)], style: HelpStyle) {
    if style == HelpStyle::Long {
        for (index, (label, help)) in rows.iter().enumerate() {
            let label = aligned_label(label);
            let _ = writeln!(output, "  {label}");
            if !help.is_empty() {
                write_indented(output, help, 10);
            }
            if index + 1 != rows.len() {
                output.push('\n');
            }
        }
        return;
    }

    let labels = rows.iter().map(|(label, _)| aligned_label(label)).collect::<Vec<_>>();
    let width = labels.iter().map(|label| label.chars().count()).max().unwrap_or(0);
    for ((_, help), label) in rows.iter().zip(labels) {
        if help.is_empty() {
            let _ = writeln!(output, "  {label}");
        } else {
            let _ = writeln!(output, "  {label:<width$}  {help}");
        }
    }
}

/// Reserves the short-option column for long-only option rows.
fn aligned_label(label: &str) -> String {
    if label.starts_with("--") { format!("    {label}") } else { label.to_owned() }
}

/// Writes multiline help with a fixed continuation indent.
fn write_indented(output: &mut String, text: &str, indent: usize) {
    let padding = " ".repeat(indent);
    for line in text.lines() {
        if line.is_empty() {
            output.push('\n');
        } else {
            let _ = writeln!(output, "{padding}{line}");
        }
    }
}

/// Combines prose with metadata according to compact or expanded help style.
fn metadata_help(
    help: Option<&str>,
    values: &[&str],
    default: Option<&str>,
    style: HelpStyle,
) -> String {
    let mut output = help.unwrap_or("").to_owned();
    match style {
        HelpStyle::Short => {
            append_inline_values(&mut output, values);
            append_inline_default(&mut output, default);
        }
        HelpStyle::Long => {
            if !values.is_empty() {
                if !output.is_empty() {
                    output.push_str("\n\n");
                }
                output.push_str("Possible values:\n");
                for value in values {
                    output.push_str("- ");
                    output.push_str(&display_bytes(value.as_bytes()));
                    output.push('\n');
                }
                output.pop();
            }
            if let Some(default) = default {
                if !output.is_empty() {
                    output.push_str("\n\n");
                }
                output.push_str("[default: ");
                output.push_str(&display_bytes(default.as_bytes()));
                output.push(']');
            }
        }
    }
    output
}

/// Appends one canonical finite vocabulary without trusting values as terminal-safe text.
fn append_inline_values(help: &mut String, values: &[&str]) {
    if values.is_empty() {
        return;
    }
    if !help.is_empty() {
        help.push(' ');
    }
    help.push_str("[possible values: ");
    for (index, value) in values.iter().enumerate() {
        if index > 0 {
            help.push_str(", ");
        }
        help.push_str(&display_bytes(value.as_bytes()));
    }
    help.push(']');
}

/// Appends a statically derivable default to compact help.
fn append_inline_default(help: &mut String, default: Option<&str>) {
    let Some(default) = default else {
        return;
    };
    if !help.is_empty() {
        help.push(' ');
    }
    help.push_str("[default: ");
    help.push_str(&display_bytes(default.as_bytes()));
    help.push(']');
}

/// Renders short and long spellings with an optional value placeholder.
fn spellings_label(shorts: &[u8], longs: &[&str], value_name: Option<&str>) -> String {
    let mut label = String::new();
    for (index, short) in shorts.iter().enumerate() {
        if index > 0 {
            label.push_str(", ");
        }
        label.push('-');
        label.push(char::from(*short));
    }
    for long in longs {
        if !label.is_empty() {
            label.push_str(", ");
        }
        label.push_str("--");
        label.push_str(long);
    }
    if let Some(name) = value_name {
        label.push_str(" <");
        label.push_str(&metavar(name));
        label.push('>');
    }
    label
}

/// Renders the selected command path as a help usage expression without the `Usage:` prefix.
pub(crate) fn render_usage(path: &[&Command<'_>]) -> String {
    render_usage_inner(path, true)
}

/// Renders the corrective usage shown for missing required arguments.
pub(crate) fn render_required_usage(path: &[&Command<'_>]) -> String {
    render_usage_inner(path, false)
}

/// Renders one usage expression, optionally advertising the generic optional-argument bucket.
fn render_usage_inner(path: &[&Command<'_>], include_options: bool) -> String {
    let Some(&command) = path.last() else {
        return String::new();
    };

    let mut usage = String::new();
    for (index, command) in path.iter().enumerate() {
        if !usage.is_empty() {
            usage.push(' ');
        }
        usage.push_str(&display_bytes(command.name.as_bytes()));
        if include_options && index + 1 == path.len() {
            usage.push_str(" [OPTIONS]");
        }
        for flag in command.flags.iter().filter(|flag| flag.required) {
            usage.push(' ');
            usage.push_str(&required_flag_usage(flag));
        }
        if index + 1 != path.len() {
            for arg in command.args.iter().filter(|arg| arg.required) {
                usage.push(' ');
                usage.push_str(&arg_usage(arg));
            }
        }
    }
    for arg in command.args {
        usage.push(' ');
        usage.push_str(&arg_usage(arg));
    }
    if !command.subcommands.is_empty() {
        usage.push_str(" <COMMAND>");
    }
    usage
}

/// Collects every unsupplied required argument in command-path declaration order.
pub(crate) fn missing_required_labels(path: &[&Command<'_>], supplied: &[Key]) -> Vec<String> {
    let mut missing = Vec::new();
    for command in path {
        for flag in command.flags.iter().filter(|flag| flag.required) {
            if !supplied.contains(&flag.key) {
                missing.push(required_flag_usage(flag));
            }
        }
        for arg in command.args.iter().filter(|arg| arg.required) {
            if !supplied.contains(&arg.key) {
                missing.push(arg_usage(arg));
            }
        }
    }
    missing
}

/// Resolves one generated missing-required label to the spelling shown in help and usage.
pub(crate) fn missing_required_label(path: &[&Command<'_>], diagnostic: &str) -> Option<String> {
    if diagnostic.starts_with('<') && diagnostic.ends_with('>') {
        return Some(diagnostic.to_owned());
    }
    for command in path.iter().rev() {
        if let Some(flag) = command.flags.iter().find(|flag| flag.diagnostic == diagnostic) {
            return Some(required_flag_usage(flag));
        }
        if let Some(arg) = command.args.iter().find(|arg| arg.name == diagnostic) {
            return Some(arg_usage(arg));
        }
    }
    None
}

/// Renders the canonical spelling of a required named flag for the usage line.
fn required_flag_usage(flag: &Flag<'_>) -> String {
    let mut usage = flag.longs.first().map_or_else(
        || {
            flag.shorts.first().map_or_else(
                || flag.name.to_owned(),
                |short| {
                    let short = char::from(*short);
                    format!("-{short}")
                },
            )
        },
        |long| format!("--{long}"),
    );
    if flag.takes_value {
        usage.push_str(" <");
        usage.push_str(&metavar(flag.name));
        usage.push('>');
    }
    usage
}

/// Renders one positional argument for usage and argument tables.
fn arg_usage(arg: &Arg<'_>) -> String {
    let name = metavar(arg.name);
    let mut usage = if arg.required { format!("<{name}>") } else { format!("[{name}]") };
    if arg.variadic {
        usage.push_str("...");
    }
    usage
}

/// Converts a canonical field name into a conventional value placeholder.
fn metavar(name: &str) -> String {
    name.replace('-', "_").to_ascii_uppercase()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::__private::ActionKind;

    static VERBOSE: Flag<'static> = Flag {
        key: 1,
        name: "verbose",
        help: Some("Enable verbose output"),
        longs: &["verbose"],
        shorts: b"v",
        ..Flag::BOOL
    };
    static OUTPUT: Flag<'static> = Flag {
        key: 2,
        name: "destination",
        help: Some("Write to this path"),
        longs: &["destination"],
        required: true,
        ..Flag::VALUE
    };
    static PROFILE: Flag<'static> = Flag {
        key: 6,
        name: "profile",
        help: Some("Select a profile"),
        longs: &["profile"],
        ..Flag::VALUE
    };
    static INPUT: Arg<'static> =
        Arg { key: 3, name: "input", help: Some("Input file"), ..Arg::REQUIRED };
    static REST: Arg<'static> =
        Arg { key: 4, name: "rest", required: false, variadic: true, ..Arg::REQUIRED };
    static GET: Command<'static> =
        Command { name: "get", about: Some("Read one value"), ..Command::EMPTY };
    static CONFIG: Command<'static> = Command {
        name: "config",
        about: Some("Manage configuration"),
        flags: &[&VERBOSE, &OUTPUT, &PROFILE],
        args: &[&INPUT, &REST],
        subcommands: &[&GET],
        key: 5,
        ..Command::EMPTY
    };
    static ROOT: Command<'static> = Command {
        name: "tool",
        about: Some("Example tool"),
        subcommands: &[&CONFIG],
        ..Command::EMPTY
    };

    #[test]
    fn command_and_value_metadata_cannot_inject_terminal_controls() {
        let token = Flag {
            key: 99,
            name: "token",
            help: None,
            longs: &["token"],
            accepted_values: &["safe", "bad\n\u{1b}[31m"],
            ..Flag::VALUE
        };
        let flags = [&token];
        let command = Command { name: "tool\n\u{1b}[31m", flags: &flags, ..Command::EMPTY };
        let help = render(&[&command]);

        assert!(!help.contains("tool\n\u{1b}"));
        assert!(!help.contains("bad\n\u{1b}"));
        assert!(!help.contains('\u{1b}'));
        assert!(help.contains(r"bad\n"));
        assert!(help.contains(r"tool\n"));
    }

    #[test]
    fn renders_scope_aware_aligned_help() {
        snapbox::Assert::new().action_env("SNAPSHOTS").eq(
            render(&[&ROOT, &CONFIG]),
            snapbox::str![[r#"
Manage configuration

Usage: tool config [OPTIONS] --destination <DESTINATION> <INPUT> [REST]... <COMMAND>

Arguments:
  <INPUT>    Input file
  [REST]...

Commands:
  get  Read one value

Options:
  -v, --verbose                    Enable verbose output
      --destination <DESTINATION>  Write to this path
      --profile <PROFILE>          Select a profile
  -h, --help                       Print help (see more with '--help')

"#]],
        );
    }

    #[test]
    fn styling_emphasizes_headings_commands_and_flags() {
        let styled = style_headings(
            "Usage: tool\n\nCommands:\n  serve  Start server\n\nLogging:\n  -v, --verbose  Verbose\n      --level <LEVEL>  Log level\n          -v      Errors\n",
        );

        assert!(styled.contains("\x1b[1;4mUsage:\x1b[0m tool"));
        assert!(styled.contains("\x1b[1;4mCommands:\x1b[0m"));
        assert!(styled.contains("  \x1b[1mserve\x1b[0m  Start server"));
        assert!(styled.contains("\x1b[1;4mLogging:\x1b[0m"));
        assert!(styled.contains("  \x1b[1m-v,\x1b[0m \x1b[1m--verbose\x1b[0m  Verbose"));
        assert!(styled.contains("      \x1b[1m--level\x1b[0m <LEVEL>  Log level"));
        assert!(styled.contains("          -v      Errors"));
    }

    #[test]
    fn descendant_help_includes_visible_globals_with_parser_shadowing() {
        static ROOT_SCOPE: Flag<'static> = Flag {
            key: 10,
            name: "root-scope",
            help: Some("Root scope"),
            longs: &["scope", "root-scope"],
            shorts: b"s",
            global: true,
            ..Flag::BOOL
        };
        static ROOT_PROFILE: Flag<'static> = Flag {
            key: 11,
            name: "profile",
            help: Some("Required profile"),
            longs: &["profile"],
            shorts: b"p",
            global: true,
            required: true,
            ..Flag::VALUE
        };
        static ROOT_VERSION: Flag<'static> = Flag {
            key: 12,
            name: "root-version",
            help: Some("Root version selector"),
            longs: &["version", "root-version"],
            global: true,
            ..Flag::BOOL
        };
        static MID_SCOPE: Flag<'static> = Flag {
            key: 13,
            name: "mid-scope",
            help: Some("Mid scope"),
            longs: &["scope", "mid-scope"],
            shorts: b"m",
            global: true,
            ..Flag::BOOL
        };
        static LOCAL_SCOPE: Flag<'static> = Flag {
            key: 14,
            name: "scope",
            help: Some("Leaf scope"),
            longs: &["scope"],
            shorts: b"l",
            ..Flag::BOOL
        };
        static VERSION: Action<'static> = Action {
            name: "version",
            diagnostic: "--version",
            help: "Print version",
            longs: &["version"],
            shorts: b"V",
            kind: ActionKind::Version { short: "1", long: "1" },
        };
        static LEAF: Command<'static> = Command {
            name: "leaf",
            actions: &[&crate::__private::HELP_ACTION, &VERSION],
            flags: &[&LOCAL_SCOPE],
            ..Command::EMPTY
        };
        static MID: Command<'static> =
            Command { name: "mid", flags: &[&MID_SCOPE], subcommands: &[&LEAF], ..Command::EMPTY };
        static GLOBAL_ROOT: Command<'static> = Command {
            name: "tool",
            flags: &[&ROOT_SCOPE, &ROOT_PROFILE, &ROOT_VERSION],
            subcommands: &[&MID],
            ..Command::EMPTY
        };

        snapbox::Assert::new().action_env("SNAPSHOTS").eq(
            render(&[&GLOBAL_ROOT, &MID, &LEAF]),
            snapbox::str![[r#"
Usage: tool --profile <PROFILE> mid leaf [OPTIONS]

Options:
  -l, --scope              Leaf scope
  -m, --mid-scope          Mid scope
  -s, --root-scope         Root scope
  -p, --profile <PROFILE>  Required profile
      --root-version       Root version selector
  -h, --help               Print help (see more with '--help')
  -V, --version            Print version

"#]],
        );
    }

    #[test]
    fn descendant_usage_keeps_required_ancestor_flags_at_their_declaring_scope() {
        static ROOT_TOKEN: Flag<'static> = Flag {
            key: 20,
            name: "root-token",
            help: Some("Root token"),
            longs: &["token"],
            global: true,
            required: true,
            ..Flag::VALUE
        };
        static ROOT_CONFIG: Flag<'static> = Flag {
            key: 21,
            name: "config",
            help: Some("Root config"),
            longs: &["config"],
            required: true,
            ..Flag::VALUE
        };
        static LOCAL_TOKEN: Flag<'static> = Flag {
            key: 22,
            name: "token",
            help: Some("Leaf token"),
            longs: &["token"],
            ..Flag::VALUE
        };
        static LEAF: Command<'static> =
            Command { name: "leaf", flags: &[&LOCAL_TOKEN], ..Command::EMPTY };
        static ROOT: Command<'static> = Command {
            name: "tool",
            flags: &[&ROOT_TOKEN, &ROOT_CONFIG],
            subcommands: &[&LEAF],
            ..Command::EMPTY
        };

        snapbox::Assert::new().action_env("SNAPSHOTS").eq(
            render(&[&ROOT, &LEAF]),
            snapbox::str![[r#"
Usage: tool --token <ROOT_TOKEN> --config <CONFIG> leaf [OPTIONS]

Options:
      --token <TOKEN>  Leaf token
  -h, --help           Print help (see more with '--help')

"#]],
        );
    }

    #[test]
    fn reused_global_mount_is_listed_only_for_the_nearest_scope() {
        static SHARED: Flag<'static> = Flag {
            key: 30,
            name: "shared",
            help: Some("Shared setting"),
            longs: &["shared"],
            global: true,
            ..Flag::VALUE
        };
        static LEAF: Command<'static> =
            Command { name: "leaf", flags: &[&SHARED], ..Command::EMPTY };
        static ROOT: Command<'static> =
            Command { name: "tool", flags: &[&SHARED], subcommands: &[&LEAF], ..Command::EMPTY };

        snapbox::Assert::new().action_env("SNAPSHOTS").eq(
            render(&[&ROOT, &LEAF]),
            snapbox::str![[r#"
Usage: tool leaf [OPTIONS]

Options:
      --shared <SHARED>  Shared setting
  -h, --help             Print help (see more with '--help')

"#]],
        );
    }
}