Struct clap::builder::Command

source ·
pub struct Command { /* private fields */ }
Expand description

Build a command-line interface.

This includes defining arguments, subcommands, parser behavior, and help output. Once all configuration is complete, the Command::get_matches family of methods starts the runtime-parsing process. These methods then return information about the user supplied arguments (or lack thereof).

When deriving a Parser, you can use CommandFactory::command to access the Command.

Examples

let m = Command::new("My Program")
    .author("Me, me@mail.com")
    .version("1.0.2")
    .about("Explains in brief what the program does")
    .arg(
        Arg::new("in_file")
    )
    .after_help("Longer explanation to appear after the options when \
                 displaying the help information from --help or -h")
    .get_matches();

// Your program logic starts here...

Implementations§

Creates a new instance of an Command.

It is common, but not required, to use binary name as the name. This name will only be displayed to the user when they request to print version or help and usage information.

See also command! and crate_name!.

Examples
Command::new("My Program")
Examples found in repository?
src/builder/debug_asserts.rs (line 855)
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
fn assert_defaults<'d>(
    arg: &Arg,
    field: &'static str,
    defaults: impl IntoIterator<Item = &'d OsStr>,
) {
    for default_os in defaults {
        let value_parser = arg.get_value_parser();
        let assert_cmd = Command::new("assert");
        if let Some(delim) = arg.get_value_delimiter() {
            let default_os = RawOsStr::new(default_os);
            for part in default_os.split(delim) {
                if let Err(err) = value_parser.parse_ref(&assert_cmd, Some(arg), &part.to_os_str())
                {
                    panic!(
                        "Argument `{}`'s {}={:?} failed validation: {}",
                        arg.get_id(),
                        field,
                        part.to_str_lossy(),
                        err
                    );
                }
            }
        } else if let Err(err) = value_parser.parse_ref(&assert_cmd, Some(arg), default_os) {
            panic!(
                "Argument `{}`'s {}={:?} failed validation: {}",
                arg.get_id(),
                field,
                default_os,
                err
            );
        }
    }
}
More examples
Hide additional examples
src/builder/command.rs (line 4273)
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
    pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) {
        debug!(
            "Command::_check_help_and_version:{} expand_help_tree={}",
            self.name, expand_help_tree
        );

        self.long_help_exists = self.long_help_exists_();

        if !self.is_disable_help_flag_set() {
            debug!("Command::_check_help_and_version: Building default --help");
            let mut arg = Arg::new(Id::HELP)
                .short('h')
                .long("help")
                .action(ArgAction::Help);
            if self.long_help_exists {
                arg = arg
                    .help("Print help information (use `--help` for more detail)")
                    .long_help("Print help information (use `-h` for a summary)");
            } else {
                arg = arg.help("Print help information");
            }
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }
        if !self.is_disable_version_flag_set() {
            debug!("Command::_check_help_and_version: Building default --version");
            let arg = Arg::new(Id::VERSION)
                .short('V')
                .long("version")
                .action(ArgAction::Version)
                .help("Print version information");
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }

        if !self.is_set(AppSettings::DisableHelpSubcommand) {
            debug!("Command::_check_help_and_version: Building help subcommand");
            let help_about = "Print this message or the help of the given subcommand(s)";

            let mut help_subcmd = if expand_help_tree {
                // Slow code path to recursively clone all other subcommand subtrees under help
                let help_subcmd = Command::new("help")
                    .about(help_about)
                    .global_setting(AppSettings::DisableHelpSubcommand)
                    .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));

                let mut help_help_subcmd = Command::new("help").about(help_about);
                help_help_subcmd.version = None;
                help_help_subcmd.long_version = None;
                help_help_subcmd = help_help_subcmd
                    .setting(AppSettings::DisableHelpFlag)
                    .setting(AppSettings::DisableVersionFlag);

                help_subcmd.subcommand(help_help_subcmd)
            } else {
                Command::new("help").about(help_about).arg(
                    Arg::new("subcommand")
                        .action(ArgAction::Append)
                        .num_args(..)
                        .value_name("COMMAND")
                        .help("Print help for the subcommand(s)"),
                )
            };
            self._propagate_subcommand(&mut help_subcmd);

            // The parser acts like this is set, so let's set it so we don't falsely
            // advertise it to the user
            help_subcmd.version = None;
            help_subcmd.long_version = None;
            help_subcmd = help_subcmd
                .setting(AppSettings::DisableHelpFlag)
                .setting(AppSettings::DisableVersionFlag)
                .unset_global_setting(AppSettings::PropagateVersion);

            self.subcommands.push(help_subcmd);
        }
    }

    fn _copy_subtree_for_help(&self) -> Command {
        let mut cmd = Command::new(self.name.clone())
            .hide(self.is_hide_set())
            .global_setting(AppSettings::DisableHelpFlag)
            .global_setting(AppSettings::DisableVersionFlag)
            .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));
        if self.get_about().is_some() {
            cmd = cmd.about(self.get_about().unwrap().clone());
        }
        cmd
    }

Adds an argument to the list of valid possibilities.

Examples
Command::new("myprog")
    // Adding a single "flag" argument with a short and help text, using Arg::new()
    .arg(
        Arg::new("debug")
           .short('d')
           .help("turns on debugging mode")
    )
    // Adding a single "option" argument with a short, a long, and help text using the less
    // verbose Arg::from()
    .arg(
        arg!(-c --config <CONFIG> "Optionally sets a config file to use")
    )
Examples found in repository?
src/builder/command.rs (line 202)
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
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
    pub fn args(mut self, args: impl IntoIterator<Item = impl Into<Arg>>) -> Self {
        for arg in args {
            self = self.arg(arg);
        }
        self
    }

    /// Allows one to mutate an [`Arg`] after it's been added to a [`Command`].
    ///
    /// This can be useful for modifying the auto-generated help or version arguments.
    ///
    /// # Panics
    ///
    /// If the argument is undefined
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg, ArgAction};
    ///
    /// let mut cmd = Command::new("foo")
    ///     .arg(Arg::new("bar")
    ///         .short('b')
    ///         .action(ArgAction::SetTrue))
    ///     .mut_arg("bar", |a| a.short('B'));
    ///
    /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]);
    ///
    /// // Since we changed `bar`'s short to "B" this should err as there
    /// // is no `-b` anymore, only `-B`
    ///
    /// assert!(res.is_err());
    ///
    /// let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]);
    /// assert!(res.is_ok());
    /// ```
    #[must_use]
    #[cfg_attr(debug_assertions, track_caller)]
    pub fn mut_arg<F>(mut self, arg_id: impl AsRef<str>, f: F) -> Self
    where
        F: FnOnce(Arg) -> Arg,
    {
        let id = arg_id.as_ref();
        let a = self
            .args
            .remove_by_name(id)
            .unwrap_or_else(|| panic!("Argument `{}` is undefined", id));

        self.args.push(f(a));
        self
    }

    /// Allows one to mutate a [`Command`] after it's been added as a subcommand.
    ///
    /// This can be useful for modifying auto-generated arguments of nested subcommands with
    /// [`Command::mut_arg`].
    ///
    /// # Panics
    ///
    /// If the subcommand is undefined
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::Command;
    ///
    /// let mut cmd = Command::new("foo")
    ///         .subcommand(Command::new("bar"))
    ///         .mut_subcommand("bar", |subcmd| subcmd.disable_help_flag(true));
    ///
    /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar", "--help"]);
    ///
    /// // Since we disabled the help flag on the "bar" subcommand, this should err.
    ///
    /// assert!(res.is_err());
    ///
    /// let res = cmd.try_get_matches_from_mut(vec!["foo", "bar"]);
    /// assert!(res.is_ok());
    /// ```
    #[must_use]
    pub fn mut_subcommand<F>(mut self, name: impl AsRef<str>, f: F) -> Self
    where
        F: FnOnce(Self) -> Self,
    {
        let name = name.as_ref();
        let pos = self.subcommands.iter().position(|s| s.name == name);

        let subcmd = if let Some(idx) = pos {
            self.subcommands.remove(idx)
        } else {
            panic!("Command `{}` is undefined", name)
        };

        self.subcommands.push(f(subcmd));
        self
    }

    /// Adds an [`ArgGroup`] to the application.
    ///
    /// [`ArgGroup`]s are a family of related arguments.
    /// By placing them in a logical group, you can build easier requirement and exclusion rules.
    ///
    /// Example use cases:
    /// - Make an entire [`ArgGroup`] required, meaning that one (and *only*
    ///   one) argument from that group must be present at runtime.
    /// - Name an [`ArgGroup`] as a conflict to another argument.
    ///   Meaning any of the arguments that belong to that group will cause a failure if present with
    ///   the conflicting argument.
    /// - Ensure exclusion between arguments.
    /// - Extract a value from a group instead of determining exactly which argument was used.
    ///
    /// # Examples
    ///
    /// The following example demonstrates using an [`ArgGroup`] to ensure that one, and only one,
    /// of the arguments from the specified group is present at runtime.
    ///
    /// ```no_run
    /// # use clap::{Command, arg, ArgGroup};
    /// Command::new("cmd")
    ///     .arg(arg!("--set-ver [ver] 'set the version manually'"))
    ///     .arg(arg!("--major 'auto increase major'"))
    ///     .arg(arg!("--minor 'auto increase minor'"))
    ///     .arg(arg!("--patch 'auto increase patch'"))
    ///     .group(ArgGroup::new("vers")
    ///          .args(["set-ver", "major", "minor","patch"])
    ///          .required(true))
    /// # ;
    /// ```
    #[inline]
    #[must_use]
    pub fn group(mut self, group: impl Into<ArgGroup>) -> Self {
        self.groups.push(group.into());
        self
    }

    /// Adds multiple [`ArgGroup`]s to the [`Command`] at once.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, arg, ArgGroup};
    /// Command::new("cmd")
    ///     .arg(arg!("--set-ver [ver] 'set the version manually'"))
    ///     .arg(arg!("--major         'auto increase major'"))
    ///     .arg(arg!("--minor         'auto increase minor'"))
    ///     .arg(arg!("--patch         'auto increase patch'"))
    ///     .arg(arg!("-c [FILE]       'a config file'"))
    ///     .arg(arg!("-i [IFACE]      'an interface'"))
    ///     .groups([
    ///         ArgGroup::new("vers")
    ///             .args(["set-ver", "major", "minor","patch"])
    ///             .required(true),
    ///         ArgGroup::new("input")
    ///             .args(["c", "i"])
    ///     ])
    /// # ;
    /// ```
    #[must_use]
    pub fn groups(mut self, groups: impl IntoIterator<Item = impl Into<ArgGroup>>) -> Self {
        for g in groups.into_iter() {
            self = self.group(g.into());
        }
        self
    }

    /// Adds a subcommand to the list of valid possibilities.
    ///
    /// Subcommands are effectively sub-[`Command`]s, because they can contain their own arguments,
    /// subcommands, version, usage, etc. They also function just like [`Command`]s, in that they get
    /// their own auto generated help, version, and usage.
    ///
    /// A subcommand's [`Command::name`] will be used for:
    /// - The argument the user passes in
    /// - Programmatically looking up the subcommand
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, arg};
    /// Command::new("myprog")
    ///     .subcommand(Command::new("config")
    ///         .about("Controls configuration features")
    ///         .arg(arg!("<config> 'Required configuration file to use'")))
    /// # ;
    /// ```
    #[inline]
    #[must_use]
    pub fn subcommand(self, subcmd: impl Into<Command>) -> Self {
        let subcmd = subcmd.into();
        self.subcommand_internal(subcmd)
    }

    fn subcommand_internal(mut self, mut subcmd: Self) -> Self {
        if let Some(current_disp_ord) = self.current_disp_ord.as_mut() {
            let current = *current_disp_ord;
            subcmd.disp_ord.get_or_insert(current);
            *current_disp_ord = current + 1;
        }
        self.subcommands.push(subcmd);
        self
    }

    /// Adds multiple subcommands to the list of valid possibilities.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg, };
    /// # Command::new("myprog")
    /// .subcommands( [
    ///        Command::new("config").about("Controls configuration functionality")
    ///                                 .arg(Arg::new("config_file")),
    ///        Command::new("debug").about("Controls debug functionality")])
    /// # ;
    /// ```
    /// [`IntoIterator`]: std::iter::IntoIterator
    #[must_use]
    pub fn subcommands(mut self, subcmds: impl IntoIterator<Item = impl Into<Self>>) -> Self {
        for subcmd in subcmds {
            self = self.subcommand(subcmd);
        }
        self
    }

    /// Catch problems earlier in the development cycle.
    ///
    /// Most error states are handled as asserts under the assumption they are programming mistake
    /// and not something to handle at runtime.  Rather than relying on tests (manual or automated)
    /// that exhaustively test your CLI to ensure the asserts are evaluated, this will run those
    /// asserts in a way convenient for running as a test.
    ///
    /// **Note::** This will not help with asserts in [`ArgMatches`], those will need exhaustive
    /// testing of your CLI.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg, ArgAction};
    /// fn cmd() -> Command {
    ///     Command::new("foo")
    ///         .arg(
    ///             Arg::new("bar").short('b').action(ArgAction::SetTrue)
    ///         )
    /// }
    ///
    /// #[test]
    /// fn verify_app() {
    ///     cmd().debug_assert();
    /// }
    ///
    /// fn main() {
    ///     let m = cmd().get_matches_from(vec!["foo", "-b"]);
    ///     println!("{}", *m.get_one::<bool>("bar").expect("defaulted by clap"));
    /// }
    /// ```
    pub fn debug_assert(mut self) {
        self.build();
    }

    /// Custom error message for post-parsing validation
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, error::ErrorKind};
    /// let mut cmd = Command::new("myprog");
    /// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case");
    /// ```
    pub fn error(&mut self, kind: ErrorKind, message: impl std::fmt::Display) -> Error {
        Error::raw(kind, message).format(self)
    }

    /// Parse [`env::args_os`], exiting on failure.
    ///
    /// # Panics
    ///
    /// If contradictory arguments or settings exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let matches = Command::new("myprog")
    ///     // Args and options go here...
    ///     .get_matches();
    /// ```
    /// [`env::args_os`]: std::env::args_os()
    /// [`Command::try_get_matches_from_mut`]: Command::try_get_matches_from_mut()
    #[inline]
    pub fn get_matches(self) -> ArgMatches {
        self.get_matches_from(&mut env::args_os())
    }

    /// Parse [`env::args_os`], exiting on failure.
    ///
    /// Like [`Command::get_matches`] but doesn't consume the `Command`.
    ///
    /// # Panics
    ///
    /// If contradictory arguments or settings exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let mut cmd = Command::new("myprog")
    ///     // Args and options go here...
    ///     ;
    /// let matches = cmd.get_matches_mut();
    /// ```
    /// [`env::args_os`]: std::env::args_os()
    /// [`Command::get_matches`]: Command::get_matches()
    pub fn get_matches_mut(&mut self) -> ArgMatches {
        self.try_get_matches_from_mut(&mut env::args_os())
            .unwrap_or_else(|e| e.exit())
    }

    /// Parse [`env::args_os`], returning a [`clap::Result`] on failure.
    ///
    /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
    /// used. It will return a [`clap::Error`], where the [`kind`] is a
    /// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call
    /// [`Error::exit`] or perform a [`std::process::exit`].
    ///
    /// # Panics
    ///
    /// If contradictory arguments or settings exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let matches = Command::new("myprog")
    ///     // Args and options go here...
    ///     .try_get_matches()
    ///     .unwrap_or_else(|e| e.exit());
    /// ```
    /// [`env::args_os`]: std::env::args_os()
    /// [`Error::exit`]: crate::Error::exit()
    /// [`std::process::exit`]: std::process::exit()
    /// [`clap::Result`]: Result
    /// [`clap::Error`]: crate::Error
    /// [`kind`]: crate::Error
    /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp
    /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion
    #[inline]
    pub fn try_get_matches(self) -> ClapResult<ArgMatches> {
        // Start the parsing
        self.try_get_matches_from(&mut env::args_os())
    }

    /// Parse the specified arguments, exiting on failure.
    ///
    /// **NOTE:** The first argument will be parsed as the binary name unless
    /// [`Command::no_binary_name`] is used.
    ///
    /// # Panics
    ///
    /// If contradictory arguments or settings exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
    ///
    /// let matches = Command::new("myprog")
    ///     // Args and options go here...
    ///     .get_matches_from(arg_vec);
    /// ```
    /// [`Command::get_matches`]: Command::get_matches()
    /// [`clap::Result`]: Result
    /// [`Vec`]: std::vec::Vec
    pub fn get_matches_from<I, T>(mut self, itr: I) -> ArgMatches
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        self.try_get_matches_from_mut(itr).unwrap_or_else(|e| {
            drop(self);
            e.exit()
        })
    }

    /// Parse the specified arguments, returning a [`clap::Result`] on failure.
    ///
    /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
    /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
    /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
    /// perform a [`std::process::exit`] yourself.
    ///
    /// **NOTE:** The first argument will be parsed as the binary name unless
    /// [`Command::no_binary_name`] is used.
    ///
    /// # Panics
    ///
    /// If contradictory arguments or settings exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
    ///
    /// let matches = Command::new("myprog")
    ///     // Args and options go here...
    ///     .try_get_matches_from(arg_vec)
    ///     .unwrap_or_else(|e| e.exit());
    /// ```
    /// [`Command::get_matches_from`]: Command::get_matches_from()
    /// [`Command::try_get_matches`]: Command::try_get_matches()
    /// [`Error::exit`]: crate::Error::exit()
    /// [`std::process::exit`]: std::process::exit()
    /// [`clap::Error`]: crate::Error
    /// [`Error::exit`]: crate::Error::exit()
    /// [`kind`]: crate::Error
    /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp
    /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion
    /// [`clap::Result`]: Result
    pub fn try_get_matches_from<I, T>(mut self, itr: I) -> ClapResult<ArgMatches>
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        self.try_get_matches_from_mut(itr)
    }

    /// Parse the specified arguments, returning a [`clap::Result`] on failure.
    ///
    /// Like [`Command::try_get_matches_from`] but doesn't consume the `Command`.
    ///
    /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
    /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
    /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
    /// perform a [`std::process::exit`] yourself.
    ///
    /// **NOTE:** The first argument will be parsed as the binary name unless
    /// [`Command::no_binary_name`] is used.
    ///
    /// # Panics
    ///
    /// If contradictory arguments or settings exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
    ///
    /// let mut cmd = Command::new("myprog");
    ///     // Args and options go here...
    /// let matches = cmd.try_get_matches_from_mut(arg_vec)
    ///     .unwrap_or_else(|e| e.exit());
    /// ```
    /// [`Command::try_get_matches_from`]: Command::try_get_matches_from()
    /// [`clap::Result`]: Result
    /// [`clap::Error`]: crate::Error
    /// [`kind`]: crate::Error
    pub fn try_get_matches_from_mut<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches>
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        let mut raw_args = clap_lex::RawArgs::new(itr.into_iter());
        let mut cursor = raw_args.cursor();

        if self.settings.is_set(AppSettings::Multicall) {
            if let Some(argv0) = raw_args.next_os(&mut cursor) {
                let argv0 = Path::new(&argv0);
                if let Some(command) = argv0.file_stem().and_then(|f| f.to_str()) {
                    // Stop borrowing command so we can get another mut ref to it.
                    let command = command.to_owned();
                    debug!(
                        "Command::try_get_matches_from_mut: Parsed command {} from argv",
                        command
                    );

                    debug!("Command::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it");
                    raw_args.insert(&cursor, [&command]);
                    debug!("Command::try_get_matches_from_mut: Clearing name and bin_name so that displayed command name starts with applet name");
                    self.name = "".into();
                    self.bin_name = None;
                    return self._do_parse(&mut raw_args, cursor);
                }
            }
        };

        // Get the name of the program (argument 1 of env::args()) and determine the
        // actual file
        // that was used to execute the program. This is because a program called
        // ./target/release/my_prog -a
        // will have two arguments, './target/release/my_prog', '-a' but we don't want
        // to display
        // the full path when displaying help messages and such
        if !self.settings.is_set(AppSettings::NoBinaryName) {
            if let Some(name) = raw_args.next_os(&mut cursor) {
                let p = Path::new(name);

                if let Some(f) = p.file_name() {
                    if let Some(s) = f.to_str() {
                        if self.bin_name.is_none() {
                            self.bin_name = Some(s.to_owned());
                        }
                    }
                }
            }
        }

        self._do_parse(&mut raw_args, cursor)
    }

    /// Prints the short help message (`-h`) to [`io::stdout()`].
    ///
    /// See also [`Command::print_long_help`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// let mut cmd = Command::new("myprog");
    /// cmd.print_help();
    /// ```
    /// [`io::stdout()`]: std::io::stdout()
    pub fn print_help(&mut self) -> io::Result<()> {
        self._build_self(false);
        let color = self.color_help();

        let mut styled = StyledStr::new();
        let usage = Usage::new(self);
        write_help(&mut styled, self, &usage, false);

        let c = Colorizer::new(Stream::Stdout, color).with_content(styled);
        c.print()
    }

    /// Prints the long help message (`--help`) to [`io::stdout()`].
    ///
    /// See also [`Command::print_help`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// let mut cmd = Command::new("myprog");
    /// cmd.print_long_help();
    /// ```
    /// [`io::stdout()`]: std::io::stdout()
    /// [`BufWriter`]: std::io::BufWriter
    /// [`-h` (short)]: Arg::help()
    /// [`--help` (long)]: Arg::long_help()
    pub fn print_long_help(&mut self) -> io::Result<()> {
        self._build_self(false);
        let color = self.color_help();

        let mut styled = StyledStr::new();
        let usage = Usage::new(self);
        write_help(&mut styled, self, &usage, true);

        let c = Colorizer::new(Stream::Stdout, color).with_content(styled);
        c.print()
    }

    /// Render the short help message (`-h`) to a [`StyledStr`]
    ///
    /// See also [`Command::render_long_help`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// use std::io;
    /// let mut cmd = Command::new("myprog");
    /// let mut out = io::stdout();
    /// let help = cmd.render_help();
    /// println!("{}", help);
    /// ```
    /// [`io::Write`]: std::io::Write
    /// [`-h` (short)]: Arg::help()
    /// [`--help` (long)]: Arg::long_help()
    pub fn render_help(&mut self) -> StyledStr {
        self._build_self(false);

        let mut styled = StyledStr::new();
        let usage = Usage::new(self);
        write_help(&mut styled, self, &usage, false);
        styled
    }

    /// Render the long help message (`--help`) to a [`StyledStr`].
    ///
    /// See also [`Command::render_help`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// use std::io;
    /// let mut cmd = Command::new("myprog");
    /// let mut out = io::stdout();
    /// let help = cmd.render_long_help();
    /// println!("{}", help);
    /// ```
    /// [`io::Write`]: std::io::Write
    /// [`-h` (short)]: Arg::help()
    /// [`--help` (long)]: Arg::long_help()
    pub fn render_long_help(&mut self) -> StyledStr {
        self._build_self(false);

        let mut styled = StyledStr::new();
        let usage = Usage::new(self);
        write_help(&mut styled, self, &usage, true);
        styled
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "Replaced with `Command::render_help`")
    )]
    pub fn write_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> {
        self._build_self(false);

        let mut styled = StyledStr::new();
        let usage = Usage::new(self);
        write_help(&mut styled, self, &usage, false);
        ok!(write!(w, "{}", styled));
        w.flush()
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "Replaced with `Command::render_long_help`")
    )]
    pub fn write_long_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> {
        self._build_self(false);

        let mut styled = StyledStr::new();
        let usage = Usage::new(self);
        write_help(&mut styled, self, &usage, true);
        ok!(write!(w, "{}", styled));
        w.flush()
    }

    /// Version message rendered as if the user ran `-V`.
    ///
    /// See also [`Command::render_long_version`].
    ///
    /// ### Coloring
    ///
    /// This function does not try to color the message nor it inserts any [ANSI escape codes].
    ///
    /// ### Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// use std::io;
    /// let cmd = Command::new("myprog");
    /// println!("{}", cmd.render_version());
    /// ```
    /// [`io::Write`]: std::io::Write
    /// [`-V` (short)]: Command::version()
    /// [`--version` (long)]: Command::long_version()
    /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
    pub fn render_version(&self) -> String {
        self._render_version(false)
    }

    /// Version message rendered as if the user ran `--version`.
    ///
    /// See also [`Command::render_version`].
    ///
    /// ### Coloring
    ///
    /// This function does not try to color the message nor it inserts any [ANSI escape codes].
    ///
    /// ### Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// use std::io;
    /// let cmd = Command::new("myprog");
    /// println!("{}", cmd.render_long_version());
    /// ```
    /// [`io::Write`]: std::io::Write
    /// [`-V` (short)]: Command::version()
    /// [`--version` (long)]: Command::long_version()
    /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
    pub fn render_long_version(&self) -> String {
        self._render_version(true)
    }

    /// Usage statement
    ///
    /// ### Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// use std::io;
    /// let mut cmd = Command::new("myprog");
    /// println!("{}", cmd.render_usage());
    /// ```
    pub fn render_usage(&mut self) -> StyledStr {
        self.render_usage_().unwrap_or_default()
    }

    pub(crate) fn render_usage_(&mut self) -> Option<StyledStr> {
        // If there are global arguments, or settings we need to propagate them down to subcommands
        // before parsing incase we run into a subcommand
        self._build_self(false);

        Usage::new(self).create_usage_with_title(&[])
    }
}

/// # Application-wide Settings
///
/// These settings will apply to the top-level command and all subcommands, by default.  Some
/// settings can be overridden in subcommands.
impl Command {
    /// Specifies that the parser should not assume the first argument passed is the binary name.
    ///
    /// This is normally the case when using a "daemon" style mode.  For shells / REPLs, see
    /// [`Command::multicall`][Command::multicall].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, arg};
    /// let m = Command::new("myprog")
    ///     .no_binary_name(true)
    ///     .arg(arg!(<cmd> ... "commands to run"))
    ///     .get_matches_from(vec!["command", "set"]);
    ///
    /// let cmds: Vec<_> = m.get_many::<String>("cmd").unwrap().collect();
    /// assert_eq!(cmds, ["command", "set"]);
    /// ```
    /// [`try_get_matches_from_mut`]: crate::Command::try_get_matches_from_mut()
    #[inline]
    pub fn no_binary_name(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::NoBinaryName)
        } else {
            self.unset_global_setting(AppSettings::NoBinaryName)
        }
    }

    /// Try not to fail on parse errors, like missing option values.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, arg};
    /// let cmd = Command::new("cmd")
    ///   .ignore_errors(true)
    ///   .arg(arg!(-c --config <FILE> "Sets a custom config file"))
    ///   .arg(arg!(-x --stuff <FILE> "Sets a custom stuff file"))
    ///   .arg(arg!(f: -f "Flag"));
    ///
    /// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]);
    ///
    /// assert!(r.is_ok(), "unexpected error: {:?}", r);
    /// let m = r.unwrap();
    /// assert_eq!(m.get_one::<String>("config").unwrap(), "file");
    /// assert!(*m.get_one::<bool>("f").expect("defaulted"));
    /// assert_eq!(m.get_one::<String>("stuff"), None);
    /// ```
    #[inline]
    pub fn ignore_errors(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::IgnoreErrors)
        } else {
            self.unset_global_setting(AppSettings::IgnoreErrors)
        }
    }

    /// Replace prior occurrences of arguments rather than error
    ///
    /// For any argument that would conflict with itself by default (e.g.
    /// [`ArgAction::Set`][ArgAction::Set], it will now override itself.
    ///
    /// This is the equivalent to saying the `foo` arg using [`Arg::overrides_with("foo")`] for all
    /// defined arguments.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// [`Arg::overrides_with("foo")`]: crate::Arg::overrides_with()
    #[inline]
    pub fn args_override_self(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::AllArgsOverrideSelf)
        } else {
            self.unset_global_setting(AppSettings::AllArgsOverrideSelf)
        }
    }

    /// Disables the automatic delimiting of values after `--` or when [`Command::trailing_var_arg`]
    /// was used.
    ///
    /// **NOTE:** The same thing can be done manually by setting the final positional argument to
    /// [`Arg::value_delimiter(None)`]. Using this setting is safer, because it's easier to locate
    /// when making changes.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .dont_delimit_trailing_values(true)
    ///     .get_matches();
    /// ```
    ///
    /// [`Arg::value_delimiter(None)`]: crate::Arg::value_delimiter()
    #[inline]
    pub fn dont_delimit_trailing_values(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::DontDelimitTrailingValues)
        } else {
            self.unset_global_setting(AppSettings::DontDelimitTrailingValues)
        }
    }

    /// Sets when to color output.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// **NOTE:** Default behaviour is [`ColorChoice::Auto`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, ColorChoice};
    /// Command::new("myprog")
    ///     .color(ColorChoice::Never)
    ///     .get_matches();
    /// ```
    /// [`ColorChoice::Auto`]: crate::ColorChoice::Auto
    #[cfg(feature = "color")]
    #[inline]
    #[must_use]
    pub fn color(self, color: ColorChoice) -> Self {
        let cmd = self
            .unset_global_setting(AppSettings::ColorAuto)
            .unset_global_setting(AppSettings::ColorAlways)
            .unset_global_setting(AppSettings::ColorNever);
        match color {
            ColorChoice::Auto => cmd.global_setting(AppSettings::ColorAuto),
            ColorChoice::Always => cmd.global_setting(AppSettings::ColorAlways),
            ColorChoice::Never => cmd.global_setting(AppSettings::ColorNever),
        }
    }

    /// Sets the terminal width at which to wrap help messages.
    ///
    /// Using `0` will ignore terminal widths and use source formatting.
    ///
    /// Defaults to current terminal width when `wrap_help` feature flag is enabled.  If the flag
    /// is disabled or it cannot be determined, the default is 100.
    ///
    /// **NOTE:** This setting applies globally and *not* on a per-command basis.
    ///
    /// **NOTE:** This requires the [`wrap_help` feature][crate::_features]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .term_width(80)
    /// # ;
    /// ```
    #[inline]
    #[must_use]
    #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))]
    pub fn term_width(mut self, width: usize) -> Self {
        self.term_w = Some(width);
        self
    }

    /// Limit the line length for wrapping help when using the current terminal's width.
    ///
    /// This only applies when [`term_width`][Command::term_width] is unset so that the current
    /// terminal's width will be used.  See [`Command::term_width`] for more details.
    ///
    /// Using `0` will ignore terminal widths and use source formatting (default).
    ///
    /// **NOTE:** This setting applies globally and *not* on a per-command basis.
    ///
    /// **NOTE:** This requires the [`wrap_help` feature][crate::_features]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .max_term_width(100)
    /// # ;
    /// ```
    #[inline]
    #[must_use]
    #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))]
    pub fn max_term_width(mut self, w: usize) -> Self {
        self.max_w = Some(w);
        self
    }

    /// Disables `-V` and `--version` flag.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, error::ErrorKind};
    /// let res = Command::new("myprog")
    ///     .disable_version_flag(true)
    ///     .try_get_matches_from(vec![
    ///         "myprog", "-V"
    ///     ]);
    /// assert!(res.is_err());
    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
    /// ```
    #[inline]
    pub fn disable_version_flag(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::DisableVersionFlag)
        } else {
            self.unset_global_setting(AppSettings::DisableVersionFlag)
        }
    }

    /// Specifies to use the version of the current command for all [`subcommands`].
    ///
    /// Defaults to `false`; subcommands have independent version strings from their parents.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .version("v1.1")
    ///     .propagate_version(true)
    ///     .subcommand(Command::new("test"))
    ///     .get_matches();
    /// // running `$ myprog test --version` will display
    /// // "myprog-test v1.1"
    /// ```
    ///
    /// [`subcommands`]: crate::Command::subcommand()
    #[inline]
    pub fn propagate_version(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::PropagateVersion)
        } else {
            self.unset_global_setting(AppSettings::PropagateVersion)
        }
    }

    /// Places the help string for all arguments and subcommands on the line after them.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .next_line_help(true)
    ///     .get_matches();
    /// ```
    #[inline]
    pub fn next_line_help(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::NextLineHelp)
        } else {
            self.unset_global_setting(AppSettings::NextLineHelp)
        }
    }

    /// Disables `-h` and `--help` flag.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, error::ErrorKind};
    /// let res = Command::new("myprog")
    ///     .disable_help_flag(true)
    ///     .try_get_matches_from(vec![
    ///         "myprog", "-h"
    ///     ]);
    /// assert!(res.is_err());
    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
    /// ```
    #[inline]
    pub fn disable_help_flag(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::DisableHelpFlag)
        } else {
            self.unset_global_setting(AppSettings::DisableHelpFlag)
        }
    }

    /// Disables the `help` [`subcommand`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, error::ErrorKind};
    /// let res = Command::new("myprog")
    ///     .disable_help_subcommand(true)
    ///     // Normally, creating a subcommand causes a `help` subcommand to automatically
    ///     // be generated as well
    ///     .subcommand(Command::new("test"))
    ///     .try_get_matches_from(vec![
    ///         "myprog", "help"
    ///     ]);
    /// assert!(res.is_err());
    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::InvalidSubcommand);
    /// ```
    ///
    /// [`subcommand`]: crate::Command::subcommand()
    #[inline]
    pub fn disable_help_subcommand(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::DisableHelpSubcommand)
        } else {
            self.unset_global_setting(AppSettings::DisableHelpSubcommand)
        }
    }

    /// Disables colorized help messages.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .disable_colored_help(true)
    ///     .get_matches();
    /// ```
    #[inline]
    pub fn disable_colored_help(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::DisableColoredHelp)
        } else {
            self.unset_global_setting(AppSettings::DisableColoredHelp)
        }
    }

    /// Panic if help descriptions are omitted.
    ///
    /// **NOTE:** When deriving [`Parser`][crate::Parser], you could instead check this at
    /// compile-time with `#![deny(missing_docs)]`
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .help_expected(true)
    ///     .arg(
    ///         Arg::new("foo").help("It does foo stuff")
    ///         // As required via `help_expected`, a help message was supplied
    ///      )
    /// #    .get_matches();
    /// ```
    ///
    /// # Panics
    ///
    /// ```rust,no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myapp")
    ///     .help_expected(true)
    ///     .arg(
    ///         Arg::new("foo")
    ///         // Someone forgot to put .about("...") here
    ///         // Since the setting `help_expected` is activated, this will lead to
    ///         // a panic (if you are in debug mode)
    ///     )
    /// #   .get_matches();
    ///```
    #[inline]
    pub fn help_expected(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::HelpExpected)
        } else {
            self.unset_global_setting(AppSettings::HelpExpected)
        }
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "This is now the default")
    )]
    pub fn dont_collapse_args_in_usage(self, _yes: bool) -> Self {
        self
    }

    /// Tells `clap` *not* to print possible values when displaying help information.
    ///
    /// This can be useful if there are many values, or they are explained elsewhere.
    ///
    /// To set this per argument, see
    /// [`Arg::hide_possible_values`][crate::Arg::hide_possible_values].
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    #[inline]
    pub fn hide_possible_values(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::HidePossibleValues)
        } else {
            self.unset_global_setting(AppSettings::HidePossibleValues)
        }
    }

    /// Allow partial matches of long arguments or their [aliases].
    ///
    /// For example, to match an argument named `--test`, one could use `--t`, `--te`, `--tes`, and
    /// `--test`.
    ///
    /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match
    /// `--te` to `--test` there could not also be another argument or alias `--temp` because both
    /// start with `--te`
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// [aliases]: crate::Command::aliases()
    #[inline]
    pub fn infer_long_args(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::InferLongArgs)
        } else {
            self.unset_global_setting(AppSettings::InferLongArgs)
        }
    }

    /// Allow partial matches of [subcommand] names and their [aliases].
    ///
    /// For example, to match a subcommand named `test`, one could use `t`, `te`, `tes`, and
    /// `test`.
    ///
    /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te`
    /// to `test` there could not also be a subcommand or alias `temp` because both start with `te`
    ///
    /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when
    /// designing CLIs which allow inferred subcommands and have potential positional/free
    /// arguments whose values could start with the same characters as subcommands. If this is the
    /// case, it's recommended to use settings such as [`Command::args_conflicts_with_subcommands`] in
    /// conjunction with this setting.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let m = Command::new("prog")
    ///     .infer_subcommands(true)
    ///     .subcommand(Command::new("test"))
    ///     .get_matches_from(vec![
    ///         "prog", "te"
    ///     ]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    ///
    /// [subcommand]: crate::Command::subcommand()
    /// [positional/free arguments]: crate::Arg::index()
    /// [aliases]: crate::Command::aliases()
    #[inline]
    pub fn infer_subcommands(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::InferSubcommands)
        } else {
            self.unset_global_setting(AppSettings::InferSubcommands)
        }
    }
}

/// # Command-specific Settings
///
/// These apply only to the current command and are not inherited by subcommands.
impl Command {
    /// (Re)Sets the program's name.
    ///
    /// See [`Command::new`] for more details.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let cmd = clap::command!()
    ///     .name("foo");
    ///
    /// // continued logic goes here, such as `cmd.get_matches()` etc.
    /// ```
    #[must_use]
    pub fn name(mut self, name: impl Into<Str>) -> Self {
        self.name = name.into();
        self
    }

    /// Overrides the runtime-determined name of the binary for help and error messages.
    ///
    /// This should only be used when absolutely necessary, such as when the binary name for your
    /// application is misleading, or perhaps *not* how the user should invoke your program.
    ///
    /// **Pro-tip:** When building things such as third party `cargo`
    /// subcommands, this setting **should** be used!
    ///
    /// **NOTE:** This *does not* change or set the name of the binary file on
    /// disk. It only changes what clap thinks the name is for the purposes of
    /// error or help messages.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("My Program")
    ///      .bin_name("my_binary")
    /// # ;
    /// ```
    #[must_use]
    pub fn bin_name(mut self, name: impl IntoResettable<String>) -> Self {
        self.bin_name = name.into_resettable().into_option();
        self
    }

    /// Overrides the runtime-determined display name of the program for help and error messages.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("My Program")
    ///      .display_name("my_program")
    /// # ;
    /// ```
    #[must_use]
    pub fn display_name(mut self, name: impl IntoResettable<String>) -> Self {
        self.display_name = name.into_resettable().into_option();
        self
    }

    /// Sets the author(s) for the help message.
    ///
    /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to
    /// automatically set your application's author(s) to the same thing as your
    /// crate at compile time.
    ///
    /// **NOTE:** A custom [`help_template`][Command::help_template] is needed for author to show
    /// up.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///      .author("Me, me@mymain.com")
    /// # ;
    /// ```
    #[must_use]
    pub fn author(mut self, author: impl IntoResettable<Str>) -> Self {
        self.author = author.into_resettable().into_option();
        self
    }

    /// Sets the program's description for the short help (`-h`).
    ///
    /// If [`Command::long_about`] is not specified, this message will be displayed for `--help`.
    ///
    /// **NOTE:** Only `Command::about` (short format) is used in completion
    /// script generation in order to be concise.
    ///
    /// See also [`crate_description!`](crate::crate_description!).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .about("Does really amazing things for great people")
    /// # ;
    /// ```
    #[must_use]
    pub fn about(mut self, about: impl IntoResettable<StyledStr>) -> Self {
        self.about = about.into_resettable().into_option();
        self
    }

    /// Sets the program's description for the long help (`--help`).
    ///
    /// If [`Command::about`] is not specified, this message will be displayed for `-h`.
    ///
    /// **NOTE:** Only [`Command::about`] (short format) is used in completion
    /// script generation in order to be concise.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .long_about(
    /// "Does really amazing things to great people. Now let's talk a little
    ///  more in depth about how this subcommand really works. It may take about
    ///  a few lines of text, but that's ok!")
    /// # ;
    /// ```
    /// [`Command::about`]: Command::about()
    #[must_use]
    pub fn long_about(mut self, long_about: impl IntoResettable<StyledStr>) -> Self {
        self.long_about = long_about.into_resettable().into_option();
        self
    }

    /// Free-form help text for after auto-generated short help (`-h`).
    ///
    /// This is often used to describe how to use the arguments, caveats to be noted, or license
    /// and contact information.
    ///
    /// If [`Command::after_long_help`] is not specified, this message will be displayed for `--help`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .after_help("Does really amazing things for great people... but be careful with -R!")
    /// # ;
    /// ```
    ///
    #[must_use]
    pub fn after_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
        self.after_help = help.into_resettable().into_option();
        self
    }

    /// Free-form help text for after auto-generated long help (`--help`).
    ///
    /// This is often used to describe how to use the arguments, caveats to be noted, or license
    /// and contact information.
    ///
    /// If [`Command::after_help`] is not specified, this message will be displayed for `-h`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .after_long_help("Does really amazing things to great people... but be careful with -R, \
    ///                      like, for real, be careful with this!")
    /// # ;
    /// ```
    #[must_use]
    pub fn after_long_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
        self.after_long_help = help.into_resettable().into_option();
        self
    }

    /// Free-form help text for before auto-generated short help (`-h`).
    ///
    /// This is often used for header, copyright, or license information.
    ///
    /// If [`Command::before_long_help`] is not specified, this message will be displayed for `--help`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .before_help("Some info I'd like to appear before the help info")
    /// # ;
    /// ```
    #[must_use]
    pub fn before_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
        self.before_help = help.into_resettable().into_option();
        self
    }

    /// Free-form help text for before auto-generated long help (`--help`).
    ///
    /// This is often used for header, copyright, or license information.
    ///
    /// If [`Command::before_help`] is not specified, this message will be displayed for `-h`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .before_long_help("Some verbose and long info I'd like to appear before the help info")
    /// # ;
    /// ```
    #[must_use]
    pub fn before_long_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
        self.before_long_help = help.into_resettable().into_option();
        self
    }

    /// Sets the version for the short version (`-V`) and help messages.
    ///
    /// If [`Command::long_version`] is not specified, this message will be displayed for `--version`.
    ///
    /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
    /// automatically set your application's version to the same thing as your
    /// crate at compile time.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .version("v0.1.24")
    /// # ;
    /// ```
    #[must_use]
    pub fn version(mut self, ver: impl IntoResettable<Str>) -> Self {
        self.version = ver.into_resettable().into_option();
        self
    }

    /// Sets the version for the long version (`--version`) and help messages.
    ///
    /// If [`Command::version`] is not specified, this message will be displayed for `-V`.
    ///
    /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
    /// automatically set your application's version to the same thing as your
    /// crate at compile time.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .long_version(
    /// "v0.1.24
    ///  commit: abcdef89726d
    ///  revision: 123
    ///  release: 2
    ///  binary: myprog")
    /// # ;
    /// ```
    #[must_use]
    pub fn long_version(mut self, ver: impl IntoResettable<Str>) -> Self {
        self.long_version = ver.into_resettable().into_option();
        self
    }

    /// Overrides the `clap` generated usage string for help and error messages.
    ///
    /// **NOTE:** Using this setting disables `clap`s "context-aware" usage
    /// strings. After this setting is set, this will be *the only* usage string
    /// displayed to the user!
    ///
    /// **NOTE:** Multiple usage lines may be present in the usage argument, but
    /// some rules need to be followed to ensure the usage lines are formatted
    /// correctly by the default help formatter:
    ///
    /// - Do not indent the first usage line.
    /// - Indent all subsequent usage lines with seven spaces.
    /// - The last line must not end with a newline.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .override_usage("myapp [-clDas] <some_file>")
    /// # ;
    /// ```
    ///
    /// Or for multiple usage lines:
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .override_usage(
    ///         "myapp -X [-a] [-b] <file>\n       \
    ///          myapp -Y [-c] <file1> <file2>\n       \
    ///          myapp -Z [-d|-e]"
    ///     )
    /// # ;
    /// ```
    ///
    /// [`ArgMatches::usage`]: ArgMatches::usage()
    #[must_use]
    pub fn override_usage(mut self, usage: impl IntoResettable<StyledStr>) -> Self {
        self.usage_str = usage.into_resettable().into_option();
        self
    }

    /// Overrides the `clap` generated help message (both `-h` and `--help`).
    ///
    /// This should only be used when the auto-generated message does not suffice.
    ///
    /// **NOTE:** This **only** replaces the help message for the current
    /// command, meaning if you are using subcommands, those help messages will
    /// still be auto-generated unless you specify a [`Command::override_help`] for
    /// them as well.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myapp")
    ///     .override_help("myapp v1.0\n\
    ///            Does awesome things\n\
    ///            (C) me@mail.com\n\n\
    ///
    ///            Usage: myapp <opts> <command>\n\n\
    ///
    ///            Options:\n\
    ///            -h, --help       Display this message\n\
    ///            -V, --version    Display version info\n\
    ///            -s <stuff>       Do something with stuff\n\
    ///            -v               Be verbose\n\n\
    ///
    ///            Commands:\n\
    ///            help             Print this message\n\
    ///            work             Do some work")
    /// # ;
    /// ```
    #[must_use]
    pub fn override_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
        self.help_str = help.into_resettable().into_option();
        self
    }

    /// Sets the help template to be used, overriding the default format.
    ///
    /// **NOTE:** The template system is by design very simple. Therefore, the
    /// tags have to be written in the lowercase and without spacing.
    ///
    /// Tags are given inside curly brackets.
    ///
    /// Valid tags are:
    ///
    ///   * `{name}`                - Display name for the (sub-)command.
    ///   * `{bin}`                 - Binary name.
    ///   * `{version}`             - Version number.
    ///   * `{author}`              - Author information.
    ///   * `{author-with-newline}` - Author followed by `\n`.
    ///   * `{author-section}`      - Author preceded and followed by `\n`.
    ///   * `{about}`               - General description (from [`Command::about`] or
    ///                               [`Command::long_about`]).
    ///   * `{about-with-newline}`  - About followed by `\n`.
    ///   * `{about-section}`       - About preceded and followed by '\n'.
    ///   * `{usage-heading}`       - Automatically generated usage heading.
    ///   * `{usage}`               - Automatically generated or given usage string.
    ///   * `{all-args}`            - Help for all arguments (options, flags, positional
    ///                               arguments, and subcommands) including titles.
    ///   * `{options}`             - Help for options.
    ///   * `{positionals}`         - Help for positional arguments.
    ///   * `{subcommands}`         - Help for subcommands.
    ///   * `{tag}`                 - Standard tab sized used within clap
    ///   * `{after-help}`          - Help from [`Command::after_help`] or [`Command::after_long_help`].
    ///   * `{before-help}`         - Help from [`Command::before_help`] or [`Command::before_long_help`].
    ///
    /// # Examples
    ///
    /// For a very brief help:
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .version("1.0")
    ///     .help_template("{bin} ({version}) - {usage}")
    /// # ;
    /// ```
    ///
    /// For showing more application context:
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .version("1.0")
    ///     .help_template("\
    /// {before-help}{name} {version}
    /// {author-with-newline}{about-with-newline}
    /// {usage-heading} {usage}
    ///
    /// {all-args}{after-help}
    /// ")
    /// # ;
    /// ```
    /// [`Command::about`]: Command::about()
    /// [`Command::long_about`]: Command::long_about()
    /// [`Command::after_help`]: Command::after_help()
    /// [`Command::after_long_help`]: Command::after_long_help()
    /// [`Command::before_help`]: Command::before_help()
    /// [`Command::before_long_help`]: Command::before_long_help()
    #[must_use]
    #[cfg(feature = "help")]
    pub fn help_template(mut self, s: impl IntoResettable<StyledStr>) -> Self {
        self.template = s.into_resettable().into_option();
        self
    }

    #[inline]
    #[must_use]
    pub(crate) fn setting<F>(mut self, setting: F) -> Self
    where
        F: Into<AppFlags>,
    {
        self.settings.insert(setting.into());
        self
    }

    #[inline]
    #[must_use]
    pub(crate) fn unset_setting<F>(mut self, setting: F) -> Self
    where
        F: Into<AppFlags>,
    {
        self.settings.remove(setting.into());
        self
    }

    #[inline]
    #[must_use]
    pub(crate) fn global_setting(mut self, setting: AppSettings) -> Self {
        self.settings.set(setting);
        self.g_settings.set(setting);
        self
    }

    #[inline]
    #[must_use]
    pub(crate) fn unset_global_setting(mut self, setting: AppSettings) -> Self {
        self.settings.unset(setting);
        self.g_settings.unset(setting);
        self
    }

    /// Set the default section heading for future args.
    ///
    /// This will be used for any arg that hasn't had [`Arg::help_heading`] called.
    ///
    /// This is useful if the default `Options` or `Arguments` headings are
    /// not specific enough for one's use case.
    ///
    /// For subcommands, see [`Command::subcommand_help_heading`]
    ///
    /// [`Command::arg`]: Command::arg()
    /// [`Arg::help_heading`]: crate::Arg::help_heading()
    #[inline]
    #[must_use]
    pub fn next_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self {
        self.current_help_heading = heading.into_resettable().into_option();
        self
    }

    /// Change the starting value for assigning future display orders for ags.
    ///
    /// This will be used for any arg that hasn't had [`Arg::display_order`] called.
    #[inline]
    #[must_use]
    pub fn next_display_order(mut self, disp_ord: impl IntoResettable<usize>) -> Self {
        self.current_disp_ord = disp_ord.into_resettable().into_option();
        self
    }

    /// Replaces an argument or subcommand used on the CLI at runtime with other arguments or subcommands.
    ///
    /// **Note:** This is gated behind [`unstable-replace`](https://github.com/clap-rs/clap/issues/2836)
    ///
    /// When this method is used, `name` is removed from the CLI, and `target`
    /// is inserted in its place. Parsing continues as if the user typed
    /// `target` instead of `name`.
    ///
    /// This can be used to create "shortcuts" for subcommands, or if a
    /// particular argument has the semantic meaning of several other specific
    /// arguments and values.
    ///
    /// # Examples
    ///
    /// We'll start with the "subcommand short" example. In this example, let's
    /// assume we have a program with a subcommand `module` which can be invoked
    /// via `cmd module`. Now let's also assume `module` also has a subcommand
    /// called `install` which can be invoked `cmd module install`. If for some
    /// reason users needed to be able to reach `cmd module install` via the
    /// short-hand `cmd install`, we'd have several options.
    ///
    /// We *could* create another sibling subcommand to `module` called
    /// `install`, but then we would need to manage another subcommand and manually
    /// dispatch to `cmd module install` handling code. This is error prone and
    /// tedious.
    ///
    /// We could instead use [`Command::replace`] so that, when the user types `cmd
    /// install`, `clap` will replace `install` with `module install` which will
    /// end up getting parsed as if the user typed the entire incantation.
    ///
    /// ```rust
    /// # use clap::Command;
    /// let m = Command::new("cmd")
    ///     .subcommand(Command::new("module")
    ///         .subcommand(Command::new("install")))
    ///     .replace("install", &["module", "install"])
    ///     .get_matches_from(vec!["cmd", "install"]);
    ///
    /// assert!(m.subcommand_matches("module").is_some());
    /// assert!(m.subcommand_matches("module").unwrap().subcommand_matches("install").is_some());
    /// ```
    ///
    /// Now let's show an argument example!
    ///
    /// Let's assume we have an application with two flags `--save-context` and
    /// `--save-runtime`. But often users end up needing to do *both* at the
    /// same time. We can add a third flag `--save-all` which semantically means
    /// the same thing as `cmd --save-context --save-runtime`. To implement that,
    /// we have several options.
    ///
    /// We could create this third argument and manually check if that argument
    /// and in our own consumer code handle the fact that both `--save-context`
    /// and `--save-runtime` *should* have been used. But again this is error
    /// prone and tedious. If we had code relying on checking `--save-context`
    /// and we forgot to update that code to *also* check `--save-all` it'd mean
    /// an error!
    ///
    /// Luckily we can use [`Command::replace`] so that when the user types
    /// `--save-all`, `clap` will replace that argument with `--save-context
    /// --save-runtime`, and parsing will continue like normal. Now all our code
    /// that was originally checking for things like `--save-context` doesn't
    /// need to change!
    ///
    /// ```rust
    /// # use clap::{Command, Arg, ArgAction};
    /// let m = Command::new("cmd")
    ///     .arg(Arg::new("save-context")
    ///         .long("save-context")
    ///         .action(ArgAction::SetTrue))
    ///     .arg(Arg::new("save-runtime")
    ///         .long("save-runtime")
    ///         .action(ArgAction::SetTrue))
    ///     .replace("--save-all", &["--save-context", "--save-runtime"])
    ///     .get_matches_from(vec!["cmd", "--save-all"]);
    ///
    /// assert!(*m.get_one::<bool>("save-context").expect("defaulted by clap"));
    /// assert!(*m.get_one::<bool>("save-runtime").expect("defaulted by clap"));
    /// ```
    ///
    /// This can also be used with options, for example if our application with
    /// `--save-*` above also had a `--format=TYPE` option. Let's say it
    /// accepted `txt` or `json` values. However, when `--save-all` is used,
    /// only `--format=json` is allowed, or valid. We could change the example
    /// above to enforce this:
    ///
    /// ```rust
    /// # use clap::{Command, Arg, ArgAction};
    /// let m = Command::new("cmd")
    ///     .arg(Arg::new("save-context")
    ///         .long("save-context")
    ///         .action(ArgAction::SetTrue))
    ///     .arg(Arg::new("save-runtime")
    ///         .long("save-runtime")
    ///         .action(ArgAction::SetTrue))
    ///     .arg(Arg::new("format")
    ///         .long("format")
    ///         .action(ArgAction::Set)
    ///         .value_parser(["txt", "json"]))
    ///     .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"])
    ///     .get_matches_from(vec!["cmd", "--save-all"]);
    ///
    /// assert!(*m.get_one::<bool>("save-context").expect("defaulted by clap"));
    /// assert!(*m.get_one::<bool>("save-runtime").expect("defaulted by clap"));
    /// assert_eq!(m.get_one::<String>("format").unwrap(), "json");
    /// ```
    ///
    /// [`Command::replace`]: Command::replace()
    #[inline]
    #[cfg(feature = "unstable-replace")]
    #[must_use]
    pub fn replace(
        mut self,
        name: impl Into<Str>,
        target: impl IntoIterator<Item = impl Into<Str>>,
    ) -> Self {
        self.replacers
            .insert(name.into(), target.into_iter().map(Into::into).collect());
        self
    }

    /// Exit gracefully if no arguments are present (e.g. `$ myprog`).
    ///
    /// **NOTE:** [`subcommands`] count as arguments
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command};
    /// Command::new("myprog")
    ///     .arg_required_else_help(true);
    /// ```
    ///
    /// [`subcommands`]: crate::Command::subcommand()
    /// [`Arg::default_value`]: crate::Arg::default_value()
    #[inline]
    pub fn arg_required_else_help(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::ArgRequiredElseHelp)
        } else {
            self.unset_setting(AppSettings::ArgRequiredElseHelp)
        }
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_hyphen_values`")
    )]
    pub fn allow_hyphen_values(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::AllowHyphenValues)
        } else {
            self.unset_setting(AppSettings::AllowHyphenValues)
        }
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_negative_numbers`")
    )]
    pub fn allow_negative_numbers(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::AllowNegativeNumbers)
        } else {
            self.unset_setting(AppSettings::AllowNegativeNumbers)
        }
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "Replaced with `Arg::trailing_var_arg`")
    )]
    pub fn trailing_var_arg(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::TrailingVarArg)
        } else {
            self.unset_setting(AppSettings::TrailingVarArg)
        }
    }

    /// Allows one to implement two styles of CLIs where positionals can be used out of order.
    ///
    /// The first example is a CLI where the second to last positional argument is optional, but
    /// the final positional argument is required. Such as `$ prog [optional] <required>` where one
    /// of the two following usages is allowed:
    ///
    /// * `$ prog [optional] <required>`
    /// * `$ prog <required>`
    ///
    /// This would otherwise not be allowed. This is useful when `[optional]` has a default value.
    ///
    /// **Note:** when using this style of "missing positionals" the final positional *must* be
    /// [required] if `--` will not be used to skip to the final positional argument.
    ///
    /// **Note:** This style also only allows a single positional argument to be "skipped" without
    /// the use of `--`. To skip more than one, see the second example.
    ///
    /// The second example is when one wants to skip multiple optional positional arguments, and use
    /// of the `--` operator is OK (but not required if all arguments will be specified anyways).
    ///
    /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where
    /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments).
    ///
    /// With this setting the following invocations are posisble:
    ///
    /// * `$ prog foo bar baz1 baz2 baz3`
    /// * `$ prog foo -- baz1 baz2 baz3`
    /// * `$ prog -- baz1 baz2 baz3`
    ///
    /// # Examples
    ///
    /// Style number one from above:
    ///
    /// ```rust
    /// # use clap::{Command, Arg};
    /// // Assume there is an external subcommand named "subcmd"
    /// let m = Command::new("myprog")
    ///     .allow_missing_positional(true)
    ///     .arg(Arg::new("arg1"))
    ///     .arg(Arg::new("arg2")
    ///         .required(true))
    ///     .get_matches_from(vec![
    ///         "prog", "other"
    ///     ]);
    ///
    /// assert_eq!(m.get_one::<String>("arg1"), None);
    /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other");
    /// ```
    ///
    /// Now the same example, but using a default value for the first optional positional argument
    ///
    /// ```rust
    /// # use clap::{Command, Arg};
    /// // Assume there is an external subcommand named "subcmd"
    /// let m = Command::new("myprog")
    ///     .allow_missing_positional(true)
    ///     .arg(Arg::new("arg1")
    ///         .default_value("something"))
    ///     .arg(Arg::new("arg2")
    ///         .required(true))
    ///     .get_matches_from(vec![
    ///         "prog", "other"
    ///     ]);
    ///
    /// assert_eq!(m.get_one::<String>("arg1").unwrap(), "something");
    /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other");
    /// ```
    ///
    /// Style number two from above:
    ///
    /// ```rust
    /// # use clap::{Command, Arg, ArgAction};
    /// // Assume there is an external subcommand named "subcmd"
    /// let m = Command::new("myprog")
    ///     .allow_missing_positional(true)
    ///     .arg(Arg::new("foo"))
    ///     .arg(Arg::new("bar"))
    ///     .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..))
    ///     .get_matches_from(vec![
    ///         "prog", "foo", "bar", "baz1", "baz2", "baz3"
    ///     ]);
    ///
    /// assert_eq!(m.get_one::<String>("foo").unwrap(), "foo");
    /// assert_eq!(m.get_one::<String>("bar").unwrap(), "bar");
    /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
    /// ```
    ///
    /// Now nofice if we don't specify `foo` or `baz` but use the `--` operator.
    ///
    /// ```rust
    /// # use clap::{Command, Arg, ArgAction};
    /// // Assume there is an external subcommand named "subcmd"
    /// let m = Command::new("myprog")
    ///     .allow_missing_positional(true)
    ///     .arg(Arg::new("foo"))
    ///     .arg(Arg::new("bar"))
    ///     .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..))
    ///     .get_matches_from(vec![
    ///         "prog", "--", "baz1", "baz2", "baz3"
    ///     ]);
    ///
    /// assert_eq!(m.get_one::<String>("foo"), None);
    /// assert_eq!(m.get_one::<String>("bar"), None);
    /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
    /// ```
    ///
    /// [required]: crate::Arg::required()
    #[inline]
    pub fn allow_missing_positional(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::AllowMissingPositional)
        } else {
            self.unset_setting(AppSettings::AllowMissingPositional)
        }
    }
}

/// # Subcommand-specific Settings
impl Command {
    /// Sets the short version of the subcommand flag without the preceding `-`.
    ///
    /// Allows the subcommand to be used as if it were an [`Arg::short`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use clap::{Command, Arg, ArgAction};
    /// let matches = Command::new("pacman")
    ///     .subcommand(
    ///         Command::new("sync").short_flag('S').arg(
    ///             Arg::new("search")
    ///                 .short('s')
    ///                 .long("search")
    ///                 .action(ArgAction::SetTrue)
    ///                 .help("search remote repositories for matching strings"),
    ///         ),
    ///     )
    ///     .get_matches_from(vec!["pacman", "-Ss"]);
    ///
    /// assert_eq!(matches.subcommand_name().unwrap(), "sync");
    /// let sync_matches = matches.subcommand_matches("sync").unwrap();
    /// assert!(*sync_matches.get_one::<bool>("search").expect("defaulted by clap"));
    /// ```
    /// [`Arg::short`]: Arg::short()
    #[must_use]
    pub fn short_flag(mut self, short: impl IntoResettable<char>) -> Self {
        self.short_flag = short.into_resettable().into_option();
        self
    }

    /// Sets the long version of the subcommand flag without the preceding `--`.
    ///
    /// Allows the subcommand to be used as if it were an [`Arg::long`].
    ///
    /// **NOTE:** Any leading `-` characters will be stripped.
    ///
    /// # Examples
    ///
    /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading
    /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however,
    /// will *not* be stripped (i.e. `sync-file` is allowed).
    ///
    /// ```
    /// # use clap::{Command, Arg, ArgAction};
    /// let matches = Command::new("pacman")
    ///     .subcommand(
    ///         Command::new("sync").long_flag("sync").arg(
    ///             Arg::new("search")
    ///                 .short('s')
    ///                 .long("search")
    ///                 .action(ArgAction::SetTrue)
    ///                 .help("search remote repositories for matching strings"),
    ///         ),
    ///     )
    ///     .get_matches_from(vec!["pacman", "--sync", "--search"]);
    ///
    /// assert_eq!(matches.subcommand_name().unwrap(), "sync");
    /// let sync_matches = matches.subcommand_matches("sync").unwrap();
    /// assert!(*sync_matches.get_one::<bool>("search").expect("defaulted by clap"));
    /// ```
    ///
    /// [`Arg::long`]: Arg::long()
    #[must_use]
    pub fn long_flag(mut self, long: impl Into<Str>) -> Self {
        self.long_flag = Some(long.into());
        self
    }

    /// Sets a hidden alias to this subcommand.
    ///
    /// This allows the subcommand to be accessed via *either* the original name, or this given
    /// alias. This is more efficient and easier than creating multiple hidden subcommands as one
    /// only needs to check for the existence of this command, and not all aliased variants.
    ///
    /// **NOTE:** Aliases defined with this method are *hidden* from the help
    /// message. If you're looking for aliases that will be displayed in the help
    /// message, see [`Command::visible_alias`].
    ///
    /// **NOTE:** When using aliases and checking for the existence of a
    /// particular subcommand within an [`ArgMatches`] struct, one only needs to
    /// search for the original name and not all aliases.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///     .subcommand(Command::new("test")
    ///         .alias("do-stuff"))
    ///     .get_matches_from(vec!["myprog", "do-stuff"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::visible_alias`]: Command::visible_alias()
    #[must_use]
    pub fn alias(mut self, name: impl IntoResettable<Str>) -> Self {
        if let Some(name) = name.into_resettable().into_option() {
            self.aliases.push((name, false));
        } else {
            self.aliases.clear();
        }
        self
    }

    /// Add an alias, which functions as  "hidden" short flag subcommand
    ///
    /// This will automatically dispatch as if this subcommand was used. This is more efficient,
    /// and easier than creating multiple hidden subcommands as one only needs to check for the
    /// existence of this command, and not all variants.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///             .subcommand(Command::new("test").short_flag('t')
    ///                 .short_flag_alias('d'))
    ///             .get_matches_from(vec!["myprog", "-d"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    #[must_use]
    pub fn short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self {
        if let Some(name) = name.into_resettable().into_option() {
            debug_assert!(name != '-', "short alias name cannot be `-`");
            self.short_flag_aliases.push((name, false));
        } else {
            self.short_flag_aliases.clear();
        }
        self
    }

    /// Add an alias, which functions as a "hidden" long flag subcommand.
    ///
    /// This will automatically dispatch as if this subcommand was used. This is more efficient,
    /// and easier than creating multiple hidden subcommands as one only needs to check for the
    /// existence of this command, and not all variants.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///             .subcommand(Command::new("test").long_flag("test")
    ///                 .long_flag_alias("testing"))
    ///             .get_matches_from(vec!["myprog", "--testing"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    #[must_use]
    pub fn long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self {
        if let Some(name) = name.into_resettable().into_option() {
            self.long_flag_aliases.push((name, false));
        } else {
            self.long_flag_aliases.clear();
        }
        self
    }

    /// Sets multiple hidden aliases to this subcommand.
    ///
    /// This allows the subcommand to be accessed via *either* the original name or any of the
    /// given aliases. This is more efficient, and easier than creating multiple hidden subcommands
    /// as one only needs to check for the existence of this command and not all aliased variants.
    ///
    /// **NOTE:** Aliases defined with this method are *hidden* from the help
    /// message. If looking for aliases that will be displayed in the help
    /// message, see [`Command::visible_aliases`].
    ///
    /// **NOTE:** When using aliases and checking for the existence of a
    /// particular subcommand within an [`ArgMatches`] struct, one only needs to
    /// search for the original name and not all aliases.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg};
    /// let m = Command::new("myprog")
    ///     .subcommand(Command::new("test")
    ///         .aliases(["do-stuff", "do-tests", "tests"]))
    ///         .arg(Arg::new("input")
    ///             .help("the file to add")
    ///             .required(false))
    ///     .get_matches_from(vec!["myprog", "do-tests"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::visible_aliases`]: Command::visible_aliases()
    #[must_use]
    pub fn aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
        self.aliases
            .extend(names.into_iter().map(|n| (n.into(), false)));
        self
    }

    /// Add aliases, which function as "hidden" short flag subcommands.
    ///
    /// These will automatically dispatch as if this subcommand was used. This is more efficient,
    /// and easier than creating multiple hidden subcommands as one only needs to check for the
    /// existence of this command, and not all variants.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///     .subcommand(Command::new("test").short_flag('t')
    ///         .short_flag_aliases(['a', 'b', 'c']))
    ///         .arg(Arg::new("input")
    ///             .help("the file to add")
    ///             .required(false))
    ///     .get_matches_from(vec!["myprog", "-a"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    #[must_use]
    pub fn short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self {
        for s in names {
            debug_assert!(s != '-', "short alias name cannot be `-`");
            self.short_flag_aliases.push((s, false));
        }
        self
    }

    /// Add aliases, which function as "hidden" long flag subcommands.
    ///
    /// These will automatically dispatch as if this subcommand was used. This is more efficient,
    /// and easier than creating multiple hidden subcommands as one only needs to check for the
    /// existence of this command, and not all variants.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///             .subcommand(Command::new("test").long_flag("test")
    ///                 .long_flag_aliases(["testing", "testall", "test_all"]))
    ///                 .arg(Arg::new("input")
    ///                             .help("the file to add")
    ///                             .required(false))
    ///             .get_matches_from(vec!["myprog", "--testing"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    #[must_use]
    pub fn long_flag_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
        for s in names {
            self = self.long_flag_alias(s)
        }
        self
    }

    /// Sets a visible alias to this subcommand.
    ///
    /// This allows the subcommand to be accessed via *either* the
    /// original name or the given alias. This is more efficient and easier
    /// than creating hidden subcommands as one only needs to check for
    /// the existence of this command and not all aliased variants.
    ///
    /// **NOTE:** The alias defined with this method is *visible* from the help
    /// message and displayed as if it were just another regular subcommand. If
    /// looking for an alias that will not be displayed in the help message, see
    /// [`Command::alias`].
    ///
    /// **NOTE:** When using aliases and checking for the existence of a
    /// particular subcommand within an [`ArgMatches`] struct, one only needs to
    /// search for the original name and not all aliases.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let m = Command::new("myprog")
    ///     .subcommand(Command::new("test")
    ///         .visible_alias("do-stuff"))
    ///     .get_matches_from(vec!["myprog", "do-stuff"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::alias`]: Command::alias()
    #[must_use]
    pub fn visible_alias(mut self, name: impl IntoResettable<Str>) -> Self {
        if let Some(name) = name.into_resettable().into_option() {
            self.aliases.push((name, true));
        } else {
            self.aliases.clear();
        }
        self
    }

    /// Add an alias, which functions as  "visible" short flag subcommand
    ///
    /// This will automatically dispatch as if this subcommand was used. This is more efficient,
    /// and easier than creating multiple hidden subcommands as one only needs to check for the
    /// existence of this command, and not all variants.
    ///
    /// See also [`Command::short_flag_alias`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///             .subcommand(Command::new("test").short_flag('t')
    ///                 .visible_short_flag_alias('d'))
    ///             .get_matches_from(vec!["myprog", "-d"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::short_flag_alias`]: Command::short_flag_alias()
    #[must_use]
    pub fn visible_short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self {
        if let Some(name) = name.into_resettable().into_option() {
            debug_assert!(name != '-', "short alias name cannot be `-`");
            self.short_flag_aliases.push((name, true));
        } else {
            self.short_flag_aliases.clear();
        }
        self
    }

    /// Add an alias, which functions as a "visible" long flag subcommand.
    ///
    /// This will automatically dispatch as if this subcommand was used. This is more efficient,
    /// and easier than creating multiple hidden subcommands as one only needs to check for the
    /// existence of this command, and not all variants.
    ///
    /// See also [`Command::long_flag_alias`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///             .subcommand(Command::new("test").long_flag("test")
    ///                 .visible_long_flag_alias("testing"))
    ///             .get_matches_from(vec!["myprog", "--testing"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::long_flag_alias`]: Command::long_flag_alias()
    #[must_use]
    pub fn visible_long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self {
        if let Some(name) = name.into_resettable().into_option() {
            self.long_flag_aliases.push((name, true));
        } else {
            self.long_flag_aliases.clear();
        }
        self
    }

    /// Sets multiple visible aliases to this subcommand.
    ///
    /// This allows the subcommand to be accessed via *either* the
    /// original name or any of the given aliases. This is more efficient and easier
    /// than creating multiple hidden subcommands as one only needs to check for
    /// the existence of this command and not all aliased variants.
    ///
    /// **NOTE:** The alias defined with this method is *visible* from the help
    /// message and displayed as if it were just another regular subcommand. If
    /// looking for an alias that will not be displayed in the help message, see
    /// [`Command::alias`].
    ///
    /// **NOTE:** When using aliases, and checking for the existence of a
    /// particular subcommand within an [`ArgMatches`] struct, one only needs to
    /// search for the original name and not all aliases.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///     .subcommand(Command::new("test")
    ///         .visible_aliases(["do-stuff", "tests"]))
    ///     .get_matches_from(vec!["myprog", "do-stuff"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::alias`]: Command::alias()
    #[must_use]
    pub fn visible_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
        self.aliases
            .extend(names.into_iter().map(|n| (n.into(), true)));
        self
    }

    /// Add aliases, which function as *visible* short flag subcommands.
    ///
    /// See [`Command::short_flag_aliases`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///             .subcommand(Command::new("test").short_flag('b')
    ///                 .visible_short_flag_aliases(['t']))
    ///             .get_matches_from(vec!["myprog", "-t"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::short_flag_aliases`]: Command::short_flag_aliases()
    #[must_use]
    pub fn visible_short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self {
        for s in names {
            debug_assert!(s != '-', "short alias name cannot be `-`");
            self.short_flag_aliases.push((s, true));
        }
        self
    }

    /// Add aliases, which function as *visible* long flag subcommands.
    ///
    /// See [`Command::long_flag_aliases`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///             .subcommand(Command::new("test").long_flag("test")
    ///                 .visible_long_flag_aliases(["testing", "testall", "test_all"]))
    ///             .get_matches_from(vec!["myprog", "--testing"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::long_flag_aliases`]: Command::long_flag_aliases()
    #[must_use]
    pub fn visible_long_flag_aliases(
        mut self,
        names: impl IntoIterator<Item = impl Into<Str>>,
    ) -> Self {
        for s in names {
            self = self.visible_long_flag_alias(s);
        }
        self
    }

    /// Set the placement of this subcommand within the help.
    ///
    /// Subcommands with a lower value will be displayed first in the help message.  Subcommands
    /// with duplicate display orders will be displayed in alphabetical order.
    ///
    /// This is helpful when one would like to emphasize frequently used subcommands, or prioritize
    /// those towards the top of the list.
    ///
    /// **NOTE:** The default is 999 for all subcommands.
    ///
    /// # Examples
    ///
    #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
    #[cfg_attr(feature = "help", doc = " ```")]
    /// # use clap::{Command, };
    /// let m = Command::new("cust-ord")
    ///     .subcommand(Command::new("alpha") // typically subcommands are grouped
    ///                                                // alphabetically by name. Subcommands
    ///                                                // without a display_order have a value of
    ///                                                // 999 and are displayed alphabetically with
    ///                                                // all other 999 subcommands
    ///         .about("Some help and text"))
    ///     .subcommand(Command::new("beta")
    ///         .display_order(1)   // In order to force this subcommand to appear *first*
    ///                             // all we have to do is give it a value lower than 999.
    ///                             // Any other subcommands with a value of 1 will be displayed
    ///                             // alphabetically with this one...then 2 values, then 3, etc.
    ///         .about("I should be first!"))
    ///     .get_matches_from(vec![
    ///         "cust-ord", "--help"
    ///     ]);
    /// ```
    ///
    /// The above example displays the following help message
    ///
    /// ```text
    /// cust-ord
    ///
    /// Usage: cust-ord [OPTIONS]
    ///
    /// Commands:
    ///     beta    I should be first!
    ///     alpha   Some help and text
    ///
    /// Options:
    ///     -h, --help       Print help information
    ///     -V, --version    Print version information
    /// ```
    #[inline]
    #[must_use]
    pub fn display_order(mut self, ord: impl IntoResettable<usize>) -> Self {
        self.disp_ord = ord.into_resettable().into_option();
        self
    }

    /// Specifies that this [`subcommand`] should be hidden from help messages
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .subcommand(
    ///         Command::new("test").hide(true)
    ///     )
    /// # ;
    /// ```
    ///
    /// [`subcommand`]: crate::Command::subcommand()
    #[inline]
    pub fn hide(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::Hidden)
        } else {
            self.unset_setting(AppSettings::Hidden)
        }
    }

    /// If no [`subcommand`] is present at runtime, error and exit gracefully.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, error::ErrorKind};
    /// let err = Command::new("myprog")
    ///     .subcommand_required(true)
    ///     .subcommand(Command::new("test"))
    ///     .try_get_matches_from(vec![
    ///         "myprog",
    ///     ]);
    /// assert!(err.is_err());
    /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand);
    /// # ;
    /// ```
    ///
    /// [`subcommand`]: crate::Command::subcommand()
    pub fn subcommand_required(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::SubcommandRequired)
        } else {
            self.unset_setting(AppSettings::SubcommandRequired)
        }
    }

    /// Assume unexpected positional arguments are a [`subcommand`].
    ///
    /// Arguments will be stored in the `""` argument in the [`ArgMatches`]
    ///
    /// **NOTE:** Use this setting with caution,
    /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand)
    /// will **not** cause an error and instead be treated as a potential subcommand.
    /// One should check for such cases manually and inform the user appropriately.
    ///
    /// **NOTE:** A built-in subcommand will be parsed as an external subcommand when escaped with
    /// `--`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use std::ffi::OsString;
    /// # use clap::Command;
    /// // Assume there is an external subcommand named "subcmd"
    /// let m = Command::new("myprog")
    ///     .allow_external_subcommands(true)
    ///     .get_matches_from(vec![
    ///         "myprog", "subcmd", "--option", "value", "-fff", "--flag"
    ///     ]);
    ///
    /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
    /// // string argument name
    /// match m.subcommand() {
    ///     Some((external, ext_m)) => {
    ///          let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect();
    ///          assert_eq!(external, "subcmd");
    ///          assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
    ///     },
    ///     _ => {},
    /// }
    /// ```
    ///
    /// [`subcommand`]: crate::Command::subcommand()
    /// [`ArgMatches`]: crate::ArgMatches
    /// [`ErrorKind::UnknownArgument`]: crate::error::ErrorKind::UnknownArgument
    pub fn allow_external_subcommands(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::AllowExternalSubcommands)
        } else {
            self.unset_setting(AppSettings::AllowExternalSubcommands)
        }
    }

    /// Specifies how to parse external subcommand arguments.
    ///
    /// The default parser is for `OsString`.  This can be used to switch it to `String` or another
    /// type.
    ///
    /// **NOTE:** Setting this requires [`Command::allow_external_subcommands`]
    ///
    /// # Examples
    ///
    #[cfg_attr(not(unix), doc = " ```ignore")]
    #[cfg_attr(unix, doc = " ```")]
    /// # use std::ffi::OsString;
    /// # use clap::Command;
    /// # use clap::value_parser;
    /// // Assume there is an external subcommand named "subcmd"
    /// let m = Command::new("myprog")
    ///     .allow_external_subcommands(true)
    ///     .get_matches_from(vec![
    ///         "myprog", "subcmd", "--option", "value", "-fff", "--flag"
    ///     ]);
    ///
    /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
    /// // string argument name
    /// match m.subcommand() {
    ///     Some((external, ext_m)) => {
    ///          let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect();
    ///          assert_eq!(external, "subcmd");
    ///          assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
    ///     },
    ///     _ => {},
    /// }
    /// ```
    ///
    /// ```
    /// # use clap::Command;
    /// # use clap::value_parser;
    /// // Assume there is an external subcommand named "subcmd"
    /// let m = Command::new("myprog")
    ///     .external_subcommand_value_parser(value_parser!(String))
    ///     .get_matches_from(vec![
    ///         "myprog", "subcmd", "--option", "value", "-fff", "--flag"
    ///     ]);
    ///
    /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
    /// // string argument name
    /// match m.subcommand() {
    ///     Some((external, ext_m)) => {
    ///          let ext_args: Vec<_> = ext_m.get_many::<String>("").unwrap().collect();
    ///          assert_eq!(external, "subcmd");
    ///          assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
    ///     },
    ///     _ => {},
    /// }
    /// ```
    ///
    /// [`subcommands`]: crate::Command::subcommand()
    pub fn external_subcommand_value_parser(
        mut self,
        parser: impl IntoResettable<super::ValueParser>,
    ) -> Self {
        self.external_value_parser = parser.into_resettable().into_option();
        self
    }

    /// Specifies that use of an argument prevents the use of [`subcommands`].
    ///
    /// By default `clap` allows arguments between subcommands such
    /// as `<cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args]`.
    ///
    /// This setting disables that functionality and says that arguments can
    /// only follow the *final* subcommand. For instance using this setting
    /// makes only the following invocations possible:
    ///
    /// * `<cmd> <subcmd> <subsubcmd> [subsubcmd_args]`
    /// * `<cmd> <subcmd> [subcmd_args]`
    /// * `<cmd> [cmd_args]`
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .args_conflicts_with_subcommands(true);
    /// ```
    ///
    /// [`subcommands`]: crate::Command::subcommand()
    pub fn args_conflicts_with_subcommands(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::ArgsNegateSubcommands)
        } else {
            self.unset_setting(AppSettings::ArgsNegateSubcommands)
        }
    }

    /// Prevent subcommands from being consumed as an arguments value.
    ///
    /// By default, if an option taking multiple values is followed by a subcommand, the
    /// subcommand will be parsed as another value.
    ///
    /// ```text
    /// cmd --foo val1 val2 subcommand
    ///           --------- ----------
    ///             values   another value
    /// ```
    ///
    /// This setting instructs the parser to stop when encountering a subcommand instead of
    /// greedily consuming arguments.
    ///
    /// ```text
    /// cmd --foo val1 val2 subcommand
    ///           --------- ----------
    ///             values   subcommand
    /// ```
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg, ArgAction};
    /// let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg(
    ///     Arg::new("arg")
    ///         .long("arg")
    ///         .num_args(1..)
    ///         .action(ArgAction::Set),
    /// );
    ///
    /// let matches = cmd
    ///     .clone()
    ///     .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
    ///     .unwrap();
    /// assert_eq!(
    ///     matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(),
    ///     &["1", "2", "3", "sub"]
    /// );
    /// assert!(matches.subcommand_matches("sub").is_none());
    ///
    /// let matches = cmd
    ///     .subcommand_precedence_over_arg(true)
    ///     .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
    ///     .unwrap();
    /// assert_eq!(
    ///     matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(),
    ///     &["1", "2", "3"]
    /// );
    /// assert!(matches.subcommand_matches("sub").is_some());
    /// ```
    pub fn subcommand_precedence_over_arg(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::SubcommandPrecedenceOverArg)
        } else {
            self.unset_setting(AppSettings::SubcommandPrecedenceOverArg)
        }
    }

    /// Allows [`subcommands`] to override all requirements of the parent command.
    ///
    /// For example, if you had a subcommand or top level application with a required argument
    /// that is only required as long as there is no subcommand present,
    /// using this setting would allow you to set those arguments to [`Arg::required(true)`]
    /// and yet receive no error so long as the user uses a valid subcommand instead.
    ///
    /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements)
    ///
    /// # Examples
    ///
    /// This first example shows that it is an error to not use a required argument
    ///
    /// ```rust
    /// # use clap::{Command, Arg, error::ErrorKind};
    /// let err = Command::new("myprog")
    ///     .subcommand_negates_reqs(true)
    ///     .arg(Arg::new("opt").required(true))
    ///     .subcommand(Command::new("test"))
    ///     .try_get_matches_from(vec![
    ///         "myprog"
    ///     ]);
    /// assert!(err.is_err());
    /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
    /// # ;
    /// ```
    ///
    /// This next example shows that it is no longer error to not use a required argument if a
    /// valid subcommand is used.
    ///
    /// ```rust
    /// # use clap::{Command, Arg, error::ErrorKind};
    /// let noerr = Command::new("myprog")
    ///     .subcommand_negates_reqs(true)
    ///     .arg(Arg::new("opt").required(true))
    ///     .subcommand(Command::new("test"))
    ///     .try_get_matches_from(vec![
    ///         "myprog", "test"
    ///     ]);
    /// assert!(noerr.is_ok());
    /// # ;
    /// ```
    ///
    /// [`Arg::required(true)`]: crate::Arg::required()
    /// [`subcommands`]: crate::Command::subcommand()
    pub fn subcommand_negates_reqs(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::SubcommandsNegateReqs)
        } else {
            self.unset_setting(AppSettings::SubcommandsNegateReqs)
        }
    }

    /// Multiple-personality program dispatched on the binary name (`argv[0]`)
    ///
    /// A "multicall" executable is a single executable
    /// that contains a variety of applets,
    /// and decides which applet to run based on the name of the file.
    /// The executable can be called from different names by creating hard links
    /// or symbolic links to it.
    ///
    /// This is desirable for:
    /// - Easy distribution, a single binary that can install hardlinks to access the different
    ///   personalities.
    /// - Minimal binary size by sharing common code (e.g. standard library, clap)
    /// - Custom shells or REPLs where there isn't a single top-level command
    ///
    /// Setting `multicall` will cause
    /// - `argv[0]` to be stripped to the base name and parsed as the first argument, as if
    ///   [`Command::no_binary_name`][Command::no_binary_name] was set.
    /// - Help and errors to report subcommands as if they were the top-level command
    ///
    /// When the subcommand is not present, there are several strategies you may employ, depending
    /// on your needs:
    /// - Let the error percolate up normally
    /// - Print a specialized error message using the
    ///   [`Error::context`][crate::Error::context]
    /// - Print the [help][Command::write_help] but this might be ambiguous
    /// - Disable `multicall` and re-parse it
    /// - Disable `multicall` and re-parse it with a specific subcommand
    ///
    /// When detecting the error condition, the [`ErrorKind`] isn't sufficient as a sub-subcommand
    /// might report the same error.  Enable
    /// [`allow_external_subcommands`][Command::allow_external_subcommands] if you want to specifically
    /// get the unrecognized binary name.
    ///
    /// **NOTE:** Multicall can't be used with [`no_binary_name`] since they interpret
    /// the command name in incompatible ways.
    ///
    /// **NOTE:** The multicall command cannot have arguments.
    ///
    /// **NOTE:** Applets are slightly semantically different from subcommands,
    /// so it's recommended to use [`Command::subcommand_help_heading`] and
    /// [`Command::subcommand_value_name`] to change the descriptive text as above.
    ///
    /// # Examples
    ///
    /// `hostname` is an example of a multicall executable.
    /// Both `hostname` and `dnsdomainname` are provided by the same executable
    /// and which behaviour to use is based on the executable file name.
    ///
    /// This is desirable when the executable has a primary purpose
    /// but there is related functionality that would be convenient to provide
    /// and implement it to be in the same executable.
    ///
    /// The name of the cmd is essentially unused
    /// and may be the same as the name of a subcommand.
    ///
    /// The names of the immediate subcommands of the Command
    /// are matched against the basename of the first argument,
    /// which is conventionally the path of the executable.
    ///
    /// This does not allow the subcommand to be passed as the first non-path argument.
    ///
    /// ```rust
    /// # use clap::{Command, error::ErrorKind};
    /// let mut cmd = Command::new("hostname")
    ///     .multicall(true)
    ///     .subcommand(Command::new("hostname"))
    ///     .subcommand(Command::new("dnsdomainname"));
    /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]);
    /// assert!(m.is_err());
    /// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument);
    /// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]);
    /// assert_eq!(m.subcommand_name(), Some("dnsdomainname"));
    /// ```
    ///
    /// Busybox is another common example of a multicall executable
    /// with a subcommmand for each applet that can be run directly,
    /// e.g. with the `cat` applet being run by running `busybox cat`,
    /// or with `cat` as a link to the `busybox` binary.
    ///
    /// This is desirable when the launcher program has additional options
    /// or it is useful to run the applet without installing a symlink
    /// e.g. to test the applet without installing it
    /// or there may already be a command of that name installed.
    ///
    /// To make an applet usable as both a multicall link and a subcommand
    /// the subcommands must be defined both in the top-level Command
    /// and as subcommands of the "main" applet.
    ///
    /// ```rust
    /// # use clap::Command;
    /// fn applet_commands() -> [Command; 2] {
    ///     [Command::new("true"), Command::new("false")]
    /// }
    /// let mut cmd = Command::new("busybox")
    ///     .multicall(true)
    ///     .subcommand(
    ///         Command::new("busybox")
    ///             .subcommand_value_name("APPLET")
    ///             .subcommand_help_heading("APPLETS")
    ///             .subcommands(applet_commands()),
    ///     )
    ///     .subcommands(applet_commands());
    /// // When called from the executable's canonical name
    /// // its applets can be matched as subcommands.
    /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap();
    /// assert_eq!(m.subcommand_name(), Some("busybox"));
    /// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true"));
    /// // When called from a link named after an applet that applet is matched.
    /// let m = cmd.get_matches_from(&["/usr/bin/true"]);
    /// assert_eq!(m.subcommand_name(), Some("true"));
    /// ```
    ///
    /// [`no_binary_name`]: crate::Command::no_binary_name
    /// [`Command::subcommand_value_name`]: crate::Command::subcommand_value_name
    /// [`Command::subcommand_help_heading`]: crate::Command::subcommand_help_heading
    #[inline]
    pub fn multicall(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::Multicall)
        } else {
            self.unset_setting(AppSettings::Multicall)
        }
    }

    /// Sets the value name used for subcommands when printing usage and help.
    ///
    /// By default, this is "COMMAND".
    ///
    /// See also [`Command::subcommand_help_heading`]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .subcommand(Command::new("sub1"))
    ///     .print_help()
    /// # ;
    /// ```
    ///
    /// will produce
    ///
    /// ```text
    /// myprog
    ///
    /// Usage: myprog [COMMAND]
    ///
    /// Commands:
    ///     help    Print this message or the help of the given subcommand(s)
    ///     sub1
    ///
    /// Options:
    ///     -h, --help       Print help information
    ///     -V, --version    Print version information
    /// ```
    ///
    /// but usage of `subcommand_value_name`
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .subcommand(Command::new("sub1"))
    ///     .subcommand_value_name("THING")
    ///     .print_help()
    /// # ;
    /// ```
    ///
    /// will produce
    ///
    /// ```text
    /// myprog
    ///
    /// Usage: myprog [THING]
    ///
    /// Commands:
    ///     help    Print this message or the help of the given subcommand(s)
    ///     sub1
    ///
    /// Options:
    ///     -h, --help       Print help information
    ///     -V, --version    Print version information
    /// ```
    #[must_use]
    pub fn subcommand_value_name(mut self, value_name: impl IntoResettable<Str>) -> Self {
        self.subcommand_value_name = value_name.into_resettable().into_option();
        self
    }

    /// Sets the help heading used for subcommands when printing usage and help.
    ///
    /// By default, this is "Commands".
    ///
    /// See also [`Command::subcommand_value_name`]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .subcommand(Command::new("sub1"))
    ///     .print_help()
    /// # ;
    /// ```
    ///
    /// will produce
    ///
    /// ```text
    /// myprog
    ///
    /// Usage: myprog [COMMAND]
    ///
    /// Commands:
    ///     help    Print this message or the help of the given subcommand(s)
    ///     sub1
    ///
    /// Options:
    ///     -h, --help       Print help information
    ///     -V, --version    Print version information
    /// ```
    ///
    /// but usage of `subcommand_help_heading`
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .subcommand(Command::new("sub1"))
    ///     .subcommand_help_heading("Things")
    ///     .print_help()
    /// # ;
    /// ```
    ///
    /// will produce
    ///
    /// ```text
    /// myprog
    ///
    /// Usage: myprog [COMMAND]
    ///
    /// Things:
    ///     help    Print this message or the help of the given subcommand(s)
    ///     sub1
    ///
    /// Options:
    ///     -h, --help       Print help information
    ///     -V, --version    Print version information
    /// ```
    #[must_use]
    pub fn subcommand_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self {
        self.subcommand_heading = heading.into_resettable().into_option();
        self
    }
}

/// # Reflection
impl Command {
    #[inline]
    #[cfg(feature = "usage")]
    pub(crate) fn get_usage_name(&self) -> Option<&str> {
        self.usage_name.as_deref()
    }

    /// Get the name of the binary.
    #[inline]
    pub fn get_display_name(&self) -> Option<&str> {
        self.display_name.as_deref()
    }

    /// Get the name of the binary.
    #[inline]
    pub fn get_bin_name(&self) -> Option<&str> {
        self.bin_name.as_deref()
    }

    /// Set binary name. Uses `&mut self` instead of `self`.
    pub fn set_bin_name(&mut self, name: impl Into<String>) {
        self.bin_name = Some(name.into());
    }

    /// Get the name of the cmd.
    #[inline]
    pub fn get_name(&self) -> &str {
        self.name.as_str()
    }

    #[inline]
    #[cfg(debug_assertions)]
    pub(crate) fn get_name_str(&self) -> &Str {
        &self.name
    }

    /// Get the version of the cmd.
    #[inline]
    pub fn get_version(&self) -> Option<&str> {
        self.version.as_deref()
    }

    /// Get the long version of the cmd.
    #[inline]
    pub fn get_long_version(&self) -> Option<&str> {
        self.long_version.as_deref()
    }

    /// Get the authors of the cmd.
    #[inline]
    pub fn get_author(&self) -> Option<&str> {
        self.author.as_deref()
    }

    /// Get the short flag of the subcommand.
    #[inline]
    pub fn get_short_flag(&self) -> Option<char> {
        self.short_flag
    }

    /// Get the long flag of the subcommand.
    #[inline]
    pub fn get_long_flag(&self) -> Option<&str> {
        self.long_flag.as_deref()
    }

    /// Get the help message specified via [`Command::about`].
    ///
    /// [`Command::about`]: Command::about()
    #[inline]
    pub fn get_about(&self) -> Option<&StyledStr> {
        self.about.as_ref()
    }

    /// Get the help message specified via [`Command::long_about`].
    ///
    /// [`Command::long_about`]: Command::long_about()
    #[inline]
    pub fn get_long_about(&self) -> Option<&StyledStr> {
        self.long_about.as_ref()
    }

    /// Get the custom section heading specified via [`Command::next_help_heading`].
    ///
    /// [`Command::help_heading`]: Command::help_heading()
    #[inline]
    pub fn get_next_help_heading(&self) -> Option<&str> {
        self.current_help_heading.as_deref()
    }

    /// Iterate through the *visible* aliases for this subcommand.
    #[inline]
    pub fn get_visible_aliases(&self) -> impl Iterator<Item = &str> + '_ {
        self.aliases
            .iter()
            .filter(|(_, vis)| *vis)
            .map(|a| a.0.as_str())
    }

    /// Iterate through the *visible* short aliases for this subcommand.
    #[inline]
    pub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
        self.short_flag_aliases
            .iter()
            .filter(|(_, vis)| *vis)
            .map(|a| a.0)
    }

    /// Iterate through the *visible* long aliases for this subcommand.
    #[inline]
    pub fn get_visible_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ {
        self.long_flag_aliases
            .iter()
            .filter(|(_, vis)| *vis)
            .map(|a| a.0.as_str())
    }

    /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden.
    #[inline]
    pub fn get_all_aliases(&self) -> impl Iterator<Item = &str> + '_ {
        self.aliases.iter().map(|a| a.0.as_str())
    }

    /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden.
    #[inline]
    pub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
        self.short_flag_aliases.iter().map(|a| a.0)
    }

    /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden.
    #[inline]
    pub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ {
        self.long_flag_aliases.iter().map(|a| a.0.as_str())
    }

    #[inline]
    pub(crate) fn is_set(&self, s: AppSettings) -> bool {
        self.settings.is_set(s) || self.g_settings.is_set(s)
    }

    /// Should we color the output?
    pub fn get_color(&self) -> ColorChoice {
        debug!("Command::color: Color setting...");

        if cfg!(feature = "color") {
            if self.is_set(AppSettings::ColorNever) {
                debug!("Never");
                ColorChoice::Never
            } else if self.is_set(AppSettings::ColorAlways) {
                debug!("Always");
                ColorChoice::Always
            } else {
                debug!("Auto");
                ColorChoice::Auto
            }
        } else {
            ColorChoice::Never
        }
    }

    /// Iterate through the set of subcommands, getting a reference to each.
    #[inline]
    pub fn get_subcommands(&self) -> impl Iterator<Item = &Command> {
        self.subcommands.iter()
    }

    /// Iterate through the set of subcommands, getting a mutable reference to each.
    #[inline]
    pub fn get_subcommands_mut(&mut self) -> impl Iterator<Item = &mut Command> {
        self.subcommands.iter_mut()
    }

    /// Returns `true` if this `Command` has subcommands.
    #[inline]
    pub fn has_subcommands(&self) -> bool {
        !self.subcommands.is_empty()
    }

    /// Returns the help heading for listing subcommands.
    #[inline]
    pub fn get_subcommand_help_heading(&self) -> Option<&str> {
        self.subcommand_heading.as_deref()
    }

    /// Returns the subcommand value name.
    #[inline]
    pub fn get_subcommand_value_name(&self) -> Option<&str> {
        self.subcommand_value_name.as_deref()
    }

    /// Returns the help heading for listing subcommands.
    #[inline]
    pub fn get_before_help(&self) -> Option<&StyledStr> {
        self.before_help.as_ref()
    }

    /// Returns the help heading for listing subcommands.
    #[inline]
    pub fn get_before_long_help(&self) -> Option<&StyledStr> {
        self.before_long_help.as_ref()
    }

    /// Returns the help heading for listing subcommands.
    #[inline]
    pub fn get_after_help(&self) -> Option<&StyledStr> {
        self.after_help.as_ref()
    }

    /// Returns the help heading for listing subcommands.
    #[inline]
    pub fn get_after_long_help(&self) -> Option<&StyledStr> {
        self.after_long_help.as_ref()
    }

    /// Find subcommand such that its name or one of aliases equals `name`.
    ///
    /// This does not recurse through subcommands of subcommands.
    #[inline]
    pub fn find_subcommand(&self, name: impl AsRef<std::ffi::OsStr>) -> Option<&Command> {
        let name = name.as_ref();
        self.get_subcommands().find(|s| s.aliases_to(name))
    }

    /// Find subcommand such that its name or one of aliases equals `name`, returning
    /// a mutable reference to the subcommand.
    ///
    /// This does not recurse through subcommands of subcommands.
    #[inline]
    pub fn find_subcommand_mut(
        &mut self,
        name: impl AsRef<std::ffi::OsStr>,
    ) -> Option<&mut Command> {
        let name = name.as_ref();
        self.get_subcommands_mut().find(|s| s.aliases_to(name))
    }

    /// Iterate through the set of groups.
    #[inline]
    pub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup> {
        self.groups.iter()
    }

    /// Iterate through the set of arguments.
    #[inline]
    pub fn get_arguments(&self) -> impl Iterator<Item = &Arg> {
        self.args.args()
    }

    /// Iterate through the *positionals* arguments.
    #[inline]
    pub fn get_positionals(&self) -> impl Iterator<Item = &Arg> {
        self.get_arguments().filter(|a| a.is_positional())
    }

    /// Iterate through the *options*.
    pub fn get_opts(&self) -> impl Iterator<Item = &Arg> {
        self.get_arguments()
            .filter(|a| a.is_takes_value_set() && !a.is_positional())
    }

    /// Get a list of all arguments the given argument conflicts with.
    ///
    /// If the provided argument is declared as global, the conflicts will be determined
    /// based on the propagation rules of global arguments.
    ///
    /// ### Panics
    ///
    /// If the given arg contains a conflict with an argument that is unknown to
    /// this `Command`.
    pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
    {
        if arg.is_global_set() {
            self.get_global_arg_conflicts_with(arg)
        } else {
            let mut result = Vec::new();
            for id in arg.blacklist.iter() {
                if let Some(arg) = self.find(id) {
                    result.push(arg);
                } else if let Some(group) = self.find_group(id) {
                    result.extend(
                        self.unroll_args_in_group(&group.id)
                            .iter()
                            .map(|id| self.find(id).expect(INTERNAL_ERROR_MSG)),
                    );
                } else {
                    panic!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd");
                }
            }
            result
        }
    }

    // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with.
    //
    // This behavior follows the propagation rules of global arguments.
    // It is useful for finding conflicts for arguments declared as global.
    //
    // ### Panics
    //
    // If the given arg contains a conflict with an argument that is unknown to
    // this `Command`.
    fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
    {
        arg.blacklist
            .iter()
            .map(|id| {
                self.args
                    .args()
                    .chain(
                        self.get_subcommands_containing(arg)
                            .iter()
                            .flat_map(|x| x.args.args()),
                    )
                    .find(|arg| arg.get_id() == id)
                    .expect(
                        "Command::get_arg_conflicts_with: \
                    The passed arg conflicts with an arg unknown to the cmd",
                    )
            })
            .collect()
    }

    // Get a list of subcommands which contain the provided Argument
    //
    // This command will only include subcommands in its list for which the subcommands
    // parent also contains the Argument.
    //
    // This search follows the propagation rules of global arguments.
    // It is useful to finding subcommands, that have inherited a global argument.
    //
    // **NOTE:** In this case only Sucommand_1 will be included
    //   Subcommand_1 (contains Arg)
    //     Subcommand_1.1 (doesn't contain Arg)
    //       Subcommand_1.1.1 (contains Arg)
    //
    fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&Self> {
        let mut vec = std::vec::Vec::new();
        for idx in 0..self.subcommands.len() {
            if self.subcommands[idx]
                .args
                .args()
                .any(|ar| ar.get_id() == arg.get_id())
            {
                vec.push(&self.subcommands[idx]);
                vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg));
            }
        }
        vec
    }

    /// Report whether [`Command::no_binary_name`] is set
    pub fn is_no_binary_name_set(&self) -> bool {
        self.is_set(AppSettings::NoBinaryName)
    }

    /// Report whether [`Command::ignore_errors`] is set
    pub(crate) fn is_ignore_errors_set(&self) -> bool {
        self.is_set(AppSettings::IgnoreErrors)
    }

    /// Report whether [`Command::dont_delimit_trailing_values`] is set
    pub fn is_dont_delimit_trailing_values_set(&self) -> bool {
        self.is_set(AppSettings::DontDelimitTrailingValues)
    }

    /// Report whether [`Command::disable_version_flag`] is set
    pub fn is_disable_version_flag_set(&self) -> bool {
        self.is_set(AppSettings::DisableVersionFlag)
            || (self.version.is_none() && self.long_version.is_none())
    }

    /// Report whether [`Command::propagate_version`] is set
    pub fn is_propagate_version_set(&self) -> bool {
        self.is_set(AppSettings::PropagateVersion)
    }

    /// Report whether [`Command::next_line_help`] is set
    pub fn is_next_line_help_set(&self) -> bool {
        self.is_set(AppSettings::NextLineHelp)
    }

    /// Report whether [`Command::disable_help_flag`] is set
    pub fn is_disable_help_flag_set(&self) -> bool {
        self.is_set(AppSettings::DisableHelpFlag)
    }

    /// Report whether [`Command::disable_help_subcommand`] is set
    pub fn is_disable_help_subcommand_set(&self) -> bool {
        self.is_set(AppSettings::DisableHelpSubcommand)
    }

    /// Report whether [`Command::disable_colored_help`] is set
    pub fn is_disable_colored_help_set(&self) -> bool {
        self.is_set(AppSettings::DisableColoredHelp)
    }

    /// Report whether [`Command::help_expected`] is set
    #[cfg(debug_assertions)]
    pub(crate) fn is_help_expected_set(&self) -> bool {
        self.is_set(AppSettings::HelpExpected)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "This is now the default")
    )]
    pub fn is_dont_collapse_args_in_usage_set(&self) -> bool {
        true
    }

    /// Report whether [`Command::infer_long_args`] is set
    pub(crate) fn is_infer_long_args_set(&self) -> bool {
        self.is_set(AppSettings::InferLongArgs)
    }

    /// Report whether [`Command::infer_subcommands`] is set
    pub(crate) fn is_infer_subcommands_set(&self) -> bool {
        self.is_set(AppSettings::InferSubcommands)
    }

    /// Report whether [`Command::arg_required_else_help`] is set
    pub fn is_arg_required_else_help_set(&self) -> bool {
        self.is_set(AppSettings::ArgRequiredElseHelp)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(
            since = "4.0.0",
            note = "Replaced with `Arg::is_allow_hyphen_values_set`"
        )
    )]
    pub(crate) fn is_allow_hyphen_values_set(&self) -> bool {
        self.is_set(AppSettings::AllowHyphenValues)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(
            since = "4.0.0",
            note = "Replaced with `Arg::is_allow_negative_numbers_set`"
        )
    )]
    pub fn is_allow_negative_numbers_set(&self) -> bool {
        self.is_set(AppSettings::AllowNegativeNumbers)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "Replaced with `Arg::is_trailing_var_arg_set`")
    )]
    pub fn is_trailing_var_arg_set(&self) -> bool {
        self.is_set(AppSettings::TrailingVarArg)
    }

    /// Report whether [`Command::allow_missing_positional`] is set
    pub fn is_allow_missing_positional_set(&self) -> bool {
        self.is_set(AppSettings::AllowMissingPositional)
    }

    /// Report whether [`Command::hide`] is set
    pub fn is_hide_set(&self) -> bool {
        self.is_set(AppSettings::Hidden)
    }

    /// Report whether [`Command::subcommand_required`] is set
    pub fn is_subcommand_required_set(&self) -> bool {
        self.is_set(AppSettings::SubcommandRequired)
    }

    /// Report whether [`Command::allow_external_subcommands`] is set
    pub fn is_allow_external_subcommands_set(&self) -> bool {
        self.is_set(AppSettings::AllowExternalSubcommands)
    }

    /// Configured parser for values passed to an external subcommand
    ///
    /// # Example
    ///
    /// ```rust
    /// let cmd = clap::Command::new("raw")
    ///     .external_subcommand_value_parser(clap::value_parser!(String));
    /// let value_parser = cmd.get_external_subcommand_value_parser();
    /// println!("{:?}", value_parser);
    /// ```
    pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> {
        if !self.is_allow_external_subcommands_set() {
            None
        } else {
            static DEFAULT: super::ValueParser = super::ValueParser::os_string();
            Some(self.external_value_parser.as_ref().unwrap_or(&DEFAULT))
        }
    }

    /// Report whether [`Command::args_conflicts_with_subcommands`] is set
    pub fn is_args_conflicts_with_subcommands_set(&self) -> bool {
        self.is_set(AppSettings::ArgsNegateSubcommands)
    }

    #[doc(hidden)]
    pub fn is_args_override_self(&self) -> bool {
        self.is_set(AppSettings::AllArgsOverrideSelf)
    }

    /// Report whether [`Command::subcommand_precedence_over_arg`] is set
    pub fn is_subcommand_precedence_over_arg_set(&self) -> bool {
        self.is_set(AppSettings::SubcommandPrecedenceOverArg)
    }

    /// Report whether [`Command::subcommand_negates_reqs`] is set
    pub fn is_subcommand_negates_reqs_set(&self) -> bool {
        self.is_set(AppSettings::SubcommandsNegateReqs)
    }

    /// Report whether [`Command::multicall`] is set
    pub fn is_multicall_set(&self) -> bool {
        self.is_set(AppSettings::Multicall)
    }
}

// Internally used only
impl Command {
    pub(crate) fn get_override_usage(&self) -> Option<&StyledStr> {
        self.usage_str.as_ref()
    }

    pub(crate) fn get_override_help(&self) -> Option<&StyledStr> {
        self.help_str.as_ref()
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_help_template(&self) -> Option<&StyledStr> {
        self.template.as_ref()
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_term_width(&self) -> Option<usize> {
        self.term_w
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_max_term_width(&self) -> Option<usize> {
        self.max_w
    }

    pub(crate) fn get_replacement(&self, key: &str) -> Option<&[Str]> {
        self.replacers.get(key).map(|v| v.as_slice())
    }

    pub(crate) fn get_keymap(&self) -> &MKeyMap {
        &self.args
    }

    fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec<Id>) {
        global_arg_vec.extend(
            self.args
                .args()
                .filter(|a| a.is_global_set())
                .map(|ga| ga.id.clone()),
        );
        if let Some((id, matches)) = matches.subcommand() {
            if let Some(used_sub) = self.find_subcommand(id) {
                used_sub.get_used_global_args(matches, global_arg_vec);
            }
        }
    }

    fn _do_parse(
        &mut self,
        raw_args: &mut clap_lex::RawArgs,
        args_cursor: clap_lex::ArgCursor,
    ) -> ClapResult<ArgMatches> {
        debug!("Command::_do_parse");

        // If there are global arguments, or settings we need to propagate them down to subcommands
        // before parsing in case we run into a subcommand
        self._build_self(false);

        let mut matcher = ArgMatcher::new(self);

        // do the real parsing
        let mut parser = Parser::new(self);
        if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) {
            if self.is_set(AppSettings::IgnoreErrors) {
                debug!("Command::_do_parse: ignoring error: {}", error);
            } else {
                return Err(error);
            }
        }

        let mut global_arg_vec = Default::default();
        self.get_used_global_args(&matcher, &mut global_arg_vec);

        matcher.propagate_globals(&global_arg_vec);

        Ok(matcher.into_inner())
    }

    /// Prepare for introspecting on all included [`Command`]s
    ///
    /// Call this on the top-level [`Command`] when done building and before reading state for
    /// cases like completions, custom help output, etc.
    pub fn build(&mut self) {
        self._build_recursive(true);
        self._build_bin_names_internal();
    }

    pub(crate) fn _build_recursive(&mut self, expand_help_tree: bool) {
        self._build_self(expand_help_tree);
        for subcmd in self.get_subcommands_mut() {
            subcmd._build_recursive(expand_help_tree);
        }
    }

    pub(crate) fn _build_self(&mut self, expand_help_tree: bool) {
        debug!("Command::_build: name={:?}", self.get_name());
        if !self.settings.is_set(AppSettings::Built) {
            // Make sure all the globally set flags apply to us as well
            self.settings = self.settings | self.g_settings;

            if self.is_multicall_set() {
                self.settings.insert(AppSettings::SubcommandRequired.into());
                self.settings.insert(AppSettings::DisableHelpFlag.into());
                self.settings.insert(AppSettings::DisableVersionFlag.into());
            }
            if !cfg!(feature = "help") && self.get_override_help().is_none() {
                self.settings.insert(AppSettings::DisableHelpFlag.into());
                self.settings
                    .insert(AppSettings::DisableHelpSubcommand.into());
            }
            if self.is_set(AppSettings::ArgsNegateSubcommands) {
                self.settings
                    .insert(AppSettings::SubcommandsNegateReqs.into());
            }
            if self.external_value_parser.is_some() {
                self.settings
                    .insert(AppSettings::AllowExternalSubcommands.into());
            }
            if !self.has_subcommands() {
                self.settings
                    .insert(AppSettings::DisableHelpSubcommand.into());
            }

            self._propagate();
            self._check_help_and_version(expand_help_tree);
            self._propagate_global_args();

            let mut pos_counter = 1;
            let hide_pv = self.is_set(AppSettings::HidePossibleValues);
            for a in self.args.args_mut() {
                // Fill in the groups
                for g in &a.groups {
                    if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) {
                        ag.args.push(a.get_id().clone());
                    } else {
                        let mut ag = ArgGroup::new(g);
                        ag.args.push(a.get_id().clone());
                        self.groups.push(ag);
                    }
                }

                // Figure out implied settings
                a._build();
                if hide_pv && a.is_takes_value_set() {
                    a.settings.set(ArgSettings::HidePossibleValues);
                }
                if a.is_positional() && a.index.is_none() {
                    a.index = Some(pos_counter);
                    pos_counter += 1;
                }
            }

            self.args._build();

            #[allow(deprecated)]
            {
                let highest_idx = self
                    .get_keymap()
                    .keys()
                    .filter_map(|x| {
                        if let crate::mkeymap::KeyType::Position(n) = x {
                            Some(*n)
                        } else {
                            None
                        }
                    })
                    .max()
                    .unwrap_or(0);
                let is_trailing_var_arg_set = self.is_trailing_var_arg_set();
                let is_allow_hyphen_values_set = self.is_allow_hyphen_values_set();
                let is_allow_negative_numbers_set = self.is_allow_negative_numbers_set();
                for arg in self.args.args_mut() {
                    if is_allow_hyphen_values_set && arg.is_takes_value_set() {
                        arg.settings.insert(ArgSettings::AllowHyphenValues.into());
                    }
                    if is_allow_negative_numbers_set && arg.is_takes_value_set() {
                        arg.settings
                            .insert(ArgSettings::AllowNegativeNumbers.into());
                    }
                    if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) {
                        arg.settings.insert(ArgSettings::TrailingVarArg.into());
                    }
                }
            }

            #[cfg(debug_assertions)]
            assert_app(self);
            self.settings.set(AppSettings::Built);
        } else {
            debug!("Command::_build: already built");
        }
    }

    pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> {
        use std::fmt::Write;

        let mut mid_string = String::from(" ");
        #[cfg(feature = "usage")]
        if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set()
        {
            let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

            for s in &reqs {
                mid_string.push_str(&s.to_string());
                mid_string.push(' ');
            }
        }
        let is_multicall_set = self.is_multicall_set();

        let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name));

        // Display subcommand name, short and long in usage
        let mut sc_names = String::new();
        sc_names.push_str(sc.name.as_str());
        let mut flag_subcmd = false;
        if let Some(l) = sc.get_long_flag() {
            write!(sc_names, "|--{}", l).unwrap();
            flag_subcmd = true;
        }
        if let Some(s) = sc.get_short_flag() {
            write!(sc_names, "|-{}", s).unwrap();
            flag_subcmd = true;
        }

        if flag_subcmd {
            sc_names = format!("{{{}}}", sc_names);
        }

        let usage_name = self
            .bin_name
            .as_ref()
            .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names))
            .unwrap_or(sc_names);
        sc.usage_name = Some(usage_name);

        // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
        // a space
        let bin_name = format!(
            "{}{}{}",
            self.bin_name.as_deref().unwrap_or_default(),
            if self.bin_name.is_some() { " " } else { "" },
            &*sc.name
        );
        debug!(
            "Command::_build_subcommand Setting bin_name of {} to {:?}",
            sc.name, bin_name
        );
        sc.bin_name = Some(bin_name);

        if sc.display_name.is_none() {
            let self_display_name = if is_multicall_set {
                self.display_name.as_deref().unwrap_or("")
            } else {
                self.display_name.as_deref().unwrap_or(&self.name)
            };
            let display_name = format!(
                "{}{}{}",
                self_display_name,
                if !self_display_name.is_empty() {
                    "-"
                } else {
                    ""
                },
                &*sc.name
            );
            debug!(
                "Command::_build_subcommand Setting display_name of {} to {:?}",
                sc.name, display_name
            );
            sc.display_name = Some(display_name);
        }

        // Ensure all args are built and ready to parse
        sc._build_self(false);

        Some(sc)
    }

    fn _build_bin_names_internal(&mut self) {
        debug!("Command::_build_bin_names");

        if !self.is_set(AppSettings::BinNameBuilt) {
            let mut mid_string = String::from(" ");
            #[cfg(feature = "usage")]
            if !self.is_subcommand_negates_reqs_set()
                && !self.is_args_conflicts_with_subcommands_set()
            {
                let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

                for s in &reqs {
                    mid_string.push_str(&s.to_string());
                    mid_string.push(' ');
                }
            }
            let is_multicall_set = self.is_multicall_set();

            let self_bin_name = if is_multicall_set {
                self.bin_name.as_deref().unwrap_or("")
            } else {
                self.bin_name.as_deref().unwrap_or(&self.name)
            }
            .to_owned();

            for mut sc in &mut self.subcommands {
                debug!("Command::_build_bin_names:iter: bin_name set...");

                if sc.usage_name.is_none() {
                    use std::fmt::Write;
                    // Display subcommand name, short and long in usage
                    let mut sc_names = String::new();
                    sc_names.push_str(sc.name.as_str());
                    let mut flag_subcmd = false;
                    if let Some(l) = sc.get_long_flag() {
                        write!(sc_names, "|--{}", l).unwrap();
                        flag_subcmd = true;
                    }
                    if let Some(s) = sc.get_short_flag() {
                        write!(sc_names, "|-{}", s).unwrap();
                        flag_subcmd = true;
                    }

                    if flag_subcmd {
                        sc_names = format!("{{{}}}", sc_names);
                    }

                    let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names);
                    debug!(
                        "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}",
                        sc.name, usage_name
                    );
                    sc.usage_name = Some(usage_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})",
                        sc.name, sc.usage_name
                    );
                }

                if sc.bin_name.is_none() {
                    let bin_name = format!(
                        "{}{}{}",
                        self_bin_name,
                        if !self_bin_name.is_empty() { " " } else { "" },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}",
                        sc.name, bin_name
                    );
                    sc.bin_name = Some(bin_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})",
                        sc.name, sc.bin_name
                    );
                }

                if sc.display_name.is_none() {
                    let self_display_name = if is_multicall_set {
                        self.display_name.as_deref().unwrap_or("")
                    } else {
                        self.display_name.as_deref().unwrap_or(&self.name)
                    };
                    let display_name = format!(
                        "{}{}{}",
                        self_display_name,
                        if !self_display_name.is_empty() {
                            "-"
                        } else {
                            ""
                        },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting display_name of {} to {:?}",
                        sc.name, display_name
                    );
                    sc.display_name = Some(display_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})",
                        sc.name, sc.display_name
                    );
                }

                sc._build_bin_names_internal();
            }
            self.set(AppSettings::BinNameBuilt);
        } else {
            debug!("Command::_build_bin_names: already built");
        }
    }

    pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) {
        if self.is_set(AppSettings::HelpExpected) || help_required_globally {
            let args_missing_help: Vec<Id> = self
                .args
                .args()
                .filter(|arg| arg.get_help().is_none() && arg.get_long_help().is_none())
                .map(|arg| arg.get_id().clone())
                .collect();

            debug_assert!(args_missing_help.is_empty(),
                    "Command::help_expected is enabled for the Command {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}",
                    self.name,
                    args_missing_help.join(", ")
                );
        }

        for sub_app in &self.subcommands {
            sub_app._panic_on_missing_help(help_required_globally);
        }
    }

    #[cfg(debug_assertions)]
    pub(crate) fn two_args_of<F>(&self, condition: F) -> Option<(&Arg, &Arg)>
    where
        F: Fn(&Arg) -> bool,
    {
        two_elements_of(self.args.args().filter(|a: &&Arg| condition(a)))
    }

    // just in case
    #[allow(unused)]
    fn two_groups_of<F>(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)>
    where
        F: Fn(&ArgGroup) -> bool,
    {
        two_elements_of(self.groups.iter().filter(|a| condition(a)))
    }

    /// Propagate global args
    pub(crate) fn _propagate_global_args(&mut self) {
        debug!("Command::_propagate_global_args:{}", self.name);

        let autogenerated_help_subcommand = !self.is_disable_help_subcommand_set();

        for sc in &mut self.subcommands {
            if sc.get_name() == "help" && autogenerated_help_subcommand {
                // Avoid propagating args to the autogenerated help subtrees used in completion.
                // This prevents args from showing up during help completions like
                // `myapp help subcmd <TAB>`, which should only suggest subcommands and not args,
                // while still allowing args to show up properly on the generated help message.
                continue;
            }

            for a in self.args.args().filter(|a| a.is_global_set()) {
                if sc.find(&a.id).is_some() {
                    debug!(
                        "Command::_propagate skipping {:?} to {}, already exists",
                        a.id,
                        sc.get_name(),
                    );
                    continue;
                }

                debug!(
                    "Command::_propagate pushing {:?} to {}",
                    a.id,
                    sc.get_name(),
                );
                sc.args.push(a.clone());
            }
        }
    }

    /// Propagate settings
    pub(crate) fn _propagate(&mut self) {
        debug!("Command::_propagate:{}", self.name);
        let mut subcommands = std::mem::take(&mut self.subcommands);
        for sc in &mut subcommands {
            self._propagate_subcommand(sc);
        }
        self.subcommands = subcommands;
    }

    fn _propagate_subcommand(&self, sc: &mut Self) {
        // We have to create a new scope in order to tell rustc the borrow of `sc` is
        // done and to recursively call this method
        {
            if self.settings.is_set(AppSettings::PropagateVersion) {
                if let Some(version) = self.version.as_ref() {
                    sc.version.get_or_insert_with(|| version.clone());
                }
                if let Some(long_version) = self.long_version.as_ref() {
                    sc.long_version.get_or_insert_with(|| long_version.clone());
                }
            }

            sc.settings = sc.settings | self.g_settings;
            sc.g_settings = sc.g_settings | self.g_settings;
            sc.term_w = self.term_w;
            sc.max_w = self.max_w;
        }
    }

    pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) {
        debug!(
            "Command::_check_help_and_version:{} expand_help_tree={}",
            self.name, expand_help_tree
        );

        self.long_help_exists = self.long_help_exists_();

        if !self.is_disable_help_flag_set() {
            debug!("Command::_check_help_and_version: Building default --help");
            let mut arg = Arg::new(Id::HELP)
                .short('h')
                .long("help")
                .action(ArgAction::Help);
            if self.long_help_exists {
                arg = arg
                    .help("Print help information (use `--help` for more detail)")
                    .long_help("Print help information (use `-h` for a summary)");
            } else {
                arg = arg.help("Print help information");
            }
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }
        if !self.is_disable_version_flag_set() {
            debug!("Command::_check_help_and_version: Building default --version");
            let arg = Arg::new(Id::VERSION)
                .short('V')
                .long("version")
                .action(ArgAction::Version)
                .help("Print version information");
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }

        if !self.is_set(AppSettings::DisableHelpSubcommand) {
            debug!("Command::_check_help_and_version: Building help subcommand");
            let help_about = "Print this message or the help of the given subcommand(s)";

            let mut help_subcmd = if expand_help_tree {
                // Slow code path to recursively clone all other subcommand subtrees under help
                let help_subcmd = Command::new("help")
                    .about(help_about)
                    .global_setting(AppSettings::DisableHelpSubcommand)
                    .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));

                let mut help_help_subcmd = Command::new("help").about(help_about);
                help_help_subcmd.version = None;
                help_help_subcmd.long_version = None;
                help_help_subcmd = help_help_subcmd
                    .setting(AppSettings::DisableHelpFlag)
                    .setting(AppSettings::DisableVersionFlag);

                help_subcmd.subcommand(help_help_subcmd)
            } else {
                Command::new("help").about(help_about).arg(
                    Arg::new("subcommand")
                        .action(ArgAction::Append)
                        .num_args(..)
                        .value_name("COMMAND")
                        .help("Print help for the subcommand(s)"),
                )
            };
            self._propagate_subcommand(&mut help_subcmd);

            // The parser acts like this is set, so let's set it so we don't falsely
            // advertise it to the user
            help_subcmd.version = None;
            help_subcmd.long_version = None;
            help_subcmd = help_subcmd
                .setting(AppSettings::DisableHelpFlag)
                .setting(AppSettings::DisableVersionFlag)
                .unset_global_setting(AppSettings::PropagateVersion);

            self.subcommands.push(help_subcmd);
        }
    }

Adds multiple arguments to the list of valid possibilities.

Examples
Command::new("myprog")
    .args([
        arg!("[debug] -d 'turns on debugging info'"),
        Arg::new("input").help("the input file to use")
    ])

Allows one to mutate an Arg after it’s been added to a Command.

This can be useful for modifying the auto-generated help or version arguments.

Panics

If the argument is undefined

Examples

let mut cmd = Command::new("foo")
    .arg(Arg::new("bar")
        .short('b')
        .action(ArgAction::SetTrue))
    .mut_arg("bar", |a| a.short('B'));

let res = cmd.try_get_matches_from_mut(vec!["foo", "-b"]);

// Since we changed `bar`'s short to "B" this should err as there
// is no `-b` anymore, only `-B`

assert!(res.is_err());

let res = cmd.try_get_matches_from_mut(vec!["foo", "-B"]);
assert!(res.is_ok());

Allows one to mutate a Command after it’s been added as a subcommand.

This can be useful for modifying auto-generated arguments of nested subcommands with Command::mut_arg.

Panics

If the subcommand is undefined

Examples

let mut cmd = Command::new("foo")
        .subcommand(Command::new("bar"))
        .mut_subcommand("bar", |subcmd| subcmd.disable_help_flag(true));

let res = cmd.try_get_matches_from_mut(vec!["foo", "bar", "--help"]);

// Since we disabled the help flag on the "bar" subcommand, this should err.

assert!(res.is_err());

let res = cmd.try_get_matches_from_mut(vec!["foo", "bar"]);
assert!(res.is_ok());

Adds an ArgGroup to the application.

ArgGroups are a family of related arguments. By placing them in a logical group, you can build easier requirement and exclusion rules.

Example use cases:

  • Make an entire ArgGroup required, meaning that one (and only one) argument from that group must be present at runtime.
  • Name an ArgGroup as a conflict to another argument. Meaning any of the arguments that belong to that group will cause a failure if present with the conflicting argument.
  • Ensure exclusion between arguments.
  • Extract a value from a group instead of determining exactly which argument was used.
Examples

The following example demonstrates using an ArgGroup to ensure that one, and only one, of the arguments from the specified group is present at runtime.

Command::new("cmd")
    .arg(arg!("--set-ver [ver] 'set the version manually'"))
    .arg(arg!("--major 'auto increase major'"))
    .arg(arg!("--minor 'auto increase minor'"))
    .arg(arg!("--patch 'auto increase patch'"))
    .group(ArgGroup::new("vers")
         .args(["set-ver", "major", "minor","patch"])
         .required(true))
Examples found in repository?
src/builder/command.rs (line 360)
358
359
360
361
362
363
    pub fn groups(mut self, groups: impl IntoIterator<Item = impl Into<ArgGroup>>) -> Self {
        for g in groups.into_iter() {
            self = self.group(g.into());
        }
        self
    }

Adds multiple ArgGroups to the Command at once.

Examples
Command::new("cmd")
    .arg(arg!("--set-ver [ver] 'set the version manually'"))
    .arg(arg!("--major         'auto increase major'"))
    .arg(arg!("--minor         'auto increase minor'"))
    .arg(arg!("--patch         'auto increase patch'"))
    .arg(arg!("-c [FILE]       'a config file'"))
    .arg(arg!("-i [IFACE]      'an interface'"))
    .groups([
        ArgGroup::new("vers")
            .args(["set-ver", "major", "minor","patch"])
            .required(true),
        ArgGroup::new("input")
            .args(["c", "i"])
    ])

Adds a subcommand to the list of valid possibilities.

Subcommands are effectively sub-Commands, because they can contain their own arguments, subcommands, version, usage, etc. They also function just like Commands, in that they get their own auto generated help, version, and usage.

A subcommand’s Command::name will be used for:

  • The argument the user passes in
  • Programmatically looking up the subcommand
Examples
Command::new("myprog")
    .subcommand(Command::new("config")
        .about("Controls configuration features")
        .arg(arg!("<config> 'Required configuration file to use'")))
Examples found in repository?
src/builder/command.rs (line 419)
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
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
    pub fn subcommands(mut self, subcmds: impl IntoIterator<Item = impl Into<Self>>) -> Self {
        for subcmd in subcmds {
            self = self.subcommand(subcmd);
        }
        self
    }

    /// Catch problems earlier in the development cycle.
    ///
    /// Most error states are handled as asserts under the assumption they are programming mistake
    /// and not something to handle at runtime.  Rather than relying on tests (manual or automated)
    /// that exhaustively test your CLI to ensure the asserts are evaluated, this will run those
    /// asserts in a way convenient for running as a test.
    ///
    /// **Note::** This will not help with asserts in [`ArgMatches`], those will need exhaustive
    /// testing of your CLI.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg, ArgAction};
    /// fn cmd() -> Command {
    ///     Command::new("foo")
    ///         .arg(
    ///             Arg::new("bar").short('b').action(ArgAction::SetTrue)
    ///         )
    /// }
    ///
    /// #[test]
    /// fn verify_app() {
    ///     cmd().debug_assert();
    /// }
    ///
    /// fn main() {
    ///     let m = cmd().get_matches_from(vec!["foo", "-b"]);
    ///     println!("{}", *m.get_one::<bool>("bar").expect("defaulted by clap"));
    /// }
    /// ```
    pub fn debug_assert(mut self) {
        self.build();
    }

    /// Custom error message for post-parsing validation
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, error::ErrorKind};
    /// let mut cmd = Command::new("myprog");
    /// let err = cmd.error(ErrorKind::InvalidValue, "Some failure case");
    /// ```
    pub fn error(&mut self, kind: ErrorKind, message: impl std::fmt::Display) -> Error {
        Error::raw(kind, message).format(self)
    }

    /// Parse [`env::args_os`], exiting on failure.
    ///
    /// # Panics
    ///
    /// If contradictory arguments or settings exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let matches = Command::new("myprog")
    ///     // Args and options go here...
    ///     .get_matches();
    /// ```
    /// [`env::args_os`]: std::env::args_os()
    /// [`Command::try_get_matches_from_mut`]: Command::try_get_matches_from_mut()
    #[inline]
    pub fn get_matches(self) -> ArgMatches {
        self.get_matches_from(&mut env::args_os())
    }

    /// Parse [`env::args_os`], exiting on failure.
    ///
    /// Like [`Command::get_matches`] but doesn't consume the `Command`.
    ///
    /// # Panics
    ///
    /// If contradictory arguments or settings exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let mut cmd = Command::new("myprog")
    ///     // Args and options go here...
    ///     ;
    /// let matches = cmd.get_matches_mut();
    /// ```
    /// [`env::args_os`]: std::env::args_os()
    /// [`Command::get_matches`]: Command::get_matches()
    pub fn get_matches_mut(&mut self) -> ArgMatches {
        self.try_get_matches_from_mut(&mut env::args_os())
            .unwrap_or_else(|e| e.exit())
    }

    /// Parse [`env::args_os`], returning a [`clap::Result`] on failure.
    ///
    /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
    /// used. It will return a [`clap::Error`], where the [`kind`] is a
    /// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call
    /// [`Error::exit`] or perform a [`std::process::exit`].
    ///
    /// # Panics
    ///
    /// If contradictory arguments or settings exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let matches = Command::new("myprog")
    ///     // Args and options go here...
    ///     .try_get_matches()
    ///     .unwrap_or_else(|e| e.exit());
    /// ```
    /// [`env::args_os`]: std::env::args_os()
    /// [`Error::exit`]: crate::Error::exit()
    /// [`std::process::exit`]: std::process::exit()
    /// [`clap::Result`]: Result
    /// [`clap::Error`]: crate::Error
    /// [`kind`]: crate::Error
    /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp
    /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion
    #[inline]
    pub fn try_get_matches(self) -> ClapResult<ArgMatches> {
        // Start the parsing
        self.try_get_matches_from(&mut env::args_os())
    }

    /// Parse the specified arguments, exiting on failure.
    ///
    /// **NOTE:** The first argument will be parsed as the binary name unless
    /// [`Command::no_binary_name`] is used.
    ///
    /// # Panics
    ///
    /// If contradictory arguments or settings exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
    ///
    /// let matches = Command::new("myprog")
    ///     // Args and options go here...
    ///     .get_matches_from(arg_vec);
    /// ```
    /// [`Command::get_matches`]: Command::get_matches()
    /// [`clap::Result`]: Result
    /// [`Vec`]: std::vec::Vec
    pub fn get_matches_from<I, T>(mut self, itr: I) -> ArgMatches
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        self.try_get_matches_from_mut(itr).unwrap_or_else(|e| {
            drop(self);
            e.exit()
        })
    }

    /// Parse the specified arguments, returning a [`clap::Result`] on failure.
    ///
    /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
    /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
    /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
    /// perform a [`std::process::exit`] yourself.
    ///
    /// **NOTE:** The first argument will be parsed as the binary name unless
    /// [`Command::no_binary_name`] is used.
    ///
    /// # Panics
    ///
    /// If contradictory arguments or settings exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
    ///
    /// let matches = Command::new("myprog")
    ///     // Args and options go here...
    ///     .try_get_matches_from(arg_vec)
    ///     .unwrap_or_else(|e| e.exit());
    /// ```
    /// [`Command::get_matches_from`]: Command::get_matches_from()
    /// [`Command::try_get_matches`]: Command::try_get_matches()
    /// [`Error::exit`]: crate::Error::exit()
    /// [`std::process::exit`]: std::process::exit()
    /// [`clap::Error`]: crate::Error
    /// [`Error::exit`]: crate::Error::exit()
    /// [`kind`]: crate::Error
    /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp
    /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion
    /// [`clap::Result`]: Result
    pub fn try_get_matches_from<I, T>(mut self, itr: I) -> ClapResult<ArgMatches>
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        self.try_get_matches_from_mut(itr)
    }

    /// Parse the specified arguments, returning a [`clap::Result`] on failure.
    ///
    /// Like [`Command::try_get_matches_from`] but doesn't consume the `Command`.
    ///
    /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
    /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
    /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
    /// perform a [`std::process::exit`] yourself.
    ///
    /// **NOTE:** The first argument will be parsed as the binary name unless
    /// [`Command::no_binary_name`] is used.
    ///
    /// # Panics
    ///
    /// If contradictory arguments or settings exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
    ///
    /// let mut cmd = Command::new("myprog");
    ///     // Args and options go here...
    /// let matches = cmd.try_get_matches_from_mut(arg_vec)
    ///     .unwrap_or_else(|e| e.exit());
    /// ```
    /// [`Command::try_get_matches_from`]: Command::try_get_matches_from()
    /// [`clap::Result`]: Result
    /// [`clap::Error`]: crate::Error
    /// [`kind`]: crate::Error
    pub fn try_get_matches_from_mut<I, T>(&mut self, itr: I) -> ClapResult<ArgMatches>
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        let mut raw_args = clap_lex::RawArgs::new(itr.into_iter());
        let mut cursor = raw_args.cursor();

        if self.settings.is_set(AppSettings::Multicall) {
            if let Some(argv0) = raw_args.next_os(&mut cursor) {
                let argv0 = Path::new(&argv0);
                if let Some(command) = argv0.file_stem().and_then(|f| f.to_str()) {
                    // Stop borrowing command so we can get another mut ref to it.
                    let command = command.to_owned();
                    debug!(
                        "Command::try_get_matches_from_mut: Parsed command {} from argv",
                        command
                    );

                    debug!("Command::try_get_matches_from_mut: Reinserting command into arguments so subcommand parser matches it");
                    raw_args.insert(&cursor, [&command]);
                    debug!("Command::try_get_matches_from_mut: Clearing name and bin_name so that displayed command name starts with applet name");
                    self.name = "".into();
                    self.bin_name = None;
                    return self._do_parse(&mut raw_args, cursor);
                }
            }
        };

        // Get the name of the program (argument 1 of env::args()) and determine the
        // actual file
        // that was used to execute the program. This is because a program called
        // ./target/release/my_prog -a
        // will have two arguments, './target/release/my_prog', '-a' but we don't want
        // to display
        // the full path when displaying help messages and such
        if !self.settings.is_set(AppSettings::NoBinaryName) {
            if let Some(name) = raw_args.next_os(&mut cursor) {
                let p = Path::new(name);

                if let Some(f) = p.file_name() {
                    if let Some(s) = f.to_str() {
                        if self.bin_name.is_none() {
                            self.bin_name = Some(s.to_owned());
                        }
                    }
                }
            }
        }

        self._do_parse(&mut raw_args, cursor)
    }

    /// Prints the short help message (`-h`) to [`io::stdout()`].
    ///
    /// See also [`Command::print_long_help`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// let mut cmd = Command::new("myprog");
    /// cmd.print_help();
    /// ```
    /// [`io::stdout()`]: std::io::stdout()
    pub fn print_help(&mut self) -> io::Result<()> {
        self._build_self(false);
        let color = self.color_help();

        let mut styled = StyledStr::new();
        let usage = Usage::new(self);
        write_help(&mut styled, self, &usage, false);

        let c = Colorizer::new(Stream::Stdout, color).with_content(styled);
        c.print()
    }

    /// Prints the long help message (`--help`) to [`io::stdout()`].
    ///
    /// See also [`Command::print_help`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// let mut cmd = Command::new("myprog");
    /// cmd.print_long_help();
    /// ```
    /// [`io::stdout()`]: std::io::stdout()
    /// [`BufWriter`]: std::io::BufWriter
    /// [`-h` (short)]: Arg::help()
    /// [`--help` (long)]: Arg::long_help()
    pub fn print_long_help(&mut self) -> io::Result<()> {
        self._build_self(false);
        let color = self.color_help();

        let mut styled = StyledStr::new();
        let usage = Usage::new(self);
        write_help(&mut styled, self, &usage, true);

        let c = Colorizer::new(Stream::Stdout, color).with_content(styled);
        c.print()
    }

    /// Render the short help message (`-h`) to a [`StyledStr`]
    ///
    /// See also [`Command::render_long_help`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// use std::io;
    /// let mut cmd = Command::new("myprog");
    /// let mut out = io::stdout();
    /// let help = cmd.render_help();
    /// println!("{}", help);
    /// ```
    /// [`io::Write`]: std::io::Write
    /// [`-h` (short)]: Arg::help()
    /// [`--help` (long)]: Arg::long_help()
    pub fn render_help(&mut self) -> StyledStr {
        self._build_self(false);

        let mut styled = StyledStr::new();
        let usage = Usage::new(self);
        write_help(&mut styled, self, &usage, false);
        styled
    }

    /// Render the long help message (`--help`) to a [`StyledStr`].
    ///
    /// See also [`Command::render_help`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// use std::io;
    /// let mut cmd = Command::new("myprog");
    /// let mut out = io::stdout();
    /// let help = cmd.render_long_help();
    /// println!("{}", help);
    /// ```
    /// [`io::Write`]: std::io::Write
    /// [`-h` (short)]: Arg::help()
    /// [`--help` (long)]: Arg::long_help()
    pub fn render_long_help(&mut self) -> StyledStr {
        self._build_self(false);

        let mut styled = StyledStr::new();
        let usage = Usage::new(self);
        write_help(&mut styled, self, &usage, true);
        styled
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "Replaced with `Command::render_help`")
    )]
    pub fn write_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> {
        self._build_self(false);

        let mut styled = StyledStr::new();
        let usage = Usage::new(self);
        write_help(&mut styled, self, &usage, false);
        ok!(write!(w, "{}", styled));
        w.flush()
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "Replaced with `Command::render_long_help`")
    )]
    pub fn write_long_help<W: io::Write>(&mut self, w: &mut W) -> io::Result<()> {
        self._build_self(false);

        let mut styled = StyledStr::new();
        let usage = Usage::new(self);
        write_help(&mut styled, self, &usage, true);
        ok!(write!(w, "{}", styled));
        w.flush()
    }

    /// Version message rendered as if the user ran `-V`.
    ///
    /// See also [`Command::render_long_version`].
    ///
    /// ### Coloring
    ///
    /// This function does not try to color the message nor it inserts any [ANSI escape codes].
    ///
    /// ### Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// use std::io;
    /// let cmd = Command::new("myprog");
    /// println!("{}", cmd.render_version());
    /// ```
    /// [`io::Write`]: std::io::Write
    /// [`-V` (short)]: Command::version()
    /// [`--version` (long)]: Command::long_version()
    /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
    pub fn render_version(&self) -> String {
        self._render_version(false)
    }

    /// Version message rendered as if the user ran `--version`.
    ///
    /// See also [`Command::render_version`].
    ///
    /// ### Coloring
    ///
    /// This function does not try to color the message nor it inserts any [ANSI escape codes].
    ///
    /// ### Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// use std::io;
    /// let cmd = Command::new("myprog");
    /// println!("{}", cmd.render_long_version());
    /// ```
    /// [`io::Write`]: std::io::Write
    /// [`-V` (short)]: Command::version()
    /// [`--version` (long)]: Command::long_version()
    /// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
    pub fn render_long_version(&self) -> String {
        self._render_version(true)
    }

    /// Usage statement
    ///
    /// ### Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// use std::io;
    /// let mut cmd = Command::new("myprog");
    /// println!("{}", cmd.render_usage());
    /// ```
    pub fn render_usage(&mut self) -> StyledStr {
        self.render_usage_().unwrap_or_default()
    }

    pub(crate) fn render_usage_(&mut self) -> Option<StyledStr> {
        // If there are global arguments, or settings we need to propagate them down to subcommands
        // before parsing incase we run into a subcommand
        self._build_self(false);

        Usage::new(self).create_usage_with_title(&[])
    }
}

/// # Application-wide Settings
///
/// These settings will apply to the top-level command and all subcommands, by default.  Some
/// settings can be overridden in subcommands.
impl Command {
    /// Specifies that the parser should not assume the first argument passed is the binary name.
    ///
    /// This is normally the case when using a "daemon" style mode.  For shells / REPLs, see
    /// [`Command::multicall`][Command::multicall].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, arg};
    /// let m = Command::new("myprog")
    ///     .no_binary_name(true)
    ///     .arg(arg!(<cmd> ... "commands to run"))
    ///     .get_matches_from(vec!["command", "set"]);
    ///
    /// let cmds: Vec<_> = m.get_many::<String>("cmd").unwrap().collect();
    /// assert_eq!(cmds, ["command", "set"]);
    /// ```
    /// [`try_get_matches_from_mut`]: crate::Command::try_get_matches_from_mut()
    #[inline]
    pub fn no_binary_name(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::NoBinaryName)
        } else {
            self.unset_global_setting(AppSettings::NoBinaryName)
        }
    }

    /// Try not to fail on parse errors, like missing option values.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, arg};
    /// let cmd = Command::new("cmd")
    ///   .ignore_errors(true)
    ///   .arg(arg!(-c --config <FILE> "Sets a custom config file"))
    ///   .arg(arg!(-x --stuff <FILE> "Sets a custom stuff file"))
    ///   .arg(arg!(f: -f "Flag"));
    ///
    /// let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]);
    ///
    /// assert!(r.is_ok(), "unexpected error: {:?}", r);
    /// let m = r.unwrap();
    /// assert_eq!(m.get_one::<String>("config").unwrap(), "file");
    /// assert!(*m.get_one::<bool>("f").expect("defaulted"));
    /// assert_eq!(m.get_one::<String>("stuff"), None);
    /// ```
    #[inline]
    pub fn ignore_errors(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::IgnoreErrors)
        } else {
            self.unset_global_setting(AppSettings::IgnoreErrors)
        }
    }

    /// Replace prior occurrences of arguments rather than error
    ///
    /// For any argument that would conflict with itself by default (e.g.
    /// [`ArgAction::Set`][ArgAction::Set], it will now override itself.
    ///
    /// This is the equivalent to saying the `foo` arg using [`Arg::overrides_with("foo")`] for all
    /// defined arguments.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// [`Arg::overrides_with("foo")`]: crate::Arg::overrides_with()
    #[inline]
    pub fn args_override_self(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::AllArgsOverrideSelf)
        } else {
            self.unset_global_setting(AppSettings::AllArgsOverrideSelf)
        }
    }

    /// Disables the automatic delimiting of values after `--` or when [`Command::trailing_var_arg`]
    /// was used.
    ///
    /// **NOTE:** The same thing can be done manually by setting the final positional argument to
    /// [`Arg::value_delimiter(None)`]. Using this setting is safer, because it's easier to locate
    /// when making changes.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .dont_delimit_trailing_values(true)
    ///     .get_matches();
    /// ```
    ///
    /// [`Arg::value_delimiter(None)`]: crate::Arg::value_delimiter()
    #[inline]
    pub fn dont_delimit_trailing_values(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::DontDelimitTrailingValues)
        } else {
            self.unset_global_setting(AppSettings::DontDelimitTrailingValues)
        }
    }

    /// Sets when to color output.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// **NOTE:** Default behaviour is [`ColorChoice::Auto`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, ColorChoice};
    /// Command::new("myprog")
    ///     .color(ColorChoice::Never)
    ///     .get_matches();
    /// ```
    /// [`ColorChoice::Auto`]: crate::ColorChoice::Auto
    #[cfg(feature = "color")]
    #[inline]
    #[must_use]
    pub fn color(self, color: ColorChoice) -> Self {
        let cmd = self
            .unset_global_setting(AppSettings::ColorAuto)
            .unset_global_setting(AppSettings::ColorAlways)
            .unset_global_setting(AppSettings::ColorNever);
        match color {
            ColorChoice::Auto => cmd.global_setting(AppSettings::ColorAuto),
            ColorChoice::Always => cmd.global_setting(AppSettings::ColorAlways),
            ColorChoice::Never => cmd.global_setting(AppSettings::ColorNever),
        }
    }

    /// Sets the terminal width at which to wrap help messages.
    ///
    /// Using `0` will ignore terminal widths and use source formatting.
    ///
    /// Defaults to current terminal width when `wrap_help` feature flag is enabled.  If the flag
    /// is disabled or it cannot be determined, the default is 100.
    ///
    /// **NOTE:** This setting applies globally and *not* on a per-command basis.
    ///
    /// **NOTE:** This requires the [`wrap_help` feature][crate::_features]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .term_width(80)
    /// # ;
    /// ```
    #[inline]
    #[must_use]
    #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))]
    pub fn term_width(mut self, width: usize) -> Self {
        self.term_w = Some(width);
        self
    }

    /// Limit the line length for wrapping help when using the current terminal's width.
    ///
    /// This only applies when [`term_width`][Command::term_width] is unset so that the current
    /// terminal's width will be used.  See [`Command::term_width`] for more details.
    ///
    /// Using `0` will ignore terminal widths and use source formatting (default).
    ///
    /// **NOTE:** This setting applies globally and *not* on a per-command basis.
    ///
    /// **NOTE:** This requires the [`wrap_help` feature][crate::_features]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .max_term_width(100)
    /// # ;
    /// ```
    #[inline]
    #[must_use]
    #[cfg(any(not(feature = "unstable-v5"), feature = "wrap_help"))]
    pub fn max_term_width(mut self, w: usize) -> Self {
        self.max_w = Some(w);
        self
    }

    /// Disables `-V` and `--version` flag.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, error::ErrorKind};
    /// let res = Command::new("myprog")
    ///     .disable_version_flag(true)
    ///     .try_get_matches_from(vec![
    ///         "myprog", "-V"
    ///     ]);
    /// assert!(res.is_err());
    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
    /// ```
    #[inline]
    pub fn disable_version_flag(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::DisableVersionFlag)
        } else {
            self.unset_global_setting(AppSettings::DisableVersionFlag)
        }
    }

    /// Specifies to use the version of the current command for all [`subcommands`].
    ///
    /// Defaults to `false`; subcommands have independent version strings from their parents.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .version("v1.1")
    ///     .propagate_version(true)
    ///     .subcommand(Command::new("test"))
    ///     .get_matches();
    /// // running `$ myprog test --version` will display
    /// // "myprog-test v1.1"
    /// ```
    ///
    /// [`subcommands`]: crate::Command::subcommand()
    #[inline]
    pub fn propagate_version(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::PropagateVersion)
        } else {
            self.unset_global_setting(AppSettings::PropagateVersion)
        }
    }

    /// Places the help string for all arguments and subcommands on the line after them.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .next_line_help(true)
    ///     .get_matches();
    /// ```
    #[inline]
    pub fn next_line_help(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::NextLineHelp)
        } else {
            self.unset_global_setting(AppSettings::NextLineHelp)
        }
    }

    /// Disables `-h` and `--help` flag.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, error::ErrorKind};
    /// let res = Command::new("myprog")
    ///     .disable_help_flag(true)
    ///     .try_get_matches_from(vec![
    ///         "myprog", "-h"
    ///     ]);
    /// assert!(res.is_err());
    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);
    /// ```
    #[inline]
    pub fn disable_help_flag(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::DisableHelpFlag)
        } else {
            self.unset_global_setting(AppSettings::DisableHelpFlag)
        }
    }

    /// Disables the `help` [`subcommand`].
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, error::ErrorKind};
    /// let res = Command::new("myprog")
    ///     .disable_help_subcommand(true)
    ///     // Normally, creating a subcommand causes a `help` subcommand to automatically
    ///     // be generated as well
    ///     .subcommand(Command::new("test"))
    ///     .try_get_matches_from(vec![
    ///         "myprog", "help"
    ///     ]);
    /// assert!(res.is_err());
    /// assert_eq!(res.unwrap_err().kind(), ErrorKind::InvalidSubcommand);
    /// ```
    ///
    /// [`subcommand`]: crate::Command::subcommand()
    #[inline]
    pub fn disable_help_subcommand(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::DisableHelpSubcommand)
        } else {
            self.unset_global_setting(AppSettings::DisableHelpSubcommand)
        }
    }

    /// Disables colorized help messages.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .disable_colored_help(true)
    ///     .get_matches();
    /// ```
    #[inline]
    pub fn disable_colored_help(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::DisableColoredHelp)
        } else {
            self.unset_global_setting(AppSettings::DisableColoredHelp)
        }
    }

    /// Panic if help descriptions are omitted.
    ///
    /// **NOTE:** When deriving [`Parser`][crate::Parser], you could instead check this at
    /// compile-time with `#![deny(missing_docs)]`
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .help_expected(true)
    ///     .arg(
    ///         Arg::new("foo").help("It does foo stuff")
    ///         // As required via `help_expected`, a help message was supplied
    ///      )
    /// #    .get_matches();
    /// ```
    ///
    /// # Panics
    ///
    /// ```rust,no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myapp")
    ///     .help_expected(true)
    ///     .arg(
    ///         Arg::new("foo")
    ///         // Someone forgot to put .about("...") here
    ///         // Since the setting `help_expected` is activated, this will lead to
    ///         // a panic (if you are in debug mode)
    ///     )
    /// #   .get_matches();
    ///```
    #[inline]
    pub fn help_expected(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::HelpExpected)
        } else {
            self.unset_global_setting(AppSettings::HelpExpected)
        }
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "This is now the default")
    )]
    pub fn dont_collapse_args_in_usage(self, _yes: bool) -> Self {
        self
    }

    /// Tells `clap` *not* to print possible values when displaying help information.
    ///
    /// This can be useful if there are many values, or they are explained elsewhere.
    ///
    /// To set this per argument, see
    /// [`Arg::hide_possible_values`][crate::Arg::hide_possible_values].
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    #[inline]
    pub fn hide_possible_values(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::HidePossibleValues)
        } else {
            self.unset_global_setting(AppSettings::HidePossibleValues)
        }
    }

    /// Allow partial matches of long arguments or their [aliases].
    ///
    /// For example, to match an argument named `--test`, one could use `--t`, `--te`, `--tes`, and
    /// `--test`.
    ///
    /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match
    /// `--te` to `--test` there could not also be another argument or alias `--temp` because both
    /// start with `--te`
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// [aliases]: crate::Command::aliases()
    #[inline]
    pub fn infer_long_args(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::InferLongArgs)
        } else {
            self.unset_global_setting(AppSettings::InferLongArgs)
        }
    }

    /// Allow partial matches of [subcommand] names and their [aliases].
    ///
    /// For example, to match a subcommand named `test`, one could use `t`, `te`, `tes`, and
    /// `test`.
    ///
    /// **NOTE:** The match *must not* be ambiguous at all in order to succeed. i.e. to match `te`
    /// to `test` there could not also be a subcommand or alias `temp` because both start with `te`
    ///
    /// **CAUTION:** This setting can interfere with [positional/free arguments], take care when
    /// designing CLIs which allow inferred subcommands and have potential positional/free
    /// arguments whose values could start with the same characters as subcommands. If this is the
    /// case, it's recommended to use settings such as [`Command::args_conflicts_with_subcommands`] in
    /// conjunction with this setting.
    ///
    /// **NOTE:** This choice is propagated to all child subcommands.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let m = Command::new("prog")
    ///     .infer_subcommands(true)
    ///     .subcommand(Command::new("test"))
    ///     .get_matches_from(vec![
    ///         "prog", "te"
    ///     ]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    ///
    /// [subcommand]: crate::Command::subcommand()
    /// [positional/free arguments]: crate::Arg::index()
    /// [aliases]: crate::Command::aliases()
    #[inline]
    pub fn infer_subcommands(self, yes: bool) -> Self {
        if yes {
            self.global_setting(AppSettings::InferSubcommands)
        } else {
            self.unset_global_setting(AppSettings::InferSubcommands)
        }
    }
}

/// # Command-specific Settings
///
/// These apply only to the current command and are not inherited by subcommands.
impl Command {
    /// (Re)Sets the program's name.
    ///
    /// See [`Command::new`] for more details.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let cmd = clap::command!()
    ///     .name("foo");
    ///
    /// // continued logic goes here, such as `cmd.get_matches()` etc.
    /// ```
    #[must_use]
    pub fn name(mut self, name: impl Into<Str>) -> Self {
        self.name = name.into();
        self
    }

    /// Overrides the runtime-determined name of the binary for help and error messages.
    ///
    /// This should only be used when absolutely necessary, such as when the binary name for your
    /// application is misleading, or perhaps *not* how the user should invoke your program.
    ///
    /// **Pro-tip:** When building things such as third party `cargo`
    /// subcommands, this setting **should** be used!
    ///
    /// **NOTE:** This *does not* change or set the name of the binary file on
    /// disk. It only changes what clap thinks the name is for the purposes of
    /// error or help messages.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("My Program")
    ///      .bin_name("my_binary")
    /// # ;
    /// ```
    #[must_use]
    pub fn bin_name(mut self, name: impl IntoResettable<String>) -> Self {
        self.bin_name = name.into_resettable().into_option();
        self
    }

    /// Overrides the runtime-determined display name of the program for help and error messages.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("My Program")
    ///      .display_name("my_program")
    /// # ;
    /// ```
    #[must_use]
    pub fn display_name(mut self, name: impl IntoResettable<String>) -> Self {
        self.display_name = name.into_resettable().into_option();
        self
    }

    /// Sets the author(s) for the help message.
    ///
    /// **Pro-tip:** Use `clap`s convenience macro [`crate_authors!`] to
    /// automatically set your application's author(s) to the same thing as your
    /// crate at compile time.
    ///
    /// **NOTE:** A custom [`help_template`][Command::help_template] is needed for author to show
    /// up.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///      .author("Me, me@mymain.com")
    /// # ;
    /// ```
    #[must_use]
    pub fn author(mut self, author: impl IntoResettable<Str>) -> Self {
        self.author = author.into_resettable().into_option();
        self
    }

    /// Sets the program's description for the short help (`-h`).
    ///
    /// If [`Command::long_about`] is not specified, this message will be displayed for `--help`.
    ///
    /// **NOTE:** Only `Command::about` (short format) is used in completion
    /// script generation in order to be concise.
    ///
    /// See also [`crate_description!`](crate::crate_description!).
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .about("Does really amazing things for great people")
    /// # ;
    /// ```
    #[must_use]
    pub fn about(mut self, about: impl IntoResettable<StyledStr>) -> Self {
        self.about = about.into_resettable().into_option();
        self
    }

    /// Sets the program's description for the long help (`--help`).
    ///
    /// If [`Command::about`] is not specified, this message will be displayed for `-h`.
    ///
    /// **NOTE:** Only [`Command::about`] (short format) is used in completion
    /// script generation in order to be concise.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .long_about(
    /// "Does really amazing things to great people. Now let's talk a little
    ///  more in depth about how this subcommand really works. It may take about
    ///  a few lines of text, but that's ok!")
    /// # ;
    /// ```
    /// [`Command::about`]: Command::about()
    #[must_use]
    pub fn long_about(mut self, long_about: impl IntoResettable<StyledStr>) -> Self {
        self.long_about = long_about.into_resettable().into_option();
        self
    }

    /// Free-form help text for after auto-generated short help (`-h`).
    ///
    /// This is often used to describe how to use the arguments, caveats to be noted, or license
    /// and contact information.
    ///
    /// If [`Command::after_long_help`] is not specified, this message will be displayed for `--help`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .after_help("Does really amazing things for great people... but be careful with -R!")
    /// # ;
    /// ```
    ///
    #[must_use]
    pub fn after_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
        self.after_help = help.into_resettable().into_option();
        self
    }

    /// Free-form help text for after auto-generated long help (`--help`).
    ///
    /// This is often used to describe how to use the arguments, caveats to be noted, or license
    /// and contact information.
    ///
    /// If [`Command::after_help`] is not specified, this message will be displayed for `-h`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .after_long_help("Does really amazing things to great people... but be careful with -R, \
    ///                      like, for real, be careful with this!")
    /// # ;
    /// ```
    #[must_use]
    pub fn after_long_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
        self.after_long_help = help.into_resettable().into_option();
        self
    }

    /// Free-form help text for before auto-generated short help (`-h`).
    ///
    /// This is often used for header, copyright, or license information.
    ///
    /// If [`Command::before_long_help`] is not specified, this message will be displayed for `--help`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .before_help("Some info I'd like to appear before the help info")
    /// # ;
    /// ```
    #[must_use]
    pub fn before_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
        self.before_help = help.into_resettable().into_option();
        self
    }

    /// Free-form help text for before auto-generated long help (`--help`).
    ///
    /// This is often used for header, copyright, or license information.
    ///
    /// If [`Command::before_help`] is not specified, this message will be displayed for `-h`.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .before_long_help("Some verbose and long info I'd like to appear before the help info")
    /// # ;
    /// ```
    #[must_use]
    pub fn before_long_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
        self.before_long_help = help.into_resettable().into_option();
        self
    }

    /// Sets the version for the short version (`-V`) and help messages.
    ///
    /// If [`Command::long_version`] is not specified, this message will be displayed for `--version`.
    ///
    /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
    /// automatically set your application's version to the same thing as your
    /// crate at compile time.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .version("v0.1.24")
    /// # ;
    /// ```
    #[must_use]
    pub fn version(mut self, ver: impl IntoResettable<Str>) -> Self {
        self.version = ver.into_resettable().into_option();
        self
    }

    /// Sets the version for the long version (`--version`) and help messages.
    ///
    /// If [`Command::version`] is not specified, this message will be displayed for `-V`.
    ///
    /// **Pro-tip:** Use `clap`s convenience macro [`crate_version!`] to
    /// automatically set your application's version to the same thing as your
    /// crate at compile time.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .long_version(
    /// "v0.1.24
    ///  commit: abcdef89726d
    ///  revision: 123
    ///  release: 2
    ///  binary: myprog")
    /// # ;
    /// ```
    #[must_use]
    pub fn long_version(mut self, ver: impl IntoResettable<Str>) -> Self {
        self.long_version = ver.into_resettable().into_option();
        self
    }

    /// Overrides the `clap` generated usage string for help and error messages.
    ///
    /// **NOTE:** Using this setting disables `clap`s "context-aware" usage
    /// strings. After this setting is set, this will be *the only* usage string
    /// displayed to the user!
    ///
    /// **NOTE:** Multiple usage lines may be present in the usage argument, but
    /// some rules need to be followed to ensure the usage lines are formatted
    /// correctly by the default help formatter:
    ///
    /// - Do not indent the first usage line.
    /// - Indent all subsequent usage lines with seven spaces.
    /// - The last line must not end with a newline.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .override_usage("myapp [-clDas] <some_file>")
    /// # ;
    /// ```
    ///
    /// Or for multiple usage lines:
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .override_usage(
    ///         "myapp -X [-a] [-b] <file>\n       \
    ///          myapp -Y [-c] <file1> <file2>\n       \
    ///          myapp -Z [-d|-e]"
    ///     )
    /// # ;
    /// ```
    ///
    /// [`ArgMatches::usage`]: ArgMatches::usage()
    #[must_use]
    pub fn override_usage(mut self, usage: impl IntoResettable<StyledStr>) -> Self {
        self.usage_str = usage.into_resettable().into_option();
        self
    }

    /// Overrides the `clap` generated help message (both `-h` and `--help`).
    ///
    /// This should only be used when the auto-generated message does not suffice.
    ///
    /// **NOTE:** This **only** replaces the help message for the current
    /// command, meaning if you are using subcommands, those help messages will
    /// still be auto-generated unless you specify a [`Command::override_help`] for
    /// them as well.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myapp")
    ///     .override_help("myapp v1.0\n\
    ///            Does awesome things\n\
    ///            (C) me@mail.com\n\n\
    ///
    ///            Usage: myapp <opts> <command>\n\n\
    ///
    ///            Options:\n\
    ///            -h, --help       Display this message\n\
    ///            -V, --version    Display version info\n\
    ///            -s <stuff>       Do something with stuff\n\
    ///            -v               Be verbose\n\n\
    ///
    ///            Commands:\n\
    ///            help             Print this message\n\
    ///            work             Do some work")
    /// # ;
    /// ```
    #[must_use]
    pub fn override_help(mut self, help: impl IntoResettable<StyledStr>) -> Self {
        self.help_str = help.into_resettable().into_option();
        self
    }

    /// Sets the help template to be used, overriding the default format.
    ///
    /// **NOTE:** The template system is by design very simple. Therefore, the
    /// tags have to be written in the lowercase and without spacing.
    ///
    /// Tags are given inside curly brackets.
    ///
    /// Valid tags are:
    ///
    ///   * `{name}`                - Display name for the (sub-)command.
    ///   * `{bin}`                 - Binary name.
    ///   * `{version}`             - Version number.
    ///   * `{author}`              - Author information.
    ///   * `{author-with-newline}` - Author followed by `\n`.
    ///   * `{author-section}`      - Author preceded and followed by `\n`.
    ///   * `{about}`               - General description (from [`Command::about`] or
    ///                               [`Command::long_about`]).
    ///   * `{about-with-newline}`  - About followed by `\n`.
    ///   * `{about-section}`       - About preceded and followed by '\n'.
    ///   * `{usage-heading}`       - Automatically generated usage heading.
    ///   * `{usage}`               - Automatically generated or given usage string.
    ///   * `{all-args}`            - Help for all arguments (options, flags, positional
    ///                               arguments, and subcommands) including titles.
    ///   * `{options}`             - Help for options.
    ///   * `{positionals}`         - Help for positional arguments.
    ///   * `{subcommands}`         - Help for subcommands.
    ///   * `{tag}`                 - Standard tab sized used within clap
    ///   * `{after-help}`          - Help from [`Command::after_help`] or [`Command::after_long_help`].
    ///   * `{before-help}`         - Help from [`Command::before_help`] or [`Command::before_long_help`].
    ///
    /// # Examples
    ///
    /// For a very brief help:
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .version("1.0")
    ///     .help_template("{bin} ({version}) - {usage}")
    /// # ;
    /// ```
    ///
    /// For showing more application context:
    ///
    /// ```no_run
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .version("1.0")
    ///     .help_template("\
    /// {before-help}{name} {version}
    /// {author-with-newline}{about-with-newline}
    /// {usage-heading} {usage}
    ///
    /// {all-args}{after-help}
    /// ")
    /// # ;
    /// ```
    /// [`Command::about`]: Command::about()
    /// [`Command::long_about`]: Command::long_about()
    /// [`Command::after_help`]: Command::after_help()
    /// [`Command::after_long_help`]: Command::after_long_help()
    /// [`Command::before_help`]: Command::before_help()
    /// [`Command::before_long_help`]: Command::before_long_help()
    #[must_use]
    #[cfg(feature = "help")]
    pub fn help_template(mut self, s: impl IntoResettable<StyledStr>) -> Self {
        self.template = s.into_resettable().into_option();
        self
    }

    #[inline]
    #[must_use]
    pub(crate) fn setting<F>(mut self, setting: F) -> Self
    where
        F: Into<AppFlags>,
    {
        self.settings.insert(setting.into());
        self
    }

    #[inline]
    #[must_use]
    pub(crate) fn unset_setting<F>(mut self, setting: F) -> Self
    where
        F: Into<AppFlags>,
    {
        self.settings.remove(setting.into());
        self
    }

    #[inline]
    #[must_use]
    pub(crate) fn global_setting(mut self, setting: AppSettings) -> Self {
        self.settings.set(setting);
        self.g_settings.set(setting);
        self
    }

    #[inline]
    #[must_use]
    pub(crate) fn unset_global_setting(mut self, setting: AppSettings) -> Self {
        self.settings.unset(setting);
        self.g_settings.unset(setting);
        self
    }

    /// Set the default section heading for future args.
    ///
    /// This will be used for any arg that hasn't had [`Arg::help_heading`] called.
    ///
    /// This is useful if the default `Options` or `Arguments` headings are
    /// not specific enough for one's use case.
    ///
    /// For subcommands, see [`Command::subcommand_help_heading`]
    ///
    /// [`Command::arg`]: Command::arg()
    /// [`Arg::help_heading`]: crate::Arg::help_heading()
    #[inline]
    #[must_use]
    pub fn next_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self {
        self.current_help_heading = heading.into_resettable().into_option();
        self
    }

    /// Change the starting value for assigning future display orders for ags.
    ///
    /// This will be used for any arg that hasn't had [`Arg::display_order`] called.
    #[inline]
    #[must_use]
    pub fn next_display_order(mut self, disp_ord: impl IntoResettable<usize>) -> Self {
        self.current_disp_ord = disp_ord.into_resettable().into_option();
        self
    }

    /// Replaces an argument or subcommand used on the CLI at runtime with other arguments or subcommands.
    ///
    /// **Note:** This is gated behind [`unstable-replace`](https://github.com/clap-rs/clap/issues/2836)
    ///
    /// When this method is used, `name` is removed from the CLI, and `target`
    /// is inserted in its place. Parsing continues as if the user typed
    /// `target` instead of `name`.
    ///
    /// This can be used to create "shortcuts" for subcommands, or if a
    /// particular argument has the semantic meaning of several other specific
    /// arguments and values.
    ///
    /// # Examples
    ///
    /// We'll start with the "subcommand short" example. In this example, let's
    /// assume we have a program with a subcommand `module` which can be invoked
    /// via `cmd module`. Now let's also assume `module` also has a subcommand
    /// called `install` which can be invoked `cmd module install`. If for some
    /// reason users needed to be able to reach `cmd module install` via the
    /// short-hand `cmd install`, we'd have several options.
    ///
    /// We *could* create another sibling subcommand to `module` called
    /// `install`, but then we would need to manage another subcommand and manually
    /// dispatch to `cmd module install` handling code. This is error prone and
    /// tedious.
    ///
    /// We could instead use [`Command::replace`] so that, when the user types `cmd
    /// install`, `clap` will replace `install` with `module install` which will
    /// end up getting parsed as if the user typed the entire incantation.
    ///
    /// ```rust
    /// # use clap::Command;
    /// let m = Command::new("cmd")
    ///     .subcommand(Command::new("module")
    ///         .subcommand(Command::new("install")))
    ///     .replace("install", &["module", "install"])
    ///     .get_matches_from(vec!["cmd", "install"]);
    ///
    /// assert!(m.subcommand_matches("module").is_some());
    /// assert!(m.subcommand_matches("module").unwrap().subcommand_matches("install").is_some());
    /// ```
    ///
    /// Now let's show an argument example!
    ///
    /// Let's assume we have an application with two flags `--save-context` and
    /// `--save-runtime`. But often users end up needing to do *both* at the
    /// same time. We can add a third flag `--save-all` which semantically means
    /// the same thing as `cmd --save-context --save-runtime`. To implement that,
    /// we have several options.
    ///
    /// We could create this third argument and manually check if that argument
    /// and in our own consumer code handle the fact that both `--save-context`
    /// and `--save-runtime` *should* have been used. But again this is error
    /// prone and tedious. If we had code relying on checking `--save-context`
    /// and we forgot to update that code to *also* check `--save-all` it'd mean
    /// an error!
    ///
    /// Luckily we can use [`Command::replace`] so that when the user types
    /// `--save-all`, `clap` will replace that argument with `--save-context
    /// --save-runtime`, and parsing will continue like normal. Now all our code
    /// that was originally checking for things like `--save-context` doesn't
    /// need to change!
    ///
    /// ```rust
    /// # use clap::{Command, Arg, ArgAction};
    /// let m = Command::new("cmd")
    ///     .arg(Arg::new("save-context")
    ///         .long("save-context")
    ///         .action(ArgAction::SetTrue))
    ///     .arg(Arg::new("save-runtime")
    ///         .long("save-runtime")
    ///         .action(ArgAction::SetTrue))
    ///     .replace("--save-all", &["--save-context", "--save-runtime"])
    ///     .get_matches_from(vec!["cmd", "--save-all"]);
    ///
    /// assert!(*m.get_one::<bool>("save-context").expect("defaulted by clap"));
    /// assert!(*m.get_one::<bool>("save-runtime").expect("defaulted by clap"));
    /// ```
    ///
    /// This can also be used with options, for example if our application with
    /// `--save-*` above also had a `--format=TYPE` option. Let's say it
    /// accepted `txt` or `json` values. However, when `--save-all` is used,
    /// only `--format=json` is allowed, or valid. We could change the example
    /// above to enforce this:
    ///
    /// ```rust
    /// # use clap::{Command, Arg, ArgAction};
    /// let m = Command::new("cmd")
    ///     .arg(Arg::new("save-context")
    ///         .long("save-context")
    ///         .action(ArgAction::SetTrue))
    ///     .arg(Arg::new("save-runtime")
    ///         .long("save-runtime")
    ///         .action(ArgAction::SetTrue))
    ///     .arg(Arg::new("format")
    ///         .long("format")
    ///         .action(ArgAction::Set)
    ///         .value_parser(["txt", "json"]))
    ///     .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"])
    ///     .get_matches_from(vec!["cmd", "--save-all"]);
    ///
    /// assert!(*m.get_one::<bool>("save-context").expect("defaulted by clap"));
    /// assert!(*m.get_one::<bool>("save-runtime").expect("defaulted by clap"));
    /// assert_eq!(m.get_one::<String>("format").unwrap(), "json");
    /// ```
    ///
    /// [`Command::replace`]: Command::replace()
    #[inline]
    #[cfg(feature = "unstable-replace")]
    #[must_use]
    pub fn replace(
        mut self,
        name: impl Into<Str>,
        target: impl IntoIterator<Item = impl Into<Str>>,
    ) -> Self {
        self.replacers
            .insert(name.into(), target.into_iter().map(Into::into).collect());
        self
    }

    /// Exit gracefully if no arguments are present (e.g. `$ myprog`).
    ///
    /// **NOTE:** [`subcommands`] count as arguments
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command};
    /// Command::new("myprog")
    ///     .arg_required_else_help(true);
    /// ```
    ///
    /// [`subcommands`]: crate::Command::subcommand()
    /// [`Arg::default_value`]: crate::Arg::default_value()
    #[inline]
    pub fn arg_required_else_help(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::ArgRequiredElseHelp)
        } else {
            self.unset_setting(AppSettings::ArgRequiredElseHelp)
        }
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_hyphen_values`")
    )]
    pub fn allow_hyphen_values(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::AllowHyphenValues)
        } else {
            self.unset_setting(AppSettings::AllowHyphenValues)
        }
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "Replaced with `Arg::allow_negative_numbers`")
    )]
    pub fn allow_negative_numbers(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::AllowNegativeNumbers)
        } else {
            self.unset_setting(AppSettings::AllowNegativeNumbers)
        }
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "Replaced with `Arg::trailing_var_arg`")
    )]
    pub fn trailing_var_arg(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::TrailingVarArg)
        } else {
            self.unset_setting(AppSettings::TrailingVarArg)
        }
    }

    /// Allows one to implement two styles of CLIs where positionals can be used out of order.
    ///
    /// The first example is a CLI where the second to last positional argument is optional, but
    /// the final positional argument is required. Such as `$ prog [optional] <required>` where one
    /// of the two following usages is allowed:
    ///
    /// * `$ prog [optional] <required>`
    /// * `$ prog <required>`
    ///
    /// This would otherwise not be allowed. This is useful when `[optional]` has a default value.
    ///
    /// **Note:** when using this style of "missing positionals" the final positional *must* be
    /// [required] if `--` will not be used to skip to the final positional argument.
    ///
    /// **Note:** This style also only allows a single positional argument to be "skipped" without
    /// the use of `--`. To skip more than one, see the second example.
    ///
    /// The second example is when one wants to skip multiple optional positional arguments, and use
    /// of the `--` operator is OK (but not required if all arguments will be specified anyways).
    ///
    /// For example, imagine a CLI which has three positional arguments `[foo] [bar] [baz]...` where
    /// `baz` accepts multiple values (similar to man `ARGS...` style training arguments).
    ///
    /// With this setting the following invocations are posisble:
    ///
    /// * `$ prog foo bar baz1 baz2 baz3`
    /// * `$ prog foo -- baz1 baz2 baz3`
    /// * `$ prog -- baz1 baz2 baz3`
    ///
    /// # Examples
    ///
    /// Style number one from above:
    ///
    /// ```rust
    /// # use clap::{Command, Arg};
    /// // Assume there is an external subcommand named "subcmd"
    /// let m = Command::new("myprog")
    ///     .allow_missing_positional(true)
    ///     .arg(Arg::new("arg1"))
    ///     .arg(Arg::new("arg2")
    ///         .required(true))
    ///     .get_matches_from(vec![
    ///         "prog", "other"
    ///     ]);
    ///
    /// assert_eq!(m.get_one::<String>("arg1"), None);
    /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other");
    /// ```
    ///
    /// Now the same example, but using a default value for the first optional positional argument
    ///
    /// ```rust
    /// # use clap::{Command, Arg};
    /// // Assume there is an external subcommand named "subcmd"
    /// let m = Command::new("myprog")
    ///     .allow_missing_positional(true)
    ///     .arg(Arg::new("arg1")
    ///         .default_value("something"))
    ///     .arg(Arg::new("arg2")
    ///         .required(true))
    ///     .get_matches_from(vec![
    ///         "prog", "other"
    ///     ]);
    ///
    /// assert_eq!(m.get_one::<String>("arg1").unwrap(), "something");
    /// assert_eq!(m.get_one::<String>("arg2").unwrap(), "other");
    /// ```
    ///
    /// Style number two from above:
    ///
    /// ```rust
    /// # use clap::{Command, Arg, ArgAction};
    /// // Assume there is an external subcommand named "subcmd"
    /// let m = Command::new("myprog")
    ///     .allow_missing_positional(true)
    ///     .arg(Arg::new("foo"))
    ///     .arg(Arg::new("bar"))
    ///     .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..))
    ///     .get_matches_from(vec![
    ///         "prog", "foo", "bar", "baz1", "baz2", "baz3"
    ///     ]);
    ///
    /// assert_eq!(m.get_one::<String>("foo").unwrap(), "foo");
    /// assert_eq!(m.get_one::<String>("bar").unwrap(), "bar");
    /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
    /// ```
    ///
    /// Now nofice if we don't specify `foo` or `baz` but use the `--` operator.
    ///
    /// ```rust
    /// # use clap::{Command, Arg, ArgAction};
    /// // Assume there is an external subcommand named "subcmd"
    /// let m = Command::new("myprog")
    ///     .allow_missing_positional(true)
    ///     .arg(Arg::new("foo"))
    ///     .arg(Arg::new("bar"))
    ///     .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..))
    ///     .get_matches_from(vec![
    ///         "prog", "--", "baz1", "baz2", "baz3"
    ///     ]);
    ///
    /// assert_eq!(m.get_one::<String>("foo"), None);
    /// assert_eq!(m.get_one::<String>("bar"), None);
    /// assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);
    /// ```
    ///
    /// [required]: crate::Arg::required()
    #[inline]
    pub fn allow_missing_positional(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::AllowMissingPositional)
        } else {
            self.unset_setting(AppSettings::AllowMissingPositional)
        }
    }
}

/// # Subcommand-specific Settings
impl Command {
    /// Sets the short version of the subcommand flag without the preceding `-`.
    ///
    /// Allows the subcommand to be used as if it were an [`Arg::short`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use clap::{Command, Arg, ArgAction};
    /// let matches = Command::new("pacman")
    ///     .subcommand(
    ///         Command::new("sync").short_flag('S').arg(
    ///             Arg::new("search")
    ///                 .short('s')
    ///                 .long("search")
    ///                 .action(ArgAction::SetTrue)
    ///                 .help("search remote repositories for matching strings"),
    ///         ),
    ///     )
    ///     .get_matches_from(vec!["pacman", "-Ss"]);
    ///
    /// assert_eq!(matches.subcommand_name().unwrap(), "sync");
    /// let sync_matches = matches.subcommand_matches("sync").unwrap();
    /// assert!(*sync_matches.get_one::<bool>("search").expect("defaulted by clap"));
    /// ```
    /// [`Arg::short`]: Arg::short()
    #[must_use]
    pub fn short_flag(mut self, short: impl IntoResettable<char>) -> Self {
        self.short_flag = short.into_resettable().into_option();
        self
    }

    /// Sets the long version of the subcommand flag without the preceding `--`.
    ///
    /// Allows the subcommand to be used as if it were an [`Arg::long`].
    ///
    /// **NOTE:** Any leading `-` characters will be stripped.
    ///
    /// # Examples
    ///
    /// To set `long_flag` use a word containing valid UTF-8 codepoints. If you supply a double leading
    /// `--` such as `--sync` they will be stripped. Hyphens in the middle of the word; however,
    /// will *not* be stripped (i.e. `sync-file` is allowed).
    ///
    /// ```
    /// # use clap::{Command, Arg, ArgAction};
    /// let matches = Command::new("pacman")
    ///     .subcommand(
    ///         Command::new("sync").long_flag("sync").arg(
    ///             Arg::new("search")
    ///                 .short('s')
    ///                 .long("search")
    ///                 .action(ArgAction::SetTrue)
    ///                 .help("search remote repositories for matching strings"),
    ///         ),
    ///     )
    ///     .get_matches_from(vec!["pacman", "--sync", "--search"]);
    ///
    /// assert_eq!(matches.subcommand_name().unwrap(), "sync");
    /// let sync_matches = matches.subcommand_matches("sync").unwrap();
    /// assert!(*sync_matches.get_one::<bool>("search").expect("defaulted by clap"));
    /// ```
    ///
    /// [`Arg::long`]: Arg::long()
    #[must_use]
    pub fn long_flag(mut self, long: impl Into<Str>) -> Self {
        self.long_flag = Some(long.into());
        self
    }

    /// Sets a hidden alias to this subcommand.
    ///
    /// This allows the subcommand to be accessed via *either* the original name, or this given
    /// alias. This is more efficient and easier than creating multiple hidden subcommands as one
    /// only needs to check for the existence of this command, and not all aliased variants.
    ///
    /// **NOTE:** Aliases defined with this method are *hidden* from the help
    /// message. If you're looking for aliases that will be displayed in the help
    /// message, see [`Command::visible_alias`].
    ///
    /// **NOTE:** When using aliases and checking for the existence of a
    /// particular subcommand within an [`ArgMatches`] struct, one only needs to
    /// search for the original name and not all aliases.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///     .subcommand(Command::new("test")
    ///         .alias("do-stuff"))
    ///     .get_matches_from(vec!["myprog", "do-stuff"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::visible_alias`]: Command::visible_alias()
    #[must_use]
    pub fn alias(mut self, name: impl IntoResettable<Str>) -> Self {
        if let Some(name) = name.into_resettable().into_option() {
            self.aliases.push((name, false));
        } else {
            self.aliases.clear();
        }
        self
    }

    /// Add an alias, which functions as  "hidden" short flag subcommand
    ///
    /// This will automatically dispatch as if this subcommand was used. This is more efficient,
    /// and easier than creating multiple hidden subcommands as one only needs to check for the
    /// existence of this command, and not all variants.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///             .subcommand(Command::new("test").short_flag('t')
    ///                 .short_flag_alias('d'))
    ///             .get_matches_from(vec!["myprog", "-d"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    #[must_use]
    pub fn short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self {
        if let Some(name) = name.into_resettable().into_option() {
            debug_assert!(name != '-', "short alias name cannot be `-`");
            self.short_flag_aliases.push((name, false));
        } else {
            self.short_flag_aliases.clear();
        }
        self
    }

    /// Add an alias, which functions as a "hidden" long flag subcommand.
    ///
    /// This will automatically dispatch as if this subcommand was used. This is more efficient,
    /// and easier than creating multiple hidden subcommands as one only needs to check for the
    /// existence of this command, and not all variants.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///             .subcommand(Command::new("test").long_flag("test")
    ///                 .long_flag_alias("testing"))
    ///             .get_matches_from(vec!["myprog", "--testing"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    #[must_use]
    pub fn long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self {
        if let Some(name) = name.into_resettable().into_option() {
            self.long_flag_aliases.push((name, false));
        } else {
            self.long_flag_aliases.clear();
        }
        self
    }

    /// Sets multiple hidden aliases to this subcommand.
    ///
    /// This allows the subcommand to be accessed via *either* the original name or any of the
    /// given aliases. This is more efficient, and easier than creating multiple hidden subcommands
    /// as one only needs to check for the existence of this command and not all aliased variants.
    ///
    /// **NOTE:** Aliases defined with this method are *hidden* from the help
    /// message. If looking for aliases that will be displayed in the help
    /// message, see [`Command::visible_aliases`].
    ///
    /// **NOTE:** When using aliases and checking for the existence of a
    /// particular subcommand within an [`ArgMatches`] struct, one only needs to
    /// search for the original name and not all aliases.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg};
    /// let m = Command::new("myprog")
    ///     .subcommand(Command::new("test")
    ///         .aliases(["do-stuff", "do-tests", "tests"]))
    ///         .arg(Arg::new("input")
    ///             .help("the file to add")
    ///             .required(false))
    ///     .get_matches_from(vec!["myprog", "do-tests"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::visible_aliases`]: Command::visible_aliases()
    #[must_use]
    pub fn aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
        self.aliases
            .extend(names.into_iter().map(|n| (n.into(), false)));
        self
    }

    /// Add aliases, which function as "hidden" short flag subcommands.
    ///
    /// These will automatically dispatch as if this subcommand was used. This is more efficient,
    /// and easier than creating multiple hidden subcommands as one only needs to check for the
    /// existence of this command, and not all variants.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///     .subcommand(Command::new("test").short_flag('t')
    ///         .short_flag_aliases(['a', 'b', 'c']))
    ///         .arg(Arg::new("input")
    ///             .help("the file to add")
    ///             .required(false))
    ///     .get_matches_from(vec!["myprog", "-a"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    #[must_use]
    pub fn short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self {
        for s in names {
            debug_assert!(s != '-', "short alias name cannot be `-`");
            self.short_flag_aliases.push((s, false));
        }
        self
    }

    /// Add aliases, which function as "hidden" long flag subcommands.
    ///
    /// These will automatically dispatch as if this subcommand was used. This is more efficient,
    /// and easier than creating multiple hidden subcommands as one only needs to check for the
    /// existence of this command, and not all variants.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///             .subcommand(Command::new("test").long_flag("test")
    ///                 .long_flag_aliases(["testing", "testall", "test_all"]))
    ///                 .arg(Arg::new("input")
    ///                             .help("the file to add")
    ///                             .required(false))
    ///             .get_matches_from(vec!["myprog", "--testing"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    #[must_use]
    pub fn long_flag_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
        for s in names {
            self = self.long_flag_alias(s)
        }
        self
    }

    /// Sets a visible alias to this subcommand.
    ///
    /// This allows the subcommand to be accessed via *either* the
    /// original name or the given alias. This is more efficient and easier
    /// than creating hidden subcommands as one only needs to check for
    /// the existence of this command and not all aliased variants.
    ///
    /// **NOTE:** The alias defined with this method is *visible* from the help
    /// message and displayed as if it were just another regular subcommand. If
    /// looking for an alias that will not be displayed in the help message, see
    /// [`Command::alias`].
    ///
    /// **NOTE:** When using aliases and checking for the existence of a
    /// particular subcommand within an [`ArgMatches`] struct, one only needs to
    /// search for the original name and not all aliases.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let m = Command::new("myprog")
    ///     .subcommand(Command::new("test")
    ///         .visible_alias("do-stuff"))
    ///     .get_matches_from(vec!["myprog", "do-stuff"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::alias`]: Command::alias()
    #[must_use]
    pub fn visible_alias(mut self, name: impl IntoResettable<Str>) -> Self {
        if let Some(name) = name.into_resettable().into_option() {
            self.aliases.push((name, true));
        } else {
            self.aliases.clear();
        }
        self
    }

    /// Add an alias, which functions as  "visible" short flag subcommand
    ///
    /// This will automatically dispatch as if this subcommand was used. This is more efficient,
    /// and easier than creating multiple hidden subcommands as one only needs to check for the
    /// existence of this command, and not all variants.
    ///
    /// See also [`Command::short_flag_alias`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///             .subcommand(Command::new("test").short_flag('t')
    ///                 .visible_short_flag_alias('d'))
    ///             .get_matches_from(vec!["myprog", "-d"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::short_flag_alias`]: Command::short_flag_alias()
    #[must_use]
    pub fn visible_short_flag_alias(mut self, name: impl IntoResettable<char>) -> Self {
        if let Some(name) = name.into_resettable().into_option() {
            debug_assert!(name != '-', "short alias name cannot be `-`");
            self.short_flag_aliases.push((name, true));
        } else {
            self.short_flag_aliases.clear();
        }
        self
    }

    /// Add an alias, which functions as a "visible" long flag subcommand.
    ///
    /// This will automatically dispatch as if this subcommand was used. This is more efficient,
    /// and easier than creating multiple hidden subcommands as one only needs to check for the
    /// existence of this command, and not all variants.
    ///
    /// See also [`Command::long_flag_alias`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///             .subcommand(Command::new("test").long_flag("test")
    ///                 .visible_long_flag_alias("testing"))
    ///             .get_matches_from(vec!["myprog", "--testing"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::long_flag_alias`]: Command::long_flag_alias()
    #[must_use]
    pub fn visible_long_flag_alias(mut self, name: impl IntoResettable<Str>) -> Self {
        if let Some(name) = name.into_resettable().into_option() {
            self.long_flag_aliases.push((name, true));
        } else {
            self.long_flag_aliases.clear();
        }
        self
    }

    /// Sets multiple visible aliases to this subcommand.
    ///
    /// This allows the subcommand to be accessed via *either* the
    /// original name or any of the given aliases. This is more efficient and easier
    /// than creating multiple hidden subcommands as one only needs to check for
    /// the existence of this command and not all aliased variants.
    ///
    /// **NOTE:** The alias defined with this method is *visible* from the help
    /// message and displayed as if it were just another regular subcommand. If
    /// looking for an alias that will not be displayed in the help message, see
    /// [`Command::alias`].
    ///
    /// **NOTE:** When using aliases, and checking for the existence of a
    /// particular subcommand within an [`ArgMatches`] struct, one only needs to
    /// search for the original name and not all aliases.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///     .subcommand(Command::new("test")
    ///         .visible_aliases(["do-stuff", "tests"]))
    ///     .get_matches_from(vec!["myprog", "do-stuff"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::alias`]: Command::alias()
    #[must_use]
    pub fn visible_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
        self.aliases
            .extend(names.into_iter().map(|n| (n.into(), true)));
        self
    }

    /// Add aliases, which function as *visible* short flag subcommands.
    ///
    /// See [`Command::short_flag_aliases`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///             .subcommand(Command::new("test").short_flag('b')
    ///                 .visible_short_flag_aliases(['t']))
    ///             .get_matches_from(vec!["myprog", "-t"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::short_flag_aliases`]: Command::short_flag_aliases()
    #[must_use]
    pub fn visible_short_flag_aliases(mut self, names: impl IntoIterator<Item = char>) -> Self {
        for s in names {
            debug_assert!(s != '-', "short alias name cannot be `-`");
            self.short_flag_aliases.push((s, true));
        }
        self
    }

    /// Add aliases, which function as *visible* long flag subcommands.
    ///
    /// See [`Command::long_flag_aliases`].
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg, };
    /// let m = Command::new("myprog")
    ///             .subcommand(Command::new("test").long_flag("test")
    ///                 .visible_long_flag_aliases(["testing", "testall", "test_all"]))
    ///             .get_matches_from(vec!["myprog", "--testing"]);
    /// assert_eq!(m.subcommand_name(), Some("test"));
    /// ```
    /// [`Command::long_flag_aliases`]: Command::long_flag_aliases()
    #[must_use]
    pub fn visible_long_flag_aliases(
        mut self,
        names: impl IntoIterator<Item = impl Into<Str>>,
    ) -> Self {
        for s in names {
            self = self.visible_long_flag_alias(s);
        }
        self
    }

    /// Set the placement of this subcommand within the help.
    ///
    /// Subcommands with a lower value will be displayed first in the help message.  Subcommands
    /// with duplicate display orders will be displayed in alphabetical order.
    ///
    /// This is helpful when one would like to emphasize frequently used subcommands, or prioritize
    /// those towards the top of the list.
    ///
    /// **NOTE:** The default is 999 for all subcommands.
    ///
    /// # Examples
    ///
    #[cfg_attr(not(feature = "help"), doc = " ```ignore")]
    #[cfg_attr(feature = "help", doc = " ```")]
    /// # use clap::{Command, };
    /// let m = Command::new("cust-ord")
    ///     .subcommand(Command::new("alpha") // typically subcommands are grouped
    ///                                                // alphabetically by name. Subcommands
    ///                                                // without a display_order have a value of
    ///                                                // 999 and are displayed alphabetically with
    ///                                                // all other 999 subcommands
    ///         .about("Some help and text"))
    ///     .subcommand(Command::new("beta")
    ///         .display_order(1)   // In order to force this subcommand to appear *first*
    ///                             // all we have to do is give it a value lower than 999.
    ///                             // Any other subcommands with a value of 1 will be displayed
    ///                             // alphabetically with this one...then 2 values, then 3, etc.
    ///         .about("I should be first!"))
    ///     .get_matches_from(vec![
    ///         "cust-ord", "--help"
    ///     ]);
    /// ```
    ///
    /// The above example displays the following help message
    ///
    /// ```text
    /// cust-ord
    ///
    /// Usage: cust-ord [OPTIONS]
    ///
    /// Commands:
    ///     beta    I should be first!
    ///     alpha   Some help and text
    ///
    /// Options:
    ///     -h, --help       Print help information
    ///     -V, --version    Print version information
    /// ```
    #[inline]
    #[must_use]
    pub fn display_order(mut self, ord: impl IntoResettable<usize>) -> Self {
        self.disp_ord = ord.into_resettable().into_option();
        self
    }

    /// Specifies that this [`subcommand`] should be hidden from help messages
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .subcommand(
    ///         Command::new("test").hide(true)
    ///     )
    /// # ;
    /// ```
    ///
    /// [`subcommand`]: crate::Command::subcommand()
    #[inline]
    pub fn hide(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::Hidden)
        } else {
            self.unset_setting(AppSettings::Hidden)
        }
    }

    /// If no [`subcommand`] is present at runtime, error and exit gracefully.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, error::ErrorKind};
    /// let err = Command::new("myprog")
    ///     .subcommand_required(true)
    ///     .subcommand(Command::new("test"))
    ///     .try_get_matches_from(vec![
    ///         "myprog",
    ///     ]);
    /// assert!(err.is_err());
    /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand);
    /// # ;
    /// ```
    ///
    /// [`subcommand`]: crate::Command::subcommand()
    pub fn subcommand_required(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::SubcommandRequired)
        } else {
            self.unset_setting(AppSettings::SubcommandRequired)
        }
    }

    /// Assume unexpected positional arguments are a [`subcommand`].
    ///
    /// Arguments will be stored in the `""` argument in the [`ArgMatches`]
    ///
    /// **NOTE:** Use this setting with caution,
    /// as a truly unexpected argument (i.e. one that is *NOT* an external subcommand)
    /// will **not** cause an error and instead be treated as a potential subcommand.
    /// One should check for such cases manually and inform the user appropriately.
    ///
    /// **NOTE:** A built-in subcommand will be parsed as an external subcommand when escaped with
    /// `--`.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use std::ffi::OsString;
    /// # use clap::Command;
    /// // Assume there is an external subcommand named "subcmd"
    /// let m = Command::new("myprog")
    ///     .allow_external_subcommands(true)
    ///     .get_matches_from(vec![
    ///         "myprog", "subcmd", "--option", "value", "-fff", "--flag"
    ///     ]);
    ///
    /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
    /// // string argument name
    /// match m.subcommand() {
    ///     Some((external, ext_m)) => {
    ///          let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect();
    ///          assert_eq!(external, "subcmd");
    ///          assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
    ///     },
    ///     _ => {},
    /// }
    /// ```
    ///
    /// [`subcommand`]: crate::Command::subcommand()
    /// [`ArgMatches`]: crate::ArgMatches
    /// [`ErrorKind::UnknownArgument`]: crate::error::ErrorKind::UnknownArgument
    pub fn allow_external_subcommands(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::AllowExternalSubcommands)
        } else {
            self.unset_setting(AppSettings::AllowExternalSubcommands)
        }
    }

    /// Specifies how to parse external subcommand arguments.
    ///
    /// The default parser is for `OsString`.  This can be used to switch it to `String` or another
    /// type.
    ///
    /// **NOTE:** Setting this requires [`Command::allow_external_subcommands`]
    ///
    /// # Examples
    ///
    #[cfg_attr(not(unix), doc = " ```ignore")]
    #[cfg_attr(unix, doc = " ```")]
    /// # use std::ffi::OsString;
    /// # use clap::Command;
    /// # use clap::value_parser;
    /// // Assume there is an external subcommand named "subcmd"
    /// let m = Command::new("myprog")
    ///     .allow_external_subcommands(true)
    ///     .get_matches_from(vec![
    ///         "myprog", "subcmd", "--option", "value", "-fff", "--flag"
    ///     ]);
    ///
    /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
    /// // string argument name
    /// match m.subcommand() {
    ///     Some((external, ext_m)) => {
    ///          let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect();
    ///          assert_eq!(external, "subcmd");
    ///          assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
    ///     },
    ///     _ => {},
    /// }
    /// ```
    ///
    /// ```
    /// # use clap::Command;
    /// # use clap::value_parser;
    /// // Assume there is an external subcommand named "subcmd"
    /// let m = Command::new("myprog")
    ///     .external_subcommand_value_parser(value_parser!(String))
    ///     .get_matches_from(vec![
    ///         "myprog", "subcmd", "--option", "value", "-fff", "--flag"
    ///     ]);
    ///
    /// // All trailing arguments will be stored under the subcommand's sub-matches using an empty
    /// // string argument name
    /// match m.subcommand() {
    ///     Some((external, ext_m)) => {
    ///          let ext_args: Vec<_> = ext_m.get_many::<String>("").unwrap().collect();
    ///          assert_eq!(external, "subcmd");
    ///          assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
    ///     },
    ///     _ => {},
    /// }
    /// ```
    ///
    /// [`subcommands`]: crate::Command::subcommand()
    pub fn external_subcommand_value_parser(
        mut self,
        parser: impl IntoResettable<super::ValueParser>,
    ) -> Self {
        self.external_value_parser = parser.into_resettable().into_option();
        self
    }

    /// Specifies that use of an argument prevents the use of [`subcommands`].
    ///
    /// By default `clap` allows arguments between subcommands such
    /// as `<cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args]`.
    ///
    /// This setting disables that functionality and says that arguments can
    /// only follow the *final* subcommand. For instance using this setting
    /// makes only the following invocations possible:
    ///
    /// * `<cmd> <subcmd> <subsubcmd> [subsubcmd_args]`
    /// * `<cmd> <subcmd> [subcmd_args]`
    /// * `<cmd> [cmd_args]`
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::Command;
    /// Command::new("myprog")
    ///     .args_conflicts_with_subcommands(true);
    /// ```
    ///
    /// [`subcommands`]: crate::Command::subcommand()
    pub fn args_conflicts_with_subcommands(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::ArgsNegateSubcommands)
        } else {
            self.unset_setting(AppSettings::ArgsNegateSubcommands)
        }
    }

    /// Prevent subcommands from being consumed as an arguments value.
    ///
    /// By default, if an option taking multiple values is followed by a subcommand, the
    /// subcommand will be parsed as another value.
    ///
    /// ```text
    /// cmd --foo val1 val2 subcommand
    ///           --------- ----------
    ///             values   another value
    /// ```
    ///
    /// This setting instructs the parser to stop when encountering a subcommand instead of
    /// greedily consuming arguments.
    ///
    /// ```text
    /// cmd --foo val1 val2 subcommand
    ///           --------- ----------
    ///             values   subcommand
    /// ```
    ///
    /// # Examples
    ///
    /// ```rust
    /// # use clap::{Command, Arg, ArgAction};
    /// let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg(
    ///     Arg::new("arg")
    ///         .long("arg")
    ///         .num_args(1..)
    ///         .action(ArgAction::Set),
    /// );
    ///
    /// let matches = cmd
    ///     .clone()
    ///     .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
    ///     .unwrap();
    /// assert_eq!(
    ///     matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(),
    ///     &["1", "2", "3", "sub"]
    /// );
    /// assert!(matches.subcommand_matches("sub").is_none());
    ///
    /// let matches = cmd
    ///     .subcommand_precedence_over_arg(true)
    ///     .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
    ///     .unwrap();
    /// assert_eq!(
    ///     matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(),
    ///     &["1", "2", "3"]
    /// );
    /// assert!(matches.subcommand_matches("sub").is_some());
    /// ```
    pub fn subcommand_precedence_over_arg(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::SubcommandPrecedenceOverArg)
        } else {
            self.unset_setting(AppSettings::SubcommandPrecedenceOverArg)
        }
    }

    /// Allows [`subcommands`] to override all requirements of the parent command.
    ///
    /// For example, if you had a subcommand or top level application with a required argument
    /// that is only required as long as there is no subcommand present,
    /// using this setting would allow you to set those arguments to [`Arg::required(true)`]
    /// and yet receive no error so long as the user uses a valid subcommand instead.
    ///
    /// **NOTE:** This defaults to false (using subcommand does *not* negate requirements)
    ///
    /// # Examples
    ///
    /// This first example shows that it is an error to not use a required argument
    ///
    /// ```rust
    /// # use clap::{Command, Arg, error::ErrorKind};
    /// let err = Command::new("myprog")
    ///     .subcommand_negates_reqs(true)
    ///     .arg(Arg::new("opt").required(true))
    ///     .subcommand(Command::new("test"))
    ///     .try_get_matches_from(vec![
    ///         "myprog"
    ///     ]);
    /// assert!(err.is_err());
    /// assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);
    /// # ;
    /// ```
    ///
    /// This next example shows that it is no longer error to not use a required argument if a
    /// valid subcommand is used.
    ///
    /// ```rust
    /// # use clap::{Command, Arg, error::ErrorKind};
    /// let noerr = Command::new("myprog")
    ///     .subcommand_negates_reqs(true)
    ///     .arg(Arg::new("opt").required(true))
    ///     .subcommand(Command::new("test"))
    ///     .try_get_matches_from(vec![
    ///         "myprog", "test"
    ///     ]);
    /// assert!(noerr.is_ok());
    /// # ;
    /// ```
    ///
    /// [`Arg::required(true)`]: crate::Arg::required()
    /// [`subcommands`]: crate::Command::subcommand()
    pub fn subcommand_negates_reqs(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::SubcommandsNegateReqs)
        } else {
            self.unset_setting(AppSettings::SubcommandsNegateReqs)
        }
    }

    /// Multiple-personality program dispatched on the binary name (`argv[0]`)
    ///
    /// A "multicall" executable is a single executable
    /// that contains a variety of applets,
    /// and decides which applet to run based on the name of the file.
    /// The executable can be called from different names by creating hard links
    /// or symbolic links to it.
    ///
    /// This is desirable for:
    /// - Easy distribution, a single binary that can install hardlinks to access the different
    ///   personalities.
    /// - Minimal binary size by sharing common code (e.g. standard library, clap)
    /// - Custom shells or REPLs where there isn't a single top-level command
    ///
    /// Setting `multicall` will cause
    /// - `argv[0]` to be stripped to the base name and parsed as the first argument, as if
    ///   [`Command::no_binary_name`][Command::no_binary_name] was set.
    /// - Help and errors to report subcommands as if they were the top-level command
    ///
    /// When the subcommand is not present, there are several strategies you may employ, depending
    /// on your needs:
    /// - Let the error percolate up normally
    /// - Print a specialized error message using the
    ///   [`Error::context`][crate::Error::context]
    /// - Print the [help][Command::write_help] but this might be ambiguous
    /// - Disable `multicall` and re-parse it
    /// - Disable `multicall` and re-parse it with a specific subcommand
    ///
    /// When detecting the error condition, the [`ErrorKind`] isn't sufficient as a sub-subcommand
    /// might report the same error.  Enable
    /// [`allow_external_subcommands`][Command::allow_external_subcommands] if you want to specifically
    /// get the unrecognized binary name.
    ///
    /// **NOTE:** Multicall can't be used with [`no_binary_name`] since they interpret
    /// the command name in incompatible ways.
    ///
    /// **NOTE:** The multicall command cannot have arguments.
    ///
    /// **NOTE:** Applets are slightly semantically different from subcommands,
    /// so it's recommended to use [`Command::subcommand_help_heading`] and
    /// [`Command::subcommand_value_name`] to change the descriptive text as above.
    ///
    /// # Examples
    ///
    /// `hostname` is an example of a multicall executable.
    /// Both `hostname` and `dnsdomainname` are provided by the same executable
    /// and which behaviour to use is based on the executable file name.
    ///
    /// This is desirable when the executable has a primary purpose
    /// but there is related functionality that would be convenient to provide
    /// and implement it to be in the same executable.
    ///
    /// The name of the cmd is essentially unused
    /// and may be the same as the name of a subcommand.
    ///
    /// The names of the immediate subcommands of the Command
    /// are matched against the basename of the first argument,
    /// which is conventionally the path of the executable.
    ///
    /// This does not allow the subcommand to be passed as the first non-path argument.
    ///
    /// ```rust
    /// # use clap::{Command, error::ErrorKind};
    /// let mut cmd = Command::new("hostname")
    ///     .multicall(true)
    ///     .subcommand(Command::new("hostname"))
    ///     .subcommand(Command::new("dnsdomainname"));
    /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]);
    /// assert!(m.is_err());
    /// assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument);
    /// let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]);
    /// assert_eq!(m.subcommand_name(), Some("dnsdomainname"));
    /// ```
    ///
    /// Busybox is another common example of a multicall executable
    /// with a subcommmand for each applet that can be run directly,
    /// e.g. with the `cat` applet being run by running `busybox cat`,
    /// or with `cat` as a link to the `busybox` binary.
    ///
    /// This is desirable when the launcher program has additional options
    /// or it is useful to run the applet without installing a symlink
    /// e.g. to test the applet without installing it
    /// or there may already be a command of that name installed.
    ///
    /// To make an applet usable as both a multicall link and a subcommand
    /// the subcommands must be defined both in the top-level Command
    /// and as subcommands of the "main" applet.
    ///
    /// ```rust
    /// # use clap::Command;
    /// fn applet_commands() -> [Command; 2] {
    ///     [Command::new("true"), Command::new("false")]
    /// }
    /// let mut cmd = Command::new("busybox")
    ///     .multicall(true)
    ///     .subcommand(
    ///         Command::new("busybox")
    ///             .subcommand_value_name("APPLET")
    ///             .subcommand_help_heading("APPLETS")
    ///             .subcommands(applet_commands()),
    ///     )
    ///     .subcommands(applet_commands());
    /// // When called from the executable's canonical name
    /// // its applets can be matched as subcommands.
    /// let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap();
    /// assert_eq!(m.subcommand_name(), Some("busybox"));
    /// assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true"));
    /// // When called from a link named after an applet that applet is matched.
    /// let m = cmd.get_matches_from(&["/usr/bin/true"]);
    /// assert_eq!(m.subcommand_name(), Some("true"));
    /// ```
    ///
    /// [`no_binary_name`]: crate::Command::no_binary_name
    /// [`Command::subcommand_value_name`]: crate::Command::subcommand_value_name
    /// [`Command::subcommand_help_heading`]: crate::Command::subcommand_help_heading
    #[inline]
    pub fn multicall(self, yes: bool) -> Self {
        if yes {
            self.setting(AppSettings::Multicall)
        } else {
            self.unset_setting(AppSettings::Multicall)
        }
    }

    /// Sets the value name used for subcommands when printing usage and help.
    ///
    /// By default, this is "COMMAND".
    ///
    /// See also [`Command::subcommand_help_heading`]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .subcommand(Command::new("sub1"))
    ///     .print_help()
    /// # ;
    /// ```
    ///
    /// will produce
    ///
    /// ```text
    /// myprog
    ///
    /// Usage: myprog [COMMAND]
    ///
    /// Commands:
    ///     help    Print this message or the help of the given subcommand(s)
    ///     sub1
    ///
    /// Options:
    ///     -h, --help       Print help information
    ///     -V, --version    Print version information
    /// ```
    ///
    /// but usage of `subcommand_value_name`
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .subcommand(Command::new("sub1"))
    ///     .subcommand_value_name("THING")
    ///     .print_help()
    /// # ;
    /// ```
    ///
    /// will produce
    ///
    /// ```text
    /// myprog
    ///
    /// Usage: myprog [THING]
    ///
    /// Commands:
    ///     help    Print this message or the help of the given subcommand(s)
    ///     sub1
    ///
    /// Options:
    ///     -h, --help       Print help information
    ///     -V, --version    Print version information
    /// ```
    #[must_use]
    pub fn subcommand_value_name(mut self, value_name: impl IntoResettable<Str>) -> Self {
        self.subcommand_value_name = value_name.into_resettable().into_option();
        self
    }

    /// Sets the help heading used for subcommands when printing usage and help.
    ///
    /// By default, this is "Commands".
    ///
    /// See also [`Command::subcommand_value_name`]
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .subcommand(Command::new("sub1"))
    ///     .print_help()
    /// # ;
    /// ```
    ///
    /// will produce
    ///
    /// ```text
    /// myprog
    ///
    /// Usage: myprog [COMMAND]
    ///
    /// Commands:
    ///     help    Print this message or the help of the given subcommand(s)
    ///     sub1
    ///
    /// Options:
    ///     -h, --help       Print help information
    ///     -V, --version    Print version information
    /// ```
    ///
    /// but usage of `subcommand_help_heading`
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// Command::new("myprog")
    ///     .subcommand(Command::new("sub1"))
    ///     .subcommand_help_heading("Things")
    ///     .print_help()
    /// # ;
    /// ```
    ///
    /// will produce
    ///
    /// ```text
    /// myprog
    ///
    /// Usage: myprog [COMMAND]
    ///
    /// Things:
    ///     help    Print this message or the help of the given subcommand(s)
    ///     sub1
    ///
    /// Options:
    ///     -h, --help       Print help information
    ///     -V, --version    Print version information
    /// ```
    #[must_use]
    pub fn subcommand_help_heading(mut self, heading: impl IntoResettable<Str>) -> Self {
        self.subcommand_heading = heading.into_resettable().into_option();
        self
    }
}

/// # Reflection
impl Command {
    #[inline]
    #[cfg(feature = "usage")]
    pub(crate) fn get_usage_name(&self) -> Option<&str> {
        self.usage_name.as_deref()
    }

    /// Get the name of the binary.
    #[inline]
    pub fn get_display_name(&self) -> Option<&str> {
        self.display_name.as_deref()
    }

    /// Get the name of the binary.
    #[inline]
    pub fn get_bin_name(&self) -> Option<&str> {
        self.bin_name.as_deref()
    }

    /// Set binary name. Uses `&mut self` instead of `self`.
    pub fn set_bin_name(&mut self, name: impl Into<String>) {
        self.bin_name = Some(name.into());
    }

    /// Get the name of the cmd.
    #[inline]
    pub fn get_name(&self) -> &str {
        self.name.as_str()
    }

    #[inline]
    #[cfg(debug_assertions)]
    pub(crate) fn get_name_str(&self) -> &Str {
        &self.name
    }

    /// Get the version of the cmd.
    #[inline]
    pub fn get_version(&self) -> Option<&str> {
        self.version.as_deref()
    }

    /// Get the long version of the cmd.
    #[inline]
    pub fn get_long_version(&self) -> Option<&str> {
        self.long_version.as_deref()
    }

    /// Get the authors of the cmd.
    #[inline]
    pub fn get_author(&self) -> Option<&str> {
        self.author.as_deref()
    }

    /// Get the short flag of the subcommand.
    #[inline]
    pub fn get_short_flag(&self) -> Option<char> {
        self.short_flag
    }

    /// Get the long flag of the subcommand.
    #[inline]
    pub fn get_long_flag(&self) -> Option<&str> {
        self.long_flag.as_deref()
    }

    /// Get the help message specified via [`Command::about`].
    ///
    /// [`Command::about`]: Command::about()
    #[inline]
    pub fn get_about(&self) -> Option<&StyledStr> {
        self.about.as_ref()
    }

    /// Get the help message specified via [`Command::long_about`].
    ///
    /// [`Command::long_about`]: Command::long_about()
    #[inline]
    pub fn get_long_about(&self) -> Option<&StyledStr> {
        self.long_about.as_ref()
    }

    /// Get the custom section heading specified via [`Command::next_help_heading`].
    ///
    /// [`Command::help_heading`]: Command::help_heading()
    #[inline]
    pub fn get_next_help_heading(&self) -> Option<&str> {
        self.current_help_heading.as_deref()
    }

    /// Iterate through the *visible* aliases for this subcommand.
    #[inline]
    pub fn get_visible_aliases(&self) -> impl Iterator<Item = &str> + '_ {
        self.aliases
            .iter()
            .filter(|(_, vis)| *vis)
            .map(|a| a.0.as_str())
    }

    /// Iterate through the *visible* short aliases for this subcommand.
    #[inline]
    pub fn get_visible_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
        self.short_flag_aliases
            .iter()
            .filter(|(_, vis)| *vis)
            .map(|a| a.0)
    }

    /// Iterate through the *visible* long aliases for this subcommand.
    #[inline]
    pub fn get_visible_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ {
        self.long_flag_aliases
            .iter()
            .filter(|(_, vis)| *vis)
            .map(|a| a.0.as_str())
    }

    /// Iterate through the set of *all* the aliases for this subcommand, both visible and hidden.
    #[inline]
    pub fn get_all_aliases(&self) -> impl Iterator<Item = &str> + '_ {
        self.aliases.iter().map(|a| a.0.as_str())
    }

    /// Iterate through the set of *all* the short aliases for this subcommand, both visible and hidden.
    #[inline]
    pub fn get_all_short_flag_aliases(&self) -> impl Iterator<Item = char> + '_ {
        self.short_flag_aliases.iter().map(|a| a.0)
    }

    /// Iterate through the set of *all* the long aliases for this subcommand, both visible and hidden.
    #[inline]
    pub fn get_all_long_flag_aliases(&self) -> impl Iterator<Item = &str> + '_ {
        self.long_flag_aliases.iter().map(|a| a.0.as_str())
    }

    #[inline]
    pub(crate) fn is_set(&self, s: AppSettings) -> bool {
        self.settings.is_set(s) || self.g_settings.is_set(s)
    }

    /// Should we color the output?
    pub fn get_color(&self) -> ColorChoice {
        debug!("Command::color: Color setting...");

        if cfg!(feature = "color") {
            if self.is_set(AppSettings::ColorNever) {
                debug!("Never");
                ColorChoice::Never
            } else if self.is_set(AppSettings::ColorAlways) {
                debug!("Always");
                ColorChoice::Always
            } else {
                debug!("Auto");
                ColorChoice::Auto
            }
        } else {
            ColorChoice::Never
        }
    }

    /// Iterate through the set of subcommands, getting a reference to each.
    #[inline]
    pub fn get_subcommands(&self) -> impl Iterator<Item = &Command> {
        self.subcommands.iter()
    }

    /// Iterate through the set of subcommands, getting a mutable reference to each.
    #[inline]
    pub fn get_subcommands_mut(&mut self) -> impl Iterator<Item = &mut Command> {
        self.subcommands.iter_mut()
    }

    /// Returns `true` if this `Command` has subcommands.
    #[inline]
    pub fn has_subcommands(&self) -> bool {
        !self.subcommands.is_empty()
    }

    /// Returns the help heading for listing subcommands.
    #[inline]
    pub fn get_subcommand_help_heading(&self) -> Option<&str> {
        self.subcommand_heading.as_deref()
    }

    /// Returns the subcommand value name.
    #[inline]
    pub fn get_subcommand_value_name(&self) -> Option<&str> {
        self.subcommand_value_name.as_deref()
    }

    /// Returns the help heading for listing subcommands.
    #[inline]
    pub fn get_before_help(&self) -> Option<&StyledStr> {
        self.before_help.as_ref()
    }

    /// Returns the help heading for listing subcommands.
    #[inline]
    pub fn get_before_long_help(&self) -> Option<&StyledStr> {
        self.before_long_help.as_ref()
    }

    /// Returns the help heading for listing subcommands.
    #[inline]
    pub fn get_after_help(&self) -> Option<&StyledStr> {
        self.after_help.as_ref()
    }

    /// Returns the help heading for listing subcommands.
    #[inline]
    pub fn get_after_long_help(&self) -> Option<&StyledStr> {
        self.after_long_help.as_ref()
    }

    /// Find subcommand such that its name or one of aliases equals `name`.
    ///
    /// This does not recurse through subcommands of subcommands.
    #[inline]
    pub fn find_subcommand(&self, name: impl AsRef<std::ffi::OsStr>) -> Option<&Command> {
        let name = name.as_ref();
        self.get_subcommands().find(|s| s.aliases_to(name))
    }

    /// Find subcommand such that its name or one of aliases equals `name`, returning
    /// a mutable reference to the subcommand.
    ///
    /// This does not recurse through subcommands of subcommands.
    #[inline]
    pub fn find_subcommand_mut(
        &mut self,
        name: impl AsRef<std::ffi::OsStr>,
    ) -> Option<&mut Command> {
        let name = name.as_ref();
        self.get_subcommands_mut().find(|s| s.aliases_to(name))
    }

    /// Iterate through the set of groups.
    #[inline]
    pub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup> {
        self.groups.iter()
    }

    /// Iterate through the set of arguments.
    #[inline]
    pub fn get_arguments(&self) -> impl Iterator<Item = &Arg> {
        self.args.args()
    }

    /// Iterate through the *positionals* arguments.
    #[inline]
    pub fn get_positionals(&self) -> impl Iterator<Item = &Arg> {
        self.get_arguments().filter(|a| a.is_positional())
    }

    /// Iterate through the *options*.
    pub fn get_opts(&self) -> impl Iterator<Item = &Arg> {
        self.get_arguments()
            .filter(|a| a.is_takes_value_set() && !a.is_positional())
    }

    /// Get a list of all arguments the given argument conflicts with.
    ///
    /// If the provided argument is declared as global, the conflicts will be determined
    /// based on the propagation rules of global arguments.
    ///
    /// ### Panics
    ///
    /// If the given arg contains a conflict with an argument that is unknown to
    /// this `Command`.
    pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
    {
        if arg.is_global_set() {
            self.get_global_arg_conflicts_with(arg)
        } else {
            let mut result = Vec::new();
            for id in arg.blacklist.iter() {
                if let Some(arg) = self.find(id) {
                    result.push(arg);
                } else if let Some(group) = self.find_group(id) {
                    result.extend(
                        self.unroll_args_in_group(&group.id)
                            .iter()
                            .map(|id| self.find(id).expect(INTERNAL_ERROR_MSG)),
                    );
                } else {
                    panic!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd");
                }
            }
            result
        }
    }

    // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with.
    //
    // This behavior follows the propagation rules of global arguments.
    // It is useful for finding conflicts for arguments declared as global.
    //
    // ### Panics
    //
    // If the given arg contains a conflict with an argument that is unknown to
    // this `Command`.
    fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
    {
        arg.blacklist
            .iter()
            .map(|id| {
                self.args
                    .args()
                    .chain(
                        self.get_subcommands_containing(arg)
                            .iter()
                            .flat_map(|x| x.args.args()),
                    )
                    .find(|arg| arg.get_id() == id)
                    .expect(
                        "Command::get_arg_conflicts_with: \
                    The passed arg conflicts with an arg unknown to the cmd",
                    )
            })
            .collect()
    }

    // Get a list of subcommands which contain the provided Argument
    //
    // This command will only include subcommands in its list for which the subcommands
    // parent also contains the Argument.
    //
    // This search follows the propagation rules of global arguments.
    // It is useful to finding subcommands, that have inherited a global argument.
    //
    // **NOTE:** In this case only Sucommand_1 will be included
    //   Subcommand_1 (contains Arg)
    //     Subcommand_1.1 (doesn't contain Arg)
    //       Subcommand_1.1.1 (contains Arg)
    //
    fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&Self> {
        let mut vec = std::vec::Vec::new();
        for idx in 0..self.subcommands.len() {
            if self.subcommands[idx]
                .args
                .args()
                .any(|ar| ar.get_id() == arg.get_id())
            {
                vec.push(&self.subcommands[idx]);
                vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg));
            }
        }
        vec
    }

    /// Report whether [`Command::no_binary_name`] is set
    pub fn is_no_binary_name_set(&self) -> bool {
        self.is_set(AppSettings::NoBinaryName)
    }

    /// Report whether [`Command::ignore_errors`] is set
    pub(crate) fn is_ignore_errors_set(&self) -> bool {
        self.is_set(AppSettings::IgnoreErrors)
    }

    /// Report whether [`Command::dont_delimit_trailing_values`] is set
    pub fn is_dont_delimit_trailing_values_set(&self) -> bool {
        self.is_set(AppSettings::DontDelimitTrailingValues)
    }

    /// Report whether [`Command::disable_version_flag`] is set
    pub fn is_disable_version_flag_set(&self) -> bool {
        self.is_set(AppSettings::DisableVersionFlag)
            || (self.version.is_none() && self.long_version.is_none())
    }

    /// Report whether [`Command::propagate_version`] is set
    pub fn is_propagate_version_set(&self) -> bool {
        self.is_set(AppSettings::PropagateVersion)
    }

    /// Report whether [`Command::next_line_help`] is set
    pub fn is_next_line_help_set(&self) -> bool {
        self.is_set(AppSettings::NextLineHelp)
    }

    /// Report whether [`Command::disable_help_flag`] is set
    pub fn is_disable_help_flag_set(&self) -> bool {
        self.is_set(AppSettings::DisableHelpFlag)
    }

    /// Report whether [`Command::disable_help_subcommand`] is set
    pub fn is_disable_help_subcommand_set(&self) -> bool {
        self.is_set(AppSettings::DisableHelpSubcommand)
    }

    /// Report whether [`Command::disable_colored_help`] is set
    pub fn is_disable_colored_help_set(&self) -> bool {
        self.is_set(AppSettings::DisableColoredHelp)
    }

    /// Report whether [`Command::help_expected`] is set
    #[cfg(debug_assertions)]
    pub(crate) fn is_help_expected_set(&self) -> bool {
        self.is_set(AppSettings::HelpExpected)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "This is now the default")
    )]
    pub fn is_dont_collapse_args_in_usage_set(&self) -> bool {
        true
    }

    /// Report whether [`Command::infer_long_args`] is set
    pub(crate) fn is_infer_long_args_set(&self) -> bool {
        self.is_set(AppSettings::InferLongArgs)
    }

    /// Report whether [`Command::infer_subcommands`] is set
    pub(crate) fn is_infer_subcommands_set(&self) -> bool {
        self.is_set(AppSettings::InferSubcommands)
    }

    /// Report whether [`Command::arg_required_else_help`] is set
    pub fn is_arg_required_else_help_set(&self) -> bool {
        self.is_set(AppSettings::ArgRequiredElseHelp)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(
            since = "4.0.0",
            note = "Replaced with `Arg::is_allow_hyphen_values_set`"
        )
    )]
    pub(crate) fn is_allow_hyphen_values_set(&self) -> bool {
        self.is_set(AppSettings::AllowHyphenValues)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(
            since = "4.0.0",
            note = "Replaced with `Arg::is_allow_negative_numbers_set`"
        )
    )]
    pub fn is_allow_negative_numbers_set(&self) -> bool {
        self.is_set(AppSettings::AllowNegativeNumbers)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "Replaced with `Arg::is_trailing_var_arg_set`")
    )]
    pub fn is_trailing_var_arg_set(&self) -> bool {
        self.is_set(AppSettings::TrailingVarArg)
    }

    /// Report whether [`Command::allow_missing_positional`] is set
    pub fn is_allow_missing_positional_set(&self) -> bool {
        self.is_set(AppSettings::AllowMissingPositional)
    }

    /// Report whether [`Command::hide`] is set
    pub fn is_hide_set(&self) -> bool {
        self.is_set(AppSettings::Hidden)
    }

    /// Report whether [`Command::subcommand_required`] is set
    pub fn is_subcommand_required_set(&self) -> bool {
        self.is_set(AppSettings::SubcommandRequired)
    }

    /// Report whether [`Command::allow_external_subcommands`] is set
    pub fn is_allow_external_subcommands_set(&self) -> bool {
        self.is_set(AppSettings::AllowExternalSubcommands)
    }

    /// Configured parser for values passed to an external subcommand
    ///
    /// # Example
    ///
    /// ```rust
    /// let cmd = clap::Command::new("raw")
    ///     .external_subcommand_value_parser(clap::value_parser!(String));
    /// let value_parser = cmd.get_external_subcommand_value_parser();
    /// println!("{:?}", value_parser);
    /// ```
    pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> {
        if !self.is_allow_external_subcommands_set() {
            None
        } else {
            static DEFAULT: super::ValueParser = super::ValueParser::os_string();
            Some(self.external_value_parser.as_ref().unwrap_or(&DEFAULT))
        }
    }

    /// Report whether [`Command::args_conflicts_with_subcommands`] is set
    pub fn is_args_conflicts_with_subcommands_set(&self) -> bool {
        self.is_set(AppSettings::ArgsNegateSubcommands)
    }

    #[doc(hidden)]
    pub fn is_args_override_self(&self) -> bool {
        self.is_set(AppSettings::AllArgsOverrideSelf)
    }

    /// Report whether [`Command::subcommand_precedence_over_arg`] is set
    pub fn is_subcommand_precedence_over_arg_set(&self) -> bool {
        self.is_set(AppSettings::SubcommandPrecedenceOverArg)
    }

    /// Report whether [`Command::subcommand_negates_reqs`] is set
    pub fn is_subcommand_negates_reqs_set(&self) -> bool {
        self.is_set(AppSettings::SubcommandsNegateReqs)
    }

    /// Report whether [`Command::multicall`] is set
    pub fn is_multicall_set(&self) -> bool {
        self.is_set(AppSettings::Multicall)
    }
}

// Internally used only
impl Command {
    pub(crate) fn get_override_usage(&self) -> Option<&StyledStr> {
        self.usage_str.as_ref()
    }

    pub(crate) fn get_override_help(&self) -> Option<&StyledStr> {
        self.help_str.as_ref()
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_help_template(&self) -> Option<&StyledStr> {
        self.template.as_ref()
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_term_width(&self) -> Option<usize> {
        self.term_w
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_max_term_width(&self) -> Option<usize> {
        self.max_w
    }

    pub(crate) fn get_replacement(&self, key: &str) -> Option<&[Str]> {
        self.replacers.get(key).map(|v| v.as_slice())
    }

    pub(crate) fn get_keymap(&self) -> &MKeyMap {
        &self.args
    }

    fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec<Id>) {
        global_arg_vec.extend(
            self.args
                .args()
                .filter(|a| a.is_global_set())
                .map(|ga| ga.id.clone()),
        );
        if let Some((id, matches)) = matches.subcommand() {
            if let Some(used_sub) = self.find_subcommand(id) {
                used_sub.get_used_global_args(matches, global_arg_vec);
            }
        }
    }

    fn _do_parse(
        &mut self,
        raw_args: &mut clap_lex::RawArgs,
        args_cursor: clap_lex::ArgCursor,
    ) -> ClapResult<ArgMatches> {
        debug!("Command::_do_parse");

        // If there are global arguments, or settings we need to propagate them down to subcommands
        // before parsing in case we run into a subcommand
        self._build_self(false);

        let mut matcher = ArgMatcher::new(self);

        // do the real parsing
        let mut parser = Parser::new(self);
        if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) {
            if self.is_set(AppSettings::IgnoreErrors) {
                debug!("Command::_do_parse: ignoring error: {}", error);
            } else {
                return Err(error);
            }
        }

        let mut global_arg_vec = Default::default();
        self.get_used_global_args(&matcher, &mut global_arg_vec);

        matcher.propagate_globals(&global_arg_vec);

        Ok(matcher.into_inner())
    }

    /// Prepare for introspecting on all included [`Command`]s
    ///
    /// Call this on the top-level [`Command`] when done building and before reading state for
    /// cases like completions, custom help output, etc.
    pub fn build(&mut self) {
        self._build_recursive(true);
        self._build_bin_names_internal();
    }

    pub(crate) fn _build_recursive(&mut self, expand_help_tree: bool) {
        self._build_self(expand_help_tree);
        for subcmd in self.get_subcommands_mut() {
            subcmd._build_recursive(expand_help_tree);
        }
    }

    pub(crate) fn _build_self(&mut self, expand_help_tree: bool) {
        debug!("Command::_build: name={:?}", self.get_name());
        if !self.settings.is_set(AppSettings::Built) {
            // Make sure all the globally set flags apply to us as well
            self.settings = self.settings | self.g_settings;

            if self.is_multicall_set() {
                self.settings.insert(AppSettings::SubcommandRequired.into());
                self.settings.insert(AppSettings::DisableHelpFlag.into());
                self.settings.insert(AppSettings::DisableVersionFlag.into());
            }
            if !cfg!(feature = "help") && self.get_override_help().is_none() {
                self.settings.insert(AppSettings::DisableHelpFlag.into());
                self.settings
                    .insert(AppSettings::DisableHelpSubcommand.into());
            }
            if self.is_set(AppSettings::ArgsNegateSubcommands) {
                self.settings
                    .insert(AppSettings::SubcommandsNegateReqs.into());
            }
            if self.external_value_parser.is_some() {
                self.settings
                    .insert(AppSettings::AllowExternalSubcommands.into());
            }
            if !self.has_subcommands() {
                self.settings
                    .insert(AppSettings::DisableHelpSubcommand.into());
            }

            self._propagate();
            self._check_help_and_version(expand_help_tree);
            self._propagate_global_args();

            let mut pos_counter = 1;
            let hide_pv = self.is_set(AppSettings::HidePossibleValues);
            for a in self.args.args_mut() {
                // Fill in the groups
                for g in &a.groups {
                    if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) {
                        ag.args.push(a.get_id().clone());
                    } else {
                        let mut ag = ArgGroup::new(g);
                        ag.args.push(a.get_id().clone());
                        self.groups.push(ag);
                    }
                }

                // Figure out implied settings
                a._build();
                if hide_pv && a.is_takes_value_set() {
                    a.settings.set(ArgSettings::HidePossibleValues);
                }
                if a.is_positional() && a.index.is_none() {
                    a.index = Some(pos_counter);
                    pos_counter += 1;
                }
            }

            self.args._build();

            #[allow(deprecated)]
            {
                let highest_idx = self
                    .get_keymap()
                    .keys()
                    .filter_map(|x| {
                        if let crate::mkeymap::KeyType::Position(n) = x {
                            Some(*n)
                        } else {
                            None
                        }
                    })
                    .max()
                    .unwrap_or(0);
                let is_trailing_var_arg_set = self.is_trailing_var_arg_set();
                let is_allow_hyphen_values_set = self.is_allow_hyphen_values_set();
                let is_allow_negative_numbers_set = self.is_allow_negative_numbers_set();
                for arg in self.args.args_mut() {
                    if is_allow_hyphen_values_set && arg.is_takes_value_set() {
                        arg.settings.insert(ArgSettings::AllowHyphenValues.into());
                    }
                    if is_allow_negative_numbers_set && arg.is_takes_value_set() {
                        arg.settings
                            .insert(ArgSettings::AllowNegativeNumbers.into());
                    }
                    if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) {
                        arg.settings.insert(ArgSettings::TrailingVarArg.into());
                    }
                }
            }

            #[cfg(debug_assertions)]
            assert_app(self);
            self.settings.set(AppSettings::Built);
        } else {
            debug!("Command::_build: already built");
        }
    }

    pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> {
        use std::fmt::Write;

        let mut mid_string = String::from(" ");
        #[cfg(feature = "usage")]
        if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set()
        {
            let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

            for s in &reqs {
                mid_string.push_str(&s.to_string());
                mid_string.push(' ');
            }
        }
        let is_multicall_set = self.is_multicall_set();

        let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name));

        // Display subcommand name, short and long in usage
        let mut sc_names = String::new();
        sc_names.push_str(sc.name.as_str());
        let mut flag_subcmd = false;
        if let Some(l) = sc.get_long_flag() {
            write!(sc_names, "|--{}", l).unwrap();
            flag_subcmd = true;
        }
        if let Some(s) = sc.get_short_flag() {
            write!(sc_names, "|-{}", s).unwrap();
            flag_subcmd = true;
        }

        if flag_subcmd {
            sc_names = format!("{{{}}}", sc_names);
        }

        let usage_name = self
            .bin_name
            .as_ref()
            .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names))
            .unwrap_or(sc_names);
        sc.usage_name = Some(usage_name);

        // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
        // a space
        let bin_name = format!(
            "{}{}{}",
            self.bin_name.as_deref().unwrap_or_default(),
            if self.bin_name.is_some() { " " } else { "" },
            &*sc.name
        );
        debug!(
            "Command::_build_subcommand Setting bin_name of {} to {:?}",
            sc.name, bin_name
        );
        sc.bin_name = Some(bin_name);

        if sc.display_name.is_none() {
            let self_display_name = if is_multicall_set {
                self.display_name.as_deref().unwrap_or("")
            } else {
                self.display_name.as_deref().unwrap_or(&self.name)
            };
            let display_name = format!(
                "{}{}{}",
                self_display_name,
                if !self_display_name.is_empty() {
                    "-"
                } else {
                    ""
                },
                &*sc.name
            );
            debug!(
                "Command::_build_subcommand Setting display_name of {} to {:?}",
                sc.name, display_name
            );
            sc.display_name = Some(display_name);
        }

        // Ensure all args are built and ready to parse
        sc._build_self(false);

        Some(sc)
    }

    fn _build_bin_names_internal(&mut self) {
        debug!("Command::_build_bin_names");

        if !self.is_set(AppSettings::BinNameBuilt) {
            let mut mid_string = String::from(" ");
            #[cfg(feature = "usage")]
            if !self.is_subcommand_negates_reqs_set()
                && !self.is_args_conflicts_with_subcommands_set()
            {
                let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

                for s in &reqs {
                    mid_string.push_str(&s.to_string());
                    mid_string.push(' ');
                }
            }
            let is_multicall_set = self.is_multicall_set();

            let self_bin_name = if is_multicall_set {
                self.bin_name.as_deref().unwrap_or("")
            } else {
                self.bin_name.as_deref().unwrap_or(&self.name)
            }
            .to_owned();

            for mut sc in &mut self.subcommands {
                debug!("Command::_build_bin_names:iter: bin_name set...");

                if sc.usage_name.is_none() {
                    use std::fmt::Write;
                    // Display subcommand name, short and long in usage
                    let mut sc_names = String::new();
                    sc_names.push_str(sc.name.as_str());
                    let mut flag_subcmd = false;
                    if let Some(l) = sc.get_long_flag() {
                        write!(sc_names, "|--{}", l).unwrap();
                        flag_subcmd = true;
                    }
                    if let Some(s) = sc.get_short_flag() {
                        write!(sc_names, "|-{}", s).unwrap();
                        flag_subcmd = true;
                    }

                    if flag_subcmd {
                        sc_names = format!("{{{}}}", sc_names);
                    }

                    let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names);
                    debug!(
                        "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}",
                        sc.name, usage_name
                    );
                    sc.usage_name = Some(usage_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})",
                        sc.name, sc.usage_name
                    );
                }

                if sc.bin_name.is_none() {
                    let bin_name = format!(
                        "{}{}{}",
                        self_bin_name,
                        if !self_bin_name.is_empty() { " " } else { "" },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}",
                        sc.name, bin_name
                    );
                    sc.bin_name = Some(bin_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})",
                        sc.name, sc.bin_name
                    );
                }

                if sc.display_name.is_none() {
                    let self_display_name = if is_multicall_set {
                        self.display_name.as_deref().unwrap_or("")
                    } else {
                        self.display_name.as_deref().unwrap_or(&self.name)
                    };
                    let display_name = format!(
                        "{}{}{}",
                        self_display_name,
                        if !self_display_name.is_empty() {
                            "-"
                        } else {
                            ""
                        },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting display_name of {} to {:?}",
                        sc.name, display_name
                    );
                    sc.display_name = Some(display_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})",
                        sc.name, sc.display_name
                    );
                }

                sc._build_bin_names_internal();
            }
            self.set(AppSettings::BinNameBuilt);
        } else {
            debug!("Command::_build_bin_names: already built");
        }
    }

    pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) {
        if self.is_set(AppSettings::HelpExpected) || help_required_globally {
            let args_missing_help: Vec<Id> = self
                .args
                .args()
                .filter(|arg| arg.get_help().is_none() && arg.get_long_help().is_none())
                .map(|arg| arg.get_id().clone())
                .collect();

            debug_assert!(args_missing_help.is_empty(),
                    "Command::help_expected is enabled for the Command {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}",
                    self.name,
                    args_missing_help.join(", ")
                );
        }

        for sub_app in &self.subcommands {
            sub_app._panic_on_missing_help(help_required_globally);
        }
    }

    #[cfg(debug_assertions)]
    pub(crate) fn two_args_of<F>(&self, condition: F) -> Option<(&Arg, &Arg)>
    where
        F: Fn(&Arg) -> bool,
    {
        two_elements_of(self.args.args().filter(|a: &&Arg| condition(a)))
    }

    // just in case
    #[allow(unused)]
    fn two_groups_of<F>(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)>
    where
        F: Fn(&ArgGroup) -> bool,
    {
        two_elements_of(self.groups.iter().filter(|a| condition(a)))
    }

    /// Propagate global args
    pub(crate) fn _propagate_global_args(&mut self) {
        debug!("Command::_propagate_global_args:{}", self.name);

        let autogenerated_help_subcommand = !self.is_disable_help_subcommand_set();

        for sc in &mut self.subcommands {
            if sc.get_name() == "help" && autogenerated_help_subcommand {
                // Avoid propagating args to the autogenerated help subtrees used in completion.
                // This prevents args from showing up during help completions like
                // `myapp help subcmd <TAB>`, which should only suggest subcommands and not args,
                // while still allowing args to show up properly on the generated help message.
                continue;
            }

            for a in self.args.args().filter(|a| a.is_global_set()) {
                if sc.find(&a.id).is_some() {
                    debug!(
                        "Command::_propagate skipping {:?} to {}, already exists",
                        a.id,
                        sc.get_name(),
                    );
                    continue;
                }

                debug!(
                    "Command::_propagate pushing {:?} to {}",
                    a.id,
                    sc.get_name(),
                );
                sc.args.push(a.clone());
            }
        }
    }

    /// Propagate settings
    pub(crate) fn _propagate(&mut self) {
        debug!("Command::_propagate:{}", self.name);
        let mut subcommands = std::mem::take(&mut self.subcommands);
        for sc in &mut subcommands {
            self._propagate_subcommand(sc);
        }
        self.subcommands = subcommands;
    }

    fn _propagate_subcommand(&self, sc: &mut Self) {
        // We have to create a new scope in order to tell rustc the borrow of `sc` is
        // done and to recursively call this method
        {
            if self.settings.is_set(AppSettings::PropagateVersion) {
                if let Some(version) = self.version.as_ref() {
                    sc.version.get_or_insert_with(|| version.clone());
                }
                if let Some(long_version) = self.long_version.as_ref() {
                    sc.long_version.get_or_insert_with(|| long_version.clone());
                }
            }

            sc.settings = sc.settings | self.g_settings;
            sc.g_settings = sc.g_settings | self.g_settings;
            sc.term_w = self.term_w;
            sc.max_w = self.max_w;
        }
    }

    pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) {
        debug!(
            "Command::_check_help_and_version:{} expand_help_tree={}",
            self.name, expand_help_tree
        );

        self.long_help_exists = self.long_help_exists_();

        if !self.is_disable_help_flag_set() {
            debug!("Command::_check_help_and_version: Building default --help");
            let mut arg = Arg::new(Id::HELP)
                .short('h')
                .long("help")
                .action(ArgAction::Help);
            if self.long_help_exists {
                arg = arg
                    .help("Print help information (use `--help` for more detail)")
                    .long_help("Print help information (use `-h` for a summary)");
            } else {
                arg = arg.help("Print help information");
            }
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }
        if !self.is_disable_version_flag_set() {
            debug!("Command::_check_help_and_version: Building default --version");
            let arg = Arg::new(Id::VERSION)
                .short('V')
                .long("version")
                .action(ArgAction::Version)
                .help("Print version information");
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }

        if !self.is_set(AppSettings::DisableHelpSubcommand) {
            debug!("Command::_check_help_and_version: Building help subcommand");
            let help_about = "Print this message or the help of the given subcommand(s)";

            let mut help_subcmd = if expand_help_tree {
                // Slow code path to recursively clone all other subcommand subtrees under help
                let help_subcmd = Command::new("help")
                    .about(help_about)
                    .global_setting(AppSettings::DisableHelpSubcommand)
                    .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));

                let mut help_help_subcmd = Command::new("help").about(help_about);
                help_help_subcmd.version = None;
                help_help_subcmd.long_version = None;
                help_help_subcmd = help_help_subcmd
                    .setting(AppSettings::DisableHelpFlag)
                    .setting(AppSettings::DisableVersionFlag);

                help_subcmd.subcommand(help_help_subcmd)
            } else {
                Command::new("help").about(help_about).arg(
                    Arg::new("subcommand")
                        .action(ArgAction::Append)
                        .num_args(..)
                        .value_name("COMMAND")
                        .help("Print help for the subcommand(s)"),
                )
            };
            self._propagate_subcommand(&mut help_subcmd);

            // The parser acts like this is set, so let's set it so we don't falsely
            // advertise it to the user
            help_subcmd.version = None;
            help_subcmd.long_version = None;
            help_subcmd = help_subcmd
                .setting(AppSettings::DisableHelpFlag)
                .setting(AppSettings::DisableVersionFlag)
                .unset_global_setting(AppSettings::PropagateVersion);

            self.subcommands.push(help_subcmd);
        }
    }

Adds multiple subcommands to the list of valid possibilities.

Examples
.subcommands( [
       Command::new("config").about("Controls configuration functionality")
                                .arg(Arg::new("config_file")),
       Command::new("debug").about("Controls debug functionality")])
Examples found in repository?
src/builder/command.rs (line 4276)
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
    pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) {
        debug!(
            "Command::_check_help_and_version:{} expand_help_tree={}",
            self.name, expand_help_tree
        );

        self.long_help_exists = self.long_help_exists_();

        if !self.is_disable_help_flag_set() {
            debug!("Command::_check_help_and_version: Building default --help");
            let mut arg = Arg::new(Id::HELP)
                .short('h')
                .long("help")
                .action(ArgAction::Help);
            if self.long_help_exists {
                arg = arg
                    .help("Print help information (use `--help` for more detail)")
                    .long_help("Print help information (use `-h` for a summary)");
            } else {
                arg = arg.help("Print help information");
            }
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }
        if !self.is_disable_version_flag_set() {
            debug!("Command::_check_help_and_version: Building default --version");
            let arg = Arg::new(Id::VERSION)
                .short('V')
                .long("version")
                .action(ArgAction::Version)
                .help("Print version information");
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }

        if !self.is_set(AppSettings::DisableHelpSubcommand) {
            debug!("Command::_check_help_and_version: Building help subcommand");
            let help_about = "Print this message or the help of the given subcommand(s)";

            let mut help_subcmd = if expand_help_tree {
                // Slow code path to recursively clone all other subcommand subtrees under help
                let help_subcmd = Command::new("help")
                    .about(help_about)
                    .global_setting(AppSettings::DisableHelpSubcommand)
                    .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));

                let mut help_help_subcmd = Command::new("help").about(help_about);
                help_help_subcmd.version = None;
                help_help_subcmd.long_version = None;
                help_help_subcmd = help_help_subcmd
                    .setting(AppSettings::DisableHelpFlag)
                    .setting(AppSettings::DisableVersionFlag);

                help_subcmd.subcommand(help_help_subcmd)
            } else {
                Command::new("help").about(help_about).arg(
                    Arg::new("subcommand")
                        .action(ArgAction::Append)
                        .num_args(..)
                        .value_name("COMMAND")
                        .help("Print help for the subcommand(s)"),
                )
            };
            self._propagate_subcommand(&mut help_subcmd);

            // The parser acts like this is set, so let's set it so we don't falsely
            // advertise it to the user
            help_subcmd.version = None;
            help_subcmd.long_version = None;
            help_subcmd = help_subcmd
                .setting(AppSettings::DisableHelpFlag)
                .setting(AppSettings::DisableVersionFlag)
                .unset_global_setting(AppSettings::PropagateVersion);

            self.subcommands.push(help_subcmd);
        }
    }

    fn _copy_subtree_for_help(&self) -> Command {
        let mut cmd = Command::new(self.name.clone())
            .hide(self.is_hide_set())
            .global_setting(AppSettings::DisableHelpFlag)
            .global_setting(AppSettings::DisableVersionFlag)
            .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));
        if self.get_about().is_some() {
            cmd = cmd.about(self.get_about().unwrap().clone());
        }
        cmd
    }

Catch problems earlier in the development cycle.

Most error states are handled as asserts under the assumption they are programming mistake and not something to handle at runtime. Rather than relying on tests (manual or automated) that exhaustively test your CLI to ensure the asserts are evaluated, this will run those asserts in a way convenient for running as a test.

Note:: This will not help with asserts in ArgMatches, those will need exhaustive testing of your CLI.

Examples
fn cmd() -> Command {
    Command::new("foo")
        .arg(
            Arg::new("bar").short('b').action(ArgAction::SetTrue)
        )
}

#[test]
fn verify_app() {
    cmd().debug_assert();
}

fn main() {
    let m = cmd().get_matches_from(vec!["foo", "-b"]);
    println!("{}", *m.get_one::<bool>("bar").expect("defaulted by clap"));
}

Custom error message for post-parsing validation

Examples
let mut cmd = Command::new("myprog");
let err = cmd.error(ErrorKind::InvalidValue, "Some failure case");

Parse env::args_os, exiting on failure.

Panics

If contradictory arguments or settings exist.

Examples
let matches = Command::new("myprog")
    // Args and options go here...
    .get_matches();
Examples found in repository?
src/derive.rs (line 82)
81
82
83
84
85
86
87
88
89
90
91
92
93
    fn parse() -> Self {
        let mut matches = <Self as CommandFactory>::command().get_matches();
        let res = <Self as FromArgMatches>::from_arg_matches_mut(&mut matches)
            .map_err(format_error::<Self>);
        match res {
            Ok(s) => s,
            Err(e) => {
                // Since this is more of a development-time error, we aren't doing as fancy of a quit
                // as `get_matches`
                e.exit()
            }
        }
    }

Parse env::args_os, exiting on failure.

Like Command::get_matches but doesn’t consume the Command.

Panics

If contradictory arguments or settings exist.

Examples
let mut cmd = Command::new("myprog")
    // Args and options go here...
    ;
let matches = cmd.get_matches_mut();

Parse env::args_os, returning a clap::Result on failure.

NOTE: This method WILL NOT exit when --help or --version (or short versions) are used. It will return a clap::Error, where the kind is a ErrorKind::DisplayHelp or ErrorKind::DisplayVersion respectively. You must call Error::exit or perform a std::process::exit.

Panics

If contradictory arguments or settings exist.

Examples
let matches = Command::new("myprog")
    // Args and options go here...
    .try_get_matches()
    .unwrap_or_else(|e| e.exit());
Examples found in repository?
src/derive.rs (line 97)
96
97
98
99
    fn try_parse() -> Result<Self, Error> {
        let mut matches = ok!(<Self as CommandFactory>::command().try_get_matches());
        <Self as FromArgMatches>::from_arg_matches_mut(&mut matches).map_err(format_error::<Self>)
    }

Parse the specified arguments, exiting on failure.

NOTE: The first argument will be parsed as the binary name unless Command::no_binary_name is used.

Panics

If contradictory arguments or settings exist.

Examples
let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];

let matches = Command::new("myprog")
    // Args and options go here...
    .get_matches_from(arg_vec);
Examples found in repository?
src/builder/command.rs (line 490)
489
490
491
    pub fn get_matches(self) -> ArgMatches {
        self.get_matches_from(&mut env::args_os())
    }
More examples
Hide additional examples
src/derive.rs (line 107)
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
    fn parse_from<I, T>(itr: I) -> Self
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        let mut matches = <Self as CommandFactory>::command().get_matches_from(itr);
        let res = <Self as FromArgMatches>::from_arg_matches_mut(&mut matches)
            .map_err(format_error::<Self>);
        match res {
            Ok(s) => s,
            Err(e) => {
                // Since this is more of a development-time error, we aren't doing as fancy of a quit
                // as `get_matches_from`
                e.exit()
            }
        }
    }

    /// Parse from iterator, return Err on error.
    fn try_parse_from<I, T>(itr: I) -> Result<Self, Error>
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        let mut matches = ok!(<Self as CommandFactory>::command().try_get_matches_from(itr));
        <Self as FromArgMatches>::from_arg_matches_mut(&mut matches).map_err(format_error::<Self>)
    }

    /// Update from iterator, exit on error
    fn update_from<I, T>(&mut self, itr: I)
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        let mut matches = <Self as CommandFactory>::command_for_update().get_matches_from(itr);
        let res = <Self as FromArgMatches>::update_from_arg_matches_mut(self, &mut matches)
            .map_err(format_error::<Self>);
        if let Err(e) = res {
            // Since this is more of a development-time error, we aren't doing as fancy of a quit
            // as `get_matches_from`
            e.exit()
        }
    }

Parse the specified arguments, returning a clap::Result on failure.

NOTE: This method WILL NOT exit when --help or --version (or short versions) are used. It will return a clap::Error, where the kind is a ErrorKind::DisplayHelp or ErrorKind::DisplayVersion respectively. You must call Error::exit or perform a std::process::exit yourself.

NOTE: The first argument will be parsed as the binary name unless Command::no_binary_name is used.

Panics

If contradictory arguments or settings exist.

Examples
let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];

let matches = Command::new("myprog")
    // Args and options go here...
    .try_get_matches_from(arg_vec)
    .unwrap_or_else(|e| e.exit());
Examples found in repository?
src/builder/command.rs (line 548)
546
547
548
549
    pub fn try_get_matches(self) -> ClapResult<ArgMatches> {
        // Start the parsing
        self.try_get_matches_from(&mut env::args_os())
    }
More examples
Hide additional examples
src/derive.rs (line 126)
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
    fn try_parse_from<I, T>(itr: I) -> Result<Self, Error>
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        let mut matches = ok!(<Self as CommandFactory>::command().try_get_matches_from(itr));
        <Self as FromArgMatches>::from_arg_matches_mut(&mut matches).map_err(format_error::<Self>)
    }

    /// Update from iterator, exit on error
    fn update_from<I, T>(&mut self, itr: I)
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        let mut matches = <Self as CommandFactory>::command_for_update().get_matches_from(itr);
        let res = <Self as FromArgMatches>::update_from_arg_matches_mut(self, &mut matches)
            .map_err(format_error::<Self>);
        if let Err(e) = res {
            // Since this is more of a development-time error, we aren't doing as fancy of a quit
            // as `get_matches_from`
            e.exit()
        }
    }

    /// Update from iterator, return Err on error.
    fn try_update_from<I, T>(&mut self, itr: I) -> Result<(), Error>
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        let mut matches =
            ok!(<Self as CommandFactory>::command_for_update().try_get_matches_from(itr));
        <Self as FromArgMatches>::update_from_arg_matches_mut(self, &mut matches)
            .map_err(format_error::<Self>)
    }

Parse the specified arguments, returning a clap::Result on failure.

Like Command::try_get_matches_from but doesn’t consume the Command.

NOTE: This method WILL NOT exit when --help or --version (or short versions) are used. It will return a clap::Error, where the kind is a ErrorKind::DisplayHelp or ErrorKind::DisplayVersion respectively. You must call Error::exit or perform a std::process::exit yourself.

NOTE: The first argument will be parsed as the binary name unless Command::no_binary_name is used.

Panics

If contradictory arguments or settings exist.

Examples
let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];

let mut cmd = Command::new("myprog");
    // Args and options go here...
let matches = cmd.try_get_matches_from_mut(arg_vec)
    .unwrap_or_else(|e| e.exit());
Examples found in repository?
src/builder/command.rs (line 513)
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
    pub fn get_matches_mut(&mut self) -> ArgMatches {
        self.try_get_matches_from_mut(&mut env::args_os())
            .unwrap_or_else(|e| e.exit())
    }

    /// Parse [`env::args_os`], returning a [`clap::Result`] on failure.
    ///
    /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
    /// used. It will return a [`clap::Error`], where the [`kind`] is a
    /// [`ErrorKind::DisplayHelp`] or [`ErrorKind::DisplayVersion`] respectively. You must call
    /// [`Error::exit`] or perform a [`std::process::exit`].
    ///
    /// # Panics
    ///
    /// If contradictory arguments or settings exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let matches = Command::new("myprog")
    ///     // Args and options go here...
    ///     .try_get_matches()
    ///     .unwrap_or_else(|e| e.exit());
    /// ```
    /// [`env::args_os`]: std::env::args_os()
    /// [`Error::exit`]: crate::Error::exit()
    /// [`std::process::exit`]: std::process::exit()
    /// [`clap::Result`]: Result
    /// [`clap::Error`]: crate::Error
    /// [`kind`]: crate::Error
    /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp
    /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion
    #[inline]
    pub fn try_get_matches(self) -> ClapResult<ArgMatches> {
        // Start the parsing
        self.try_get_matches_from(&mut env::args_os())
    }

    /// Parse the specified arguments, exiting on failure.
    ///
    /// **NOTE:** The first argument will be parsed as the binary name unless
    /// [`Command::no_binary_name`] is used.
    ///
    /// # Panics
    ///
    /// If contradictory arguments or settings exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
    ///
    /// let matches = Command::new("myprog")
    ///     // Args and options go here...
    ///     .get_matches_from(arg_vec);
    /// ```
    /// [`Command::get_matches`]: Command::get_matches()
    /// [`clap::Result`]: Result
    /// [`Vec`]: std::vec::Vec
    pub fn get_matches_from<I, T>(mut self, itr: I) -> ArgMatches
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        self.try_get_matches_from_mut(itr).unwrap_or_else(|e| {
            drop(self);
            e.exit()
        })
    }

    /// Parse the specified arguments, returning a [`clap::Result`] on failure.
    ///
    /// **NOTE:** This method WILL NOT exit when `--help` or `--version` (or short versions) are
    /// used. It will return a [`clap::Error`], where the [`kind`] is a [`ErrorKind::DisplayHelp`]
    /// or [`ErrorKind::DisplayVersion`] respectively. You must call [`Error::exit`] or
    /// perform a [`std::process::exit`] yourself.
    ///
    /// **NOTE:** The first argument will be parsed as the binary name unless
    /// [`Command::no_binary_name`] is used.
    ///
    /// # Panics
    ///
    /// If contradictory arguments or settings exist.
    ///
    /// # Examples
    ///
    /// ```no_run
    /// # use clap::{Command, Arg};
    /// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
    ///
    /// let matches = Command::new("myprog")
    ///     // Args and options go here...
    ///     .try_get_matches_from(arg_vec)
    ///     .unwrap_or_else(|e| e.exit());
    /// ```
    /// [`Command::get_matches_from`]: Command::get_matches_from()
    /// [`Command::try_get_matches`]: Command::try_get_matches()
    /// [`Error::exit`]: crate::Error::exit()
    /// [`std::process::exit`]: std::process::exit()
    /// [`clap::Error`]: crate::Error
    /// [`Error::exit`]: crate::Error::exit()
    /// [`kind`]: crate::Error
    /// [`ErrorKind::DisplayHelp`]: crate::error::ErrorKind::DisplayHelp
    /// [`ErrorKind::DisplayVersion`]: crate::error::ErrorKind::DisplayVersion
    /// [`clap::Result`]: Result
    pub fn try_get_matches_from<I, T>(mut self, itr: I) -> ClapResult<ArgMatches>
    where
        I: IntoIterator<Item = T>,
        T: Into<OsString> + Clone,
    {
        self.try_get_matches_from_mut(itr)
    }

Prints the short help message (-h) to io::stdout().

See also Command::print_long_help.

Examples
let mut cmd = Command::new("myprog");
cmd.print_help();

Prints the long help message (--help) to io::stdout().

See also Command::print_help.

Examples
let mut cmd = Command::new("myprog");
cmd.print_long_help();

Render the short help message (-h) to a StyledStr

See also Command::render_long_help.

Examples
use std::io;
let mut cmd = Command::new("myprog");
let mut out = io::stdout();
let help = cmd.render_help();
println!("{}", help);

Render the long help message (--help) to a StyledStr.

See also Command::render_help.

Examples
use std::io;
let mut cmd = Command::new("myprog");
let mut out = io::stdout();
let help = cmd.render_long_help();
println!("{}", help);

Version message rendered as if the user ran -V.

See also Command::render_long_version.

Coloring

This function does not try to color the message nor it inserts any ANSI escape codes.

Examples
use std::io;
let cmd = Command::new("myprog");
println!("{}", cmd.render_version());

Version message rendered as if the user ran --version.

See also Command::render_version.

Coloring

This function does not try to color the message nor it inserts any ANSI escape codes.

Examples
use std::io;
let cmd = Command::new("myprog");
println!("{}", cmd.render_long_version());

Usage statement

Examples
use std::io;
let mut cmd = Command::new("myprog");
println!("{}", cmd.render_usage());

Application-wide Settings

These settings will apply to the top-level command and all subcommands, by default. Some settings can be overridden in subcommands.

Specifies that the parser should not assume the first argument passed is the binary name.

This is normally the case when using a “daemon” style mode. For shells / REPLs, see Command::multicall.

Examples
let m = Command::new("myprog")
    .no_binary_name(true)
    .arg(arg!(<cmd> ... "commands to run"))
    .get_matches_from(vec!["command", "set"]);

let cmds: Vec<_> = m.get_many::<String>("cmd").unwrap().collect();
assert_eq!(cmds, ["command", "set"]);

Try not to fail on parse errors, like missing option values.

NOTE: This choice is propagated to all child subcommands.

Examples
let cmd = Command::new("cmd")
  .ignore_errors(true)
  .arg(arg!(-c --config <FILE> "Sets a custom config file"))
  .arg(arg!(-x --stuff <FILE> "Sets a custom stuff file"))
  .arg(arg!(f: -f "Flag"));

let r = cmd.try_get_matches_from(vec!["cmd", "-c", "file", "-f", "-x"]);

assert!(r.is_ok(), "unexpected error: {:?}", r);
let m = r.unwrap();
assert_eq!(m.get_one::<String>("config").unwrap(), "file");
assert!(*m.get_one::<bool>("f").expect("defaulted"));
assert_eq!(m.get_one::<String>("stuff"), None);

Replace prior occurrences of arguments rather than error

For any argument that would conflict with itself by default (e.g. ArgAction::Set, it will now override itself.

This is the equivalent to saying the foo arg using Arg::overrides_with("foo") for all defined arguments.

NOTE: This choice is propagated to all child subcommands.

Disables the automatic delimiting of values after -- or when Command::trailing_var_arg was used.

NOTE: The same thing can be done manually by setting the final positional argument to Arg::value_delimiter(None). Using this setting is safer, because it’s easier to locate when making changes.

NOTE: This choice is propagated to all child subcommands.

Examples
Command::new("myprog")
    .dont_delimit_trailing_values(true)
    .get_matches();
Available on crate feature color only.

Sets when to color output.

NOTE: This choice is propagated to all child subcommands.

NOTE: Default behaviour is ColorChoice::Auto.

Examples
Command::new("myprog")
    .color(ColorChoice::Never)
    .get_matches();
Available on non-crate feature unstable-v5 or crate feature wrap_help only.

Sets the terminal width at which to wrap help messages.

Using 0 will ignore terminal widths and use source formatting.

Defaults to current terminal width when wrap_help feature flag is enabled. If the flag is disabled or it cannot be determined, the default is 100.

NOTE: This setting applies globally and not on a per-command basis.

NOTE: This requires the wrap_help feature

Examples
Command::new("myprog")
    .term_width(80)
Available on non-crate feature unstable-v5 or crate feature wrap_help only.

Limit the line length for wrapping help when using the current terminal’s width.

This only applies when term_width is unset so that the current terminal’s width will be used. See Command::term_width for more details.

Using 0 will ignore terminal widths and use source formatting (default).

NOTE: This setting applies globally and not on a per-command basis.

NOTE: This requires the wrap_help feature

Examples
Command::new("myprog")
    .max_term_width(100)

Disables -V and --version flag.

Examples
let res = Command::new("myprog")
    .disable_version_flag(true)
    .try_get_matches_from(vec![
        "myprog", "-V"
    ]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);

Specifies to use the version of the current command for all subcommands.

Defaults to false; subcommands have independent version strings from their parents.

NOTE: This choice is propagated to all child subcommands.

Examples
Command::new("myprog")
    .version("v1.1")
    .propagate_version(true)
    .subcommand(Command::new("test"))
    .get_matches();
// running `$ myprog test --version` will display
// "myprog-test v1.1"

Places the help string for all arguments and subcommands on the line after them.

NOTE: This choice is propagated to all child subcommands.

Examples
Command::new("myprog")
    .next_line_help(true)
    .get_matches();

Disables -h and --help flag.

NOTE: This choice is propagated to all child subcommands.

Examples
let res = Command::new("myprog")
    .disable_help_flag(true)
    .try_get_matches_from(vec![
        "myprog", "-h"
    ]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::UnknownArgument);

Disables the help subcommand.

Examples
let res = Command::new("myprog")
    .disable_help_subcommand(true)
    // Normally, creating a subcommand causes a `help` subcommand to automatically
    // be generated as well
    .subcommand(Command::new("test"))
    .try_get_matches_from(vec![
        "myprog", "help"
    ]);
assert!(res.is_err());
assert_eq!(res.unwrap_err().kind(), ErrorKind::InvalidSubcommand);

Disables colorized help messages.

NOTE: This choice is propagated to all child subcommands.

Examples
Command::new("myprog")
    .disable_colored_help(true)
    .get_matches();

Panic if help descriptions are omitted.

NOTE: When deriving Parser, you could instead check this at compile-time with #![deny(missing_docs)]

NOTE: This choice is propagated to all child subcommands.

Examples
Command::new("myprog")
    .help_expected(true)
    .arg(
        Arg::new("foo").help("It does foo stuff")
        // As required via `help_expected`, a help message was supplied
     )
Panics
Command::new("myapp")
    .help_expected(true)
    .arg(
        Arg::new("foo")
        // Someone forgot to put .about("...") here
        // Since the setting `help_expected` is activated, this will lead to
        // a panic (if you are in debug mode)
    )

Tells clap not to print possible values when displaying help information.

This can be useful if there are many values, or they are explained elsewhere.

To set this per argument, see Arg::hide_possible_values.

NOTE: This choice is propagated to all child subcommands.

Allow partial matches of long arguments or their aliases.

For example, to match an argument named --test, one could use --t, --te, --tes, and --test.

NOTE: The match must not be ambiguous at all in order to succeed. i.e. to match --te to --test there could not also be another argument or alias --temp because both start with --te

NOTE: This choice is propagated to all child subcommands.

Allow partial matches of subcommand names and their aliases.

For example, to match a subcommand named test, one could use t, te, tes, and test.

NOTE: The match must not be ambiguous at all in order to succeed. i.e. to match te to test there could not also be a subcommand or alias temp because both start with te

CAUTION: This setting can interfere with positional/free arguments, take care when designing CLIs which allow inferred subcommands and have potential positional/free arguments whose values could start with the same characters as subcommands. If this is the case, it’s recommended to use settings such as Command::args_conflicts_with_subcommands in conjunction with this setting.

NOTE: This choice is propagated to all child subcommands.

Examples
let m = Command::new("prog")
    .infer_subcommands(true)
    .subcommand(Command::new("test"))
    .get_matches_from(vec![
        "prog", "te"
    ]);
assert_eq!(m.subcommand_name(), Some("test"));

Command-specific Settings

These apply only to the current command and are not inherited by subcommands.

(Re)Sets the program’s name.

See Command::new for more details.

Examples
let cmd = clap::command!()
    .name("foo");

// continued logic goes here, such as `cmd.get_matches()` etc.

Overrides the runtime-determined name of the binary for help and error messages.

This should only be used when absolutely necessary, such as when the binary name for your application is misleading, or perhaps not how the user should invoke your program.

Pro-tip: When building things such as third party cargo subcommands, this setting should be used!

NOTE: This does not change or set the name of the binary file on disk. It only changes what clap thinks the name is for the purposes of error or help messages.

Examples
Command::new("My Program")
     .bin_name("my_binary")

Overrides the runtime-determined display name of the program for help and error messages.

Examples
Command::new("My Program")
     .display_name("my_program")

Sets the author(s) for the help message.

Pro-tip: Use claps convenience macro crate_authors! to automatically set your application’s author(s) to the same thing as your crate at compile time.

NOTE: A custom help_template is needed for author to show up.

Examples
Command::new("myprog")
     .author("Me, me@mymain.com")

Sets the program’s description for the short help (-h).

If Command::long_about is not specified, this message will be displayed for --help.

NOTE: Only Command::about (short format) is used in completion script generation in order to be concise.

See also crate_description!.

Examples
Command::new("myprog")
    .about("Does really amazing things for great people")
Examples found in repository?
src/builder/command.rs (line 4274)
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
    pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) {
        debug!(
            "Command::_check_help_and_version:{} expand_help_tree={}",
            self.name, expand_help_tree
        );

        self.long_help_exists = self.long_help_exists_();

        if !self.is_disable_help_flag_set() {
            debug!("Command::_check_help_and_version: Building default --help");
            let mut arg = Arg::new(Id::HELP)
                .short('h')
                .long("help")
                .action(ArgAction::Help);
            if self.long_help_exists {
                arg = arg
                    .help("Print help information (use `--help` for more detail)")
                    .long_help("Print help information (use `-h` for a summary)");
            } else {
                arg = arg.help("Print help information");
            }
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }
        if !self.is_disable_version_flag_set() {
            debug!("Command::_check_help_and_version: Building default --version");
            let arg = Arg::new(Id::VERSION)
                .short('V')
                .long("version")
                .action(ArgAction::Version)
                .help("Print version information");
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }

        if !self.is_set(AppSettings::DisableHelpSubcommand) {
            debug!("Command::_check_help_and_version: Building help subcommand");
            let help_about = "Print this message or the help of the given subcommand(s)";

            let mut help_subcmd = if expand_help_tree {
                // Slow code path to recursively clone all other subcommand subtrees under help
                let help_subcmd = Command::new("help")
                    .about(help_about)
                    .global_setting(AppSettings::DisableHelpSubcommand)
                    .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));

                let mut help_help_subcmd = Command::new("help").about(help_about);
                help_help_subcmd.version = None;
                help_help_subcmd.long_version = None;
                help_help_subcmd = help_help_subcmd
                    .setting(AppSettings::DisableHelpFlag)
                    .setting(AppSettings::DisableVersionFlag);

                help_subcmd.subcommand(help_help_subcmd)
            } else {
                Command::new("help").about(help_about).arg(
                    Arg::new("subcommand")
                        .action(ArgAction::Append)
                        .num_args(..)
                        .value_name("COMMAND")
                        .help("Print help for the subcommand(s)"),
                )
            };
            self._propagate_subcommand(&mut help_subcmd);

            // The parser acts like this is set, so let's set it so we don't falsely
            // advertise it to the user
            help_subcmd.version = None;
            help_subcmd.long_version = None;
            help_subcmd = help_subcmd
                .setting(AppSettings::DisableHelpFlag)
                .setting(AppSettings::DisableVersionFlag)
                .unset_global_setting(AppSettings::PropagateVersion);

            self.subcommands.push(help_subcmd);
        }
    }

    fn _copy_subtree_for_help(&self) -> Command {
        let mut cmd = Command::new(self.name.clone())
            .hide(self.is_hide_set())
            .global_setting(AppSettings::DisableHelpFlag)
            .global_setting(AppSettings::DisableVersionFlag)
            .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));
        if self.get_about().is_some() {
            cmd = cmd.about(self.get_about().unwrap().clone());
        }
        cmd
    }

Sets the program’s description for the long help (--help).

If Command::about is not specified, this message will be displayed for -h.

NOTE: Only Command::about (short format) is used in completion script generation in order to be concise.

Examples
Command::new("myprog")
    .long_about(
"Does really amazing things to great people. Now let's talk a little
 more in depth about how this subcommand really works. It may take about
 a few lines of text, but that's ok!")

Free-form help text for after auto-generated short help (-h).

This is often used to describe how to use the arguments, caveats to be noted, or license and contact information.

If Command::after_long_help is not specified, this message will be displayed for --help.

Examples
Command::new("myprog")
    .after_help("Does really amazing things for great people... but be careful with -R!")

Free-form help text for after auto-generated long help (--help).

This is often used to describe how to use the arguments, caveats to be noted, or license and contact information.

If Command::after_help is not specified, this message will be displayed for -h.

Examples
Command::new("myprog")
    .after_long_help("Does really amazing things to great people... but be careful with -R, \
                     like, for real, be careful with this!")

Free-form help text for before auto-generated short help (-h).

This is often used for header, copyright, or license information.

If Command::before_long_help is not specified, this message will be displayed for --help.

Examples
Command::new("myprog")
    .before_help("Some info I'd like to appear before the help info")

Free-form help text for before auto-generated long help (--help).

This is often used for header, copyright, or license information.

If Command::before_help is not specified, this message will be displayed for -h.

Examples
Command::new("myprog")
    .before_long_help("Some verbose and long info I'd like to appear before the help info")

Sets the version for the short version (-V) and help messages.

If Command::long_version is not specified, this message will be displayed for --version.

Pro-tip: Use claps convenience macro crate_version! to automatically set your application’s version to the same thing as your crate at compile time.

Examples
Command::new("myprog")
    .version("v0.1.24")

Sets the version for the long version (--version) and help messages.

If Command::version is not specified, this message will be displayed for -V.

Pro-tip: Use claps convenience macro crate_version! to automatically set your application’s version to the same thing as your crate at compile time.

Examples
Command::new("myprog")
    .long_version(
"v0.1.24
 commit: abcdef89726d
 revision: 123
 release: 2
 binary: myprog")

Overrides the clap generated usage string for help and error messages.

NOTE: Using this setting disables claps “context-aware” usage strings. After this setting is set, this will be the only usage string displayed to the user!

NOTE: Multiple usage lines may be present in the usage argument, but some rules need to be followed to ensure the usage lines are formatted correctly by the default help formatter:

  • Do not indent the first usage line.
  • Indent all subsequent usage lines with seven spaces.
  • The last line must not end with a newline.
Examples
Command::new("myprog")
    .override_usage("myapp [-clDas] <some_file>")

Or for multiple usage lines:

Command::new("myprog")
    .override_usage(
        "myapp -X [-a] [-b] <file>\n       \
         myapp -Y [-c] <file1> <file2>\n       \
         myapp -Z [-d|-e]"
    )

Overrides the clap generated help message (both -h and --help).

This should only be used when the auto-generated message does not suffice.

NOTE: This only replaces the help message for the current command, meaning if you are using subcommands, those help messages will still be auto-generated unless you specify a Command::override_help for them as well.

Examples
Command::new("myapp")
    .override_help("myapp v1.0\n\
           Does awesome things\n\
           (C) me@mail.com\n\n\

           Usage: myapp <opts> <command>\n\n\

           Options:\n\
           -h, --help       Display this message\n\
           -V, --version    Display version info\n\
           -s <stuff>       Do something with stuff\n\
           -v               Be verbose\n\n\

           Commands:\n\
           help             Print this message\n\
           work             Do some work")
Available on crate feature help only.

Sets the help template to be used, overriding the default format.

NOTE: The template system is by design very simple. Therefore, the tags have to be written in the lowercase and without spacing.

Tags are given inside curly brackets.

Valid tags are:

  • {name} - Display name for the (sub-)command.
  • {bin} - Binary name.
  • {version} - Version number.
  • {author} - Author information.
  • {author-with-newline} - Author followed by \n.
  • {author-section} - Author preceded and followed by \n.
  • {about} - General description (from Command::about or Command::long_about).
  • {about-with-newline} - About followed by \n.
  • {about-section} - About preceded and followed by ‘\n’.
  • {usage-heading} - Automatically generated usage heading.
  • {usage} - Automatically generated or given usage string.
  • {all-args} - Help for all arguments (options, flags, positional arguments, and subcommands) including titles.
  • {options} - Help for options.
  • {positionals} - Help for positional arguments.
  • {subcommands} - Help for subcommands.
  • {tag} - Standard tab sized used within clap
  • {after-help} - Help from Command::after_help or Command::after_long_help.
  • {before-help} - Help from Command::before_help or Command::before_long_help.
Examples

For a very brief help:

Command::new("myprog")
    .version("1.0")
    .help_template("{bin} ({version}) - {usage}")

For showing more application context:

Command::new("myprog")
    .version("1.0")
    .help_template("\
{before-help}{name} {version}
{author-with-newline}{about-with-newline}
{usage-heading} {usage}

{all-args}{after-help}
")

Set the default section heading for future args.

This will be used for any arg that hasn’t had Arg::help_heading called.

This is useful if the default Options or Arguments headings are not specific enough for one’s use case.

For subcommands, see Command::subcommand_help_heading

Change the starting value for assigning future display orders for ags.

This will be used for any arg that hasn’t had Arg::display_order called.

Available on crate feature unstable-replace only.

Replaces an argument or subcommand used on the CLI at runtime with other arguments or subcommands.

Note: This is gated behind unstable-replace

When this method is used, name is removed from the CLI, and target is inserted in its place. Parsing continues as if the user typed target instead of name.

This can be used to create “shortcuts” for subcommands, or if a particular argument has the semantic meaning of several other specific arguments and values.

Examples

We’ll start with the “subcommand short” example. In this example, let’s assume we have a program with a subcommand module which can be invoked via cmd module. Now let’s also assume module also has a subcommand called install which can be invoked cmd module install. If for some reason users needed to be able to reach cmd module install via the short-hand cmd install, we’d have several options.

We could create another sibling subcommand to module called install, but then we would need to manage another subcommand and manually dispatch to cmd module install handling code. This is error prone and tedious.

We could instead use Command::replace so that, when the user types cmd install, clap will replace install with module install which will end up getting parsed as if the user typed the entire incantation.

let m = Command::new("cmd")
    .subcommand(Command::new("module")
        .subcommand(Command::new("install")))
    .replace("install", &["module", "install"])
    .get_matches_from(vec!["cmd", "install"]);

assert!(m.subcommand_matches("module").is_some());
assert!(m.subcommand_matches("module").unwrap().subcommand_matches("install").is_some());

Now let’s show an argument example!

Let’s assume we have an application with two flags --save-context and --save-runtime. But often users end up needing to do both at the same time. We can add a third flag --save-all which semantically means the same thing as cmd --save-context --save-runtime. To implement that, we have several options.

We could create this third argument and manually check if that argument and in our own consumer code handle the fact that both --save-context and --save-runtime should have been used. But again this is error prone and tedious. If we had code relying on checking --save-context and we forgot to update that code to also check --save-all it’d mean an error!

Luckily we can use Command::replace so that when the user types --save-all, clap will replace that argument with --save-context --save-runtime, and parsing will continue like normal. Now all our code that was originally checking for things like --save-context doesn’t need to change!

let m = Command::new("cmd")
    .arg(Arg::new("save-context")
        .long("save-context")
        .action(ArgAction::SetTrue))
    .arg(Arg::new("save-runtime")
        .long("save-runtime")
        .action(ArgAction::SetTrue))
    .replace("--save-all", &["--save-context", "--save-runtime"])
    .get_matches_from(vec!["cmd", "--save-all"]);

assert!(*m.get_one::<bool>("save-context").expect("defaulted by clap"));
assert!(*m.get_one::<bool>("save-runtime").expect("defaulted by clap"));

This can also be used with options, for example if our application with --save-* above also had a --format=TYPE option. Let’s say it accepted txt or json values. However, when --save-all is used, only --format=json is allowed, or valid. We could change the example above to enforce this:

let m = Command::new("cmd")
    .arg(Arg::new("save-context")
        .long("save-context")
        .action(ArgAction::SetTrue))
    .arg(Arg::new("save-runtime")
        .long("save-runtime")
        .action(ArgAction::SetTrue))
    .arg(Arg::new("format")
        .long("format")
        .action(ArgAction::Set)
        .value_parser(["txt", "json"]))
    .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"])
    .get_matches_from(vec!["cmd", "--save-all"]);

assert!(*m.get_one::<bool>("save-context").expect("defaulted by clap"));
assert!(*m.get_one::<bool>("save-runtime").expect("defaulted by clap"));
assert_eq!(m.get_one::<String>("format").unwrap(), "json");

Exit gracefully if no arguments are present (e.g. $ myprog).

NOTE: subcommands count as arguments

Examples
Command::new("myprog")
    .arg_required_else_help(true);

Allows one to implement two styles of CLIs where positionals can be used out of order.

The first example is a CLI where the second to last positional argument is optional, but the final positional argument is required. Such as $ prog [optional] <required> where one of the two following usages is allowed:

  • $ prog [optional] <required>
  • $ prog <required>

This would otherwise not be allowed. This is useful when [optional] has a default value.

Note: when using this style of “missing positionals” the final positional must be required if -- will not be used to skip to the final positional argument.

Note: This style also only allows a single positional argument to be “skipped” without the use of --. To skip more than one, see the second example.

The second example is when one wants to skip multiple optional positional arguments, and use of the -- operator is OK (but not required if all arguments will be specified anyways).

For example, imagine a CLI which has three positional arguments [foo] [bar] [baz]... where baz accepts multiple values (similar to man ARGS... style training arguments).

With this setting the following invocations are posisble:

  • $ prog foo bar baz1 baz2 baz3
  • $ prog foo -- baz1 baz2 baz3
  • $ prog -- baz1 baz2 baz3
Examples

Style number one from above:

// Assume there is an external subcommand named "subcmd"
let m = Command::new("myprog")
    .allow_missing_positional(true)
    .arg(Arg::new("arg1"))
    .arg(Arg::new("arg2")
        .required(true))
    .get_matches_from(vec![
        "prog", "other"
    ]);

assert_eq!(m.get_one::<String>("arg1"), None);
assert_eq!(m.get_one::<String>("arg2").unwrap(), "other");

Now the same example, but using a default value for the first optional positional argument

// Assume there is an external subcommand named "subcmd"
let m = Command::new("myprog")
    .allow_missing_positional(true)
    .arg(Arg::new("arg1")
        .default_value("something"))
    .arg(Arg::new("arg2")
        .required(true))
    .get_matches_from(vec![
        "prog", "other"
    ]);

assert_eq!(m.get_one::<String>("arg1").unwrap(), "something");
assert_eq!(m.get_one::<String>("arg2").unwrap(), "other");

Style number two from above:

// Assume there is an external subcommand named "subcmd"
let m = Command::new("myprog")
    .allow_missing_positional(true)
    .arg(Arg::new("foo"))
    .arg(Arg::new("bar"))
    .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..))
    .get_matches_from(vec![
        "prog", "foo", "bar", "baz1", "baz2", "baz3"
    ]);

assert_eq!(m.get_one::<String>("foo").unwrap(), "foo");
assert_eq!(m.get_one::<String>("bar").unwrap(), "bar");
assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);

Now nofice if we don’t specify foo or baz but use the -- operator.

// Assume there is an external subcommand named "subcmd"
let m = Command::new("myprog")
    .allow_missing_positional(true)
    .arg(Arg::new("foo"))
    .arg(Arg::new("bar"))
    .arg(Arg::new("baz").action(ArgAction::Set).num_args(1..))
    .get_matches_from(vec![
        "prog", "--", "baz1", "baz2", "baz3"
    ]);

assert_eq!(m.get_one::<String>("foo"), None);
assert_eq!(m.get_one::<String>("bar"), None);
assert_eq!(m.get_many::<String>("baz").unwrap().collect::<Vec<_>>(), &["baz1", "baz2", "baz3"]);

Sets the short version of the subcommand flag without the preceding -.

Allows the subcommand to be used as if it were an Arg::short.

Examples
let matches = Command::new("pacman")
    .subcommand(
        Command::new("sync").short_flag('S').arg(
            Arg::new("search")
                .short('s')
                .long("search")
                .action(ArgAction::SetTrue)
                .help("search remote repositories for matching strings"),
        ),
    )
    .get_matches_from(vec!["pacman", "-Ss"]);

assert_eq!(matches.subcommand_name().unwrap(), "sync");
let sync_matches = matches.subcommand_matches("sync").unwrap();
assert!(*sync_matches.get_one::<bool>("search").expect("defaulted by clap"));

Sets the long version of the subcommand flag without the preceding --.

Allows the subcommand to be used as if it were an Arg::long.

NOTE: Any leading - characters will be stripped.

Examples

To set long_flag use a word containing valid UTF-8 codepoints. If you supply a double leading -- such as --sync they will be stripped. Hyphens in the middle of the word; however, will not be stripped (i.e. sync-file is allowed).

let matches = Command::new("pacman")
    .subcommand(
        Command::new("sync").long_flag("sync").arg(
            Arg::new("search")
                .short('s')
                .long("search")
                .action(ArgAction::SetTrue)
                .help("search remote repositories for matching strings"),
        ),
    )
    .get_matches_from(vec!["pacman", "--sync", "--search"]);

assert_eq!(matches.subcommand_name().unwrap(), "sync");
let sync_matches = matches.subcommand_matches("sync").unwrap();
assert!(*sync_matches.get_one::<bool>("search").expect("defaulted by clap"));

Sets a hidden alias to this subcommand.

This allows the subcommand to be accessed via either the original name, or this given alias. This is more efficient and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all aliased variants.

NOTE: Aliases defined with this method are hidden from the help message. If you’re looking for aliases that will be displayed in the help message, see Command::visible_alias.

NOTE: When using aliases and checking for the existence of a particular subcommand within an ArgMatches struct, one only needs to search for the original name and not all aliases.

Examples
let m = Command::new("myprog")
    .subcommand(Command::new("test")
        .alias("do-stuff"))
    .get_matches_from(vec!["myprog", "do-stuff"]);
assert_eq!(m.subcommand_name(), Some("test"));

Add an alias, which functions as “hidden” short flag subcommand

This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.

Examples
let m = Command::new("myprog")
            .subcommand(Command::new("test").short_flag('t')
                .short_flag_alias('d'))
            .get_matches_from(vec!["myprog", "-d"]);
assert_eq!(m.subcommand_name(), Some("test"));

Add an alias, which functions as a “hidden” long flag subcommand.

This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.

Examples
let m = Command::new("myprog")
            .subcommand(Command::new("test").long_flag("test")
                .long_flag_alias("testing"))
            .get_matches_from(vec!["myprog", "--testing"]);
assert_eq!(m.subcommand_name(), Some("test"));
Examples found in repository?
src/builder/command.rs (line 2414)
2412
2413
2414
2415
2416
2417
    pub fn long_flag_aliases(mut self, names: impl IntoIterator<Item = impl Into<Str>>) -> Self {
        for s in names {
            self = self.long_flag_alias(s)
        }
        self
    }

Sets multiple hidden aliases to this subcommand.

This allows the subcommand to be accessed via either the original name or any of the given aliases. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command and not all aliased variants.

NOTE: Aliases defined with this method are hidden from the help message. If looking for aliases that will be displayed in the help message, see Command::visible_aliases.

NOTE: When using aliases and checking for the existence of a particular subcommand within an ArgMatches struct, one only needs to search for the original name and not all aliases.

Examples
let m = Command::new("myprog")
    .subcommand(Command::new("test")
        .aliases(["do-stuff", "do-tests", "tests"]))
        .arg(Arg::new("input")
            .help("the file to add")
            .required(false))
    .get_matches_from(vec!["myprog", "do-tests"]);
assert_eq!(m.subcommand_name(), Some("test"));

Add aliases, which function as “hidden” short flag subcommands.

These will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.

Examples
let m = Command::new("myprog")
    .subcommand(Command::new("test").short_flag('t')
        .short_flag_aliases(['a', 'b', 'c']))
        .arg(Arg::new("input")
            .help("the file to add")
            .required(false))
    .get_matches_from(vec!["myprog", "-a"]);
assert_eq!(m.subcommand_name(), Some("test"));

Add aliases, which function as “hidden” long flag subcommands.

These will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.

Examples
let m = Command::new("myprog")
            .subcommand(Command::new("test").long_flag("test")
                .long_flag_aliases(["testing", "testall", "test_all"]))
                .arg(Arg::new("input")
                            .help("the file to add")
                            .required(false))
            .get_matches_from(vec!["myprog", "--testing"]);
assert_eq!(m.subcommand_name(), Some("test"));

Sets a visible alias to this subcommand.

This allows the subcommand to be accessed via either the original name or the given alias. This is more efficient and easier than creating hidden subcommands as one only needs to check for the existence of this command and not all aliased variants.

NOTE: The alias defined with this method is visible from the help message and displayed as if it were just another regular subcommand. If looking for an alias that will not be displayed in the help message, see Command::alias.

NOTE: When using aliases and checking for the existence of a particular subcommand within an ArgMatches struct, one only needs to search for the original name and not all aliases.

Examples
let m = Command::new("myprog")
    .subcommand(Command::new("test")
        .visible_alias("do-stuff"))
    .get_matches_from(vec!["myprog", "do-stuff"]);
assert_eq!(m.subcommand_name(), Some("test"));

Add an alias, which functions as “visible” short flag subcommand

This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.

See also Command::short_flag_alias.

Examples
let m = Command::new("myprog")
            .subcommand(Command::new("test").short_flag('t')
                .visible_short_flag_alias('d'))
            .get_matches_from(vec!["myprog", "-d"]);
assert_eq!(m.subcommand_name(), Some("test"));

Add an alias, which functions as a “visible” long flag subcommand.

This will automatically dispatch as if this subcommand was used. This is more efficient, and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command, and not all variants.

See also Command::long_flag_alias.

Examples
let m = Command::new("myprog")
            .subcommand(Command::new("test").long_flag("test")
                .visible_long_flag_alias("testing"))
            .get_matches_from(vec!["myprog", "--testing"]);
assert_eq!(m.subcommand_name(), Some("test"));
Examples found in repository?
src/builder/command.rs (line 2594)
2589
2590
2591
2592
2593
2594
2595
2596
2597
    pub fn visible_long_flag_aliases(
        mut self,
        names: impl IntoIterator<Item = impl Into<Str>>,
    ) -> Self {
        for s in names {
            self = self.visible_long_flag_alias(s);
        }
        self
    }

Sets multiple visible aliases to this subcommand.

This allows the subcommand to be accessed via either the original name or any of the given aliases. This is more efficient and easier than creating multiple hidden subcommands as one only needs to check for the existence of this command and not all aliased variants.

NOTE: The alias defined with this method is visible from the help message and displayed as if it were just another regular subcommand. If looking for an alias that will not be displayed in the help message, see Command::alias.

NOTE: When using aliases, and checking for the existence of a particular subcommand within an ArgMatches struct, one only needs to search for the original name and not all aliases.

Examples
let m = Command::new("myprog")
    .subcommand(Command::new("test")
        .visible_aliases(["do-stuff", "tests"]))
    .get_matches_from(vec!["myprog", "do-stuff"]);
assert_eq!(m.subcommand_name(), Some("test"));

Add aliases, which function as visible short flag subcommands.

See Command::short_flag_aliases.

Examples
let m = Command::new("myprog")
            .subcommand(Command::new("test").short_flag('b')
                .visible_short_flag_aliases(['t']))
            .get_matches_from(vec!["myprog", "-t"]);
assert_eq!(m.subcommand_name(), Some("test"));

Add aliases, which function as visible long flag subcommands.

See Command::long_flag_aliases.

Examples
let m = Command::new("myprog")
            .subcommand(Command::new("test").long_flag("test")
                .visible_long_flag_aliases(["testing", "testall", "test_all"]))
            .get_matches_from(vec!["myprog", "--testing"]);
assert_eq!(m.subcommand_name(), Some("test"));

Set the placement of this subcommand within the help.

Subcommands with a lower value will be displayed first in the help message. Subcommands with duplicate display orders will be displayed in alphabetical order.

This is helpful when one would like to emphasize frequently used subcommands, or prioritize those towards the top of the list.

NOTE: The default is 999 for all subcommands.

Examples
let m = Command::new("cust-ord")
   .subcommand(Command::new("alpha") // typically subcommands are grouped
                                              // alphabetically by name. Subcommands
                                              // without a display_order have a value of
                                              // 999 and are displayed alphabetically with
                                              // all other 999 subcommands
       .about("Some help and text"))
   .subcommand(Command::new("beta")
       .display_order(1)   // In order to force this subcommand to appear *first*
                           // all we have to do is give it a value lower than 999.
                           // Any other subcommands with a value of 1 will be displayed
                           // alphabetically with this one...then 2 values, then 3, etc.
       .about("I should be first!"))
   .get_matches_from(vec![
       "cust-ord", "--help"
   ]);

The above example displays the following help message

cust-ord

Usage: cust-ord [OPTIONS]

Commands:
    beta    I should be first!
    alpha   Some help and text

Options:
    -h, --help       Print help information
    -V, --version    Print version information

Specifies that this subcommand should be hidden from help messages

Examples
Command::new("myprog")
    .subcommand(
        Command::new("test").hide(true)
    )
Examples found in repository?
src/builder/command.rs (line 4312)
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
    fn _copy_subtree_for_help(&self) -> Command {
        let mut cmd = Command::new(self.name.clone())
            .hide(self.is_hide_set())
            .global_setting(AppSettings::DisableHelpFlag)
            .global_setting(AppSettings::DisableVersionFlag)
            .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));
        if self.get_about().is_some() {
            cmd = cmd.about(self.get_about().unwrap().clone());
        }
        cmd
    }

If no subcommand is present at runtime, error and exit gracefully.

Examples
let err = Command::new("myprog")
    .subcommand_required(true)
    .subcommand(Command::new("test"))
    .try_get_matches_from(vec![
        "myprog",
    ]);
assert!(err.is_err());
assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingSubcommand);

Assume unexpected positional arguments are a subcommand.

Arguments will be stored in the "" argument in the ArgMatches

NOTE: Use this setting with caution, as a truly unexpected argument (i.e. one that is NOT an external subcommand) will not cause an error and instead be treated as a potential subcommand. One should check for such cases manually and inform the user appropriately.

NOTE: A built-in subcommand will be parsed as an external subcommand when escaped with --.

Examples
// Assume there is an external subcommand named "subcmd"
let m = Command::new("myprog")
    .allow_external_subcommands(true)
    .get_matches_from(vec![
        "myprog", "subcmd", "--option", "value", "-fff", "--flag"
    ]);

// All trailing arguments will be stored under the subcommand's sub-matches using an empty
// string argument name
match m.subcommand() {
    Some((external, ext_m)) => {
         let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect();
         assert_eq!(external, "subcmd");
         assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
    },
    _ => {},
}

Specifies how to parse external subcommand arguments.

The default parser is for OsString. This can be used to switch it to String or another type.

NOTE: Setting this requires Command::allow_external_subcommands

Examples
// Assume there is an external subcommand named "subcmd"
let m = Command::new("myprog")
   .allow_external_subcommands(true)
   .get_matches_from(vec![
       "myprog", "subcmd", "--option", "value", "-fff", "--flag"
   ]);

// All trailing arguments will be stored under the subcommand's sub-matches using an empty
// string argument name
match m.subcommand() {
   Some((external, ext_m)) => {
        let ext_args: Vec<_> = ext_m.get_many::<OsString>("").unwrap().collect();
        assert_eq!(external, "subcmd");
        assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
   },
   _ => {},
}
// Assume there is an external subcommand named "subcmd"
let m = Command::new("myprog")
    .external_subcommand_value_parser(value_parser!(String))
    .get_matches_from(vec![
        "myprog", "subcmd", "--option", "value", "-fff", "--flag"
    ]);

// All trailing arguments will be stored under the subcommand's sub-matches using an empty
// string argument name
match m.subcommand() {
    Some((external, ext_m)) => {
         let ext_args: Vec<_> = ext_m.get_many::<String>("").unwrap().collect();
         assert_eq!(external, "subcmd");
         assert_eq!(ext_args, ["--option", "value", "-fff", "--flag"]);
    },
    _ => {},
}

Specifies that use of an argument prevents the use of subcommands.

By default clap allows arguments between subcommands such as <cmd> [cmd_args] <subcmd> [subcmd_args] <subsubcmd> [subsubcmd_args].

This setting disables that functionality and says that arguments can only follow the final subcommand. For instance using this setting makes only the following invocations possible:

  • <cmd> <subcmd> <subsubcmd> [subsubcmd_args]
  • <cmd> <subcmd> [subcmd_args]
  • <cmd> [cmd_args]
Examples
Command::new("myprog")
    .args_conflicts_with_subcommands(true);

Prevent subcommands from being consumed as an arguments value.

By default, if an option taking multiple values is followed by a subcommand, the subcommand will be parsed as another value.

cmd --foo val1 val2 subcommand
          --------- ----------
            values   another value

This setting instructs the parser to stop when encountering a subcommand instead of greedily consuming arguments.

cmd --foo val1 val2 subcommand
          --------- ----------
            values   subcommand
Examples
let cmd = Command::new("cmd").subcommand(Command::new("sub")).arg(
    Arg::new("arg")
        .long("arg")
        .num_args(1..)
        .action(ArgAction::Set),
);

let matches = cmd
    .clone()
    .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
    .unwrap();
assert_eq!(
    matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(),
    &["1", "2", "3", "sub"]
);
assert!(matches.subcommand_matches("sub").is_none());

let matches = cmd
    .subcommand_precedence_over_arg(true)
    .try_get_matches_from(&["cmd", "--arg", "1", "2", "3", "sub"])
    .unwrap();
assert_eq!(
    matches.get_many::<String>("arg").unwrap().collect::<Vec<_>>(),
    &["1", "2", "3"]
);
assert!(matches.subcommand_matches("sub").is_some());

Allows subcommands to override all requirements of the parent command.

For example, if you had a subcommand or top level application with a required argument that is only required as long as there is no subcommand present, using this setting would allow you to set those arguments to Arg::required(true) and yet receive no error so long as the user uses a valid subcommand instead.

NOTE: This defaults to false (using subcommand does not negate requirements)

Examples

This first example shows that it is an error to not use a required argument

let err = Command::new("myprog")
    .subcommand_negates_reqs(true)
    .arg(Arg::new("opt").required(true))
    .subcommand(Command::new("test"))
    .try_get_matches_from(vec![
        "myprog"
    ]);
assert!(err.is_err());
assert_eq!(err.unwrap_err().kind(), ErrorKind::MissingRequiredArgument);

This next example shows that it is no longer error to not use a required argument if a valid subcommand is used.

let noerr = Command::new("myprog")
    .subcommand_negates_reqs(true)
    .arg(Arg::new("opt").required(true))
    .subcommand(Command::new("test"))
    .try_get_matches_from(vec![
        "myprog", "test"
    ]);
assert!(noerr.is_ok());

Multiple-personality program dispatched on the binary name (argv[0])

A “multicall” executable is a single executable that contains a variety of applets, and decides which applet to run based on the name of the file. The executable can be called from different names by creating hard links or symbolic links to it.

This is desirable for:

  • Easy distribution, a single binary that can install hardlinks to access the different personalities.
  • Minimal binary size by sharing common code (e.g. standard library, clap)
  • Custom shells or REPLs where there isn’t a single top-level command

Setting multicall will cause

  • argv[0] to be stripped to the base name and parsed as the first argument, as if Command::no_binary_name was set.
  • Help and errors to report subcommands as if they were the top-level command

When the subcommand is not present, there are several strategies you may employ, depending on your needs:

  • Let the error percolate up normally
  • Print a specialized error message using the Error::context
  • Print the help but this might be ambiguous
  • Disable multicall and re-parse it
  • Disable multicall and re-parse it with a specific subcommand

When detecting the error condition, the ErrorKind isn’t sufficient as a sub-subcommand might report the same error. Enable allow_external_subcommands if you want to specifically get the unrecognized binary name.

NOTE: Multicall can’t be used with no_binary_name since they interpret the command name in incompatible ways.

NOTE: The multicall command cannot have arguments.

NOTE: Applets are slightly semantically different from subcommands, so it’s recommended to use Command::subcommand_help_heading and Command::subcommand_value_name to change the descriptive text as above.

Examples

hostname is an example of a multicall executable. Both hostname and dnsdomainname are provided by the same executable and which behaviour to use is based on the executable file name.

This is desirable when the executable has a primary purpose but there is related functionality that would be convenient to provide and implement it to be in the same executable.

The name of the cmd is essentially unused and may be the same as the name of a subcommand.

The names of the immediate subcommands of the Command are matched against the basename of the first argument, which is conventionally the path of the executable.

This does not allow the subcommand to be passed as the first non-path argument.

let mut cmd = Command::new("hostname")
    .multicall(true)
    .subcommand(Command::new("hostname"))
    .subcommand(Command::new("dnsdomainname"));
let m = cmd.try_get_matches_from_mut(&["/usr/bin/hostname", "dnsdomainname"]);
assert!(m.is_err());
assert_eq!(m.unwrap_err().kind(), ErrorKind::UnknownArgument);
let m = cmd.get_matches_from(&["/usr/bin/dnsdomainname"]);
assert_eq!(m.subcommand_name(), Some("dnsdomainname"));

Busybox is another common example of a multicall executable with a subcommmand for each applet that can be run directly, e.g. with the cat applet being run by running busybox cat, or with cat as a link to the busybox binary.

This is desirable when the launcher program has additional options or it is useful to run the applet without installing a symlink e.g. to test the applet without installing it or there may already be a command of that name installed.

To make an applet usable as both a multicall link and a subcommand the subcommands must be defined both in the top-level Command and as subcommands of the “main” applet.

fn applet_commands() -> [Command; 2] {
    [Command::new("true"), Command::new("false")]
}
let mut cmd = Command::new("busybox")
    .multicall(true)
    .subcommand(
        Command::new("busybox")
            .subcommand_value_name("APPLET")
            .subcommand_help_heading("APPLETS")
            .subcommands(applet_commands()),
    )
    .subcommands(applet_commands());
// When called from the executable's canonical name
// its applets can be matched as subcommands.
let m = cmd.try_get_matches_from_mut(&["/usr/bin/busybox", "true"]).unwrap();
assert_eq!(m.subcommand_name(), Some("busybox"));
assert_eq!(m.subcommand().unwrap().1.subcommand_name(), Some("true"));
// When called from a link named after an applet that applet is matched.
let m = cmd.get_matches_from(&["/usr/bin/true"]);
assert_eq!(m.subcommand_name(), Some("true"));

Sets the value name used for subcommands when printing usage and help.

By default, this is “COMMAND”.

See also Command::subcommand_help_heading

Examples
Command::new("myprog")
    .subcommand(Command::new("sub1"))
    .print_help()

will produce

myprog

Usage: myprog [COMMAND]

Commands:
    help    Print this message or the help of the given subcommand(s)
    sub1

Options:
    -h, --help       Print help information
    -V, --version    Print version information

but usage of subcommand_value_name

Command::new("myprog")
    .subcommand(Command::new("sub1"))
    .subcommand_value_name("THING")
    .print_help()

will produce

myprog

Usage: myprog [THING]

Commands:
    help    Print this message or the help of the given subcommand(s)
    sub1

Options:
    -h, --help       Print help information
    -V, --version    Print version information

Sets the help heading used for subcommands when printing usage and help.

By default, this is “Commands”.

See also Command::subcommand_value_name

Examples
Command::new("myprog")
    .subcommand(Command::new("sub1"))
    .print_help()

will produce

myprog

Usage: myprog [COMMAND]

Commands:
    help    Print this message or the help of the given subcommand(s)
    sub1

Options:
    -h, --help       Print help information
    -V, --version    Print version information

but usage of subcommand_help_heading

Command::new("myprog")
    .subcommand(Command::new("sub1"))
    .subcommand_help_heading("Things")
    .print_help()

will produce

myprog

Usage: myprog [COMMAND]

Things:
    help    Print this message or the help of the given subcommand(s)
    sub1

Options:
    -h, --help       Print help information
    -V, --version    Print version information

Get the name of the binary.

Examples found in repository?
src/output/help_template.rs (line 227)
221
222
223
224
225
226
227
228
229
230
231
232
233
    fn write_display_name(&mut self) {
        debug!("HelpTemplate::write_display_name");

        let display_name = wrap(
            &self
                .cmd
                .get_display_name()
                .unwrap_or_else(|| self.cmd.get_name())
                .replace("{n}", "\n"),
            self.term_w,
        );
        self.none(&display_name);
    }
More examples
Hide additional examples
src/builder/command.rs (line 4336)
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
    pub(crate) fn _render_version(&self, use_long: bool) -> String {
        debug!("Command::_render_version");

        let ver = if use_long {
            self.long_version
                .as_deref()
                .or(self.version.as_deref())
                .unwrap_or_default()
        } else {
            self.version
                .as_deref()
                .or(self.long_version.as_deref())
                .unwrap_or_default()
        };
        let display_name = self.get_display_name().unwrap_or_else(|| self.get_name());
        format!("{} {}\n", display_name, ver)
    }

Get the name of the binary.

Examples found in repository?
src/output/help_template.rs (line 239)
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
    fn write_bin_name(&mut self) {
        debug!("HelpTemplate::write_bin_name");

        let bin_name = if let Some(bn) = self.cmd.get_bin_name() {
            if bn.contains(' ') {
                // In case we're dealing with subcommands i.e. git mv is translated to git-mv
                bn.replace(' ', "-")
            } else {
                wrap(&self.cmd.get_name().replace("{n}", "\n"), self.term_w)
            }
        } else {
            wrap(&self.cmd.get_name().replace("{n}", "\n"), self.term_w)
        };
        self.none(&bin_name);
    }
More examples
Hide additional examples
src/output/usage.rs (line 79)
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
    fn create_help_usage(&self, incl_reqs: bool) -> StyledStr {
        debug!("Usage::create_help_usage; incl_reqs={:?}", incl_reqs);
        let mut styled = StyledStr::new();
        let name = self
            .cmd
            .get_usage_name()
            .or_else(|| self.cmd.get_bin_name())
            .unwrap_or_else(|| self.cmd.get_name());
        styled.literal(name);

        if self.needs_options_tag() {
            styled.placeholder(" [OPTIONS]");
        }

        self.write_args(&[], !incl_reqs, &mut styled);

        // incl_reqs is only false when this function is called recursively
        if self.cmd.has_visible_subcommands() && incl_reqs
            || self.cmd.is_allow_external_subcommands_set()
        {
            let placeholder = self
                .cmd
                .get_subcommand_value_name()
                .unwrap_or(DEFAULT_SUB_VALUE_NAME);
            if self.cmd.is_subcommand_negates_reqs_set()
                || self.cmd.is_args_conflicts_with_subcommands_set()
            {
                styled.none("\n");
                styled.none("       ");
                if self.cmd.is_args_conflicts_with_subcommands_set() {
                    // Short-circuit full usage creation since no args will be relevant
                    styled.literal(name);
                } else {
                    styled.extend(self.create_help_usage(false).into_iter());
                }
                styled.placeholder(" <");
                styled.placeholder(placeholder);
                styled.placeholder(">");
            } else if self.cmd.is_subcommand_required_set() {
                styled.placeholder(" <");
                styled.placeholder(placeholder);
                styled.placeholder(">");
            } else {
                styled.placeholder(" [");
                styled.placeholder(placeholder);
                styled.placeholder("]");
            }
        }
        styled.trim();
        debug!("Usage::create_help_usage: usage={}", styled);
        styled
    }

    // Creates a context aware usage string, or "smart usage" from currently used
    // args, and requirements
    fn create_smart_usage(&self, used: &[Id]) -> StyledStr {
        debug!("Usage::create_smart_usage");
        let mut styled = StyledStr::new();

        styled.literal(
            self.cmd
                .get_usage_name()
                .or_else(|| self.cmd.get_bin_name())
                .unwrap_or_else(|| self.cmd.get_name()),
        );

        self.write_args(used, false, &mut styled);

        if self.cmd.is_subcommand_required_set() {
            styled.placeholder(" <");
            styled.placeholder(
                self.cmd
                    .get_subcommand_value_name()
                    .unwrap_or(DEFAULT_SUB_VALUE_NAME),
            );
            styled.placeholder(">");
        }
        styled
    }
src/parser/parser.rs (line 516)
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
    fn match_arg_error(
        &self,
        arg_os: &clap_lex::ParsedArg<'_>,
        valid_arg_found: bool,
        trailing_values: bool,
    ) -> ClapError {
        // If argument follows a `--`
        if trailing_values {
            // If the arg matches a subcommand name, or any of its aliases (if defined)
            if self
                .possible_subcommand(arg_os.to_value(), valid_arg_found)
                .is_some()
            {
                return ClapError::unnecessary_double_dash(
                    self.cmd,
                    arg_os.display().to_string(),
                    Usage::new(self.cmd).create_usage_with_title(&[]),
                );
            }
        }

        let candidates = suggestions::did_you_mean(
            &arg_os.display().to_string(),
            self.cmd.all_subcommand_names(),
        );
        // If the argument looks like a subcommand.
        if !candidates.is_empty() {
            return ClapError::invalid_subcommand(
                self.cmd,
                arg_os.display().to_string(),
                candidates,
                self.cmd
                    .get_bin_name()
                    .unwrap_or_else(|| self.cmd.get_name())
                    .to_owned(),
                Usage::new(self.cmd).create_usage_with_title(&[]),
            );
        }

        // If the argument must be a subcommand.
        if self.cmd.has_subcommands()
            && (!self.cmd.has_positionals() || self.cmd.is_infer_subcommands_set())
        {
            return ClapError::unrecognized_subcommand(
                self.cmd,
                arg_os.display().to_string(),
                Usage::new(self.cmd).create_usage_with_title(&[]),
            );
        }

        let suggested_trailing_arg = !trailing_values
            && self.cmd.has_positionals()
            && (arg_os.is_long() || arg_os.is_short());
        ClapError::unknown_argument(
            self.cmd,
            arg_os.display().to_string(),
            None,
            suggested_trailing_arg,
            Usage::new(self.cmd).create_usage_with_title(&[]),
        )
    }
src/parser/validator.rs (line 68)
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
    pub(crate) fn validate(
        &mut self,
        parse_state: ParseState,
        matcher: &mut ArgMatcher,
    ) -> ClapResult<()> {
        debug!("Validator::validate");
        let mut conflicts = Conflicts::new();
        let has_subcmd = matcher.subcommand_name().is_some();

        if let ParseState::Opt(a) = parse_state {
            debug!("Validator::validate: needs_val_of={:?}", a);

            let o = &self.cmd[&a];
            let should_err = if let Some(v) = matcher.args.get(o.get_id()) {
                v.all_val_groups_empty() && o.get_min_vals() != 0
            } else {
                true
            };
            if should_err {
                return Err(Error::empty_value(
                    self.cmd,
                    &get_possible_values_cli(o)
                        .iter()
                        .filter(|pv| !pv.is_hide_set())
                        .map(|n| n.get_name().to_owned())
                        .collect::<Vec<_>>(),
                    o.to_string(),
                ));
            }
        }

        if !has_subcmd && self.cmd.is_arg_required_else_help_set() {
            let num_user_values = matcher
                .arg_ids()
                .filter(|arg_id| matcher.check_explicit(arg_id, &ArgPredicate::IsPresent))
                .count();
            if num_user_values == 0 {
                let message = self.cmd.write_help_err(false);
                return Err(Error::display_help_error(self.cmd, message));
            }
        }
        if !has_subcmd && self.cmd.is_subcommand_required_set() {
            let bn = self
                .cmd
                .get_bin_name()
                .unwrap_or_else(|| self.cmd.get_name());
            return Err(Error::missing_subcommand(
                self.cmd,
                bn.to_string(),
                self.cmd
                    .all_subcommand_names()
                    .map(|s| s.to_owned())
                    .collect::<Vec<_>>(),
                Usage::new(self.cmd)
                    .required(&self.required)
                    .create_usage_with_title(&[]),
            ));
        }

        ok!(self.validate_conflicts(matcher, &mut conflicts));
        if !(self.cmd.is_subcommand_negates_reqs_set() && has_subcmd) {
            ok!(self.validate_required(matcher, &mut conflicts));
        }

        Ok(())
    }

Set binary name. Uses &mut self instead of self.

Get the name of the cmd.

Examples found in repository?
src/output/help_template.rs (line 228)
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
    fn write_display_name(&mut self) {
        debug!("HelpTemplate::write_display_name");

        let display_name = wrap(
            &self
                .cmd
                .get_display_name()
                .unwrap_or_else(|| self.cmd.get_name())
                .replace("{n}", "\n"),
            self.term_w,
        );
        self.none(&display_name);
    }

    /// Writes binary name of a Parser Object to the wrapped stream.
    fn write_bin_name(&mut self) {
        debug!("HelpTemplate::write_bin_name");

        let bin_name = if let Some(bn) = self.cmd.get_bin_name() {
            if bn.contains(' ') {
                // In case we're dealing with subcommands i.e. git mv is translated to git-mv
                bn.replace(' ', "-")
            } else {
                wrap(&self.cmd.get_name().replace("{n}", "\n"), self.term_w)
            }
        } else {
            wrap(&self.cmd.get_name().replace("{n}", "\n"), self.term_w)
        };
        self.none(&bin_name);
    }

    fn write_version(&mut self) {
        let version = self
            .cmd
            .get_version()
            .or_else(|| self.cmd.get_long_version());
        if let Some(output) = version {
            self.none(wrap(output, self.term_w));
        }
    }

    fn write_author(&mut self, before_new_line: bool, after_new_line: bool) {
        if let Some(author) = self.cmd.get_author() {
            if before_new_line {
                self.none("\n");
            }
            self.none(wrap(author, self.term_w));
            if after_new_line {
                self.none("\n");
            }
        }
    }

    fn write_about(&mut self, before_new_line: bool, after_new_line: bool) {
        let about = if self.use_long {
            self.cmd.get_long_about().or_else(|| self.cmd.get_about())
        } else {
            self.cmd.get_about()
        };
        if let Some(output) = about {
            if before_new_line {
                self.none("\n");
            }
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
            if after_new_line {
                self.none("\n");
            }
        }
    }

    fn write_before_help(&mut self) {
        debug!("HelpTemplate::write_before_help");
        let before_help = if self.use_long {
            self.cmd
                .get_before_long_help()
                .or_else(|| self.cmd.get_before_help())
        } else {
            self.cmd.get_before_help()
        };
        if let Some(output) = before_help {
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
            self.none("\n\n");
        }
    }

    fn write_after_help(&mut self) {
        debug!("HelpTemplate::write_after_help");
        let after_help = if self.use_long {
            self.cmd
                .get_after_long_help()
                .or_else(|| self.cmd.get_after_help())
        } else {
            self.cmd.get_after_help()
        };
        if let Some(output) = after_help {
            self.none("\n\n");
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
        }
    }
}

/// Arg handling
impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
    /// Writes help for all arguments (options, flags, args, subcommands)
    /// including titles of a Parser Object to the wrapped stream.
    pub(crate) fn write_all_args(&mut self) {
        debug!("HelpTemplate::write_all_args");
        let pos = self
            .cmd
            .get_positionals()
            .filter(|a| a.get_help_heading().is_none())
            .filter(|arg| should_show_arg(self.use_long, arg))
            .collect::<Vec<_>>();
        let non_pos = self
            .cmd
            .get_non_positionals()
            .filter(|a| a.get_help_heading().is_none())
            .filter(|arg| should_show_arg(self.use_long, arg))
            .collect::<Vec<_>>();
        let subcmds = self.cmd.has_visible_subcommands();

        let custom_headings = self
            .cmd
            .get_arguments()
            .filter_map(|arg| arg.get_help_heading())
            .collect::<FlatSet<_>>();

        let mut first = true;

        if subcmds {
            if !first {
                self.none("\n\n");
            }
            first = false;
            let default_help_heading = Str::from("Commands");
            self.header(
                self.cmd
                    .get_subcommand_help_heading()
                    .unwrap_or(&default_help_heading),
            );
            self.header(":\n");

            self.write_subcommands(self.cmd);
        }

        if !pos.is_empty() {
            if !first {
                self.none("\n\n");
            }
            first = false;
            // Write positional args if any
            self.header("Arguments:\n");
            self.write_args(&pos, "Arguments", positional_sort_key);
        }

        if !non_pos.is_empty() {
            if !first {
                self.none("\n\n");
            }
            first = false;
            self.header("Options:\n");
            self.write_args(&non_pos, "Options", option_sort_key);
        }
        if !custom_headings.is_empty() {
            for heading in custom_headings {
                let args = self
                    .cmd
                    .get_arguments()
                    .filter(|a| {
                        if let Some(help_heading) = a.get_help_heading() {
                            return help_heading == heading;
                        }
                        false
                    })
                    .filter(|arg| should_show_arg(self.use_long, arg))
                    .collect::<Vec<_>>();

                if !args.is_empty() {
                    if !first {
                        self.none("\n\n");
                    }
                    first = false;
                    self.header(format!("{}:\n", heading));
                    self.write_args(&args, heading, option_sort_key);
                }
            }
        }
    }
    /// Sorts arguments by length and display order and write their help to the wrapped stream.
    fn write_args(&mut self, args: &[&Arg], _category: &str, sort_key: ArgSortKey) {
        debug!("HelpTemplate::write_args {}", _category);
        // The shortest an arg can legally be is 2 (i.e. '-x')
        let mut longest = 2;
        let mut ord_v = Vec::new();

        // Determine the longest
        for &arg in args.iter().filter(|arg| {
            // If it's NextLineHelp we don't care to compute how long it is because it may be
            // NextLineHelp on purpose simply *because* it's so long and would throw off all other
            // args alignment
            should_show_arg(self.use_long, arg)
        }) {
            if longest_filter(arg) {
                longest = longest.max(display_width(&arg.to_string()));
                debug!(
                    "HelpTemplate::write_args: arg={:?} longest={}",
                    arg.get_id(),
                    longest
                );
            }

            let key = (sort_key)(arg);
            ord_v.push((key, arg));
        }
        ord_v.sort_by(|a, b| a.0.cmp(&b.0));

        let next_line_help = self.will_args_wrap(args, longest);

        for (i, (_, arg)) in ord_v.iter().enumerate() {
            if i != 0 {
                self.none("\n");
                if next_line_help && self.use_long {
                    self.none("\n");
                }
            }
            self.write_arg(arg, next_line_help, longest);
        }
    }

    /// Writes help for an argument to the wrapped stream.
    fn write_arg(&mut self, arg: &Arg, next_line_help: bool, longest: usize) {
        let spec_vals = &self.spec_vals(arg);

        self.none(TAB);
        self.short(arg);
        self.long(arg);
        self.writer.extend(arg.stylize_arg_suffix(None).into_iter());
        self.align_to_about(arg, next_line_help, longest);

        let about = if self.use_long {
            arg.get_long_help()
                .or_else(|| arg.get_help())
                .unwrap_or_default()
        } else {
            arg.get_help()
                .or_else(|| arg.get_long_help())
                .unwrap_or_default()
        };

        self.help(Some(arg), about, spec_vals, next_line_help, longest);
    }

    /// Writes argument's short command to the wrapped stream.
    fn short(&mut self, arg: &Arg) {
        debug!("HelpTemplate::short");

        if let Some(s) = arg.get_short() {
            self.literal(format!("-{}", s));
        } else if arg.get_long().is_some() {
            self.none("    ");
        }
    }

    /// Writes argument's long command to the wrapped stream.
    fn long(&mut self, arg: &Arg) {
        debug!("HelpTemplate::long");
        if let Some(long) = arg.get_long() {
            if arg.get_short().is_some() {
                self.none(", ");
            }
            self.literal(format!("--{}", long));
        }
    }

    /// Write alignment padding between arg's switches/values and its about message.
    fn align_to_about(&mut self, arg: &Arg, next_line_help: bool, longest: usize) {
        debug!(
            "HelpTemplate::align_to_about: arg={}, next_line_help={}, longest={}",
            arg.get_id(),
            next_line_help,
            longest
        );
        if self.use_long || next_line_help {
            // long help prints messages on the next line so it doesn't need to align text
            debug!("HelpTemplate::align_to_about: printing long help so skip alignment");
        } else if !arg.is_positional() {
            let self_len = display_width(&arg.to_string());
            // Since we're writing spaces from the tab point we first need to know if we
            // had a long and short, or just short
            let padding = if arg.get_long().is_some() {
                // Only account 4 after the val
                TAB_WIDTH
            } else {
                // Only account for ', --' + 4 after the val
                TAB_WIDTH + 4
            };
            let spcs = longest + padding - self_len;
            debug!(
                "HelpTemplate::align_to_about: positional=false arg_len={}, spaces={}",
                self_len, spcs
            );

            self.spaces(spcs);
        } else {
            let self_len = display_width(&arg.to_string());
            let padding = TAB_WIDTH;
            let spcs = longest + padding - self_len;
            debug!(
                "HelpTemplate::align_to_about: positional=true arg_len={}, spaces={}",
                self_len, spcs
            );

            self.spaces(spcs);
        }
    }

    /// Writes argument's help to the wrapped stream.
    fn help(
        &mut self,
        arg: Option<&Arg>,
        about: &StyledStr,
        spec_vals: &str,
        next_line_help: bool,
        longest: usize,
    ) {
        debug!("HelpTemplate::help");

        // Is help on next line, if so then indent
        if next_line_help {
            debug!("HelpTemplate::help: Next Line...{:?}", next_line_help);
            self.none("\n");
            self.none(TAB);
            self.none(NEXT_LINE_INDENT);
        }

        let spaces = if next_line_help {
            TAB.len() + NEXT_LINE_INDENT.len()
        } else if let Some(true) = arg.map(|a| a.is_positional()) {
            longest + TAB_WIDTH * 2
        } else {
            longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
        };
        let trailing_indent = spaces; // Don't indent any further than the first line is indented
        let trailing_indent = self.get_spaces(trailing_indent);

        let mut help = about.clone();
        replace_newline_var(&mut help);
        if !spec_vals.is_empty() {
            if !help.is_empty() {
                let sep = if self.use_long && arg.is_some() {
                    "\n\n"
                } else {
                    " "
                };
                help.none(sep);
            }
            help.none(spec_vals);
        }
        let avail_chars = self.term_w.saturating_sub(spaces);
        debug!(
            "HelpTemplate::help: help_width={}, spaces={}, avail={}",
            spaces,
            help.display_width(),
            avail_chars
        );
        help.wrap(avail_chars);
        help.indent("", &trailing_indent);
        let help_is_empty = help.is_empty();
        self.writer.extend(help.into_iter());
        if let Some(arg) = arg {
            const DASH_SPACE: usize = "- ".len();
            const COLON_SPACE: usize = ": ".len();
            let possible_vals = arg.get_possible_values();
            if self.use_long
                && !arg.is_hide_possible_values_set()
                && possible_vals.iter().any(PossibleValue::should_show_help)
            {
                debug!(
                    "HelpTemplate::help: Found possible vals...{:?}",
                    possible_vals
                );
                if !help_is_empty {
                    self.none("\n\n");
                    self.spaces(spaces);
                }
                self.none("Possible values:");
                let longest = possible_vals
                    .iter()
                    .filter_map(|f| f.get_visible_quoted_name().map(|name| display_width(&name)))
                    .max()
                    .expect("Only called with possible value");
                let help_longest = possible_vals
                    .iter()
                    .filter_map(|f| f.get_visible_help().map(|h| h.display_width()))
                    .max()
                    .expect("Only called with possible value with help");
                // should new line
                let taken = longest + spaces + DASH_SPACE;

                let possible_value_new_line =
                    self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest;

                let spaces = spaces + TAB_WIDTH - DASH_SPACE;
                let trailing_indent = if possible_value_new_line {
                    spaces + DASH_SPACE
                } else {
                    spaces + longest + DASH_SPACE + COLON_SPACE
                };
                let trailing_indent = self.get_spaces(trailing_indent);

                for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) {
                    self.none("\n");
                    self.spaces(spaces);
                    self.none("- ");
                    self.literal(pv.get_name());
                    if let Some(help) = pv.get_help() {
                        debug!("HelpTemplate::help: Possible Value help");

                        if possible_value_new_line {
                            self.none(":\n");
                            self.spaces(trailing_indent.len());
                        } else {
                            self.none(": ");
                            // To align help messages
                            self.spaces(longest - display_width(pv.get_name()));
                        }

                        let avail_chars = if self.term_w > trailing_indent.len() {
                            self.term_w - trailing_indent.len()
                        } else {
                            usize::MAX
                        };

                        let mut help = help.clone();
                        replace_newline_var(&mut help);
                        help.wrap(avail_chars);
                        help.indent("", &trailing_indent);
                        self.writer.extend(help.into_iter());
                    }
                }
            }
        }
    }

    /// Will use next line help on writing args.
    fn will_args_wrap(&self, args: &[&Arg], longest: usize) -> bool {
        args.iter()
            .filter(|arg| should_show_arg(self.use_long, arg))
            .any(|arg| {
                let spec_vals = &self.spec_vals(arg);
                self.arg_next_line_help(arg, spec_vals, longest)
            })
    }

    fn arg_next_line_help(&self, arg: &Arg, spec_vals: &str, longest: usize) -> bool {
        if self.next_line_help || arg.is_next_line_help_set() || self.use_long {
            // setting_next_line
            true
        } else {
            // force_next_line
            let h = arg.get_help().unwrap_or_default();
            let h_w = h.display_width() + display_width(spec_vals);
            let taken = if arg.is_positional() {
                longest + TAB_WIDTH * 2
            } else {
                longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
            };
            self.term_w >= taken
                && (taken as f32 / self.term_w as f32) > 0.40
                && h_w > (self.term_w - taken)
        }
    }

    fn spec_vals(&self, a: &Arg) -> String {
        debug!("HelpTemplate::spec_vals: a={}", a);
        let mut spec_vals = Vec::new();
        #[cfg(feature = "env")]
        if let Some(ref env) = a.env {
            if !a.is_hide_env_set() {
                debug!(
                    "HelpTemplate::spec_vals: Found environment variable...[{:?}:{:?}]",
                    env.0, env.1
                );
                let env_val = if !a.is_hide_env_values_set() {
                    format!(
                        "={}",
                        env.1
                            .as_ref()
                            .map(|s| s.to_string_lossy())
                            .unwrap_or_default()
                    )
                } else {
                    Default::default()
                };
                let env_info = format!("[env: {}{}]", env.0.to_string_lossy(), env_val);
                spec_vals.push(env_info);
            }
        }
        if a.is_takes_value_set() && !a.is_hide_default_value_set() && !a.default_vals.is_empty() {
            debug!(
                "HelpTemplate::spec_vals: Found default value...[{:?}]",
                a.default_vals
            );

            let pvs = a
                .default_vals
                .iter()
                .map(|pvs| pvs.to_string_lossy())
                .map(|pvs| {
                    if pvs.contains(char::is_whitespace) {
                        Cow::from(format!("{:?}", pvs))
                    } else {
                        pvs
                    }
                })
                .collect::<Vec<_>>()
                .join(" ");

            spec_vals.push(format!("[default: {}]", pvs));
        }

        let als = a
            .aliases
            .iter()
            .filter(|&als| als.1) // visible
            .map(|als| als.0.as_str()) // name
            .collect::<Vec<_>>()
            .join(", ");
        if !als.is_empty() {
            debug!("HelpTemplate::spec_vals: Found aliases...{:?}", a.aliases);
            spec_vals.push(format!("[aliases: {}]", als));
        }

        let als = a
            .short_aliases
            .iter()
            .filter(|&als| als.1) // visible
            .map(|&als| als.0.to_string()) // name
            .collect::<Vec<_>>()
            .join(", ");
        if !als.is_empty() {
            debug!(
                "HelpTemplate::spec_vals: Found short aliases...{:?}",
                a.short_aliases
            );
            spec_vals.push(format!("[short aliases: {}]", als));
        }

        let possible_vals = a.get_possible_values();
        if !(a.is_hide_possible_values_set()
            || possible_vals.is_empty()
            || self.use_long && possible_vals.iter().any(PossibleValue::should_show_help))
        {
            debug!(
                "HelpTemplate::spec_vals: Found possible vals...{:?}",
                possible_vals
            );

            let pvs = possible_vals
                .iter()
                .filter_map(PossibleValue::get_visible_quoted_name)
                .collect::<Vec<_>>()
                .join(", ");

            spec_vals.push(format!("[possible values: {}]", pvs));
        }
        let connector = if self.use_long { "\n" } else { " " };
        spec_vals.join(connector)
    }

    fn header<T: Into<String>>(&mut self, msg: T) {
        self.writer.header(msg);
    }

    fn literal<T: Into<String>>(&mut self, msg: T) {
        self.writer.literal(msg);
    }

    fn none<T: Into<String>>(&mut self, msg: T) {
        self.writer.none(msg);
    }

    fn get_spaces(&self, n: usize) -> String {
        " ".repeat(n)
    }

    fn spaces(&mut self, n: usize) {
        self.none(self.get_spaces(n));
    }
}

/// Subcommand handling
impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
    /// Writes help for subcommands of a Parser Object to the wrapped stream.
    fn write_subcommands(&mut self, cmd: &Command) {
        debug!("HelpTemplate::write_subcommands");
        // The shortest an arg can legally be is 2 (i.e. '-x')
        let mut longest = 2;
        let mut ord_v = Vec::new();
        for subcommand in cmd
            .get_subcommands()
            .filter(|subcommand| should_show_subcommand(subcommand))
        {
            let mut styled = StyledStr::new();
            styled.literal(subcommand.get_name());
            if let Some(short) = subcommand.get_short_flag() {
                styled.none(", ");
                styled.literal(format!("-{}", short));
            }
            if let Some(long) = subcommand.get_long_flag() {
                styled.none(", ");
                styled.literal(format!("--{}", long));
            }
            longest = longest.max(styled.display_width());
            ord_v.push((subcommand.get_display_order(), styled, subcommand));
        }
        ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));

        debug!("HelpTemplate::write_subcommands longest = {}", longest);

        let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest);

        let mut first = true;
        for (_, sc_str, sc) in ord_v {
            if first {
                first = false;
            } else {
                self.none("\n");
            }
            self.write_subcommand(sc_str, sc, next_line_help, longest);
        }
    }
More examples
Hide additional examples
src/parser/features/suggestions.rs (line 64)
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
pub(crate) fn did_you_mean_flag<'a, 'help, I, T>(
    arg: &str,
    remaining_args: &[&std::ffi::OsStr],
    longs: I,
    subcommands: impl IntoIterator<Item = &'a mut Command>,
) -> Option<(String, Option<String>)>
where
    'help: 'a,
    T: AsRef<str>,
    I: IntoIterator<Item = T>,
{
    use crate::mkeymap::KeyType;

    match did_you_mean(arg, longs).pop() {
        Some(candidate) => Some((candidate, None)),
        None => subcommands
            .into_iter()
            .filter_map(|subcommand| {
                subcommand._build_self(false);

                let longs = subcommand.get_keymap().keys().filter_map(|a| {
                    if let KeyType::Long(v) = a {
                        Some(v.to_string_lossy().into_owned())
                    } else {
                        None
                    }
                });

                let subcommand_name = subcommand.get_name();

                let candidate = some!(did_you_mean(arg, longs).pop());
                let score = some!(remaining_args.iter().position(|x| subcommand_name == *x));
                Some((score, (candidate, Some(subcommand_name.to_string()))))
            })
            .min_by_key(|(x, _)| *x)
            .map(|(_, suggestion)| suggestion),
    }
}
src/builder/command.rs (line 4172)
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
    pub(crate) fn _propagate_global_args(&mut self) {
        debug!("Command::_propagate_global_args:{}", self.name);

        let autogenerated_help_subcommand = !self.is_disable_help_subcommand_set();

        for sc in &mut self.subcommands {
            if sc.get_name() == "help" && autogenerated_help_subcommand {
                // Avoid propagating args to the autogenerated help subtrees used in completion.
                // This prevents args from showing up during help completions like
                // `myapp help subcmd <TAB>`, which should only suggest subcommands and not args,
                // while still allowing args to show up properly on the generated help message.
                continue;
            }

            for a in self.args.args().filter(|a| a.is_global_set()) {
                if sc.find(&a.id).is_some() {
                    debug!(
                        "Command::_propagate skipping {:?} to {}, already exists",
                        a.id,
                        sc.get_name(),
                    );
                    continue;
                }

                debug!(
                    "Command::_propagate pushing {:?} to {}",
                    a.id,
                    sc.get_name(),
                );
                sc.args.push(a.clone());
            }
        }
    }

    /// Propagate settings
    pub(crate) fn _propagate(&mut self) {
        debug!("Command::_propagate:{}", self.name);
        let mut subcommands = std::mem::take(&mut self.subcommands);
        for sc in &mut subcommands {
            self._propagate_subcommand(sc);
        }
        self.subcommands = subcommands;
    }

    fn _propagate_subcommand(&self, sc: &mut Self) {
        // We have to create a new scope in order to tell rustc the borrow of `sc` is
        // done and to recursively call this method
        {
            if self.settings.is_set(AppSettings::PropagateVersion) {
                if let Some(version) = self.version.as_ref() {
                    sc.version.get_or_insert_with(|| version.clone());
                }
                if let Some(long_version) = self.long_version.as_ref() {
                    sc.long_version.get_or_insert_with(|| long_version.clone());
                }
            }

            sc.settings = sc.settings | self.g_settings;
            sc.g_settings = sc.g_settings | self.g_settings;
            sc.term_w = self.term_w;
            sc.max_w = self.max_w;
        }
    }

    pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) {
        debug!(
            "Command::_check_help_and_version:{} expand_help_tree={}",
            self.name, expand_help_tree
        );

        self.long_help_exists = self.long_help_exists_();

        if !self.is_disable_help_flag_set() {
            debug!("Command::_check_help_and_version: Building default --help");
            let mut arg = Arg::new(Id::HELP)
                .short('h')
                .long("help")
                .action(ArgAction::Help);
            if self.long_help_exists {
                arg = arg
                    .help("Print help information (use `--help` for more detail)")
                    .long_help("Print help information (use `-h` for a summary)");
            } else {
                arg = arg.help("Print help information");
            }
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }
        if !self.is_disable_version_flag_set() {
            debug!("Command::_check_help_and_version: Building default --version");
            let arg = Arg::new(Id::VERSION)
                .short('V')
                .long("version")
                .action(ArgAction::Version)
                .help("Print version information");
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }

        if !self.is_set(AppSettings::DisableHelpSubcommand) {
            debug!("Command::_check_help_and_version: Building help subcommand");
            let help_about = "Print this message or the help of the given subcommand(s)";

            let mut help_subcmd = if expand_help_tree {
                // Slow code path to recursively clone all other subcommand subtrees under help
                let help_subcmd = Command::new("help")
                    .about(help_about)
                    .global_setting(AppSettings::DisableHelpSubcommand)
                    .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));

                let mut help_help_subcmd = Command::new("help").about(help_about);
                help_help_subcmd.version = None;
                help_help_subcmd.long_version = None;
                help_help_subcmd = help_help_subcmd
                    .setting(AppSettings::DisableHelpFlag)
                    .setting(AppSettings::DisableVersionFlag);

                help_subcmd.subcommand(help_help_subcmd)
            } else {
                Command::new("help").about(help_about).arg(
                    Arg::new("subcommand")
                        .action(ArgAction::Append)
                        .num_args(..)
                        .value_name("COMMAND")
                        .help("Print help for the subcommand(s)"),
                )
            };
            self._propagate_subcommand(&mut help_subcmd);

            // The parser acts like this is set, so let's set it so we don't falsely
            // advertise it to the user
            help_subcmd.version = None;
            help_subcmd.long_version = None;
            help_subcmd = help_subcmd
                .setting(AppSettings::DisableHelpFlag)
                .setting(AppSettings::DisableVersionFlag)
                .unset_global_setting(AppSettings::PropagateVersion);

            self.subcommands.push(help_subcmd);
        }
    }

    fn _copy_subtree_for_help(&self) -> Command {
        let mut cmd = Command::new(self.name.clone())
            .hide(self.is_hide_set())
            .global_setting(AppSettings::DisableHelpFlag)
            .global_setting(AppSettings::DisableVersionFlag)
            .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));
        if self.get_about().is_some() {
            cmd = cmd.about(self.get_about().unwrap().clone());
        }
        cmd
    }

    pub(crate) fn _render_version(&self, use_long: bool) -> String {
        debug!("Command::_render_version");

        let ver = if use_long {
            self.long_version
                .as_deref()
                .or(self.version.as_deref())
                .unwrap_or_default()
        } else {
            self.version
                .as_deref()
                .or(self.long_version.as_deref())
                .unwrap_or_default()
        };
        let display_name = self.get_display_name().unwrap_or_else(|| self.get_name());
        format!("{} {}\n", display_name, ver)
    }

    pub(crate) fn format_group(&self, g: &Id) -> StyledStr {
        let g_string = self
            .unroll_args_in_group(g)
            .iter()
            .filter_map(|x| self.find(x))
            .map(|x| {
                if x.is_positional() {
                    // Print val_name for positional arguments. e.g. <file_name>
                    x.name_no_brackets()
                } else {
                    // Print usage string for flags arguments, e.g. <--help>
                    x.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join("|");
        let mut styled = StyledStr::new();
        styled.none("<");
        styled.none(g_string);
        styled.none(">");
        styled
    }
}

/// A workaround:
/// <https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999>
pub(crate) trait Captures<'a> {}
impl<'a, T> Captures<'a> for T {}

// Internal Query Methods
impl Command {
    /// Iterate through the *flags* & *options* arguments.
    #[cfg(any(feature = "usage", feature = "help"))]
    pub(crate) fn get_non_positionals(&self) -> impl Iterator<Item = &Arg> {
        self.get_arguments().filter(|a| !a.is_positional())
    }

    pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg> {
        self.args.args().find(|a| a.get_id() == arg_id)
    }

    #[inline]
    pub(crate) fn contains_short(&self, s: char) -> bool {
        debug_assert!(
            self.is_set(AppSettings::Built),
            "If Command::_build hasn't been called, manually search through Arg shorts"
        );

        self.args.contains(s)
    }

    #[inline]
    pub(crate) fn set(&mut self, s: AppSettings) {
        self.settings.set(s)
    }

    #[inline]
    pub(crate) fn has_positionals(&self) -> bool {
        self.get_positionals().next().is_some()
    }

    #[cfg(any(feature = "usage", feature = "help"))]
    pub(crate) fn has_visible_subcommands(&self) -> bool {
        self.subcommands
            .iter()
            .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden))
    }

    /// Check if this subcommand can be referred to as `name`. In other words,
    /// check if `name` is the name of this subcommand or is one of its aliases.
    #[inline]
    pub(crate) fn aliases_to(&self, name: impl AsRef<std::ffi::OsStr>) -> bool {
        let name = name.as_ref();
        self.get_name() == name || self.get_all_aliases().any(|alias| alias == name)
    }

    /// Check if this subcommand can be referred to as `name`. In other words,
    /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases.
    #[inline]
    pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool {
        Some(flag) == self.short_flag
            || self.get_all_short_flag_aliases().any(|alias| flag == alias)
    }

    /// Check if this subcommand can be referred to as `name`. In other words,
    /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases.
    #[inline]
    pub(crate) fn long_flag_aliases_to(&self, flag: &str) -> bool {
        match self.long_flag.as_ref() {
            Some(long_flag) => {
                long_flag == flag || self.get_all_long_flag_aliases().any(|alias| alias == flag)
            }
            None => self.get_all_long_flag_aliases().any(|alias| alias == flag),
        }
    }

    #[cfg(debug_assertions)]
    pub(crate) fn id_exists(&self, id: &Id) -> bool {
        self.args.args().any(|x| x.get_id() == id) || self.groups.iter().any(|x| x.id == *id)
    }

    /// Iterate through the groups this arg is member of.
    pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator<Item = Id> + 'a {
        debug!("Command::groups_for_arg: id={:?}", arg);
        let arg = arg.clone();
        self.groups
            .iter()
            .filter(move |grp| grp.args.iter().any(|a| a == &arg))
            .map(|grp| grp.id.clone())
    }

    pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup> {
        self.groups.iter().find(|g| g.id == *group_id)
    }

    /// Iterate through all the names of all subcommands (not recursively), including aliases.
    /// Used for suggestions.
    pub(crate) fn all_subcommand_names(&self) -> impl Iterator<Item = &str> + Captures {
        self.get_subcommands().flat_map(|sc| {
            let name = sc.get_name();
            let aliases = sc.get_all_aliases();
            std::iter::once(name).chain(aliases)
        })
    }

    pub(crate) fn required_graph(&self) -> ChildGraph<Id> {
        let mut reqs = ChildGraph::with_capacity(5);
        for a in self.args.args().filter(|a| a.is_required_set()) {
            reqs.insert(a.get_id().clone());
        }
        for group in &self.groups {
            if group.required {
                let idx = reqs.insert(group.id.clone());
                for a in &group.requires {
                    reqs.insert_child(idx, a.clone());
                }
            }
        }

        reqs
    }

    pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec<Id> {
        debug!("Command::unroll_args_in_group: group={:?}", group);
        let mut g_vec = vec![group];
        let mut args = vec![];

        while let Some(g) = g_vec.pop() {
            for n in self
                .groups
                .iter()
                .find(|grp| grp.id == *g)
                .expect(INTERNAL_ERROR_MSG)
                .args
                .iter()
            {
                debug!("Command::unroll_args_in_group:iter: entity={:?}", n);
                if !args.contains(n) {
                    if self.find(n).is_some() {
                        debug!("Command::unroll_args_in_group:iter: this is an arg");
                        args.push(n.clone())
                    } else {
                        debug!("Command::unroll_args_in_group:iter: this is a group");
                        g_vec.push(n);
                    }
                }
            }
        }

        args
    }

    pub(crate) fn unroll_arg_requires<F>(&self, func: F, arg: &Id) -> Vec<Id>
    where
        F: Fn(&(ArgPredicate, Id)) -> Option<Id>,
    {
        let mut processed = vec![];
        let mut r_vec = vec![arg];
        let mut args = vec![];

        while let Some(a) = r_vec.pop() {
            if processed.contains(&a) {
                continue;
            }

            processed.push(a);

            if let Some(arg) = self.find(a) {
                for r in arg.requires.iter().filter_map(&func) {
                    if let Some(req) = self.find(&r) {
                        if !req.requires.is_empty() {
                            r_vec.push(req.get_id())
                        }
                    }
                    args.push(r);
                }
            }
        }

        args
    }

    /// Find a flag subcommand name by short flag or an alias
    pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> {
        self.get_subcommands()
            .find(|sc| sc.short_flag_aliases_to(c))
            .map(|sc| sc.get_name())
    }

    /// Find a flag subcommand name by long flag or an alias
    pub(crate) fn find_long_subcmd(&self, long: &str) -> Option<&str> {
        self.get_subcommands()
            .find(|sc| sc.long_flag_aliases_to(long))
            .map(|sc| sc.get_name())
    }
src/output/usage.rs (line 80)
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
    fn create_help_usage(&self, incl_reqs: bool) -> StyledStr {
        debug!("Usage::create_help_usage; incl_reqs={:?}", incl_reqs);
        let mut styled = StyledStr::new();
        let name = self
            .cmd
            .get_usage_name()
            .or_else(|| self.cmd.get_bin_name())
            .unwrap_or_else(|| self.cmd.get_name());
        styled.literal(name);

        if self.needs_options_tag() {
            styled.placeholder(" [OPTIONS]");
        }

        self.write_args(&[], !incl_reqs, &mut styled);

        // incl_reqs is only false when this function is called recursively
        if self.cmd.has_visible_subcommands() && incl_reqs
            || self.cmd.is_allow_external_subcommands_set()
        {
            let placeholder = self
                .cmd
                .get_subcommand_value_name()
                .unwrap_or(DEFAULT_SUB_VALUE_NAME);
            if self.cmd.is_subcommand_negates_reqs_set()
                || self.cmd.is_args_conflicts_with_subcommands_set()
            {
                styled.none("\n");
                styled.none("       ");
                if self.cmd.is_args_conflicts_with_subcommands_set() {
                    // Short-circuit full usage creation since no args will be relevant
                    styled.literal(name);
                } else {
                    styled.extend(self.create_help_usage(false).into_iter());
                }
                styled.placeholder(" <");
                styled.placeholder(placeholder);
                styled.placeholder(">");
            } else if self.cmd.is_subcommand_required_set() {
                styled.placeholder(" <");
                styled.placeholder(placeholder);
                styled.placeholder(">");
            } else {
                styled.placeholder(" [");
                styled.placeholder(placeholder);
                styled.placeholder("]");
            }
        }
        styled.trim();
        debug!("Usage::create_help_usage: usage={}", styled);
        styled
    }

    // Creates a context aware usage string, or "smart usage" from currently used
    // args, and requirements
    fn create_smart_usage(&self, used: &[Id]) -> StyledStr {
        debug!("Usage::create_smart_usage");
        let mut styled = StyledStr::new();

        styled.literal(
            self.cmd
                .get_usage_name()
                .or_else(|| self.cmd.get_bin_name())
                .unwrap_or_else(|| self.cmd.get_name()),
        );

        self.write_args(used, false, &mut styled);

        if self.cmd.is_subcommand_required_set() {
            styled.placeholder(" <");
            styled.placeholder(
                self.cmd
                    .get_subcommand_value_name()
                    .unwrap_or(DEFAULT_SUB_VALUE_NAME),
            );
            styled.placeholder(">");
        }
        styled
    }
src/parser/validator.rs (line 69)
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
    pub(crate) fn validate(
        &mut self,
        parse_state: ParseState,
        matcher: &mut ArgMatcher,
    ) -> ClapResult<()> {
        debug!("Validator::validate");
        let mut conflicts = Conflicts::new();
        let has_subcmd = matcher.subcommand_name().is_some();

        if let ParseState::Opt(a) = parse_state {
            debug!("Validator::validate: needs_val_of={:?}", a);

            let o = &self.cmd[&a];
            let should_err = if let Some(v) = matcher.args.get(o.get_id()) {
                v.all_val_groups_empty() && o.get_min_vals() != 0
            } else {
                true
            };
            if should_err {
                return Err(Error::empty_value(
                    self.cmd,
                    &get_possible_values_cli(o)
                        .iter()
                        .filter(|pv| !pv.is_hide_set())
                        .map(|n| n.get_name().to_owned())
                        .collect::<Vec<_>>(),
                    o.to_string(),
                ));
            }
        }

        if !has_subcmd && self.cmd.is_arg_required_else_help_set() {
            let num_user_values = matcher
                .arg_ids()
                .filter(|arg_id| matcher.check_explicit(arg_id, &ArgPredicate::IsPresent))
                .count();
            if num_user_values == 0 {
                let message = self.cmd.write_help_err(false);
                return Err(Error::display_help_error(self.cmd, message));
            }
        }
        if !has_subcmd && self.cmd.is_subcommand_required_set() {
            let bn = self
                .cmd
                .get_bin_name()
                .unwrap_or_else(|| self.cmd.get_name());
            return Err(Error::missing_subcommand(
                self.cmd,
                bn.to_string(),
                self.cmd
                    .all_subcommand_names()
                    .map(|s| s.to_owned())
                    .collect::<Vec<_>>(),
                Usage::new(self.cmd)
                    .required(&self.required)
                    .create_usage_with_title(&[]),
            ));
        }

        ok!(self.validate_conflicts(matcher, &mut conflicts));
        if !(self.cmd.is_subcommand_negates_reqs_set() && has_subcmd) {
            ok!(self.validate_required(matcher, &mut conflicts));
        }

        Ok(())
    }
src/builder/debug_asserts.rs (line 26)
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
pub(crate) fn assert_app(cmd: &Command) {
    debug!("Command::_debug_asserts");

    let mut short_flags = vec![];
    let mut long_flags = vec![];

    // Invalid version flag settings
    if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
        // PropagateVersion is meaningless if there is no version
        assert!(
            !cmd.is_propagate_version_set(),
            "Command {}: No version information via Command::version or Command::long_version to propagate",
            cmd.get_name(),
        );

        // Used `Command::mut_arg("version", ..) but did not provide any version information to display
        let version_needed = cmd
            .get_arguments()
            .filter(|x| matches!(x.get_action(), ArgAction::Version))
            .map(|x| x.get_id())
            .collect::<Vec<_>>();

        assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
            ,cmd.get_name()
        );
    }

    for sc in cmd.get_subcommands() {
        if let Some(s) = sc.get_short_flag().as_ref() {
            short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
        }

        for short_alias in sc.get_all_short_flag_aliases() {
            short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
        }

        if let Some(l) = sc.get_long_flag().as_ref() {
            assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
            long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
        }

        for long_alias in sc.get_all_long_flag_aliases() {
            long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
        }
    }

    for arg in cmd.get_arguments() {
        assert_arg(arg);

        assert!(
            !cmd.is_multicall_set(),
            "Command {}: Arguments like {} cannot be set on a multicall command",
            cmd.get_name(),
            arg.get_id()
        );

        if let Some(s) = arg.get_short() {
            short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str()));
        }

        for (short_alias, _) in &arg.short_aliases {
            short_flags.push(Flag::Arg(
                format!("-{}", short_alias),
                arg.get_id().as_str(),
            ));
        }

        if let Some(l) = arg.get_long() {
            assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l);
            long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str()));
        }

        for (long_alias, _) in &arg.aliases {
            long_flags.push(Flag::Arg(
                format!("--{}", long_alias),
                arg.get_id().as_str(),
            ));
        }

        // Name conflicts
        if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
            panic!(
            "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
            cmd.get_name(),
            arg.get_id(),
            duplicate_tip(cmd, first, second),
        );
        }

        // Long conflicts
        if let Some(l) = arg.get_long() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) {
                panic!(
                    "Command {}: Long option names must be unique for each argument, \
                            but '--{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    l,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second)
                )
            }
        }

        // Short conflicts
        if let Some(s) = arg.get_short() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
                panic!(
                    "Command {}: Short option names must be unique for each argument, \
                            but '-{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    s,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second),
                )
            }
        }

        // Index conflicts
        if let Some(idx) = arg.index {
            if let Some((first, second)) =
                cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
            {
                panic!(
                    "Command {}: Argument '{}' has the same index as '{}' \
                    and they are both positional arguments\n\n\t \
                    Use `Arg::num_args(1..)` to allow one \
                    positional argument to take multiple values",
                    cmd.get_name(),
                    first.get_id(),
                    second.get_id()
                )
            }
        }

        // requires, r_if, r_unless
        for req in &arg.requires {
            assert!(
                cmd.id_exists(&req.1),
                "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
                cmd.get_name(),
                req.1,
                arg.get_id(),
            );
        }

        for req in &arg.r_ifs {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_ifs_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq_all`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_unless {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        for req in &arg.r_unless_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // blacklist
        for req in &arg.blacklist {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // overrides
        for req in &arg.overrides {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        if arg.is_last_set() {
            assert!(
                arg.get_long().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
            assert!(
                arg.get_short().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }

        assert!(
            !(arg.is_required_set() && arg.is_global_set()),
            "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
                    cmd.get_name(),
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_positional(),
                "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
                cmd.get_name(),
                arg.get_id()
            );

            assert!(
                arg.is_trailing_var_arg_set() || arg.is_last_set(),
                "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }
    }

    for group in cmd.get_groups() {
        let derive_hint = if cfg!(feature = "derive") {
            " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
        } else {
            ""
        };

        // Name conflicts
        assert!(
            cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
            "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        // Groups should not have naming conflicts with Args
        assert!(
            !cmd.get_arguments().any(|x| x.get_id() == group.get_id()),
            "Command {}: Argument group name '{}' must not conflict with argument name{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        for arg in &group.args {
            // Args listed inside groups should exist
            assert!(
                cmd.get_arguments().any(|x| x.get_id() == arg),
                "Command {}: Argument group '{}' contains non-existent argument '{}'",
                cmd.get_name(),
                group.get_id(),
                arg
            );
        }
    }

    // Conflicts between flags and subcommands

    long_flags.sort_unstable();
    short_flags.sort_unstable();

    detect_duplicate_flags(&long_flags, "long");
    detect_duplicate_flags(&short_flags, "short");

    let mut subs = FlatSet::new();
    for sc in cmd.get_subcommands() {
        assert!(
            subs.insert(sc.get_name()),
            "Command {}: command name `{}` is duplicated",
            cmd.get_name(),
            sc.get_name()
        );
        for alias in sc.get_all_aliases() {
            assert!(
                subs.insert(alias),
                "Command {}: command `{}` alias `{}` is duplicated",
                cmd.get_name(),
                sc.get_name(),
                alias
            );
        }
    }

    _verify_positionals(cmd);

    #[cfg(feature = "help")]
    if let Some(help_template) = cmd.get_help_template() {
        assert!(
            !help_template.to_string().contains("{flags}"),
            "Command {}: {}",
                    cmd.get_name(),
            "`{flags}` template variable was removed in clap3, they are now included in `{options}`",
        );
        assert!(
            !help_template.to_string().contains("{unified}"),
            "Command {}: {}",
            cmd.get_name(),
            "`{unified}` template variable was removed in clap3, use `{options}` instead"
        );
    }

    cmd._panic_on_missing_help(cmd.is_help_expected_set());
    assert_app_flags(cmd);
}

fn duplicate_tip(cmd: &Command, first: &Arg, second: &Arg) -> &'static str {
    if !cmd.is_disable_help_flag_set()
        && (first.get_id() == Id::HELP || second.get_id() == Id::HELP)
    {
        " (call `cmd.disable_help_flag(true)` to remove the auto-generated `--help`)"
    } else if !cmd.is_disable_version_flag_set()
        && (first.get_id() == Id::VERSION || second.get_id() == Id::VERSION)
    {
        " (call `cmd.disable_version_flag(true)` to remove the auto-generated `--version`)"
    } else {
        ""
    }
}

#[derive(Eq)]
enum Flag<'a> {
    Command(String, &'a str),
    Arg(String, &'a str),
}

impl PartialEq for Flag<'_> {
    fn eq(&self, other: &Flag) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl PartialOrd for Flag<'_> {
    fn partial_cmp(&self, other: &Flag) -> Option<Ordering> {
        use Flag::*;

        match (self, other) {
            (Command(s1, _), Command(s2, _))
            | (Arg(s1, _), Arg(s2, _))
            | (Command(s1, _), Arg(s2, _))
            | (Arg(s1, _), Command(s2, _)) => {
                if s1 == s2 {
                    Some(Ordering::Equal)
                } else {
                    s1.partial_cmp(s2)
                }
            }
        }
    }
}

impl Ord for Flag<'_> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

fn detect_duplicate_flags(flags: &[Flag], short_or_long: &str) {
    use Flag::*;

    for (one, two) in find_duplicates(flags) {
        match (one, two) {
            (Command(flag, one), Command(_, another)) if one != another => panic!(
                "the '{}' {} flag is specified for both '{}' and '{}' subcommands",
                flag, short_or_long, one, another
            ),

            (Arg(flag, one), Arg(_, another)) if one != another => panic!(
                "{} option names must be unique, but '{}' is in use by both '{}' and '{}'",
                short_or_long, flag, one, another
            ),

            (Arg(flag, arg), Command(_, sub)) | (Command(flag, sub), Arg(_, arg)) => panic!(
                "the '{}' {} flag for the '{}' argument conflicts with the short flag \
                     for '{}' subcommand",
                flag, short_or_long, arg, sub
            ),

            _ => {}
        }
    }
}

/// Find duplicates in a sorted array.
///
/// The algorithm is simple: the array is sorted, duplicates
/// must be placed next to each other, we can check only adjacent elements.
fn find_duplicates<T: PartialEq>(slice: &[T]) -> impl Iterator<Item = (&T, &T)> {
    slice.windows(2).filter_map(|w| {
        if w[0] == w[1] {
            Some((&w[0], &w[1]))
        } else {
            None
        }
    })
}

fn assert_app_flags(cmd: &Command) {
    macro_rules! checker {
        ($a:ident requires $($b:ident)|+) => {
            if cmd.$a() {
                let mut s = String::new();

                $(
                    if !cmd.$b() {
                        use std::fmt::Write;
                        write!(&mut s, "  AppSettings::{} is required when AppSettings::{} is set.\n", std::stringify!($b), std::stringify!($a)).unwrap();
                    }
                )+

                if !s.is_empty() {
                    panic!("{}", s)
                }
            }
        };
        ($a:ident conflicts $($b:ident)|+) => {
            if cmd.$a() {
                let mut s = String::new();

                $(
                    if cmd.$b() {
                        use std::fmt::Write;
                        write!(&mut s, "  AppSettings::{} conflicts with AppSettings::{}.\n", std::stringify!($b), std::stringify!($a)).unwrap();
                    }
                )+

                if !s.is_empty() {
                    panic!("{}\n{}", cmd.get_name(), s)
                }
            }
        };
    }

    checker!(is_multicall_set conflicts is_no_binary_name_set);
}

#[cfg(debug_assertions)]
fn _verify_positionals(cmd: &Command) -> bool {
    debug!("Command::_verify_positionals");
    // Because you must wait until all arguments have been supplied, this is the first chance
    // to make assertions on positional argument indexes
    //
    // First we verify that the index highest supplied index, is equal to the number of
    // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3
    // but no 2)

    let highest_idx = cmd
        .get_keymap()
        .keys()
        .filter_map(|x| {
            if let KeyType::Position(n) = x {
                Some(*n)
            } else {
                None
            }
        })
        .max()
        .unwrap_or(0);

    let num_p = cmd.get_keymap().keys().filter(|x| x.is_position()).count();

    assert!(
        highest_idx == num_p,
        "Found positional argument whose index is {} but there \
             are only {} positional arguments defined",
        highest_idx,
        num_p
    );

    for arg in cmd.get_arguments() {
        if arg.index.unwrap_or(0) == highest_idx {
            assert!(
                !arg.is_trailing_var_arg_set() || !arg.is_last_set(),
                "{}:{}: `Arg::trailing_var_arg` and `Arg::last` cannot be used together",
                cmd.get_name(),
                arg.get_id()
            );

            if arg.is_trailing_var_arg_set() {
                assert!(
                    arg.is_multiple(),
                    "{}:{}: `Arg::trailing_var_arg` must accept multiple values",
                    cmd.get_name(),
                    arg.get_id()
                );
            }
        } else {
            assert!(
                !arg.is_trailing_var_arg_set(),
                "{}:{}: `Arg::trailing_var_arg` can only apply to last positional",
                cmd.get_name(),
                arg.get_id()
            );
        }
    }

    // Next we verify that only the highest index has takes multiple arguments (if any)
    let only_highest = |a: &Arg| a.is_multiple() && (a.get_index().unwrap_or(0) != highest_idx);
    if cmd.get_positionals().any(only_highest) {
        // First we make sure if there is a positional that allows multiple values
        // the one before it (second to last) has one of these:
        //  * a value terminator
        //  * ArgSettings::Last
        //  * The last arg is Required

        // We can't pass the closure (it.next()) to the macro directly because each call to
        // find() (iterator, not macro) gets called repeatedly.
        let last = &cmd.get_keymap()[&KeyType::Position(highest_idx)];
        let second_to_last = &cmd.get_keymap()[&KeyType::Position(highest_idx - 1)];

        // Either the final positional is required
        // Or the second to last has a terminator or .last(true) set
        let ok = last.is_required_set()
            || (second_to_last.terminator.is_some() || second_to_last.is_last_set())
            || last.is_last_set();
        assert!(
            ok,
            "When using a positional argument with `.num_args(1..)` that is *not the \
                 last* positional argument, the last positional argument (i.e. the one \
                 with the highest index) *must* have .required(true) or .last(true) set."
        );

        // We make sure if the second to last is Multiple the last is ArgSettings::Last
        let ok = second_to_last.is_multiple() || last.is_last_set();
        assert!(
            ok,
            "Only the last positional argument, or second to last positional \
                 argument may be set to `.num_args(1..)`"
        );

        // Next we check how many have both Multiple and not a specific number of values set
        let count = cmd
            .get_positionals()
            .filter(|p| {
                p.is_multiple_values_set()
                    && !p.get_num_args().expect(INTERNAL_ERROR_MSG).is_fixed()
            })
            .count();
        let ok = count <= 1
            || (last.is_last_set()
                && last.is_multiple()
                && second_to_last.is_multiple()
                && count == 2);
        assert!(
            ok,
            "Only one positional argument with `.num_args(1..)` set is allowed per \
                 command, unless the second one also has .last(true) set"
        );
    }

    let mut found = false;

    if cmd.is_allow_missing_positional_set() {
        // Check that if a required positional argument is found, all positions with a lower
        // index are also required.
        let mut foundx2 = false;

        for p in cmd.get_positionals() {
            if foundx2 && !p.is_required_set() {
                assert!(
                    p.is_required_set(),
                    "Found non-required positional argument with a lower \
                         index than a required positional argument by two or more: {:?} \
                         index {:?}",
                    p.get_id(),
                    p.get_index()
                );
            } else if p.is_required_set() && !p.is_last_set() {
                // Args that .last(true) don't count since they can be required and have
                // positionals with a lower index that aren't required
                // Imagine: prog <req1> [opt1] -- <req2>
                // Both of these are valid invocations:
                //      $ prog r1 -- r2
                //      $ prog r1 o1 -- r2
                if found {
                    foundx2 = true;
                    continue;
                }
                found = true;
                continue;
            } else {
                found = false;
            }
        }
    } else {
        // Check that if a required positional argument is found, all positions with a lower
        // index are also required
        for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) {
            if found {
                assert!(
                    p.is_required_set(),
                    "Found non-required positional argument with a lower \
                         index than a required positional argument: {:?} index {:?}",
                    p.get_id(),
                    p.get_index()
                );
            } else if p.is_required_set() && !p.is_last_set() {
                // Args that .last(true) don't count since they can be required and have
                // positionals with a lower index that aren't required
                // Imagine: prog <req1> [opt1] -- <req2>
                // Both of these are valid invocations:
                //      $ prog r1 -- r2
                //      $ prog r1 o1 -- r2
                found = true;
                continue;
            }
        }
    }
    assert!(
        cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2,
        "Only one positional argument may have last(true) set. Found two."
    );
    if cmd
        .get_positionals()
        .any(|p| p.is_last_set() && p.is_required_set())
        && cmd.has_subcommands()
        && !cmd.is_subcommand_negates_reqs_set()
    {
        panic!(
            "Having a required positional argument with .last(true) set *and* child \
                 subcommands without setting SubcommandsNegateReqs isn't compatible."
        );
    }

    true
}

Get the version of the cmd.

Examples found in repository?
src/output/help_template.rs (line 255)
252
253
254
255
256
257
258
259
260
    fn write_version(&mut self) {
        let version = self
            .cmd
            .get_version()
            .or_else(|| self.cmd.get_long_version());
        if let Some(output) = version {
            self.none(wrap(output, self.term_w));
        }
    }
More examples
Hide additional examples
src/builder/debug_asserts.rs (line 21)
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
pub(crate) fn assert_app(cmd: &Command) {
    debug!("Command::_debug_asserts");

    let mut short_flags = vec![];
    let mut long_flags = vec![];

    // Invalid version flag settings
    if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
        // PropagateVersion is meaningless if there is no version
        assert!(
            !cmd.is_propagate_version_set(),
            "Command {}: No version information via Command::version or Command::long_version to propagate",
            cmd.get_name(),
        );

        // Used `Command::mut_arg("version", ..) but did not provide any version information to display
        let version_needed = cmd
            .get_arguments()
            .filter(|x| matches!(x.get_action(), ArgAction::Version))
            .map(|x| x.get_id())
            .collect::<Vec<_>>();

        assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
            ,cmd.get_name()
        );
    }

    for sc in cmd.get_subcommands() {
        if let Some(s) = sc.get_short_flag().as_ref() {
            short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
        }

        for short_alias in sc.get_all_short_flag_aliases() {
            short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
        }

        if let Some(l) = sc.get_long_flag().as_ref() {
            assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
            long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
        }

        for long_alias in sc.get_all_long_flag_aliases() {
            long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
        }
    }

    for arg in cmd.get_arguments() {
        assert_arg(arg);

        assert!(
            !cmd.is_multicall_set(),
            "Command {}: Arguments like {} cannot be set on a multicall command",
            cmd.get_name(),
            arg.get_id()
        );

        if let Some(s) = arg.get_short() {
            short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str()));
        }

        for (short_alias, _) in &arg.short_aliases {
            short_flags.push(Flag::Arg(
                format!("-{}", short_alias),
                arg.get_id().as_str(),
            ));
        }

        if let Some(l) = arg.get_long() {
            assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l);
            long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str()));
        }

        for (long_alias, _) in &arg.aliases {
            long_flags.push(Flag::Arg(
                format!("--{}", long_alias),
                arg.get_id().as_str(),
            ));
        }

        // Name conflicts
        if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
            panic!(
            "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
            cmd.get_name(),
            arg.get_id(),
            duplicate_tip(cmd, first, second),
        );
        }

        // Long conflicts
        if let Some(l) = arg.get_long() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) {
                panic!(
                    "Command {}: Long option names must be unique for each argument, \
                            but '--{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    l,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second)
                )
            }
        }

        // Short conflicts
        if let Some(s) = arg.get_short() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
                panic!(
                    "Command {}: Short option names must be unique for each argument, \
                            but '-{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    s,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second),
                )
            }
        }

        // Index conflicts
        if let Some(idx) = arg.index {
            if let Some((first, second)) =
                cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
            {
                panic!(
                    "Command {}: Argument '{}' has the same index as '{}' \
                    and they are both positional arguments\n\n\t \
                    Use `Arg::num_args(1..)` to allow one \
                    positional argument to take multiple values",
                    cmd.get_name(),
                    first.get_id(),
                    second.get_id()
                )
            }
        }

        // requires, r_if, r_unless
        for req in &arg.requires {
            assert!(
                cmd.id_exists(&req.1),
                "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
                cmd.get_name(),
                req.1,
                arg.get_id(),
            );
        }

        for req in &arg.r_ifs {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_ifs_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq_all`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_unless {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        for req in &arg.r_unless_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // blacklist
        for req in &arg.blacklist {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // overrides
        for req in &arg.overrides {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        if arg.is_last_set() {
            assert!(
                arg.get_long().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
            assert!(
                arg.get_short().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }

        assert!(
            !(arg.is_required_set() && arg.is_global_set()),
            "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
                    cmd.get_name(),
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_positional(),
                "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
                cmd.get_name(),
                arg.get_id()
            );

            assert!(
                arg.is_trailing_var_arg_set() || arg.is_last_set(),
                "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }
    }

    for group in cmd.get_groups() {
        let derive_hint = if cfg!(feature = "derive") {
            " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
        } else {
            ""
        };

        // Name conflicts
        assert!(
            cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
            "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        // Groups should not have naming conflicts with Args
        assert!(
            !cmd.get_arguments().any(|x| x.get_id() == group.get_id()),
            "Command {}: Argument group name '{}' must not conflict with argument name{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        for arg in &group.args {
            // Args listed inside groups should exist
            assert!(
                cmd.get_arguments().any(|x| x.get_id() == arg),
                "Command {}: Argument group '{}' contains non-existent argument '{}'",
                cmd.get_name(),
                group.get_id(),
                arg
            );
        }
    }

    // Conflicts between flags and subcommands

    long_flags.sort_unstable();
    short_flags.sort_unstable();

    detect_duplicate_flags(&long_flags, "long");
    detect_duplicate_flags(&short_flags, "short");

    let mut subs = FlatSet::new();
    for sc in cmd.get_subcommands() {
        assert!(
            subs.insert(sc.get_name()),
            "Command {}: command name `{}` is duplicated",
            cmd.get_name(),
            sc.get_name()
        );
        for alias in sc.get_all_aliases() {
            assert!(
                subs.insert(alias),
                "Command {}: command `{}` alias `{}` is duplicated",
                cmd.get_name(),
                sc.get_name(),
                alias
            );
        }
    }

    _verify_positionals(cmd);

    #[cfg(feature = "help")]
    if let Some(help_template) = cmd.get_help_template() {
        assert!(
            !help_template.to_string().contains("{flags}"),
            "Command {}: {}",
                    cmd.get_name(),
            "`{flags}` template variable was removed in clap3, they are now included in `{options}`",
        );
        assert!(
            !help_template.to_string().contains("{unified}"),
            "Command {}: {}",
            cmd.get_name(),
            "`{unified}` template variable was removed in clap3, use `{options}` instead"
        );
    }

    cmd._panic_on_missing_help(cmd.is_help_expected_set());
    assert_app_flags(cmd);
}

Get the long version of the cmd.

Examples found in repository?
src/output/help_template.rs (line 256)
252
253
254
255
256
257
258
259
260
    fn write_version(&mut self) {
        let version = self
            .cmd
            .get_version()
            .or_else(|| self.cmd.get_long_version());
        if let Some(output) = version {
            self.none(wrap(output, self.term_w));
        }
    }
More examples
Hide additional examples
src/builder/debug_asserts.rs (line 21)
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
pub(crate) fn assert_app(cmd: &Command) {
    debug!("Command::_debug_asserts");

    let mut short_flags = vec![];
    let mut long_flags = vec![];

    // Invalid version flag settings
    if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
        // PropagateVersion is meaningless if there is no version
        assert!(
            !cmd.is_propagate_version_set(),
            "Command {}: No version information via Command::version or Command::long_version to propagate",
            cmd.get_name(),
        );

        // Used `Command::mut_arg("version", ..) but did not provide any version information to display
        let version_needed = cmd
            .get_arguments()
            .filter(|x| matches!(x.get_action(), ArgAction::Version))
            .map(|x| x.get_id())
            .collect::<Vec<_>>();

        assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
            ,cmd.get_name()
        );
    }

    for sc in cmd.get_subcommands() {
        if let Some(s) = sc.get_short_flag().as_ref() {
            short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
        }

        for short_alias in sc.get_all_short_flag_aliases() {
            short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
        }

        if let Some(l) = sc.get_long_flag().as_ref() {
            assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
            long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
        }

        for long_alias in sc.get_all_long_flag_aliases() {
            long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
        }
    }

    for arg in cmd.get_arguments() {
        assert_arg(arg);

        assert!(
            !cmd.is_multicall_set(),
            "Command {}: Arguments like {} cannot be set on a multicall command",
            cmd.get_name(),
            arg.get_id()
        );

        if let Some(s) = arg.get_short() {
            short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str()));
        }

        for (short_alias, _) in &arg.short_aliases {
            short_flags.push(Flag::Arg(
                format!("-{}", short_alias),
                arg.get_id().as_str(),
            ));
        }

        if let Some(l) = arg.get_long() {
            assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l);
            long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str()));
        }

        for (long_alias, _) in &arg.aliases {
            long_flags.push(Flag::Arg(
                format!("--{}", long_alias),
                arg.get_id().as_str(),
            ));
        }

        // Name conflicts
        if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
            panic!(
            "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
            cmd.get_name(),
            arg.get_id(),
            duplicate_tip(cmd, first, second),
        );
        }

        // Long conflicts
        if let Some(l) = arg.get_long() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) {
                panic!(
                    "Command {}: Long option names must be unique for each argument, \
                            but '--{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    l,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second)
                )
            }
        }

        // Short conflicts
        if let Some(s) = arg.get_short() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
                panic!(
                    "Command {}: Short option names must be unique for each argument, \
                            but '-{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    s,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second),
                )
            }
        }

        // Index conflicts
        if let Some(idx) = arg.index {
            if let Some((first, second)) =
                cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
            {
                panic!(
                    "Command {}: Argument '{}' has the same index as '{}' \
                    and they are both positional arguments\n\n\t \
                    Use `Arg::num_args(1..)` to allow one \
                    positional argument to take multiple values",
                    cmd.get_name(),
                    first.get_id(),
                    second.get_id()
                )
            }
        }

        // requires, r_if, r_unless
        for req in &arg.requires {
            assert!(
                cmd.id_exists(&req.1),
                "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
                cmd.get_name(),
                req.1,
                arg.get_id(),
            );
        }

        for req in &arg.r_ifs {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_ifs_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq_all`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_unless {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        for req in &arg.r_unless_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // blacklist
        for req in &arg.blacklist {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // overrides
        for req in &arg.overrides {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        if arg.is_last_set() {
            assert!(
                arg.get_long().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
            assert!(
                arg.get_short().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }

        assert!(
            !(arg.is_required_set() && arg.is_global_set()),
            "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
                    cmd.get_name(),
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_positional(),
                "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
                cmd.get_name(),
                arg.get_id()
            );

            assert!(
                arg.is_trailing_var_arg_set() || arg.is_last_set(),
                "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }
    }

    for group in cmd.get_groups() {
        let derive_hint = if cfg!(feature = "derive") {
            " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
        } else {
            ""
        };

        // Name conflicts
        assert!(
            cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
            "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        // Groups should not have naming conflicts with Args
        assert!(
            !cmd.get_arguments().any(|x| x.get_id() == group.get_id()),
            "Command {}: Argument group name '{}' must not conflict with argument name{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        for arg in &group.args {
            // Args listed inside groups should exist
            assert!(
                cmd.get_arguments().any(|x| x.get_id() == arg),
                "Command {}: Argument group '{}' contains non-existent argument '{}'",
                cmd.get_name(),
                group.get_id(),
                arg
            );
        }
    }

    // Conflicts between flags and subcommands

    long_flags.sort_unstable();
    short_flags.sort_unstable();

    detect_duplicate_flags(&long_flags, "long");
    detect_duplicate_flags(&short_flags, "short");

    let mut subs = FlatSet::new();
    for sc in cmd.get_subcommands() {
        assert!(
            subs.insert(sc.get_name()),
            "Command {}: command name `{}` is duplicated",
            cmd.get_name(),
            sc.get_name()
        );
        for alias in sc.get_all_aliases() {
            assert!(
                subs.insert(alias),
                "Command {}: command `{}` alias `{}` is duplicated",
                cmd.get_name(),
                sc.get_name(),
                alias
            );
        }
    }

    _verify_positionals(cmd);

    #[cfg(feature = "help")]
    if let Some(help_template) = cmd.get_help_template() {
        assert!(
            !help_template.to_string().contains("{flags}"),
            "Command {}: {}",
                    cmd.get_name(),
            "`{flags}` template variable was removed in clap3, they are now included in `{options}`",
        );
        assert!(
            !help_template.to_string().contains("{unified}"),
            "Command {}: {}",
            cmd.get_name(),
            "`{unified}` template variable was removed in clap3, use `{options}` instead"
        );
    }

    cmd._panic_on_missing_help(cmd.is_help_expected_set());
    assert_app_flags(cmd);
}

Get the authors of the cmd.

Examples found in repository?
src/output/help_template.rs (line 263)
262
263
264
265
266
267
268
269
270
271
272
    fn write_author(&mut self, before_new_line: bool, after_new_line: bool) {
        if let Some(author) = self.cmd.get_author() {
            if before_new_line {
                self.none("\n");
            }
            self.none(wrap(author, self.term_w));
            if after_new_line {
                self.none("\n");
            }
        }
    }

Get the short flag of the subcommand.

Examples found in repository?
src/output/help_template.rs (line 835)
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
    fn write_subcommands(&mut self, cmd: &Command) {
        debug!("HelpTemplate::write_subcommands");
        // The shortest an arg can legally be is 2 (i.e. '-x')
        let mut longest = 2;
        let mut ord_v = Vec::new();
        for subcommand in cmd
            .get_subcommands()
            .filter(|subcommand| should_show_subcommand(subcommand))
        {
            let mut styled = StyledStr::new();
            styled.literal(subcommand.get_name());
            if let Some(short) = subcommand.get_short_flag() {
                styled.none(", ");
                styled.literal(format!("-{}", short));
            }
            if let Some(long) = subcommand.get_long_flag() {
                styled.none(", ");
                styled.literal(format!("--{}", long));
            }
            longest = longest.max(styled.display_width());
            ord_v.push((subcommand.get_display_order(), styled, subcommand));
        }
        ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));

        debug!("HelpTemplate::write_subcommands longest = {}", longest);

        let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest);

        let mut first = true;
        for (_, sc_str, sc) in ord_v {
            if first {
                first = false;
            } else {
                self.none("\n");
            }
            self.write_subcommand(sc_str, sc, next_line_help, longest);
        }
    }
More examples
Hide additional examples
src/builder/command.rs (line 3953)
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
    pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> {
        use std::fmt::Write;

        let mut mid_string = String::from(" ");
        #[cfg(feature = "usage")]
        if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set()
        {
            let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

            for s in &reqs {
                mid_string.push_str(&s.to_string());
                mid_string.push(' ');
            }
        }
        let is_multicall_set = self.is_multicall_set();

        let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name));

        // Display subcommand name, short and long in usage
        let mut sc_names = String::new();
        sc_names.push_str(sc.name.as_str());
        let mut flag_subcmd = false;
        if let Some(l) = sc.get_long_flag() {
            write!(sc_names, "|--{}", l).unwrap();
            flag_subcmd = true;
        }
        if let Some(s) = sc.get_short_flag() {
            write!(sc_names, "|-{}", s).unwrap();
            flag_subcmd = true;
        }

        if flag_subcmd {
            sc_names = format!("{{{}}}", sc_names);
        }

        let usage_name = self
            .bin_name
            .as_ref()
            .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names))
            .unwrap_or(sc_names);
        sc.usage_name = Some(usage_name);

        // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
        // a space
        let bin_name = format!(
            "{}{}{}",
            self.bin_name.as_deref().unwrap_or_default(),
            if self.bin_name.is_some() { " " } else { "" },
            &*sc.name
        );
        debug!(
            "Command::_build_subcommand Setting bin_name of {} to {:?}",
            sc.name, bin_name
        );
        sc.bin_name = Some(bin_name);

        if sc.display_name.is_none() {
            let self_display_name = if is_multicall_set {
                self.display_name.as_deref().unwrap_or("")
            } else {
                self.display_name.as_deref().unwrap_or(&self.name)
            };
            let display_name = format!(
                "{}{}{}",
                self_display_name,
                if !self_display_name.is_empty() {
                    "-"
                } else {
                    ""
                },
                &*sc.name
            );
            debug!(
                "Command::_build_subcommand Setting display_name of {} to {:?}",
                sc.name, display_name
            );
            sc.display_name = Some(display_name);
        }

        // Ensure all args are built and ready to parse
        sc._build_self(false);

        Some(sc)
    }

    fn _build_bin_names_internal(&mut self) {
        debug!("Command::_build_bin_names");

        if !self.is_set(AppSettings::BinNameBuilt) {
            let mut mid_string = String::from(" ");
            #[cfg(feature = "usage")]
            if !self.is_subcommand_negates_reqs_set()
                && !self.is_args_conflicts_with_subcommands_set()
            {
                let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

                for s in &reqs {
                    mid_string.push_str(&s.to_string());
                    mid_string.push(' ');
                }
            }
            let is_multicall_set = self.is_multicall_set();

            let self_bin_name = if is_multicall_set {
                self.bin_name.as_deref().unwrap_or("")
            } else {
                self.bin_name.as_deref().unwrap_or(&self.name)
            }
            .to_owned();

            for mut sc in &mut self.subcommands {
                debug!("Command::_build_bin_names:iter: bin_name set...");

                if sc.usage_name.is_none() {
                    use std::fmt::Write;
                    // Display subcommand name, short and long in usage
                    let mut sc_names = String::new();
                    sc_names.push_str(sc.name.as_str());
                    let mut flag_subcmd = false;
                    if let Some(l) = sc.get_long_flag() {
                        write!(sc_names, "|--{}", l).unwrap();
                        flag_subcmd = true;
                    }
                    if let Some(s) = sc.get_short_flag() {
                        write!(sc_names, "|-{}", s).unwrap();
                        flag_subcmd = true;
                    }

                    if flag_subcmd {
                        sc_names = format!("{{{}}}", sc_names);
                    }

                    let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names);
                    debug!(
                        "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}",
                        sc.name, usage_name
                    );
                    sc.usage_name = Some(usage_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})",
                        sc.name, sc.usage_name
                    );
                }

                if sc.bin_name.is_none() {
                    let bin_name = format!(
                        "{}{}{}",
                        self_bin_name,
                        if !self_bin_name.is_empty() { " " } else { "" },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}",
                        sc.name, bin_name
                    );
                    sc.bin_name = Some(bin_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})",
                        sc.name, sc.bin_name
                    );
                }

                if sc.display_name.is_none() {
                    let self_display_name = if is_multicall_set {
                        self.display_name.as_deref().unwrap_or("")
                    } else {
                        self.display_name.as_deref().unwrap_or(&self.name)
                    };
                    let display_name = format!(
                        "{}{}{}",
                        self_display_name,
                        if !self_display_name.is_empty() {
                            "-"
                        } else {
                            ""
                        },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting display_name of {} to {:?}",
                        sc.name, display_name
                    );
                    sc.display_name = Some(display_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})",
                        sc.name, sc.display_name
                    );
                }

                sc._build_bin_names_internal();
            }
            self.set(AppSettings::BinNameBuilt);
        } else {
            debug!("Command::_build_bin_names: already built");
        }
    }
src/builder/debug_asserts.rs (line 42)
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
pub(crate) fn assert_app(cmd: &Command) {
    debug!("Command::_debug_asserts");

    let mut short_flags = vec![];
    let mut long_flags = vec![];

    // Invalid version flag settings
    if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
        // PropagateVersion is meaningless if there is no version
        assert!(
            !cmd.is_propagate_version_set(),
            "Command {}: No version information via Command::version or Command::long_version to propagate",
            cmd.get_name(),
        );

        // Used `Command::mut_arg("version", ..) but did not provide any version information to display
        let version_needed = cmd
            .get_arguments()
            .filter(|x| matches!(x.get_action(), ArgAction::Version))
            .map(|x| x.get_id())
            .collect::<Vec<_>>();

        assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
            ,cmd.get_name()
        );
    }

    for sc in cmd.get_subcommands() {
        if let Some(s) = sc.get_short_flag().as_ref() {
            short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
        }

        for short_alias in sc.get_all_short_flag_aliases() {
            short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
        }

        if let Some(l) = sc.get_long_flag().as_ref() {
            assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
            long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
        }

        for long_alias in sc.get_all_long_flag_aliases() {
            long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
        }
    }

    for arg in cmd.get_arguments() {
        assert_arg(arg);

        assert!(
            !cmd.is_multicall_set(),
            "Command {}: Arguments like {} cannot be set on a multicall command",
            cmd.get_name(),
            arg.get_id()
        );

        if let Some(s) = arg.get_short() {
            short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str()));
        }

        for (short_alias, _) in &arg.short_aliases {
            short_flags.push(Flag::Arg(
                format!("-{}", short_alias),
                arg.get_id().as_str(),
            ));
        }

        if let Some(l) = arg.get_long() {
            assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l);
            long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str()));
        }

        for (long_alias, _) in &arg.aliases {
            long_flags.push(Flag::Arg(
                format!("--{}", long_alias),
                arg.get_id().as_str(),
            ));
        }

        // Name conflicts
        if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
            panic!(
            "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
            cmd.get_name(),
            arg.get_id(),
            duplicate_tip(cmd, first, second),
        );
        }

        // Long conflicts
        if let Some(l) = arg.get_long() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) {
                panic!(
                    "Command {}: Long option names must be unique for each argument, \
                            but '--{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    l,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second)
                )
            }
        }

        // Short conflicts
        if let Some(s) = arg.get_short() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
                panic!(
                    "Command {}: Short option names must be unique for each argument, \
                            but '-{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    s,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second),
                )
            }
        }

        // Index conflicts
        if let Some(idx) = arg.index {
            if let Some((first, second)) =
                cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
            {
                panic!(
                    "Command {}: Argument '{}' has the same index as '{}' \
                    and they are both positional arguments\n\n\t \
                    Use `Arg::num_args(1..)` to allow one \
                    positional argument to take multiple values",
                    cmd.get_name(),
                    first.get_id(),
                    second.get_id()
                )
            }
        }

        // requires, r_if, r_unless
        for req in &arg.requires {
            assert!(
                cmd.id_exists(&req.1),
                "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
                cmd.get_name(),
                req.1,
                arg.get_id(),
            );
        }

        for req in &arg.r_ifs {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_ifs_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq_all`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_unless {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        for req in &arg.r_unless_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // blacklist
        for req in &arg.blacklist {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // overrides
        for req in &arg.overrides {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        if arg.is_last_set() {
            assert!(
                arg.get_long().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
            assert!(
                arg.get_short().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }

        assert!(
            !(arg.is_required_set() && arg.is_global_set()),
            "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
                    cmd.get_name(),
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_positional(),
                "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
                cmd.get_name(),
                arg.get_id()
            );

            assert!(
                arg.is_trailing_var_arg_set() || arg.is_last_set(),
                "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }
    }

    for group in cmd.get_groups() {
        let derive_hint = if cfg!(feature = "derive") {
            " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
        } else {
            ""
        };

        // Name conflicts
        assert!(
            cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
            "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        // Groups should not have naming conflicts with Args
        assert!(
            !cmd.get_arguments().any(|x| x.get_id() == group.get_id()),
            "Command {}: Argument group name '{}' must not conflict with argument name{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        for arg in &group.args {
            // Args listed inside groups should exist
            assert!(
                cmd.get_arguments().any(|x| x.get_id() == arg),
                "Command {}: Argument group '{}' contains non-existent argument '{}'",
                cmd.get_name(),
                group.get_id(),
                arg
            );
        }
    }

    // Conflicts between flags and subcommands

    long_flags.sort_unstable();
    short_flags.sort_unstable();

    detect_duplicate_flags(&long_flags, "long");
    detect_duplicate_flags(&short_flags, "short");

    let mut subs = FlatSet::new();
    for sc in cmd.get_subcommands() {
        assert!(
            subs.insert(sc.get_name()),
            "Command {}: command name `{}` is duplicated",
            cmd.get_name(),
            sc.get_name()
        );
        for alias in sc.get_all_aliases() {
            assert!(
                subs.insert(alias),
                "Command {}: command `{}` alias `{}` is duplicated",
                cmd.get_name(),
                sc.get_name(),
                alias
            );
        }
    }

    _verify_positionals(cmd);

    #[cfg(feature = "help")]
    if let Some(help_template) = cmd.get_help_template() {
        assert!(
            !help_template.to_string().contains("{flags}"),
            "Command {}: {}",
                    cmd.get_name(),
            "`{flags}` template variable was removed in clap3, they are now included in `{options}`",
        );
        assert!(
            !help_template.to_string().contains("{unified}"),
            "Command {}: {}",
            cmd.get_name(),
            "`{unified}` template variable was removed in clap3, use `{options}` instead"
        );
    }

    cmd._panic_on_missing_help(cmd.is_help_expected_set());
    assert_app_flags(cmd);
}

Get the long flag of the subcommand.

Examples found in repository?
src/parser/parser.rs (line 587)
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
    fn possible_long_flag_subcommand(&self, arg: &str) -> Option<&str> {
        debug!("Parser::possible_long_flag_subcommand: arg={:?}", arg);
        if self.cmd.is_infer_subcommands_set() {
            let options = self
                .cmd
                .get_subcommands()
                .fold(Vec::new(), |mut options, sc| {
                    if let Some(long) = sc.get_long_flag() {
                        if long.starts_with(arg) {
                            options.push(long);
                        }
                        options.extend(sc.get_all_aliases().filter(|alias| alias.starts_with(arg)))
                    }
                    options
                });
            if options.len() == 1 {
                return Some(options[0]);
            }

            for sc in options {
                if sc == arg {
                    return Some(sc);
                }
            }
        } else if let Some(sc_name) = self.cmd.find_long_subcmd(arg) {
            return Some(sc_name);
        }
        None
    }
More examples
Hide additional examples
src/output/help_template.rs (line 839)
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
    fn write_subcommands(&mut self, cmd: &Command) {
        debug!("HelpTemplate::write_subcommands");
        // The shortest an arg can legally be is 2 (i.e. '-x')
        let mut longest = 2;
        let mut ord_v = Vec::new();
        for subcommand in cmd
            .get_subcommands()
            .filter(|subcommand| should_show_subcommand(subcommand))
        {
            let mut styled = StyledStr::new();
            styled.literal(subcommand.get_name());
            if let Some(short) = subcommand.get_short_flag() {
                styled.none(", ");
                styled.literal(format!("-{}", short));
            }
            if let Some(long) = subcommand.get_long_flag() {
                styled.none(", ");
                styled.literal(format!("--{}", long));
            }
            longest = longest.max(styled.display_width());
            ord_v.push((subcommand.get_display_order(), styled, subcommand));
        }
        ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));

        debug!("HelpTemplate::write_subcommands longest = {}", longest);

        let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest);

        let mut first = true;
        for (_, sc_str, sc) in ord_v {
            if first {
                first = false;
            } else {
                self.none("\n");
            }
            self.write_subcommand(sc_str, sc, next_line_help, longest);
        }
    }
src/builder/command.rs (line 3949)
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
    pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> {
        use std::fmt::Write;

        let mut mid_string = String::from(" ");
        #[cfg(feature = "usage")]
        if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set()
        {
            let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

            for s in &reqs {
                mid_string.push_str(&s.to_string());
                mid_string.push(' ');
            }
        }
        let is_multicall_set = self.is_multicall_set();

        let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name));

        // Display subcommand name, short and long in usage
        let mut sc_names = String::new();
        sc_names.push_str(sc.name.as_str());
        let mut flag_subcmd = false;
        if let Some(l) = sc.get_long_flag() {
            write!(sc_names, "|--{}", l).unwrap();
            flag_subcmd = true;
        }
        if let Some(s) = sc.get_short_flag() {
            write!(sc_names, "|-{}", s).unwrap();
            flag_subcmd = true;
        }

        if flag_subcmd {
            sc_names = format!("{{{}}}", sc_names);
        }

        let usage_name = self
            .bin_name
            .as_ref()
            .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names))
            .unwrap_or(sc_names);
        sc.usage_name = Some(usage_name);

        // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
        // a space
        let bin_name = format!(
            "{}{}{}",
            self.bin_name.as_deref().unwrap_or_default(),
            if self.bin_name.is_some() { " " } else { "" },
            &*sc.name
        );
        debug!(
            "Command::_build_subcommand Setting bin_name of {} to {:?}",
            sc.name, bin_name
        );
        sc.bin_name = Some(bin_name);

        if sc.display_name.is_none() {
            let self_display_name = if is_multicall_set {
                self.display_name.as_deref().unwrap_or("")
            } else {
                self.display_name.as_deref().unwrap_or(&self.name)
            };
            let display_name = format!(
                "{}{}{}",
                self_display_name,
                if !self_display_name.is_empty() {
                    "-"
                } else {
                    ""
                },
                &*sc.name
            );
            debug!(
                "Command::_build_subcommand Setting display_name of {} to {:?}",
                sc.name, display_name
            );
            sc.display_name = Some(display_name);
        }

        // Ensure all args are built and ready to parse
        sc._build_self(false);

        Some(sc)
    }

    fn _build_bin_names_internal(&mut self) {
        debug!("Command::_build_bin_names");

        if !self.is_set(AppSettings::BinNameBuilt) {
            let mut mid_string = String::from(" ");
            #[cfg(feature = "usage")]
            if !self.is_subcommand_negates_reqs_set()
                && !self.is_args_conflicts_with_subcommands_set()
            {
                let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

                for s in &reqs {
                    mid_string.push_str(&s.to_string());
                    mid_string.push(' ');
                }
            }
            let is_multicall_set = self.is_multicall_set();

            let self_bin_name = if is_multicall_set {
                self.bin_name.as_deref().unwrap_or("")
            } else {
                self.bin_name.as_deref().unwrap_or(&self.name)
            }
            .to_owned();

            for mut sc in &mut self.subcommands {
                debug!("Command::_build_bin_names:iter: bin_name set...");

                if sc.usage_name.is_none() {
                    use std::fmt::Write;
                    // Display subcommand name, short and long in usage
                    let mut sc_names = String::new();
                    sc_names.push_str(sc.name.as_str());
                    let mut flag_subcmd = false;
                    if let Some(l) = sc.get_long_flag() {
                        write!(sc_names, "|--{}", l).unwrap();
                        flag_subcmd = true;
                    }
                    if let Some(s) = sc.get_short_flag() {
                        write!(sc_names, "|-{}", s).unwrap();
                        flag_subcmd = true;
                    }

                    if flag_subcmd {
                        sc_names = format!("{{{}}}", sc_names);
                    }

                    let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names);
                    debug!(
                        "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}",
                        sc.name, usage_name
                    );
                    sc.usage_name = Some(usage_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})",
                        sc.name, sc.usage_name
                    );
                }

                if sc.bin_name.is_none() {
                    let bin_name = format!(
                        "{}{}{}",
                        self_bin_name,
                        if !self_bin_name.is_empty() { " " } else { "" },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}",
                        sc.name, bin_name
                    );
                    sc.bin_name = Some(bin_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})",
                        sc.name, sc.bin_name
                    );
                }

                if sc.display_name.is_none() {
                    let self_display_name = if is_multicall_set {
                        self.display_name.as_deref().unwrap_or("")
                    } else {
                        self.display_name.as_deref().unwrap_or(&self.name)
                    };
                    let display_name = format!(
                        "{}{}{}",
                        self_display_name,
                        if !self_display_name.is_empty() {
                            "-"
                        } else {
                            ""
                        },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting display_name of {} to {:?}",
                        sc.name, display_name
                    );
                    sc.display_name = Some(display_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})",
                        sc.name, sc.display_name
                    );
                }

                sc._build_bin_names_internal();
            }
            self.set(AppSettings::BinNameBuilt);
        } else {
            debug!("Command::_build_bin_names: already built");
        }
    }
src/builder/debug_asserts.rs (line 50)
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
pub(crate) fn assert_app(cmd: &Command) {
    debug!("Command::_debug_asserts");

    let mut short_flags = vec![];
    let mut long_flags = vec![];

    // Invalid version flag settings
    if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
        // PropagateVersion is meaningless if there is no version
        assert!(
            !cmd.is_propagate_version_set(),
            "Command {}: No version information via Command::version or Command::long_version to propagate",
            cmd.get_name(),
        );

        // Used `Command::mut_arg("version", ..) but did not provide any version information to display
        let version_needed = cmd
            .get_arguments()
            .filter(|x| matches!(x.get_action(), ArgAction::Version))
            .map(|x| x.get_id())
            .collect::<Vec<_>>();

        assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
            ,cmd.get_name()
        );
    }

    for sc in cmd.get_subcommands() {
        if let Some(s) = sc.get_short_flag().as_ref() {
            short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
        }

        for short_alias in sc.get_all_short_flag_aliases() {
            short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
        }

        if let Some(l) = sc.get_long_flag().as_ref() {
            assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
            long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
        }

        for long_alias in sc.get_all_long_flag_aliases() {
            long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
        }
    }

    for arg in cmd.get_arguments() {
        assert_arg(arg);

        assert!(
            !cmd.is_multicall_set(),
            "Command {}: Arguments like {} cannot be set on a multicall command",
            cmd.get_name(),
            arg.get_id()
        );

        if let Some(s) = arg.get_short() {
            short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str()));
        }

        for (short_alias, _) in &arg.short_aliases {
            short_flags.push(Flag::Arg(
                format!("-{}", short_alias),
                arg.get_id().as_str(),
            ));
        }

        if let Some(l) = arg.get_long() {
            assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l);
            long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str()));
        }

        for (long_alias, _) in &arg.aliases {
            long_flags.push(Flag::Arg(
                format!("--{}", long_alias),
                arg.get_id().as_str(),
            ));
        }

        // Name conflicts
        if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
            panic!(
            "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
            cmd.get_name(),
            arg.get_id(),
            duplicate_tip(cmd, first, second),
        );
        }

        // Long conflicts
        if let Some(l) = arg.get_long() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) {
                panic!(
                    "Command {}: Long option names must be unique for each argument, \
                            but '--{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    l,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second)
                )
            }
        }

        // Short conflicts
        if let Some(s) = arg.get_short() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
                panic!(
                    "Command {}: Short option names must be unique for each argument, \
                            but '-{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    s,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second),
                )
            }
        }

        // Index conflicts
        if let Some(idx) = arg.index {
            if let Some((first, second)) =
                cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
            {
                panic!(
                    "Command {}: Argument '{}' has the same index as '{}' \
                    and they are both positional arguments\n\n\t \
                    Use `Arg::num_args(1..)` to allow one \
                    positional argument to take multiple values",
                    cmd.get_name(),
                    first.get_id(),
                    second.get_id()
                )
            }
        }

        // requires, r_if, r_unless
        for req in &arg.requires {
            assert!(
                cmd.id_exists(&req.1),
                "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
                cmd.get_name(),
                req.1,
                arg.get_id(),
            );
        }

        for req in &arg.r_ifs {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_ifs_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq_all`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_unless {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        for req in &arg.r_unless_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // blacklist
        for req in &arg.blacklist {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // overrides
        for req in &arg.overrides {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        if arg.is_last_set() {
            assert!(
                arg.get_long().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
            assert!(
                arg.get_short().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }

        assert!(
            !(arg.is_required_set() && arg.is_global_set()),
            "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
                    cmd.get_name(),
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_positional(),
                "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
                cmd.get_name(),
                arg.get_id()
            );

            assert!(
                arg.is_trailing_var_arg_set() || arg.is_last_set(),
                "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }
    }

    for group in cmd.get_groups() {
        let derive_hint = if cfg!(feature = "derive") {
            " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
        } else {
            ""
        };

        // Name conflicts
        assert!(
            cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
            "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        // Groups should not have naming conflicts with Args
        assert!(
            !cmd.get_arguments().any(|x| x.get_id() == group.get_id()),
            "Command {}: Argument group name '{}' must not conflict with argument name{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        for arg in &group.args {
            // Args listed inside groups should exist
            assert!(
                cmd.get_arguments().any(|x| x.get_id() == arg),
                "Command {}: Argument group '{}' contains non-existent argument '{}'",
                cmd.get_name(),
                group.get_id(),
                arg
            );
        }
    }

    // Conflicts between flags and subcommands

    long_flags.sort_unstable();
    short_flags.sort_unstable();

    detect_duplicate_flags(&long_flags, "long");
    detect_duplicate_flags(&short_flags, "short");

    let mut subs = FlatSet::new();
    for sc in cmd.get_subcommands() {
        assert!(
            subs.insert(sc.get_name()),
            "Command {}: command name `{}` is duplicated",
            cmd.get_name(),
            sc.get_name()
        );
        for alias in sc.get_all_aliases() {
            assert!(
                subs.insert(alias),
                "Command {}: command `{}` alias `{}` is duplicated",
                cmd.get_name(),
                sc.get_name(),
                alias
            );
        }
    }

    _verify_positionals(cmd);

    #[cfg(feature = "help")]
    if let Some(help_template) = cmd.get_help_template() {
        assert!(
            !help_template.to_string().contains("{flags}"),
            "Command {}: {}",
                    cmd.get_name(),
            "`{flags}` template variable was removed in clap3, they are now included in `{options}`",
        );
        assert!(
            !help_template.to_string().contains("{unified}"),
            "Command {}: {}",
            cmd.get_name(),
            "`{unified}` template variable was removed in clap3, use `{options}` instead"
        );
    }

    cmd._panic_on_missing_help(cmd.is_help_expected_set());
    assert_app_flags(cmd);
}

Get the help message specified via Command::about.

Examples found in repository?
src/builder/command.rs (line 4316)
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
    fn _copy_subtree_for_help(&self) -> Command {
        let mut cmd = Command::new(self.name.clone())
            .hide(self.is_hide_set())
            .global_setting(AppSettings::DisableHelpFlag)
            .global_setting(AppSettings::DisableVersionFlag)
            .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));
        if self.get_about().is_some() {
            cmd = cmd.about(self.get_about().unwrap().clone());
        }
        cmd
    }
More examples
Hide additional examples
src/output/help_template.rs (line 276)
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
    fn write_about(&mut self, before_new_line: bool, after_new_line: bool) {
        let about = if self.use_long {
            self.cmd.get_long_about().or_else(|| self.cmd.get_about())
        } else {
            self.cmd.get_about()
        };
        if let Some(output) = about {
            if before_new_line {
                self.none("\n");
            }
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
            if after_new_line {
                self.none("\n");
            }
        }
    }

    fn write_before_help(&mut self) {
        debug!("HelpTemplate::write_before_help");
        let before_help = if self.use_long {
            self.cmd
                .get_before_long_help()
                .or_else(|| self.cmd.get_before_help())
        } else {
            self.cmd.get_before_help()
        };
        if let Some(output) = before_help {
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
            self.none("\n\n");
        }
    }

    fn write_after_help(&mut self) {
        debug!("HelpTemplate::write_after_help");
        let after_help = if self.use_long {
            self.cmd
                .get_after_long_help()
                .or_else(|| self.cmd.get_after_help())
        } else {
            self.cmd.get_after_help()
        };
        if let Some(output) = after_help {
            self.none("\n\n");
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
        }
    }
}

/// Arg handling
impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
    /// Writes help for all arguments (options, flags, args, subcommands)
    /// including titles of a Parser Object to the wrapped stream.
    pub(crate) fn write_all_args(&mut self) {
        debug!("HelpTemplate::write_all_args");
        let pos = self
            .cmd
            .get_positionals()
            .filter(|a| a.get_help_heading().is_none())
            .filter(|arg| should_show_arg(self.use_long, arg))
            .collect::<Vec<_>>();
        let non_pos = self
            .cmd
            .get_non_positionals()
            .filter(|a| a.get_help_heading().is_none())
            .filter(|arg| should_show_arg(self.use_long, arg))
            .collect::<Vec<_>>();
        let subcmds = self.cmd.has_visible_subcommands();

        let custom_headings = self
            .cmd
            .get_arguments()
            .filter_map(|arg| arg.get_help_heading())
            .collect::<FlatSet<_>>();

        let mut first = true;

        if subcmds {
            if !first {
                self.none("\n\n");
            }
            first = false;
            let default_help_heading = Str::from("Commands");
            self.header(
                self.cmd
                    .get_subcommand_help_heading()
                    .unwrap_or(&default_help_heading),
            );
            self.header(":\n");

            self.write_subcommands(self.cmd);
        }

        if !pos.is_empty() {
            if !first {
                self.none("\n\n");
            }
            first = false;
            // Write positional args if any
            self.header("Arguments:\n");
            self.write_args(&pos, "Arguments", positional_sort_key);
        }

        if !non_pos.is_empty() {
            if !first {
                self.none("\n\n");
            }
            first = false;
            self.header("Options:\n");
            self.write_args(&non_pos, "Options", option_sort_key);
        }
        if !custom_headings.is_empty() {
            for heading in custom_headings {
                let args = self
                    .cmd
                    .get_arguments()
                    .filter(|a| {
                        if let Some(help_heading) = a.get_help_heading() {
                            return help_heading == heading;
                        }
                        false
                    })
                    .filter(|arg| should_show_arg(self.use_long, arg))
                    .collect::<Vec<_>>();

                if !args.is_empty() {
                    if !first {
                        self.none("\n\n");
                    }
                    first = false;
                    self.header(format!("{}:\n", heading));
                    self.write_args(&args, heading, option_sort_key);
                }
            }
        }
    }
    /// Sorts arguments by length and display order and write their help to the wrapped stream.
    fn write_args(&mut self, args: &[&Arg], _category: &str, sort_key: ArgSortKey) {
        debug!("HelpTemplate::write_args {}", _category);
        // The shortest an arg can legally be is 2 (i.e. '-x')
        let mut longest = 2;
        let mut ord_v = Vec::new();

        // Determine the longest
        for &arg in args.iter().filter(|arg| {
            // If it's NextLineHelp we don't care to compute how long it is because it may be
            // NextLineHelp on purpose simply *because* it's so long and would throw off all other
            // args alignment
            should_show_arg(self.use_long, arg)
        }) {
            if longest_filter(arg) {
                longest = longest.max(display_width(&arg.to_string()));
                debug!(
                    "HelpTemplate::write_args: arg={:?} longest={}",
                    arg.get_id(),
                    longest
                );
            }

            let key = (sort_key)(arg);
            ord_v.push((key, arg));
        }
        ord_v.sort_by(|a, b| a.0.cmp(&b.0));

        let next_line_help = self.will_args_wrap(args, longest);

        for (i, (_, arg)) in ord_v.iter().enumerate() {
            if i != 0 {
                self.none("\n");
                if next_line_help && self.use_long {
                    self.none("\n");
                }
            }
            self.write_arg(arg, next_line_help, longest);
        }
    }

    /// Writes help for an argument to the wrapped stream.
    fn write_arg(&mut self, arg: &Arg, next_line_help: bool, longest: usize) {
        let spec_vals = &self.spec_vals(arg);

        self.none(TAB);
        self.short(arg);
        self.long(arg);
        self.writer.extend(arg.stylize_arg_suffix(None).into_iter());
        self.align_to_about(arg, next_line_help, longest);

        let about = if self.use_long {
            arg.get_long_help()
                .or_else(|| arg.get_help())
                .unwrap_or_default()
        } else {
            arg.get_help()
                .or_else(|| arg.get_long_help())
                .unwrap_or_default()
        };

        self.help(Some(arg), about, spec_vals, next_line_help, longest);
    }

    /// Writes argument's short command to the wrapped stream.
    fn short(&mut self, arg: &Arg) {
        debug!("HelpTemplate::short");

        if let Some(s) = arg.get_short() {
            self.literal(format!("-{}", s));
        } else if arg.get_long().is_some() {
            self.none("    ");
        }
    }

    /// Writes argument's long command to the wrapped stream.
    fn long(&mut self, arg: &Arg) {
        debug!("HelpTemplate::long");
        if let Some(long) = arg.get_long() {
            if arg.get_short().is_some() {
                self.none(", ");
            }
            self.literal(format!("--{}", long));
        }
    }

    /// Write alignment padding between arg's switches/values and its about message.
    fn align_to_about(&mut self, arg: &Arg, next_line_help: bool, longest: usize) {
        debug!(
            "HelpTemplate::align_to_about: arg={}, next_line_help={}, longest={}",
            arg.get_id(),
            next_line_help,
            longest
        );
        if self.use_long || next_line_help {
            // long help prints messages on the next line so it doesn't need to align text
            debug!("HelpTemplate::align_to_about: printing long help so skip alignment");
        } else if !arg.is_positional() {
            let self_len = display_width(&arg.to_string());
            // Since we're writing spaces from the tab point we first need to know if we
            // had a long and short, or just short
            let padding = if arg.get_long().is_some() {
                // Only account 4 after the val
                TAB_WIDTH
            } else {
                // Only account for ', --' + 4 after the val
                TAB_WIDTH + 4
            };
            let spcs = longest + padding - self_len;
            debug!(
                "HelpTemplate::align_to_about: positional=false arg_len={}, spaces={}",
                self_len, spcs
            );

            self.spaces(spcs);
        } else {
            let self_len = display_width(&arg.to_string());
            let padding = TAB_WIDTH;
            let spcs = longest + padding - self_len;
            debug!(
                "HelpTemplate::align_to_about: positional=true arg_len={}, spaces={}",
                self_len, spcs
            );

            self.spaces(spcs);
        }
    }

    /// Writes argument's help to the wrapped stream.
    fn help(
        &mut self,
        arg: Option<&Arg>,
        about: &StyledStr,
        spec_vals: &str,
        next_line_help: bool,
        longest: usize,
    ) {
        debug!("HelpTemplate::help");

        // Is help on next line, if so then indent
        if next_line_help {
            debug!("HelpTemplate::help: Next Line...{:?}", next_line_help);
            self.none("\n");
            self.none(TAB);
            self.none(NEXT_LINE_INDENT);
        }

        let spaces = if next_line_help {
            TAB.len() + NEXT_LINE_INDENT.len()
        } else if let Some(true) = arg.map(|a| a.is_positional()) {
            longest + TAB_WIDTH * 2
        } else {
            longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
        };
        let trailing_indent = spaces; // Don't indent any further than the first line is indented
        let trailing_indent = self.get_spaces(trailing_indent);

        let mut help = about.clone();
        replace_newline_var(&mut help);
        if !spec_vals.is_empty() {
            if !help.is_empty() {
                let sep = if self.use_long && arg.is_some() {
                    "\n\n"
                } else {
                    " "
                };
                help.none(sep);
            }
            help.none(spec_vals);
        }
        let avail_chars = self.term_w.saturating_sub(spaces);
        debug!(
            "HelpTemplate::help: help_width={}, spaces={}, avail={}",
            spaces,
            help.display_width(),
            avail_chars
        );
        help.wrap(avail_chars);
        help.indent("", &trailing_indent);
        let help_is_empty = help.is_empty();
        self.writer.extend(help.into_iter());
        if let Some(arg) = arg {
            const DASH_SPACE: usize = "- ".len();
            const COLON_SPACE: usize = ": ".len();
            let possible_vals = arg.get_possible_values();
            if self.use_long
                && !arg.is_hide_possible_values_set()
                && possible_vals.iter().any(PossibleValue::should_show_help)
            {
                debug!(
                    "HelpTemplate::help: Found possible vals...{:?}",
                    possible_vals
                );
                if !help_is_empty {
                    self.none("\n\n");
                    self.spaces(spaces);
                }
                self.none("Possible values:");
                let longest = possible_vals
                    .iter()
                    .filter_map(|f| f.get_visible_quoted_name().map(|name| display_width(&name)))
                    .max()
                    .expect("Only called with possible value");
                let help_longest = possible_vals
                    .iter()
                    .filter_map(|f| f.get_visible_help().map(|h| h.display_width()))
                    .max()
                    .expect("Only called with possible value with help");
                // should new line
                let taken = longest + spaces + DASH_SPACE;

                let possible_value_new_line =
                    self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest;

                let spaces = spaces + TAB_WIDTH - DASH_SPACE;
                let trailing_indent = if possible_value_new_line {
                    spaces + DASH_SPACE
                } else {
                    spaces + longest + DASH_SPACE + COLON_SPACE
                };
                let trailing_indent = self.get_spaces(trailing_indent);

                for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) {
                    self.none("\n");
                    self.spaces(spaces);
                    self.none("- ");
                    self.literal(pv.get_name());
                    if let Some(help) = pv.get_help() {
                        debug!("HelpTemplate::help: Possible Value help");

                        if possible_value_new_line {
                            self.none(":\n");
                            self.spaces(trailing_indent.len());
                        } else {
                            self.none(": ");
                            // To align help messages
                            self.spaces(longest - display_width(pv.get_name()));
                        }

                        let avail_chars = if self.term_w > trailing_indent.len() {
                            self.term_w - trailing_indent.len()
                        } else {
                            usize::MAX
                        };

                        let mut help = help.clone();
                        replace_newline_var(&mut help);
                        help.wrap(avail_chars);
                        help.indent("", &trailing_indent);
                        self.writer.extend(help.into_iter());
                    }
                }
            }
        }
    }

    /// Will use next line help on writing args.
    fn will_args_wrap(&self, args: &[&Arg], longest: usize) -> bool {
        args.iter()
            .filter(|arg| should_show_arg(self.use_long, arg))
            .any(|arg| {
                let spec_vals = &self.spec_vals(arg);
                self.arg_next_line_help(arg, spec_vals, longest)
            })
    }

    fn arg_next_line_help(&self, arg: &Arg, spec_vals: &str, longest: usize) -> bool {
        if self.next_line_help || arg.is_next_line_help_set() || self.use_long {
            // setting_next_line
            true
        } else {
            // force_next_line
            let h = arg.get_help().unwrap_or_default();
            let h_w = h.display_width() + display_width(spec_vals);
            let taken = if arg.is_positional() {
                longest + TAB_WIDTH * 2
            } else {
                longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
            };
            self.term_w >= taken
                && (taken as f32 / self.term_w as f32) > 0.40
                && h_w > (self.term_w - taken)
        }
    }

    fn spec_vals(&self, a: &Arg) -> String {
        debug!("HelpTemplate::spec_vals: a={}", a);
        let mut spec_vals = Vec::new();
        #[cfg(feature = "env")]
        if let Some(ref env) = a.env {
            if !a.is_hide_env_set() {
                debug!(
                    "HelpTemplate::spec_vals: Found environment variable...[{:?}:{:?}]",
                    env.0, env.1
                );
                let env_val = if !a.is_hide_env_values_set() {
                    format!(
                        "={}",
                        env.1
                            .as_ref()
                            .map(|s| s.to_string_lossy())
                            .unwrap_or_default()
                    )
                } else {
                    Default::default()
                };
                let env_info = format!("[env: {}{}]", env.0.to_string_lossy(), env_val);
                spec_vals.push(env_info);
            }
        }
        if a.is_takes_value_set() && !a.is_hide_default_value_set() && !a.default_vals.is_empty() {
            debug!(
                "HelpTemplate::spec_vals: Found default value...[{:?}]",
                a.default_vals
            );

            let pvs = a
                .default_vals
                .iter()
                .map(|pvs| pvs.to_string_lossy())
                .map(|pvs| {
                    if pvs.contains(char::is_whitespace) {
                        Cow::from(format!("{:?}", pvs))
                    } else {
                        pvs
                    }
                })
                .collect::<Vec<_>>()
                .join(" ");

            spec_vals.push(format!("[default: {}]", pvs));
        }

        let als = a
            .aliases
            .iter()
            .filter(|&als| als.1) // visible
            .map(|als| als.0.as_str()) // name
            .collect::<Vec<_>>()
            .join(", ");
        if !als.is_empty() {
            debug!("HelpTemplate::spec_vals: Found aliases...{:?}", a.aliases);
            spec_vals.push(format!("[aliases: {}]", als));
        }

        let als = a
            .short_aliases
            .iter()
            .filter(|&als| als.1) // visible
            .map(|&als| als.0.to_string()) // name
            .collect::<Vec<_>>()
            .join(", ");
        if !als.is_empty() {
            debug!(
                "HelpTemplate::spec_vals: Found short aliases...{:?}",
                a.short_aliases
            );
            spec_vals.push(format!("[short aliases: {}]", als));
        }

        let possible_vals = a.get_possible_values();
        if !(a.is_hide_possible_values_set()
            || possible_vals.is_empty()
            || self.use_long && possible_vals.iter().any(PossibleValue::should_show_help))
        {
            debug!(
                "HelpTemplate::spec_vals: Found possible vals...{:?}",
                possible_vals
            );

            let pvs = possible_vals
                .iter()
                .filter_map(PossibleValue::get_visible_quoted_name)
                .collect::<Vec<_>>()
                .join(", ");

            spec_vals.push(format!("[possible values: {}]", pvs));
        }
        let connector = if self.use_long { "\n" } else { " " };
        spec_vals.join(connector)
    }

    fn header<T: Into<String>>(&mut self, msg: T) {
        self.writer.header(msg);
    }

    fn literal<T: Into<String>>(&mut self, msg: T) {
        self.writer.literal(msg);
    }

    fn none<T: Into<String>>(&mut self, msg: T) {
        self.writer.none(msg);
    }

    fn get_spaces(&self, n: usize) -> String {
        " ".repeat(n)
    }

    fn spaces(&mut self, n: usize) {
        self.none(self.get_spaces(n));
    }
}

/// Subcommand handling
impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
    /// Writes help for subcommands of a Parser Object to the wrapped stream.
    fn write_subcommands(&mut self, cmd: &Command) {
        debug!("HelpTemplate::write_subcommands");
        // The shortest an arg can legally be is 2 (i.e. '-x')
        let mut longest = 2;
        let mut ord_v = Vec::new();
        for subcommand in cmd
            .get_subcommands()
            .filter(|subcommand| should_show_subcommand(subcommand))
        {
            let mut styled = StyledStr::new();
            styled.literal(subcommand.get_name());
            if let Some(short) = subcommand.get_short_flag() {
                styled.none(", ");
                styled.literal(format!("-{}", short));
            }
            if let Some(long) = subcommand.get_long_flag() {
                styled.none(", ");
                styled.literal(format!("--{}", long));
            }
            longest = longest.max(styled.display_width());
            ord_v.push((subcommand.get_display_order(), styled, subcommand));
        }
        ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));

        debug!("HelpTemplate::write_subcommands longest = {}", longest);

        let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest);

        let mut first = true;
        for (_, sc_str, sc) in ord_v {
            if first {
                first = false;
            } else {
                self.none("\n");
            }
            self.write_subcommand(sc_str, sc, next_line_help, longest);
        }
    }

    /// Will use next line help on writing subcommands.
    fn will_subcommands_wrap<'a>(
        &self,
        subcommands: impl IntoIterator<Item = &'a Command>,
        longest: usize,
    ) -> bool {
        subcommands
            .into_iter()
            .filter(|&subcommand| should_show_subcommand(subcommand))
            .any(|subcommand| {
                let spec_vals = &self.sc_spec_vals(subcommand);
                self.subcommand_next_line_help(subcommand, spec_vals, longest)
            })
    }

    fn write_subcommand(
        &mut self,
        sc_str: StyledStr,
        cmd: &Command,
        next_line_help: bool,
        longest: usize,
    ) {
        debug!("HelpTemplate::write_subcommand");

        let spec_vals = &self.sc_spec_vals(cmd);

        let about = cmd
            .get_about()
            .or_else(|| cmd.get_long_about())
            .unwrap_or_default();

        self.subcmd(sc_str, next_line_help, longest);
        self.help(None, about, spec_vals, next_line_help, longest)
    }

    fn sc_spec_vals(&self, a: &Command) -> String {
        debug!("HelpTemplate::sc_spec_vals: a={}", a.get_name());
        let mut spec_vals = vec![];

        let mut short_als = a
            .get_visible_short_flag_aliases()
            .map(|a| format!("-{}", a))
            .collect::<Vec<_>>();
        let als = a.get_visible_aliases().map(|s| s.to_string());
        short_als.extend(als);
        let all_als = short_als.join(", ");
        if !all_als.is_empty() {
            debug!(
                "HelpTemplate::spec_vals: Found aliases...{:?}",
                a.get_all_aliases().collect::<Vec<_>>()
            );
            debug!(
                "HelpTemplate::spec_vals: Found short flag aliases...{:?}",
                a.get_all_short_flag_aliases().collect::<Vec<_>>()
            );
            spec_vals.push(format!("[aliases: {}]", all_als));
        }

        spec_vals.join(" ")
    }

    fn subcommand_next_line_help(&self, cmd: &Command, spec_vals: &str, longest: usize) -> bool {
        if self.next_line_help | self.use_long {
            // setting_next_line
            true
        } else {
            // force_next_line
            let h = cmd.get_about().unwrap_or_default();
            let h_w = h.display_width() + display_width(spec_vals);
            let taken = longest + TAB_WIDTH * 2;
            self.term_w >= taken
                && (taken as f32 / self.term_w as f32) > 0.40
                && h_w > (self.term_w - taken)
        }
    }

Get the help message specified via Command::long_about.

Examples found in repository?
src/output/help_template.rs (line 276)
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
    fn write_about(&mut self, before_new_line: bool, after_new_line: bool) {
        let about = if self.use_long {
            self.cmd.get_long_about().or_else(|| self.cmd.get_about())
        } else {
            self.cmd.get_about()
        };
        if let Some(output) = about {
            if before_new_line {
                self.none("\n");
            }
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
            if after_new_line {
                self.none("\n");
            }
        }
    }

    fn write_before_help(&mut self) {
        debug!("HelpTemplate::write_before_help");
        let before_help = if self.use_long {
            self.cmd
                .get_before_long_help()
                .or_else(|| self.cmd.get_before_help())
        } else {
            self.cmd.get_before_help()
        };
        if let Some(output) = before_help {
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
            self.none("\n\n");
        }
    }

    fn write_after_help(&mut self) {
        debug!("HelpTemplate::write_after_help");
        let after_help = if self.use_long {
            self.cmd
                .get_after_long_help()
                .or_else(|| self.cmd.get_after_help())
        } else {
            self.cmd.get_after_help()
        };
        if let Some(output) = after_help {
            self.none("\n\n");
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
        }
    }
}

/// Arg handling
impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
    /// Writes help for all arguments (options, flags, args, subcommands)
    /// including titles of a Parser Object to the wrapped stream.
    pub(crate) fn write_all_args(&mut self) {
        debug!("HelpTemplate::write_all_args");
        let pos = self
            .cmd
            .get_positionals()
            .filter(|a| a.get_help_heading().is_none())
            .filter(|arg| should_show_arg(self.use_long, arg))
            .collect::<Vec<_>>();
        let non_pos = self
            .cmd
            .get_non_positionals()
            .filter(|a| a.get_help_heading().is_none())
            .filter(|arg| should_show_arg(self.use_long, arg))
            .collect::<Vec<_>>();
        let subcmds = self.cmd.has_visible_subcommands();

        let custom_headings = self
            .cmd
            .get_arguments()
            .filter_map(|arg| arg.get_help_heading())
            .collect::<FlatSet<_>>();

        let mut first = true;

        if subcmds {
            if !first {
                self.none("\n\n");
            }
            first = false;
            let default_help_heading = Str::from("Commands");
            self.header(
                self.cmd
                    .get_subcommand_help_heading()
                    .unwrap_or(&default_help_heading),
            );
            self.header(":\n");

            self.write_subcommands(self.cmd);
        }

        if !pos.is_empty() {
            if !first {
                self.none("\n\n");
            }
            first = false;
            // Write positional args if any
            self.header("Arguments:\n");
            self.write_args(&pos, "Arguments", positional_sort_key);
        }

        if !non_pos.is_empty() {
            if !first {
                self.none("\n\n");
            }
            first = false;
            self.header("Options:\n");
            self.write_args(&non_pos, "Options", option_sort_key);
        }
        if !custom_headings.is_empty() {
            for heading in custom_headings {
                let args = self
                    .cmd
                    .get_arguments()
                    .filter(|a| {
                        if let Some(help_heading) = a.get_help_heading() {
                            return help_heading == heading;
                        }
                        false
                    })
                    .filter(|arg| should_show_arg(self.use_long, arg))
                    .collect::<Vec<_>>();

                if !args.is_empty() {
                    if !first {
                        self.none("\n\n");
                    }
                    first = false;
                    self.header(format!("{}:\n", heading));
                    self.write_args(&args, heading, option_sort_key);
                }
            }
        }
    }
    /// Sorts arguments by length and display order and write their help to the wrapped stream.
    fn write_args(&mut self, args: &[&Arg], _category: &str, sort_key: ArgSortKey) {
        debug!("HelpTemplate::write_args {}", _category);
        // The shortest an arg can legally be is 2 (i.e. '-x')
        let mut longest = 2;
        let mut ord_v = Vec::new();

        // Determine the longest
        for &arg in args.iter().filter(|arg| {
            // If it's NextLineHelp we don't care to compute how long it is because it may be
            // NextLineHelp on purpose simply *because* it's so long and would throw off all other
            // args alignment
            should_show_arg(self.use_long, arg)
        }) {
            if longest_filter(arg) {
                longest = longest.max(display_width(&arg.to_string()));
                debug!(
                    "HelpTemplate::write_args: arg={:?} longest={}",
                    arg.get_id(),
                    longest
                );
            }

            let key = (sort_key)(arg);
            ord_v.push((key, arg));
        }
        ord_v.sort_by(|a, b| a.0.cmp(&b.0));

        let next_line_help = self.will_args_wrap(args, longest);

        for (i, (_, arg)) in ord_v.iter().enumerate() {
            if i != 0 {
                self.none("\n");
                if next_line_help && self.use_long {
                    self.none("\n");
                }
            }
            self.write_arg(arg, next_line_help, longest);
        }
    }

    /// Writes help for an argument to the wrapped stream.
    fn write_arg(&mut self, arg: &Arg, next_line_help: bool, longest: usize) {
        let spec_vals = &self.spec_vals(arg);

        self.none(TAB);
        self.short(arg);
        self.long(arg);
        self.writer.extend(arg.stylize_arg_suffix(None).into_iter());
        self.align_to_about(arg, next_line_help, longest);

        let about = if self.use_long {
            arg.get_long_help()
                .or_else(|| arg.get_help())
                .unwrap_or_default()
        } else {
            arg.get_help()
                .or_else(|| arg.get_long_help())
                .unwrap_or_default()
        };

        self.help(Some(arg), about, spec_vals, next_line_help, longest);
    }

    /// Writes argument's short command to the wrapped stream.
    fn short(&mut self, arg: &Arg) {
        debug!("HelpTemplate::short");

        if let Some(s) = arg.get_short() {
            self.literal(format!("-{}", s));
        } else if arg.get_long().is_some() {
            self.none("    ");
        }
    }

    /// Writes argument's long command to the wrapped stream.
    fn long(&mut self, arg: &Arg) {
        debug!("HelpTemplate::long");
        if let Some(long) = arg.get_long() {
            if arg.get_short().is_some() {
                self.none(", ");
            }
            self.literal(format!("--{}", long));
        }
    }

    /// Write alignment padding between arg's switches/values and its about message.
    fn align_to_about(&mut self, arg: &Arg, next_line_help: bool, longest: usize) {
        debug!(
            "HelpTemplate::align_to_about: arg={}, next_line_help={}, longest={}",
            arg.get_id(),
            next_line_help,
            longest
        );
        if self.use_long || next_line_help {
            // long help prints messages on the next line so it doesn't need to align text
            debug!("HelpTemplate::align_to_about: printing long help so skip alignment");
        } else if !arg.is_positional() {
            let self_len = display_width(&arg.to_string());
            // Since we're writing spaces from the tab point we first need to know if we
            // had a long and short, or just short
            let padding = if arg.get_long().is_some() {
                // Only account 4 after the val
                TAB_WIDTH
            } else {
                // Only account for ', --' + 4 after the val
                TAB_WIDTH + 4
            };
            let spcs = longest + padding - self_len;
            debug!(
                "HelpTemplate::align_to_about: positional=false arg_len={}, spaces={}",
                self_len, spcs
            );

            self.spaces(spcs);
        } else {
            let self_len = display_width(&arg.to_string());
            let padding = TAB_WIDTH;
            let spcs = longest + padding - self_len;
            debug!(
                "HelpTemplate::align_to_about: positional=true arg_len={}, spaces={}",
                self_len, spcs
            );

            self.spaces(spcs);
        }
    }

    /// Writes argument's help to the wrapped stream.
    fn help(
        &mut self,
        arg: Option<&Arg>,
        about: &StyledStr,
        spec_vals: &str,
        next_line_help: bool,
        longest: usize,
    ) {
        debug!("HelpTemplate::help");

        // Is help on next line, if so then indent
        if next_line_help {
            debug!("HelpTemplate::help: Next Line...{:?}", next_line_help);
            self.none("\n");
            self.none(TAB);
            self.none(NEXT_LINE_INDENT);
        }

        let spaces = if next_line_help {
            TAB.len() + NEXT_LINE_INDENT.len()
        } else if let Some(true) = arg.map(|a| a.is_positional()) {
            longest + TAB_WIDTH * 2
        } else {
            longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
        };
        let trailing_indent = spaces; // Don't indent any further than the first line is indented
        let trailing_indent = self.get_spaces(trailing_indent);

        let mut help = about.clone();
        replace_newline_var(&mut help);
        if !spec_vals.is_empty() {
            if !help.is_empty() {
                let sep = if self.use_long && arg.is_some() {
                    "\n\n"
                } else {
                    " "
                };
                help.none(sep);
            }
            help.none(spec_vals);
        }
        let avail_chars = self.term_w.saturating_sub(spaces);
        debug!(
            "HelpTemplate::help: help_width={}, spaces={}, avail={}",
            spaces,
            help.display_width(),
            avail_chars
        );
        help.wrap(avail_chars);
        help.indent("", &trailing_indent);
        let help_is_empty = help.is_empty();
        self.writer.extend(help.into_iter());
        if let Some(arg) = arg {
            const DASH_SPACE: usize = "- ".len();
            const COLON_SPACE: usize = ": ".len();
            let possible_vals = arg.get_possible_values();
            if self.use_long
                && !arg.is_hide_possible_values_set()
                && possible_vals.iter().any(PossibleValue::should_show_help)
            {
                debug!(
                    "HelpTemplate::help: Found possible vals...{:?}",
                    possible_vals
                );
                if !help_is_empty {
                    self.none("\n\n");
                    self.spaces(spaces);
                }
                self.none("Possible values:");
                let longest = possible_vals
                    .iter()
                    .filter_map(|f| f.get_visible_quoted_name().map(|name| display_width(&name)))
                    .max()
                    .expect("Only called with possible value");
                let help_longest = possible_vals
                    .iter()
                    .filter_map(|f| f.get_visible_help().map(|h| h.display_width()))
                    .max()
                    .expect("Only called with possible value with help");
                // should new line
                let taken = longest + spaces + DASH_SPACE;

                let possible_value_new_line =
                    self.term_w >= taken && self.term_w < taken + COLON_SPACE + help_longest;

                let spaces = spaces + TAB_WIDTH - DASH_SPACE;
                let trailing_indent = if possible_value_new_line {
                    spaces + DASH_SPACE
                } else {
                    spaces + longest + DASH_SPACE + COLON_SPACE
                };
                let trailing_indent = self.get_spaces(trailing_indent);

                for pv in possible_vals.iter().filter(|pv| !pv.is_hide_set()) {
                    self.none("\n");
                    self.spaces(spaces);
                    self.none("- ");
                    self.literal(pv.get_name());
                    if let Some(help) = pv.get_help() {
                        debug!("HelpTemplate::help: Possible Value help");

                        if possible_value_new_line {
                            self.none(":\n");
                            self.spaces(trailing_indent.len());
                        } else {
                            self.none(": ");
                            // To align help messages
                            self.spaces(longest - display_width(pv.get_name()));
                        }

                        let avail_chars = if self.term_w > trailing_indent.len() {
                            self.term_w - trailing_indent.len()
                        } else {
                            usize::MAX
                        };

                        let mut help = help.clone();
                        replace_newline_var(&mut help);
                        help.wrap(avail_chars);
                        help.indent("", &trailing_indent);
                        self.writer.extend(help.into_iter());
                    }
                }
            }
        }
    }

    /// Will use next line help on writing args.
    fn will_args_wrap(&self, args: &[&Arg], longest: usize) -> bool {
        args.iter()
            .filter(|arg| should_show_arg(self.use_long, arg))
            .any(|arg| {
                let spec_vals = &self.spec_vals(arg);
                self.arg_next_line_help(arg, spec_vals, longest)
            })
    }

    fn arg_next_line_help(&self, arg: &Arg, spec_vals: &str, longest: usize) -> bool {
        if self.next_line_help || arg.is_next_line_help_set() || self.use_long {
            // setting_next_line
            true
        } else {
            // force_next_line
            let h = arg.get_help().unwrap_or_default();
            let h_w = h.display_width() + display_width(spec_vals);
            let taken = if arg.is_positional() {
                longest + TAB_WIDTH * 2
            } else {
                longest + TAB_WIDTH * 2 + 4 // See `fn short` for the 4
            };
            self.term_w >= taken
                && (taken as f32 / self.term_w as f32) > 0.40
                && h_w > (self.term_w - taken)
        }
    }

    fn spec_vals(&self, a: &Arg) -> String {
        debug!("HelpTemplate::spec_vals: a={}", a);
        let mut spec_vals = Vec::new();
        #[cfg(feature = "env")]
        if let Some(ref env) = a.env {
            if !a.is_hide_env_set() {
                debug!(
                    "HelpTemplate::spec_vals: Found environment variable...[{:?}:{:?}]",
                    env.0, env.1
                );
                let env_val = if !a.is_hide_env_values_set() {
                    format!(
                        "={}",
                        env.1
                            .as_ref()
                            .map(|s| s.to_string_lossy())
                            .unwrap_or_default()
                    )
                } else {
                    Default::default()
                };
                let env_info = format!("[env: {}{}]", env.0.to_string_lossy(), env_val);
                spec_vals.push(env_info);
            }
        }
        if a.is_takes_value_set() && !a.is_hide_default_value_set() && !a.default_vals.is_empty() {
            debug!(
                "HelpTemplate::spec_vals: Found default value...[{:?}]",
                a.default_vals
            );

            let pvs = a
                .default_vals
                .iter()
                .map(|pvs| pvs.to_string_lossy())
                .map(|pvs| {
                    if pvs.contains(char::is_whitespace) {
                        Cow::from(format!("{:?}", pvs))
                    } else {
                        pvs
                    }
                })
                .collect::<Vec<_>>()
                .join(" ");

            spec_vals.push(format!("[default: {}]", pvs));
        }

        let als = a
            .aliases
            .iter()
            .filter(|&als| als.1) // visible
            .map(|als| als.0.as_str()) // name
            .collect::<Vec<_>>()
            .join(", ");
        if !als.is_empty() {
            debug!("HelpTemplate::spec_vals: Found aliases...{:?}", a.aliases);
            spec_vals.push(format!("[aliases: {}]", als));
        }

        let als = a
            .short_aliases
            .iter()
            .filter(|&als| als.1) // visible
            .map(|&als| als.0.to_string()) // name
            .collect::<Vec<_>>()
            .join(", ");
        if !als.is_empty() {
            debug!(
                "HelpTemplate::spec_vals: Found short aliases...{:?}",
                a.short_aliases
            );
            spec_vals.push(format!("[short aliases: {}]", als));
        }

        let possible_vals = a.get_possible_values();
        if !(a.is_hide_possible_values_set()
            || possible_vals.is_empty()
            || self.use_long && possible_vals.iter().any(PossibleValue::should_show_help))
        {
            debug!(
                "HelpTemplate::spec_vals: Found possible vals...{:?}",
                possible_vals
            );

            let pvs = possible_vals
                .iter()
                .filter_map(PossibleValue::get_visible_quoted_name)
                .collect::<Vec<_>>()
                .join(", ");

            spec_vals.push(format!("[possible values: {}]", pvs));
        }
        let connector = if self.use_long { "\n" } else { " " };
        spec_vals.join(connector)
    }

    fn header<T: Into<String>>(&mut self, msg: T) {
        self.writer.header(msg);
    }

    fn literal<T: Into<String>>(&mut self, msg: T) {
        self.writer.literal(msg);
    }

    fn none<T: Into<String>>(&mut self, msg: T) {
        self.writer.none(msg);
    }

    fn get_spaces(&self, n: usize) -> String {
        " ".repeat(n)
    }

    fn spaces(&mut self, n: usize) {
        self.none(self.get_spaces(n));
    }
}

/// Subcommand handling
impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
    /// Writes help for subcommands of a Parser Object to the wrapped stream.
    fn write_subcommands(&mut self, cmd: &Command) {
        debug!("HelpTemplate::write_subcommands");
        // The shortest an arg can legally be is 2 (i.e. '-x')
        let mut longest = 2;
        let mut ord_v = Vec::new();
        for subcommand in cmd
            .get_subcommands()
            .filter(|subcommand| should_show_subcommand(subcommand))
        {
            let mut styled = StyledStr::new();
            styled.literal(subcommand.get_name());
            if let Some(short) = subcommand.get_short_flag() {
                styled.none(", ");
                styled.literal(format!("-{}", short));
            }
            if let Some(long) = subcommand.get_long_flag() {
                styled.none(", ");
                styled.literal(format!("--{}", long));
            }
            longest = longest.max(styled.display_width());
            ord_v.push((subcommand.get_display_order(), styled, subcommand));
        }
        ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));

        debug!("HelpTemplate::write_subcommands longest = {}", longest);

        let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest);

        let mut first = true;
        for (_, sc_str, sc) in ord_v {
            if first {
                first = false;
            } else {
                self.none("\n");
            }
            self.write_subcommand(sc_str, sc, next_line_help, longest);
        }
    }

    /// Will use next line help on writing subcommands.
    fn will_subcommands_wrap<'a>(
        &self,
        subcommands: impl IntoIterator<Item = &'a Command>,
        longest: usize,
    ) -> bool {
        subcommands
            .into_iter()
            .filter(|&subcommand| should_show_subcommand(subcommand))
            .any(|subcommand| {
                let spec_vals = &self.sc_spec_vals(subcommand);
                self.subcommand_next_line_help(subcommand, spec_vals, longest)
            })
    }

    fn write_subcommand(
        &mut self,
        sc_str: StyledStr,
        cmd: &Command,
        next_line_help: bool,
        longest: usize,
    ) {
        debug!("HelpTemplate::write_subcommand");

        let spec_vals = &self.sc_spec_vals(cmd);

        let about = cmd
            .get_about()
            .or_else(|| cmd.get_long_about())
            .unwrap_or_default();

        self.subcmd(sc_str, next_line_help, longest);
        self.help(None, about, spec_vals, next_line_help, longest)
    }
More examples
Hide additional examples
src/builder/command.rs (line 4606)
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
    fn long_help_exists_(&self) -> bool {
        debug!("Command::long_help_exists");
        // In this case, both must be checked. This allows the retention of
        // original formatting, but also ensures that the actual -h or --help
        // specified by the user is sent through. If hide_short_help is not included,
        // then items specified with hidden_short_help will also be hidden.
        let should_long = |v: &Arg| {
            v.get_long_help().is_some()
                || v.is_hide_long_help_set()
                || v.is_hide_short_help_set()
                || v.get_possible_values()
                    .iter()
                    .any(PossibleValue::should_show_help)
        };

        // Subcommands aren't checked because we prefer short help for them, deferring to
        // `cmd subcmd --help` for more.
        self.get_long_about().is_some()
            || self.get_before_long_help().is_some()
            || self.get_after_long_help().is_some()
            || self.get_arguments().any(should_long)
    }

Get the custom section heading specified via Command::next_help_heading.

Iterate through the visible aliases for this subcommand.

Examples found in repository?
src/output/help_template.rs (line 906)
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
    fn sc_spec_vals(&self, a: &Command) -> String {
        debug!("HelpTemplate::sc_spec_vals: a={}", a.get_name());
        let mut spec_vals = vec![];

        let mut short_als = a
            .get_visible_short_flag_aliases()
            .map(|a| format!("-{}", a))
            .collect::<Vec<_>>();
        let als = a.get_visible_aliases().map(|s| s.to_string());
        short_als.extend(als);
        let all_als = short_als.join(", ");
        if !all_als.is_empty() {
            debug!(
                "HelpTemplate::spec_vals: Found aliases...{:?}",
                a.get_all_aliases().collect::<Vec<_>>()
            );
            debug!(
                "HelpTemplate::spec_vals: Found short flag aliases...{:?}",
                a.get_all_short_flag_aliases().collect::<Vec<_>>()
            );
            spec_vals.push(format!("[aliases: {}]", all_als));
        }

        spec_vals.join(" ")
    }

Iterate through the visible short aliases for this subcommand.

Examples found in repository?
src/output/help_template.rs (line 903)
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
    fn sc_spec_vals(&self, a: &Command) -> String {
        debug!("HelpTemplate::sc_spec_vals: a={}", a.get_name());
        let mut spec_vals = vec![];

        let mut short_als = a
            .get_visible_short_flag_aliases()
            .map(|a| format!("-{}", a))
            .collect::<Vec<_>>();
        let als = a.get_visible_aliases().map(|s| s.to_string());
        short_als.extend(als);
        let all_als = short_als.join(", ");
        if !all_als.is_empty() {
            debug!(
                "HelpTemplate::spec_vals: Found aliases...{:?}",
                a.get_all_aliases().collect::<Vec<_>>()
            );
            debug!(
                "HelpTemplate::spec_vals: Found short flag aliases...{:?}",
                a.get_all_short_flag_aliases().collect::<Vec<_>>()
            );
            spec_vals.push(format!("[aliases: {}]", all_als));
        }

        spec_vals.join(" ")
    }

Iterate through the visible long aliases for this subcommand.

Iterate through the set of all the aliases for this subcommand, both visible and hidden.

Examples found in repository?
src/builder/command.rs (line 4413)
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
    pub(crate) fn aliases_to(&self, name: impl AsRef<std::ffi::OsStr>) -> bool {
        let name = name.as_ref();
        self.get_name() == name || self.get_all_aliases().any(|alias| alias == name)
    }

    /// Check if this subcommand can be referred to as `name`. In other words,
    /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases.
    #[inline]
    pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool {
        Some(flag) == self.short_flag
            || self.get_all_short_flag_aliases().any(|alias| flag == alias)
    }

    /// Check if this subcommand can be referred to as `name`. In other words,
    /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases.
    #[inline]
    pub(crate) fn long_flag_aliases_to(&self, flag: &str) -> bool {
        match self.long_flag.as_ref() {
            Some(long_flag) => {
                long_flag == flag || self.get_all_long_flag_aliases().any(|alias| alias == flag)
            }
            None => self.get_all_long_flag_aliases().any(|alias| alias == flag),
        }
    }

    #[cfg(debug_assertions)]
    pub(crate) fn id_exists(&self, id: &Id) -> bool {
        self.args.args().any(|x| x.get_id() == id) || self.groups.iter().any(|x| x.id == *id)
    }

    /// Iterate through the groups this arg is member of.
    pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator<Item = Id> + 'a {
        debug!("Command::groups_for_arg: id={:?}", arg);
        let arg = arg.clone();
        self.groups
            .iter()
            .filter(move |grp| grp.args.iter().any(|a| a == &arg))
            .map(|grp| grp.id.clone())
    }

    pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup> {
        self.groups.iter().find(|g| g.id == *group_id)
    }

    /// Iterate through all the names of all subcommands (not recursively), including aliases.
    /// Used for suggestions.
    pub(crate) fn all_subcommand_names(&self) -> impl Iterator<Item = &str> + Captures {
        self.get_subcommands().flat_map(|sc| {
            let name = sc.get_name();
            let aliases = sc.get_all_aliases();
            std::iter::once(name).chain(aliases)
        })
    }
More examples
Hide additional examples
src/parser/parser.rs (line 591)
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
    fn possible_long_flag_subcommand(&self, arg: &str) -> Option<&str> {
        debug!("Parser::possible_long_flag_subcommand: arg={:?}", arg);
        if self.cmd.is_infer_subcommands_set() {
            let options = self
                .cmd
                .get_subcommands()
                .fold(Vec::new(), |mut options, sc| {
                    if let Some(long) = sc.get_long_flag() {
                        if long.starts_with(arg) {
                            options.push(long);
                        }
                        options.extend(sc.get_all_aliases().filter(|alias| alias.starts_with(arg)))
                    }
                    options
                });
            if options.len() == 1 {
                return Some(options[0]);
            }

            for sc in options {
                if sc == arg {
                    return Some(sc);
                }
            }
        } else if let Some(sc_name) = self.cmd.find_long_subcmd(arg) {
            return Some(sc_name);
        }
        None
    }
src/builder/debug_asserts.rs (line 335)
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
pub(crate) fn assert_app(cmd: &Command) {
    debug!("Command::_debug_asserts");

    let mut short_flags = vec![];
    let mut long_flags = vec![];

    // Invalid version flag settings
    if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
        // PropagateVersion is meaningless if there is no version
        assert!(
            !cmd.is_propagate_version_set(),
            "Command {}: No version information via Command::version or Command::long_version to propagate",
            cmd.get_name(),
        );

        // Used `Command::mut_arg("version", ..) but did not provide any version information to display
        let version_needed = cmd
            .get_arguments()
            .filter(|x| matches!(x.get_action(), ArgAction::Version))
            .map(|x| x.get_id())
            .collect::<Vec<_>>();

        assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
            ,cmd.get_name()
        );
    }

    for sc in cmd.get_subcommands() {
        if let Some(s) = sc.get_short_flag().as_ref() {
            short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
        }

        for short_alias in sc.get_all_short_flag_aliases() {
            short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
        }

        if let Some(l) = sc.get_long_flag().as_ref() {
            assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
            long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
        }

        for long_alias in sc.get_all_long_flag_aliases() {
            long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
        }
    }

    for arg in cmd.get_arguments() {
        assert_arg(arg);

        assert!(
            !cmd.is_multicall_set(),
            "Command {}: Arguments like {} cannot be set on a multicall command",
            cmd.get_name(),
            arg.get_id()
        );

        if let Some(s) = arg.get_short() {
            short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str()));
        }

        for (short_alias, _) in &arg.short_aliases {
            short_flags.push(Flag::Arg(
                format!("-{}", short_alias),
                arg.get_id().as_str(),
            ));
        }

        if let Some(l) = arg.get_long() {
            assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l);
            long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str()));
        }

        for (long_alias, _) in &arg.aliases {
            long_flags.push(Flag::Arg(
                format!("--{}", long_alias),
                arg.get_id().as_str(),
            ));
        }

        // Name conflicts
        if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
            panic!(
            "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
            cmd.get_name(),
            arg.get_id(),
            duplicate_tip(cmd, first, second),
        );
        }

        // Long conflicts
        if let Some(l) = arg.get_long() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) {
                panic!(
                    "Command {}: Long option names must be unique for each argument, \
                            but '--{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    l,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second)
                )
            }
        }

        // Short conflicts
        if let Some(s) = arg.get_short() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
                panic!(
                    "Command {}: Short option names must be unique for each argument, \
                            but '-{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    s,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second),
                )
            }
        }

        // Index conflicts
        if let Some(idx) = arg.index {
            if let Some((first, second)) =
                cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
            {
                panic!(
                    "Command {}: Argument '{}' has the same index as '{}' \
                    and they are both positional arguments\n\n\t \
                    Use `Arg::num_args(1..)` to allow one \
                    positional argument to take multiple values",
                    cmd.get_name(),
                    first.get_id(),
                    second.get_id()
                )
            }
        }

        // requires, r_if, r_unless
        for req in &arg.requires {
            assert!(
                cmd.id_exists(&req.1),
                "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
                cmd.get_name(),
                req.1,
                arg.get_id(),
            );
        }

        for req in &arg.r_ifs {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_ifs_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq_all`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_unless {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        for req in &arg.r_unless_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // blacklist
        for req in &arg.blacklist {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // overrides
        for req in &arg.overrides {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        if arg.is_last_set() {
            assert!(
                arg.get_long().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
            assert!(
                arg.get_short().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }

        assert!(
            !(arg.is_required_set() && arg.is_global_set()),
            "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
                    cmd.get_name(),
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_positional(),
                "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
                cmd.get_name(),
                arg.get_id()
            );

            assert!(
                arg.is_trailing_var_arg_set() || arg.is_last_set(),
                "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }
    }

    for group in cmd.get_groups() {
        let derive_hint = if cfg!(feature = "derive") {
            " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
        } else {
            ""
        };

        // Name conflicts
        assert!(
            cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
            "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        // Groups should not have naming conflicts with Args
        assert!(
            !cmd.get_arguments().any(|x| x.get_id() == group.get_id()),
            "Command {}: Argument group name '{}' must not conflict with argument name{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        for arg in &group.args {
            // Args listed inside groups should exist
            assert!(
                cmd.get_arguments().any(|x| x.get_id() == arg),
                "Command {}: Argument group '{}' contains non-existent argument '{}'",
                cmd.get_name(),
                group.get_id(),
                arg
            );
        }
    }

    // Conflicts between flags and subcommands

    long_flags.sort_unstable();
    short_flags.sort_unstable();

    detect_duplicate_flags(&long_flags, "long");
    detect_duplicate_flags(&short_flags, "short");

    let mut subs = FlatSet::new();
    for sc in cmd.get_subcommands() {
        assert!(
            subs.insert(sc.get_name()),
            "Command {}: command name `{}` is duplicated",
            cmd.get_name(),
            sc.get_name()
        );
        for alias in sc.get_all_aliases() {
            assert!(
                subs.insert(alias),
                "Command {}: command `{}` alias `{}` is duplicated",
                cmd.get_name(),
                sc.get_name(),
                alias
            );
        }
    }

    _verify_positionals(cmd);

    #[cfg(feature = "help")]
    if let Some(help_template) = cmd.get_help_template() {
        assert!(
            !help_template.to_string().contains("{flags}"),
            "Command {}: {}",
                    cmd.get_name(),
            "`{flags}` template variable was removed in clap3, they are now included in `{options}`",
        );
        assert!(
            !help_template.to_string().contains("{unified}"),
            "Command {}: {}",
            cmd.get_name(),
            "`{unified}` template variable was removed in clap3, use `{options}` instead"
        );
    }

    cmd._panic_on_missing_help(cmd.is_help_expected_set());
    assert_app_flags(cmd);
}

Iterate through the set of all the short aliases for this subcommand, both visible and hidden.

Examples found in repository?
src/builder/command.rs (line 4421)
4419
4420
4421
4422
    pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool {
        Some(flag) == self.short_flag
            || self.get_all_short_flag_aliases().any(|alias| flag == alias)
    }
More examples
Hide additional examples
src/builder/debug_asserts.rs (line 46)
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
pub(crate) fn assert_app(cmd: &Command) {
    debug!("Command::_debug_asserts");

    let mut short_flags = vec![];
    let mut long_flags = vec![];

    // Invalid version flag settings
    if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
        // PropagateVersion is meaningless if there is no version
        assert!(
            !cmd.is_propagate_version_set(),
            "Command {}: No version information via Command::version or Command::long_version to propagate",
            cmd.get_name(),
        );

        // Used `Command::mut_arg("version", ..) but did not provide any version information to display
        let version_needed = cmd
            .get_arguments()
            .filter(|x| matches!(x.get_action(), ArgAction::Version))
            .map(|x| x.get_id())
            .collect::<Vec<_>>();

        assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
            ,cmd.get_name()
        );
    }

    for sc in cmd.get_subcommands() {
        if let Some(s) = sc.get_short_flag().as_ref() {
            short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
        }

        for short_alias in sc.get_all_short_flag_aliases() {
            short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
        }

        if let Some(l) = sc.get_long_flag().as_ref() {
            assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
            long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
        }

        for long_alias in sc.get_all_long_flag_aliases() {
            long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
        }
    }

    for arg in cmd.get_arguments() {
        assert_arg(arg);

        assert!(
            !cmd.is_multicall_set(),
            "Command {}: Arguments like {} cannot be set on a multicall command",
            cmd.get_name(),
            arg.get_id()
        );

        if let Some(s) = arg.get_short() {
            short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str()));
        }

        for (short_alias, _) in &arg.short_aliases {
            short_flags.push(Flag::Arg(
                format!("-{}", short_alias),
                arg.get_id().as_str(),
            ));
        }

        if let Some(l) = arg.get_long() {
            assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l);
            long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str()));
        }

        for (long_alias, _) in &arg.aliases {
            long_flags.push(Flag::Arg(
                format!("--{}", long_alias),
                arg.get_id().as_str(),
            ));
        }

        // Name conflicts
        if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
            panic!(
            "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
            cmd.get_name(),
            arg.get_id(),
            duplicate_tip(cmd, first, second),
        );
        }

        // Long conflicts
        if let Some(l) = arg.get_long() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) {
                panic!(
                    "Command {}: Long option names must be unique for each argument, \
                            but '--{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    l,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second)
                )
            }
        }

        // Short conflicts
        if let Some(s) = arg.get_short() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
                panic!(
                    "Command {}: Short option names must be unique for each argument, \
                            but '-{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    s,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second),
                )
            }
        }

        // Index conflicts
        if let Some(idx) = arg.index {
            if let Some((first, second)) =
                cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
            {
                panic!(
                    "Command {}: Argument '{}' has the same index as '{}' \
                    and they are both positional arguments\n\n\t \
                    Use `Arg::num_args(1..)` to allow one \
                    positional argument to take multiple values",
                    cmd.get_name(),
                    first.get_id(),
                    second.get_id()
                )
            }
        }

        // requires, r_if, r_unless
        for req in &arg.requires {
            assert!(
                cmd.id_exists(&req.1),
                "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
                cmd.get_name(),
                req.1,
                arg.get_id(),
            );
        }

        for req in &arg.r_ifs {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_ifs_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq_all`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_unless {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        for req in &arg.r_unless_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // blacklist
        for req in &arg.blacklist {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // overrides
        for req in &arg.overrides {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        if arg.is_last_set() {
            assert!(
                arg.get_long().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
            assert!(
                arg.get_short().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }

        assert!(
            !(arg.is_required_set() && arg.is_global_set()),
            "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
                    cmd.get_name(),
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_positional(),
                "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
                cmd.get_name(),
                arg.get_id()
            );

            assert!(
                arg.is_trailing_var_arg_set() || arg.is_last_set(),
                "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }
    }

    for group in cmd.get_groups() {
        let derive_hint = if cfg!(feature = "derive") {
            " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
        } else {
            ""
        };

        // Name conflicts
        assert!(
            cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
            "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        // Groups should not have naming conflicts with Args
        assert!(
            !cmd.get_arguments().any(|x| x.get_id() == group.get_id()),
            "Command {}: Argument group name '{}' must not conflict with argument name{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        for arg in &group.args {
            // Args listed inside groups should exist
            assert!(
                cmd.get_arguments().any(|x| x.get_id() == arg),
                "Command {}: Argument group '{}' contains non-existent argument '{}'",
                cmd.get_name(),
                group.get_id(),
                arg
            );
        }
    }

    // Conflicts between flags and subcommands

    long_flags.sort_unstable();
    short_flags.sort_unstable();

    detect_duplicate_flags(&long_flags, "long");
    detect_duplicate_flags(&short_flags, "short");

    let mut subs = FlatSet::new();
    for sc in cmd.get_subcommands() {
        assert!(
            subs.insert(sc.get_name()),
            "Command {}: command name `{}` is duplicated",
            cmd.get_name(),
            sc.get_name()
        );
        for alias in sc.get_all_aliases() {
            assert!(
                subs.insert(alias),
                "Command {}: command `{}` alias `{}` is duplicated",
                cmd.get_name(),
                sc.get_name(),
                alias
            );
        }
    }

    _verify_positionals(cmd);

    #[cfg(feature = "help")]
    if let Some(help_template) = cmd.get_help_template() {
        assert!(
            !help_template.to_string().contains("{flags}"),
            "Command {}: {}",
                    cmd.get_name(),
            "`{flags}` template variable was removed in clap3, they are now included in `{options}`",
        );
        assert!(
            !help_template.to_string().contains("{unified}"),
            "Command {}: {}",
            cmd.get_name(),
            "`{unified}` template variable was removed in clap3, use `{options}` instead"
        );
    }

    cmd._panic_on_missing_help(cmd.is_help_expected_set());
    assert_app_flags(cmd);
}

Iterate through the set of all the long aliases for this subcommand, both visible and hidden.

Examples found in repository?
src/builder/command.rs (line 4430)
4427
4428
4429
4430
4431
4432
4433
4434
    pub(crate) fn long_flag_aliases_to(&self, flag: &str) -> bool {
        match self.long_flag.as_ref() {
            Some(long_flag) => {
                long_flag == flag || self.get_all_long_flag_aliases().any(|alias| alias == flag)
            }
            None => self.get_all_long_flag_aliases().any(|alias| alias == flag),
        }
    }
More examples
Hide additional examples
src/builder/debug_asserts.rs (line 55)
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
pub(crate) fn assert_app(cmd: &Command) {
    debug!("Command::_debug_asserts");

    let mut short_flags = vec![];
    let mut long_flags = vec![];

    // Invalid version flag settings
    if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
        // PropagateVersion is meaningless if there is no version
        assert!(
            !cmd.is_propagate_version_set(),
            "Command {}: No version information via Command::version or Command::long_version to propagate",
            cmd.get_name(),
        );

        // Used `Command::mut_arg("version", ..) but did not provide any version information to display
        let version_needed = cmd
            .get_arguments()
            .filter(|x| matches!(x.get_action(), ArgAction::Version))
            .map(|x| x.get_id())
            .collect::<Vec<_>>();

        assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
            ,cmd.get_name()
        );
    }

    for sc in cmd.get_subcommands() {
        if let Some(s) = sc.get_short_flag().as_ref() {
            short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
        }

        for short_alias in sc.get_all_short_flag_aliases() {
            short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
        }

        if let Some(l) = sc.get_long_flag().as_ref() {
            assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
            long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
        }

        for long_alias in sc.get_all_long_flag_aliases() {
            long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
        }
    }

    for arg in cmd.get_arguments() {
        assert_arg(arg);

        assert!(
            !cmd.is_multicall_set(),
            "Command {}: Arguments like {} cannot be set on a multicall command",
            cmd.get_name(),
            arg.get_id()
        );

        if let Some(s) = arg.get_short() {
            short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str()));
        }

        for (short_alias, _) in &arg.short_aliases {
            short_flags.push(Flag::Arg(
                format!("-{}", short_alias),
                arg.get_id().as_str(),
            ));
        }

        if let Some(l) = arg.get_long() {
            assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l);
            long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str()));
        }

        for (long_alias, _) in &arg.aliases {
            long_flags.push(Flag::Arg(
                format!("--{}", long_alias),
                arg.get_id().as_str(),
            ));
        }

        // Name conflicts
        if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
            panic!(
            "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
            cmd.get_name(),
            arg.get_id(),
            duplicate_tip(cmd, first, second),
        );
        }

        // Long conflicts
        if let Some(l) = arg.get_long() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) {
                panic!(
                    "Command {}: Long option names must be unique for each argument, \
                            but '--{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    l,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second)
                )
            }
        }

        // Short conflicts
        if let Some(s) = arg.get_short() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
                panic!(
                    "Command {}: Short option names must be unique for each argument, \
                            but '-{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    s,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second),
                )
            }
        }

        // Index conflicts
        if let Some(idx) = arg.index {
            if let Some((first, second)) =
                cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
            {
                panic!(
                    "Command {}: Argument '{}' has the same index as '{}' \
                    and they are both positional arguments\n\n\t \
                    Use `Arg::num_args(1..)` to allow one \
                    positional argument to take multiple values",
                    cmd.get_name(),
                    first.get_id(),
                    second.get_id()
                )
            }
        }

        // requires, r_if, r_unless
        for req in &arg.requires {
            assert!(
                cmd.id_exists(&req.1),
                "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
                cmd.get_name(),
                req.1,
                arg.get_id(),
            );
        }

        for req in &arg.r_ifs {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_ifs_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq_all`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_unless {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        for req in &arg.r_unless_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // blacklist
        for req in &arg.blacklist {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // overrides
        for req in &arg.overrides {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        if arg.is_last_set() {
            assert!(
                arg.get_long().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
            assert!(
                arg.get_short().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }

        assert!(
            !(arg.is_required_set() && arg.is_global_set()),
            "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
                    cmd.get_name(),
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_positional(),
                "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
                cmd.get_name(),
                arg.get_id()
            );

            assert!(
                arg.is_trailing_var_arg_set() || arg.is_last_set(),
                "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }
    }

    for group in cmd.get_groups() {
        let derive_hint = if cfg!(feature = "derive") {
            " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
        } else {
            ""
        };

        // Name conflicts
        assert!(
            cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
            "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        // Groups should not have naming conflicts with Args
        assert!(
            !cmd.get_arguments().any(|x| x.get_id() == group.get_id()),
            "Command {}: Argument group name '{}' must not conflict with argument name{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        for arg in &group.args {
            // Args listed inside groups should exist
            assert!(
                cmd.get_arguments().any(|x| x.get_id() == arg),
                "Command {}: Argument group '{}' contains non-existent argument '{}'",
                cmd.get_name(),
                group.get_id(),
                arg
            );
        }
    }

    // Conflicts between flags and subcommands

    long_flags.sort_unstable();
    short_flags.sort_unstable();

    detect_duplicate_flags(&long_flags, "long");
    detect_duplicate_flags(&short_flags, "short");

    let mut subs = FlatSet::new();
    for sc in cmd.get_subcommands() {
        assert!(
            subs.insert(sc.get_name()),
            "Command {}: command name `{}` is duplicated",
            cmd.get_name(),
            sc.get_name()
        );
        for alias in sc.get_all_aliases() {
            assert!(
                subs.insert(alias),
                "Command {}: command `{}` alias `{}` is duplicated",
                cmd.get_name(),
                sc.get_name(),
                alias
            );
        }
    }

    _verify_positionals(cmd);

    #[cfg(feature = "help")]
    if let Some(help_template) = cmd.get_help_template() {
        assert!(
            !help_template.to_string().contains("{flags}"),
            "Command {}: {}",
                    cmd.get_name(),
            "`{flags}` template variable was removed in clap3, they are now included in `{options}`",
        );
        assert!(
            !help_template.to_string().contains("{unified}"),
            "Command {}: {}",
            cmd.get_name(),
            "`{unified}` template variable was removed in clap3, use `{options}` instead"
        );
    }

    cmd._panic_on_missing_help(cmd.is_help_expected_set());
    assert_app_flags(cmd);
}

Should we color the output?

Examples found in repository?
src/error/mod.rs (line 145)
144
145
146
147
148
    pub fn with_cmd(self, cmd: &Command) -> Self {
        self.set_color(cmd.get_color())
            .set_colored_help(cmd.color_help())
            .set_help_flag(format::get_help_flag(cmd))
    }
More examples
Hide additional examples
src/builder/command.rs (line 4619)
4613
4614
4615
4616
4617
4618
4619
4620
    pub(crate) fn color_help(&self) -> ColorChoice {
        #[cfg(feature = "color")]
        if self.is_disable_colored_help_set() {
            return ColorChoice::Never;
        }

        self.get_color()
    }

Iterate through the set of subcommands, getting a reference to each.

Examples found in repository?
src/builder/command.rs (line 3430)
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
    pub fn find_subcommand(&self, name: impl AsRef<std::ffi::OsStr>) -> Option<&Command> {
        let name = name.as_ref();
        self.get_subcommands().find(|s| s.aliases_to(name))
    }

    /// Find subcommand such that its name or one of aliases equals `name`, returning
    /// a mutable reference to the subcommand.
    ///
    /// This does not recurse through subcommands of subcommands.
    #[inline]
    pub fn find_subcommand_mut(
        &mut self,
        name: impl AsRef<std::ffi::OsStr>,
    ) -> Option<&mut Command> {
        let name = name.as_ref();
        self.get_subcommands_mut().find(|s| s.aliases_to(name))
    }

    /// Iterate through the set of groups.
    #[inline]
    pub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup> {
        self.groups.iter()
    }

    /// Iterate through the set of arguments.
    #[inline]
    pub fn get_arguments(&self) -> impl Iterator<Item = &Arg> {
        self.args.args()
    }

    /// Iterate through the *positionals* arguments.
    #[inline]
    pub fn get_positionals(&self) -> impl Iterator<Item = &Arg> {
        self.get_arguments().filter(|a| a.is_positional())
    }

    /// Iterate through the *options*.
    pub fn get_opts(&self) -> impl Iterator<Item = &Arg> {
        self.get_arguments()
            .filter(|a| a.is_takes_value_set() && !a.is_positional())
    }

    /// Get a list of all arguments the given argument conflicts with.
    ///
    /// If the provided argument is declared as global, the conflicts will be determined
    /// based on the propagation rules of global arguments.
    ///
    /// ### Panics
    ///
    /// If the given arg contains a conflict with an argument that is unknown to
    /// this `Command`.
    pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
    {
        if arg.is_global_set() {
            self.get_global_arg_conflicts_with(arg)
        } else {
            let mut result = Vec::new();
            for id in arg.blacklist.iter() {
                if let Some(arg) = self.find(id) {
                    result.push(arg);
                } else if let Some(group) = self.find_group(id) {
                    result.extend(
                        self.unroll_args_in_group(&group.id)
                            .iter()
                            .map(|id| self.find(id).expect(INTERNAL_ERROR_MSG)),
                    );
                } else {
                    panic!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd");
                }
            }
            result
        }
    }

    // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with.
    //
    // This behavior follows the propagation rules of global arguments.
    // It is useful for finding conflicts for arguments declared as global.
    //
    // ### Panics
    //
    // If the given arg contains a conflict with an argument that is unknown to
    // this `Command`.
    fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
    {
        arg.blacklist
            .iter()
            .map(|id| {
                self.args
                    .args()
                    .chain(
                        self.get_subcommands_containing(arg)
                            .iter()
                            .flat_map(|x| x.args.args()),
                    )
                    .find(|arg| arg.get_id() == id)
                    .expect(
                        "Command::get_arg_conflicts_with: \
                    The passed arg conflicts with an arg unknown to the cmd",
                    )
            })
            .collect()
    }

    // Get a list of subcommands which contain the provided Argument
    //
    // This command will only include subcommands in its list for which the subcommands
    // parent also contains the Argument.
    //
    // This search follows the propagation rules of global arguments.
    // It is useful to finding subcommands, that have inherited a global argument.
    //
    // **NOTE:** In this case only Sucommand_1 will be included
    //   Subcommand_1 (contains Arg)
    //     Subcommand_1.1 (doesn't contain Arg)
    //       Subcommand_1.1.1 (contains Arg)
    //
    fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&Self> {
        let mut vec = std::vec::Vec::new();
        for idx in 0..self.subcommands.len() {
            if self.subcommands[idx]
                .args
                .args()
                .any(|ar| ar.get_id() == arg.get_id())
            {
                vec.push(&self.subcommands[idx]);
                vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg));
            }
        }
        vec
    }

    /// Report whether [`Command::no_binary_name`] is set
    pub fn is_no_binary_name_set(&self) -> bool {
        self.is_set(AppSettings::NoBinaryName)
    }

    /// Report whether [`Command::ignore_errors`] is set
    pub(crate) fn is_ignore_errors_set(&self) -> bool {
        self.is_set(AppSettings::IgnoreErrors)
    }

    /// Report whether [`Command::dont_delimit_trailing_values`] is set
    pub fn is_dont_delimit_trailing_values_set(&self) -> bool {
        self.is_set(AppSettings::DontDelimitTrailingValues)
    }

    /// Report whether [`Command::disable_version_flag`] is set
    pub fn is_disable_version_flag_set(&self) -> bool {
        self.is_set(AppSettings::DisableVersionFlag)
            || (self.version.is_none() && self.long_version.is_none())
    }

    /// Report whether [`Command::propagate_version`] is set
    pub fn is_propagate_version_set(&self) -> bool {
        self.is_set(AppSettings::PropagateVersion)
    }

    /// Report whether [`Command::next_line_help`] is set
    pub fn is_next_line_help_set(&self) -> bool {
        self.is_set(AppSettings::NextLineHelp)
    }

    /// Report whether [`Command::disable_help_flag`] is set
    pub fn is_disable_help_flag_set(&self) -> bool {
        self.is_set(AppSettings::DisableHelpFlag)
    }

    /// Report whether [`Command::disable_help_subcommand`] is set
    pub fn is_disable_help_subcommand_set(&self) -> bool {
        self.is_set(AppSettings::DisableHelpSubcommand)
    }

    /// Report whether [`Command::disable_colored_help`] is set
    pub fn is_disable_colored_help_set(&self) -> bool {
        self.is_set(AppSettings::DisableColoredHelp)
    }

    /// Report whether [`Command::help_expected`] is set
    #[cfg(debug_assertions)]
    pub(crate) fn is_help_expected_set(&self) -> bool {
        self.is_set(AppSettings::HelpExpected)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "This is now the default")
    )]
    pub fn is_dont_collapse_args_in_usage_set(&self) -> bool {
        true
    }

    /// Report whether [`Command::infer_long_args`] is set
    pub(crate) fn is_infer_long_args_set(&self) -> bool {
        self.is_set(AppSettings::InferLongArgs)
    }

    /// Report whether [`Command::infer_subcommands`] is set
    pub(crate) fn is_infer_subcommands_set(&self) -> bool {
        self.is_set(AppSettings::InferSubcommands)
    }

    /// Report whether [`Command::arg_required_else_help`] is set
    pub fn is_arg_required_else_help_set(&self) -> bool {
        self.is_set(AppSettings::ArgRequiredElseHelp)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(
            since = "4.0.0",
            note = "Replaced with `Arg::is_allow_hyphen_values_set`"
        )
    )]
    pub(crate) fn is_allow_hyphen_values_set(&self) -> bool {
        self.is_set(AppSettings::AllowHyphenValues)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(
            since = "4.0.0",
            note = "Replaced with `Arg::is_allow_negative_numbers_set`"
        )
    )]
    pub fn is_allow_negative_numbers_set(&self) -> bool {
        self.is_set(AppSettings::AllowNegativeNumbers)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "Replaced with `Arg::is_trailing_var_arg_set`")
    )]
    pub fn is_trailing_var_arg_set(&self) -> bool {
        self.is_set(AppSettings::TrailingVarArg)
    }

    /// Report whether [`Command::allow_missing_positional`] is set
    pub fn is_allow_missing_positional_set(&self) -> bool {
        self.is_set(AppSettings::AllowMissingPositional)
    }

    /// Report whether [`Command::hide`] is set
    pub fn is_hide_set(&self) -> bool {
        self.is_set(AppSettings::Hidden)
    }

    /// Report whether [`Command::subcommand_required`] is set
    pub fn is_subcommand_required_set(&self) -> bool {
        self.is_set(AppSettings::SubcommandRequired)
    }

    /// Report whether [`Command::allow_external_subcommands`] is set
    pub fn is_allow_external_subcommands_set(&self) -> bool {
        self.is_set(AppSettings::AllowExternalSubcommands)
    }

    /// Configured parser for values passed to an external subcommand
    ///
    /// # Example
    ///
    /// ```rust
    /// let cmd = clap::Command::new("raw")
    ///     .external_subcommand_value_parser(clap::value_parser!(String));
    /// let value_parser = cmd.get_external_subcommand_value_parser();
    /// println!("{:?}", value_parser);
    /// ```
    pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> {
        if !self.is_allow_external_subcommands_set() {
            None
        } else {
            static DEFAULT: super::ValueParser = super::ValueParser::os_string();
            Some(self.external_value_parser.as_ref().unwrap_or(&DEFAULT))
        }
    }

    /// Report whether [`Command::args_conflicts_with_subcommands`] is set
    pub fn is_args_conflicts_with_subcommands_set(&self) -> bool {
        self.is_set(AppSettings::ArgsNegateSubcommands)
    }

    #[doc(hidden)]
    pub fn is_args_override_self(&self) -> bool {
        self.is_set(AppSettings::AllArgsOverrideSelf)
    }

    /// Report whether [`Command::subcommand_precedence_over_arg`] is set
    pub fn is_subcommand_precedence_over_arg_set(&self) -> bool {
        self.is_set(AppSettings::SubcommandPrecedenceOverArg)
    }

    /// Report whether [`Command::subcommand_negates_reqs`] is set
    pub fn is_subcommand_negates_reqs_set(&self) -> bool {
        self.is_set(AppSettings::SubcommandsNegateReqs)
    }

    /// Report whether [`Command::multicall`] is set
    pub fn is_multicall_set(&self) -> bool {
        self.is_set(AppSettings::Multicall)
    }
}

// Internally used only
impl Command {
    pub(crate) fn get_override_usage(&self) -> Option<&StyledStr> {
        self.usage_str.as_ref()
    }

    pub(crate) fn get_override_help(&self) -> Option<&StyledStr> {
        self.help_str.as_ref()
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_help_template(&self) -> Option<&StyledStr> {
        self.template.as_ref()
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_term_width(&self) -> Option<usize> {
        self.term_w
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_max_term_width(&self) -> Option<usize> {
        self.max_w
    }

    pub(crate) fn get_replacement(&self, key: &str) -> Option<&[Str]> {
        self.replacers.get(key).map(|v| v.as_slice())
    }

    pub(crate) fn get_keymap(&self) -> &MKeyMap {
        &self.args
    }

    fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec<Id>) {
        global_arg_vec.extend(
            self.args
                .args()
                .filter(|a| a.is_global_set())
                .map(|ga| ga.id.clone()),
        );
        if let Some((id, matches)) = matches.subcommand() {
            if let Some(used_sub) = self.find_subcommand(id) {
                used_sub.get_used_global_args(matches, global_arg_vec);
            }
        }
    }

    fn _do_parse(
        &mut self,
        raw_args: &mut clap_lex::RawArgs,
        args_cursor: clap_lex::ArgCursor,
    ) -> ClapResult<ArgMatches> {
        debug!("Command::_do_parse");

        // If there are global arguments, or settings we need to propagate them down to subcommands
        // before parsing in case we run into a subcommand
        self._build_self(false);

        let mut matcher = ArgMatcher::new(self);

        // do the real parsing
        let mut parser = Parser::new(self);
        if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) {
            if self.is_set(AppSettings::IgnoreErrors) {
                debug!("Command::_do_parse: ignoring error: {}", error);
            } else {
                return Err(error);
            }
        }

        let mut global_arg_vec = Default::default();
        self.get_used_global_args(&matcher, &mut global_arg_vec);

        matcher.propagate_globals(&global_arg_vec);

        Ok(matcher.into_inner())
    }

    /// Prepare for introspecting on all included [`Command`]s
    ///
    /// Call this on the top-level [`Command`] when done building and before reading state for
    /// cases like completions, custom help output, etc.
    pub fn build(&mut self) {
        self._build_recursive(true);
        self._build_bin_names_internal();
    }

    pub(crate) fn _build_recursive(&mut self, expand_help_tree: bool) {
        self._build_self(expand_help_tree);
        for subcmd in self.get_subcommands_mut() {
            subcmd._build_recursive(expand_help_tree);
        }
    }

    pub(crate) fn _build_self(&mut self, expand_help_tree: bool) {
        debug!("Command::_build: name={:?}", self.get_name());
        if !self.settings.is_set(AppSettings::Built) {
            // Make sure all the globally set flags apply to us as well
            self.settings = self.settings | self.g_settings;

            if self.is_multicall_set() {
                self.settings.insert(AppSettings::SubcommandRequired.into());
                self.settings.insert(AppSettings::DisableHelpFlag.into());
                self.settings.insert(AppSettings::DisableVersionFlag.into());
            }
            if !cfg!(feature = "help") && self.get_override_help().is_none() {
                self.settings.insert(AppSettings::DisableHelpFlag.into());
                self.settings
                    .insert(AppSettings::DisableHelpSubcommand.into());
            }
            if self.is_set(AppSettings::ArgsNegateSubcommands) {
                self.settings
                    .insert(AppSettings::SubcommandsNegateReqs.into());
            }
            if self.external_value_parser.is_some() {
                self.settings
                    .insert(AppSettings::AllowExternalSubcommands.into());
            }
            if !self.has_subcommands() {
                self.settings
                    .insert(AppSettings::DisableHelpSubcommand.into());
            }

            self._propagate();
            self._check_help_and_version(expand_help_tree);
            self._propagate_global_args();

            let mut pos_counter = 1;
            let hide_pv = self.is_set(AppSettings::HidePossibleValues);
            for a in self.args.args_mut() {
                // Fill in the groups
                for g in &a.groups {
                    if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) {
                        ag.args.push(a.get_id().clone());
                    } else {
                        let mut ag = ArgGroup::new(g);
                        ag.args.push(a.get_id().clone());
                        self.groups.push(ag);
                    }
                }

                // Figure out implied settings
                a._build();
                if hide_pv && a.is_takes_value_set() {
                    a.settings.set(ArgSettings::HidePossibleValues);
                }
                if a.is_positional() && a.index.is_none() {
                    a.index = Some(pos_counter);
                    pos_counter += 1;
                }
            }

            self.args._build();

            #[allow(deprecated)]
            {
                let highest_idx = self
                    .get_keymap()
                    .keys()
                    .filter_map(|x| {
                        if let crate::mkeymap::KeyType::Position(n) = x {
                            Some(*n)
                        } else {
                            None
                        }
                    })
                    .max()
                    .unwrap_or(0);
                let is_trailing_var_arg_set = self.is_trailing_var_arg_set();
                let is_allow_hyphen_values_set = self.is_allow_hyphen_values_set();
                let is_allow_negative_numbers_set = self.is_allow_negative_numbers_set();
                for arg in self.args.args_mut() {
                    if is_allow_hyphen_values_set && arg.is_takes_value_set() {
                        arg.settings.insert(ArgSettings::AllowHyphenValues.into());
                    }
                    if is_allow_negative_numbers_set && arg.is_takes_value_set() {
                        arg.settings
                            .insert(ArgSettings::AllowNegativeNumbers.into());
                    }
                    if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) {
                        arg.settings.insert(ArgSettings::TrailingVarArg.into());
                    }
                }
            }

            #[cfg(debug_assertions)]
            assert_app(self);
            self.settings.set(AppSettings::Built);
        } else {
            debug!("Command::_build: already built");
        }
    }

    pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> {
        use std::fmt::Write;

        let mut mid_string = String::from(" ");
        #[cfg(feature = "usage")]
        if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set()
        {
            let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

            for s in &reqs {
                mid_string.push_str(&s.to_string());
                mid_string.push(' ');
            }
        }
        let is_multicall_set = self.is_multicall_set();

        let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name));

        // Display subcommand name, short and long in usage
        let mut sc_names = String::new();
        sc_names.push_str(sc.name.as_str());
        let mut flag_subcmd = false;
        if let Some(l) = sc.get_long_flag() {
            write!(sc_names, "|--{}", l).unwrap();
            flag_subcmd = true;
        }
        if let Some(s) = sc.get_short_flag() {
            write!(sc_names, "|-{}", s).unwrap();
            flag_subcmd = true;
        }

        if flag_subcmd {
            sc_names = format!("{{{}}}", sc_names);
        }

        let usage_name = self
            .bin_name
            .as_ref()
            .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names))
            .unwrap_or(sc_names);
        sc.usage_name = Some(usage_name);

        // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
        // a space
        let bin_name = format!(
            "{}{}{}",
            self.bin_name.as_deref().unwrap_or_default(),
            if self.bin_name.is_some() { " " } else { "" },
            &*sc.name
        );
        debug!(
            "Command::_build_subcommand Setting bin_name of {} to {:?}",
            sc.name, bin_name
        );
        sc.bin_name = Some(bin_name);

        if sc.display_name.is_none() {
            let self_display_name = if is_multicall_set {
                self.display_name.as_deref().unwrap_or("")
            } else {
                self.display_name.as_deref().unwrap_or(&self.name)
            };
            let display_name = format!(
                "{}{}{}",
                self_display_name,
                if !self_display_name.is_empty() {
                    "-"
                } else {
                    ""
                },
                &*sc.name
            );
            debug!(
                "Command::_build_subcommand Setting display_name of {} to {:?}",
                sc.name, display_name
            );
            sc.display_name = Some(display_name);
        }

        // Ensure all args are built and ready to parse
        sc._build_self(false);

        Some(sc)
    }

    fn _build_bin_names_internal(&mut self) {
        debug!("Command::_build_bin_names");

        if !self.is_set(AppSettings::BinNameBuilt) {
            let mut mid_string = String::from(" ");
            #[cfg(feature = "usage")]
            if !self.is_subcommand_negates_reqs_set()
                && !self.is_args_conflicts_with_subcommands_set()
            {
                let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

                for s in &reqs {
                    mid_string.push_str(&s.to_string());
                    mid_string.push(' ');
                }
            }
            let is_multicall_set = self.is_multicall_set();

            let self_bin_name = if is_multicall_set {
                self.bin_name.as_deref().unwrap_or("")
            } else {
                self.bin_name.as_deref().unwrap_or(&self.name)
            }
            .to_owned();

            for mut sc in &mut self.subcommands {
                debug!("Command::_build_bin_names:iter: bin_name set...");

                if sc.usage_name.is_none() {
                    use std::fmt::Write;
                    // Display subcommand name, short and long in usage
                    let mut sc_names = String::new();
                    sc_names.push_str(sc.name.as_str());
                    let mut flag_subcmd = false;
                    if let Some(l) = sc.get_long_flag() {
                        write!(sc_names, "|--{}", l).unwrap();
                        flag_subcmd = true;
                    }
                    if let Some(s) = sc.get_short_flag() {
                        write!(sc_names, "|-{}", s).unwrap();
                        flag_subcmd = true;
                    }

                    if flag_subcmd {
                        sc_names = format!("{{{}}}", sc_names);
                    }

                    let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names);
                    debug!(
                        "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}",
                        sc.name, usage_name
                    );
                    sc.usage_name = Some(usage_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})",
                        sc.name, sc.usage_name
                    );
                }

                if sc.bin_name.is_none() {
                    let bin_name = format!(
                        "{}{}{}",
                        self_bin_name,
                        if !self_bin_name.is_empty() { " " } else { "" },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}",
                        sc.name, bin_name
                    );
                    sc.bin_name = Some(bin_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})",
                        sc.name, sc.bin_name
                    );
                }

                if sc.display_name.is_none() {
                    let self_display_name = if is_multicall_set {
                        self.display_name.as_deref().unwrap_or("")
                    } else {
                        self.display_name.as_deref().unwrap_or(&self.name)
                    };
                    let display_name = format!(
                        "{}{}{}",
                        self_display_name,
                        if !self_display_name.is_empty() {
                            "-"
                        } else {
                            ""
                        },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting display_name of {} to {:?}",
                        sc.name, display_name
                    );
                    sc.display_name = Some(display_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})",
                        sc.name, sc.display_name
                    );
                }

                sc._build_bin_names_internal();
            }
            self.set(AppSettings::BinNameBuilt);
        } else {
            debug!("Command::_build_bin_names: already built");
        }
    }

    pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) {
        if self.is_set(AppSettings::HelpExpected) || help_required_globally {
            let args_missing_help: Vec<Id> = self
                .args
                .args()
                .filter(|arg| arg.get_help().is_none() && arg.get_long_help().is_none())
                .map(|arg| arg.get_id().clone())
                .collect();

            debug_assert!(args_missing_help.is_empty(),
                    "Command::help_expected is enabled for the Command {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}",
                    self.name,
                    args_missing_help.join(", ")
                );
        }

        for sub_app in &self.subcommands {
            sub_app._panic_on_missing_help(help_required_globally);
        }
    }

    #[cfg(debug_assertions)]
    pub(crate) fn two_args_of<F>(&self, condition: F) -> Option<(&Arg, &Arg)>
    where
        F: Fn(&Arg) -> bool,
    {
        two_elements_of(self.args.args().filter(|a: &&Arg| condition(a)))
    }

    // just in case
    #[allow(unused)]
    fn two_groups_of<F>(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)>
    where
        F: Fn(&ArgGroup) -> bool,
    {
        two_elements_of(self.groups.iter().filter(|a| condition(a)))
    }

    /// Propagate global args
    pub(crate) fn _propagate_global_args(&mut self) {
        debug!("Command::_propagate_global_args:{}", self.name);

        let autogenerated_help_subcommand = !self.is_disable_help_subcommand_set();

        for sc in &mut self.subcommands {
            if sc.get_name() == "help" && autogenerated_help_subcommand {
                // Avoid propagating args to the autogenerated help subtrees used in completion.
                // This prevents args from showing up during help completions like
                // `myapp help subcmd <TAB>`, which should only suggest subcommands and not args,
                // while still allowing args to show up properly on the generated help message.
                continue;
            }

            for a in self.args.args().filter(|a| a.is_global_set()) {
                if sc.find(&a.id).is_some() {
                    debug!(
                        "Command::_propagate skipping {:?} to {}, already exists",
                        a.id,
                        sc.get_name(),
                    );
                    continue;
                }

                debug!(
                    "Command::_propagate pushing {:?} to {}",
                    a.id,
                    sc.get_name(),
                );
                sc.args.push(a.clone());
            }
        }
    }

    /// Propagate settings
    pub(crate) fn _propagate(&mut self) {
        debug!("Command::_propagate:{}", self.name);
        let mut subcommands = std::mem::take(&mut self.subcommands);
        for sc in &mut subcommands {
            self._propagate_subcommand(sc);
        }
        self.subcommands = subcommands;
    }

    fn _propagate_subcommand(&self, sc: &mut Self) {
        // We have to create a new scope in order to tell rustc the borrow of `sc` is
        // done and to recursively call this method
        {
            if self.settings.is_set(AppSettings::PropagateVersion) {
                if let Some(version) = self.version.as_ref() {
                    sc.version.get_or_insert_with(|| version.clone());
                }
                if let Some(long_version) = self.long_version.as_ref() {
                    sc.long_version.get_or_insert_with(|| long_version.clone());
                }
            }

            sc.settings = sc.settings | self.g_settings;
            sc.g_settings = sc.g_settings | self.g_settings;
            sc.term_w = self.term_w;
            sc.max_w = self.max_w;
        }
    }

    pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) {
        debug!(
            "Command::_check_help_and_version:{} expand_help_tree={}",
            self.name, expand_help_tree
        );

        self.long_help_exists = self.long_help_exists_();

        if !self.is_disable_help_flag_set() {
            debug!("Command::_check_help_and_version: Building default --help");
            let mut arg = Arg::new(Id::HELP)
                .short('h')
                .long("help")
                .action(ArgAction::Help);
            if self.long_help_exists {
                arg = arg
                    .help("Print help information (use `--help` for more detail)")
                    .long_help("Print help information (use `-h` for a summary)");
            } else {
                arg = arg.help("Print help information");
            }
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }
        if !self.is_disable_version_flag_set() {
            debug!("Command::_check_help_and_version: Building default --version");
            let arg = Arg::new(Id::VERSION)
                .short('V')
                .long("version")
                .action(ArgAction::Version)
                .help("Print version information");
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }

        if !self.is_set(AppSettings::DisableHelpSubcommand) {
            debug!("Command::_check_help_and_version: Building help subcommand");
            let help_about = "Print this message or the help of the given subcommand(s)";

            let mut help_subcmd = if expand_help_tree {
                // Slow code path to recursively clone all other subcommand subtrees under help
                let help_subcmd = Command::new("help")
                    .about(help_about)
                    .global_setting(AppSettings::DisableHelpSubcommand)
                    .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));

                let mut help_help_subcmd = Command::new("help").about(help_about);
                help_help_subcmd.version = None;
                help_help_subcmd.long_version = None;
                help_help_subcmd = help_help_subcmd
                    .setting(AppSettings::DisableHelpFlag)
                    .setting(AppSettings::DisableVersionFlag);

                help_subcmd.subcommand(help_help_subcmd)
            } else {
                Command::new("help").about(help_about).arg(
                    Arg::new("subcommand")
                        .action(ArgAction::Append)
                        .num_args(..)
                        .value_name("COMMAND")
                        .help("Print help for the subcommand(s)"),
                )
            };
            self._propagate_subcommand(&mut help_subcmd);

            // The parser acts like this is set, so let's set it so we don't falsely
            // advertise it to the user
            help_subcmd.version = None;
            help_subcmd.long_version = None;
            help_subcmd = help_subcmd
                .setting(AppSettings::DisableHelpFlag)
                .setting(AppSettings::DisableVersionFlag)
                .unset_global_setting(AppSettings::PropagateVersion);

            self.subcommands.push(help_subcmd);
        }
    }

    fn _copy_subtree_for_help(&self) -> Command {
        let mut cmd = Command::new(self.name.clone())
            .hide(self.is_hide_set())
            .global_setting(AppSettings::DisableHelpFlag)
            .global_setting(AppSettings::DisableVersionFlag)
            .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));
        if self.get_about().is_some() {
            cmd = cmd.about(self.get_about().unwrap().clone());
        }
        cmd
    }

    pub(crate) fn _render_version(&self, use_long: bool) -> String {
        debug!("Command::_render_version");

        let ver = if use_long {
            self.long_version
                .as_deref()
                .or(self.version.as_deref())
                .unwrap_or_default()
        } else {
            self.version
                .as_deref()
                .or(self.long_version.as_deref())
                .unwrap_or_default()
        };
        let display_name = self.get_display_name().unwrap_or_else(|| self.get_name());
        format!("{} {}\n", display_name, ver)
    }

    pub(crate) fn format_group(&self, g: &Id) -> StyledStr {
        let g_string = self
            .unroll_args_in_group(g)
            .iter()
            .filter_map(|x| self.find(x))
            .map(|x| {
                if x.is_positional() {
                    // Print val_name for positional arguments. e.g. <file_name>
                    x.name_no_brackets()
                } else {
                    // Print usage string for flags arguments, e.g. <--help>
                    x.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join("|");
        let mut styled = StyledStr::new();
        styled.none("<");
        styled.none(g_string);
        styled.none(">");
        styled
    }
}

/// A workaround:
/// <https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999>
pub(crate) trait Captures<'a> {}
impl<'a, T> Captures<'a> for T {}

// Internal Query Methods
impl Command {
    /// Iterate through the *flags* & *options* arguments.
    #[cfg(any(feature = "usage", feature = "help"))]
    pub(crate) fn get_non_positionals(&self) -> impl Iterator<Item = &Arg> {
        self.get_arguments().filter(|a| !a.is_positional())
    }

    pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg> {
        self.args.args().find(|a| a.get_id() == arg_id)
    }

    #[inline]
    pub(crate) fn contains_short(&self, s: char) -> bool {
        debug_assert!(
            self.is_set(AppSettings::Built),
            "If Command::_build hasn't been called, manually search through Arg shorts"
        );

        self.args.contains(s)
    }

    #[inline]
    pub(crate) fn set(&mut self, s: AppSettings) {
        self.settings.set(s)
    }

    #[inline]
    pub(crate) fn has_positionals(&self) -> bool {
        self.get_positionals().next().is_some()
    }

    #[cfg(any(feature = "usage", feature = "help"))]
    pub(crate) fn has_visible_subcommands(&self) -> bool {
        self.subcommands
            .iter()
            .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden))
    }

    /// Check if this subcommand can be referred to as `name`. In other words,
    /// check if `name` is the name of this subcommand or is one of its aliases.
    #[inline]
    pub(crate) fn aliases_to(&self, name: impl AsRef<std::ffi::OsStr>) -> bool {
        let name = name.as_ref();
        self.get_name() == name || self.get_all_aliases().any(|alias| alias == name)
    }

    /// Check if this subcommand can be referred to as `name`. In other words,
    /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases.
    #[inline]
    pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool {
        Some(flag) == self.short_flag
            || self.get_all_short_flag_aliases().any(|alias| flag == alias)
    }

    /// Check if this subcommand can be referred to as `name`. In other words,
    /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases.
    #[inline]
    pub(crate) fn long_flag_aliases_to(&self, flag: &str) -> bool {
        match self.long_flag.as_ref() {
            Some(long_flag) => {
                long_flag == flag || self.get_all_long_flag_aliases().any(|alias| alias == flag)
            }
            None => self.get_all_long_flag_aliases().any(|alias| alias == flag),
        }
    }

    #[cfg(debug_assertions)]
    pub(crate) fn id_exists(&self, id: &Id) -> bool {
        self.args.args().any(|x| x.get_id() == id) || self.groups.iter().any(|x| x.id == *id)
    }

    /// Iterate through the groups this arg is member of.
    pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator<Item = Id> + 'a {
        debug!("Command::groups_for_arg: id={:?}", arg);
        let arg = arg.clone();
        self.groups
            .iter()
            .filter(move |grp| grp.args.iter().any(|a| a == &arg))
            .map(|grp| grp.id.clone())
    }

    pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup> {
        self.groups.iter().find(|g| g.id == *group_id)
    }

    /// Iterate through all the names of all subcommands (not recursively), including aliases.
    /// Used for suggestions.
    pub(crate) fn all_subcommand_names(&self) -> impl Iterator<Item = &str> + Captures {
        self.get_subcommands().flat_map(|sc| {
            let name = sc.get_name();
            let aliases = sc.get_all_aliases();
            std::iter::once(name).chain(aliases)
        })
    }

    pub(crate) fn required_graph(&self) -> ChildGraph<Id> {
        let mut reqs = ChildGraph::with_capacity(5);
        for a in self.args.args().filter(|a| a.is_required_set()) {
            reqs.insert(a.get_id().clone());
        }
        for group in &self.groups {
            if group.required {
                let idx = reqs.insert(group.id.clone());
                for a in &group.requires {
                    reqs.insert_child(idx, a.clone());
                }
            }
        }

        reqs
    }

    pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec<Id> {
        debug!("Command::unroll_args_in_group: group={:?}", group);
        let mut g_vec = vec![group];
        let mut args = vec![];

        while let Some(g) = g_vec.pop() {
            for n in self
                .groups
                .iter()
                .find(|grp| grp.id == *g)
                .expect(INTERNAL_ERROR_MSG)
                .args
                .iter()
            {
                debug!("Command::unroll_args_in_group:iter: entity={:?}", n);
                if !args.contains(n) {
                    if self.find(n).is_some() {
                        debug!("Command::unroll_args_in_group:iter: this is an arg");
                        args.push(n.clone())
                    } else {
                        debug!("Command::unroll_args_in_group:iter: this is a group");
                        g_vec.push(n);
                    }
                }
            }
        }

        args
    }

    pub(crate) fn unroll_arg_requires<F>(&self, func: F, arg: &Id) -> Vec<Id>
    where
        F: Fn(&(ArgPredicate, Id)) -> Option<Id>,
    {
        let mut processed = vec![];
        let mut r_vec = vec![arg];
        let mut args = vec![];

        while let Some(a) = r_vec.pop() {
            if processed.contains(&a) {
                continue;
            }

            processed.push(a);

            if let Some(arg) = self.find(a) {
                for r in arg.requires.iter().filter_map(&func) {
                    if let Some(req) = self.find(&r) {
                        if !req.requires.is_empty() {
                            r_vec.push(req.get_id())
                        }
                    }
                    args.push(r);
                }
            }
        }

        args
    }

    /// Find a flag subcommand name by short flag or an alias
    pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> {
        self.get_subcommands()
            .find(|sc| sc.short_flag_aliases_to(c))
            .map(|sc| sc.get_name())
    }

    /// Find a flag subcommand name by long flag or an alias
    pub(crate) fn find_long_subcmd(&self, long: &str) -> Option<&str> {
        self.get_subcommands()
            .find(|sc| sc.long_flag_aliases_to(long))
            .map(|sc| sc.get_name())
    }
More examples
Hide additional examples
src/parser/arg_matcher.rs (line 34)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    pub(crate) fn new(_cmd: &Command) -> Self {
        ArgMatcher {
            matches: ArgMatches {
                #[cfg(debug_assertions)]
                valid_args: {
                    let args = _cmd.get_arguments().map(|a| a.get_id().clone());
                    let groups = _cmd.get_groups().map(|g| g.get_id().clone());
                    args.chain(groups).collect()
                },
                #[cfg(debug_assertions)]
                valid_subcommands: _cmd
                    .get_subcommands()
                    .map(|sc| sc.get_name_str().clone())
                    .collect(),
                ..Default::default()
            },
            pending: None,
        }
    }
src/parser/parser.rs (line 585)
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
    fn possible_long_flag_subcommand(&self, arg: &str) -> Option<&str> {
        debug!("Parser::possible_long_flag_subcommand: arg={:?}", arg);
        if self.cmd.is_infer_subcommands_set() {
            let options = self
                .cmd
                .get_subcommands()
                .fold(Vec::new(), |mut options, sc| {
                    if let Some(long) = sc.get_long_flag() {
                        if long.starts_with(arg) {
                            options.push(long);
                        }
                        options.extend(sc.get_all_aliases().filter(|alias| alias.starts_with(arg)))
                    }
                    options
                });
            if options.len() == 1 {
                return Some(options[0]);
            }

            for sc in options {
                if sc == arg {
                    return Some(sc);
                }
            }
        } else if let Some(sc_name) = self.cmd.find_long_subcmd(arg) {
            return Some(sc_name);
        }
        None
    }
src/output/help_template.rs (line 830)
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
    fn write_subcommands(&mut self, cmd: &Command) {
        debug!("HelpTemplate::write_subcommands");
        // The shortest an arg can legally be is 2 (i.e. '-x')
        let mut longest = 2;
        let mut ord_v = Vec::new();
        for subcommand in cmd
            .get_subcommands()
            .filter(|subcommand| should_show_subcommand(subcommand))
        {
            let mut styled = StyledStr::new();
            styled.literal(subcommand.get_name());
            if let Some(short) = subcommand.get_short_flag() {
                styled.none(", ");
                styled.literal(format!("-{}", short));
            }
            if let Some(long) = subcommand.get_long_flag() {
                styled.none(", ");
                styled.literal(format!("--{}", long));
            }
            longest = longest.max(styled.display_width());
            ord_v.push((subcommand.get_display_order(), styled, subcommand));
        }
        ord_v.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));

        debug!("HelpTemplate::write_subcommands longest = {}", longest);

        let next_line_help = self.will_subcommands_wrap(cmd.get_subcommands(), longest);

        let mut first = true;
        for (_, sc_str, sc) in ord_v {
            if first {
                first = false;
            } else {
                self.none("\n");
            }
            self.write_subcommand(sc_str, sc, next_line_help, longest);
        }
    }
src/builder/debug_asserts.rs (line 41)
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
pub(crate) fn assert_app(cmd: &Command) {
    debug!("Command::_debug_asserts");

    let mut short_flags = vec![];
    let mut long_flags = vec![];

    // Invalid version flag settings
    if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
        // PropagateVersion is meaningless if there is no version
        assert!(
            !cmd.is_propagate_version_set(),
            "Command {}: No version information via Command::version or Command::long_version to propagate",
            cmd.get_name(),
        );

        // Used `Command::mut_arg("version", ..) but did not provide any version information to display
        let version_needed = cmd
            .get_arguments()
            .filter(|x| matches!(x.get_action(), ArgAction::Version))
            .map(|x| x.get_id())
            .collect::<Vec<_>>();

        assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
            ,cmd.get_name()
        );
    }

    for sc in cmd.get_subcommands() {
        if let Some(s) = sc.get_short_flag().as_ref() {
            short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
        }

        for short_alias in sc.get_all_short_flag_aliases() {
            short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
        }

        if let Some(l) = sc.get_long_flag().as_ref() {
            assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
            long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
        }

        for long_alias in sc.get_all_long_flag_aliases() {
            long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
        }
    }

    for arg in cmd.get_arguments() {
        assert_arg(arg);

        assert!(
            !cmd.is_multicall_set(),
            "Command {}: Arguments like {} cannot be set on a multicall command",
            cmd.get_name(),
            arg.get_id()
        );

        if let Some(s) = arg.get_short() {
            short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str()));
        }

        for (short_alias, _) in &arg.short_aliases {
            short_flags.push(Flag::Arg(
                format!("-{}", short_alias),
                arg.get_id().as_str(),
            ));
        }

        if let Some(l) = arg.get_long() {
            assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l);
            long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str()));
        }

        for (long_alias, _) in &arg.aliases {
            long_flags.push(Flag::Arg(
                format!("--{}", long_alias),
                arg.get_id().as_str(),
            ));
        }

        // Name conflicts
        if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
            panic!(
            "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
            cmd.get_name(),
            arg.get_id(),
            duplicate_tip(cmd, first, second),
        );
        }

        // Long conflicts
        if let Some(l) = arg.get_long() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) {
                panic!(
                    "Command {}: Long option names must be unique for each argument, \
                            but '--{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    l,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second)
                )
            }
        }

        // Short conflicts
        if let Some(s) = arg.get_short() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
                panic!(
                    "Command {}: Short option names must be unique for each argument, \
                            but '-{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    s,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second),
                )
            }
        }

        // Index conflicts
        if let Some(idx) = arg.index {
            if let Some((first, second)) =
                cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
            {
                panic!(
                    "Command {}: Argument '{}' has the same index as '{}' \
                    and they are both positional arguments\n\n\t \
                    Use `Arg::num_args(1..)` to allow one \
                    positional argument to take multiple values",
                    cmd.get_name(),
                    first.get_id(),
                    second.get_id()
                )
            }
        }

        // requires, r_if, r_unless
        for req in &arg.requires {
            assert!(
                cmd.id_exists(&req.1),
                "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
                cmd.get_name(),
                req.1,
                arg.get_id(),
            );
        }

        for req in &arg.r_ifs {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_ifs_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq_all`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_unless {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        for req in &arg.r_unless_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // blacklist
        for req in &arg.blacklist {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // overrides
        for req in &arg.overrides {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        if arg.is_last_set() {
            assert!(
                arg.get_long().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
            assert!(
                arg.get_short().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }

        assert!(
            !(arg.is_required_set() && arg.is_global_set()),
            "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
                    cmd.get_name(),
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_positional(),
                "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
                cmd.get_name(),
                arg.get_id()
            );

            assert!(
                arg.is_trailing_var_arg_set() || arg.is_last_set(),
                "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }
    }

    for group in cmd.get_groups() {
        let derive_hint = if cfg!(feature = "derive") {
            " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
        } else {
            ""
        };

        // Name conflicts
        assert!(
            cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
            "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        // Groups should not have naming conflicts with Args
        assert!(
            !cmd.get_arguments().any(|x| x.get_id() == group.get_id()),
            "Command {}: Argument group name '{}' must not conflict with argument name{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        for arg in &group.args {
            // Args listed inside groups should exist
            assert!(
                cmd.get_arguments().any(|x| x.get_id() == arg),
                "Command {}: Argument group '{}' contains non-existent argument '{}'",
                cmd.get_name(),
                group.get_id(),
                arg
            );
        }
    }

    // Conflicts between flags and subcommands

    long_flags.sort_unstable();
    short_flags.sort_unstable();

    detect_duplicate_flags(&long_flags, "long");
    detect_duplicate_flags(&short_flags, "short");

    let mut subs = FlatSet::new();
    for sc in cmd.get_subcommands() {
        assert!(
            subs.insert(sc.get_name()),
            "Command {}: command name `{}` is duplicated",
            cmd.get_name(),
            sc.get_name()
        );
        for alias in sc.get_all_aliases() {
            assert!(
                subs.insert(alias),
                "Command {}: command `{}` alias `{}` is duplicated",
                cmd.get_name(),
                sc.get_name(),
                alias
            );
        }
    }

    _verify_positionals(cmd);

    #[cfg(feature = "help")]
    if let Some(help_template) = cmd.get_help_template() {
        assert!(
            !help_template.to_string().contains("{flags}"),
            "Command {}: {}",
                    cmd.get_name(),
            "`{flags}` template variable was removed in clap3, they are now included in `{options}`",
        );
        assert!(
            !help_template.to_string().contains("{unified}"),
            "Command {}: {}",
            cmd.get_name(),
            "`{unified}` template variable was removed in clap3, use `{options}` instead"
        );
    }

    cmd._panic_on_missing_help(cmd.is_help_expected_set());
    assert_app_flags(cmd);
}

Iterate through the set of subcommands, getting a mutable reference to each.

Examples found in repository?
src/builder/command.rs (line 3443)
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
    pub fn find_subcommand_mut(
        &mut self,
        name: impl AsRef<std::ffi::OsStr>,
    ) -> Option<&mut Command> {
        let name = name.as_ref();
        self.get_subcommands_mut().find(|s| s.aliases_to(name))
    }

    /// Iterate through the set of groups.
    #[inline]
    pub fn get_groups(&self) -> impl Iterator<Item = &ArgGroup> {
        self.groups.iter()
    }

    /// Iterate through the set of arguments.
    #[inline]
    pub fn get_arguments(&self) -> impl Iterator<Item = &Arg> {
        self.args.args()
    }

    /// Iterate through the *positionals* arguments.
    #[inline]
    pub fn get_positionals(&self) -> impl Iterator<Item = &Arg> {
        self.get_arguments().filter(|a| a.is_positional())
    }

    /// Iterate through the *options*.
    pub fn get_opts(&self) -> impl Iterator<Item = &Arg> {
        self.get_arguments()
            .filter(|a| a.is_takes_value_set() && !a.is_positional())
    }

    /// Get a list of all arguments the given argument conflicts with.
    ///
    /// If the provided argument is declared as global, the conflicts will be determined
    /// based on the propagation rules of global arguments.
    ///
    /// ### Panics
    ///
    /// If the given arg contains a conflict with an argument that is unknown to
    /// this `Command`.
    pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
    {
        if arg.is_global_set() {
            self.get_global_arg_conflicts_with(arg)
        } else {
            let mut result = Vec::new();
            for id in arg.blacklist.iter() {
                if let Some(arg) = self.find(id) {
                    result.push(arg);
                } else if let Some(group) = self.find_group(id) {
                    result.extend(
                        self.unroll_args_in_group(&group.id)
                            .iter()
                            .map(|id| self.find(id).expect(INTERNAL_ERROR_MSG)),
                    );
                } else {
                    panic!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd");
                }
            }
            result
        }
    }

    // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with.
    //
    // This behavior follows the propagation rules of global arguments.
    // It is useful for finding conflicts for arguments declared as global.
    //
    // ### Panics
    //
    // If the given arg contains a conflict with an argument that is unknown to
    // this `Command`.
    fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
    {
        arg.blacklist
            .iter()
            .map(|id| {
                self.args
                    .args()
                    .chain(
                        self.get_subcommands_containing(arg)
                            .iter()
                            .flat_map(|x| x.args.args()),
                    )
                    .find(|arg| arg.get_id() == id)
                    .expect(
                        "Command::get_arg_conflicts_with: \
                    The passed arg conflicts with an arg unknown to the cmd",
                    )
            })
            .collect()
    }

    // Get a list of subcommands which contain the provided Argument
    //
    // This command will only include subcommands in its list for which the subcommands
    // parent also contains the Argument.
    //
    // This search follows the propagation rules of global arguments.
    // It is useful to finding subcommands, that have inherited a global argument.
    //
    // **NOTE:** In this case only Sucommand_1 will be included
    //   Subcommand_1 (contains Arg)
    //     Subcommand_1.1 (doesn't contain Arg)
    //       Subcommand_1.1.1 (contains Arg)
    //
    fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&Self> {
        let mut vec = std::vec::Vec::new();
        for idx in 0..self.subcommands.len() {
            if self.subcommands[idx]
                .args
                .args()
                .any(|ar| ar.get_id() == arg.get_id())
            {
                vec.push(&self.subcommands[idx]);
                vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg));
            }
        }
        vec
    }

    /// Report whether [`Command::no_binary_name`] is set
    pub fn is_no_binary_name_set(&self) -> bool {
        self.is_set(AppSettings::NoBinaryName)
    }

    /// Report whether [`Command::ignore_errors`] is set
    pub(crate) fn is_ignore_errors_set(&self) -> bool {
        self.is_set(AppSettings::IgnoreErrors)
    }

    /// Report whether [`Command::dont_delimit_trailing_values`] is set
    pub fn is_dont_delimit_trailing_values_set(&self) -> bool {
        self.is_set(AppSettings::DontDelimitTrailingValues)
    }

    /// Report whether [`Command::disable_version_flag`] is set
    pub fn is_disable_version_flag_set(&self) -> bool {
        self.is_set(AppSettings::DisableVersionFlag)
            || (self.version.is_none() && self.long_version.is_none())
    }

    /// Report whether [`Command::propagate_version`] is set
    pub fn is_propagate_version_set(&self) -> bool {
        self.is_set(AppSettings::PropagateVersion)
    }

    /// Report whether [`Command::next_line_help`] is set
    pub fn is_next_line_help_set(&self) -> bool {
        self.is_set(AppSettings::NextLineHelp)
    }

    /// Report whether [`Command::disable_help_flag`] is set
    pub fn is_disable_help_flag_set(&self) -> bool {
        self.is_set(AppSettings::DisableHelpFlag)
    }

    /// Report whether [`Command::disable_help_subcommand`] is set
    pub fn is_disable_help_subcommand_set(&self) -> bool {
        self.is_set(AppSettings::DisableHelpSubcommand)
    }

    /// Report whether [`Command::disable_colored_help`] is set
    pub fn is_disable_colored_help_set(&self) -> bool {
        self.is_set(AppSettings::DisableColoredHelp)
    }

    /// Report whether [`Command::help_expected`] is set
    #[cfg(debug_assertions)]
    pub(crate) fn is_help_expected_set(&self) -> bool {
        self.is_set(AppSettings::HelpExpected)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "This is now the default")
    )]
    pub fn is_dont_collapse_args_in_usage_set(&self) -> bool {
        true
    }

    /// Report whether [`Command::infer_long_args`] is set
    pub(crate) fn is_infer_long_args_set(&self) -> bool {
        self.is_set(AppSettings::InferLongArgs)
    }

    /// Report whether [`Command::infer_subcommands`] is set
    pub(crate) fn is_infer_subcommands_set(&self) -> bool {
        self.is_set(AppSettings::InferSubcommands)
    }

    /// Report whether [`Command::arg_required_else_help`] is set
    pub fn is_arg_required_else_help_set(&self) -> bool {
        self.is_set(AppSettings::ArgRequiredElseHelp)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(
            since = "4.0.0",
            note = "Replaced with `Arg::is_allow_hyphen_values_set`"
        )
    )]
    pub(crate) fn is_allow_hyphen_values_set(&self) -> bool {
        self.is_set(AppSettings::AllowHyphenValues)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(
            since = "4.0.0",
            note = "Replaced with `Arg::is_allow_negative_numbers_set`"
        )
    )]
    pub fn is_allow_negative_numbers_set(&self) -> bool {
        self.is_set(AppSettings::AllowNegativeNumbers)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "Replaced with `Arg::is_trailing_var_arg_set`")
    )]
    pub fn is_trailing_var_arg_set(&self) -> bool {
        self.is_set(AppSettings::TrailingVarArg)
    }

    /// Report whether [`Command::allow_missing_positional`] is set
    pub fn is_allow_missing_positional_set(&self) -> bool {
        self.is_set(AppSettings::AllowMissingPositional)
    }

    /// Report whether [`Command::hide`] is set
    pub fn is_hide_set(&self) -> bool {
        self.is_set(AppSettings::Hidden)
    }

    /// Report whether [`Command::subcommand_required`] is set
    pub fn is_subcommand_required_set(&self) -> bool {
        self.is_set(AppSettings::SubcommandRequired)
    }

    /// Report whether [`Command::allow_external_subcommands`] is set
    pub fn is_allow_external_subcommands_set(&self) -> bool {
        self.is_set(AppSettings::AllowExternalSubcommands)
    }

    /// Configured parser for values passed to an external subcommand
    ///
    /// # Example
    ///
    /// ```rust
    /// let cmd = clap::Command::new("raw")
    ///     .external_subcommand_value_parser(clap::value_parser!(String));
    /// let value_parser = cmd.get_external_subcommand_value_parser();
    /// println!("{:?}", value_parser);
    /// ```
    pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> {
        if !self.is_allow_external_subcommands_set() {
            None
        } else {
            static DEFAULT: super::ValueParser = super::ValueParser::os_string();
            Some(self.external_value_parser.as_ref().unwrap_or(&DEFAULT))
        }
    }

    /// Report whether [`Command::args_conflicts_with_subcommands`] is set
    pub fn is_args_conflicts_with_subcommands_set(&self) -> bool {
        self.is_set(AppSettings::ArgsNegateSubcommands)
    }

    #[doc(hidden)]
    pub fn is_args_override_self(&self) -> bool {
        self.is_set(AppSettings::AllArgsOverrideSelf)
    }

    /// Report whether [`Command::subcommand_precedence_over_arg`] is set
    pub fn is_subcommand_precedence_over_arg_set(&self) -> bool {
        self.is_set(AppSettings::SubcommandPrecedenceOverArg)
    }

    /// Report whether [`Command::subcommand_negates_reqs`] is set
    pub fn is_subcommand_negates_reqs_set(&self) -> bool {
        self.is_set(AppSettings::SubcommandsNegateReqs)
    }

    /// Report whether [`Command::multicall`] is set
    pub fn is_multicall_set(&self) -> bool {
        self.is_set(AppSettings::Multicall)
    }
}

// Internally used only
impl Command {
    pub(crate) fn get_override_usage(&self) -> Option<&StyledStr> {
        self.usage_str.as_ref()
    }

    pub(crate) fn get_override_help(&self) -> Option<&StyledStr> {
        self.help_str.as_ref()
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_help_template(&self) -> Option<&StyledStr> {
        self.template.as_ref()
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_term_width(&self) -> Option<usize> {
        self.term_w
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_max_term_width(&self) -> Option<usize> {
        self.max_w
    }

    pub(crate) fn get_replacement(&self, key: &str) -> Option<&[Str]> {
        self.replacers.get(key).map(|v| v.as_slice())
    }

    pub(crate) fn get_keymap(&self) -> &MKeyMap {
        &self.args
    }

    fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec<Id>) {
        global_arg_vec.extend(
            self.args
                .args()
                .filter(|a| a.is_global_set())
                .map(|ga| ga.id.clone()),
        );
        if let Some((id, matches)) = matches.subcommand() {
            if let Some(used_sub) = self.find_subcommand(id) {
                used_sub.get_used_global_args(matches, global_arg_vec);
            }
        }
    }

    fn _do_parse(
        &mut self,
        raw_args: &mut clap_lex::RawArgs,
        args_cursor: clap_lex::ArgCursor,
    ) -> ClapResult<ArgMatches> {
        debug!("Command::_do_parse");

        // If there are global arguments, or settings we need to propagate them down to subcommands
        // before parsing in case we run into a subcommand
        self._build_self(false);

        let mut matcher = ArgMatcher::new(self);

        // do the real parsing
        let mut parser = Parser::new(self);
        if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) {
            if self.is_set(AppSettings::IgnoreErrors) {
                debug!("Command::_do_parse: ignoring error: {}", error);
            } else {
                return Err(error);
            }
        }

        let mut global_arg_vec = Default::default();
        self.get_used_global_args(&matcher, &mut global_arg_vec);

        matcher.propagate_globals(&global_arg_vec);

        Ok(matcher.into_inner())
    }

    /// Prepare for introspecting on all included [`Command`]s
    ///
    /// Call this on the top-level [`Command`] when done building and before reading state for
    /// cases like completions, custom help output, etc.
    pub fn build(&mut self) {
        self._build_recursive(true);
        self._build_bin_names_internal();
    }

    pub(crate) fn _build_recursive(&mut self, expand_help_tree: bool) {
        self._build_self(expand_help_tree);
        for subcmd in self.get_subcommands_mut() {
            subcmd._build_recursive(expand_help_tree);
        }
    }
More examples
Hide additional examples
src/parser/parser.rs (line 1544)
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
    fn did_you_mean_error(
        &mut self,
        arg: &str,
        matcher: &mut ArgMatcher,
        remaining_args: &[&OsStr],
        trailing_values: bool,
    ) -> ClapError {
        debug!("Parser::did_you_mean_error: arg={}", arg);
        // Didn't match a flag or option
        let longs = self
            .cmd
            .get_keymap()
            .keys()
            .filter_map(|x| match x {
                KeyType::Long(l) => Some(l.to_string_lossy().into_owned()),
                _ => None,
            })
            .collect::<Vec<_>>();
        debug!("Parser::did_you_mean_error: longs={:?}", longs);

        let did_you_mean = suggestions::did_you_mean_flag(
            arg,
            remaining_args,
            longs.iter().map(|x| &x[..]),
            self.cmd.get_subcommands_mut(),
        );

        // Add the arg to the matches to build a proper usage string
        if let Some((name, _)) = did_you_mean.as_ref() {
            if let Some(arg) = self.cmd.get_keymap().get(&name.as_ref()) {
                self.start_custom_arg(matcher, arg, ValueSource::CommandLine);
            }
        }

        let required = self.cmd.required_graph();
        let used: Vec<Id> = matcher
            .arg_ids()
            .filter(|arg_id| {
                matcher.check_explicit(arg_id, &crate::builder::ArgPredicate::IsPresent)
            })
            .filter(|n| self.cmd.find(n).map_or(true, |a| !a.is_hide_set()))
            .cloned()
            .collect();

        // `did_you_mean` is a lot more likely and should cause us to skip the `--` suggestion
        //
        // In theory, this is only called for `--long`s, so we don't need to check
        let suggested_trailing_arg =
            did_you_mean.is_none() && !trailing_values && self.cmd.has_positionals();
        ClapError::unknown_argument(
            self.cmd,
            format!("--{}", arg),
            did_you_mean,
            suggested_trailing_arg,
            Usage::new(self.cmd)
                .required(&required)
                .create_usage_with_title(&used),
        )
    }

Returns true if this Command has subcommands.

Examples found in repository?
src/error/format.rs (line 394)
391
392
393
394
395
396
397
398
399
pub(crate) fn get_help_flag(cmd: &Command) -> Option<&'static str> {
    if !cmd.is_disable_help_flag_set() {
        Some("--help")
    } else if cmd.has_subcommands() && !cmd.is_disable_help_subcommand_set() {
        Some("help")
    } else {
        None
    }
}
More examples
Hide additional examples
src/parser/parser.rs (line 524)
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
    fn match_arg_error(
        &self,
        arg_os: &clap_lex::ParsedArg<'_>,
        valid_arg_found: bool,
        trailing_values: bool,
    ) -> ClapError {
        // If argument follows a `--`
        if trailing_values {
            // If the arg matches a subcommand name, or any of its aliases (if defined)
            if self
                .possible_subcommand(arg_os.to_value(), valid_arg_found)
                .is_some()
            {
                return ClapError::unnecessary_double_dash(
                    self.cmd,
                    arg_os.display().to_string(),
                    Usage::new(self.cmd).create_usage_with_title(&[]),
                );
            }
        }

        let candidates = suggestions::did_you_mean(
            &arg_os.display().to_string(),
            self.cmd.all_subcommand_names(),
        );
        // If the argument looks like a subcommand.
        if !candidates.is_empty() {
            return ClapError::invalid_subcommand(
                self.cmd,
                arg_os.display().to_string(),
                candidates,
                self.cmd
                    .get_bin_name()
                    .unwrap_or_else(|| self.cmd.get_name())
                    .to_owned(),
                Usage::new(self.cmd).create_usage_with_title(&[]),
            );
        }

        // If the argument must be a subcommand.
        if self.cmd.has_subcommands()
            && (!self.cmd.has_positionals() || self.cmd.is_infer_subcommands_set())
        {
            return ClapError::unrecognized_subcommand(
                self.cmd,
                arg_os.display().to_string(),
                Usage::new(self.cmd).create_usage_with_title(&[]),
            );
        }

        let suggested_trailing_arg = !trailing_values
            && self.cmd.has_positionals()
            && (arg_os.is_long() || arg_os.is_short());
        ClapError::unknown_argument(
            self.cmd,
            arg_os.display().to_string(),
            None,
            suggested_trailing_arg,
            Usage::new(self.cmd).create_usage_with_title(&[]),
        )
    }
src/builder/command.rs (line 3852)
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
    pub(crate) fn _build_self(&mut self, expand_help_tree: bool) {
        debug!("Command::_build: name={:?}", self.get_name());
        if !self.settings.is_set(AppSettings::Built) {
            // Make sure all the globally set flags apply to us as well
            self.settings = self.settings | self.g_settings;

            if self.is_multicall_set() {
                self.settings.insert(AppSettings::SubcommandRequired.into());
                self.settings.insert(AppSettings::DisableHelpFlag.into());
                self.settings.insert(AppSettings::DisableVersionFlag.into());
            }
            if !cfg!(feature = "help") && self.get_override_help().is_none() {
                self.settings.insert(AppSettings::DisableHelpFlag.into());
                self.settings
                    .insert(AppSettings::DisableHelpSubcommand.into());
            }
            if self.is_set(AppSettings::ArgsNegateSubcommands) {
                self.settings
                    .insert(AppSettings::SubcommandsNegateReqs.into());
            }
            if self.external_value_parser.is_some() {
                self.settings
                    .insert(AppSettings::AllowExternalSubcommands.into());
            }
            if !self.has_subcommands() {
                self.settings
                    .insert(AppSettings::DisableHelpSubcommand.into());
            }

            self._propagate();
            self._check_help_and_version(expand_help_tree);
            self._propagate_global_args();

            let mut pos_counter = 1;
            let hide_pv = self.is_set(AppSettings::HidePossibleValues);
            for a in self.args.args_mut() {
                // Fill in the groups
                for g in &a.groups {
                    if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) {
                        ag.args.push(a.get_id().clone());
                    } else {
                        let mut ag = ArgGroup::new(g);
                        ag.args.push(a.get_id().clone());
                        self.groups.push(ag);
                    }
                }

                // Figure out implied settings
                a._build();
                if hide_pv && a.is_takes_value_set() {
                    a.settings.set(ArgSettings::HidePossibleValues);
                }
                if a.is_positional() && a.index.is_none() {
                    a.index = Some(pos_counter);
                    pos_counter += 1;
                }
            }

            self.args._build();

            #[allow(deprecated)]
            {
                let highest_idx = self
                    .get_keymap()
                    .keys()
                    .filter_map(|x| {
                        if let crate::mkeymap::KeyType::Position(n) = x {
                            Some(*n)
                        } else {
                            None
                        }
                    })
                    .max()
                    .unwrap_or(0);
                let is_trailing_var_arg_set = self.is_trailing_var_arg_set();
                let is_allow_hyphen_values_set = self.is_allow_hyphen_values_set();
                let is_allow_negative_numbers_set = self.is_allow_negative_numbers_set();
                for arg in self.args.args_mut() {
                    if is_allow_hyphen_values_set && arg.is_takes_value_set() {
                        arg.settings.insert(ArgSettings::AllowHyphenValues.into());
                    }
                    if is_allow_negative_numbers_set && arg.is_takes_value_set() {
                        arg.settings
                            .insert(ArgSettings::AllowNegativeNumbers.into());
                    }
                    if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) {
                        arg.settings.insert(ArgSettings::TrailingVarArg.into());
                    }
                }
            }

            #[cfg(debug_assertions)]
            assert_app(self);
            self.settings.set(AppSettings::Built);
        } else {
            debug!("Command::_build: already built");
        }
    }
src/builder/debug_asserts.rs (line 677)
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
fn _verify_positionals(cmd: &Command) -> bool {
    debug!("Command::_verify_positionals");
    // Because you must wait until all arguments have been supplied, this is the first chance
    // to make assertions on positional argument indexes
    //
    // First we verify that the index highest supplied index, is equal to the number of
    // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3
    // but no 2)

    let highest_idx = cmd
        .get_keymap()
        .keys()
        .filter_map(|x| {
            if let KeyType::Position(n) = x {
                Some(*n)
            } else {
                None
            }
        })
        .max()
        .unwrap_or(0);

    let num_p = cmd.get_keymap().keys().filter(|x| x.is_position()).count();

    assert!(
        highest_idx == num_p,
        "Found positional argument whose index is {} but there \
             are only {} positional arguments defined",
        highest_idx,
        num_p
    );

    for arg in cmd.get_arguments() {
        if arg.index.unwrap_or(0) == highest_idx {
            assert!(
                !arg.is_trailing_var_arg_set() || !arg.is_last_set(),
                "{}:{}: `Arg::trailing_var_arg` and `Arg::last` cannot be used together",
                cmd.get_name(),
                arg.get_id()
            );

            if arg.is_trailing_var_arg_set() {
                assert!(
                    arg.is_multiple(),
                    "{}:{}: `Arg::trailing_var_arg` must accept multiple values",
                    cmd.get_name(),
                    arg.get_id()
                );
            }
        } else {
            assert!(
                !arg.is_trailing_var_arg_set(),
                "{}:{}: `Arg::trailing_var_arg` can only apply to last positional",
                cmd.get_name(),
                arg.get_id()
            );
        }
    }

    // Next we verify that only the highest index has takes multiple arguments (if any)
    let only_highest = |a: &Arg| a.is_multiple() && (a.get_index().unwrap_or(0) != highest_idx);
    if cmd.get_positionals().any(only_highest) {
        // First we make sure if there is a positional that allows multiple values
        // the one before it (second to last) has one of these:
        //  * a value terminator
        //  * ArgSettings::Last
        //  * The last arg is Required

        // We can't pass the closure (it.next()) to the macro directly because each call to
        // find() (iterator, not macro) gets called repeatedly.
        let last = &cmd.get_keymap()[&KeyType::Position(highest_idx)];
        let second_to_last = &cmd.get_keymap()[&KeyType::Position(highest_idx - 1)];

        // Either the final positional is required
        // Or the second to last has a terminator or .last(true) set
        let ok = last.is_required_set()
            || (second_to_last.terminator.is_some() || second_to_last.is_last_set())
            || last.is_last_set();
        assert!(
            ok,
            "When using a positional argument with `.num_args(1..)` that is *not the \
                 last* positional argument, the last positional argument (i.e. the one \
                 with the highest index) *must* have .required(true) or .last(true) set."
        );

        // We make sure if the second to last is Multiple the last is ArgSettings::Last
        let ok = second_to_last.is_multiple() || last.is_last_set();
        assert!(
            ok,
            "Only the last positional argument, or second to last positional \
                 argument may be set to `.num_args(1..)`"
        );

        // Next we check how many have both Multiple and not a specific number of values set
        let count = cmd
            .get_positionals()
            .filter(|p| {
                p.is_multiple_values_set()
                    && !p.get_num_args().expect(INTERNAL_ERROR_MSG).is_fixed()
            })
            .count();
        let ok = count <= 1
            || (last.is_last_set()
                && last.is_multiple()
                && second_to_last.is_multiple()
                && count == 2);
        assert!(
            ok,
            "Only one positional argument with `.num_args(1..)` set is allowed per \
                 command, unless the second one also has .last(true) set"
        );
    }

    let mut found = false;

    if cmd.is_allow_missing_positional_set() {
        // Check that if a required positional argument is found, all positions with a lower
        // index are also required.
        let mut foundx2 = false;

        for p in cmd.get_positionals() {
            if foundx2 && !p.is_required_set() {
                assert!(
                    p.is_required_set(),
                    "Found non-required positional argument with a lower \
                         index than a required positional argument by two or more: {:?} \
                         index {:?}",
                    p.get_id(),
                    p.get_index()
                );
            } else if p.is_required_set() && !p.is_last_set() {
                // Args that .last(true) don't count since they can be required and have
                // positionals with a lower index that aren't required
                // Imagine: prog <req1> [opt1] -- <req2>
                // Both of these are valid invocations:
                //      $ prog r1 -- r2
                //      $ prog r1 o1 -- r2
                if found {
                    foundx2 = true;
                    continue;
                }
                found = true;
                continue;
            } else {
                found = false;
            }
        }
    } else {
        // Check that if a required positional argument is found, all positions with a lower
        // index are also required
        for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) {
            if found {
                assert!(
                    p.is_required_set(),
                    "Found non-required positional argument with a lower \
                         index than a required positional argument: {:?} index {:?}",
                    p.get_id(),
                    p.get_index()
                );
            } else if p.is_required_set() && !p.is_last_set() {
                // Args that .last(true) don't count since they can be required and have
                // positionals with a lower index that aren't required
                // Imagine: prog <req1> [opt1] -- <req2>
                // Both of these are valid invocations:
                //      $ prog r1 -- r2
                //      $ prog r1 o1 -- r2
                found = true;
                continue;
            }
        }
    }
    assert!(
        cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2,
        "Only one positional argument may have last(true) set. Found two."
    );
    if cmd
        .get_positionals()
        .any(|p| p.is_last_set() && p.is_required_set())
        && cmd.has_subcommands()
        && !cmd.is_subcommand_negates_reqs_set()
    {
        panic!(
            "Having a required positional argument with .last(true) set *and* child \
                 subcommands without setting SubcommandsNegateReqs isn't compatible."
        );
    }

    true
}

Returns the help heading for listing subcommands.

Examples found in repository?
src/output/help_template.rs (line 367)
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
    pub(crate) fn write_all_args(&mut self) {
        debug!("HelpTemplate::write_all_args");
        let pos = self
            .cmd
            .get_positionals()
            .filter(|a| a.get_help_heading().is_none())
            .filter(|arg| should_show_arg(self.use_long, arg))
            .collect::<Vec<_>>();
        let non_pos = self
            .cmd
            .get_non_positionals()
            .filter(|a| a.get_help_heading().is_none())
            .filter(|arg| should_show_arg(self.use_long, arg))
            .collect::<Vec<_>>();
        let subcmds = self.cmd.has_visible_subcommands();

        let custom_headings = self
            .cmd
            .get_arguments()
            .filter_map(|arg| arg.get_help_heading())
            .collect::<FlatSet<_>>();

        let mut first = true;

        if subcmds {
            if !first {
                self.none("\n\n");
            }
            first = false;
            let default_help_heading = Str::from("Commands");
            self.header(
                self.cmd
                    .get_subcommand_help_heading()
                    .unwrap_or(&default_help_heading),
            );
            self.header(":\n");

            self.write_subcommands(self.cmd);
        }

        if !pos.is_empty() {
            if !first {
                self.none("\n\n");
            }
            first = false;
            // Write positional args if any
            self.header("Arguments:\n");
            self.write_args(&pos, "Arguments", positional_sort_key);
        }

        if !non_pos.is_empty() {
            if !first {
                self.none("\n\n");
            }
            first = false;
            self.header("Options:\n");
            self.write_args(&non_pos, "Options", option_sort_key);
        }
        if !custom_headings.is_empty() {
            for heading in custom_headings {
                let args = self
                    .cmd
                    .get_arguments()
                    .filter(|a| {
                        if let Some(help_heading) = a.get_help_heading() {
                            return help_heading == heading;
                        }
                        false
                    })
                    .filter(|arg| should_show_arg(self.use_long, arg))
                    .collect::<Vec<_>>();

                if !args.is_empty() {
                    if !first {
                        self.none("\n\n");
                    }
                    first = false;
                    self.header(format!("{}:\n", heading));
                    self.write_args(&args, heading, option_sort_key);
                }
            }
        }
    }

Returns the subcommand value name.

Examples found in repository?
src/output/usage.rs (line 95)
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
    fn create_help_usage(&self, incl_reqs: bool) -> StyledStr {
        debug!("Usage::create_help_usage; incl_reqs={:?}", incl_reqs);
        let mut styled = StyledStr::new();
        let name = self
            .cmd
            .get_usage_name()
            .or_else(|| self.cmd.get_bin_name())
            .unwrap_or_else(|| self.cmd.get_name());
        styled.literal(name);

        if self.needs_options_tag() {
            styled.placeholder(" [OPTIONS]");
        }

        self.write_args(&[], !incl_reqs, &mut styled);

        // incl_reqs is only false when this function is called recursively
        if self.cmd.has_visible_subcommands() && incl_reqs
            || self.cmd.is_allow_external_subcommands_set()
        {
            let placeholder = self
                .cmd
                .get_subcommand_value_name()
                .unwrap_or(DEFAULT_SUB_VALUE_NAME);
            if self.cmd.is_subcommand_negates_reqs_set()
                || self.cmd.is_args_conflicts_with_subcommands_set()
            {
                styled.none("\n");
                styled.none("       ");
                if self.cmd.is_args_conflicts_with_subcommands_set() {
                    // Short-circuit full usage creation since no args will be relevant
                    styled.literal(name);
                } else {
                    styled.extend(self.create_help_usage(false).into_iter());
                }
                styled.placeholder(" <");
                styled.placeholder(placeholder);
                styled.placeholder(">");
            } else if self.cmd.is_subcommand_required_set() {
                styled.placeholder(" <");
                styled.placeholder(placeholder);
                styled.placeholder(">");
            } else {
                styled.placeholder(" [");
                styled.placeholder(placeholder);
                styled.placeholder("]");
            }
        }
        styled.trim();
        debug!("Usage::create_help_usage: usage={}", styled);
        styled
    }

    // Creates a context aware usage string, or "smart usage" from currently used
    // args, and requirements
    fn create_smart_usage(&self, used: &[Id]) -> StyledStr {
        debug!("Usage::create_smart_usage");
        let mut styled = StyledStr::new();

        styled.literal(
            self.cmd
                .get_usage_name()
                .or_else(|| self.cmd.get_bin_name())
                .unwrap_or_else(|| self.cmd.get_name()),
        );

        self.write_args(used, false, &mut styled);

        if self.cmd.is_subcommand_required_set() {
            styled.placeholder(" <");
            styled.placeholder(
                self.cmd
                    .get_subcommand_value_name()
                    .unwrap_or(DEFAULT_SUB_VALUE_NAME),
            );
            styled.placeholder(">");
        }
        styled
    }

Returns the help heading for listing subcommands.

Examples found in repository?
src/output/help_template.rs (line 299)
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
    fn write_before_help(&mut self) {
        debug!("HelpTemplate::write_before_help");
        let before_help = if self.use_long {
            self.cmd
                .get_before_long_help()
                .or_else(|| self.cmd.get_before_help())
        } else {
            self.cmd.get_before_help()
        };
        if let Some(output) = before_help {
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
            self.none("\n\n");
        }
    }

Returns the help heading for listing subcommands.

Examples found in repository?
src/output/help_template.rs (line 298)
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
    fn write_before_help(&mut self) {
        debug!("HelpTemplate::write_before_help");
        let before_help = if self.use_long {
            self.cmd
                .get_before_long_help()
                .or_else(|| self.cmd.get_before_help())
        } else {
            self.cmd.get_before_help()
        };
        if let Some(output) = before_help {
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
            self.none("\n\n");
        }
    }
More examples
Hide additional examples
src/builder/command.rs (line 4607)
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
    fn long_help_exists_(&self) -> bool {
        debug!("Command::long_help_exists");
        // In this case, both must be checked. This allows the retention of
        // original formatting, but also ensures that the actual -h or --help
        // specified by the user is sent through. If hide_short_help is not included,
        // then items specified with hidden_short_help will also be hidden.
        let should_long = |v: &Arg| {
            v.get_long_help().is_some()
                || v.is_hide_long_help_set()
                || v.is_hide_short_help_set()
                || v.get_possible_values()
                    .iter()
                    .any(PossibleValue::should_show_help)
        };

        // Subcommands aren't checked because we prefer short help for them, deferring to
        // `cmd subcmd --help` for more.
        self.get_long_about().is_some()
            || self.get_before_long_help().is_some()
            || self.get_after_long_help().is_some()
            || self.get_arguments().any(should_long)
    }

Returns the help heading for listing subcommands.

Examples found in repository?
src/output/help_template.rs (line 317)
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
    fn write_after_help(&mut self) {
        debug!("HelpTemplate::write_after_help");
        let after_help = if self.use_long {
            self.cmd
                .get_after_long_help()
                .or_else(|| self.cmd.get_after_help())
        } else {
            self.cmd.get_after_help()
        };
        if let Some(output) = after_help {
            self.none("\n\n");
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
        }
    }

Returns the help heading for listing subcommands.

Examples found in repository?
src/output/help_template.rs (line 316)
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
    fn write_after_help(&mut self) {
        debug!("HelpTemplate::write_after_help");
        let after_help = if self.use_long {
            self.cmd
                .get_after_long_help()
                .or_else(|| self.cmd.get_after_help())
        } else {
            self.cmd.get_after_help()
        };
        if let Some(output) = after_help {
            self.none("\n\n");
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
        }
    }
More examples
Hide additional examples
src/builder/command.rs (line 4608)
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
    fn long_help_exists_(&self) -> bool {
        debug!("Command::long_help_exists");
        // In this case, both must be checked. This allows the retention of
        // original formatting, but also ensures that the actual -h or --help
        // specified by the user is sent through. If hide_short_help is not included,
        // then items specified with hidden_short_help will also be hidden.
        let should_long = |v: &Arg| {
            v.get_long_help().is_some()
                || v.is_hide_long_help_set()
                || v.is_hide_short_help_set()
                || v.get_possible_values()
                    .iter()
                    .any(PossibleValue::should_show_help)
        };

        // Subcommands aren't checked because we prefer short help for them, deferring to
        // `cmd subcmd --help` for more.
        self.get_long_about().is_some()
            || self.get_before_long_help().is_some()
            || self.get_after_long_help().is_some()
            || self.get_arguments().any(should_long)
    }

Find subcommand such that its name or one of aliases equals name.

This does not recurse through subcommands of subcommands.

Examples found in repository?
src/builder/command.rs (line 3775)
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
    fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec<Id>) {
        global_arg_vec.extend(
            self.args
                .args()
                .filter(|a| a.is_global_set())
                .map(|ga| ga.id.clone()),
        );
        if let Some((id, matches)) = matches.subcommand() {
            if let Some(used_sub) = self.find_subcommand(id) {
                used_sub.get_used_global_args(matches, global_arg_vec);
            }
        }
    }
More examples
Hide additional examples
src/parser/parser.rs (line 470)
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
    pub(crate) fn get_matches_with(
        &mut self,
        matcher: &mut ArgMatcher,
        raw_args: &mut clap_lex::RawArgs,
        mut args_cursor: clap_lex::ArgCursor,
    ) -> ClapResult<()> {
        debug!("Parser::get_matches_with");
        // Verify all positional assertions pass

        let mut subcmd_name: Option<String> = None;
        let mut keep_state = false;
        let mut parse_state = ParseState::ValuesDone;
        let mut pos_counter = 1;

        // Already met any valid arg(then we shouldn't expect subcommands after it).
        let mut valid_arg_found = false;
        // If the user already passed '--'. Meaning only positional args follow.
        let mut trailing_values = false;

        // Count of positional args
        let positional_count = self
            .cmd
            .get_keymap()
            .keys()
            .filter(|x| x.is_position())
            .count();
        // If any arg sets .last(true)
        let contains_last = self.cmd.get_arguments().any(|x| x.is_last_set());

        while let Some(arg_os) = raw_args.next(&mut args_cursor) {
            // Recover the replaced items if any.
            if let Some(replaced_items) = arg_os
                .to_value()
                .ok()
                .and_then(|a| self.cmd.get_replacement(a))
            {
                debug!(
                    "Parser::get_matches_with: found replacer: {:?}, target: {:?}",
                    arg_os, replaced_items
                );
                raw_args.insert(&args_cursor, replaced_items);
                continue;
            }

            debug!(
                "Parser::get_matches_with: Begin parsing '{:?}' ({:?})",
                arg_os.to_value_os(),
                arg_os.to_value_os().as_raw_bytes()
            );

            // Has the user already passed '--'? Meaning only positional args follow
            if !trailing_values {
                if self.cmd.is_subcommand_precedence_over_arg_set()
                    || !matches!(parse_state, ParseState::Opt(_) | ParseState::Pos(_))
                {
                    // Does the arg match a subcommand name, or any of its aliases (if defined)
                    let sc_name = self.possible_subcommand(arg_os.to_value(), valid_arg_found);
                    debug!("Parser::get_matches_with: sc={:?}", sc_name);
                    if let Some(sc_name) = sc_name {
                        if sc_name == "help" && !self.cmd.is_disable_help_subcommand_set() {
                            ok!(self.parse_help_subcommand(raw_args.remaining(&mut args_cursor)));
                            unreachable!("`parse_help_subcommand` always errors");
                        } else {
                            subcmd_name = Some(sc_name.to_owned());
                        }
                        break;
                    }
                }

                if arg_os.is_escape() {
                    if matches!(&parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if
                        self.cmd[opt].is_allow_hyphen_values_set())
                    {
                        // ParseResult::MaybeHyphenValue, do nothing
                    } else {
                        debug!("Parser::get_matches_with: setting TrailingVals=true");
                        trailing_values = true;
                        matcher.start_trailing();
                        continue;
                    }
                } else if let Some((long_arg, long_value)) = arg_os.to_long() {
                    let parse_result = ok!(self.parse_long_arg(
                        matcher,
                        long_arg,
                        long_value,
                        &parse_state,
                        pos_counter,
                        &mut valid_arg_found,
                    ));
                    debug!(
                        "Parser::get_matches_with: After parse_long_arg {:?}",
                        parse_result
                    );
                    match parse_result {
                        ParseResult::NoArg => {
                            unreachable!("`to_long` always has the flag specified")
                        }
                        ParseResult::ValuesDone => {
                            parse_state = ParseState::ValuesDone;
                            continue;
                        }
                        ParseResult::Opt(id) => {
                            parse_state = ParseState::Opt(id);
                            continue;
                        }
                        ParseResult::FlagSubCommand(name) => {
                            debug!(
                                "Parser::get_matches_with: FlagSubCommand found in long arg {:?}",
                                &name
                            );
                            subcmd_name = Some(name);
                            break;
                        }
                        ParseResult::EqualsNotProvided { arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::no_equals(
                                self.cmd,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::NoMatchingArg { arg } => {
                            let _ = self.resolve_pending(matcher);
                            let remaining_args: Vec<_> =
                                raw_args.remaining(&mut args_cursor).collect();
                            return Err(self.did_you_mean_error(
                                &arg,
                                matcher,
                                &remaining_args,
                                trailing_values,
                            ));
                        }
                        ParseResult::UnneededAttachedValue { rest, used, arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::too_many_values(
                                self.cmd,
                                rest,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&used),
                            ));
                        }
                        ParseResult::MaybeHyphenValue => {
                            // Maybe a hyphen value, do nothing.
                        }
                        ParseResult::AttachedValueNotConsumed => {
                            unreachable!()
                        }
                    }
                } else if let Some(short_arg) = arg_os.to_short() {
                    // Arg looks like a short flag, and not a possible number

                    // Try to parse short args like normal, if allow_hyphen_values or
                    // AllowNegativeNumbers is set, parse_short_arg will *not* throw
                    // an error, and instead return Ok(None)
                    let parse_result = ok!(self.parse_short_arg(
                        matcher,
                        short_arg,
                        &parse_state,
                        pos_counter,
                        &mut valid_arg_found,
                    ));
                    // If it's None, we then check if one of those two AppSettings was set
                    debug!(
                        "Parser::get_matches_with: After parse_short_arg {:?}",
                        parse_result
                    );
                    match parse_result {
                        ParseResult::NoArg => {
                            // Is a single dash `-`, try positional.
                        }
                        ParseResult::ValuesDone => {
                            parse_state = ParseState::ValuesDone;
                            continue;
                        }
                        ParseResult::Opt(id) => {
                            parse_state = ParseState::Opt(id);
                            continue;
                        }
                        ParseResult::FlagSubCommand(name) => {
                            // If there are more short flags to be processed, we should keep the state, and later
                            // revisit the current group of short flags skipping the subcommand.
                            keep_state = self
                                .flag_subcmd_at
                                .map(|at| {
                                    raw_args
                                        .seek(&mut args_cursor, clap_lex::SeekFrom::Current(-1));
                                    // Since we are now saving the current state, the number of flags to skip during state recovery should
                                    // be the current index (`cur_idx`) minus ONE UNIT TO THE LEFT of the starting position.
                                    self.flag_subcmd_skip = self.cur_idx.get() - at + 1;
                                })
                                .is_some();

                            debug!(
                                "Parser::get_matches_with:FlagSubCommandShort: subcmd_name={}, keep_state={}, flag_subcmd_skip={}",
                                name,
                                keep_state,
                                self.flag_subcmd_skip
                            );

                            subcmd_name = Some(name);
                            break;
                        }
                        ParseResult::EqualsNotProvided { arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::no_equals(
                                self.cmd,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::NoMatchingArg { arg } => {
                            let _ = self.resolve_pending(matcher);
                            // We already know it looks like a flag
                            let suggested_trailing_arg =
                                !trailing_values && self.cmd.has_positionals();
                            return Err(ClapError::unknown_argument(
                                self.cmd,
                                arg,
                                None,
                                suggested_trailing_arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::MaybeHyphenValue => {
                            // Maybe a hyphen value, do nothing.
                        }
                        ParseResult::UnneededAttachedValue { .. }
                        | ParseResult::AttachedValueNotConsumed => unreachable!(),
                    }
                }

                if let ParseState::Opt(id) = &parse_state {
                    // Assume this is a value of a previous arg.

                    // get the option so we can check the settings
                    let arg = &self.cmd[id];
                    let parse_result = if let Some(parse_result) =
                        self.check_terminator(arg, arg_os.to_value_os())
                    {
                        parse_result
                    } else {
                        let trailing_values = false;
                        let arg_values = matcher.pending_values_mut(id, None, trailing_values);
                        arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
                        if matcher.needs_more_vals(arg) {
                            ParseResult::Opt(arg.get_id().clone())
                        } else {
                            ParseResult::ValuesDone
                        }
                    };
                    parse_state = match parse_result {
                        ParseResult::Opt(id) => ParseState::Opt(id),
                        ParseResult::ValuesDone => ParseState::ValuesDone,
                        _ => unreachable!(),
                    };
                    // get the next value from the iterator
                    continue;
                }
            }

            // Correct pos_counter.
            pos_counter = {
                let is_second_to_last = pos_counter + 1 == positional_count;

                // The last positional argument, or second to last positional
                // argument may be set to .multiple_values(true) or `.multiple_occurrences(true)`
                let low_index_mults = is_second_to_last
                    && self.cmd.get_positionals().any(|a| {
                        a.is_multiple() && (positional_count != a.get_index().unwrap_or(0))
                    })
                    && self
                        .cmd
                        .get_positionals()
                        .last()
                        .map_or(false, |p_name| !p_name.is_last_set());

                let missing_pos = self.cmd.is_allow_missing_positional_set()
                    && is_second_to_last
                    && !trailing_values;

                debug!(
                    "Parser::get_matches_with: Positional counter...{}",
                    pos_counter
                );
                debug!(
                    "Parser::get_matches_with: Low index multiples...{:?}",
                    low_index_mults
                );

                if low_index_mults || missing_pos {
                    let skip_current = if let Some(n) = raw_args.peek(&args_cursor) {
                        if let Some(arg) = self
                            .cmd
                            .get_positionals()
                            .find(|a| a.get_index() == Some(pos_counter))
                        {
                            // If next value looks like a new_arg or it's a
                            // subcommand, skip positional argument under current
                            // pos_counter(which means current value cannot be a
                            // positional argument with a value next to it), assume
                            // current value matches the next arg.
                            self.is_new_arg(&n, arg)
                                || self
                                    .possible_subcommand(n.to_value(), valid_arg_found)
                                    .is_some()
                        } else {
                            true
                        }
                    } else {
                        true
                    };

                    if skip_current {
                        debug!("Parser::get_matches_with: Bumping the positional counter...");
                        pos_counter + 1
                    } else {
                        pos_counter
                    }
                } else if trailing_values
                    && (self.cmd.is_allow_missing_positional_set() || contains_last)
                {
                    // Came to -- and one positional has .last(true) set, so we go immediately
                    // to the last (highest index) positional
                    debug!("Parser::get_matches_with: .last(true) and --, setting last pos");
                    positional_count
                } else {
                    pos_counter
                }
            };

            if let Some(arg) = self.cmd.get_keymap().get(&pos_counter) {
                if arg.is_last_set() && !trailing_values {
                    let _ = self.resolve_pending(matcher);
                    // Its already considered a positional, we don't need to suggest turning it
                    // into one
                    let suggested_trailing_arg = false;
                    return Err(ClapError::unknown_argument(
                        self.cmd,
                        arg_os.display().to_string(),
                        None,
                        suggested_trailing_arg,
                        Usage::new(self.cmd).create_usage_with_title(&[]),
                    ));
                }

                if arg.is_trailing_var_arg_set() {
                    trailing_values = true;
                }

                if matcher.pending_arg_id() != Some(arg.get_id()) || !arg.is_multiple_values_set() {
                    ok!(self.resolve_pending(matcher));
                }
                if let Some(_parse_result) = self.check_terminator(arg, arg_os.to_value_os()) {
                    debug!(
                        "Parser::get_matches_with: ignoring terminator result {:?}",
                        _parse_result
                    );
                } else {
                    let arg_values = matcher.pending_values_mut(
                        arg.get_id(),
                        Some(Identifier::Index),
                        trailing_values,
                    );
                    arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
                }

                // Only increment the positional counter if it doesn't allow multiples
                if !arg.is_multiple() {
                    pos_counter += 1;
                    parse_state = ParseState::ValuesDone;
                } else {
                    parse_state = ParseState::Pos(arg.get_id().clone());
                }
                valid_arg_found = true;
            } else if let Some(external_parser) =
                self.cmd.get_external_subcommand_value_parser().cloned()
            {
                // Get external subcommand name
                let sc_name = match arg_os.to_value() {
                    Ok(s) => s.to_owned(),
                    Err(_) => {
                        let _ = self.resolve_pending(matcher);
                        return Err(ClapError::invalid_utf8(
                            self.cmd,
                            Usage::new(self.cmd).create_usage_with_title(&[]),
                        ));
                    }
                };

                // Collect the external subcommand args
                let mut sc_m = ArgMatcher::new(self.cmd);
                sc_m.start_occurrence_of_external(self.cmd);

                for raw_val in raw_args.remaining(&mut args_cursor) {
                    let val = ok!(external_parser.parse_ref(self.cmd, None, raw_val));
                    let external_id = Id::from_static_ref(Id::EXTERNAL);
                    sc_m.add_val_to(&external_id, val, raw_val.to_os_string());
                }

                matcher.subcommand(SubCommand {
                    name: sc_name,
                    matches: sc_m.into_inner(),
                });

                ok!(self.resolve_pending(matcher));
                #[cfg(feature = "env")]
                ok!(self.add_env(matcher));
                ok!(self.add_defaults(matcher));
                return Validator::new(self.cmd).validate(parse_state, matcher);
            } else {
                // Start error processing
                let _ = self.resolve_pending(matcher);
                return Err(self.match_arg_error(&arg_os, valid_arg_found, trailing_values));
            }
        }

        if let Some(ref pos_sc_name) = subcmd_name {
            let sc_name = self
                .cmd
                .find_subcommand(pos_sc_name)
                .expect(INTERNAL_ERROR_MSG)
                .get_name()
                .to_owned();
            ok!(self.parse_subcommand(&sc_name, matcher, raw_args, args_cursor, keep_state));
        }

        ok!(self.resolve_pending(matcher));
        #[cfg(feature = "env")]
        ok!(self.add_env(matcher));
        ok!(self.add_defaults(matcher));
        Validator::new(self.cmd).validate(parse_state, matcher)
    }

    fn match_arg_error(
        &self,
        arg_os: &clap_lex::ParsedArg<'_>,
        valid_arg_found: bool,
        trailing_values: bool,
    ) -> ClapError {
        // If argument follows a `--`
        if trailing_values {
            // If the arg matches a subcommand name, or any of its aliases (if defined)
            if self
                .possible_subcommand(arg_os.to_value(), valid_arg_found)
                .is_some()
            {
                return ClapError::unnecessary_double_dash(
                    self.cmd,
                    arg_os.display().to_string(),
                    Usage::new(self.cmd).create_usage_with_title(&[]),
                );
            }
        }

        let candidates = suggestions::did_you_mean(
            &arg_os.display().to_string(),
            self.cmd.all_subcommand_names(),
        );
        // If the argument looks like a subcommand.
        if !candidates.is_empty() {
            return ClapError::invalid_subcommand(
                self.cmd,
                arg_os.display().to_string(),
                candidates,
                self.cmd
                    .get_bin_name()
                    .unwrap_or_else(|| self.cmd.get_name())
                    .to_owned(),
                Usage::new(self.cmd).create_usage_with_title(&[]),
            );
        }

        // If the argument must be a subcommand.
        if self.cmd.has_subcommands()
            && (!self.cmd.has_positionals() || self.cmd.is_infer_subcommands_set())
        {
            return ClapError::unrecognized_subcommand(
                self.cmd,
                arg_os.display().to_string(),
                Usage::new(self.cmd).create_usage_with_title(&[]),
            );
        }

        let suggested_trailing_arg = !trailing_values
            && self.cmd.has_positionals()
            && (arg_os.is_long() || arg_os.is_short());
        ClapError::unknown_argument(
            self.cmd,
            arg_os.display().to_string(),
            None,
            suggested_trailing_arg,
            Usage::new(self.cmd).create_usage_with_title(&[]),
        )
    }

    // Checks if the arg matches a subcommand name, or any of its aliases (if defined)
    fn possible_subcommand(
        &self,
        arg: Result<&str, &RawOsStr>,
        valid_arg_found: bool,
    ) -> Option<&str> {
        debug!("Parser::possible_subcommand: arg={:?}", arg);
        let arg = some!(arg.ok());

        if !(self.cmd.is_args_conflicts_with_subcommands_set() && valid_arg_found) {
            if self.cmd.is_infer_subcommands_set() {
                // For subcommand `test`, we accepts it's prefix: `t`, `te`,
                // `tes` and `test`.
                let v = self
                    .cmd
                    .all_subcommand_names()
                    .filter(|s| s.starts_with(arg))
                    .collect::<Vec<_>>();

                if v.len() == 1 {
                    return Some(v[0]);
                }

                // If there is any ambiguity, fallback to non-infer subcommand
                // search.
            }
            if let Some(sc) = self.cmd.find_subcommand(arg) {
                return Some(sc.get_name());
            }
        }
        None
    }

    // Checks if the arg matches a long flag subcommand name, or any of its aliases (if defined)
    fn possible_long_flag_subcommand(&self, arg: &str) -> Option<&str> {
        debug!("Parser::possible_long_flag_subcommand: arg={:?}", arg);
        if self.cmd.is_infer_subcommands_set() {
            let options = self
                .cmd
                .get_subcommands()
                .fold(Vec::new(), |mut options, sc| {
                    if let Some(long) = sc.get_long_flag() {
                        if long.starts_with(arg) {
                            options.push(long);
                        }
                        options.extend(sc.get_all_aliases().filter(|alias| alias.starts_with(arg)))
                    }
                    options
                });
            if options.len() == 1 {
                return Some(options[0]);
            }

            for sc in options {
                if sc == arg {
                    return Some(sc);
                }
            }
        } else if let Some(sc_name) = self.cmd.find_long_subcmd(arg) {
            return Some(sc_name);
        }
        None
    }

    fn parse_help_subcommand(
        &self,
        cmds: impl Iterator<Item = &'cmd OsStr>,
    ) -> ClapResult<std::convert::Infallible> {
        debug!("Parser::parse_help_subcommand");

        let mut cmd = self.cmd.clone();
        let sc = {
            let mut sc = &mut cmd;

            for cmd in cmds {
                sc = if let Some(sc_name) =
                    sc.find_subcommand(cmd).map(|sc| sc.get_name().to_owned())
                {
                    sc._build_subcommand(&sc_name).unwrap()
                } else {
                    return Err(ClapError::unrecognized_subcommand(
                        sc,
                        cmd.to_string_lossy().into_owned(),
                        Usage::new(sc).create_usage_with_title(&[]),
                    ));
                };
            }

            sc
        };
        let parser = Parser::new(sc);

        Err(parser.help_err(true))
    }

Find subcommand such that its name or one of aliases equals name, returning a mutable reference to the subcommand.

This does not recurse through subcommands of subcommands.

Iterate through the set of groups.

Examples found in repository?
src/parser/arg_matcher.rs (line 29)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    pub(crate) fn new(_cmd: &Command) -> Self {
        ArgMatcher {
            matches: ArgMatches {
                #[cfg(debug_assertions)]
                valid_args: {
                    let args = _cmd.get_arguments().map(|a| a.get_id().clone());
                    let groups = _cmd.get_groups().map(|g| g.get_id().clone());
                    args.chain(groups).collect()
                },
                #[cfg(debug_assertions)]
                valid_subcommands: _cmd
                    .get_subcommands()
                    .map(|sc| sc.get_name_str().clone())
                    .collect(),
                ..Default::default()
            },
            pending: None,
        }
    }
More examples
Hide additional examples
src/output/usage.rs (line 175)
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
    fn needs_options_tag(&self) -> bool {
        debug!("Usage::needs_options_tag");
        'outer: for f in self.cmd.get_non_positionals() {
            debug!("Usage::needs_options_tag:iter: f={}", f.get_id());

            // Don't print `[OPTIONS]` just for help or version
            if f.get_long() == Some("help") || f.get_long() == Some("version") {
                debug!("Usage::needs_options_tag:iter Option is built-in");
                continue;
            }

            if f.is_hide_set() {
                debug!("Usage::needs_options_tag:iter Option is hidden");
                continue;
            }
            if f.is_required_set() {
                debug!("Usage::needs_options_tag:iter Option is required");
                continue;
            }
            for grp_s in self.cmd.groups_for_arg(f.get_id()) {
                debug!("Usage::needs_options_tag:iter:iter: grp_s={:?}", grp_s);
                if self.cmd.get_groups().any(|g| g.id == grp_s && g.required) {
                    debug!("Usage::needs_options_tag:iter:iter: Group is required");
                    continue 'outer;
                }
            }

            debug!("Usage::needs_options_tag:iter: [OPTIONS] required");
            return true;
        }

        debug!("Usage::needs_options_tag: [OPTIONS] not required");
        false
    }
src/builder/debug_asserts.rs (line 282)
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
pub(crate) fn assert_app(cmd: &Command) {
    debug!("Command::_debug_asserts");

    let mut short_flags = vec![];
    let mut long_flags = vec![];

    // Invalid version flag settings
    if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
        // PropagateVersion is meaningless if there is no version
        assert!(
            !cmd.is_propagate_version_set(),
            "Command {}: No version information via Command::version or Command::long_version to propagate",
            cmd.get_name(),
        );

        // Used `Command::mut_arg("version", ..) but did not provide any version information to display
        let version_needed = cmd
            .get_arguments()
            .filter(|x| matches!(x.get_action(), ArgAction::Version))
            .map(|x| x.get_id())
            .collect::<Vec<_>>();

        assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
            ,cmd.get_name()
        );
    }

    for sc in cmd.get_subcommands() {
        if let Some(s) = sc.get_short_flag().as_ref() {
            short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
        }

        for short_alias in sc.get_all_short_flag_aliases() {
            short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
        }

        if let Some(l) = sc.get_long_flag().as_ref() {
            assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
            long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
        }

        for long_alias in sc.get_all_long_flag_aliases() {
            long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
        }
    }

    for arg in cmd.get_arguments() {
        assert_arg(arg);

        assert!(
            !cmd.is_multicall_set(),
            "Command {}: Arguments like {} cannot be set on a multicall command",
            cmd.get_name(),
            arg.get_id()
        );

        if let Some(s) = arg.get_short() {
            short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str()));
        }

        for (short_alias, _) in &arg.short_aliases {
            short_flags.push(Flag::Arg(
                format!("-{}", short_alias),
                arg.get_id().as_str(),
            ));
        }

        if let Some(l) = arg.get_long() {
            assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l);
            long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str()));
        }

        for (long_alias, _) in &arg.aliases {
            long_flags.push(Flag::Arg(
                format!("--{}", long_alias),
                arg.get_id().as_str(),
            ));
        }

        // Name conflicts
        if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
            panic!(
            "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
            cmd.get_name(),
            arg.get_id(),
            duplicate_tip(cmd, first, second),
        );
        }

        // Long conflicts
        if let Some(l) = arg.get_long() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) {
                panic!(
                    "Command {}: Long option names must be unique for each argument, \
                            but '--{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    l,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second)
                )
            }
        }

        // Short conflicts
        if let Some(s) = arg.get_short() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
                panic!(
                    "Command {}: Short option names must be unique for each argument, \
                            but '-{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    s,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second),
                )
            }
        }

        // Index conflicts
        if let Some(idx) = arg.index {
            if let Some((first, second)) =
                cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
            {
                panic!(
                    "Command {}: Argument '{}' has the same index as '{}' \
                    and they are both positional arguments\n\n\t \
                    Use `Arg::num_args(1..)` to allow one \
                    positional argument to take multiple values",
                    cmd.get_name(),
                    first.get_id(),
                    second.get_id()
                )
            }
        }

        // requires, r_if, r_unless
        for req in &arg.requires {
            assert!(
                cmd.id_exists(&req.1),
                "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
                cmd.get_name(),
                req.1,
                arg.get_id(),
            );
        }

        for req in &arg.r_ifs {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_ifs_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq_all`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_unless {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        for req in &arg.r_unless_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // blacklist
        for req in &arg.blacklist {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // overrides
        for req in &arg.overrides {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        if arg.is_last_set() {
            assert!(
                arg.get_long().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
            assert!(
                arg.get_short().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }

        assert!(
            !(arg.is_required_set() && arg.is_global_set()),
            "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
                    cmd.get_name(),
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_positional(),
                "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
                cmd.get_name(),
                arg.get_id()
            );

            assert!(
                arg.is_trailing_var_arg_set() || arg.is_last_set(),
                "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }
    }

    for group in cmd.get_groups() {
        let derive_hint = if cfg!(feature = "derive") {
            " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
        } else {
            ""
        };

        // Name conflicts
        assert!(
            cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
            "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        // Groups should not have naming conflicts with Args
        assert!(
            !cmd.get_arguments().any(|x| x.get_id() == group.get_id()),
            "Command {}: Argument group name '{}' must not conflict with argument name{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        for arg in &group.args {
            // Args listed inside groups should exist
            assert!(
                cmd.get_arguments().any(|x| x.get_id() == arg),
                "Command {}: Argument group '{}' contains non-existent argument '{}'",
                cmd.get_name(),
                group.get_id(),
                arg
            );
        }
    }

    // Conflicts between flags and subcommands

    long_flags.sort_unstable();
    short_flags.sort_unstable();

    detect_duplicate_flags(&long_flags, "long");
    detect_duplicate_flags(&short_flags, "short");

    let mut subs = FlatSet::new();
    for sc in cmd.get_subcommands() {
        assert!(
            subs.insert(sc.get_name()),
            "Command {}: command name `{}` is duplicated",
            cmd.get_name(),
            sc.get_name()
        );
        for alias in sc.get_all_aliases() {
            assert!(
                subs.insert(alias),
                "Command {}: command `{}` alias `{}` is duplicated",
                cmd.get_name(),
                sc.get_name(),
                alias
            );
        }
    }

    _verify_positionals(cmd);

    #[cfg(feature = "help")]
    if let Some(help_template) = cmd.get_help_template() {
        assert!(
            !help_template.to_string().contains("{flags}"),
            "Command {}: {}",
                    cmd.get_name(),
            "`{flags}` template variable was removed in clap3, they are now included in `{options}`",
        );
        assert!(
            !help_template.to_string().contains("{unified}"),
            "Command {}: {}",
            cmd.get_name(),
            "`{unified}` template variable was removed in clap3, use `{options}` instead"
        );
    }

    cmd._panic_on_missing_help(cmd.is_help_expected_set());
    assert_app_flags(cmd);
}

Iterate through the set of arguments.

Examples found in repository?
src/builder/command.rs (line 3461)
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
    pub fn get_positionals(&self) -> impl Iterator<Item = &Arg> {
        self.get_arguments().filter(|a| a.is_positional())
    }

    /// Iterate through the *options*.
    pub fn get_opts(&self) -> impl Iterator<Item = &Arg> {
        self.get_arguments()
            .filter(|a| a.is_takes_value_set() && !a.is_positional())
    }

    /// Get a list of all arguments the given argument conflicts with.
    ///
    /// If the provided argument is declared as global, the conflicts will be determined
    /// based on the propagation rules of global arguments.
    ///
    /// ### Panics
    ///
    /// If the given arg contains a conflict with an argument that is unknown to
    /// this `Command`.
    pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
    {
        if arg.is_global_set() {
            self.get_global_arg_conflicts_with(arg)
        } else {
            let mut result = Vec::new();
            for id in arg.blacklist.iter() {
                if let Some(arg) = self.find(id) {
                    result.push(arg);
                } else if let Some(group) = self.find_group(id) {
                    result.extend(
                        self.unroll_args_in_group(&group.id)
                            .iter()
                            .map(|id| self.find(id).expect(INTERNAL_ERROR_MSG)),
                    );
                } else {
                    panic!("Command::get_arg_conflicts_with: The passed arg conflicts with an arg unknown to the cmd");
                }
            }
            result
        }
    }

    // Get a unique list of all arguments of all commands and continuous subcommands the given argument conflicts with.
    //
    // This behavior follows the propagation rules of global arguments.
    // It is useful for finding conflicts for arguments declared as global.
    //
    // ### Panics
    //
    // If the given arg contains a conflict with an argument that is unknown to
    // this `Command`.
    fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg> // FIXME: This could probably have been an iterator
    {
        arg.blacklist
            .iter()
            .map(|id| {
                self.args
                    .args()
                    .chain(
                        self.get_subcommands_containing(arg)
                            .iter()
                            .flat_map(|x| x.args.args()),
                    )
                    .find(|arg| arg.get_id() == id)
                    .expect(
                        "Command::get_arg_conflicts_with: \
                    The passed arg conflicts with an arg unknown to the cmd",
                    )
            })
            .collect()
    }

    // Get a list of subcommands which contain the provided Argument
    //
    // This command will only include subcommands in its list for which the subcommands
    // parent also contains the Argument.
    //
    // This search follows the propagation rules of global arguments.
    // It is useful to finding subcommands, that have inherited a global argument.
    //
    // **NOTE:** In this case only Sucommand_1 will be included
    //   Subcommand_1 (contains Arg)
    //     Subcommand_1.1 (doesn't contain Arg)
    //       Subcommand_1.1.1 (contains Arg)
    //
    fn get_subcommands_containing(&self, arg: &Arg) -> Vec<&Self> {
        let mut vec = std::vec::Vec::new();
        for idx in 0..self.subcommands.len() {
            if self.subcommands[idx]
                .args
                .args()
                .any(|ar| ar.get_id() == arg.get_id())
            {
                vec.push(&self.subcommands[idx]);
                vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg));
            }
        }
        vec
    }

    /// Report whether [`Command::no_binary_name`] is set
    pub fn is_no_binary_name_set(&self) -> bool {
        self.is_set(AppSettings::NoBinaryName)
    }

    /// Report whether [`Command::ignore_errors`] is set
    pub(crate) fn is_ignore_errors_set(&self) -> bool {
        self.is_set(AppSettings::IgnoreErrors)
    }

    /// Report whether [`Command::dont_delimit_trailing_values`] is set
    pub fn is_dont_delimit_trailing_values_set(&self) -> bool {
        self.is_set(AppSettings::DontDelimitTrailingValues)
    }

    /// Report whether [`Command::disable_version_flag`] is set
    pub fn is_disable_version_flag_set(&self) -> bool {
        self.is_set(AppSettings::DisableVersionFlag)
            || (self.version.is_none() && self.long_version.is_none())
    }

    /// Report whether [`Command::propagate_version`] is set
    pub fn is_propagate_version_set(&self) -> bool {
        self.is_set(AppSettings::PropagateVersion)
    }

    /// Report whether [`Command::next_line_help`] is set
    pub fn is_next_line_help_set(&self) -> bool {
        self.is_set(AppSettings::NextLineHelp)
    }

    /// Report whether [`Command::disable_help_flag`] is set
    pub fn is_disable_help_flag_set(&self) -> bool {
        self.is_set(AppSettings::DisableHelpFlag)
    }

    /// Report whether [`Command::disable_help_subcommand`] is set
    pub fn is_disable_help_subcommand_set(&self) -> bool {
        self.is_set(AppSettings::DisableHelpSubcommand)
    }

    /// Report whether [`Command::disable_colored_help`] is set
    pub fn is_disable_colored_help_set(&self) -> bool {
        self.is_set(AppSettings::DisableColoredHelp)
    }

    /// Report whether [`Command::help_expected`] is set
    #[cfg(debug_assertions)]
    pub(crate) fn is_help_expected_set(&self) -> bool {
        self.is_set(AppSettings::HelpExpected)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "This is now the default")
    )]
    pub fn is_dont_collapse_args_in_usage_set(&self) -> bool {
        true
    }

    /// Report whether [`Command::infer_long_args`] is set
    pub(crate) fn is_infer_long_args_set(&self) -> bool {
        self.is_set(AppSettings::InferLongArgs)
    }

    /// Report whether [`Command::infer_subcommands`] is set
    pub(crate) fn is_infer_subcommands_set(&self) -> bool {
        self.is_set(AppSettings::InferSubcommands)
    }

    /// Report whether [`Command::arg_required_else_help`] is set
    pub fn is_arg_required_else_help_set(&self) -> bool {
        self.is_set(AppSettings::ArgRequiredElseHelp)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(
            since = "4.0.0",
            note = "Replaced with `Arg::is_allow_hyphen_values_set`"
        )
    )]
    pub(crate) fn is_allow_hyphen_values_set(&self) -> bool {
        self.is_set(AppSettings::AllowHyphenValues)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(
            since = "4.0.0",
            note = "Replaced with `Arg::is_allow_negative_numbers_set`"
        )
    )]
    pub fn is_allow_negative_numbers_set(&self) -> bool {
        self.is_set(AppSettings::AllowNegativeNumbers)
    }

    #[doc(hidden)]
    #[cfg_attr(
        feature = "deprecated",
        deprecated(since = "4.0.0", note = "Replaced with `Arg::is_trailing_var_arg_set`")
    )]
    pub fn is_trailing_var_arg_set(&self) -> bool {
        self.is_set(AppSettings::TrailingVarArg)
    }

    /// Report whether [`Command::allow_missing_positional`] is set
    pub fn is_allow_missing_positional_set(&self) -> bool {
        self.is_set(AppSettings::AllowMissingPositional)
    }

    /// Report whether [`Command::hide`] is set
    pub fn is_hide_set(&self) -> bool {
        self.is_set(AppSettings::Hidden)
    }

    /// Report whether [`Command::subcommand_required`] is set
    pub fn is_subcommand_required_set(&self) -> bool {
        self.is_set(AppSettings::SubcommandRequired)
    }

    /// Report whether [`Command::allow_external_subcommands`] is set
    pub fn is_allow_external_subcommands_set(&self) -> bool {
        self.is_set(AppSettings::AllowExternalSubcommands)
    }

    /// Configured parser for values passed to an external subcommand
    ///
    /// # Example
    ///
    /// ```rust
    /// let cmd = clap::Command::new("raw")
    ///     .external_subcommand_value_parser(clap::value_parser!(String));
    /// let value_parser = cmd.get_external_subcommand_value_parser();
    /// println!("{:?}", value_parser);
    /// ```
    pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> {
        if !self.is_allow_external_subcommands_set() {
            None
        } else {
            static DEFAULT: super::ValueParser = super::ValueParser::os_string();
            Some(self.external_value_parser.as_ref().unwrap_or(&DEFAULT))
        }
    }

    /// Report whether [`Command::args_conflicts_with_subcommands`] is set
    pub fn is_args_conflicts_with_subcommands_set(&self) -> bool {
        self.is_set(AppSettings::ArgsNegateSubcommands)
    }

    #[doc(hidden)]
    pub fn is_args_override_self(&self) -> bool {
        self.is_set(AppSettings::AllArgsOverrideSelf)
    }

    /// Report whether [`Command::subcommand_precedence_over_arg`] is set
    pub fn is_subcommand_precedence_over_arg_set(&self) -> bool {
        self.is_set(AppSettings::SubcommandPrecedenceOverArg)
    }

    /// Report whether [`Command::subcommand_negates_reqs`] is set
    pub fn is_subcommand_negates_reqs_set(&self) -> bool {
        self.is_set(AppSettings::SubcommandsNegateReqs)
    }

    /// Report whether [`Command::multicall`] is set
    pub fn is_multicall_set(&self) -> bool {
        self.is_set(AppSettings::Multicall)
    }
}

// Internally used only
impl Command {
    pub(crate) fn get_override_usage(&self) -> Option<&StyledStr> {
        self.usage_str.as_ref()
    }

    pub(crate) fn get_override_help(&self) -> Option<&StyledStr> {
        self.help_str.as_ref()
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_help_template(&self) -> Option<&StyledStr> {
        self.template.as_ref()
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_term_width(&self) -> Option<usize> {
        self.term_w
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_max_term_width(&self) -> Option<usize> {
        self.max_w
    }

    pub(crate) fn get_replacement(&self, key: &str) -> Option<&[Str]> {
        self.replacers.get(key).map(|v| v.as_slice())
    }

    pub(crate) fn get_keymap(&self) -> &MKeyMap {
        &self.args
    }

    fn get_used_global_args(&self, matches: &ArgMatches, global_arg_vec: &mut Vec<Id>) {
        global_arg_vec.extend(
            self.args
                .args()
                .filter(|a| a.is_global_set())
                .map(|ga| ga.id.clone()),
        );
        if let Some((id, matches)) = matches.subcommand() {
            if let Some(used_sub) = self.find_subcommand(id) {
                used_sub.get_used_global_args(matches, global_arg_vec);
            }
        }
    }

    fn _do_parse(
        &mut self,
        raw_args: &mut clap_lex::RawArgs,
        args_cursor: clap_lex::ArgCursor,
    ) -> ClapResult<ArgMatches> {
        debug!("Command::_do_parse");

        // If there are global arguments, or settings we need to propagate them down to subcommands
        // before parsing in case we run into a subcommand
        self._build_self(false);

        let mut matcher = ArgMatcher::new(self);

        // do the real parsing
        let mut parser = Parser::new(self);
        if let Err(error) = parser.get_matches_with(&mut matcher, raw_args, args_cursor) {
            if self.is_set(AppSettings::IgnoreErrors) {
                debug!("Command::_do_parse: ignoring error: {}", error);
            } else {
                return Err(error);
            }
        }

        let mut global_arg_vec = Default::default();
        self.get_used_global_args(&matcher, &mut global_arg_vec);

        matcher.propagate_globals(&global_arg_vec);

        Ok(matcher.into_inner())
    }

    /// Prepare for introspecting on all included [`Command`]s
    ///
    /// Call this on the top-level [`Command`] when done building and before reading state for
    /// cases like completions, custom help output, etc.
    pub fn build(&mut self) {
        self._build_recursive(true);
        self._build_bin_names_internal();
    }

    pub(crate) fn _build_recursive(&mut self, expand_help_tree: bool) {
        self._build_self(expand_help_tree);
        for subcmd in self.get_subcommands_mut() {
            subcmd._build_recursive(expand_help_tree);
        }
    }

    pub(crate) fn _build_self(&mut self, expand_help_tree: bool) {
        debug!("Command::_build: name={:?}", self.get_name());
        if !self.settings.is_set(AppSettings::Built) {
            // Make sure all the globally set flags apply to us as well
            self.settings = self.settings | self.g_settings;

            if self.is_multicall_set() {
                self.settings.insert(AppSettings::SubcommandRequired.into());
                self.settings.insert(AppSettings::DisableHelpFlag.into());
                self.settings.insert(AppSettings::DisableVersionFlag.into());
            }
            if !cfg!(feature = "help") && self.get_override_help().is_none() {
                self.settings.insert(AppSettings::DisableHelpFlag.into());
                self.settings
                    .insert(AppSettings::DisableHelpSubcommand.into());
            }
            if self.is_set(AppSettings::ArgsNegateSubcommands) {
                self.settings
                    .insert(AppSettings::SubcommandsNegateReqs.into());
            }
            if self.external_value_parser.is_some() {
                self.settings
                    .insert(AppSettings::AllowExternalSubcommands.into());
            }
            if !self.has_subcommands() {
                self.settings
                    .insert(AppSettings::DisableHelpSubcommand.into());
            }

            self._propagate();
            self._check_help_and_version(expand_help_tree);
            self._propagate_global_args();

            let mut pos_counter = 1;
            let hide_pv = self.is_set(AppSettings::HidePossibleValues);
            for a in self.args.args_mut() {
                // Fill in the groups
                for g in &a.groups {
                    if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) {
                        ag.args.push(a.get_id().clone());
                    } else {
                        let mut ag = ArgGroup::new(g);
                        ag.args.push(a.get_id().clone());
                        self.groups.push(ag);
                    }
                }

                // Figure out implied settings
                a._build();
                if hide_pv && a.is_takes_value_set() {
                    a.settings.set(ArgSettings::HidePossibleValues);
                }
                if a.is_positional() && a.index.is_none() {
                    a.index = Some(pos_counter);
                    pos_counter += 1;
                }
            }

            self.args._build();

            #[allow(deprecated)]
            {
                let highest_idx = self
                    .get_keymap()
                    .keys()
                    .filter_map(|x| {
                        if let crate::mkeymap::KeyType::Position(n) = x {
                            Some(*n)
                        } else {
                            None
                        }
                    })
                    .max()
                    .unwrap_or(0);
                let is_trailing_var_arg_set = self.is_trailing_var_arg_set();
                let is_allow_hyphen_values_set = self.is_allow_hyphen_values_set();
                let is_allow_negative_numbers_set = self.is_allow_negative_numbers_set();
                for arg in self.args.args_mut() {
                    if is_allow_hyphen_values_set && arg.is_takes_value_set() {
                        arg.settings.insert(ArgSettings::AllowHyphenValues.into());
                    }
                    if is_allow_negative_numbers_set && arg.is_takes_value_set() {
                        arg.settings
                            .insert(ArgSettings::AllowNegativeNumbers.into());
                    }
                    if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) {
                        arg.settings.insert(ArgSettings::TrailingVarArg.into());
                    }
                }
            }

            #[cfg(debug_assertions)]
            assert_app(self);
            self.settings.set(AppSettings::Built);
        } else {
            debug!("Command::_build: already built");
        }
    }

    pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> {
        use std::fmt::Write;

        let mut mid_string = String::from(" ");
        #[cfg(feature = "usage")]
        if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set()
        {
            let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

            for s in &reqs {
                mid_string.push_str(&s.to_string());
                mid_string.push(' ');
            }
        }
        let is_multicall_set = self.is_multicall_set();

        let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name));

        // Display subcommand name, short and long in usage
        let mut sc_names = String::new();
        sc_names.push_str(sc.name.as_str());
        let mut flag_subcmd = false;
        if let Some(l) = sc.get_long_flag() {
            write!(sc_names, "|--{}", l).unwrap();
            flag_subcmd = true;
        }
        if let Some(s) = sc.get_short_flag() {
            write!(sc_names, "|-{}", s).unwrap();
            flag_subcmd = true;
        }

        if flag_subcmd {
            sc_names = format!("{{{}}}", sc_names);
        }

        let usage_name = self
            .bin_name
            .as_ref()
            .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names))
            .unwrap_or(sc_names);
        sc.usage_name = Some(usage_name);

        // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
        // a space
        let bin_name = format!(
            "{}{}{}",
            self.bin_name.as_deref().unwrap_or_default(),
            if self.bin_name.is_some() { " " } else { "" },
            &*sc.name
        );
        debug!(
            "Command::_build_subcommand Setting bin_name of {} to {:?}",
            sc.name, bin_name
        );
        sc.bin_name = Some(bin_name);

        if sc.display_name.is_none() {
            let self_display_name = if is_multicall_set {
                self.display_name.as_deref().unwrap_or("")
            } else {
                self.display_name.as_deref().unwrap_or(&self.name)
            };
            let display_name = format!(
                "{}{}{}",
                self_display_name,
                if !self_display_name.is_empty() {
                    "-"
                } else {
                    ""
                },
                &*sc.name
            );
            debug!(
                "Command::_build_subcommand Setting display_name of {} to {:?}",
                sc.name, display_name
            );
            sc.display_name = Some(display_name);
        }

        // Ensure all args are built and ready to parse
        sc._build_self(false);

        Some(sc)
    }

    fn _build_bin_names_internal(&mut self) {
        debug!("Command::_build_bin_names");

        if !self.is_set(AppSettings::BinNameBuilt) {
            let mut mid_string = String::from(" ");
            #[cfg(feature = "usage")]
            if !self.is_subcommand_negates_reqs_set()
                && !self.is_args_conflicts_with_subcommands_set()
            {
                let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

                for s in &reqs {
                    mid_string.push_str(&s.to_string());
                    mid_string.push(' ');
                }
            }
            let is_multicall_set = self.is_multicall_set();

            let self_bin_name = if is_multicall_set {
                self.bin_name.as_deref().unwrap_or("")
            } else {
                self.bin_name.as_deref().unwrap_or(&self.name)
            }
            .to_owned();

            for mut sc in &mut self.subcommands {
                debug!("Command::_build_bin_names:iter: bin_name set...");

                if sc.usage_name.is_none() {
                    use std::fmt::Write;
                    // Display subcommand name, short and long in usage
                    let mut sc_names = String::new();
                    sc_names.push_str(sc.name.as_str());
                    let mut flag_subcmd = false;
                    if let Some(l) = sc.get_long_flag() {
                        write!(sc_names, "|--{}", l).unwrap();
                        flag_subcmd = true;
                    }
                    if let Some(s) = sc.get_short_flag() {
                        write!(sc_names, "|-{}", s).unwrap();
                        flag_subcmd = true;
                    }

                    if flag_subcmd {
                        sc_names = format!("{{{}}}", sc_names);
                    }

                    let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names);
                    debug!(
                        "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}",
                        sc.name, usage_name
                    );
                    sc.usage_name = Some(usage_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})",
                        sc.name, sc.usage_name
                    );
                }

                if sc.bin_name.is_none() {
                    let bin_name = format!(
                        "{}{}{}",
                        self_bin_name,
                        if !self_bin_name.is_empty() { " " } else { "" },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}",
                        sc.name, bin_name
                    );
                    sc.bin_name = Some(bin_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})",
                        sc.name, sc.bin_name
                    );
                }

                if sc.display_name.is_none() {
                    let self_display_name = if is_multicall_set {
                        self.display_name.as_deref().unwrap_or("")
                    } else {
                        self.display_name.as_deref().unwrap_or(&self.name)
                    };
                    let display_name = format!(
                        "{}{}{}",
                        self_display_name,
                        if !self_display_name.is_empty() {
                            "-"
                        } else {
                            ""
                        },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting display_name of {} to {:?}",
                        sc.name, display_name
                    );
                    sc.display_name = Some(display_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})",
                        sc.name, sc.display_name
                    );
                }

                sc._build_bin_names_internal();
            }
            self.set(AppSettings::BinNameBuilt);
        } else {
            debug!("Command::_build_bin_names: already built");
        }
    }

    pub(crate) fn _panic_on_missing_help(&self, help_required_globally: bool) {
        if self.is_set(AppSettings::HelpExpected) || help_required_globally {
            let args_missing_help: Vec<Id> = self
                .args
                .args()
                .filter(|arg| arg.get_help().is_none() && arg.get_long_help().is_none())
                .map(|arg| arg.get_id().clone())
                .collect();

            debug_assert!(args_missing_help.is_empty(),
                    "Command::help_expected is enabled for the Command {}, but at least one of its arguments does not have either `help` or `long_help` set. List of such arguments: {}",
                    self.name,
                    args_missing_help.join(", ")
                );
        }

        for sub_app in &self.subcommands {
            sub_app._panic_on_missing_help(help_required_globally);
        }
    }

    #[cfg(debug_assertions)]
    pub(crate) fn two_args_of<F>(&self, condition: F) -> Option<(&Arg, &Arg)>
    where
        F: Fn(&Arg) -> bool,
    {
        two_elements_of(self.args.args().filter(|a: &&Arg| condition(a)))
    }

    // just in case
    #[allow(unused)]
    fn two_groups_of<F>(&self, condition: F) -> Option<(&ArgGroup, &ArgGroup)>
    where
        F: Fn(&ArgGroup) -> bool,
    {
        two_elements_of(self.groups.iter().filter(|a| condition(a)))
    }

    /// Propagate global args
    pub(crate) fn _propagate_global_args(&mut self) {
        debug!("Command::_propagate_global_args:{}", self.name);

        let autogenerated_help_subcommand = !self.is_disable_help_subcommand_set();

        for sc in &mut self.subcommands {
            if sc.get_name() == "help" && autogenerated_help_subcommand {
                // Avoid propagating args to the autogenerated help subtrees used in completion.
                // This prevents args from showing up during help completions like
                // `myapp help subcmd <TAB>`, which should only suggest subcommands and not args,
                // while still allowing args to show up properly on the generated help message.
                continue;
            }

            for a in self.args.args().filter(|a| a.is_global_set()) {
                if sc.find(&a.id).is_some() {
                    debug!(
                        "Command::_propagate skipping {:?} to {}, already exists",
                        a.id,
                        sc.get_name(),
                    );
                    continue;
                }

                debug!(
                    "Command::_propagate pushing {:?} to {}",
                    a.id,
                    sc.get_name(),
                );
                sc.args.push(a.clone());
            }
        }
    }

    /// Propagate settings
    pub(crate) fn _propagate(&mut self) {
        debug!("Command::_propagate:{}", self.name);
        let mut subcommands = std::mem::take(&mut self.subcommands);
        for sc in &mut subcommands {
            self._propagate_subcommand(sc);
        }
        self.subcommands = subcommands;
    }

    fn _propagate_subcommand(&self, sc: &mut Self) {
        // We have to create a new scope in order to tell rustc the borrow of `sc` is
        // done and to recursively call this method
        {
            if self.settings.is_set(AppSettings::PropagateVersion) {
                if let Some(version) = self.version.as_ref() {
                    sc.version.get_or_insert_with(|| version.clone());
                }
                if let Some(long_version) = self.long_version.as_ref() {
                    sc.long_version.get_or_insert_with(|| long_version.clone());
                }
            }

            sc.settings = sc.settings | self.g_settings;
            sc.g_settings = sc.g_settings | self.g_settings;
            sc.term_w = self.term_w;
            sc.max_w = self.max_w;
        }
    }

    pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) {
        debug!(
            "Command::_check_help_and_version:{} expand_help_tree={}",
            self.name, expand_help_tree
        );

        self.long_help_exists = self.long_help_exists_();

        if !self.is_disable_help_flag_set() {
            debug!("Command::_check_help_and_version: Building default --help");
            let mut arg = Arg::new(Id::HELP)
                .short('h')
                .long("help")
                .action(ArgAction::Help);
            if self.long_help_exists {
                arg = arg
                    .help("Print help information (use `--help` for more detail)")
                    .long_help("Print help information (use `-h` for a summary)");
            } else {
                arg = arg.help("Print help information");
            }
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }
        if !self.is_disable_version_flag_set() {
            debug!("Command::_check_help_and_version: Building default --version");
            let arg = Arg::new(Id::VERSION)
                .short('V')
                .long("version")
                .action(ArgAction::Version)
                .help("Print version information");
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }

        if !self.is_set(AppSettings::DisableHelpSubcommand) {
            debug!("Command::_check_help_and_version: Building help subcommand");
            let help_about = "Print this message or the help of the given subcommand(s)";

            let mut help_subcmd = if expand_help_tree {
                // Slow code path to recursively clone all other subcommand subtrees under help
                let help_subcmd = Command::new("help")
                    .about(help_about)
                    .global_setting(AppSettings::DisableHelpSubcommand)
                    .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));

                let mut help_help_subcmd = Command::new("help").about(help_about);
                help_help_subcmd.version = None;
                help_help_subcmd.long_version = None;
                help_help_subcmd = help_help_subcmd
                    .setting(AppSettings::DisableHelpFlag)
                    .setting(AppSettings::DisableVersionFlag);

                help_subcmd.subcommand(help_help_subcmd)
            } else {
                Command::new("help").about(help_about).arg(
                    Arg::new("subcommand")
                        .action(ArgAction::Append)
                        .num_args(..)
                        .value_name("COMMAND")
                        .help("Print help for the subcommand(s)"),
                )
            };
            self._propagate_subcommand(&mut help_subcmd);

            // The parser acts like this is set, so let's set it so we don't falsely
            // advertise it to the user
            help_subcmd.version = None;
            help_subcmd.long_version = None;
            help_subcmd = help_subcmd
                .setting(AppSettings::DisableHelpFlag)
                .setting(AppSettings::DisableVersionFlag)
                .unset_global_setting(AppSettings::PropagateVersion);

            self.subcommands.push(help_subcmd);
        }
    }

    fn _copy_subtree_for_help(&self) -> Command {
        let mut cmd = Command::new(self.name.clone())
            .hide(self.is_hide_set())
            .global_setting(AppSettings::DisableHelpFlag)
            .global_setting(AppSettings::DisableVersionFlag)
            .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));
        if self.get_about().is_some() {
            cmd = cmd.about(self.get_about().unwrap().clone());
        }
        cmd
    }

    pub(crate) fn _render_version(&self, use_long: bool) -> String {
        debug!("Command::_render_version");

        let ver = if use_long {
            self.long_version
                .as_deref()
                .or(self.version.as_deref())
                .unwrap_or_default()
        } else {
            self.version
                .as_deref()
                .or(self.long_version.as_deref())
                .unwrap_or_default()
        };
        let display_name = self.get_display_name().unwrap_or_else(|| self.get_name());
        format!("{} {}\n", display_name, ver)
    }

    pub(crate) fn format_group(&self, g: &Id) -> StyledStr {
        let g_string = self
            .unroll_args_in_group(g)
            .iter()
            .filter_map(|x| self.find(x))
            .map(|x| {
                if x.is_positional() {
                    // Print val_name for positional arguments. e.g. <file_name>
                    x.name_no_brackets()
                } else {
                    // Print usage string for flags arguments, e.g. <--help>
                    x.to_string()
                }
            })
            .collect::<Vec<_>>()
            .join("|");
        let mut styled = StyledStr::new();
        styled.none("<");
        styled.none(g_string);
        styled.none(">");
        styled
    }
}

/// A workaround:
/// <https://github.com/rust-lang/rust/issues/34511#issuecomment-373423999>
pub(crate) trait Captures<'a> {}
impl<'a, T> Captures<'a> for T {}

// Internal Query Methods
impl Command {
    /// Iterate through the *flags* & *options* arguments.
    #[cfg(any(feature = "usage", feature = "help"))]
    pub(crate) fn get_non_positionals(&self) -> impl Iterator<Item = &Arg> {
        self.get_arguments().filter(|a| !a.is_positional())
    }

    pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg> {
        self.args.args().find(|a| a.get_id() == arg_id)
    }

    #[inline]
    pub(crate) fn contains_short(&self, s: char) -> bool {
        debug_assert!(
            self.is_set(AppSettings::Built),
            "If Command::_build hasn't been called, manually search through Arg shorts"
        );

        self.args.contains(s)
    }

    #[inline]
    pub(crate) fn set(&mut self, s: AppSettings) {
        self.settings.set(s)
    }

    #[inline]
    pub(crate) fn has_positionals(&self) -> bool {
        self.get_positionals().next().is_some()
    }

    #[cfg(any(feature = "usage", feature = "help"))]
    pub(crate) fn has_visible_subcommands(&self) -> bool {
        self.subcommands
            .iter()
            .any(|sc| sc.name != "help" && !sc.is_set(AppSettings::Hidden))
    }

    /// Check if this subcommand can be referred to as `name`. In other words,
    /// check if `name` is the name of this subcommand or is one of its aliases.
    #[inline]
    pub(crate) fn aliases_to(&self, name: impl AsRef<std::ffi::OsStr>) -> bool {
        let name = name.as_ref();
        self.get_name() == name || self.get_all_aliases().any(|alias| alias == name)
    }

    /// Check if this subcommand can be referred to as `name`. In other words,
    /// check if `name` is the name of this short flag subcommand or is one of its short flag aliases.
    #[inline]
    pub(crate) fn short_flag_aliases_to(&self, flag: char) -> bool {
        Some(flag) == self.short_flag
            || self.get_all_short_flag_aliases().any(|alias| flag == alias)
    }

    /// Check if this subcommand can be referred to as `name`. In other words,
    /// check if `name` is the name of this long flag subcommand or is one of its long flag aliases.
    #[inline]
    pub(crate) fn long_flag_aliases_to(&self, flag: &str) -> bool {
        match self.long_flag.as_ref() {
            Some(long_flag) => {
                long_flag == flag || self.get_all_long_flag_aliases().any(|alias| alias == flag)
            }
            None => self.get_all_long_flag_aliases().any(|alias| alias == flag),
        }
    }

    #[cfg(debug_assertions)]
    pub(crate) fn id_exists(&self, id: &Id) -> bool {
        self.args.args().any(|x| x.get_id() == id) || self.groups.iter().any(|x| x.id == *id)
    }

    /// Iterate through the groups this arg is member of.
    pub(crate) fn groups_for_arg<'a>(&'a self, arg: &Id) -> impl Iterator<Item = Id> + 'a {
        debug!("Command::groups_for_arg: id={:?}", arg);
        let arg = arg.clone();
        self.groups
            .iter()
            .filter(move |grp| grp.args.iter().any(|a| a == &arg))
            .map(|grp| grp.id.clone())
    }

    pub(crate) fn find_group(&self, group_id: &Id) -> Option<&ArgGroup> {
        self.groups.iter().find(|g| g.id == *group_id)
    }

    /// Iterate through all the names of all subcommands (not recursively), including aliases.
    /// Used for suggestions.
    pub(crate) fn all_subcommand_names(&self) -> impl Iterator<Item = &str> + Captures {
        self.get_subcommands().flat_map(|sc| {
            let name = sc.get_name();
            let aliases = sc.get_all_aliases();
            std::iter::once(name).chain(aliases)
        })
    }

    pub(crate) fn required_graph(&self) -> ChildGraph<Id> {
        let mut reqs = ChildGraph::with_capacity(5);
        for a in self.args.args().filter(|a| a.is_required_set()) {
            reqs.insert(a.get_id().clone());
        }
        for group in &self.groups {
            if group.required {
                let idx = reqs.insert(group.id.clone());
                for a in &group.requires {
                    reqs.insert_child(idx, a.clone());
                }
            }
        }

        reqs
    }

    pub(crate) fn unroll_args_in_group(&self, group: &Id) -> Vec<Id> {
        debug!("Command::unroll_args_in_group: group={:?}", group);
        let mut g_vec = vec![group];
        let mut args = vec![];

        while let Some(g) = g_vec.pop() {
            for n in self
                .groups
                .iter()
                .find(|grp| grp.id == *g)
                .expect(INTERNAL_ERROR_MSG)
                .args
                .iter()
            {
                debug!("Command::unroll_args_in_group:iter: entity={:?}", n);
                if !args.contains(n) {
                    if self.find(n).is_some() {
                        debug!("Command::unroll_args_in_group:iter: this is an arg");
                        args.push(n.clone())
                    } else {
                        debug!("Command::unroll_args_in_group:iter: this is a group");
                        g_vec.push(n);
                    }
                }
            }
        }

        args
    }

    pub(crate) fn unroll_arg_requires<F>(&self, func: F, arg: &Id) -> Vec<Id>
    where
        F: Fn(&(ArgPredicate, Id)) -> Option<Id>,
    {
        let mut processed = vec![];
        let mut r_vec = vec![arg];
        let mut args = vec![];

        while let Some(a) = r_vec.pop() {
            if processed.contains(&a) {
                continue;
            }

            processed.push(a);

            if let Some(arg) = self.find(a) {
                for r in arg.requires.iter().filter_map(&func) {
                    if let Some(req) = self.find(&r) {
                        if !req.requires.is_empty() {
                            r_vec.push(req.get_id())
                        }
                    }
                    args.push(r);
                }
            }
        }

        args
    }

    /// Find a flag subcommand name by short flag or an alias
    pub(crate) fn find_short_subcmd(&self, c: char) -> Option<&str> {
        self.get_subcommands()
            .find(|sc| sc.short_flag_aliases_to(c))
            .map(|sc| sc.get_name())
    }

    /// Find a flag subcommand name by long flag or an alias
    pub(crate) fn find_long_subcmd(&self, long: &str) -> Option<&str> {
        self.get_subcommands()
            .find(|sc| sc.long_flag_aliases_to(long))
            .map(|sc| sc.get_name())
    }

    #[cfg(feature = "help")]
    pub(crate) fn get_display_order(&self) -> usize {
        self.disp_ord.unwrap_or(999)
    }

    pub(crate) fn write_help_err(&self, mut use_long: bool) -> StyledStr {
        debug!(
            "Command::write_help_err: {}, use_long={:?}",
            self.get_display_name().unwrap_or_else(|| self.get_name()),
            use_long && self.long_help_exists(),
        );

        use_long = use_long && self.long_help_exists();
        let usage = Usage::new(self);

        let mut styled = StyledStr::new();
        write_help(&mut styled, self, &usage, use_long);

        styled
    }

    pub(crate) fn write_version_err(&self, use_long: bool) -> StyledStr {
        let msg = self._render_version(use_long);
        let mut styled = StyledStr::new();
        styled.none(msg);
        styled
    }

    pub(crate) fn long_help_exists(&self) -> bool {
        debug!("Command::long_help_exists: {}", self.long_help_exists);
        self.long_help_exists
    }

    fn long_help_exists_(&self) -> bool {
        debug!("Command::long_help_exists");
        // In this case, both must be checked. This allows the retention of
        // original formatting, but also ensures that the actual -h or --help
        // specified by the user is sent through. If hide_short_help is not included,
        // then items specified with hidden_short_help will also be hidden.
        let should_long = |v: &Arg| {
            v.get_long_help().is_some()
                || v.is_hide_long_help_set()
                || v.is_hide_short_help_set()
                || v.get_possible_values()
                    .iter()
                    .any(PossibleValue::should_show_help)
        };

        // Subcommands aren't checked because we prefer short help for them, deferring to
        // `cmd subcmd --help` for more.
        self.get_long_about().is_some()
            || self.get_before_long_help().is_some()
            || self.get_after_long_help().is_some()
            || self.get_arguments().any(should_long)
    }
More examples
Hide additional examples
src/parser/arg_matcher.rs (line 28)
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
    pub(crate) fn new(_cmd: &Command) -> Self {
        ArgMatcher {
            matches: ArgMatches {
                #[cfg(debug_assertions)]
                valid_args: {
                    let args = _cmd.get_arguments().map(|a| a.get_id().clone());
                    let groups = _cmd.get_groups().map(|g| g.get_id().clone());
                    args.chain(groups).collect()
                },
                #[cfg(debug_assertions)]
                valid_subcommands: _cmd
                    .get_subcommands()
                    .map(|sc| sc.get_name_str().clone())
                    .collect(),
                ..Default::default()
            },
            pending: None,
        }
    }
src/output/help_template.rs (line 353)
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
    pub(crate) fn write_all_args(&mut self) {
        debug!("HelpTemplate::write_all_args");
        let pos = self
            .cmd
            .get_positionals()
            .filter(|a| a.get_help_heading().is_none())
            .filter(|arg| should_show_arg(self.use_long, arg))
            .collect::<Vec<_>>();
        let non_pos = self
            .cmd
            .get_non_positionals()
            .filter(|a| a.get_help_heading().is_none())
            .filter(|arg| should_show_arg(self.use_long, arg))
            .collect::<Vec<_>>();
        let subcmds = self.cmd.has_visible_subcommands();

        let custom_headings = self
            .cmd
            .get_arguments()
            .filter_map(|arg| arg.get_help_heading())
            .collect::<FlatSet<_>>();

        let mut first = true;

        if subcmds {
            if !first {
                self.none("\n\n");
            }
            first = false;
            let default_help_heading = Str::from("Commands");
            self.header(
                self.cmd
                    .get_subcommand_help_heading()
                    .unwrap_or(&default_help_heading),
            );
            self.header(":\n");

            self.write_subcommands(self.cmd);
        }

        if !pos.is_empty() {
            if !first {
                self.none("\n\n");
            }
            first = false;
            // Write positional args if any
            self.header("Arguments:\n");
            self.write_args(&pos, "Arguments", positional_sort_key);
        }

        if !non_pos.is_empty() {
            if !first {
                self.none("\n\n");
            }
            first = false;
            self.header("Options:\n");
            self.write_args(&non_pos, "Options", option_sort_key);
        }
        if !custom_headings.is_empty() {
            for heading in custom_headings {
                let args = self
                    .cmd
                    .get_arguments()
                    .filter(|a| {
                        if let Some(help_heading) = a.get_help_heading() {
                            return help_heading == heading;
                        }
                        false
                    })
                    .filter(|arg| should_show_arg(self.use_long, arg))
                    .collect::<Vec<_>>();

                if !args.is_empty() {
                    if !first {
                        self.none("\n\n");
                    }
                    first = false;
                    self.header(format!("{}:\n", heading));
                    self.write_args(&args, heading, option_sort_key);
                }
            }
        }
    }
src/parser/validator.rs (line 309)
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
    fn validate_required(
        &mut self,
        matcher: &ArgMatcher,
        conflicts: &mut Conflicts,
    ) -> ClapResult<()> {
        debug!("Validator::validate_required: required={:?}", self.required);
        self.gather_requires(matcher);

        let mut missing_required = Vec::new();
        let mut highest_index = 0;

        let is_exclusive_present = matcher
            .arg_ids()
            .filter(|arg_id| matcher.check_explicit(arg_id, &ArgPredicate::IsPresent))
            .any(|id| {
                self.cmd
                    .find(id)
                    .map(|arg| arg.is_exclusive_set())
                    .unwrap_or_default()
            });
        debug!(
            "Validator::validate_required: is_exclusive_present={}",
            is_exclusive_present
        );

        for arg_or_group in self
            .required
            .iter()
            .filter(|r| !matcher.check_explicit(r, &ArgPredicate::IsPresent))
        {
            debug!("Validator::validate_required:iter:aog={:?}", arg_or_group);
            if let Some(arg) = self.cmd.find(arg_or_group) {
                debug!("Validator::validate_required:iter: This is an arg");
                if !is_exclusive_present && !self.is_missing_required_ok(arg, matcher, conflicts) {
                    debug!(
                        "Validator::validate_required:iter: Missing {:?}",
                        arg.get_id()
                    );
                    missing_required.push(arg.get_id().clone());
                    if !arg.is_last_set() {
                        highest_index = highest_index.max(arg.get_index().unwrap_or(0));
                    }
                }
            } else if let Some(group) = self.cmd.find_group(arg_or_group) {
                debug!("Validator::validate_required:iter: This is a group");
                if !self
                    .cmd
                    .unroll_args_in_group(&group.id)
                    .iter()
                    .any(|a| matcher.check_explicit(a, &ArgPredicate::IsPresent))
                {
                    debug!(
                        "Validator::validate_required:iter: Missing {:?}",
                        group.get_id()
                    );
                    missing_required.push(group.get_id().clone());
                }
            }
        }

        // Validate the conditionally required args
        for a in self
            .cmd
            .get_arguments()
            .filter(|a| !matcher.check_explicit(a.get_id(), &ArgPredicate::IsPresent))
        {
            let mut required = false;

            for (other, val) in &a.r_ifs {
                if matcher.check_explicit(other, &ArgPredicate::Equals(val.into())) {
                    debug!(
                        "Validator::validate_required:iter: Missing {:?}",
                        a.get_id()
                    );
                    required = true;
                }
            }

            let match_all = a.r_ifs_all.iter().all(|(other, val)| {
                matcher.check_explicit(other, &ArgPredicate::Equals(val.into()))
            });
            if match_all && !a.r_ifs_all.is_empty() {
                debug!(
                    "Validator::validate_required:iter: Missing {:?}",
                    a.get_id()
                );
                required = true;
            }

            if (!a.r_unless.is_empty() || !a.r_unless_all.is_empty())
                && self.fails_arg_required_unless(a, matcher)
            {
                debug!(
                    "Validator::validate_required:iter: Missing {:?}",
                    a.get_id()
                );
                required = true;
            }

            if required {
                missing_required.push(a.get_id().clone());
                if !a.is_last_set() {
                    highest_index = highest_index.max(a.get_index().unwrap_or(0));
                }
            }
        }

        // For display purposes, include all of the preceding positional arguments
        if !self.cmd.is_allow_missing_positional_set() {
            for pos in self
                .cmd
                .get_positionals()
                .filter(|a| !matcher.check_explicit(a.get_id(), &ArgPredicate::IsPresent))
            {
                if pos.get_index() < Some(highest_index) {
                    debug!(
                        "Validator::validate_required:iter: Missing {:?}",
                        pos.get_id()
                    );
                    missing_required.push(pos.get_id().clone());
                }
            }
        }

        if !missing_required.is_empty() {
            ok!(self.missing_required_error(matcher, missing_required));
        }

        Ok(())
    }
src/builder/debug_asserts.rs (line 31)
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
pub(crate) fn assert_app(cmd: &Command) {
    debug!("Command::_debug_asserts");

    let mut short_flags = vec![];
    let mut long_flags = vec![];

    // Invalid version flag settings
    if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
        // PropagateVersion is meaningless if there is no version
        assert!(
            !cmd.is_propagate_version_set(),
            "Command {}: No version information via Command::version or Command::long_version to propagate",
            cmd.get_name(),
        );

        // Used `Command::mut_arg("version", ..) but did not provide any version information to display
        let version_needed = cmd
            .get_arguments()
            .filter(|x| matches!(x.get_action(), ArgAction::Version))
            .map(|x| x.get_id())
            .collect::<Vec<_>>();

        assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
            ,cmd.get_name()
        );
    }

    for sc in cmd.get_subcommands() {
        if let Some(s) = sc.get_short_flag().as_ref() {
            short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
        }

        for short_alias in sc.get_all_short_flag_aliases() {
            short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
        }

        if let Some(l) = sc.get_long_flag().as_ref() {
            assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
            long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
        }

        for long_alias in sc.get_all_long_flag_aliases() {
            long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
        }
    }

    for arg in cmd.get_arguments() {
        assert_arg(arg);

        assert!(
            !cmd.is_multicall_set(),
            "Command {}: Arguments like {} cannot be set on a multicall command",
            cmd.get_name(),
            arg.get_id()
        );

        if let Some(s) = arg.get_short() {
            short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str()));
        }

        for (short_alias, _) in &arg.short_aliases {
            short_flags.push(Flag::Arg(
                format!("-{}", short_alias),
                arg.get_id().as_str(),
            ));
        }

        if let Some(l) = arg.get_long() {
            assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l);
            long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str()));
        }

        for (long_alias, _) in &arg.aliases {
            long_flags.push(Flag::Arg(
                format!("--{}", long_alias),
                arg.get_id().as_str(),
            ));
        }

        // Name conflicts
        if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
            panic!(
            "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
            cmd.get_name(),
            arg.get_id(),
            duplicate_tip(cmd, first, second),
        );
        }

        // Long conflicts
        if let Some(l) = arg.get_long() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) {
                panic!(
                    "Command {}: Long option names must be unique for each argument, \
                            but '--{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    l,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second)
                )
            }
        }

        // Short conflicts
        if let Some(s) = arg.get_short() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
                panic!(
                    "Command {}: Short option names must be unique for each argument, \
                            but '-{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    s,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second),
                )
            }
        }

        // Index conflicts
        if let Some(idx) = arg.index {
            if let Some((first, second)) =
                cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
            {
                panic!(
                    "Command {}: Argument '{}' has the same index as '{}' \
                    and they are both positional arguments\n\n\t \
                    Use `Arg::num_args(1..)` to allow one \
                    positional argument to take multiple values",
                    cmd.get_name(),
                    first.get_id(),
                    second.get_id()
                )
            }
        }

        // requires, r_if, r_unless
        for req in &arg.requires {
            assert!(
                cmd.id_exists(&req.1),
                "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
                cmd.get_name(),
                req.1,
                arg.get_id(),
            );
        }

        for req in &arg.r_ifs {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_ifs_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq_all`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_unless {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        for req in &arg.r_unless_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // blacklist
        for req in &arg.blacklist {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // overrides
        for req in &arg.overrides {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        if arg.is_last_set() {
            assert!(
                arg.get_long().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
            assert!(
                arg.get_short().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }

        assert!(
            !(arg.is_required_set() && arg.is_global_set()),
            "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
                    cmd.get_name(),
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_positional(),
                "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
                cmd.get_name(),
                arg.get_id()
            );

            assert!(
                arg.is_trailing_var_arg_set() || arg.is_last_set(),
                "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }
    }

    for group in cmd.get_groups() {
        let derive_hint = if cfg!(feature = "derive") {
            " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
        } else {
            ""
        };

        // Name conflicts
        assert!(
            cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
            "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        // Groups should not have naming conflicts with Args
        assert!(
            !cmd.get_arguments().any(|x| x.get_id() == group.get_id()),
            "Command {}: Argument group name '{}' must not conflict with argument name{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        for arg in &group.args {
            // Args listed inside groups should exist
            assert!(
                cmd.get_arguments().any(|x| x.get_id() == arg),
                "Command {}: Argument group '{}' contains non-existent argument '{}'",
                cmd.get_name(),
                group.get_id(),
                arg
            );
        }
    }

    // Conflicts between flags and subcommands

    long_flags.sort_unstable();
    short_flags.sort_unstable();

    detect_duplicate_flags(&long_flags, "long");
    detect_duplicate_flags(&short_flags, "short");

    let mut subs = FlatSet::new();
    for sc in cmd.get_subcommands() {
        assert!(
            subs.insert(sc.get_name()),
            "Command {}: command name `{}` is duplicated",
            cmd.get_name(),
            sc.get_name()
        );
        for alias in sc.get_all_aliases() {
            assert!(
                subs.insert(alias),
                "Command {}: command `{}` alias `{}` is duplicated",
                cmd.get_name(),
                sc.get_name(),
                alias
            );
        }
    }

    _verify_positionals(cmd);

    #[cfg(feature = "help")]
    if let Some(help_template) = cmd.get_help_template() {
        assert!(
            !help_template.to_string().contains("{flags}"),
            "Command {}: {}",
                    cmd.get_name(),
            "`{flags}` template variable was removed in clap3, they are now included in `{options}`",
        );
        assert!(
            !help_template.to_string().contains("{unified}"),
            "Command {}: {}",
            cmd.get_name(),
            "`{unified}` template variable was removed in clap3, use `{options}` instead"
        );
    }

    cmd._panic_on_missing_help(cmd.is_help_expected_set());
    assert_app_flags(cmd);
}

fn duplicate_tip(cmd: &Command, first: &Arg, second: &Arg) -> &'static str {
    if !cmd.is_disable_help_flag_set()
        && (first.get_id() == Id::HELP || second.get_id() == Id::HELP)
    {
        " (call `cmd.disable_help_flag(true)` to remove the auto-generated `--help`)"
    } else if !cmd.is_disable_version_flag_set()
        && (first.get_id() == Id::VERSION || second.get_id() == Id::VERSION)
    {
        " (call `cmd.disable_version_flag(true)` to remove the auto-generated `--version`)"
    } else {
        ""
    }
}

#[derive(Eq)]
enum Flag<'a> {
    Command(String, &'a str),
    Arg(String, &'a str),
}

impl PartialEq for Flag<'_> {
    fn eq(&self, other: &Flag) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl PartialOrd for Flag<'_> {
    fn partial_cmp(&self, other: &Flag) -> Option<Ordering> {
        use Flag::*;

        match (self, other) {
            (Command(s1, _), Command(s2, _))
            | (Arg(s1, _), Arg(s2, _))
            | (Command(s1, _), Arg(s2, _))
            | (Arg(s1, _), Command(s2, _)) => {
                if s1 == s2 {
                    Some(Ordering::Equal)
                } else {
                    s1.partial_cmp(s2)
                }
            }
        }
    }
}

impl Ord for Flag<'_> {
    fn cmp(&self, other: &Self) -> Ordering {
        self.partial_cmp(other).unwrap()
    }
}

fn detect_duplicate_flags(flags: &[Flag], short_or_long: &str) {
    use Flag::*;

    for (one, two) in find_duplicates(flags) {
        match (one, two) {
            (Command(flag, one), Command(_, another)) if one != another => panic!(
                "the '{}' {} flag is specified for both '{}' and '{}' subcommands",
                flag, short_or_long, one, another
            ),

            (Arg(flag, one), Arg(_, another)) if one != another => panic!(
                "{} option names must be unique, but '{}' is in use by both '{}' and '{}'",
                short_or_long, flag, one, another
            ),

            (Arg(flag, arg), Command(_, sub)) | (Command(flag, sub), Arg(_, arg)) => panic!(
                "the '{}' {} flag for the '{}' argument conflicts with the short flag \
                     for '{}' subcommand",
                flag, short_or_long, arg, sub
            ),

            _ => {}
        }
    }
}

/// Find duplicates in a sorted array.
///
/// The algorithm is simple: the array is sorted, duplicates
/// must be placed next to each other, we can check only adjacent elements.
fn find_duplicates<T: PartialEq>(slice: &[T]) -> impl Iterator<Item = (&T, &T)> {
    slice.windows(2).filter_map(|w| {
        if w[0] == w[1] {
            Some((&w[0], &w[1]))
        } else {
            None
        }
    })
}

fn assert_app_flags(cmd: &Command) {
    macro_rules! checker {
        ($a:ident requires $($b:ident)|+) => {
            if cmd.$a() {
                let mut s = String::new();

                $(
                    if !cmd.$b() {
                        use std::fmt::Write;
                        write!(&mut s, "  AppSettings::{} is required when AppSettings::{} is set.\n", std::stringify!($b), std::stringify!($a)).unwrap();
                    }
                )+

                if !s.is_empty() {
                    panic!("{}", s)
                }
            }
        };
        ($a:ident conflicts $($b:ident)|+) => {
            if cmd.$a() {
                let mut s = String::new();

                $(
                    if cmd.$b() {
                        use std::fmt::Write;
                        write!(&mut s, "  AppSettings::{} conflicts with AppSettings::{}.\n", std::stringify!($b), std::stringify!($a)).unwrap();
                    }
                )+

                if !s.is_empty() {
                    panic!("{}\n{}", cmd.get_name(), s)
                }
            }
        };
    }

    checker!(is_multicall_set conflicts is_no_binary_name_set);
}

#[cfg(debug_assertions)]
fn _verify_positionals(cmd: &Command) -> bool {
    debug!("Command::_verify_positionals");
    // Because you must wait until all arguments have been supplied, this is the first chance
    // to make assertions on positional argument indexes
    //
    // First we verify that the index highest supplied index, is equal to the number of
    // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3
    // but no 2)

    let highest_idx = cmd
        .get_keymap()
        .keys()
        .filter_map(|x| {
            if let KeyType::Position(n) = x {
                Some(*n)
            } else {
                None
            }
        })
        .max()
        .unwrap_or(0);

    let num_p = cmd.get_keymap().keys().filter(|x| x.is_position()).count();

    assert!(
        highest_idx == num_p,
        "Found positional argument whose index is {} but there \
             are only {} positional arguments defined",
        highest_idx,
        num_p
    );

    for arg in cmd.get_arguments() {
        if arg.index.unwrap_or(0) == highest_idx {
            assert!(
                !arg.is_trailing_var_arg_set() || !arg.is_last_set(),
                "{}:{}: `Arg::trailing_var_arg` and `Arg::last` cannot be used together",
                cmd.get_name(),
                arg.get_id()
            );

            if arg.is_trailing_var_arg_set() {
                assert!(
                    arg.is_multiple(),
                    "{}:{}: `Arg::trailing_var_arg` must accept multiple values",
                    cmd.get_name(),
                    arg.get_id()
                );
            }
        } else {
            assert!(
                !arg.is_trailing_var_arg_set(),
                "{}:{}: `Arg::trailing_var_arg` can only apply to last positional",
                cmd.get_name(),
                arg.get_id()
            );
        }
    }

    // Next we verify that only the highest index has takes multiple arguments (if any)
    let only_highest = |a: &Arg| a.is_multiple() && (a.get_index().unwrap_or(0) != highest_idx);
    if cmd.get_positionals().any(only_highest) {
        // First we make sure if there is a positional that allows multiple values
        // the one before it (second to last) has one of these:
        //  * a value terminator
        //  * ArgSettings::Last
        //  * The last arg is Required

        // We can't pass the closure (it.next()) to the macro directly because each call to
        // find() (iterator, not macro) gets called repeatedly.
        let last = &cmd.get_keymap()[&KeyType::Position(highest_idx)];
        let second_to_last = &cmd.get_keymap()[&KeyType::Position(highest_idx - 1)];

        // Either the final positional is required
        // Or the second to last has a terminator or .last(true) set
        let ok = last.is_required_set()
            || (second_to_last.terminator.is_some() || second_to_last.is_last_set())
            || last.is_last_set();
        assert!(
            ok,
            "When using a positional argument with `.num_args(1..)` that is *not the \
                 last* positional argument, the last positional argument (i.e. the one \
                 with the highest index) *must* have .required(true) or .last(true) set."
        );

        // We make sure if the second to last is Multiple the last is ArgSettings::Last
        let ok = second_to_last.is_multiple() || last.is_last_set();
        assert!(
            ok,
            "Only the last positional argument, or second to last positional \
                 argument may be set to `.num_args(1..)`"
        );

        // Next we check how many have both Multiple and not a specific number of values set
        let count = cmd
            .get_positionals()
            .filter(|p| {
                p.is_multiple_values_set()
                    && !p.get_num_args().expect(INTERNAL_ERROR_MSG).is_fixed()
            })
            .count();
        let ok = count <= 1
            || (last.is_last_set()
                && last.is_multiple()
                && second_to_last.is_multiple()
                && count == 2);
        assert!(
            ok,
            "Only one positional argument with `.num_args(1..)` set is allowed per \
                 command, unless the second one also has .last(true) set"
        );
    }

    let mut found = false;

    if cmd.is_allow_missing_positional_set() {
        // Check that if a required positional argument is found, all positions with a lower
        // index are also required.
        let mut foundx2 = false;

        for p in cmd.get_positionals() {
            if foundx2 && !p.is_required_set() {
                assert!(
                    p.is_required_set(),
                    "Found non-required positional argument with a lower \
                         index than a required positional argument by two or more: {:?} \
                         index {:?}",
                    p.get_id(),
                    p.get_index()
                );
            } else if p.is_required_set() && !p.is_last_set() {
                // Args that .last(true) don't count since they can be required and have
                // positionals with a lower index that aren't required
                // Imagine: prog <req1> [opt1] -- <req2>
                // Both of these are valid invocations:
                //      $ prog r1 -- r2
                //      $ prog r1 o1 -- r2
                if found {
                    foundx2 = true;
                    continue;
                }
                found = true;
                continue;
            } else {
                found = false;
            }
        }
    } else {
        // Check that if a required positional argument is found, all positions with a lower
        // index are also required
        for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) {
            if found {
                assert!(
                    p.is_required_set(),
                    "Found non-required positional argument with a lower \
                         index than a required positional argument: {:?} index {:?}",
                    p.get_id(),
                    p.get_index()
                );
            } else if p.is_required_set() && !p.is_last_set() {
                // Args that .last(true) don't count since they can be required and have
                // positionals with a lower index that aren't required
                // Imagine: prog <req1> [opt1] -- <req2>
                // Both of these are valid invocations:
                //      $ prog r1 -- r2
                //      $ prog r1 o1 -- r2
                found = true;
                continue;
            }
        }
    }
    assert!(
        cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2,
        "Only one positional argument may have last(true) set. Found two."
    );
    if cmd
        .get_positionals()
        .any(|p| p.is_last_set() && p.is_required_set())
        && cmd.has_subcommands()
        && !cmd.is_subcommand_negates_reqs_set()
    {
        panic!(
            "Having a required positional argument with .last(true) set *and* child \
                 subcommands without setting SubcommandsNegateReqs isn't compatible."
        );
    }

    true
}
src/parser/parser.rs (line 78)
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
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
    pub(crate) fn get_matches_with(
        &mut self,
        matcher: &mut ArgMatcher,
        raw_args: &mut clap_lex::RawArgs,
        mut args_cursor: clap_lex::ArgCursor,
    ) -> ClapResult<()> {
        debug!("Parser::get_matches_with");
        // Verify all positional assertions pass

        let mut subcmd_name: Option<String> = None;
        let mut keep_state = false;
        let mut parse_state = ParseState::ValuesDone;
        let mut pos_counter = 1;

        // Already met any valid arg(then we shouldn't expect subcommands after it).
        let mut valid_arg_found = false;
        // If the user already passed '--'. Meaning only positional args follow.
        let mut trailing_values = false;

        // Count of positional args
        let positional_count = self
            .cmd
            .get_keymap()
            .keys()
            .filter(|x| x.is_position())
            .count();
        // If any arg sets .last(true)
        let contains_last = self.cmd.get_arguments().any(|x| x.is_last_set());

        while let Some(arg_os) = raw_args.next(&mut args_cursor) {
            // Recover the replaced items if any.
            if let Some(replaced_items) = arg_os
                .to_value()
                .ok()
                .and_then(|a| self.cmd.get_replacement(a))
            {
                debug!(
                    "Parser::get_matches_with: found replacer: {:?}, target: {:?}",
                    arg_os, replaced_items
                );
                raw_args.insert(&args_cursor, replaced_items);
                continue;
            }

            debug!(
                "Parser::get_matches_with: Begin parsing '{:?}' ({:?})",
                arg_os.to_value_os(),
                arg_os.to_value_os().as_raw_bytes()
            );

            // Has the user already passed '--'? Meaning only positional args follow
            if !trailing_values {
                if self.cmd.is_subcommand_precedence_over_arg_set()
                    || !matches!(parse_state, ParseState::Opt(_) | ParseState::Pos(_))
                {
                    // Does the arg match a subcommand name, or any of its aliases (if defined)
                    let sc_name = self.possible_subcommand(arg_os.to_value(), valid_arg_found);
                    debug!("Parser::get_matches_with: sc={:?}", sc_name);
                    if let Some(sc_name) = sc_name {
                        if sc_name == "help" && !self.cmd.is_disable_help_subcommand_set() {
                            ok!(self.parse_help_subcommand(raw_args.remaining(&mut args_cursor)));
                            unreachable!("`parse_help_subcommand` always errors");
                        } else {
                            subcmd_name = Some(sc_name.to_owned());
                        }
                        break;
                    }
                }

                if arg_os.is_escape() {
                    if matches!(&parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if
                        self.cmd[opt].is_allow_hyphen_values_set())
                    {
                        // ParseResult::MaybeHyphenValue, do nothing
                    } else {
                        debug!("Parser::get_matches_with: setting TrailingVals=true");
                        trailing_values = true;
                        matcher.start_trailing();
                        continue;
                    }
                } else if let Some((long_arg, long_value)) = arg_os.to_long() {
                    let parse_result = ok!(self.parse_long_arg(
                        matcher,
                        long_arg,
                        long_value,
                        &parse_state,
                        pos_counter,
                        &mut valid_arg_found,
                    ));
                    debug!(
                        "Parser::get_matches_with: After parse_long_arg {:?}",
                        parse_result
                    );
                    match parse_result {
                        ParseResult::NoArg => {
                            unreachable!("`to_long` always has the flag specified")
                        }
                        ParseResult::ValuesDone => {
                            parse_state = ParseState::ValuesDone;
                            continue;
                        }
                        ParseResult::Opt(id) => {
                            parse_state = ParseState::Opt(id);
                            continue;
                        }
                        ParseResult::FlagSubCommand(name) => {
                            debug!(
                                "Parser::get_matches_with: FlagSubCommand found in long arg {:?}",
                                &name
                            );
                            subcmd_name = Some(name);
                            break;
                        }
                        ParseResult::EqualsNotProvided { arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::no_equals(
                                self.cmd,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::NoMatchingArg { arg } => {
                            let _ = self.resolve_pending(matcher);
                            let remaining_args: Vec<_> =
                                raw_args.remaining(&mut args_cursor).collect();
                            return Err(self.did_you_mean_error(
                                &arg,
                                matcher,
                                &remaining_args,
                                trailing_values,
                            ));
                        }
                        ParseResult::UnneededAttachedValue { rest, used, arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::too_many_values(
                                self.cmd,
                                rest,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&used),
                            ));
                        }
                        ParseResult::MaybeHyphenValue => {
                            // Maybe a hyphen value, do nothing.
                        }
                        ParseResult::AttachedValueNotConsumed => {
                            unreachable!()
                        }
                    }
                } else if let Some(short_arg) = arg_os.to_short() {
                    // Arg looks like a short flag, and not a possible number

                    // Try to parse short args like normal, if allow_hyphen_values or
                    // AllowNegativeNumbers is set, parse_short_arg will *not* throw
                    // an error, and instead return Ok(None)
                    let parse_result = ok!(self.parse_short_arg(
                        matcher,
                        short_arg,
                        &parse_state,
                        pos_counter,
                        &mut valid_arg_found,
                    ));
                    // If it's None, we then check if one of those two AppSettings was set
                    debug!(
                        "Parser::get_matches_with: After parse_short_arg {:?}",
                        parse_result
                    );
                    match parse_result {
                        ParseResult::NoArg => {
                            // Is a single dash `-`, try positional.
                        }
                        ParseResult::ValuesDone => {
                            parse_state = ParseState::ValuesDone;
                            continue;
                        }
                        ParseResult::Opt(id) => {
                            parse_state = ParseState::Opt(id);
                            continue;
                        }
                        ParseResult::FlagSubCommand(name) => {
                            // If there are more short flags to be processed, we should keep the state, and later
                            // revisit the current group of short flags skipping the subcommand.
                            keep_state = self
                                .flag_subcmd_at
                                .map(|at| {
                                    raw_args
                                        .seek(&mut args_cursor, clap_lex::SeekFrom::Current(-1));
                                    // Since we are now saving the current state, the number of flags to skip during state recovery should
                                    // be the current index (`cur_idx`) minus ONE UNIT TO THE LEFT of the starting position.
                                    self.flag_subcmd_skip = self.cur_idx.get() - at + 1;
                                })
                                .is_some();

                            debug!(
                                "Parser::get_matches_with:FlagSubCommandShort: subcmd_name={}, keep_state={}, flag_subcmd_skip={}",
                                name,
                                keep_state,
                                self.flag_subcmd_skip
                            );

                            subcmd_name = Some(name);
                            break;
                        }
                        ParseResult::EqualsNotProvided { arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::no_equals(
                                self.cmd,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::NoMatchingArg { arg } => {
                            let _ = self.resolve_pending(matcher);
                            // We already know it looks like a flag
                            let suggested_trailing_arg =
                                !trailing_values && self.cmd.has_positionals();
                            return Err(ClapError::unknown_argument(
                                self.cmd,
                                arg,
                                None,
                                suggested_trailing_arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::MaybeHyphenValue => {
                            // Maybe a hyphen value, do nothing.
                        }
                        ParseResult::UnneededAttachedValue { .. }
                        | ParseResult::AttachedValueNotConsumed => unreachable!(),
                    }
                }

                if let ParseState::Opt(id) = &parse_state {
                    // Assume this is a value of a previous arg.

                    // get the option so we can check the settings
                    let arg = &self.cmd[id];
                    let parse_result = if let Some(parse_result) =
                        self.check_terminator(arg, arg_os.to_value_os())
                    {
                        parse_result
                    } else {
                        let trailing_values = false;
                        let arg_values = matcher.pending_values_mut(id, None, trailing_values);
                        arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
                        if matcher.needs_more_vals(arg) {
                            ParseResult::Opt(arg.get_id().clone())
                        } else {
                            ParseResult::ValuesDone
                        }
                    };
                    parse_state = match parse_result {
                        ParseResult::Opt(id) => ParseState::Opt(id),
                        ParseResult::ValuesDone => ParseState::ValuesDone,
                        _ => unreachable!(),
                    };
                    // get the next value from the iterator
                    continue;
                }
            }

            // Correct pos_counter.
            pos_counter = {
                let is_second_to_last = pos_counter + 1 == positional_count;

                // The last positional argument, or second to last positional
                // argument may be set to .multiple_values(true) or `.multiple_occurrences(true)`
                let low_index_mults = is_second_to_last
                    && self.cmd.get_positionals().any(|a| {
                        a.is_multiple() && (positional_count != a.get_index().unwrap_or(0))
                    })
                    && self
                        .cmd
                        .get_positionals()
                        .last()
                        .map_or(false, |p_name| !p_name.is_last_set());

                let missing_pos = self.cmd.is_allow_missing_positional_set()
                    && is_second_to_last
                    && !trailing_values;

                debug!(
                    "Parser::get_matches_with: Positional counter...{}",
                    pos_counter
                );
                debug!(
                    "Parser::get_matches_with: Low index multiples...{:?}",
                    low_index_mults
                );

                if low_index_mults || missing_pos {
                    let skip_current = if let Some(n) = raw_args.peek(&args_cursor) {
                        if let Some(arg) = self
                            .cmd
                            .get_positionals()
                            .find(|a| a.get_index() == Some(pos_counter))
                        {
                            // If next value looks like a new_arg or it's a
                            // subcommand, skip positional argument under current
                            // pos_counter(which means current value cannot be a
                            // positional argument with a value next to it), assume
                            // current value matches the next arg.
                            self.is_new_arg(&n, arg)
                                || self
                                    .possible_subcommand(n.to_value(), valid_arg_found)
                                    .is_some()
                        } else {
                            true
                        }
                    } else {
                        true
                    };

                    if skip_current {
                        debug!("Parser::get_matches_with: Bumping the positional counter...");
                        pos_counter + 1
                    } else {
                        pos_counter
                    }
                } else if trailing_values
                    && (self.cmd.is_allow_missing_positional_set() || contains_last)
                {
                    // Came to -- and one positional has .last(true) set, so we go immediately
                    // to the last (highest index) positional
                    debug!("Parser::get_matches_with: .last(true) and --, setting last pos");
                    positional_count
                } else {
                    pos_counter
                }
            };

            if let Some(arg) = self.cmd.get_keymap().get(&pos_counter) {
                if arg.is_last_set() && !trailing_values {
                    let _ = self.resolve_pending(matcher);
                    // Its already considered a positional, we don't need to suggest turning it
                    // into one
                    let suggested_trailing_arg = false;
                    return Err(ClapError::unknown_argument(
                        self.cmd,
                        arg_os.display().to_string(),
                        None,
                        suggested_trailing_arg,
                        Usage::new(self.cmd).create_usage_with_title(&[]),
                    ));
                }

                if arg.is_trailing_var_arg_set() {
                    trailing_values = true;
                }

                if matcher.pending_arg_id() != Some(arg.get_id()) || !arg.is_multiple_values_set() {
                    ok!(self.resolve_pending(matcher));
                }
                if let Some(_parse_result) = self.check_terminator(arg, arg_os.to_value_os()) {
                    debug!(
                        "Parser::get_matches_with: ignoring terminator result {:?}",
                        _parse_result
                    );
                } else {
                    let arg_values = matcher.pending_values_mut(
                        arg.get_id(),
                        Some(Identifier::Index),
                        trailing_values,
                    );
                    arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
                }

                // Only increment the positional counter if it doesn't allow multiples
                if !arg.is_multiple() {
                    pos_counter += 1;
                    parse_state = ParseState::ValuesDone;
                } else {
                    parse_state = ParseState::Pos(arg.get_id().clone());
                }
                valid_arg_found = true;
            } else if let Some(external_parser) =
                self.cmd.get_external_subcommand_value_parser().cloned()
            {
                // Get external subcommand name
                let sc_name = match arg_os.to_value() {
                    Ok(s) => s.to_owned(),
                    Err(_) => {
                        let _ = self.resolve_pending(matcher);
                        return Err(ClapError::invalid_utf8(
                            self.cmd,
                            Usage::new(self.cmd).create_usage_with_title(&[]),
                        ));
                    }
                };

                // Collect the external subcommand args
                let mut sc_m = ArgMatcher::new(self.cmd);
                sc_m.start_occurrence_of_external(self.cmd);

                for raw_val in raw_args.remaining(&mut args_cursor) {
                    let val = ok!(external_parser.parse_ref(self.cmd, None, raw_val));
                    let external_id = Id::from_static_ref(Id::EXTERNAL);
                    sc_m.add_val_to(&external_id, val, raw_val.to_os_string());
                }

                matcher.subcommand(SubCommand {
                    name: sc_name,
                    matches: sc_m.into_inner(),
                });

                ok!(self.resolve_pending(matcher));
                #[cfg(feature = "env")]
                ok!(self.add_env(matcher));
                ok!(self.add_defaults(matcher));
                return Validator::new(self.cmd).validate(parse_state, matcher);
            } else {
                // Start error processing
                let _ = self.resolve_pending(matcher);
                return Err(self.match_arg_error(&arg_os, valid_arg_found, trailing_values));
            }
        }

        if let Some(ref pos_sc_name) = subcmd_name {
            let sc_name = self
                .cmd
                .find_subcommand(pos_sc_name)
                .expect(INTERNAL_ERROR_MSG)
                .get_name()
                .to_owned();
            ok!(self.parse_subcommand(&sc_name, matcher, raw_args, args_cursor, keep_state));
        }

        ok!(self.resolve_pending(matcher));
        #[cfg(feature = "env")]
        ok!(self.add_env(matcher));
        ok!(self.add_defaults(matcher));
        Validator::new(self.cmd).validate(parse_state, matcher)
    }

    fn match_arg_error(
        &self,
        arg_os: &clap_lex::ParsedArg<'_>,
        valid_arg_found: bool,
        trailing_values: bool,
    ) -> ClapError {
        // If argument follows a `--`
        if trailing_values {
            // If the arg matches a subcommand name, or any of its aliases (if defined)
            if self
                .possible_subcommand(arg_os.to_value(), valid_arg_found)
                .is_some()
            {
                return ClapError::unnecessary_double_dash(
                    self.cmd,
                    arg_os.display().to_string(),
                    Usage::new(self.cmd).create_usage_with_title(&[]),
                );
            }
        }

        let candidates = suggestions::did_you_mean(
            &arg_os.display().to_string(),
            self.cmd.all_subcommand_names(),
        );
        // If the argument looks like a subcommand.
        if !candidates.is_empty() {
            return ClapError::invalid_subcommand(
                self.cmd,
                arg_os.display().to_string(),
                candidates,
                self.cmd
                    .get_bin_name()
                    .unwrap_or_else(|| self.cmd.get_name())
                    .to_owned(),
                Usage::new(self.cmd).create_usage_with_title(&[]),
            );
        }

        // If the argument must be a subcommand.
        if self.cmd.has_subcommands()
            && (!self.cmd.has_positionals() || self.cmd.is_infer_subcommands_set())
        {
            return ClapError::unrecognized_subcommand(
                self.cmd,
                arg_os.display().to_string(),
                Usage::new(self.cmd).create_usage_with_title(&[]),
            );
        }

        let suggested_trailing_arg = !trailing_values
            && self.cmd.has_positionals()
            && (arg_os.is_long() || arg_os.is_short());
        ClapError::unknown_argument(
            self.cmd,
            arg_os.display().to_string(),
            None,
            suggested_trailing_arg,
            Usage::new(self.cmd).create_usage_with_title(&[]),
        )
    }

    // Checks if the arg matches a subcommand name, or any of its aliases (if defined)
    fn possible_subcommand(
        &self,
        arg: Result<&str, &RawOsStr>,
        valid_arg_found: bool,
    ) -> Option<&str> {
        debug!("Parser::possible_subcommand: arg={:?}", arg);
        let arg = some!(arg.ok());

        if !(self.cmd.is_args_conflicts_with_subcommands_set() && valid_arg_found) {
            if self.cmd.is_infer_subcommands_set() {
                // For subcommand `test`, we accepts it's prefix: `t`, `te`,
                // `tes` and `test`.
                let v = self
                    .cmd
                    .all_subcommand_names()
                    .filter(|s| s.starts_with(arg))
                    .collect::<Vec<_>>();

                if v.len() == 1 {
                    return Some(v[0]);
                }

                // If there is any ambiguity, fallback to non-infer subcommand
                // search.
            }
            if let Some(sc) = self.cmd.find_subcommand(arg) {
                return Some(sc.get_name());
            }
        }
        None
    }

    // Checks if the arg matches a long flag subcommand name, or any of its aliases (if defined)
    fn possible_long_flag_subcommand(&self, arg: &str) -> Option<&str> {
        debug!("Parser::possible_long_flag_subcommand: arg={:?}", arg);
        if self.cmd.is_infer_subcommands_set() {
            let options = self
                .cmd
                .get_subcommands()
                .fold(Vec::new(), |mut options, sc| {
                    if let Some(long) = sc.get_long_flag() {
                        if long.starts_with(arg) {
                            options.push(long);
                        }
                        options.extend(sc.get_all_aliases().filter(|alias| alias.starts_with(arg)))
                    }
                    options
                });
            if options.len() == 1 {
                return Some(options[0]);
            }

            for sc in options {
                if sc == arg {
                    return Some(sc);
                }
            }
        } else if let Some(sc_name) = self.cmd.find_long_subcmd(arg) {
            return Some(sc_name);
        }
        None
    }

    fn parse_help_subcommand(
        &self,
        cmds: impl Iterator<Item = &'cmd OsStr>,
    ) -> ClapResult<std::convert::Infallible> {
        debug!("Parser::parse_help_subcommand");

        let mut cmd = self.cmd.clone();
        let sc = {
            let mut sc = &mut cmd;

            for cmd in cmds {
                sc = if let Some(sc_name) =
                    sc.find_subcommand(cmd).map(|sc| sc.get_name().to_owned())
                {
                    sc._build_subcommand(&sc_name).unwrap()
                } else {
                    return Err(ClapError::unrecognized_subcommand(
                        sc,
                        cmd.to_string_lossy().into_owned(),
                        Usage::new(sc).create_usage_with_title(&[]),
                    ));
                };
            }

            sc
        };
        let parser = Parser::new(sc);

        Err(parser.help_err(true))
    }

    fn is_new_arg(&self, next: &clap_lex::ParsedArg<'_>, current_positional: &Arg) -> bool {
        #![allow(clippy::needless_bool)] // Prefer consistent if/else-if ladder

        debug!(
            "Parser::is_new_arg: {:?}:{}",
            next.to_value_os(),
            current_positional.get_id()
        );

        if self.cmd[current_positional.get_id()].is_allow_hyphen_values_set()
            || (self.cmd[current_positional.get_id()].is_allow_negative_numbers_set()
                && next.is_number())
        {
            // If allow hyphen, this isn't a new arg.
            debug!("Parser::is_new_arg: Allow hyphen");
            false
        } else if next.is_long() {
            // If this is a long flag, this is a new arg.
            debug!("Parser::is_new_arg: --<something> found");
            true
        } else if next.is_short() {
            // If this is a short flag, this is a new arg. But a singe '-' by
            // itself is a value and typically means "stdin" on unix systems.
            debug!("Parser::is_new_arg: -<something> found");
            true
        } else {
            // Nothing special, this is a value.
            debug!("Parser::is_new_arg: value");
            false
        }
    }

    fn parse_subcommand(
        &mut self,
        sc_name: &str,
        matcher: &mut ArgMatcher,
        raw_args: &mut clap_lex::RawArgs,
        args_cursor: clap_lex::ArgCursor,
        keep_state: bool,
    ) -> ClapResult<()> {
        debug!("Parser::parse_subcommand");

        let partial_parsing_enabled = self.cmd.is_ignore_errors_set();

        if let Some(sc) = self.cmd._build_subcommand(sc_name) {
            let mut sc_matcher = ArgMatcher::new(sc);

            debug!(
                "Parser::parse_subcommand: About to parse sc={}",
                sc.get_name()
            );

            {
                let mut p = Parser::new(sc);
                // HACK: maintain indexes between parsers
                // FlagSubCommand short arg needs to revisit the current short args, but skip the subcommand itself
                if keep_state {
                    p.cur_idx.set(self.cur_idx.get());
                    p.flag_subcmd_at = self.flag_subcmd_at;
                    p.flag_subcmd_skip = self.flag_subcmd_skip;
                }
                if let Err(error) = p.get_matches_with(&mut sc_matcher, raw_args, args_cursor) {
                    if partial_parsing_enabled {
                        debug!(
                            "Parser::parse_subcommand: ignored error in subcommand {}: {:?}",
                            sc_name, error
                        );
                    } else {
                        return Err(error);
                    }
                }
            }
            matcher.subcommand(SubCommand {
                name: sc.get_name().to_owned(),
                matches: sc_matcher.into_inner(),
            });
        }
        Ok(())
    }

    fn parse_long_arg(
        &mut self,
        matcher: &mut ArgMatcher,
        long_arg: Result<&str, &RawOsStr>,
        long_value: Option<&RawOsStr>,
        parse_state: &ParseState,
        pos_counter: usize,
        valid_arg_found: &mut bool,
    ) -> ClapResult<ParseResult> {
        // maybe here lifetime should be 'a
        debug!("Parser::parse_long_arg");

        #[allow(clippy::blocks_in_if_conditions)]
        if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if
            self.cmd[opt].is_allow_hyphen_values_set())
        {
            debug!("Parser::parse_long_arg: prior arg accepts hyphenated values",);
            return Ok(ParseResult::MaybeHyphenValue);
        }

        debug!("Parser::parse_long_arg: Does it contain '='...");
        let long_arg = match long_arg {
            Ok(long_arg) => long_arg,
            Err(long_arg) => {
                return Ok(ParseResult::NoMatchingArg {
                    arg: long_arg.to_str_lossy().into_owned(),
                });
            }
        };
        if long_arg.is_empty() {
            debug_assert!(
                long_value.is_some(),
                "`--` should be filtered out before this point"
            );
        }

        let arg = if let Some(arg) = self.cmd.get_keymap().get(long_arg) {
            debug!("Parser::parse_long_arg: Found valid arg or flag '{}'", arg);
            Some((long_arg, arg))
        } else if self.cmd.is_infer_long_args_set() {
            self.cmd.get_arguments().find_map(|a| {
                if let Some(long) = a.get_long() {
                    if long.starts_with(long_arg) {
                        return Some((long, a));
                    }
                }
                a.aliases
                    .iter()
                    .find_map(|(alias, _)| alias.starts_with(long_arg).then(|| (alias.as_str(), a)))
            })
        } else {
            None
        };

        if let Some((_long_arg, arg)) = arg {
            let ident = Identifier::Long;
            *valid_arg_found = true;
            if arg.is_takes_value_set() {
                debug!(
                    "Parser::parse_long_arg({:?}): Found an arg with value '{:?}'",
                    long_arg, &long_value
                );
                let has_eq = long_value.is_some();
                self.parse_opt_value(ident, long_value, arg, matcher, has_eq)
            } else if let Some(rest) = long_value {
                let required = self.cmd.required_graph();
                debug!(
                    "Parser::parse_long_arg({:?}): Got invalid literal `{:?}`",
                    long_arg, rest
                );
                let mut used: Vec<Id> = matcher
                    .arg_ids()
                    .filter(|arg_id| {
                        matcher.check_explicit(arg_id, &crate::builder::ArgPredicate::IsPresent)
                    })
                    .filter(|&n| {
                        self.cmd.find(n).map_or(true, |a| {
                            !(a.is_hide_set() || required.contains(a.get_id()))
                        })
                    })
                    .cloned()
                    .collect();
                used.push(arg.get_id().clone());

                Ok(ParseResult::UnneededAttachedValue {
                    rest: rest.to_str_lossy().into_owned(),
                    used,
                    arg: arg.to_string(),
                })
            } else {
                debug!("Parser::parse_long_arg({:?}): Presence validated", long_arg);
                let trailing_idx = None;
                self.react(
                    Some(ident),
                    ValueSource::CommandLine,
                    arg,
                    vec![],
                    trailing_idx,
                    matcher,
                )
            }
        } else if let Some(sc_name) = self.possible_long_flag_subcommand(long_arg) {
            Ok(ParseResult::FlagSubCommand(sc_name.to_string()))
        } else if self
            .cmd
            .get_keymap()
            .get(&pos_counter)
            .map_or(false, |arg| {
                arg.is_allow_hyphen_values_set() && !arg.is_last_set()
            })
        {
            debug!(
                "Parser::parse_long_args: positional at {} allows hyphens",
                pos_counter
            );
            Ok(ParseResult::MaybeHyphenValue)
        } else {
            Ok(ParseResult::NoMatchingArg {
                arg: long_arg.to_owned(),
            })
        }
    }

    fn parse_short_arg(
        &mut self,
        matcher: &mut ArgMatcher,
        mut short_arg: clap_lex::ShortFlags<'_>,
        parse_state: &ParseState,
        // change this to possible pos_arg when removing the usage of &mut Parser.
        pos_counter: usize,
        valid_arg_found: &mut bool,
    ) -> ClapResult<ParseResult> {
        debug!("Parser::parse_short_arg: short_arg={:?}", short_arg);

        #[allow(clippy::blocks_in_if_conditions)]
        if matches!(parse_state, ParseState::Opt(opt) | ParseState::Pos(opt)
                if self.cmd[opt].is_allow_hyphen_values_set() || (self.cmd[opt].is_allow_negative_numbers_set() && short_arg.is_number()))
        {
            debug!("Parser::parse_short_args: prior arg accepts hyphenated values",);
            return Ok(ParseResult::MaybeHyphenValue);
        } else if self
            .cmd
            .get_keymap()
            .get(&pos_counter)
            .map_or(false, |arg| arg.is_allow_negative_numbers_set())
            && short_arg.is_number()
        {
            debug!("Parser::parse_short_arg: negative number");
            return Ok(ParseResult::MaybeHyphenValue);
        } else if self
            .cmd
            .get_keymap()
            .get(&pos_counter)
            .map_or(false, |arg| {
                arg.is_allow_hyphen_values_set() && !arg.is_last_set()
            })
            && short_arg
                .clone()
                .any(|c| !c.map(|c| self.cmd.contains_short(c)).unwrap_or_default())
        {
            debug!(
                "Parser::parse_short_args: positional at {} allows hyphens",
                pos_counter
            );
            return Ok(ParseResult::MaybeHyphenValue);
        }

        let mut ret = ParseResult::NoArg;

        let skip = self.flag_subcmd_skip;
        self.flag_subcmd_skip = 0;
        let res = short_arg.advance_by(skip);
        debug_assert_eq!(
            res,
            Ok(()),
            "tracking of `flag_subcmd_skip` is off for `{:?}`",
            short_arg
        );
        while let Some(c) = short_arg.next_flag() {
            let c = match c {
                Ok(c) => c,
                Err(rest) => {
                    return Ok(ParseResult::NoMatchingArg {
                        arg: format!("-{}", rest.to_str_lossy()),
                    });
                }
            };
            debug!("Parser::parse_short_arg:iter:{}", c);

            // Check for matching short options, and return the name if there is no trailing
            // concatenated value: -oval
            // Option: -o
            // Value: val
            if let Some(arg) = self.cmd.get_keymap().get(&c) {
                let ident = Identifier::Short;
                debug!(
                    "Parser::parse_short_arg:iter:{}: Found valid opt or flag",
                    c
                );
                *valid_arg_found = true;
                if !arg.is_takes_value_set() {
                    let arg_values = Vec::new();
                    let trailing_idx = None;
                    ret = ok!(self.react(
                        Some(ident),
                        ValueSource::CommandLine,
                        arg,
                        arg_values,
                        trailing_idx,
                        matcher,
                    ));
                    continue;
                }

                // Check for trailing concatenated value
                //
                // Cloning the iterator, so we rollback if it isn't there.
                let val = short_arg.clone().next_value_os().unwrap_or_default();
                debug!(
                    "Parser::parse_short_arg:iter:{}: val={:?} (bytes), val={:?} (ascii), short_arg={:?}",
                    c, val, val.as_raw_bytes(), short_arg
                );
                let val = Some(val).filter(|v| !v.is_empty());

                // Default to "we're expecting a value later".
                //
                // If attached value is not consumed, we may have more short
                // flags to parse, continue.
                //
                // e.g. `-xvf`, when require_equals && x.min_vals == 0, we don't
                // consume the `vf`, even if it's provided as value.
                let (val, has_eq) = if let Some(val) = val.and_then(|v| v.strip_prefix('=')) {
                    (Some(val), true)
                } else {
                    (val, false)
                };
                match ok!(self.parse_opt_value(ident, val, arg, matcher, has_eq)) {
                    ParseResult::AttachedValueNotConsumed => continue,
                    x => return Ok(x),
                }
            }

            return if let Some(sc_name) = self.cmd.find_short_subcmd(c) {
                debug!("Parser::parse_short_arg:iter:{}: subcommand={}", c, sc_name);
                // Make sure indices get updated before reading `self.cur_idx`
                ok!(self.resolve_pending(matcher));
                self.cur_idx.set(self.cur_idx.get() + 1);
                debug!("Parser::parse_short_arg: cur_idx:={}", self.cur_idx.get());

                let name = sc_name.to_string();
                // Get the index of the previously saved flag subcommand in the group of flags (if exists).
                // If it is a new flag subcommand, then the formentioned index should be the current one
                // (ie. `cur_idx`), and should be registered.
                let cur_idx = self.cur_idx.get();
                self.flag_subcmd_at.get_or_insert(cur_idx);
                let done_short_args = short_arg.is_empty();
                if done_short_args {
                    self.flag_subcmd_at = None;
                }
                Ok(ParseResult::FlagSubCommand(name))
            } else {
                Ok(ParseResult::NoMatchingArg {
                    arg: format!("-{}", c),
                })
            };
        }
        Ok(ret)
    }

    fn parse_opt_value(
        &self,
        ident: Identifier,
        attached_value: Option<&RawOsStr>,
        arg: &Arg,
        matcher: &mut ArgMatcher,
        has_eq: bool,
    ) -> ClapResult<ParseResult> {
        debug!(
            "Parser::parse_opt_value; arg={}, val={:?}, has_eq={:?}",
            arg.get_id(),
            attached_value,
            has_eq
        );
        debug!("Parser::parse_opt_value; arg.settings={:?}", arg.settings);

        debug!("Parser::parse_opt_value; Checking for val...");
        // require_equals is set, but no '=' is provided, try throwing error.
        if arg.is_require_equals_set() && !has_eq {
            if arg.get_min_vals() == 0 {
                debug!("Requires equals, but min_vals == 0");
                let arg_values = Vec::new();
                let trailing_idx = None;
                let react_result = ok!(self.react(
                    Some(ident),
                    ValueSource::CommandLine,
                    arg,
                    arg_values,
                    trailing_idx,
                    matcher,
                ));
                debug_assert_eq!(react_result, ParseResult::ValuesDone);
                if attached_value.is_some() {
                    Ok(ParseResult::AttachedValueNotConsumed)
                } else {
                    Ok(ParseResult::ValuesDone)
                }
            } else {
                debug!("Requires equals but not provided. Error.");
                Ok(ParseResult::EqualsNotProvided {
                    arg: arg.to_string(),
                })
            }
        } else if let Some(v) = attached_value {
            let arg_values = vec![v.to_os_str().into_owned()];
            let trailing_idx = None;
            let react_result = ok!(self.react(
                Some(ident),
                ValueSource::CommandLine,
                arg,
                arg_values,
                trailing_idx,
                matcher,
            ));
            debug_assert_eq!(react_result, ParseResult::ValuesDone);
            // Attached are always done
            Ok(ParseResult::ValuesDone)
        } else {
            debug!("Parser::parse_opt_value: More arg vals required...");
            ok!(self.resolve_pending(matcher));
            let trailing_values = false;
            matcher.pending_values_mut(arg.get_id(), Some(ident), trailing_values);
            Ok(ParseResult::Opt(arg.get_id().clone()))
        }
    }

    fn check_terminator(&self, arg: &Arg, val: &RawOsStr) -> Option<ParseResult> {
        if Some(val)
            == arg
                .terminator
                .as_ref()
                .map(|s| RawOsStr::from_str(s.as_str()))
        {
            debug!("Parser::check_terminator: terminator={:?}", arg.terminator);
            Some(ParseResult::ValuesDone)
        } else {
            None
        }
    }

    fn push_arg_values(
        &self,
        arg: &Arg,
        raw_vals: Vec<OsString>,
        matcher: &mut ArgMatcher,
    ) -> ClapResult<()> {
        debug!("Parser::push_arg_values: {:?}", raw_vals);

        for raw_val in raw_vals {
            // update the current index because each value is a distinct index to clap
            self.cur_idx.set(self.cur_idx.get() + 1);
            debug!(
                "Parser::add_single_val_to_arg: cur_idx:={}",
                self.cur_idx.get()
            );
            let value_parser = arg.get_value_parser();
            let val = ok!(value_parser.parse_ref(self.cmd, Some(arg), &raw_val));

            matcher.add_val_to(arg.get_id(), val, raw_val);
            matcher.add_index_to(arg.get_id(), self.cur_idx.get());
        }

        Ok(())
    }

    fn resolve_pending(&self, matcher: &mut ArgMatcher) -> ClapResult<()> {
        let pending = match matcher.take_pending() {
            Some(pending) => pending,
            None => {
                return Ok(());
            }
        };

        debug!("Parser::resolve_pending: id={:?}", pending.id);
        let arg = self.cmd.find(&pending.id).expect(INTERNAL_ERROR_MSG);
        let _ = ok!(self.react(
            pending.ident,
            ValueSource::CommandLine,
            arg,
            pending.raw_vals,
            pending.trailing_idx,
            matcher,
        ));

        Ok(())
    }

    fn react(
        &self,
        ident: Option<Identifier>,
        source: ValueSource,
        arg: &Arg,
        mut raw_vals: Vec<OsString>,
        mut trailing_idx: Option<usize>,
        matcher: &mut ArgMatcher,
    ) -> ClapResult<ParseResult> {
        ok!(self.resolve_pending(matcher));

        debug!(
            "Parser::react action={:?}, identifier={:?}, source={:?}",
            arg.get_action(),
            ident,
            source
        );

        // Process before `default_missing_values` to avoid it counting as values from the command
        // line
        if source == ValueSource::CommandLine {
            ok!(self.verify_num_args(arg, &raw_vals));
        }

        if raw_vals.is_empty() {
            // We assume this case is valid: require equals, but min_vals == 0.
            if !arg.default_missing_vals.is_empty() {
                debug!("Parser::react: has default_missing_vals");
                trailing_idx = None;
                raw_vals.extend(
                    arg.default_missing_vals
                        .iter()
                        .map(|s| s.as_os_str().to_owned()),
                );
            }
        }

        if let Some(val_delim) = arg.get_value_delimiter() {
            if self.cmd.is_dont_delimit_trailing_values_set() && trailing_idx == Some(0) {
                // Nothing to do
            } else {
                let mut split_raw_vals = Vec::with_capacity(raw_vals.len());
                for (i, raw_val) in raw_vals.into_iter().enumerate() {
                    let raw_val = RawOsString::new(raw_val);
                    if !raw_val.contains(val_delim)
                        || (self.cmd.is_dont_delimit_trailing_values_set()
                            && trailing_idx == Some(i))
                    {
                        split_raw_vals.push(raw_val.into_os_string());
                    } else {
                        split_raw_vals
                            .extend(raw_val.split(val_delim).map(|x| x.to_os_str().into_owned()));
                    }
                }
                raw_vals = split_raw_vals
            }
        }

        match arg.get_action() {
            ArgAction::Set => {
                if source == ValueSource::CommandLine
                    && matches!(ident, Some(Identifier::Short) | Some(Identifier::Long))
                {
                    // Record flag's index
                    self.cur_idx.set(self.cur_idx.get() + 1);
                    debug!("Parser::react: cur_idx:={}", self.cur_idx.get());
                }
                if matcher.remove(arg.get_id())
                    && !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
                {
                    return Err(ClapError::argument_conflict(
                        self.cmd,
                        arg.to_string(),
                        vec![arg.to_string()],
                        Usage::new(self.cmd).create_usage_with_title(&[]),
                    ));
                }
                self.start_custom_arg(matcher, arg, source);
                ok!(self.push_arg_values(arg, raw_vals, matcher));
                if cfg!(debug_assertions) && matcher.needs_more_vals(arg) {
                    debug!(
                        "Parser::react not enough values passed in, leaving it to the validator to complain",
                    );
                }
                Ok(ParseResult::ValuesDone)
            }
            ArgAction::Append => {
                if source == ValueSource::CommandLine
                    && matches!(ident, Some(Identifier::Short) | Some(Identifier::Long))
                {
                    // Record flag's index
                    self.cur_idx.set(self.cur_idx.get() + 1);
                    debug!("Parser::react: cur_idx:={}", self.cur_idx.get());
                }
                self.start_custom_arg(matcher, arg, source);
                ok!(self.push_arg_values(arg, raw_vals, matcher));
                if cfg!(debug_assertions) && matcher.needs_more_vals(arg) {
                    debug!(
                        "Parser::react not enough values passed in, leaving it to the validator to complain",
                    );
                }
                Ok(ParseResult::ValuesDone)
            }
            ArgAction::SetTrue => {
                let raw_vals = if raw_vals.is_empty() {
                    vec![OsString::from("true")]
                } else {
                    raw_vals
                };

                if matcher.remove(arg.get_id())
                    && !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
                {
                    return Err(ClapError::argument_conflict(
                        self.cmd,
                        arg.to_string(),
                        vec![arg.to_string()],
                        Usage::new(self.cmd).create_usage_with_title(&[]),
                    ));
                }
                self.start_custom_arg(matcher, arg, source);
                ok!(self.push_arg_values(arg, raw_vals, matcher));
                Ok(ParseResult::ValuesDone)
            }
            ArgAction::SetFalse => {
                let raw_vals = if raw_vals.is_empty() {
                    vec![OsString::from("false")]
                } else {
                    raw_vals
                };

                if matcher.remove(arg.get_id())
                    && !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
                {
                    return Err(ClapError::argument_conflict(
                        self.cmd,
                        arg.to_string(),
                        vec![arg.to_string()],
                        Usage::new(self.cmd).create_usage_with_title(&[]),
                    ));
                }
                self.start_custom_arg(matcher, arg, source);
                ok!(self.push_arg_values(arg, raw_vals, matcher));
                Ok(ParseResult::ValuesDone)
            }
            ArgAction::Count => {
                let raw_vals = if raw_vals.is_empty() {
                    let existing_value = *matcher
                        .get_one::<crate::builder::CountType>(arg.get_id().as_str())
                        .unwrap_or(&0);
                    let next_value = existing_value.saturating_add(1);
                    vec![OsString::from(next_value.to_string())]
                } else {
                    raw_vals
                };

                matcher.remove(arg.get_id());
                self.start_custom_arg(matcher, arg, source);
                ok!(self.push_arg_values(arg, raw_vals, matcher));
                Ok(ParseResult::ValuesDone)
            }
            ArgAction::Help => {
                let use_long = match ident {
                    Some(Identifier::Long) => true,
                    Some(Identifier::Short) => false,
                    Some(Identifier::Index) => true,
                    None => true,
                };
                debug!("Help: use_long={}", use_long);
                Err(self.help_err(use_long))
            }
            ArgAction::Version => {
                let use_long = match ident {
                    Some(Identifier::Long) => true,
                    Some(Identifier::Short) => false,
                    Some(Identifier::Index) => true,
                    None => true,
                };
                debug!("Version: use_long={}", use_long);
                Err(self.version_err(use_long))
            }
        }
    }

    fn verify_num_args(&self, arg: &Arg, raw_vals: &[OsString]) -> ClapResult<()> {
        if self.cmd.is_ignore_errors_set() {
            return Ok(());
        }

        let actual = raw_vals.len();
        let expected = arg.get_num_args().expect(INTERNAL_ERROR_MSG);

        if 0 < expected.min_values() && actual == 0 {
            // Issue 665 (https://github.com/clap-rs/clap/issues/665)
            // Issue 1105 (https://github.com/clap-rs/clap/issues/1105)
            return Err(ClapError::empty_value(
                self.cmd,
                &super::get_possible_values_cli(arg)
                    .iter()
                    .filter(|pv| !pv.is_hide_set())
                    .map(|n| n.get_name().to_owned())
                    .collect::<Vec<_>>(),
                arg.to_string(),
            ));
        } else if let Some(expected) = expected.num_values() {
            if expected != actual {
                debug!("Validator::validate_arg_num_vals: Sending error WrongNumberOfValues");
                return Err(ClapError::wrong_number_of_values(
                    self.cmd,
                    arg.to_string(),
                    expected,
                    actual,
                    Usage::new(self.cmd).create_usage_with_title(&[]),
                ));
            }
        } else if actual < expected.min_values() {
            return Err(ClapError::too_few_values(
                self.cmd,
                arg.to_string(),
                expected.min_values(),
                actual,
                Usage::new(self.cmd).create_usage_with_title(&[]),
            ));
        } else if expected.max_values() < actual {
            debug!("Validator::validate_arg_num_vals: Sending error TooManyValues");
            return Err(ClapError::too_many_values(
                self.cmd,
                raw_vals
                    .last()
                    .expect(INTERNAL_ERROR_MSG)
                    .to_string_lossy()
                    .into_owned(),
                arg.to_string(),
                Usage::new(self.cmd).create_usage_with_title(&[]),
            ));
        }

        Ok(())
    }

    fn remove_overrides(&self, arg: &Arg, matcher: &mut ArgMatcher) {
        debug!("Parser::remove_overrides: id={:?}", arg.id);
        for override_id in &arg.overrides {
            debug!("Parser::remove_overrides:iter:{:?}: removing", override_id);
            matcher.remove(override_id);
        }

        // Override anything that can override us
        let mut transitive = Vec::new();
        for arg_id in matcher.arg_ids() {
            if let Some(overrider) = self.cmd.find(arg_id) {
                if overrider.overrides.contains(arg.get_id()) {
                    transitive.push(overrider.get_id());
                }
            }
        }
        for overrider_id in transitive {
            debug!("Parser::remove_overrides:iter:{:?}: removing", overrider_id);
            matcher.remove(overrider_id);
        }
    }

    #[cfg(feature = "env")]
    fn add_env(&mut self, matcher: &mut ArgMatcher) -> ClapResult<()> {
        debug!("Parser::add_env");

        for arg in self.cmd.get_arguments() {
            // Use env only if the arg was absent among command line args,
            // early return if this is not the case.
            if matcher.contains(&arg.id) {
                debug!("Parser::add_env: Skipping existing arg `{}`", arg);
                continue;
            }

            debug!("Parser::add_env: Checking arg `{}`", arg);
            if let Some((_, Some(ref val))) = arg.env {
                debug!("Parser::add_env: Found an opt with value={:?}", val);
                let arg_values = vec![val.to_owned()];
                let trailing_idx = None;
                let _ = ok!(self.react(
                    None,
                    ValueSource::EnvVariable,
                    arg,
                    arg_values,
                    trailing_idx,
                    matcher,
                ));
            }
        }

        Ok(())
    }

    fn add_defaults(&self, matcher: &mut ArgMatcher) -> ClapResult<()> {
        debug!("Parser::add_defaults");

        for arg in self.cmd.get_arguments() {
            debug!("Parser::add_defaults:iter:{}:", arg.get_id());
            ok!(self.add_default_value(arg, matcher));
        }

        Ok(())
    }

Iterate through the positionals arguments.

Examples found in repository?
src/builder/command.rs (line 4398)
4397
4398
4399
    pub(crate) fn has_positionals(&self) -> bool {
        self.get_positionals().next().is_some()
    }
More examples
Hide additional examples
src/output/help_template.rs (line 41)
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
    pub(crate) fn write_help(&mut self) {
        let pos = self
            .template
            .cmd
            .get_positionals()
            .any(|arg| should_show_arg(self.template.use_long, arg));
        let non_pos = self
            .template
            .cmd
            .get_non_positionals()
            .any(|arg| should_show_arg(self.template.use_long, arg));
        let subcmds = self.template.cmd.has_visible_subcommands();

        let template = if non_pos || pos || subcmds {
            DEFAULT_TEMPLATE
        } else {
            DEFAULT_NO_ARGS_TEMPLATE
        };
        self.template.write_templated_help(template);
    }
}

const DEFAULT_TEMPLATE: &str = "\
{before-help}{about-with-newline}
{usage-heading} {usage}

{all-args}{after-help}\
    ";

const DEFAULT_NO_ARGS_TEMPLATE: &str = "\
{before-help}{about-with-newline}
{usage-heading} {usage}{after-help}\
    ";

/// `clap` HelpTemplate Writer.
///
/// Wraps a writer stream providing different methods to generate help for `clap` objects.
pub(crate) struct HelpTemplate<'cmd, 'writer> {
    writer: &'writer mut StyledStr,
    cmd: &'cmd Command,
    usage: &'cmd Usage<'cmd>,
    next_line_help: bool,
    term_w: usize,
    use_long: bool,
}

// Public Functions
impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
    /// Create a new `HelpTemplate` instance.
    pub(crate) fn new(
        writer: &'writer mut StyledStr,
        cmd: &'cmd Command,
        usage: &'cmd Usage<'cmd>,
        use_long: bool,
    ) -> Self {
        debug!(
            "HelpTemplate::new cmd={}, use_long={}",
            cmd.get_name(),
            use_long
        );
        let term_w = match cmd.get_term_width() {
            Some(0) => usize::MAX,
            Some(w) => w,
            None => {
                let (current_width, _h) = dimensions();
                let current_width = current_width.unwrap_or(100);
                let max_width = match cmd.get_max_term_width() {
                    None | Some(0) => usize::MAX,
                    Some(mw) => mw,
                };
                cmp::min(current_width, max_width)
            }
        };
        let next_line_help = cmd.is_next_line_help_set();

        HelpTemplate {
            writer,
            cmd,
            usage,
            next_line_help,
            term_w,
            use_long,
        }
    }

    /// Write help to stream for the parser in the format defined by the template.
    ///
    /// For details about the template language see [`Command::help_template`].
    ///
    /// [`Command::help_template`]: Command::help_template()
    pub(crate) fn write_templated_help(&mut self, template: &str) {
        debug!("HelpTemplate::write_templated_help");

        let mut parts = template.split('{');
        if let Some(first) = parts.next() {
            self.none(first);
        }
        for part in parts {
            if let Some((tag, rest)) = part.split_once('}') {
                match tag {
                    "name" => {
                        self.write_display_name();
                    }
                    "bin" => {
                        self.write_bin_name();
                    }
                    "version" => {
                        self.write_version();
                    }
                    "author" => {
                        self.write_author(false, false);
                    }
                    "author-with-newline" => {
                        self.write_author(false, true);
                    }
                    "author-section" => {
                        self.write_author(true, true);
                    }
                    "about" => {
                        self.write_about(false, false);
                    }
                    "about-with-newline" => {
                        self.write_about(false, true);
                    }
                    "about-section" => {
                        self.write_about(true, true);
                    }
                    "usage-heading" => {
                        self.header("Usage:");
                    }
                    "usage" => {
                        self.writer.extend(
                            self.usage
                                .create_usage_no_title(&[])
                                .unwrap_or_default()
                                .into_iter(),
                        );
                    }
                    "all-args" => {
                        self.write_all_args();
                    }
                    "options" => {
                        // Include even those with a heading as we don't have a good way of
                        // handling help_heading in the template.
                        self.write_args(
                            &self.cmd.get_non_positionals().collect::<Vec<_>>(),
                            "options",
                            option_sort_key,
                        );
                    }
                    "positionals" => {
                        self.write_args(
                            &self.cmd.get_positionals().collect::<Vec<_>>(),
                            "positionals",
                            positional_sort_key,
                        );
                    }
                    "subcommands" => {
                        self.write_subcommands(self.cmd);
                    }
                    "tab" => {
                        self.none(TAB);
                    }
                    "after-help" => {
                        self.write_after_help();
                    }
                    "before-help" => {
                        self.write_before_help();
                    }
                    _ => {
                        self.none("{");
                        self.none(tag);
                        self.none("}");
                    }
                }
                self.none(rest);
            }
        }
    }
}

/// Basic template methods
impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
    /// Writes binary name of a Parser Object to the wrapped stream.
    fn write_display_name(&mut self) {
        debug!("HelpTemplate::write_display_name");

        let display_name = wrap(
            &self
                .cmd
                .get_display_name()
                .unwrap_or_else(|| self.cmd.get_name())
                .replace("{n}", "\n"),
            self.term_w,
        );
        self.none(&display_name);
    }

    /// Writes binary name of a Parser Object to the wrapped stream.
    fn write_bin_name(&mut self) {
        debug!("HelpTemplate::write_bin_name");

        let bin_name = if let Some(bn) = self.cmd.get_bin_name() {
            if bn.contains(' ') {
                // In case we're dealing with subcommands i.e. git mv is translated to git-mv
                bn.replace(' ', "-")
            } else {
                wrap(&self.cmd.get_name().replace("{n}", "\n"), self.term_w)
            }
        } else {
            wrap(&self.cmd.get_name().replace("{n}", "\n"), self.term_w)
        };
        self.none(&bin_name);
    }

    fn write_version(&mut self) {
        let version = self
            .cmd
            .get_version()
            .or_else(|| self.cmd.get_long_version());
        if let Some(output) = version {
            self.none(wrap(output, self.term_w));
        }
    }

    fn write_author(&mut self, before_new_line: bool, after_new_line: bool) {
        if let Some(author) = self.cmd.get_author() {
            if before_new_line {
                self.none("\n");
            }
            self.none(wrap(author, self.term_w));
            if after_new_line {
                self.none("\n");
            }
        }
    }

    fn write_about(&mut self, before_new_line: bool, after_new_line: bool) {
        let about = if self.use_long {
            self.cmd.get_long_about().or_else(|| self.cmd.get_about())
        } else {
            self.cmd.get_about()
        };
        if let Some(output) = about {
            if before_new_line {
                self.none("\n");
            }
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
            if after_new_line {
                self.none("\n");
            }
        }
    }

    fn write_before_help(&mut self) {
        debug!("HelpTemplate::write_before_help");
        let before_help = if self.use_long {
            self.cmd
                .get_before_long_help()
                .or_else(|| self.cmd.get_before_help())
        } else {
            self.cmd.get_before_help()
        };
        if let Some(output) = before_help {
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
            self.none("\n\n");
        }
    }

    fn write_after_help(&mut self) {
        debug!("HelpTemplate::write_after_help");
        let after_help = if self.use_long {
            self.cmd
                .get_after_long_help()
                .or_else(|| self.cmd.get_after_help())
        } else {
            self.cmd.get_after_help()
        };
        if let Some(output) = after_help {
            self.none("\n\n");
            let mut output = output.clone();
            replace_newline_var(&mut output);
            output.wrap(self.term_w);
            self.writer.extend(output.into_iter());
        }
    }
}

/// Arg handling
impl<'cmd, 'writer> HelpTemplate<'cmd, 'writer> {
    /// Writes help for all arguments (options, flags, args, subcommands)
    /// including titles of a Parser Object to the wrapped stream.
    pub(crate) fn write_all_args(&mut self) {
        debug!("HelpTemplate::write_all_args");
        let pos = self
            .cmd
            .get_positionals()
            .filter(|a| a.get_help_heading().is_none())
            .filter(|arg| should_show_arg(self.use_long, arg))
            .collect::<Vec<_>>();
        let non_pos = self
            .cmd
            .get_non_positionals()
            .filter(|a| a.get_help_heading().is_none())
            .filter(|arg| should_show_arg(self.use_long, arg))
            .collect::<Vec<_>>();
        let subcmds = self.cmd.has_visible_subcommands();

        let custom_headings = self
            .cmd
            .get_arguments()
            .filter_map(|arg| arg.get_help_heading())
            .collect::<FlatSet<_>>();

        let mut first = true;

        if subcmds {
            if !first {
                self.none("\n\n");
            }
            first = false;
            let default_help_heading = Str::from("Commands");
            self.header(
                self.cmd
                    .get_subcommand_help_heading()
                    .unwrap_or(&default_help_heading),
            );
            self.header(":\n");

            self.write_subcommands(self.cmd);
        }

        if !pos.is_empty() {
            if !first {
                self.none("\n\n");
            }
            first = false;
            // Write positional args if any
            self.header("Arguments:\n");
            self.write_args(&pos, "Arguments", positional_sort_key);
        }

        if !non_pos.is_empty() {
            if !first {
                self.none("\n\n");
            }
            first = false;
            self.header("Options:\n");
            self.write_args(&non_pos, "Options", option_sort_key);
        }
        if !custom_headings.is_empty() {
            for heading in custom_headings {
                let args = self
                    .cmd
                    .get_arguments()
                    .filter(|a| {
                        if let Some(help_heading) = a.get_help_heading() {
                            return help_heading == heading;
                        }
                        false
                    })
                    .filter(|arg| should_show_arg(self.use_long, arg))
                    .collect::<Vec<_>>();

                if !args.is_empty() {
                    if !first {
                        self.none("\n\n");
                    }
                    first = false;
                    self.header(format!("{}:\n", heading));
                    self.write_args(&args, heading, option_sort_key);
                }
            }
        }
    }
src/output/usage.rs (line 265)
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
    pub(crate) fn get_args(&self, incls: &[Id], force_optional: bool) -> Vec<StyledStr> {
        debug!("Usage::get_args: incls={:?}", incls,);

        let required_owned;
        let required = if let Some(required) = self.required {
            required
        } else {
            required_owned = self.cmd.required_graph();
            &required_owned
        };

        let mut unrolled_reqs = Vec::new();
        for a in required.iter() {
            let is_relevant = |(val, req_arg): &(ArgPredicate, Id)| -> Option<Id> {
                let required = match val {
                    ArgPredicate::Equals(_) => false,
                    ArgPredicate::IsPresent => true,
                };
                required.then(|| req_arg.clone())
            };

            for aa in self.cmd.unroll_arg_requires(is_relevant, a) {
                // if we don't check for duplicates here this causes duplicate error messages
                // see https://github.com/clap-rs/clap/issues/2770
                unrolled_reqs.push(aa);
            }
            // always include the required arg itself. it will not be enumerated
            // by unroll_requirements_for_arg.
            unrolled_reqs.push(a.clone());
        }
        debug!("Usage::get_args: unrolled_reqs={:?}", unrolled_reqs);

        let mut required_groups_members = FlatSet::new();
        let mut required_groups = FlatSet::new();
        for req in unrolled_reqs.iter().chain(incls.iter()) {
            if self.cmd.find_group(req).is_some() {
                let group_members = self.cmd.unroll_args_in_group(req);
                let elem = self.cmd.format_group(req);
                required_groups.insert(elem);
                required_groups_members.extend(group_members);
            } else {
                debug_assert!(self.cmd.find(req).is_some());
            }
        }

        let mut required_opts = FlatSet::new();
        let mut required_positionals = Vec::new();
        for req in unrolled_reqs.iter().chain(incls.iter()) {
            if let Some(arg) = self.cmd.find(req) {
                if required_groups_members.contains(arg.get_id()) {
                    continue;
                }

                let stylized = arg.stylized(Some(!force_optional));
                if let Some(index) = arg.get_index() {
                    let new_len = index + 1;
                    if required_positionals.len() < new_len {
                        required_positionals.resize(new_len, None);
                    }
                    required_positionals[index] = Some(stylized);
                } else {
                    required_opts.insert(stylized);
                }
            } else {
                debug_assert!(self.cmd.find_group(req).is_some());
            }
        }

        for pos in self.cmd.get_positionals() {
            if pos.is_hide_set() {
                continue;
            }
            if required_groups_members.contains(pos.get_id()) {
                continue;
            }

            let index = pos.get_index().unwrap();
            let new_len = index + 1;
            if required_positionals.len() < new_len {
                required_positionals.resize(new_len, None);
            }
            if required_positionals[index].is_some() {
                if pos.is_last_set() {
                    let styled = required_positionals[index].take().unwrap();
                    let mut new = StyledStr::new();
                    new.literal("-- ");
                    new.extend(styled.into_iter());
                    required_positionals[index] = Some(new);
                }
            } else {
                let mut styled;
                if pos.is_last_set() {
                    styled = StyledStr::new();
                    styled.literal("[-- ");
                    styled.extend(pos.stylized(Some(true)).into_iter());
                    styled.literal("]");
                } else {
                    styled = pos.stylized(Some(false));
                }
                required_positionals[index] = Some(styled);
            }
            if pos.is_last_set() && force_optional {
                required_positionals[index] = None;
            }
        }

        let mut ret_val = Vec::new();
        if !force_optional {
            ret_val.extend(required_opts);
            ret_val.extend(required_groups);
        }
        for pos in required_positionals.into_iter().flatten() {
            ret_val.push(pos);
        }

        debug!("Usage::get_args: ret_val={:?}", ret_val);
        ret_val
    }
src/parser/validator.rs (line 357)
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
    fn validate_required(
        &mut self,
        matcher: &ArgMatcher,
        conflicts: &mut Conflicts,
    ) -> ClapResult<()> {
        debug!("Validator::validate_required: required={:?}", self.required);
        self.gather_requires(matcher);

        let mut missing_required = Vec::new();
        let mut highest_index = 0;

        let is_exclusive_present = matcher
            .arg_ids()
            .filter(|arg_id| matcher.check_explicit(arg_id, &ArgPredicate::IsPresent))
            .any(|id| {
                self.cmd
                    .find(id)
                    .map(|arg| arg.is_exclusive_set())
                    .unwrap_or_default()
            });
        debug!(
            "Validator::validate_required: is_exclusive_present={}",
            is_exclusive_present
        );

        for arg_or_group in self
            .required
            .iter()
            .filter(|r| !matcher.check_explicit(r, &ArgPredicate::IsPresent))
        {
            debug!("Validator::validate_required:iter:aog={:?}", arg_or_group);
            if let Some(arg) = self.cmd.find(arg_or_group) {
                debug!("Validator::validate_required:iter: This is an arg");
                if !is_exclusive_present && !self.is_missing_required_ok(arg, matcher, conflicts) {
                    debug!(
                        "Validator::validate_required:iter: Missing {:?}",
                        arg.get_id()
                    );
                    missing_required.push(arg.get_id().clone());
                    if !arg.is_last_set() {
                        highest_index = highest_index.max(arg.get_index().unwrap_or(0));
                    }
                }
            } else if let Some(group) = self.cmd.find_group(arg_or_group) {
                debug!("Validator::validate_required:iter: This is a group");
                if !self
                    .cmd
                    .unroll_args_in_group(&group.id)
                    .iter()
                    .any(|a| matcher.check_explicit(a, &ArgPredicate::IsPresent))
                {
                    debug!(
                        "Validator::validate_required:iter: Missing {:?}",
                        group.get_id()
                    );
                    missing_required.push(group.get_id().clone());
                }
            }
        }

        // Validate the conditionally required args
        for a in self
            .cmd
            .get_arguments()
            .filter(|a| !matcher.check_explicit(a.get_id(), &ArgPredicate::IsPresent))
        {
            let mut required = false;

            for (other, val) in &a.r_ifs {
                if matcher.check_explicit(other, &ArgPredicate::Equals(val.into())) {
                    debug!(
                        "Validator::validate_required:iter: Missing {:?}",
                        a.get_id()
                    );
                    required = true;
                }
            }

            let match_all = a.r_ifs_all.iter().all(|(other, val)| {
                matcher.check_explicit(other, &ArgPredicate::Equals(val.into()))
            });
            if match_all && !a.r_ifs_all.is_empty() {
                debug!(
                    "Validator::validate_required:iter: Missing {:?}",
                    a.get_id()
                );
                required = true;
            }

            if (!a.r_unless.is_empty() || !a.r_unless_all.is_empty())
                && self.fails_arg_required_unless(a, matcher)
            {
                debug!(
                    "Validator::validate_required:iter: Missing {:?}",
                    a.get_id()
                );
                required = true;
            }

            if required {
                missing_required.push(a.get_id().clone());
                if !a.is_last_set() {
                    highest_index = highest_index.max(a.get_index().unwrap_or(0));
                }
            }
        }

        // For display purposes, include all of the preceding positional arguments
        if !self.cmd.is_allow_missing_positional_set() {
            for pos in self
                .cmd
                .get_positionals()
                .filter(|a| !matcher.check_explicit(a.get_id(), &ArgPredicate::IsPresent))
            {
                if pos.get_index() < Some(highest_index) {
                    debug!(
                        "Validator::validate_required:iter: Missing {:?}",
                        pos.get_id()
                    );
                    missing_required.push(pos.get_id().clone());
                }
            }
        }

        if !missing_required.is_empty() {
            ok!(self.missing_required_error(matcher, missing_required));
        }

        Ok(())
    }
src/builder/debug_asserts.rs (line 560)
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
fn _verify_positionals(cmd: &Command) -> bool {
    debug!("Command::_verify_positionals");
    // Because you must wait until all arguments have been supplied, this is the first chance
    // to make assertions on positional argument indexes
    //
    // First we verify that the index highest supplied index, is equal to the number of
    // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3
    // but no 2)

    let highest_idx = cmd
        .get_keymap()
        .keys()
        .filter_map(|x| {
            if let KeyType::Position(n) = x {
                Some(*n)
            } else {
                None
            }
        })
        .max()
        .unwrap_or(0);

    let num_p = cmd.get_keymap().keys().filter(|x| x.is_position()).count();

    assert!(
        highest_idx == num_p,
        "Found positional argument whose index is {} but there \
             are only {} positional arguments defined",
        highest_idx,
        num_p
    );

    for arg in cmd.get_arguments() {
        if arg.index.unwrap_or(0) == highest_idx {
            assert!(
                !arg.is_trailing_var_arg_set() || !arg.is_last_set(),
                "{}:{}: `Arg::trailing_var_arg` and `Arg::last` cannot be used together",
                cmd.get_name(),
                arg.get_id()
            );

            if arg.is_trailing_var_arg_set() {
                assert!(
                    arg.is_multiple(),
                    "{}:{}: `Arg::trailing_var_arg` must accept multiple values",
                    cmd.get_name(),
                    arg.get_id()
                );
            }
        } else {
            assert!(
                !arg.is_trailing_var_arg_set(),
                "{}:{}: `Arg::trailing_var_arg` can only apply to last positional",
                cmd.get_name(),
                arg.get_id()
            );
        }
    }

    // Next we verify that only the highest index has takes multiple arguments (if any)
    let only_highest = |a: &Arg| a.is_multiple() && (a.get_index().unwrap_or(0) != highest_idx);
    if cmd.get_positionals().any(only_highest) {
        // First we make sure if there is a positional that allows multiple values
        // the one before it (second to last) has one of these:
        //  * a value terminator
        //  * ArgSettings::Last
        //  * The last arg is Required

        // We can't pass the closure (it.next()) to the macro directly because each call to
        // find() (iterator, not macro) gets called repeatedly.
        let last = &cmd.get_keymap()[&KeyType::Position(highest_idx)];
        let second_to_last = &cmd.get_keymap()[&KeyType::Position(highest_idx - 1)];

        // Either the final positional is required
        // Or the second to last has a terminator or .last(true) set
        let ok = last.is_required_set()
            || (second_to_last.terminator.is_some() || second_to_last.is_last_set())
            || last.is_last_set();
        assert!(
            ok,
            "When using a positional argument with `.num_args(1..)` that is *not the \
                 last* positional argument, the last positional argument (i.e. the one \
                 with the highest index) *must* have .required(true) or .last(true) set."
        );

        // We make sure if the second to last is Multiple the last is ArgSettings::Last
        let ok = second_to_last.is_multiple() || last.is_last_set();
        assert!(
            ok,
            "Only the last positional argument, or second to last positional \
                 argument may be set to `.num_args(1..)`"
        );

        // Next we check how many have both Multiple and not a specific number of values set
        let count = cmd
            .get_positionals()
            .filter(|p| {
                p.is_multiple_values_set()
                    && !p.get_num_args().expect(INTERNAL_ERROR_MSG).is_fixed()
            })
            .count();
        let ok = count <= 1
            || (last.is_last_set()
                && last.is_multiple()
                && second_to_last.is_multiple()
                && count == 2);
        assert!(
            ok,
            "Only one positional argument with `.num_args(1..)` set is allowed per \
                 command, unless the second one also has .last(true) set"
        );
    }

    let mut found = false;

    if cmd.is_allow_missing_positional_set() {
        // Check that if a required positional argument is found, all positions with a lower
        // index are also required.
        let mut foundx2 = false;

        for p in cmd.get_positionals() {
            if foundx2 && !p.is_required_set() {
                assert!(
                    p.is_required_set(),
                    "Found non-required positional argument with a lower \
                         index than a required positional argument by two or more: {:?} \
                         index {:?}",
                    p.get_id(),
                    p.get_index()
                );
            } else if p.is_required_set() && !p.is_last_set() {
                // Args that .last(true) don't count since they can be required and have
                // positionals with a lower index that aren't required
                // Imagine: prog <req1> [opt1] -- <req2>
                // Both of these are valid invocations:
                //      $ prog r1 -- r2
                //      $ prog r1 o1 -- r2
                if found {
                    foundx2 = true;
                    continue;
                }
                found = true;
                continue;
            } else {
                found = false;
            }
        }
    } else {
        // Check that if a required positional argument is found, all positions with a lower
        // index are also required
        for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) {
            if found {
                assert!(
                    p.is_required_set(),
                    "Found non-required positional argument with a lower \
                         index than a required positional argument: {:?} index {:?}",
                    p.get_id(),
                    p.get_index()
                );
            } else if p.is_required_set() && !p.is_last_set() {
                // Args that .last(true) don't count since they can be required and have
                // positionals with a lower index that aren't required
                // Imagine: prog <req1> [opt1] -- <req2>
                // Both of these are valid invocations:
                //      $ prog r1 -- r2
                //      $ prog r1 o1 -- r2
                found = true;
                continue;
            }
        }
    }
    assert!(
        cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2,
        "Only one positional argument may have last(true) set. Found two."
    );
    if cmd
        .get_positionals()
        .any(|p| p.is_last_set() && p.is_required_set())
        && cmd.has_subcommands()
        && !cmd.is_subcommand_negates_reqs_set()
    {
        panic!(
            "Having a required positional argument with .last(true) set *and* child \
                 subcommands without setting SubcommandsNegateReqs isn't compatible."
        );
    }

    true
}
src/parser/parser.rs (line 318)
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
    pub(crate) fn get_matches_with(
        &mut self,
        matcher: &mut ArgMatcher,
        raw_args: &mut clap_lex::RawArgs,
        mut args_cursor: clap_lex::ArgCursor,
    ) -> ClapResult<()> {
        debug!("Parser::get_matches_with");
        // Verify all positional assertions pass

        let mut subcmd_name: Option<String> = None;
        let mut keep_state = false;
        let mut parse_state = ParseState::ValuesDone;
        let mut pos_counter = 1;

        // Already met any valid arg(then we shouldn't expect subcommands after it).
        let mut valid_arg_found = false;
        // If the user already passed '--'. Meaning only positional args follow.
        let mut trailing_values = false;

        // Count of positional args
        let positional_count = self
            .cmd
            .get_keymap()
            .keys()
            .filter(|x| x.is_position())
            .count();
        // If any arg sets .last(true)
        let contains_last = self.cmd.get_arguments().any(|x| x.is_last_set());

        while let Some(arg_os) = raw_args.next(&mut args_cursor) {
            // Recover the replaced items if any.
            if let Some(replaced_items) = arg_os
                .to_value()
                .ok()
                .and_then(|a| self.cmd.get_replacement(a))
            {
                debug!(
                    "Parser::get_matches_with: found replacer: {:?}, target: {:?}",
                    arg_os, replaced_items
                );
                raw_args.insert(&args_cursor, replaced_items);
                continue;
            }

            debug!(
                "Parser::get_matches_with: Begin parsing '{:?}' ({:?})",
                arg_os.to_value_os(),
                arg_os.to_value_os().as_raw_bytes()
            );

            // Has the user already passed '--'? Meaning only positional args follow
            if !trailing_values {
                if self.cmd.is_subcommand_precedence_over_arg_set()
                    || !matches!(parse_state, ParseState::Opt(_) | ParseState::Pos(_))
                {
                    // Does the arg match a subcommand name, or any of its aliases (if defined)
                    let sc_name = self.possible_subcommand(arg_os.to_value(), valid_arg_found);
                    debug!("Parser::get_matches_with: sc={:?}", sc_name);
                    if let Some(sc_name) = sc_name {
                        if sc_name == "help" && !self.cmd.is_disable_help_subcommand_set() {
                            ok!(self.parse_help_subcommand(raw_args.remaining(&mut args_cursor)));
                            unreachable!("`parse_help_subcommand` always errors");
                        } else {
                            subcmd_name = Some(sc_name.to_owned());
                        }
                        break;
                    }
                }

                if arg_os.is_escape() {
                    if matches!(&parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if
                        self.cmd[opt].is_allow_hyphen_values_set())
                    {
                        // ParseResult::MaybeHyphenValue, do nothing
                    } else {
                        debug!("Parser::get_matches_with: setting TrailingVals=true");
                        trailing_values = true;
                        matcher.start_trailing();
                        continue;
                    }
                } else if let Some((long_arg, long_value)) = arg_os.to_long() {
                    let parse_result = ok!(self.parse_long_arg(
                        matcher,
                        long_arg,
                        long_value,
                        &parse_state,
                        pos_counter,
                        &mut valid_arg_found,
                    ));
                    debug!(
                        "Parser::get_matches_with: After parse_long_arg {:?}",
                        parse_result
                    );
                    match parse_result {
                        ParseResult::NoArg => {
                            unreachable!("`to_long` always has the flag specified")
                        }
                        ParseResult::ValuesDone => {
                            parse_state = ParseState::ValuesDone;
                            continue;
                        }
                        ParseResult::Opt(id) => {
                            parse_state = ParseState::Opt(id);
                            continue;
                        }
                        ParseResult::FlagSubCommand(name) => {
                            debug!(
                                "Parser::get_matches_with: FlagSubCommand found in long arg {:?}",
                                &name
                            );
                            subcmd_name = Some(name);
                            break;
                        }
                        ParseResult::EqualsNotProvided { arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::no_equals(
                                self.cmd,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::NoMatchingArg { arg } => {
                            let _ = self.resolve_pending(matcher);
                            let remaining_args: Vec<_> =
                                raw_args.remaining(&mut args_cursor).collect();
                            return Err(self.did_you_mean_error(
                                &arg,
                                matcher,
                                &remaining_args,
                                trailing_values,
                            ));
                        }
                        ParseResult::UnneededAttachedValue { rest, used, arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::too_many_values(
                                self.cmd,
                                rest,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&used),
                            ));
                        }
                        ParseResult::MaybeHyphenValue => {
                            // Maybe a hyphen value, do nothing.
                        }
                        ParseResult::AttachedValueNotConsumed => {
                            unreachable!()
                        }
                    }
                } else if let Some(short_arg) = arg_os.to_short() {
                    // Arg looks like a short flag, and not a possible number

                    // Try to parse short args like normal, if allow_hyphen_values or
                    // AllowNegativeNumbers is set, parse_short_arg will *not* throw
                    // an error, and instead return Ok(None)
                    let parse_result = ok!(self.parse_short_arg(
                        matcher,
                        short_arg,
                        &parse_state,
                        pos_counter,
                        &mut valid_arg_found,
                    ));
                    // If it's None, we then check if one of those two AppSettings was set
                    debug!(
                        "Parser::get_matches_with: After parse_short_arg {:?}",
                        parse_result
                    );
                    match parse_result {
                        ParseResult::NoArg => {
                            // Is a single dash `-`, try positional.
                        }
                        ParseResult::ValuesDone => {
                            parse_state = ParseState::ValuesDone;
                            continue;
                        }
                        ParseResult::Opt(id) => {
                            parse_state = ParseState::Opt(id);
                            continue;
                        }
                        ParseResult::FlagSubCommand(name) => {
                            // If there are more short flags to be processed, we should keep the state, and later
                            // revisit the current group of short flags skipping the subcommand.
                            keep_state = self
                                .flag_subcmd_at
                                .map(|at| {
                                    raw_args
                                        .seek(&mut args_cursor, clap_lex::SeekFrom::Current(-1));
                                    // Since we are now saving the current state, the number of flags to skip during state recovery should
                                    // be the current index (`cur_idx`) minus ONE UNIT TO THE LEFT of the starting position.
                                    self.flag_subcmd_skip = self.cur_idx.get() - at + 1;
                                })
                                .is_some();

                            debug!(
                                "Parser::get_matches_with:FlagSubCommandShort: subcmd_name={}, keep_state={}, flag_subcmd_skip={}",
                                name,
                                keep_state,
                                self.flag_subcmd_skip
                            );

                            subcmd_name = Some(name);
                            break;
                        }
                        ParseResult::EqualsNotProvided { arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::no_equals(
                                self.cmd,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::NoMatchingArg { arg } => {
                            let _ = self.resolve_pending(matcher);
                            // We already know it looks like a flag
                            let suggested_trailing_arg =
                                !trailing_values && self.cmd.has_positionals();
                            return Err(ClapError::unknown_argument(
                                self.cmd,
                                arg,
                                None,
                                suggested_trailing_arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::MaybeHyphenValue => {
                            // Maybe a hyphen value, do nothing.
                        }
                        ParseResult::UnneededAttachedValue { .. }
                        | ParseResult::AttachedValueNotConsumed => unreachable!(),
                    }
                }

                if let ParseState::Opt(id) = &parse_state {
                    // Assume this is a value of a previous arg.

                    // get the option so we can check the settings
                    let arg = &self.cmd[id];
                    let parse_result = if let Some(parse_result) =
                        self.check_terminator(arg, arg_os.to_value_os())
                    {
                        parse_result
                    } else {
                        let trailing_values = false;
                        let arg_values = matcher.pending_values_mut(id, None, trailing_values);
                        arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
                        if matcher.needs_more_vals(arg) {
                            ParseResult::Opt(arg.get_id().clone())
                        } else {
                            ParseResult::ValuesDone
                        }
                    };
                    parse_state = match parse_result {
                        ParseResult::Opt(id) => ParseState::Opt(id),
                        ParseResult::ValuesDone => ParseState::ValuesDone,
                        _ => unreachable!(),
                    };
                    // get the next value from the iterator
                    continue;
                }
            }

            // Correct pos_counter.
            pos_counter = {
                let is_second_to_last = pos_counter + 1 == positional_count;

                // The last positional argument, or second to last positional
                // argument may be set to .multiple_values(true) or `.multiple_occurrences(true)`
                let low_index_mults = is_second_to_last
                    && self.cmd.get_positionals().any(|a| {
                        a.is_multiple() && (positional_count != a.get_index().unwrap_or(0))
                    })
                    && self
                        .cmd
                        .get_positionals()
                        .last()
                        .map_or(false, |p_name| !p_name.is_last_set());

                let missing_pos = self.cmd.is_allow_missing_positional_set()
                    && is_second_to_last
                    && !trailing_values;

                debug!(
                    "Parser::get_matches_with: Positional counter...{}",
                    pos_counter
                );
                debug!(
                    "Parser::get_matches_with: Low index multiples...{:?}",
                    low_index_mults
                );

                if low_index_mults || missing_pos {
                    let skip_current = if let Some(n) = raw_args.peek(&args_cursor) {
                        if let Some(arg) = self
                            .cmd
                            .get_positionals()
                            .find(|a| a.get_index() == Some(pos_counter))
                        {
                            // If next value looks like a new_arg or it's a
                            // subcommand, skip positional argument under current
                            // pos_counter(which means current value cannot be a
                            // positional argument with a value next to it), assume
                            // current value matches the next arg.
                            self.is_new_arg(&n, arg)
                                || self
                                    .possible_subcommand(n.to_value(), valid_arg_found)
                                    .is_some()
                        } else {
                            true
                        }
                    } else {
                        true
                    };

                    if skip_current {
                        debug!("Parser::get_matches_with: Bumping the positional counter...");
                        pos_counter + 1
                    } else {
                        pos_counter
                    }
                } else if trailing_values
                    && (self.cmd.is_allow_missing_positional_set() || contains_last)
                {
                    // Came to -- and one positional has .last(true) set, so we go immediately
                    // to the last (highest index) positional
                    debug!("Parser::get_matches_with: .last(true) and --, setting last pos");
                    positional_count
                } else {
                    pos_counter
                }
            };

            if let Some(arg) = self.cmd.get_keymap().get(&pos_counter) {
                if arg.is_last_set() && !trailing_values {
                    let _ = self.resolve_pending(matcher);
                    // Its already considered a positional, we don't need to suggest turning it
                    // into one
                    let suggested_trailing_arg = false;
                    return Err(ClapError::unknown_argument(
                        self.cmd,
                        arg_os.display().to_string(),
                        None,
                        suggested_trailing_arg,
                        Usage::new(self.cmd).create_usage_with_title(&[]),
                    ));
                }

                if arg.is_trailing_var_arg_set() {
                    trailing_values = true;
                }

                if matcher.pending_arg_id() != Some(arg.get_id()) || !arg.is_multiple_values_set() {
                    ok!(self.resolve_pending(matcher));
                }
                if let Some(_parse_result) = self.check_terminator(arg, arg_os.to_value_os()) {
                    debug!(
                        "Parser::get_matches_with: ignoring terminator result {:?}",
                        _parse_result
                    );
                } else {
                    let arg_values = matcher.pending_values_mut(
                        arg.get_id(),
                        Some(Identifier::Index),
                        trailing_values,
                    );
                    arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
                }

                // Only increment the positional counter if it doesn't allow multiples
                if !arg.is_multiple() {
                    pos_counter += 1;
                    parse_state = ParseState::ValuesDone;
                } else {
                    parse_state = ParseState::Pos(arg.get_id().clone());
                }
                valid_arg_found = true;
            } else if let Some(external_parser) =
                self.cmd.get_external_subcommand_value_parser().cloned()
            {
                // Get external subcommand name
                let sc_name = match arg_os.to_value() {
                    Ok(s) => s.to_owned(),
                    Err(_) => {
                        let _ = self.resolve_pending(matcher);
                        return Err(ClapError::invalid_utf8(
                            self.cmd,
                            Usage::new(self.cmd).create_usage_with_title(&[]),
                        ));
                    }
                };

                // Collect the external subcommand args
                let mut sc_m = ArgMatcher::new(self.cmd);
                sc_m.start_occurrence_of_external(self.cmd);

                for raw_val in raw_args.remaining(&mut args_cursor) {
                    let val = ok!(external_parser.parse_ref(self.cmd, None, raw_val));
                    let external_id = Id::from_static_ref(Id::EXTERNAL);
                    sc_m.add_val_to(&external_id, val, raw_val.to_os_string());
                }

                matcher.subcommand(SubCommand {
                    name: sc_name,
                    matches: sc_m.into_inner(),
                });

                ok!(self.resolve_pending(matcher));
                #[cfg(feature = "env")]
                ok!(self.add_env(matcher));
                ok!(self.add_defaults(matcher));
                return Validator::new(self.cmd).validate(parse_state, matcher);
            } else {
                // Start error processing
                let _ = self.resolve_pending(matcher);
                return Err(self.match_arg_error(&arg_os, valid_arg_found, trailing_values));
            }
        }

        if let Some(ref pos_sc_name) = subcmd_name {
            let sc_name = self
                .cmd
                .find_subcommand(pos_sc_name)
                .expect(INTERNAL_ERROR_MSG)
                .get_name()
                .to_owned();
            ok!(self.parse_subcommand(&sc_name, matcher, raw_args, args_cursor, keep_state));
        }

        ok!(self.resolve_pending(matcher));
        #[cfg(feature = "env")]
        ok!(self.add_env(matcher));
        ok!(self.add_defaults(matcher));
        Validator::new(self.cmd).validate(parse_state, matcher)
    }

Iterate through the options.

Get a list of all arguments the given argument conflicts with.

If the provided argument is declared as global, the conflicts will be determined based on the propagation rules of global arguments.

Panics

If the given arg contains a conflict with an argument that is unknown to this Command.

Report whether Command::no_binary_name is set

Examples found in repository?
src/parser/parser.rs (line 1155)
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
    fn react(
        &self,
        ident: Option<Identifier>,
        source: ValueSource,
        arg: &Arg,
        mut raw_vals: Vec<OsString>,
        mut trailing_idx: Option<usize>,
        matcher: &mut ArgMatcher,
    ) -> ClapResult<ParseResult> {
        ok!(self.resolve_pending(matcher));

        debug!(
            "Parser::react action={:?}, identifier={:?}, source={:?}",
            arg.get_action(),
            ident,
            source
        );

        // Process before `default_missing_values` to avoid it counting as values from the command
        // line
        if source == ValueSource::CommandLine {
            ok!(self.verify_num_args(arg, &raw_vals));
        }

        if raw_vals.is_empty() {
            // We assume this case is valid: require equals, but min_vals == 0.
            if !arg.default_missing_vals.is_empty() {
                debug!("Parser::react: has default_missing_vals");
                trailing_idx = None;
                raw_vals.extend(
                    arg.default_missing_vals
                        .iter()
                        .map(|s| s.as_os_str().to_owned()),
                );
            }
        }

        if let Some(val_delim) = arg.get_value_delimiter() {
            if self.cmd.is_dont_delimit_trailing_values_set() && trailing_idx == Some(0) {
                // Nothing to do
            } else {
                let mut split_raw_vals = Vec::with_capacity(raw_vals.len());
                for (i, raw_val) in raw_vals.into_iter().enumerate() {
                    let raw_val = RawOsString::new(raw_val);
                    if !raw_val.contains(val_delim)
                        || (self.cmd.is_dont_delimit_trailing_values_set()
                            && trailing_idx == Some(i))
                    {
                        split_raw_vals.push(raw_val.into_os_string());
                    } else {
                        split_raw_vals
                            .extend(raw_val.split(val_delim).map(|x| x.to_os_str().into_owned()));
                    }
                }
                raw_vals = split_raw_vals
            }
        }

        match arg.get_action() {
            ArgAction::Set => {
                if source == ValueSource::CommandLine
                    && matches!(ident, Some(Identifier::Short) | Some(Identifier::Long))
                {
                    // Record flag's index
                    self.cur_idx.set(self.cur_idx.get() + 1);
                    debug!("Parser::react: cur_idx:={}", self.cur_idx.get());
                }
                if matcher.remove(arg.get_id())
                    && !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
                {
                    return Err(ClapError::argument_conflict(
                        self.cmd,
                        arg.to_string(),
                        vec![arg.to_string()],
                        Usage::new(self.cmd).create_usage_with_title(&[]),
                    ));
                }
                self.start_custom_arg(matcher, arg, source);
                ok!(self.push_arg_values(arg, raw_vals, matcher));
                if cfg!(debug_assertions) && matcher.needs_more_vals(arg) {
                    debug!(
                        "Parser::react not enough values passed in, leaving it to the validator to complain",
                    );
                }
                Ok(ParseResult::ValuesDone)
            }
            ArgAction::Append => {
                if source == ValueSource::CommandLine
                    && matches!(ident, Some(Identifier::Short) | Some(Identifier::Long))
                {
                    // Record flag's index
                    self.cur_idx.set(self.cur_idx.get() + 1);
                    debug!("Parser::react: cur_idx:={}", self.cur_idx.get());
                }
                self.start_custom_arg(matcher, arg, source);
                ok!(self.push_arg_values(arg, raw_vals, matcher));
                if cfg!(debug_assertions) && matcher.needs_more_vals(arg) {
                    debug!(
                        "Parser::react not enough values passed in, leaving it to the validator to complain",
                    );
                }
                Ok(ParseResult::ValuesDone)
            }
            ArgAction::SetTrue => {
                let raw_vals = if raw_vals.is_empty() {
                    vec![OsString::from("true")]
                } else {
                    raw_vals
                };

                if matcher.remove(arg.get_id())
                    && !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
                {
                    return Err(ClapError::argument_conflict(
                        self.cmd,
                        arg.to_string(),
                        vec![arg.to_string()],
                        Usage::new(self.cmd).create_usage_with_title(&[]),
                    ));
                }
                self.start_custom_arg(matcher, arg, source);
                ok!(self.push_arg_values(arg, raw_vals, matcher));
                Ok(ParseResult::ValuesDone)
            }
            ArgAction::SetFalse => {
                let raw_vals = if raw_vals.is_empty() {
                    vec![OsString::from("false")]
                } else {
                    raw_vals
                };

                if matcher.remove(arg.get_id())
                    && !(self.cmd.is_args_override_self() || arg.overrides.contains(arg.get_id()))
                {
                    return Err(ClapError::argument_conflict(
                        self.cmd,
                        arg.to_string(),
                        vec![arg.to_string()],
                        Usage::new(self.cmd).create_usage_with_title(&[]),
                    ));
                }
                self.start_custom_arg(matcher, arg, source);
                ok!(self.push_arg_values(arg, raw_vals, matcher));
                Ok(ParseResult::ValuesDone)
            }
            ArgAction::Count => {
                let raw_vals = if raw_vals.is_empty() {
                    let existing_value = *matcher
                        .get_one::<crate::builder::CountType>(arg.get_id().as_str())
                        .unwrap_or(&0);
                    let next_value = existing_value.saturating_add(1);
                    vec![OsString::from(next_value.to_string())]
                } else {
                    raw_vals
                };

                matcher.remove(arg.get_id());
                self.start_custom_arg(matcher, arg, source);
                ok!(self.push_arg_values(arg, raw_vals, matcher));
                Ok(ParseResult::ValuesDone)
            }
            ArgAction::Help => {
                let use_long = match ident {
                    Some(Identifier::Long) => true,
                    Some(Identifier::Short) => false,
                    Some(Identifier::Index) => true,
                    None => true,
                };
                debug!("Help: use_long={}", use_long);
                Err(self.help_err(use_long))
            }
            ArgAction::Version => {
                let use_long = match ident {
                    Some(Identifier::Long) => true,
                    Some(Identifier::Short) => false,
                    Some(Identifier::Index) => true,
                    None => true,
                };
                debug!("Version: use_long={}", use_long);
                Err(self.version_err(use_long))
            }
        }
    }

Report whether Command::disable_version_flag is set

Examples found in repository?
src/builder/debug_asserts.rs (line 373)
368
369
370
371
372
373
374
375
376
377
378
379
380
fn duplicate_tip(cmd: &Command, first: &Arg, second: &Arg) -> &'static str {
    if !cmd.is_disable_help_flag_set()
        && (first.get_id() == Id::HELP || second.get_id() == Id::HELP)
    {
        " (call `cmd.disable_help_flag(true)` to remove the auto-generated `--help`)"
    } else if !cmd.is_disable_version_flag_set()
        && (first.get_id() == Id::VERSION || second.get_id() == Id::VERSION)
    {
        " (call `cmd.disable_version_flag(true)` to remove the auto-generated `--version`)"
    } else {
        ""
    }
}
More examples
Hide additional examples
src/builder/command.rs (line 4255)
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
    pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) {
        debug!(
            "Command::_check_help_and_version:{} expand_help_tree={}",
            self.name, expand_help_tree
        );

        self.long_help_exists = self.long_help_exists_();

        if !self.is_disable_help_flag_set() {
            debug!("Command::_check_help_and_version: Building default --help");
            let mut arg = Arg::new(Id::HELP)
                .short('h')
                .long("help")
                .action(ArgAction::Help);
            if self.long_help_exists {
                arg = arg
                    .help("Print help information (use `--help` for more detail)")
                    .long_help("Print help information (use `-h` for a summary)");
            } else {
                arg = arg.help("Print help information");
            }
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }
        if !self.is_disable_version_flag_set() {
            debug!("Command::_check_help_and_version: Building default --version");
            let arg = Arg::new(Id::VERSION)
                .short('V')
                .long("version")
                .action(ArgAction::Version)
                .help("Print version information");
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }

        if !self.is_set(AppSettings::DisableHelpSubcommand) {
            debug!("Command::_check_help_and_version: Building help subcommand");
            let help_about = "Print this message or the help of the given subcommand(s)";

            let mut help_subcmd = if expand_help_tree {
                // Slow code path to recursively clone all other subcommand subtrees under help
                let help_subcmd = Command::new("help")
                    .about(help_about)
                    .global_setting(AppSettings::DisableHelpSubcommand)
                    .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));

                let mut help_help_subcmd = Command::new("help").about(help_about);
                help_help_subcmd.version = None;
                help_help_subcmd.long_version = None;
                help_help_subcmd = help_help_subcmd
                    .setting(AppSettings::DisableHelpFlag)
                    .setting(AppSettings::DisableVersionFlag);

                help_subcmd.subcommand(help_help_subcmd)
            } else {
                Command::new("help").about(help_about).arg(
                    Arg::new("subcommand")
                        .action(ArgAction::Append)
                        .num_args(..)
                        .value_name("COMMAND")
                        .help("Print help for the subcommand(s)"),
                )
            };
            self._propagate_subcommand(&mut help_subcmd);

            // The parser acts like this is set, so let's set it so we don't falsely
            // advertise it to the user
            help_subcmd.version = None;
            help_subcmd.long_version = None;
            help_subcmd = help_subcmd
                .setting(AppSettings::DisableHelpFlag)
                .setting(AppSettings::DisableVersionFlag)
                .unset_global_setting(AppSettings::PropagateVersion);

            self.subcommands.push(help_subcmd);
        }
    }

Report whether Command::propagate_version is set

Examples found in repository?
src/builder/debug_asserts.rs (line 24)
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
pub(crate) fn assert_app(cmd: &Command) {
    debug!("Command::_debug_asserts");

    let mut short_flags = vec![];
    let mut long_flags = vec![];

    // Invalid version flag settings
    if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
        // PropagateVersion is meaningless if there is no version
        assert!(
            !cmd.is_propagate_version_set(),
            "Command {}: No version information via Command::version or Command::long_version to propagate",
            cmd.get_name(),
        );

        // Used `Command::mut_arg("version", ..) but did not provide any version information to display
        let version_needed = cmd
            .get_arguments()
            .filter(|x| matches!(x.get_action(), ArgAction::Version))
            .map(|x| x.get_id())
            .collect::<Vec<_>>();

        assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
            ,cmd.get_name()
        );
    }

    for sc in cmd.get_subcommands() {
        if let Some(s) = sc.get_short_flag().as_ref() {
            short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
        }

        for short_alias in sc.get_all_short_flag_aliases() {
            short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
        }

        if let Some(l) = sc.get_long_flag().as_ref() {
            assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
            long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
        }

        for long_alias in sc.get_all_long_flag_aliases() {
            long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
        }
    }

    for arg in cmd.get_arguments() {
        assert_arg(arg);

        assert!(
            !cmd.is_multicall_set(),
            "Command {}: Arguments like {} cannot be set on a multicall command",
            cmd.get_name(),
            arg.get_id()
        );

        if let Some(s) = arg.get_short() {
            short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str()));
        }

        for (short_alias, _) in &arg.short_aliases {
            short_flags.push(Flag::Arg(
                format!("-{}", short_alias),
                arg.get_id().as_str(),
            ));
        }

        if let Some(l) = arg.get_long() {
            assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l);
            long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str()));
        }

        for (long_alias, _) in &arg.aliases {
            long_flags.push(Flag::Arg(
                format!("--{}", long_alias),
                arg.get_id().as_str(),
            ));
        }

        // Name conflicts
        if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
            panic!(
            "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
            cmd.get_name(),
            arg.get_id(),
            duplicate_tip(cmd, first, second),
        );
        }

        // Long conflicts
        if let Some(l) = arg.get_long() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) {
                panic!(
                    "Command {}: Long option names must be unique for each argument, \
                            but '--{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    l,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second)
                )
            }
        }

        // Short conflicts
        if let Some(s) = arg.get_short() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
                panic!(
                    "Command {}: Short option names must be unique for each argument, \
                            but '-{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    s,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second),
                )
            }
        }

        // Index conflicts
        if let Some(idx) = arg.index {
            if let Some((first, second)) =
                cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
            {
                panic!(
                    "Command {}: Argument '{}' has the same index as '{}' \
                    and they are both positional arguments\n\n\t \
                    Use `Arg::num_args(1..)` to allow one \
                    positional argument to take multiple values",
                    cmd.get_name(),
                    first.get_id(),
                    second.get_id()
                )
            }
        }

        // requires, r_if, r_unless
        for req in &arg.requires {
            assert!(
                cmd.id_exists(&req.1),
                "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
                cmd.get_name(),
                req.1,
                arg.get_id(),
            );
        }

        for req in &arg.r_ifs {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_ifs_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq_all`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_unless {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        for req in &arg.r_unless_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // blacklist
        for req in &arg.blacklist {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // overrides
        for req in &arg.overrides {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        if arg.is_last_set() {
            assert!(
                arg.get_long().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
            assert!(
                arg.get_short().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }

        assert!(
            !(arg.is_required_set() && arg.is_global_set()),
            "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
                    cmd.get_name(),
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_positional(),
                "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
                cmd.get_name(),
                arg.get_id()
            );

            assert!(
                arg.is_trailing_var_arg_set() || arg.is_last_set(),
                "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }
    }

    for group in cmd.get_groups() {
        let derive_hint = if cfg!(feature = "derive") {
            " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
        } else {
            ""
        };

        // Name conflicts
        assert!(
            cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
            "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        // Groups should not have naming conflicts with Args
        assert!(
            !cmd.get_arguments().any(|x| x.get_id() == group.get_id()),
            "Command {}: Argument group name '{}' must not conflict with argument name{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        for arg in &group.args {
            // Args listed inside groups should exist
            assert!(
                cmd.get_arguments().any(|x| x.get_id() == arg),
                "Command {}: Argument group '{}' contains non-existent argument '{}'",
                cmd.get_name(),
                group.get_id(),
                arg
            );
        }
    }

    // Conflicts between flags and subcommands

    long_flags.sort_unstable();
    short_flags.sort_unstable();

    detect_duplicate_flags(&long_flags, "long");
    detect_duplicate_flags(&short_flags, "short");

    let mut subs = FlatSet::new();
    for sc in cmd.get_subcommands() {
        assert!(
            subs.insert(sc.get_name()),
            "Command {}: command name `{}` is duplicated",
            cmd.get_name(),
            sc.get_name()
        );
        for alias in sc.get_all_aliases() {
            assert!(
                subs.insert(alias),
                "Command {}: command `{}` alias `{}` is duplicated",
                cmd.get_name(),
                sc.get_name(),
                alias
            );
        }
    }

    _verify_positionals(cmd);

    #[cfg(feature = "help")]
    if let Some(help_template) = cmd.get_help_template() {
        assert!(
            !help_template.to_string().contains("{flags}"),
            "Command {}: {}",
                    cmd.get_name(),
            "`{flags}` template variable was removed in clap3, they are now included in `{options}`",
        );
        assert!(
            !help_template.to_string().contains("{unified}"),
            "Command {}: {}",
            cmd.get_name(),
            "`{unified}` template variable was removed in clap3, use `{options}` instead"
        );
    }

    cmd._panic_on_missing_help(cmd.is_help_expected_set());
    assert_app_flags(cmd);
}

Report whether Command::next_line_help is set

Examples found in repository?
src/output/help_template.rs (line 110)
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
    pub(crate) fn new(
        writer: &'writer mut StyledStr,
        cmd: &'cmd Command,
        usage: &'cmd Usage<'cmd>,
        use_long: bool,
    ) -> Self {
        debug!(
            "HelpTemplate::new cmd={}, use_long={}",
            cmd.get_name(),
            use_long
        );
        let term_w = match cmd.get_term_width() {
            Some(0) => usize::MAX,
            Some(w) => w,
            None => {
                let (current_width, _h) = dimensions();
                let current_width = current_width.unwrap_or(100);
                let max_width = match cmd.get_max_term_width() {
                    None | Some(0) => usize::MAX,
                    Some(mw) => mw,
                };
                cmp::min(current_width, max_width)
            }
        };
        let next_line_help = cmd.is_next_line_help_set();

        HelpTemplate {
            writer,
            cmd,
            usage,
            next_line_help,
            term_w,
            use_long,
        }
    }

Report whether Command::disable_help_flag is set

Examples found in repository?
src/error/format.rs (line 392)
391
392
393
394
395
396
397
398
399
pub(crate) fn get_help_flag(cmd: &Command) -> Option<&'static str> {
    if !cmd.is_disable_help_flag_set() {
        Some("--help")
    } else if cmd.has_subcommands() && !cmd.is_disable_help_subcommand_set() {
        Some("help")
    } else {
        None
    }
}
More examples
Hide additional examples
src/builder/debug_asserts.rs (line 369)
368
369
370
371
372
373
374
375
376
377
378
379
380
fn duplicate_tip(cmd: &Command, first: &Arg, second: &Arg) -> &'static str {
    if !cmd.is_disable_help_flag_set()
        && (first.get_id() == Id::HELP || second.get_id() == Id::HELP)
    {
        " (call `cmd.disable_help_flag(true)` to remove the auto-generated `--help`)"
    } else if !cmd.is_disable_version_flag_set()
        && (first.get_id() == Id::VERSION || second.get_id() == Id::VERSION)
    {
        " (call `cmd.disable_version_flag(true)` to remove the auto-generated `--version`)"
    } else {
        ""
    }
}
src/builder/command.rs (line 4238)
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
    pub(crate) fn _check_help_and_version(&mut self, expand_help_tree: bool) {
        debug!(
            "Command::_check_help_and_version:{} expand_help_tree={}",
            self.name, expand_help_tree
        );

        self.long_help_exists = self.long_help_exists_();

        if !self.is_disable_help_flag_set() {
            debug!("Command::_check_help_and_version: Building default --help");
            let mut arg = Arg::new(Id::HELP)
                .short('h')
                .long("help")
                .action(ArgAction::Help);
            if self.long_help_exists {
                arg = arg
                    .help("Print help information (use `--help` for more detail)")
                    .long_help("Print help information (use `-h` for a summary)");
            } else {
                arg = arg.help("Print help information");
            }
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }
        if !self.is_disable_version_flag_set() {
            debug!("Command::_check_help_and_version: Building default --version");
            let arg = Arg::new(Id::VERSION)
                .short('V')
                .long("version")
                .action(ArgAction::Version)
                .help("Print version information");
            // Avoiding `arg_internal` to not be sensitive to `next_help_heading` /
            // `next_display_order`
            self.args.push(arg);
        }

        if !self.is_set(AppSettings::DisableHelpSubcommand) {
            debug!("Command::_check_help_and_version: Building help subcommand");
            let help_about = "Print this message or the help of the given subcommand(s)";

            let mut help_subcmd = if expand_help_tree {
                // Slow code path to recursively clone all other subcommand subtrees under help
                let help_subcmd = Command::new("help")
                    .about(help_about)
                    .global_setting(AppSettings::DisableHelpSubcommand)
                    .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));

                let mut help_help_subcmd = Command::new("help").about(help_about);
                help_help_subcmd.version = None;
                help_help_subcmd.long_version = None;
                help_help_subcmd = help_help_subcmd
                    .setting(AppSettings::DisableHelpFlag)
                    .setting(AppSettings::DisableVersionFlag);

                help_subcmd.subcommand(help_help_subcmd)
            } else {
                Command::new("help").about(help_about).arg(
                    Arg::new("subcommand")
                        .action(ArgAction::Append)
                        .num_args(..)
                        .value_name("COMMAND")
                        .help("Print help for the subcommand(s)"),
                )
            };
            self._propagate_subcommand(&mut help_subcmd);

            // The parser acts like this is set, so let's set it so we don't falsely
            // advertise it to the user
            help_subcmd.version = None;
            help_subcmd.long_version = None;
            help_subcmd = help_subcmd
                .setting(AppSettings::DisableHelpFlag)
                .setting(AppSettings::DisableVersionFlag)
                .unset_global_setting(AppSettings::PropagateVersion);

            self.subcommands.push(help_subcmd);
        }
    }

Report whether Command::disable_help_subcommand is set

Examples found in repository?
src/error/format.rs (line 394)
391
392
393
394
395
396
397
398
399
pub(crate) fn get_help_flag(cmd: &Command) -> Option<&'static str> {
    if !cmd.is_disable_help_flag_set() {
        Some("--help")
    } else if cmd.has_subcommands() && !cmd.is_disable_help_subcommand_set() {
        Some("help")
    } else {
        None
    }
}
More examples
Hide additional examples
src/builder/command.rs (line 4169)
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
    pub(crate) fn _propagate_global_args(&mut self) {
        debug!("Command::_propagate_global_args:{}", self.name);

        let autogenerated_help_subcommand = !self.is_disable_help_subcommand_set();

        for sc in &mut self.subcommands {
            if sc.get_name() == "help" && autogenerated_help_subcommand {
                // Avoid propagating args to the autogenerated help subtrees used in completion.
                // This prevents args from showing up during help completions like
                // `myapp help subcmd <TAB>`, which should only suggest subcommands and not args,
                // while still allowing args to show up properly on the generated help message.
                continue;
            }

            for a in self.args.args().filter(|a| a.is_global_set()) {
                if sc.find(&a.id).is_some() {
                    debug!(
                        "Command::_propagate skipping {:?} to {}, already exists",
                        a.id,
                        sc.get_name(),
                    );
                    continue;
                }

                debug!(
                    "Command::_propagate pushing {:?} to {}",
                    a.id,
                    sc.get_name(),
                );
                sc.args.push(a.clone());
            }
        }
    }
src/parser/parser.rs (line 110)
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
    pub(crate) fn get_matches_with(
        &mut self,
        matcher: &mut ArgMatcher,
        raw_args: &mut clap_lex::RawArgs,
        mut args_cursor: clap_lex::ArgCursor,
    ) -> ClapResult<()> {
        debug!("Parser::get_matches_with");
        // Verify all positional assertions pass

        let mut subcmd_name: Option<String> = None;
        let mut keep_state = false;
        let mut parse_state = ParseState::ValuesDone;
        let mut pos_counter = 1;

        // Already met any valid arg(then we shouldn't expect subcommands after it).
        let mut valid_arg_found = false;
        // If the user already passed '--'. Meaning only positional args follow.
        let mut trailing_values = false;

        // Count of positional args
        let positional_count = self
            .cmd
            .get_keymap()
            .keys()
            .filter(|x| x.is_position())
            .count();
        // If any arg sets .last(true)
        let contains_last = self.cmd.get_arguments().any(|x| x.is_last_set());

        while let Some(arg_os) = raw_args.next(&mut args_cursor) {
            // Recover the replaced items if any.
            if let Some(replaced_items) = arg_os
                .to_value()
                .ok()
                .and_then(|a| self.cmd.get_replacement(a))
            {
                debug!(
                    "Parser::get_matches_with: found replacer: {:?}, target: {:?}",
                    arg_os, replaced_items
                );
                raw_args.insert(&args_cursor, replaced_items);
                continue;
            }

            debug!(
                "Parser::get_matches_with: Begin parsing '{:?}' ({:?})",
                arg_os.to_value_os(),
                arg_os.to_value_os().as_raw_bytes()
            );

            // Has the user already passed '--'? Meaning only positional args follow
            if !trailing_values {
                if self.cmd.is_subcommand_precedence_over_arg_set()
                    || !matches!(parse_state, ParseState::Opt(_) | ParseState::Pos(_))
                {
                    // Does the arg match a subcommand name, or any of its aliases (if defined)
                    let sc_name = self.possible_subcommand(arg_os.to_value(), valid_arg_found);
                    debug!("Parser::get_matches_with: sc={:?}", sc_name);
                    if let Some(sc_name) = sc_name {
                        if sc_name == "help" && !self.cmd.is_disable_help_subcommand_set() {
                            ok!(self.parse_help_subcommand(raw_args.remaining(&mut args_cursor)));
                            unreachable!("`parse_help_subcommand` always errors");
                        } else {
                            subcmd_name = Some(sc_name.to_owned());
                        }
                        break;
                    }
                }

                if arg_os.is_escape() {
                    if matches!(&parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if
                        self.cmd[opt].is_allow_hyphen_values_set())
                    {
                        // ParseResult::MaybeHyphenValue, do nothing
                    } else {
                        debug!("Parser::get_matches_with: setting TrailingVals=true");
                        trailing_values = true;
                        matcher.start_trailing();
                        continue;
                    }
                } else if let Some((long_arg, long_value)) = arg_os.to_long() {
                    let parse_result = ok!(self.parse_long_arg(
                        matcher,
                        long_arg,
                        long_value,
                        &parse_state,
                        pos_counter,
                        &mut valid_arg_found,
                    ));
                    debug!(
                        "Parser::get_matches_with: After parse_long_arg {:?}",
                        parse_result
                    );
                    match parse_result {
                        ParseResult::NoArg => {
                            unreachable!("`to_long` always has the flag specified")
                        }
                        ParseResult::ValuesDone => {
                            parse_state = ParseState::ValuesDone;
                            continue;
                        }
                        ParseResult::Opt(id) => {
                            parse_state = ParseState::Opt(id);
                            continue;
                        }
                        ParseResult::FlagSubCommand(name) => {
                            debug!(
                                "Parser::get_matches_with: FlagSubCommand found in long arg {:?}",
                                &name
                            );
                            subcmd_name = Some(name);
                            break;
                        }
                        ParseResult::EqualsNotProvided { arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::no_equals(
                                self.cmd,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::NoMatchingArg { arg } => {
                            let _ = self.resolve_pending(matcher);
                            let remaining_args: Vec<_> =
                                raw_args.remaining(&mut args_cursor).collect();
                            return Err(self.did_you_mean_error(
                                &arg,
                                matcher,
                                &remaining_args,
                                trailing_values,
                            ));
                        }
                        ParseResult::UnneededAttachedValue { rest, used, arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::too_many_values(
                                self.cmd,
                                rest,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&used),
                            ));
                        }
                        ParseResult::MaybeHyphenValue => {
                            // Maybe a hyphen value, do nothing.
                        }
                        ParseResult::AttachedValueNotConsumed => {
                            unreachable!()
                        }
                    }
                } else if let Some(short_arg) = arg_os.to_short() {
                    // Arg looks like a short flag, and not a possible number

                    // Try to parse short args like normal, if allow_hyphen_values or
                    // AllowNegativeNumbers is set, parse_short_arg will *not* throw
                    // an error, and instead return Ok(None)
                    let parse_result = ok!(self.parse_short_arg(
                        matcher,
                        short_arg,
                        &parse_state,
                        pos_counter,
                        &mut valid_arg_found,
                    ));
                    // If it's None, we then check if one of those two AppSettings was set
                    debug!(
                        "Parser::get_matches_with: After parse_short_arg {:?}",
                        parse_result
                    );
                    match parse_result {
                        ParseResult::NoArg => {
                            // Is a single dash `-`, try positional.
                        }
                        ParseResult::ValuesDone => {
                            parse_state = ParseState::ValuesDone;
                            continue;
                        }
                        ParseResult::Opt(id) => {
                            parse_state = ParseState::Opt(id);
                            continue;
                        }
                        ParseResult::FlagSubCommand(name) => {
                            // If there are more short flags to be processed, we should keep the state, and later
                            // revisit the current group of short flags skipping the subcommand.
                            keep_state = self
                                .flag_subcmd_at
                                .map(|at| {
                                    raw_args
                                        .seek(&mut args_cursor, clap_lex::SeekFrom::Current(-1));
                                    // Since we are now saving the current state, the number of flags to skip during state recovery should
                                    // be the current index (`cur_idx`) minus ONE UNIT TO THE LEFT of the starting position.
                                    self.flag_subcmd_skip = self.cur_idx.get() - at + 1;
                                })
                                .is_some();

                            debug!(
                                "Parser::get_matches_with:FlagSubCommandShort: subcmd_name={}, keep_state={}, flag_subcmd_skip={}",
                                name,
                                keep_state,
                                self.flag_subcmd_skip
                            );

                            subcmd_name = Some(name);
                            break;
                        }
                        ParseResult::EqualsNotProvided { arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::no_equals(
                                self.cmd,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::NoMatchingArg { arg } => {
                            let _ = self.resolve_pending(matcher);
                            // We already know it looks like a flag
                            let suggested_trailing_arg =
                                !trailing_values && self.cmd.has_positionals();
                            return Err(ClapError::unknown_argument(
                                self.cmd,
                                arg,
                                None,
                                suggested_trailing_arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::MaybeHyphenValue => {
                            // Maybe a hyphen value, do nothing.
                        }
                        ParseResult::UnneededAttachedValue { .. }
                        | ParseResult::AttachedValueNotConsumed => unreachable!(),
                    }
                }

                if let ParseState::Opt(id) = &parse_state {
                    // Assume this is a value of a previous arg.

                    // get the option so we can check the settings
                    let arg = &self.cmd[id];
                    let parse_result = if let Some(parse_result) =
                        self.check_terminator(arg, arg_os.to_value_os())
                    {
                        parse_result
                    } else {
                        let trailing_values = false;
                        let arg_values = matcher.pending_values_mut(id, None, trailing_values);
                        arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
                        if matcher.needs_more_vals(arg) {
                            ParseResult::Opt(arg.get_id().clone())
                        } else {
                            ParseResult::ValuesDone
                        }
                    };
                    parse_state = match parse_result {
                        ParseResult::Opt(id) => ParseState::Opt(id),
                        ParseResult::ValuesDone => ParseState::ValuesDone,
                        _ => unreachable!(),
                    };
                    // get the next value from the iterator
                    continue;
                }
            }

            // Correct pos_counter.
            pos_counter = {
                let is_second_to_last = pos_counter + 1 == positional_count;

                // The last positional argument, or second to last positional
                // argument may be set to .multiple_values(true) or `.multiple_occurrences(true)`
                let low_index_mults = is_second_to_last
                    && self.cmd.get_positionals().any(|a| {
                        a.is_multiple() && (positional_count != a.get_index().unwrap_or(0))
                    })
                    && self
                        .cmd
                        .get_positionals()
                        .last()
                        .map_or(false, |p_name| !p_name.is_last_set());

                let missing_pos = self.cmd.is_allow_missing_positional_set()
                    && is_second_to_last
                    && !trailing_values;

                debug!(
                    "Parser::get_matches_with: Positional counter...{}",
                    pos_counter
                );
                debug!(
                    "Parser::get_matches_with: Low index multiples...{:?}",
                    low_index_mults
                );

                if low_index_mults || missing_pos {
                    let skip_current = if let Some(n) = raw_args.peek(&args_cursor) {
                        if let Some(arg) = self
                            .cmd
                            .get_positionals()
                            .find(|a| a.get_index() == Some(pos_counter))
                        {
                            // If next value looks like a new_arg or it's a
                            // subcommand, skip positional argument under current
                            // pos_counter(which means current value cannot be a
                            // positional argument with a value next to it), assume
                            // current value matches the next arg.
                            self.is_new_arg(&n, arg)
                                || self
                                    .possible_subcommand(n.to_value(), valid_arg_found)
                                    .is_some()
                        } else {
                            true
                        }
                    } else {
                        true
                    };

                    if skip_current {
                        debug!("Parser::get_matches_with: Bumping the positional counter...");
                        pos_counter + 1
                    } else {
                        pos_counter
                    }
                } else if trailing_values
                    && (self.cmd.is_allow_missing_positional_set() || contains_last)
                {
                    // Came to -- and one positional has .last(true) set, so we go immediately
                    // to the last (highest index) positional
                    debug!("Parser::get_matches_with: .last(true) and --, setting last pos");
                    positional_count
                } else {
                    pos_counter
                }
            };

            if let Some(arg) = self.cmd.get_keymap().get(&pos_counter) {
                if arg.is_last_set() && !trailing_values {
                    let _ = self.resolve_pending(matcher);
                    // Its already considered a positional, we don't need to suggest turning it
                    // into one
                    let suggested_trailing_arg = false;
                    return Err(ClapError::unknown_argument(
                        self.cmd,
                        arg_os.display().to_string(),
                        None,
                        suggested_trailing_arg,
                        Usage::new(self.cmd).create_usage_with_title(&[]),
                    ));
                }

                if arg.is_trailing_var_arg_set() {
                    trailing_values = true;
                }

                if matcher.pending_arg_id() != Some(arg.get_id()) || !arg.is_multiple_values_set() {
                    ok!(self.resolve_pending(matcher));
                }
                if let Some(_parse_result) = self.check_terminator(arg, arg_os.to_value_os()) {
                    debug!(
                        "Parser::get_matches_with: ignoring terminator result {:?}",
                        _parse_result
                    );
                } else {
                    let arg_values = matcher.pending_values_mut(
                        arg.get_id(),
                        Some(Identifier::Index),
                        trailing_values,
                    );
                    arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
                }

                // Only increment the positional counter if it doesn't allow multiples
                if !arg.is_multiple() {
                    pos_counter += 1;
                    parse_state = ParseState::ValuesDone;
                } else {
                    parse_state = ParseState::Pos(arg.get_id().clone());
                }
                valid_arg_found = true;
            } else if let Some(external_parser) =
                self.cmd.get_external_subcommand_value_parser().cloned()
            {
                // Get external subcommand name
                let sc_name = match arg_os.to_value() {
                    Ok(s) => s.to_owned(),
                    Err(_) => {
                        let _ = self.resolve_pending(matcher);
                        return Err(ClapError::invalid_utf8(
                            self.cmd,
                            Usage::new(self.cmd).create_usage_with_title(&[]),
                        ));
                    }
                };

                // Collect the external subcommand args
                let mut sc_m = ArgMatcher::new(self.cmd);
                sc_m.start_occurrence_of_external(self.cmd);

                for raw_val in raw_args.remaining(&mut args_cursor) {
                    let val = ok!(external_parser.parse_ref(self.cmd, None, raw_val));
                    let external_id = Id::from_static_ref(Id::EXTERNAL);
                    sc_m.add_val_to(&external_id, val, raw_val.to_os_string());
                }

                matcher.subcommand(SubCommand {
                    name: sc_name,
                    matches: sc_m.into_inner(),
                });

                ok!(self.resolve_pending(matcher));
                #[cfg(feature = "env")]
                ok!(self.add_env(matcher));
                ok!(self.add_defaults(matcher));
                return Validator::new(self.cmd).validate(parse_state, matcher);
            } else {
                // Start error processing
                let _ = self.resolve_pending(matcher);
                return Err(self.match_arg_error(&arg_os, valid_arg_found, trailing_values));
            }
        }

        if let Some(ref pos_sc_name) = subcmd_name {
            let sc_name = self
                .cmd
                .find_subcommand(pos_sc_name)
                .expect(INTERNAL_ERROR_MSG)
                .get_name()
                .to_owned();
            ok!(self.parse_subcommand(&sc_name, matcher, raw_args, args_cursor, keep_state));
        }

        ok!(self.resolve_pending(matcher));
        #[cfg(feature = "env")]
        ok!(self.add_env(matcher));
        ok!(self.add_defaults(matcher));
        Validator::new(self.cmd).validate(parse_state, matcher)
    }

Report whether Command::disable_colored_help is set

Examples found in repository?
src/builder/command.rs (line 4615)
4613
4614
4615
4616
4617
4618
4619
4620
    pub(crate) fn color_help(&self) -> ColorChoice {
        #[cfg(feature = "color")]
        if self.is_disable_colored_help_set() {
            return ColorChoice::Never;
        }

        self.get_color()
    }

Report whether Command::arg_required_else_help is set

Examples found in repository?
src/parser/validator.rs (line 55)
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
    pub(crate) fn validate(
        &mut self,
        parse_state: ParseState,
        matcher: &mut ArgMatcher,
    ) -> ClapResult<()> {
        debug!("Validator::validate");
        let mut conflicts = Conflicts::new();
        let has_subcmd = matcher.subcommand_name().is_some();

        if let ParseState::Opt(a) = parse_state {
            debug!("Validator::validate: needs_val_of={:?}", a);

            let o = &self.cmd[&a];
            let should_err = if let Some(v) = matcher.args.get(o.get_id()) {
                v.all_val_groups_empty() && o.get_min_vals() != 0
            } else {
                true
            };
            if should_err {
                return Err(Error::empty_value(
                    self.cmd,
                    &get_possible_values_cli(o)
                        .iter()
                        .filter(|pv| !pv.is_hide_set())
                        .map(|n| n.get_name().to_owned())
                        .collect::<Vec<_>>(),
                    o.to_string(),
                ));
            }
        }

        if !has_subcmd && self.cmd.is_arg_required_else_help_set() {
            let num_user_values = matcher
                .arg_ids()
                .filter(|arg_id| matcher.check_explicit(arg_id, &ArgPredicate::IsPresent))
                .count();
            if num_user_values == 0 {
                let message = self.cmd.write_help_err(false);
                return Err(Error::display_help_error(self.cmd, message));
            }
        }
        if !has_subcmd && self.cmd.is_subcommand_required_set() {
            let bn = self
                .cmd
                .get_bin_name()
                .unwrap_or_else(|| self.cmd.get_name());
            return Err(Error::missing_subcommand(
                self.cmd,
                bn.to_string(),
                self.cmd
                    .all_subcommand_names()
                    .map(|s| s.to_owned())
                    .collect::<Vec<_>>(),
                Usage::new(self.cmd)
                    .required(&self.required)
                    .create_usage_with_title(&[]),
            ));
        }

        ok!(self.validate_conflicts(matcher, &mut conflicts));
        if !(self.cmd.is_subcommand_negates_reqs_set() && has_subcmd) {
            ok!(self.validate_required(matcher, &mut conflicts));
        }

        Ok(())
    }

Report whether Command::allow_missing_positional is set

Examples found in repository?
src/parser/validator.rs (line 354)
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
    fn validate_required(
        &mut self,
        matcher: &ArgMatcher,
        conflicts: &mut Conflicts,
    ) -> ClapResult<()> {
        debug!("Validator::validate_required: required={:?}", self.required);
        self.gather_requires(matcher);

        let mut missing_required = Vec::new();
        let mut highest_index = 0;

        let is_exclusive_present = matcher
            .arg_ids()
            .filter(|arg_id| matcher.check_explicit(arg_id, &ArgPredicate::IsPresent))
            .any(|id| {
                self.cmd
                    .find(id)
                    .map(|arg| arg.is_exclusive_set())
                    .unwrap_or_default()
            });
        debug!(
            "Validator::validate_required: is_exclusive_present={}",
            is_exclusive_present
        );

        for arg_or_group in self
            .required
            .iter()
            .filter(|r| !matcher.check_explicit(r, &ArgPredicate::IsPresent))
        {
            debug!("Validator::validate_required:iter:aog={:?}", arg_or_group);
            if let Some(arg) = self.cmd.find(arg_or_group) {
                debug!("Validator::validate_required:iter: This is an arg");
                if !is_exclusive_present && !self.is_missing_required_ok(arg, matcher, conflicts) {
                    debug!(
                        "Validator::validate_required:iter: Missing {:?}",
                        arg.get_id()
                    );
                    missing_required.push(arg.get_id().clone());
                    if !arg.is_last_set() {
                        highest_index = highest_index.max(arg.get_index().unwrap_or(0));
                    }
                }
            } else if let Some(group) = self.cmd.find_group(arg_or_group) {
                debug!("Validator::validate_required:iter: This is a group");
                if !self
                    .cmd
                    .unroll_args_in_group(&group.id)
                    .iter()
                    .any(|a| matcher.check_explicit(a, &ArgPredicate::IsPresent))
                {
                    debug!(
                        "Validator::validate_required:iter: Missing {:?}",
                        group.get_id()
                    );
                    missing_required.push(group.get_id().clone());
                }
            }
        }

        // Validate the conditionally required args
        for a in self
            .cmd
            .get_arguments()
            .filter(|a| !matcher.check_explicit(a.get_id(), &ArgPredicate::IsPresent))
        {
            let mut required = false;

            for (other, val) in &a.r_ifs {
                if matcher.check_explicit(other, &ArgPredicate::Equals(val.into())) {
                    debug!(
                        "Validator::validate_required:iter: Missing {:?}",
                        a.get_id()
                    );
                    required = true;
                }
            }

            let match_all = a.r_ifs_all.iter().all(|(other, val)| {
                matcher.check_explicit(other, &ArgPredicate::Equals(val.into()))
            });
            if match_all && !a.r_ifs_all.is_empty() {
                debug!(
                    "Validator::validate_required:iter: Missing {:?}",
                    a.get_id()
                );
                required = true;
            }

            if (!a.r_unless.is_empty() || !a.r_unless_all.is_empty())
                && self.fails_arg_required_unless(a, matcher)
            {
                debug!(
                    "Validator::validate_required:iter: Missing {:?}",
                    a.get_id()
                );
                required = true;
            }

            if required {
                missing_required.push(a.get_id().clone());
                if !a.is_last_set() {
                    highest_index = highest_index.max(a.get_index().unwrap_or(0));
                }
            }
        }

        // For display purposes, include all of the preceding positional arguments
        if !self.cmd.is_allow_missing_positional_set() {
            for pos in self
                .cmd
                .get_positionals()
                .filter(|a| !matcher.check_explicit(a.get_id(), &ArgPredicate::IsPresent))
            {
                if pos.get_index() < Some(highest_index) {
                    debug!(
                        "Validator::validate_required:iter: Missing {:?}",
                        pos.get_id()
                    );
                    missing_required.push(pos.get_id().clone());
                }
            }
        }

        if !missing_required.is_empty() {
            ok!(self.missing_required_error(matcher, missing_required));
        }

        Ok(())
    }
More examples
Hide additional examples
src/builder/debug_asserts.rs (line 614)
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
fn _verify_positionals(cmd: &Command) -> bool {
    debug!("Command::_verify_positionals");
    // Because you must wait until all arguments have been supplied, this is the first chance
    // to make assertions on positional argument indexes
    //
    // First we verify that the index highest supplied index, is equal to the number of
    // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3
    // but no 2)

    let highest_idx = cmd
        .get_keymap()
        .keys()
        .filter_map(|x| {
            if let KeyType::Position(n) = x {
                Some(*n)
            } else {
                None
            }
        })
        .max()
        .unwrap_or(0);

    let num_p = cmd.get_keymap().keys().filter(|x| x.is_position()).count();

    assert!(
        highest_idx == num_p,
        "Found positional argument whose index is {} but there \
             are only {} positional arguments defined",
        highest_idx,
        num_p
    );

    for arg in cmd.get_arguments() {
        if arg.index.unwrap_or(0) == highest_idx {
            assert!(
                !arg.is_trailing_var_arg_set() || !arg.is_last_set(),
                "{}:{}: `Arg::trailing_var_arg` and `Arg::last` cannot be used together",
                cmd.get_name(),
                arg.get_id()
            );

            if arg.is_trailing_var_arg_set() {
                assert!(
                    arg.is_multiple(),
                    "{}:{}: `Arg::trailing_var_arg` must accept multiple values",
                    cmd.get_name(),
                    arg.get_id()
                );
            }
        } else {
            assert!(
                !arg.is_trailing_var_arg_set(),
                "{}:{}: `Arg::trailing_var_arg` can only apply to last positional",
                cmd.get_name(),
                arg.get_id()
            );
        }
    }

    // Next we verify that only the highest index has takes multiple arguments (if any)
    let only_highest = |a: &Arg| a.is_multiple() && (a.get_index().unwrap_or(0) != highest_idx);
    if cmd.get_positionals().any(only_highest) {
        // First we make sure if there is a positional that allows multiple values
        // the one before it (second to last) has one of these:
        //  * a value terminator
        //  * ArgSettings::Last
        //  * The last arg is Required

        // We can't pass the closure (it.next()) to the macro directly because each call to
        // find() (iterator, not macro) gets called repeatedly.
        let last = &cmd.get_keymap()[&KeyType::Position(highest_idx)];
        let second_to_last = &cmd.get_keymap()[&KeyType::Position(highest_idx - 1)];

        // Either the final positional is required
        // Or the second to last has a terminator or .last(true) set
        let ok = last.is_required_set()
            || (second_to_last.terminator.is_some() || second_to_last.is_last_set())
            || last.is_last_set();
        assert!(
            ok,
            "When using a positional argument with `.num_args(1..)` that is *not the \
                 last* positional argument, the last positional argument (i.e. the one \
                 with the highest index) *must* have .required(true) or .last(true) set."
        );

        // We make sure if the second to last is Multiple the last is ArgSettings::Last
        let ok = second_to_last.is_multiple() || last.is_last_set();
        assert!(
            ok,
            "Only the last positional argument, or second to last positional \
                 argument may be set to `.num_args(1..)`"
        );

        // Next we check how many have both Multiple and not a specific number of values set
        let count = cmd
            .get_positionals()
            .filter(|p| {
                p.is_multiple_values_set()
                    && !p.get_num_args().expect(INTERNAL_ERROR_MSG).is_fixed()
            })
            .count();
        let ok = count <= 1
            || (last.is_last_set()
                && last.is_multiple()
                && second_to_last.is_multiple()
                && count == 2);
        assert!(
            ok,
            "Only one positional argument with `.num_args(1..)` set is allowed per \
                 command, unless the second one also has .last(true) set"
        );
    }

    let mut found = false;

    if cmd.is_allow_missing_positional_set() {
        // Check that if a required positional argument is found, all positions with a lower
        // index are also required.
        let mut foundx2 = false;

        for p in cmd.get_positionals() {
            if foundx2 && !p.is_required_set() {
                assert!(
                    p.is_required_set(),
                    "Found non-required positional argument with a lower \
                         index than a required positional argument by two or more: {:?} \
                         index {:?}",
                    p.get_id(),
                    p.get_index()
                );
            } else if p.is_required_set() && !p.is_last_set() {
                // Args that .last(true) don't count since they can be required and have
                // positionals with a lower index that aren't required
                // Imagine: prog <req1> [opt1] -- <req2>
                // Both of these are valid invocations:
                //      $ prog r1 -- r2
                //      $ prog r1 o1 -- r2
                if found {
                    foundx2 = true;
                    continue;
                }
                found = true;
                continue;
            } else {
                found = false;
            }
        }
    } else {
        // Check that if a required positional argument is found, all positions with a lower
        // index are also required
        for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) {
            if found {
                assert!(
                    p.is_required_set(),
                    "Found non-required positional argument with a lower \
                         index than a required positional argument: {:?} index {:?}",
                    p.get_id(),
                    p.get_index()
                );
            } else if p.is_required_set() && !p.is_last_set() {
                // Args that .last(true) don't count since they can be required and have
                // positionals with a lower index that aren't required
                // Imagine: prog <req1> [opt1] -- <req2>
                // Both of these are valid invocations:
                //      $ prog r1 -- r2
                //      $ prog r1 o1 -- r2
                found = true;
                continue;
            }
        }
    }
    assert!(
        cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2,
        "Only one positional argument may have last(true) set. Found two."
    );
    if cmd
        .get_positionals()
        .any(|p| p.is_last_set() && p.is_required_set())
        && cmd.has_subcommands()
        && !cmd.is_subcommand_negates_reqs_set()
    {
        panic!(
            "Having a required positional argument with .last(true) set *and* child \
                 subcommands without setting SubcommandsNegateReqs isn't compatible."
        );
    }

    true
}
src/parser/parser.rs (line 327)
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
    pub(crate) fn get_matches_with(
        &mut self,
        matcher: &mut ArgMatcher,
        raw_args: &mut clap_lex::RawArgs,
        mut args_cursor: clap_lex::ArgCursor,
    ) -> ClapResult<()> {
        debug!("Parser::get_matches_with");
        // Verify all positional assertions pass

        let mut subcmd_name: Option<String> = None;
        let mut keep_state = false;
        let mut parse_state = ParseState::ValuesDone;
        let mut pos_counter = 1;

        // Already met any valid arg(then we shouldn't expect subcommands after it).
        let mut valid_arg_found = false;
        // If the user already passed '--'. Meaning only positional args follow.
        let mut trailing_values = false;

        // Count of positional args
        let positional_count = self
            .cmd
            .get_keymap()
            .keys()
            .filter(|x| x.is_position())
            .count();
        // If any arg sets .last(true)
        let contains_last = self.cmd.get_arguments().any(|x| x.is_last_set());

        while let Some(arg_os) = raw_args.next(&mut args_cursor) {
            // Recover the replaced items if any.
            if let Some(replaced_items) = arg_os
                .to_value()
                .ok()
                .and_then(|a| self.cmd.get_replacement(a))
            {
                debug!(
                    "Parser::get_matches_with: found replacer: {:?}, target: {:?}",
                    arg_os, replaced_items
                );
                raw_args.insert(&args_cursor, replaced_items);
                continue;
            }

            debug!(
                "Parser::get_matches_with: Begin parsing '{:?}' ({:?})",
                arg_os.to_value_os(),
                arg_os.to_value_os().as_raw_bytes()
            );

            // Has the user already passed '--'? Meaning only positional args follow
            if !trailing_values {
                if self.cmd.is_subcommand_precedence_over_arg_set()
                    || !matches!(parse_state, ParseState::Opt(_) | ParseState::Pos(_))
                {
                    // Does the arg match a subcommand name, or any of its aliases (if defined)
                    let sc_name = self.possible_subcommand(arg_os.to_value(), valid_arg_found);
                    debug!("Parser::get_matches_with: sc={:?}", sc_name);
                    if let Some(sc_name) = sc_name {
                        if sc_name == "help" && !self.cmd.is_disable_help_subcommand_set() {
                            ok!(self.parse_help_subcommand(raw_args.remaining(&mut args_cursor)));
                            unreachable!("`parse_help_subcommand` always errors");
                        } else {
                            subcmd_name = Some(sc_name.to_owned());
                        }
                        break;
                    }
                }

                if arg_os.is_escape() {
                    if matches!(&parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if
                        self.cmd[opt].is_allow_hyphen_values_set())
                    {
                        // ParseResult::MaybeHyphenValue, do nothing
                    } else {
                        debug!("Parser::get_matches_with: setting TrailingVals=true");
                        trailing_values = true;
                        matcher.start_trailing();
                        continue;
                    }
                } else if let Some((long_arg, long_value)) = arg_os.to_long() {
                    let parse_result = ok!(self.parse_long_arg(
                        matcher,
                        long_arg,
                        long_value,
                        &parse_state,
                        pos_counter,
                        &mut valid_arg_found,
                    ));
                    debug!(
                        "Parser::get_matches_with: After parse_long_arg {:?}",
                        parse_result
                    );
                    match parse_result {
                        ParseResult::NoArg => {
                            unreachable!("`to_long` always has the flag specified")
                        }
                        ParseResult::ValuesDone => {
                            parse_state = ParseState::ValuesDone;
                            continue;
                        }
                        ParseResult::Opt(id) => {
                            parse_state = ParseState::Opt(id);
                            continue;
                        }
                        ParseResult::FlagSubCommand(name) => {
                            debug!(
                                "Parser::get_matches_with: FlagSubCommand found in long arg {:?}",
                                &name
                            );
                            subcmd_name = Some(name);
                            break;
                        }
                        ParseResult::EqualsNotProvided { arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::no_equals(
                                self.cmd,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::NoMatchingArg { arg } => {
                            let _ = self.resolve_pending(matcher);
                            let remaining_args: Vec<_> =
                                raw_args.remaining(&mut args_cursor).collect();
                            return Err(self.did_you_mean_error(
                                &arg,
                                matcher,
                                &remaining_args,
                                trailing_values,
                            ));
                        }
                        ParseResult::UnneededAttachedValue { rest, used, arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::too_many_values(
                                self.cmd,
                                rest,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&used),
                            ));
                        }
                        ParseResult::MaybeHyphenValue => {
                            // Maybe a hyphen value, do nothing.
                        }
                        ParseResult::AttachedValueNotConsumed => {
                            unreachable!()
                        }
                    }
                } else if let Some(short_arg) = arg_os.to_short() {
                    // Arg looks like a short flag, and not a possible number

                    // Try to parse short args like normal, if allow_hyphen_values or
                    // AllowNegativeNumbers is set, parse_short_arg will *not* throw
                    // an error, and instead return Ok(None)
                    let parse_result = ok!(self.parse_short_arg(
                        matcher,
                        short_arg,
                        &parse_state,
                        pos_counter,
                        &mut valid_arg_found,
                    ));
                    // If it's None, we then check if one of those two AppSettings was set
                    debug!(
                        "Parser::get_matches_with: After parse_short_arg {:?}",
                        parse_result
                    );
                    match parse_result {
                        ParseResult::NoArg => {
                            // Is a single dash `-`, try positional.
                        }
                        ParseResult::ValuesDone => {
                            parse_state = ParseState::ValuesDone;
                            continue;
                        }
                        ParseResult::Opt(id) => {
                            parse_state = ParseState::Opt(id);
                            continue;
                        }
                        ParseResult::FlagSubCommand(name) => {
                            // If there are more short flags to be processed, we should keep the state, and later
                            // revisit the current group of short flags skipping the subcommand.
                            keep_state = self
                                .flag_subcmd_at
                                .map(|at| {
                                    raw_args
                                        .seek(&mut args_cursor, clap_lex::SeekFrom::Current(-1));
                                    // Since we are now saving the current state, the number of flags to skip during state recovery should
                                    // be the current index (`cur_idx`) minus ONE UNIT TO THE LEFT of the starting position.
                                    self.flag_subcmd_skip = self.cur_idx.get() - at + 1;
                                })
                                .is_some();

                            debug!(
                                "Parser::get_matches_with:FlagSubCommandShort: subcmd_name={}, keep_state={}, flag_subcmd_skip={}",
                                name,
                                keep_state,
                                self.flag_subcmd_skip
                            );

                            subcmd_name = Some(name);
                            break;
                        }
                        ParseResult::EqualsNotProvided { arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::no_equals(
                                self.cmd,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::NoMatchingArg { arg } => {
                            let _ = self.resolve_pending(matcher);
                            // We already know it looks like a flag
                            let suggested_trailing_arg =
                                !trailing_values && self.cmd.has_positionals();
                            return Err(ClapError::unknown_argument(
                                self.cmd,
                                arg,
                                None,
                                suggested_trailing_arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::MaybeHyphenValue => {
                            // Maybe a hyphen value, do nothing.
                        }
                        ParseResult::UnneededAttachedValue { .. }
                        | ParseResult::AttachedValueNotConsumed => unreachable!(),
                    }
                }

                if let ParseState::Opt(id) = &parse_state {
                    // Assume this is a value of a previous arg.

                    // get the option so we can check the settings
                    let arg = &self.cmd[id];
                    let parse_result = if let Some(parse_result) =
                        self.check_terminator(arg, arg_os.to_value_os())
                    {
                        parse_result
                    } else {
                        let trailing_values = false;
                        let arg_values = matcher.pending_values_mut(id, None, trailing_values);
                        arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
                        if matcher.needs_more_vals(arg) {
                            ParseResult::Opt(arg.get_id().clone())
                        } else {
                            ParseResult::ValuesDone
                        }
                    };
                    parse_state = match parse_result {
                        ParseResult::Opt(id) => ParseState::Opt(id),
                        ParseResult::ValuesDone => ParseState::ValuesDone,
                        _ => unreachable!(),
                    };
                    // get the next value from the iterator
                    continue;
                }
            }

            // Correct pos_counter.
            pos_counter = {
                let is_second_to_last = pos_counter + 1 == positional_count;

                // The last positional argument, or second to last positional
                // argument may be set to .multiple_values(true) or `.multiple_occurrences(true)`
                let low_index_mults = is_second_to_last
                    && self.cmd.get_positionals().any(|a| {
                        a.is_multiple() && (positional_count != a.get_index().unwrap_or(0))
                    })
                    && self
                        .cmd
                        .get_positionals()
                        .last()
                        .map_or(false, |p_name| !p_name.is_last_set());

                let missing_pos = self.cmd.is_allow_missing_positional_set()
                    && is_second_to_last
                    && !trailing_values;

                debug!(
                    "Parser::get_matches_with: Positional counter...{}",
                    pos_counter
                );
                debug!(
                    "Parser::get_matches_with: Low index multiples...{:?}",
                    low_index_mults
                );

                if low_index_mults || missing_pos {
                    let skip_current = if let Some(n) = raw_args.peek(&args_cursor) {
                        if let Some(arg) = self
                            .cmd
                            .get_positionals()
                            .find(|a| a.get_index() == Some(pos_counter))
                        {
                            // If next value looks like a new_arg or it's a
                            // subcommand, skip positional argument under current
                            // pos_counter(which means current value cannot be a
                            // positional argument with a value next to it), assume
                            // current value matches the next arg.
                            self.is_new_arg(&n, arg)
                                || self
                                    .possible_subcommand(n.to_value(), valid_arg_found)
                                    .is_some()
                        } else {
                            true
                        }
                    } else {
                        true
                    };

                    if skip_current {
                        debug!("Parser::get_matches_with: Bumping the positional counter...");
                        pos_counter + 1
                    } else {
                        pos_counter
                    }
                } else if trailing_values
                    && (self.cmd.is_allow_missing_positional_set() || contains_last)
                {
                    // Came to -- and one positional has .last(true) set, so we go immediately
                    // to the last (highest index) positional
                    debug!("Parser::get_matches_with: .last(true) and --, setting last pos");
                    positional_count
                } else {
                    pos_counter
                }
            };

            if let Some(arg) = self.cmd.get_keymap().get(&pos_counter) {
                if arg.is_last_set() && !trailing_values {
                    let _ = self.resolve_pending(matcher);
                    // Its already considered a positional, we don't need to suggest turning it
                    // into one
                    let suggested_trailing_arg = false;
                    return Err(ClapError::unknown_argument(
                        self.cmd,
                        arg_os.display().to_string(),
                        None,
                        suggested_trailing_arg,
                        Usage::new(self.cmd).create_usage_with_title(&[]),
                    ));
                }

                if arg.is_trailing_var_arg_set() {
                    trailing_values = true;
                }

                if matcher.pending_arg_id() != Some(arg.get_id()) || !arg.is_multiple_values_set() {
                    ok!(self.resolve_pending(matcher));
                }
                if let Some(_parse_result) = self.check_terminator(arg, arg_os.to_value_os()) {
                    debug!(
                        "Parser::get_matches_with: ignoring terminator result {:?}",
                        _parse_result
                    );
                } else {
                    let arg_values = matcher.pending_values_mut(
                        arg.get_id(),
                        Some(Identifier::Index),
                        trailing_values,
                    );
                    arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
                }

                // Only increment the positional counter if it doesn't allow multiples
                if !arg.is_multiple() {
                    pos_counter += 1;
                    parse_state = ParseState::ValuesDone;
                } else {
                    parse_state = ParseState::Pos(arg.get_id().clone());
                }
                valid_arg_found = true;
            } else if let Some(external_parser) =
                self.cmd.get_external_subcommand_value_parser().cloned()
            {
                // Get external subcommand name
                let sc_name = match arg_os.to_value() {
                    Ok(s) => s.to_owned(),
                    Err(_) => {
                        let _ = self.resolve_pending(matcher);
                        return Err(ClapError::invalid_utf8(
                            self.cmd,
                            Usage::new(self.cmd).create_usage_with_title(&[]),
                        ));
                    }
                };

                // Collect the external subcommand args
                let mut sc_m = ArgMatcher::new(self.cmd);
                sc_m.start_occurrence_of_external(self.cmd);

                for raw_val in raw_args.remaining(&mut args_cursor) {
                    let val = ok!(external_parser.parse_ref(self.cmd, None, raw_val));
                    let external_id = Id::from_static_ref(Id::EXTERNAL);
                    sc_m.add_val_to(&external_id, val, raw_val.to_os_string());
                }

                matcher.subcommand(SubCommand {
                    name: sc_name,
                    matches: sc_m.into_inner(),
                });

                ok!(self.resolve_pending(matcher));
                #[cfg(feature = "env")]
                ok!(self.add_env(matcher));
                ok!(self.add_defaults(matcher));
                return Validator::new(self.cmd).validate(parse_state, matcher);
            } else {
                // Start error processing
                let _ = self.resolve_pending(matcher);
                return Err(self.match_arg_error(&arg_os, valid_arg_found, trailing_values));
            }
        }

        if let Some(ref pos_sc_name) = subcmd_name {
            let sc_name = self
                .cmd
                .find_subcommand(pos_sc_name)
                .expect(INTERNAL_ERROR_MSG)
                .get_name()
                .to_owned();
            ok!(self.parse_subcommand(&sc_name, matcher, raw_args, args_cursor, keep_state));
        }

        ok!(self.resolve_pending(matcher));
        #[cfg(feature = "env")]
        ok!(self.add_env(matcher));
        ok!(self.add_defaults(matcher));
        Validator::new(self.cmd).validate(parse_state, matcher)
    }

Report whether Command::hide is set

Examples found in repository?
src/output/help_template.rs (line 1014)
1013
1014
1015
fn should_show_subcommand(subcommand: &Command) -> bool {
    !subcommand.is_hide_set()
}
More examples
Hide additional examples
src/builder/command.rs (line 4312)
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
    fn _copy_subtree_for_help(&self) -> Command {
        let mut cmd = Command::new(self.name.clone())
            .hide(self.is_hide_set())
            .global_setting(AppSettings::DisableHelpFlag)
            .global_setting(AppSettings::DisableVersionFlag)
            .subcommands(self.get_subcommands().map(Command::_copy_subtree_for_help));
        if self.get_about().is_some() {
            cmd = cmd.about(self.get_about().unwrap().clone());
        }
        cmd
    }

Report whether Command::subcommand_required is set

Examples found in repository?
src/output/usage.rs (line 111)
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
    fn create_help_usage(&self, incl_reqs: bool) -> StyledStr {
        debug!("Usage::create_help_usage; incl_reqs={:?}", incl_reqs);
        let mut styled = StyledStr::new();
        let name = self
            .cmd
            .get_usage_name()
            .or_else(|| self.cmd.get_bin_name())
            .unwrap_or_else(|| self.cmd.get_name());
        styled.literal(name);

        if self.needs_options_tag() {
            styled.placeholder(" [OPTIONS]");
        }

        self.write_args(&[], !incl_reqs, &mut styled);

        // incl_reqs is only false when this function is called recursively
        if self.cmd.has_visible_subcommands() && incl_reqs
            || self.cmd.is_allow_external_subcommands_set()
        {
            let placeholder = self
                .cmd
                .get_subcommand_value_name()
                .unwrap_or(DEFAULT_SUB_VALUE_NAME);
            if self.cmd.is_subcommand_negates_reqs_set()
                || self.cmd.is_args_conflicts_with_subcommands_set()
            {
                styled.none("\n");
                styled.none("       ");
                if self.cmd.is_args_conflicts_with_subcommands_set() {
                    // Short-circuit full usage creation since no args will be relevant
                    styled.literal(name);
                } else {
                    styled.extend(self.create_help_usage(false).into_iter());
                }
                styled.placeholder(" <");
                styled.placeholder(placeholder);
                styled.placeholder(">");
            } else if self.cmd.is_subcommand_required_set() {
                styled.placeholder(" <");
                styled.placeholder(placeholder);
                styled.placeholder(">");
            } else {
                styled.placeholder(" [");
                styled.placeholder(placeholder);
                styled.placeholder("]");
            }
        }
        styled.trim();
        debug!("Usage::create_help_usage: usage={}", styled);
        styled
    }

    // Creates a context aware usage string, or "smart usage" from currently used
    // args, and requirements
    fn create_smart_usage(&self, used: &[Id]) -> StyledStr {
        debug!("Usage::create_smart_usage");
        let mut styled = StyledStr::new();

        styled.literal(
            self.cmd
                .get_usage_name()
                .or_else(|| self.cmd.get_bin_name())
                .unwrap_or_else(|| self.cmd.get_name()),
        );

        self.write_args(used, false, &mut styled);

        if self.cmd.is_subcommand_required_set() {
            styled.placeholder(" <");
            styled.placeholder(
                self.cmd
                    .get_subcommand_value_name()
                    .unwrap_or(DEFAULT_SUB_VALUE_NAME),
            );
            styled.placeholder(">");
        }
        styled
    }
More examples
Hide additional examples
src/parser/validator.rs (line 65)
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
    pub(crate) fn validate(
        &mut self,
        parse_state: ParseState,
        matcher: &mut ArgMatcher,
    ) -> ClapResult<()> {
        debug!("Validator::validate");
        let mut conflicts = Conflicts::new();
        let has_subcmd = matcher.subcommand_name().is_some();

        if let ParseState::Opt(a) = parse_state {
            debug!("Validator::validate: needs_val_of={:?}", a);

            let o = &self.cmd[&a];
            let should_err = if let Some(v) = matcher.args.get(o.get_id()) {
                v.all_val_groups_empty() && o.get_min_vals() != 0
            } else {
                true
            };
            if should_err {
                return Err(Error::empty_value(
                    self.cmd,
                    &get_possible_values_cli(o)
                        .iter()
                        .filter(|pv| !pv.is_hide_set())
                        .map(|n| n.get_name().to_owned())
                        .collect::<Vec<_>>(),
                    o.to_string(),
                ));
            }
        }

        if !has_subcmd && self.cmd.is_arg_required_else_help_set() {
            let num_user_values = matcher
                .arg_ids()
                .filter(|arg_id| matcher.check_explicit(arg_id, &ArgPredicate::IsPresent))
                .count();
            if num_user_values == 0 {
                let message = self.cmd.write_help_err(false);
                return Err(Error::display_help_error(self.cmd, message));
            }
        }
        if !has_subcmd && self.cmd.is_subcommand_required_set() {
            let bn = self
                .cmd
                .get_bin_name()
                .unwrap_or_else(|| self.cmd.get_name());
            return Err(Error::missing_subcommand(
                self.cmd,
                bn.to_string(),
                self.cmd
                    .all_subcommand_names()
                    .map(|s| s.to_owned())
                    .collect::<Vec<_>>(),
                Usage::new(self.cmd)
                    .required(&self.required)
                    .create_usage_with_title(&[]),
            ));
        }

        ok!(self.validate_conflicts(matcher, &mut conflicts));
        if !(self.cmd.is_subcommand_negates_reqs_set() && has_subcmd) {
            ok!(self.validate_required(matcher, &mut conflicts));
        }

        Ok(())
    }
Examples found in repository?
src/builder/command.rs (line 3700)
3699
3700
3701
3702
3703
3704
3705
3706
    pub fn get_external_subcommand_value_parser(&self) -> Option<&super::ValueParser> {
        if !self.is_allow_external_subcommands_set() {
            None
        } else {
            static DEFAULT: super::ValueParser = super::ValueParser::os_string();
            Some(self.external_value_parser.as_ref().unwrap_or(&DEFAULT))
        }
    }
More examples
Hide additional examples
src/output/usage.rs (line 91)
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
    fn create_help_usage(&self, incl_reqs: bool) -> StyledStr {
        debug!("Usage::create_help_usage; incl_reqs={:?}", incl_reqs);
        let mut styled = StyledStr::new();
        let name = self
            .cmd
            .get_usage_name()
            .or_else(|| self.cmd.get_bin_name())
            .unwrap_or_else(|| self.cmd.get_name());
        styled.literal(name);

        if self.needs_options_tag() {
            styled.placeholder(" [OPTIONS]");
        }

        self.write_args(&[], !incl_reqs, &mut styled);

        // incl_reqs is only false when this function is called recursively
        if self.cmd.has_visible_subcommands() && incl_reqs
            || self.cmd.is_allow_external_subcommands_set()
        {
            let placeholder = self
                .cmd
                .get_subcommand_value_name()
                .unwrap_or(DEFAULT_SUB_VALUE_NAME);
            if self.cmd.is_subcommand_negates_reqs_set()
                || self.cmd.is_args_conflicts_with_subcommands_set()
            {
                styled.none("\n");
                styled.none("       ");
                if self.cmd.is_args_conflicts_with_subcommands_set() {
                    // Short-circuit full usage creation since no args will be relevant
                    styled.literal(name);
                } else {
                    styled.extend(self.create_help_usage(false).into_iter());
                }
                styled.placeholder(" <");
                styled.placeholder(placeholder);
                styled.placeholder(">");
            } else if self.cmd.is_subcommand_required_set() {
                styled.placeholder(" <");
                styled.placeholder(placeholder);
                styled.placeholder(">");
            } else {
                styled.placeholder(" [");
                styled.placeholder(placeholder);
                styled.placeholder("]");
            }
        }
        styled.trim();
        debug!("Usage::create_help_usage: usage={}", styled);
        styled
    }

Configured parser for values passed to an external subcommand

Example
let cmd = clap::Command::new("raw")
    .external_subcommand_value_parser(clap::value_parser!(String));
let value_parser = cmd.get_external_subcommand_value_parser();
println!("{:?}", value_parser);
Examples found in repository?
src/parser/matches/matched_arg.rs (line 56)
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
    pub(crate) fn new_external(cmd: &crate::Command) -> Self {
        let ignore_case = false;
        Self {
            source: None,
            indices: Vec::new(),
            type_id: Some(
                cmd.get_external_subcommand_value_parser()
                    .expect(INTERNAL_ERROR_MSG)
                    .type_id(),
            ),
            vals: Vec::new(),
            raw_vals: Vec::new(),
            ignore_case,
        }
    }
More examples
Hide additional examples
src/parser/arg_matcher.rs (line 162)
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
    pub(crate) fn start_occurrence_of_external(&mut self, cmd: &crate::Command) {
        let id = Id::from_static_ref(Id::EXTERNAL);
        debug!("ArgMatcher::start_occurrence_of_external: id={:?}", id,);
        let ma = self.entry(id).or_insert(MatchedArg::new_external(cmd));
        debug_assert_eq!(
            ma.type_id(),
            Some(
                cmd.get_external_subcommand_value_parser()
                    .expect(INTERNAL_ERROR_MSG)
                    .type_id()
            )
        );
        ma.set_source(ValueSource::CommandLine);
        ma.new_val_group();
    }
src/parser/parser.rs (line 426)
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
    pub(crate) fn get_matches_with(
        &mut self,
        matcher: &mut ArgMatcher,
        raw_args: &mut clap_lex::RawArgs,
        mut args_cursor: clap_lex::ArgCursor,
    ) -> ClapResult<()> {
        debug!("Parser::get_matches_with");
        // Verify all positional assertions pass

        let mut subcmd_name: Option<String> = None;
        let mut keep_state = false;
        let mut parse_state = ParseState::ValuesDone;
        let mut pos_counter = 1;

        // Already met any valid arg(then we shouldn't expect subcommands after it).
        let mut valid_arg_found = false;
        // If the user already passed '--'. Meaning only positional args follow.
        let mut trailing_values = false;

        // Count of positional args
        let positional_count = self
            .cmd
            .get_keymap()
            .keys()
            .filter(|x| x.is_position())
            .count();
        // If any arg sets .last(true)
        let contains_last = self.cmd.get_arguments().any(|x| x.is_last_set());

        while let Some(arg_os) = raw_args.next(&mut args_cursor) {
            // Recover the replaced items if any.
            if let Some(replaced_items) = arg_os
                .to_value()
                .ok()
                .and_then(|a| self.cmd.get_replacement(a))
            {
                debug!(
                    "Parser::get_matches_with: found replacer: {:?}, target: {:?}",
                    arg_os, replaced_items
                );
                raw_args.insert(&args_cursor, replaced_items);
                continue;
            }

            debug!(
                "Parser::get_matches_with: Begin parsing '{:?}' ({:?})",
                arg_os.to_value_os(),
                arg_os.to_value_os().as_raw_bytes()
            );

            // Has the user already passed '--'? Meaning only positional args follow
            if !trailing_values {
                if self.cmd.is_subcommand_precedence_over_arg_set()
                    || !matches!(parse_state, ParseState::Opt(_) | ParseState::Pos(_))
                {
                    // Does the arg match a subcommand name, or any of its aliases (if defined)
                    let sc_name = self.possible_subcommand(arg_os.to_value(), valid_arg_found);
                    debug!("Parser::get_matches_with: sc={:?}", sc_name);
                    if let Some(sc_name) = sc_name {
                        if sc_name == "help" && !self.cmd.is_disable_help_subcommand_set() {
                            ok!(self.parse_help_subcommand(raw_args.remaining(&mut args_cursor)));
                            unreachable!("`parse_help_subcommand` always errors");
                        } else {
                            subcmd_name = Some(sc_name.to_owned());
                        }
                        break;
                    }
                }

                if arg_os.is_escape() {
                    if matches!(&parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if
                        self.cmd[opt].is_allow_hyphen_values_set())
                    {
                        // ParseResult::MaybeHyphenValue, do nothing
                    } else {
                        debug!("Parser::get_matches_with: setting TrailingVals=true");
                        trailing_values = true;
                        matcher.start_trailing();
                        continue;
                    }
                } else if let Some((long_arg, long_value)) = arg_os.to_long() {
                    let parse_result = ok!(self.parse_long_arg(
                        matcher,
                        long_arg,
                        long_value,
                        &parse_state,
                        pos_counter,
                        &mut valid_arg_found,
                    ));
                    debug!(
                        "Parser::get_matches_with: After parse_long_arg {:?}",
                        parse_result
                    );
                    match parse_result {
                        ParseResult::NoArg => {
                            unreachable!("`to_long` always has the flag specified")
                        }
                        ParseResult::ValuesDone => {
                            parse_state = ParseState::ValuesDone;
                            continue;
                        }
                        ParseResult::Opt(id) => {
                            parse_state = ParseState::Opt(id);
                            continue;
                        }
                        ParseResult::FlagSubCommand(name) => {
                            debug!(
                                "Parser::get_matches_with: FlagSubCommand found in long arg {:?}",
                                &name
                            );
                            subcmd_name = Some(name);
                            break;
                        }
                        ParseResult::EqualsNotProvided { arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::no_equals(
                                self.cmd,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::NoMatchingArg { arg } => {
                            let _ = self.resolve_pending(matcher);
                            let remaining_args: Vec<_> =
                                raw_args.remaining(&mut args_cursor).collect();
                            return Err(self.did_you_mean_error(
                                &arg,
                                matcher,
                                &remaining_args,
                                trailing_values,
                            ));
                        }
                        ParseResult::UnneededAttachedValue { rest, used, arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::too_many_values(
                                self.cmd,
                                rest,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&used),
                            ));
                        }
                        ParseResult::MaybeHyphenValue => {
                            // Maybe a hyphen value, do nothing.
                        }
                        ParseResult::AttachedValueNotConsumed => {
                            unreachable!()
                        }
                    }
                } else if let Some(short_arg) = arg_os.to_short() {
                    // Arg looks like a short flag, and not a possible number

                    // Try to parse short args like normal, if allow_hyphen_values or
                    // AllowNegativeNumbers is set, parse_short_arg will *not* throw
                    // an error, and instead return Ok(None)
                    let parse_result = ok!(self.parse_short_arg(
                        matcher,
                        short_arg,
                        &parse_state,
                        pos_counter,
                        &mut valid_arg_found,
                    ));
                    // If it's None, we then check if one of those two AppSettings was set
                    debug!(
                        "Parser::get_matches_with: After parse_short_arg {:?}",
                        parse_result
                    );
                    match parse_result {
                        ParseResult::NoArg => {
                            // Is a single dash `-`, try positional.
                        }
                        ParseResult::ValuesDone => {
                            parse_state = ParseState::ValuesDone;
                            continue;
                        }
                        ParseResult::Opt(id) => {
                            parse_state = ParseState::Opt(id);
                            continue;
                        }
                        ParseResult::FlagSubCommand(name) => {
                            // If there are more short flags to be processed, we should keep the state, and later
                            // revisit the current group of short flags skipping the subcommand.
                            keep_state = self
                                .flag_subcmd_at
                                .map(|at| {
                                    raw_args
                                        .seek(&mut args_cursor, clap_lex::SeekFrom::Current(-1));
                                    // Since we are now saving the current state, the number of flags to skip during state recovery should
                                    // be the current index (`cur_idx`) minus ONE UNIT TO THE LEFT of the starting position.
                                    self.flag_subcmd_skip = self.cur_idx.get() - at + 1;
                                })
                                .is_some();

                            debug!(
                                "Parser::get_matches_with:FlagSubCommandShort: subcmd_name={}, keep_state={}, flag_subcmd_skip={}",
                                name,
                                keep_state,
                                self.flag_subcmd_skip
                            );

                            subcmd_name = Some(name);
                            break;
                        }
                        ParseResult::EqualsNotProvided { arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::no_equals(
                                self.cmd,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::NoMatchingArg { arg } => {
                            let _ = self.resolve_pending(matcher);
                            // We already know it looks like a flag
                            let suggested_trailing_arg =
                                !trailing_values && self.cmd.has_positionals();
                            return Err(ClapError::unknown_argument(
                                self.cmd,
                                arg,
                                None,
                                suggested_trailing_arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::MaybeHyphenValue => {
                            // Maybe a hyphen value, do nothing.
                        }
                        ParseResult::UnneededAttachedValue { .. }
                        | ParseResult::AttachedValueNotConsumed => unreachable!(),
                    }
                }

                if let ParseState::Opt(id) = &parse_state {
                    // Assume this is a value of a previous arg.

                    // get the option so we can check the settings
                    let arg = &self.cmd[id];
                    let parse_result = if let Some(parse_result) =
                        self.check_terminator(arg, arg_os.to_value_os())
                    {
                        parse_result
                    } else {
                        let trailing_values = false;
                        let arg_values = matcher.pending_values_mut(id, None, trailing_values);
                        arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
                        if matcher.needs_more_vals(arg) {
                            ParseResult::Opt(arg.get_id().clone())
                        } else {
                            ParseResult::ValuesDone
                        }
                    };
                    parse_state = match parse_result {
                        ParseResult::Opt(id) => ParseState::Opt(id),
                        ParseResult::ValuesDone => ParseState::ValuesDone,
                        _ => unreachable!(),
                    };
                    // get the next value from the iterator
                    continue;
                }
            }

            // Correct pos_counter.
            pos_counter = {
                let is_second_to_last = pos_counter + 1 == positional_count;

                // The last positional argument, or second to last positional
                // argument may be set to .multiple_values(true) or `.multiple_occurrences(true)`
                let low_index_mults = is_second_to_last
                    && self.cmd.get_positionals().any(|a| {
                        a.is_multiple() && (positional_count != a.get_index().unwrap_or(0))
                    })
                    && self
                        .cmd
                        .get_positionals()
                        .last()
                        .map_or(false, |p_name| !p_name.is_last_set());

                let missing_pos = self.cmd.is_allow_missing_positional_set()
                    && is_second_to_last
                    && !trailing_values;

                debug!(
                    "Parser::get_matches_with: Positional counter...{}",
                    pos_counter
                );
                debug!(
                    "Parser::get_matches_with: Low index multiples...{:?}",
                    low_index_mults
                );

                if low_index_mults || missing_pos {
                    let skip_current = if let Some(n) = raw_args.peek(&args_cursor) {
                        if let Some(arg) = self
                            .cmd
                            .get_positionals()
                            .find(|a| a.get_index() == Some(pos_counter))
                        {
                            // If next value looks like a new_arg or it's a
                            // subcommand, skip positional argument under current
                            // pos_counter(which means current value cannot be a
                            // positional argument with a value next to it), assume
                            // current value matches the next arg.
                            self.is_new_arg(&n, arg)
                                || self
                                    .possible_subcommand(n.to_value(), valid_arg_found)
                                    .is_some()
                        } else {
                            true
                        }
                    } else {
                        true
                    };

                    if skip_current {
                        debug!("Parser::get_matches_with: Bumping the positional counter...");
                        pos_counter + 1
                    } else {
                        pos_counter
                    }
                } else if trailing_values
                    && (self.cmd.is_allow_missing_positional_set() || contains_last)
                {
                    // Came to -- and one positional has .last(true) set, so we go immediately
                    // to the last (highest index) positional
                    debug!("Parser::get_matches_with: .last(true) and --, setting last pos");
                    positional_count
                } else {
                    pos_counter
                }
            };

            if let Some(arg) = self.cmd.get_keymap().get(&pos_counter) {
                if arg.is_last_set() && !trailing_values {
                    let _ = self.resolve_pending(matcher);
                    // Its already considered a positional, we don't need to suggest turning it
                    // into one
                    let suggested_trailing_arg = false;
                    return Err(ClapError::unknown_argument(
                        self.cmd,
                        arg_os.display().to_string(),
                        None,
                        suggested_trailing_arg,
                        Usage::new(self.cmd).create_usage_with_title(&[]),
                    ));
                }

                if arg.is_trailing_var_arg_set() {
                    trailing_values = true;
                }

                if matcher.pending_arg_id() != Some(arg.get_id()) || !arg.is_multiple_values_set() {
                    ok!(self.resolve_pending(matcher));
                }
                if let Some(_parse_result) = self.check_terminator(arg, arg_os.to_value_os()) {
                    debug!(
                        "Parser::get_matches_with: ignoring terminator result {:?}",
                        _parse_result
                    );
                } else {
                    let arg_values = matcher.pending_values_mut(
                        arg.get_id(),
                        Some(Identifier::Index),
                        trailing_values,
                    );
                    arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
                }

                // Only increment the positional counter if it doesn't allow multiples
                if !arg.is_multiple() {
                    pos_counter += 1;
                    parse_state = ParseState::ValuesDone;
                } else {
                    parse_state = ParseState::Pos(arg.get_id().clone());
                }
                valid_arg_found = true;
            } else if let Some(external_parser) =
                self.cmd.get_external_subcommand_value_parser().cloned()
            {
                // Get external subcommand name
                let sc_name = match arg_os.to_value() {
                    Ok(s) => s.to_owned(),
                    Err(_) => {
                        let _ = self.resolve_pending(matcher);
                        return Err(ClapError::invalid_utf8(
                            self.cmd,
                            Usage::new(self.cmd).create_usage_with_title(&[]),
                        ));
                    }
                };

                // Collect the external subcommand args
                let mut sc_m = ArgMatcher::new(self.cmd);
                sc_m.start_occurrence_of_external(self.cmd);

                for raw_val in raw_args.remaining(&mut args_cursor) {
                    let val = ok!(external_parser.parse_ref(self.cmd, None, raw_val));
                    let external_id = Id::from_static_ref(Id::EXTERNAL);
                    sc_m.add_val_to(&external_id, val, raw_val.to_os_string());
                }

                matcher.subcommand(SubCommand {
                    name: sc_name,
                    matches: sc_m.into_inner(),
                });

                ok!(self.resolve_pending(matcher));
                #[cfg(feature = "env")]
                ok!(self.add_env(matcher));
                ok!(self.add_defaults(matcher));
                return Validator::new(self.cmd).validate(parse_state, matcher);
            } else {
                // Start error processing
                let _ = self.resolve_pending(matcher);
                return Err(self.match_arg_error(&arg_os, valid_arg_found, trailing_values));
            }
        }

        if let Some(ref pos_sc_name) = subcmd_name {
            let sc_name = self
                .cmd
                .find_subcommand(pos_sc_name)
                .expect(INTERNAL_ERROR_MSG)
                .get_name()
                .to_owned();
            ok!(self.parse_subcommand(&sc_name, matcher, raw_args, args_cursor, keep_state));
        }

        ok!(self.resolve_pending(matcher));
        #[cfg(feature = "env")]
        ok!(self.add_env(matcher));
        ok!(self.add_defaults(matcher));
        Validator::new(self.cmd).validate(parse_state, matcher)
    }
Examples found in repository?
src/parser/parser.rs (line 555)
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
    fn possible_subcommand(
        &self,
        arg: Result<&str, &RawOsStr>,
        valid_arg_found: bool,
    ) -> Option<&str> {
        debug!("Parser::possible_subcommand: arg={:?}", arg);
        let arg = some!(arg.ok());

        if !(self.cmd.is_args_conflicts_with_subcommands_set() && valid_arg_found) {
            if self.cmd.is_infer_subcommands_set() {
                // For subcommand `test`, we accepts it's prefix: `t`, `te`,
                // `tes` and `test`.
                let v = self
                    .cmd
                    .all_subcommand_names()
                    .filter(|s| s.starts_with(arg))
                    .collect::<Vec<_>>();

                if v.len() == 1 {
                    return Some(v[0]);
                }

                // If there is any ambiguity, fallback to non-infer subcommand
                // search.
            }
            if let Some(sc) = self.cmd.find_subcommand(arg) {
                return Some(sc.get_name());
            }
        }
        None
    }
More examples
Hide additional examples
src/output/usage.rs (line 98)
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
    fn create_help_usage(&self, incl_reqs: bool) -> StyledStr {
        debug!("Usage::create_help_usage; incl_reqs={:?}", incl_reqs);
        let mut styled = StyledStr::new();
        let name = self
            .cmd
            .get_usage_name()
            .or_else(|| self.cmd.get_bin_name())
            .unwrap_or_else(|| self.cmd.get_name());
        styled.literal(name);

        if self.needs_options_tag() {
            styled.placeholder(" [OPTIONS]");
        }

        self.write_args(&[], !incl_reqs, &mut styled);

        // incl_reqs is only false when this function is called recursively
        if self.cmd.has_visible_subcommands() && incl_reqs
            || self.cmd.is_allow_external_subcommands_set()
        {
            let placeholder = self
                .cmd
                .get_subcommand_value_name()
                .unwrap_or(DEFAULT_SUB_VALUE_NAME);
            if self.cmd.is_subcommand_negates_reqs_set()
                || self.cmd.is_args_conflicts_with_subcommands_set()
            {
                styled.none("\n");
                styled.none("       ");
                if self.cmd.is_args_conflicts_with_subcommands_set() {
                    // Short-circuit full usage creation since no args will be relevant
                    styled.literal(name);
                } else {
                    styled.extend(self.create_help_usage(false).into_iter());
                }
                styled.placeholder(" <");
                styled.placeholder(placeholder);
                styled.placeholder(">");
            } else if self.cmd.is_subcommand_required_set() {
                styled.placeholder(" <");
                styled.placeholder(placeholder);
                styled.placeholder(">");
            } else {
                styled.placeholder(" [");
                styled.placeholder(placeholder);
                styled.placeholder("]");
            }
        }
        styled.trim();
        debug!("Usage::create_help_usage: usage={}", styled);
        styled
    }
src/builder/command.rs (line 3932)
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
    pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> {
        use std::fmt::Write;

        let mut mid_string = String::from(" ");
        #[cfg(feature = "usage")]
        if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set()
        {
            let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

            for s in &reqs {
                mid_string.push_str(&s.to_string());
                mid_string.push(' ');
            }
        }
        let is_multicall_set = self.is_multicall_set();

        let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name));

        // Display subcommand name, short and long in usage
        let mut sc_names = String::new();
        sc_names.push_str(sc.name.as_str());
        let mut flag_subcmd = false;
        if let Some(l) = sc.get_long_flag() {
            write!(sc_names, "|--{}", l).unwrap();
            flag_subcmd = true;
        }
        if let Some(s) = sc.get_short_flag() {
            write!(sc_names, "|-{}", s).unwrap();
            flag_subcmd = true;
        }

        if flag_subcmd {
            sc_names = format!("{{{}}}", sc_names);
        }

        let usage_name = self
            .bin_name
            .as_ref()
            .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names))
            .unwrap_or(sc_names);
        sc.usage_name = Some(usage_name);

        // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
        // a space
        let bin_name = format!(
            "{}{}{}",
            self.bin_name.as_deref().unwrap_or_default(),
            if self.bin_name.is_some() { " " } else { "" },
            &*sc.name
        );
        debug!(
            "Command::_build_subcommand Setting bin_name of {} to {:?}",
            sc.name, bin_name
        );
        sc.bin_name = Some(bin_name);

        if sc.display_name.is_none() {
            let self_display_name = if is_multicall_set {
                self.display_name.as_deref().unwrap_or("")
            } else {
                self.display_name.as_deref().unwrap_or(&self.name)
            };
            let display_name = format!(
                "{}{}{}",
                self_display_name,
                if !self_display_name.is_empty() {
                    "-"
                } else {
                    ""
                },
                &*sc.name
            );
            debug!(
                "Command::_build_subcommand Setting display_name of {} to {:?}",
                sc.name, display_name
            );
            sc.display_name = Some(display_name);
        }

        // Ensure all args are built and ready to parse
        sc._build_self(false);

        Some(sc)
    }

    fn _build_bin_names_internal(&mut self) {
        debug!("Command::_build_bin_names");

        if !self.is_set(AppSettings::BinNameBuilt) {
            let mut mid_string = String::from(" ");
            #[cfg(feature = "usage")]
            if !self.is_subcommand_negates_reqs_set()
                && !self.is_args_conflicts_with_subcommands_set()
            {
                let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

                for s in &reqs {
                    mid_string.push_str(&s.to_string());
                    mid_string.push(' ');
                }
            }
            let is_multicall_set = self.is_multicall_set();

            let self_bin_name = if is_multicall_set {
                self.bin_name.as_deref().unwrap_or("")
            } else {
                self.bin_name.as_deref().unwrap_or(&self.name)
            }
            .to_owned();

            for mut sc in &mut self.subcommands {
                debug!("Command::_build_bin_names:iter: bin_name set...");

                if sc.usage_name.is_none() {
                    use std::fmt::Write;
                    // Display subcommand name, short and long in usage
                    let mut sc_names = String::new();
                    sc_names.push_str(sc.name.as_str());
                    let mut flag_subcmd = false;
                    if let Some(l) = sc.get_long_flag() {
                        write!(sc_names, "|--{}", l).unwrap();
                        flag_subcmd = true;
                    }
                    if let Some(s) = sc.get_short_flag() {
                        write!(sc_names, "|-{}", s).unwrap();
                        flag_subcmd = true;
                    }

                    if flag_subcmd {
                        sc_names = format!("{{{}}}", sc_names);
                    }

                    let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names);
                    debug!(
                        "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}",
                        sc.name, usage_name
                    );
                    sc.usage_name = Some(usage_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})",
                        sc.name, sc.usage_name
                    );
                }

                if sc.bin_name.is_none() {
                    let bin_name = format!(
                        "{}{}{}",
                        self_bin_name,
                        if !self_bin_name.is_empty() { " " } else { "" },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}",
                        sc.name, bin_name
                    );
                    sc.bin_name = Some(bin_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})",
                        sc.name, sc.bin_name
                    );
                }

                if sc.display_name.is_none() {
                    let self_display_name = if is_multicall_set {
                        self.display_name.as_deref().unwrap_or("")
                    } else {
                        self.display_name.as_deref().unwrap_or(&self.name)
                    };
                    let display_name = format!(
                        "{}{}{}",
                        self_display_name,
                        if !self_display_name.is_empty() {
                            "-"
                        } else {
                            ""
                        },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting display_name of {} to {:?}",
                        sc.name, display_name
                    );
                    sc.display_name = Some(display_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})",
                        sc.name, sc.display_name
                    );
                }

                sc._build_bin_names_internal();
            }
            self.set(AppSettings::BinNameBuilt);
        } else {
            debug!("Command::_build_bin_names: already built");
        }
    }
Examples found in repository?
src/parser/parser.rs (line 103)
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
    pub(crate) fn get_matches_with(
        &mut self,
        matcher: &mut ArgMatcher,
        raw_args: &mut clap_lex::RawArgs,
        mut args_cursor: clap_lex::ArgCursor,
    ) -> ClapResult<()> {
        debug!("Parser::get_matches_with");
        // Verify all positional assertions pass

        let mut subcmd_name: Option<String> = None;
        let mut keep_state = false;
        let mut parse_state = ParseState::ValuesDone;
        let mut pos_counter = 1;

        // Already met any valid arg(then we shouldn't expect subcommands after it).
        let mut valid_arg_found = false;
        // If the user already passed '--'. Meaning only positional args follow.
        let mut trailing_values = false;

        // Count of positional args
        let positional_count = self
            .cmd
            .get_keymap()
            .keys()
            .filter(|x| x.is_position())
            .count();
        // If any arg sets .last(true)
        let contains_last = self.cmd.get_arguments().any(|x| x.is_last_set());

        while let Some(arg_os) = raw_args.next(&mut args_cursor) {
            // Recover the replaced items if any.
            if let Some(replaced_items) = arg_os
                .to_value()
                .ok()
                .and_then(|a| self.cmd.get_replacement(a))
            {
                debug!(
                    "Parser::get_matches_with: found replacer: {:?}, target: {:?}",
                    arg_os, replaced_items
                );
                raw_args.insert(&args_cursor, replaced_items);
                continue;
            }

            debug!(
                "Parser::get_matches_with: Begin parsing '{:?}' ({:?})",
                arg_os.to_value_os(),
                arg_os.to_value_os().as_raw_bytes()
            );

            // Has the user already passed '--'? Meaning only positional args follow
            if !trailing_values {
                if self.cmd.is_subcommand_precedence_over_arg_set()
                    || !matches!(parse_state, ParseState::Opt(_) | ParseState::Pos(_))
                {
                    // Does the arg match a subcommand name, or any of its aliases (if defined)
                    let sc_name = self.possible_subcommand(arg_os.to_value(), valid_arg_found);
                    debug!("Parser::get_matches_with: sc={:?}", sc_name);
                    if let Some(sc_name) = sc_name {
                        if sc_name == "help" && !self.cmd.is_disable_help_subcommand_set() {
                            ok!(self.parse_help_subcommand(raw_args.remaining(&mut args_cursor)));
                            unreachable!("`parse_help_subcommand` always errors");
                        } else {
                            subcmd_name = Some(sc_name.to_owned());
                        }
                        break;
                    }
                }

                if arg_os.is_escape() {
                    if matches!(&parse_state, ParseState::Opt(opt) | ParseState::Pos(opt) if
                        self.cmd[opt].is_allow_hyphen_values_set())
                    {
                        // ParseResult::MaybeHyphenValue, do nothing
                    } else {
                        debug!("Parser::get_matches_with: setting TrailingVals=true");
                        trailing_values = true;
                        matcher.start_trailing();
                        continue;
                    }
                } else if let Some((long_arg, long_value)) = arg_os.to_long() {
                    let parse_result = ok!(self.parse_long_arg(
                        matcher,
                        long_arg,
                        long_value,
                        &parse_state,
                        pos_counter,
                        &mut valid_arg_found,
                    ));
                    debug!(
                        "Parser::get_matches_with: After parse_long_arg {:?}",
                        parse_result
                    );
                    match parse_result {
                        ParseResult::NoArg => {
                            unreachable!("`to_long` always has the flag specified")
                        }
                        ParseResult::ValuesDone => {
                            parse_state = ParseState::ValuesDone;
                            continue;
                        }
                        ParseResult::Opt(id) => {
                            parse_state = ParseState::Opt(id);
                            continue;
                        }
                        ParseResult::FlagSubCommand(name) => {
                            debug!(
                                "Parser::get_matches_with: FlagSubCommand found in long arg {:?}",
                                &name
                            );
                            subcmd_name = Some(name);
                            break;
                        }
                        ParseResult::EqualsNotProvided { arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::no_equals(
                                self.cmd,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::NoMatchingArg { arg } => {
                            let _ = self.resolve_pending(matcher);
                            let remaining_args: Vec<_> =
                                raw_args.remaining(&mut args_cursor).collect();
                            return Err(self.did_you_mean_error(
                                &arg,
                                matcher,
                                &remaining_args,
                                trailing_values,
                            ));
                        }
                        ParseResult::UnneededAttachedValue { rest, used, arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::too_many_values(
                                self.cmd,
                                rest,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&used),
                            ));
                        }
                        ParseResult::MaybeHyphenValue => {
                            // Maybe a hyphen value, do nothing.
                        }
                        ParseResult::AttachedValueNotConsumed => {
                            unreachable!()
                        }
                    }
                } else if let Some(short_arg) = arg_os.to_short() {
                    // Arg looks like a short flag, and not a possible number

                    // Try to parse short args like normal, if allow_hyphen_values or
                    // AllowNegativeNumbers is set, parse_short_arg will *not* throw
                    // an error, and instead return Ok(None)
                    let parse_result = ok!(self.parse_short_arg(
                        matcher,
                        short_arg,
                        &parse_state,
                        pos_counter,
                        &mut valid_arg_found,
                    ));
                    // If it's None, we then check if one of those two AppSettings was set
                    debug!(
                        "Parser::get_matches_with: After parse_short_arg {:?}",
                        parse_result
                    );
                    match parse_result {
                        ParseResult::NoArg => {
                            // Is a single dash `-`, try positional.
                        }
                        ParseResult::ValuesDone => {
                            parse_state = ParseState::ValuesDone;
                            continue;
                        }
                        ParseResult::Opt(id) => {
                            parse_state = ParseState::Opt(id);
                            continue;
                        }
                        ParseResult::FlagSubCommand(name) => {
                            // If there are more short flags to be processed, we should keep the state, and later
                            // revisit the current group of short flags skipping the subcommand.
                            keep_state = self
                                .flag_subcmd_at
                                .map(|at| {
                                    raw_args
                                        .seek(&mut args_cursor, clap_lex::SeekFrom::Current(-1));
                                    // Since we are now saving the current state, the number of flags to skip during state recovery should
                                    // be the current index (`cur_idx`) minus ONE UNIT TO THE LEFT of the starting position.
                                    self.flag_subcmd_skip = self.cur_idx.get() - at + 1;
                                })
                                .is_some();

                            debug!(
                                "Parser::get_matches_with:FlagSubCommandShort: subcmd_name={}, keep_state={}, flag_subcmd_skip={}",
                                name,
                                keep_state,
                                self.flag_subcmd_skip
                            );

                            subcmd_name = Some(name);
                            break;
                        }
                        ParseResult::EqualsNotProvided { arg } => {
                            let _ = self.resolve_pending(matcher);
                            return Err(ClapError::no_equals(
                                self.cmd,
                                arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::NoMatchingArg { arg } => {
                            let _ = self.resolve_pending(matcher);
                            // We already know it looks like a flag
                            let suggested_trailing_arg =
                                !trailing_values && self.cmd.has_positionals();
                            return Err(ClapError::unknown_argument(
                                self.cmd,
                                arg,
                                None,
                                suggested_trailing_arg,
                                Usage::new(self.cmd).create_usage_with_title(&[]),
                            ));
                        }
                        ParseResult::MaybeHyphenValue => {
                            // Maybe a hyphen value, do nothing.
                        }
                        ParseResult::UnneededAttachedValue { .. }
                        | ParseResult::AttachedValueNotConsumed => unreachable!(),
                    }
                }

                if let ParseState::Opt(id) = &parse_state {
                    // Assume this is a value of a previous arg.

                    // get the option so we can check the settings
                    let arg = &self.cmd[id];
                    let parse_result = if let Some(parse_result) =
                        self.check_terminator(arg, arg_os.to_value_os())
                    {
                        parse_result
                    } else {
                        let trailing_values = false;
                        let arg_values = matcher.pending_values_mut(id, None, trailing_values);
                        arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
                        if matcher.needs_more_vals(arg) {
                            ParseResult::Opt(arg.get_id().clone())
                        } else {
                            ParseResult::ValuesDone
                        }
                    };
                    parse_state = match parse_result {
                        ParseResult::Opt(id) => ParseState::Opt(id),
                        ParseResult::ValuesDone => ParseState::ValuesDone,
                        _ => unreachable!(),
                    };
                    // get the next value from the iterator
                    continue;
                }
            }

            // Correct pos_counter.
            pos_counter = {
                let is_second_to_last = pos_counter + 1 == positional_count;

                // The last positional argument, or second to last positional
                // argument may be set to .multiple_values(true) or `.multiple_occurrences(true)`
                let low_index_mults = is_second_to_last
                    && self.cmd.get_positionals().any(|a| {
                        a.is_multiple() && (positional_count != a.get_index().unwrap_or(0))
                    })
                    && self
                        .cmd
                        .get_positionals()
                        .last()
                        .map_or(false, |p_name| !p_name.is_last_set());

                let missing_pos = self.cmd.is_allow_missing_positional_set()
                    && is_second_to_last
                    && !trailing_values;

                debug!(
                    "Parser::get_matches_with: Positional counter...{}",
                    pos_counter
                );
                debug!(
                    "Parser::get_matches_with: Low index multiples...{:?}",
                    low_index_mults
                );

                if low_index_mults || missing_pos {
                    let skip_current = if let Some(n) = raw_args.peek(&args_cursor) {
                        if let Some(arg) = self
                            .cmd
                            .get_positionals()
                            .find(|a| a.get_index() == Some(pos_counter))
                        {
                            // If next value looks like a new_arg or it's a
                            // subcommand, skip positional argument under current
                            // pos_counter(which means current value cannot be a
                            // positional argument with a value next to it), assume
                            // current value matches the next arg.
                            self.is_new_arg(&n, arg)
                                || self
                                    .possible_subcommand(n.to_value(), valid_arg_found)
                                    .is_some()
                        } else {
                            true
                        }
                    } else {
                        true
                    };

                    if skip_current {
                        debug!("Parser::get_matches_with: Bumping the positional counter...");
                        pos_counter + 1
                    } else {
                        pos_counter
                    }
                } else if trailing_values
                    && (self.cmd.is_allow_missing_positional_set() || contains_last)
                {
                    // Came to -- and one positional has .last(true) set, so we go immediately
                    // to the last (highest index) positional
                    debug!("Parser::get_matches_with: .last(true) and --, setting last pos");
                    positional_count
                } else {
                    pos_counter
                }
            };

            if let Some(arg) = self.cmd.get_keymap().get(&pos_counter) {
                if arg.is_last_set() && !trailing_values {
                    let _ = self.resolve_pending(matcher);
                    // Its already considered a positional, we don't need to suggest turning it
                    // into one
                    let suggested_trailing_arg = false;
                    return Err(ClapError::unknown_argument(
                        self.cmd,
                        arg_os.display().to_string(),
                        None,
                        suggested_trailing_arg,
                        Usage::new(self.cmd).create_usage_with_title(&[]),
                    ));
                }

                if arg.is_trailing_var_arg_set() {
                    trailing_values = true;
                }

                if matcher.pending_arg_id() != Some(arg.get_id()) || !arg.is_multiple_values_set() {
                    ok!(self.resolve_pending(matcher));
                }
                if let Some(_parse_result) = self.check_terminator(arg, arg_os.to_value_os()) {
                    debug!(
                        "Parser::get_matches_with: ignoring terminator result {:?}",
                        _parse_result
                    );
                } else {
                    let arg_values = matcher.pending_values_mut(
                        arg.get_id(),
                        Some(Identifier::Index),
                        trailing_values,
                    );
                    arg_values.push(arg_os.to_value_os().to_os_str().into_owned());
                }

                // Only increment the positional counter if it doesn't allow multiples
                if !arg.is_multiple() {
                    pos_counter += 1;
                    parse_state = ParseState::ValuesDone;
                } else {
                    parse_state = ParseState::Pos(arg.get_id().clone());
                }
                valid_arg_found = true;
            } else if let Some(external_parser) =
                self.cmd.get_external_subcommand_value_parser().cloned()
            {
                // Get external subcommand name
                let sc_name = match arg_os.to_value() {
                    Ok(s) => s.to_owned(),
                    Err(_) => {
                        let _ = self.resolve_pending(matcher);
                        return Err(ClapError::invalid_utf8(
                            self.cmd,
                            Usage::new(self.cmd).create_usage_with_title(&[]),
                        ));
                    }
                };

                // Collect the external subcommand args
                let mut sc_m = ArgMatcher::new(self.cmd);
                sc_m.start_occurrence_of_external(self.cmd);

                for raw_val in raw_args.remaining(&mut args_cursor) {
                    let val = ok!(external_parser.parse_ref(self.cmd, None, raw_val));
                    let external_id = Id::from_static_ref(Id::EXTERNAL);
                    sc_m.add_val_to(&external_id, val, raw_val.to_os_string());
                }

                matcher.subcommand(SubCommand {
                    name: sc_name,
                    matches: sc_m.into_inner(),
                });

                ok!(self.resolve_pending(matcher));
                #[cfg(feature = "env")]
                ok!(self.add_env(matcher));
                ok!(self.add_defaults(matcher));
                return Validator::new(self.cmd).validate(parse_state, matcher);
            } else {
                // Start error processing
                let _ = self.resolve_pending(matcher);
                return Err(self.match_arg_error(&arg_os, valid_arg_found, trailing_values));
            }
        }

        if let Some(ref pos_sc_name) = subcmd_name {
            let sc_name = self
                .cmd
                .find_subcommand(pos_sc_name)
                .expect(INTERNAL_ERROR_MSG)
                .get_name()
                .to_owned();
            ok!(self.parse_subcommand(&sc_name, matcher, raw_args, args_cursor, keep_state));
        }

        ok!(self.resolve_pending(matcher));
        #[cfg(feature = "env")]
        ok!(self.add_env(matcher));
        ok!(self.add_defaults(matcher));
        Validator::new(self.cmd).validate(parse_state, matcher)
    }

Report whether Command::subcommand_negates_reqs is set

Examples found in repository?
src/output/usage.rs (line 97)
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
    fn create_help_usage(&self, incl_reqs: bool) -> StyledStr {
        debug!("Usage::create_help_usage; incl_reqs={:?}", incl_reqs);
        let mut styled = StyledStr::new();
        let name = self
            .cmd
            .get_usage_name()
            .or_else(|| self.cmd.get_bin_name())
            .unwrap_or_else(|| self.cmd.get_name());
        styled.literal(name);

        if self.needs_options_tag() {
            styled.placeholder(" [OPTIONS]");
        }

        self.write_args(&[], !incl_reqs, &mut styled);

        // incl_reqs is only false when this function is called recursively
        if self.cmd.has_visible_subcommands() && incl_reqs
            || self.cmd.is_allow_external_subcommands_set()
        {
            let placeholder = self
                .cmd
                .get_subcommand_value_name()
                .unwrap_or(DEFAULT_SUB_VALUE_NAME);
            if self.cmd.is_subcommand_negates_reqs_set()
                || self.cmd.is_args_conflicts_with_subcommands_set()
            {
                styled.none("\n");
                styled.none("       ");
                if self.cmd.is_args_conflicts_with_subcommands_set() {
                    // Short-circuit full usage creation since no args will be relevant
                    styled.literal(name);
                } else {
                    styled.extend(self.create_help_usage(false).into_iter());
                }
                styled.placeholder(" <");
                styled.placeholder(placeholder);
                styled.placeholder(">");
            } else if self.cmd.is_subcommand_required_set() {
                styled.placeholder(" <");
                styled.placeholder(placeholder);
                styled.placeholder(">");
            } else {
                styled.placeholder(" [");
                styled.placeholder(placeholder);
                styled.placeholder("]");
            }
        }
        styled.trim();
        debug!("Usage::create_help_usage: usage={}", styled);
        styled
    }
More examples
Hide additional examples
src/parser/validator.rs (line 84)
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
    pub(crate) fn validate(
        &mut self,
        parse_state: ParseState,
        matcher: &mut ArgMatcher,
    ) -> ClapResult<()> {
        debug!("Validator::validate");
        let mut conflicts = Conflicts::new();
        let has_subcmd = matcher.subcommand_name().is_some();

        if let ParseState::Opt(a) = parse_state {
            debug!("Validator::validate: needs_val_of={:?}", a);

            let o = &self.cmd[&a];
            let should_err = if let Some(v) = matcher.args.get(o.get_id()) {
                v.all_val_groups_empty() && o.get_min_vals() != 0
            } else {
                true
            };
            if should_err {
                return Err(Error::empty_value(
                    self.cmd,
                    &get_possible_values_cli(o)
                        .iter()
                        .filter(|pv| !pv.is_hide_set())
                        .map(|n| n.get_name().to_owned())
                        .collect::<Vec<_>>(),
                    o.to_string(),
                ));
            }
        }

        if !has_subcmd && self.cmd.is_arg_required_else_help_set() {
            let num_user_values = matcher
                .arg_ids()
                .filter(|arg_id| matcher.check_explicit(arg_id, &ArgPredicate::IsPresent))
                .count();
            if num_user_values == 0 {
                let message = self.cmd.write_help_err(false);
                return Err(Error::display_help_error(self.cmd, message));
            }
        }
        if !has_subcmd && self.cmd.is_subcommand_required_set() {
            let bn = self
                .cmd
                .get_bin_name()
                .unwrap_or_else(|| self.cmd.get_name());
            return Err(Error::missing_subcommand(
                self.cmd,
                bn.to_string(),
                self.cmd
                    .all_subcommand_names()
                    .map(|s| s.to_owned())
                    .collect::<Vec<_>>(),
                Usage::new(self.cmd)
                    .required(&self.required)
                    .create_usage_with_title(&[]),
            ));
        }

        ok!(self.validate_conflicts(matcher, &mut conflicts));
        if !(self.cmd.is_subcommand_negates_reqs_set() && has_subcmd) {
            ok!(self.validate_required(matcher, &mut conflicts));
        }

        Ok(())
    }
src/builder/command.rs (line 3932)
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
    pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> {
        use std::fmt::Write;

        let mut mid_string = String::from(" ");
        #[cfg(feature = "usage")]
        if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set()
        {
            let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

            for s in &reqs {
                mid_string.push_str(&s.to_string());
                mid_string.push(' ');
            }
        }
        let is_multicall_set = self.is_multicall_set();

        let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name));

        // Display subcommand name, short and long in usage
        let mut sc_names = String::new();
        sc_names.push_str(sc.name.as_str());
        let mut flag_subcmd = false;
        if let Some(l) = sc.get_long_flag() {
            write!(sc_names, "|--{}", l).unwrap();
            flag_subcmd = true;
        }
        if let Some(s) = sc.get_short_flag() {
            write!(sc_names, "|-{}", s).unwrap();
            flag_subcmd = true;
        }

        if flag_subcmd {
            sc_names = format!("{{{}}}", sc_names);
        }

        let usage_name = self
            .bin_name
            .as_ref()
            .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names))
            .unwrap_or(sc_names);
        sc.usage_name = Some(usage_name);

        // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
        // a space
        let bin_name = format!(
            "{}{}{}",
            self.bin_name.as_deref().unwrap_or_default(),
            if self.bin_name.is_some() { " " } else { "" },
            &*sc.name
        );
        debug!(
            "Command::_build_subcommand Setting bin_name of {} to {:?}",
            sc.name, bin_name
        );
        sc.bin_name = Some(bin_name);

        if sc.display_name.is_none() {
            let self_display_name = if is_multicall_set {
                self.display_name.as_deref().unwrap_or("")
            } else {
                self.display_name.as_deref().unwrap_or(&self.name)
            };
            let display_name = format!(
                "{}{}{}",
                self_display_name,
                if !self_display_name.is_empty() {
                    "-"
                } else {
                    ""
                },
                &*sc.name
            );
            debug!(
                "Command::_build_subcommand Setting display_name of {} to {:?}",
                sc.name, display_name
            );
            sc.display_name = Some(display_name);
        }

        // Ensure all args are built and ready to parse
        sc._build_self(false);

        Some(sc)
    }

    fn _build_bin_names_internal(&mut self) {
        debug!("Command::_build_bin_names");

        if !self.is_set(AppSettings::BinNameBuilt) {
            let mut mid_string = String::from(" ");
            #[cfg(feature = "usage")]
            if !self.is_subcommand_negates_reqs_set()
                && !self.is_args_conflicts_with_subcommands_set()
            {
                let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

                for s in &reqs {
                    mid_string.push_str(&s.to_string());
                    mid_string.push(' ');
                }
            }
            let is_multicall_set = self.is_multicall_set();

            let self_bin_name = if is_multicall_set {
                self.bin_name.as_deref().unwrap_or("")
            } else {
                self.bin_name.as_deref().unwrap_or(&self.name)
            }
            .to_owned();

            for mut sc in &mut self.subcommands {
                debug!("Command::_build_bin_names:iter: bin_name set...");

                if sc.usage_name.is_none() {
                    use std::fmt::Write;
                    // Display subcommand name, short and long in usage
                    let mut sc_names = String::new();
                    sc_names.push_str(sc.name.as_str());
                    let mut flag_subcmd = false;
                    if let Some(l) = sc.get_long_flag() {
                        write!(sc_names, "|--{}", l).unwrap();
                        flag_subcmd = true;
                    }
                    if let Some(s) = sc.get_short_flag() {
                        write!(sc_names, "|-{}", s).unwrap();
                        flag_subcmd = true;
                    }

                    if flag_subcmd {
                        sc_names = format!("{{{}}}", sc_names);
                    }

                    let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names);
                    debug!(
                        "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}",
                        sc.name, usage_name
                    );
                    sc.usage_name = Some(usage_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})",
                        sc.name, sc.usage_name
                    );
                }

                if sc.bin_name.is_none() {
                    let bin_name = format!(
                        "{}{}{}",
                        self_bin_name,
                        if !self_bin_name.is_empty() { " " } else { "" },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}",
                        sc.name, bin_name
                    );
                    sc.bin_name = Some(bin_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})",
                        sc.name, sc.bin_name
                    );
                }

                if sc.display_name.is_none() {
                    let self_display_name = if is_multicall_set {
                        self.display_name.as_deref().unwrap_or("")
                    } else {
                        self.display_name.as_deref().unwrap_or(&self.name)
                    };
                    let display_name = format!(
                        "{}{}{}",
                        self_display_name,
                        if !self_display_name.is_empty() {
                            "-"
                        } else {
                            ""
                        },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting display_name of {} to {:?}",
                        sc.name, display_name
                    );
                    sc.display_name = Some(display_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})",
                        sc.name, sc.display_name
                    );
                }

                sc._build_bin_names_internal();
            }
            self.set(AppSettings::BinNameBuilt);
        } else {
            debug!("Command::_build_bin_names: already built");
        }
    }
src/builder/debug_asserts.rs (line 678)
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
fn _verify_positionals(cmd: &Command) -> bool {
    debug!("Command::_verify_positionals");
    // Because you must wait until all arguments have been supplied, this is the first chance
    // to make assertions on positional argument indexes
    //
    // First we verify that the index highest supplied index, is equal to the number of
    // positional arguments to verify there are no gaps (i.e. supplying an index of 1 and 3
    // but no 2)

    let highest_idx = cmd
        .get_keymap()
        .keys()
        .filter_map(|x| {
            if let KeyType::Position(n) = x {
                Some(*n)
            } else {
                None
            }
        })
        .max()
        .unwrap_or(0);

    let num_p = cmd.get_keymap().keys().filter(|x| x.is_position()).count();

    assert!(
        highest_idx == num_p,
        "Found positional argument whose index is {} but there \
             are only {} positional arguments defined",
        highest_idx,
        num_p
    );

    for arg in cmd.get_arguments() {
        if arg.index.unwrap_or(0) == highest_idx {
            assert!(
                !arg.is_trailing_var_arg_set() || !arg.is_last_set(),
                "{}:{}: `Arg::trailing_var_arg` and `Arg::last` cannot be used together",
                cmd.get_name(),
                arg.get_id()
            );

            if arg.is_trailing_var_arg_set() {
                assert!(
                    arg.is_multiple(),
                    "{}:{}: `Arg::trailing_var_arg` must accept multiple values",
                    cmd.get_name(),
                    arg.get_id()
                );
            }
        } else {
            assert!(
                !arg.is_trailing_var_arg_set(),
                "{}:{}: `Arg::trailing_var_arg` can only apply to last positional",
                cmd.get_name(),
                arg.get_id()
            );
        }
    }

    // Next we verify that only the highest index has takes multiple arguments (if any)
    let only_highest = |a: &Arg| a.is_multiple() && (a.get_index().unwrap_or(0) != highest_idx);
    if cmd.get_positionals().any(only_highest) {
        // First we make sure if there is a positional that allows multiple values
        // the one before it (second to last) has one of these:
        //  * a value terminator
        //  * ArgSettings::Last
        //  * The last arg is Required

        // We can't pass the closure (it.next()) to the macro directly because each call to
        // find() (iterator, not macro) gets called repeatedly.
        let last = &cmd.get_keymap()[&KeyType::Position(highest_idx)];
        let second_to_last = &cmd.get_keymap()[&KeyType::Position(highest_idx - 1)];

        // Either the final positional is required
        // Or the second to last has a terminator or .last(true) set
        let ok = last.is_required_set()
            || (second_to_last.terminator.is_some() || second_to_last.is_last_set())
            || last.is_last_set();
        assert!(
            ok,
            "When using a positional argument with `.num_args(1..)` that is *not the \
                 last* positional argument, the last positional argument (i.e. the one \
                 with the highest index) *must* have .required(true) or .last(true) set."
        );

        // We make sure if the second to last is Multiple the last is ArgSettings::Last
        let ok = second_to_last.is_multiple() || last.is_last_set();
        assert!(
            ok,
            "Only the last positional argument, or second to last positional \
                 argument may be set to `.num_args(1..)`"
        );

        // Next we check how many have both Multiple and not a specific number of values set
        let count = cmd
            .get_positionals()
            .filter(|p| {
                p.is_multiple_values_set()
                    && !p.get_num_args().expect(INTERNAL_ERROR_MSG).is_fixed()
            })
            .count();
        let ok = count <= 1
            || (last.is_last_set()
                && last.is_multiple()
                && second_to_last.is_multiple()
                && count == 2);
        assert!(
            ok,
            "Only one positional argument with `.num_args(1..)` set is allowed per \
                 command, unless the second one also has .last(true) set"
        );
    }

    let mut found = false;

    if cmd.is_allow_missing_positional_set() {
        // Check that if a required positional argument is found, all positions with a lower
        // index are also required.
        let mut foundx2 = false;

        for p in cmd.get_positionals() {
            if foundx2 && !p.is_required_set() {
                assert!(
                    p.is_required_set(),
                    "Found non-required positional argument with a lower \
                         index than a required positional argument by two or more: {:?} \
                         index {:?}",
                    p.get_id(),
                    p.get_index()
                );
            } else if p.is_required_set() && !p.is_last_set() {
                // Args that .last(true) don't count since they can be required and have
                // positionals with a lower index that aren't required
                // Imagine: prog <req1> [opt1] -- <req2>
                // Both of these are valid invocations:
                //      $ prog r1 -- r2
                //      $ prog r1 o1 -- r2
                if found {
                    foundx2 = true;
                    continue;
                }
                found = true;
                continue;
            } else {
                found = false;
            }
        }
    } else {
        // Check that if a required positional argument is found, all positions with a lower
        // index are also required
        for p in (1..=num_p).rev().filter_map(|n| cmd.get_keymap().get(&n)) {
            if found {
                assert!(
                    p.is_required_set(),
                    "Found non-required positional argument with a lower \
                         index than a required positional argument: {:?} index {:?}",
                    p.get_id(),
                    p.get_index()
                );
            } else if p.is_required_set() && !p.is_last_set() {
                // Args that .last(true) don't count since they can be required and have
                // positionals with a lower index that aren't required
                // Imagine: prog <req1> [opt1] -- <req2>
                // Both of these are valid invocations:
                //      $ prog r1 -- r2
                //      $ prog r1 o1 -- r2
                found = true;
                continue;
            }
        }
    }
    assert!(
        cmd.get_positionals().filter(|p| p.is_last_set()).count() < 2,
        "Only one positional argument may have last(true) set. Found two."
    );
    if cmd
        .get_positionals()
        .any(|p| p.is_last_set() && p.is_required_set())
        && cmd.has_subcommands()
        && !cmd.is_subcommand_negates_reqs_set()
    {
        panic!(
            "Having a required positional argument with .last(true) set *and* child \
                 subcommands without setting SubcommandsNegateReqs isn't compatible."
        );
    }

    true
}

Report whether Command::multicall is set

Examples found in repository?
src/builder/command.rs (line 3834)
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
    pub(crate) fn _build_self(&mut self, expand_help_tree: bool) {
        debug!("Command::_build: name={:?}", self.get_name());
        if !self.settings.is_set(AppSettings::Built) {
            // Make sure all the globally set flags apply to us as well
            self.settings = self.settings | self.g_settings;

            if self.is_multicall_set() {
                self.settings.insert(AppSettings::SubcommandRequired.into());
                self.settings.insert(AppSettings::DisableHelpFlag.into());
                self.settings.insert(AppSettings::DisableVersionFlag.into());
            }
            if !cfg!(feature = "help") && self.get_override_help().is_none() {
                self.settings.insert(AppSettings::DisableHelpFlag.into());
                self.settings
                    .insert(AppSettings::DisableHelpSubcommand.into());
            }
            if self.is_set(AppSettings::ArgsNegateSubcommands) {
                self.settings
                    .insert(AppSettings::SubcommandsNegateReqs.into());
            }
            if self.external_value_parser.is_some() {
                self.settings
                    .insert(AppSettings::AllowExternalSubcommands.into());
            }
            if !self.has_subcommands() {
                self.settings
                    .insert(AppSettings::DisableHelpSubcommand.into());
            }

            self._propagate();
            self._check_help_and_version(expand_help_tree);
            self._propagate_global_args();

            let mut pos_counter = 1;
            let hide_pv = self.is_set(AppSettings::HidePossibleValues);
            for a in self.args.args_mut() {
                // Fill in the groups
                for g in &a.groups {
                    if let Some(ag) = self.groups.iter_mut().find(|grp| grp.id == *g) {
                        ag.args.push(a.get_id().clone());
                    } else {
                        let mut ag = ArgGroup::new(g);
                        ag.args.push(a.get_id().clone());
                        self.groups.push(ag);
                    }
                }

                // Figure out implied settings
                a._build();
                if hide_pv && a.is_takes_value_set() {
                    a.settings.set(ArgSettings::HidePossibleValues);
                }
                if a.is_positional() && a.index.is_none() {
                    a.index = Some(pos_counter);
                    pos_counter += 1;
                }
            }

            self.args._build();

            #[allow(deprecated)]
            {
                let highest_idx = self
                    .get_keymap()
                    .keys()
                    .filter_map(|x| {
                        if let crate::mkeymap::KeyType::Position(n) = x {
                            Some(*n)
                        } else {
                            None
                        }
                    })
                    .max()
                    .unwrap_or(0);
                let is_trailing_var_arg_set = self.is_trailing_var_arg_set();
                let is_allow_hyphen_values_set = self.is_allow_hyphen_values_set();
                let is_allow_negative_numbers_set = self.is_allow_negative_numbers_set();
                for arg in self.args.args_mut() {
                    if is_allow_hyphen_values_set && arg.is_takes_value_set() {
                        arg.settings.insert(ArgSettings::AllowHyphenValues.into());
                    }
                    if is_allow_negative_numbers_set && arg.is_takes_value_set() {
                        arg.settings
                            .insert(ArgSettings::AllowNegativeNumbers.into());
                    }
                    if is_trailing_var_arg_set && arg.get_index() == Some(highest_idx) {
                        arg.settings.insert(ArgSettings::TrailingVarArg.into());
                    }
                }
            }

            #[cfg(debug_assertions)]
            assert_app(self);
            self.settings.set(AppSettings::Built);
        } else {
            debug!("Command::_build: already built");
        }
    }

    pub(crate) fn _build_subcommand(&mut self, name: &str) -> Option<&mut Self> {
        use std::fmt::Write;

        let mut mid_string = String::from(" ");
        #[cfg(feature = "usage")]
        if !self.is_subcommand_negates_reqs_set() && !self.is_args_conflicts_with_subcommands_set()
        {
            let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

            for s in &reqs {
                mid_string.push_str(&s.to_string());
                mid_string.push(' ');
            }
        }
        let is_multicall_set = self.is_multicall_set();

        let sc = some!(self.subcommands.iter_mut().find(|s| s.name == name));

        // Display subcommand name, short and long in usage
        let mut sc_names = String::new();
        sc_names.push_str(sc.name.as_str());
        let mut flag_subcmd = false;
        if let Some(l) = sc.get_long_flag() {
            write!(sc_names, "|--{}", l).unwrap();
            flag_subcmd = true;
        }
        if let Some(s) = sc.get_short_flag() {
            write!(sc_names, "|-{}", s).unwrap();
            flag_subcmd = true;
        }

        if flag_subcmd {
            sc_names = format!("{{{}}}", sc_names);
        }

        let usage_name = self
            .bin_name
            .as_ref()
            .map(|bin_name| format!("{}{}{}", bin_name, mid_string, sc_names))
            .unwrap_or(sc_names);
        sc.usage_name = Some(usage_name);

        // bin_name should be parent's bin_name + [<reqs>] + the sc's name separated by
        // a space
        let bin_name = format!(
            "{}{}{}",
            self.bin_name.as_deref().unwrap_or_default(),
            if self.bin_name.is_some() { " " } else { "" },
            &*sc.name
        );
        debug!(
            "Command::_build_subcommand Setting bin_name of {} to {:?}",
            sc.name, bin_name
        );
        sc.bin_name = Some(bin_name);

        if sc.display_name.is_none() {
            let self_display_name = if is_multicall_set {
                self.display_name.as_deref().unwrap_or("")
            } else {
                self.display_name.as_deref().unwrap_or(&self.name)
            };
            let display_name = format!(
                "{}{}{}",
                self_display_name,
                if !self_display_name.is_empty() {
                    "-"
                } else {
                    ""
                },
                &*sc.name
            );
            debug!(
                "Command::_build_subcommand Setting display_name of {} to {:?}",
                sc.name, display_name
            );
            sc.display_name = Some(display_name);
        }

        // Ensure all args are built and ready to parse
        sc._build_self(false);

        Some(sc)
    }

    fn _build_bin_names_internal(&mut self) {
        debug!("Command::_build_bin_names");

        if !self.is_set(AppSettings::BinNameBuilt) {
            let mut mid_string = String::from(" ");
            #[cfg(feature = "usage")]
            if !self.is_subcommand_negates_reqs_set()
                && !self.is_args_conflicts_with_subcommands_set()
            {
                let reqs = Usage::new(self).get_required_usage_from(&[], None, true); // maybe Some(m)

                for s in &reqs {
                    mid_string.push_str(&s.to_string());
                    mid_string.push(' ');
                }
            }
            let is_multicall_set = self.is_multicall_set();

            let self_bin_name = if is_multicall_set {
                self.bin_name.as_deref().unwrap_or("")
            } else {
                self.bin_name.as_deref().unwrap_or(&self.name)
            }
            .to_owned();

            for mut sc in &mut self.subcommands {
                debug!("Command::_build_bin_names:iter: bin_name set...");

                if sc.usage_name.is_none() {
                    use std::fmt::Write;
                    // Display subcommand name, short and long in usage
                    let mut sc_names = String::new();
                    sc_names.push_str(sc.name.as_str());
                    let mut flag_subcmd = false;
                    if let Some(l) = sc.get_long_flag() {
                        write!(sc_names, "|--{}", l).unwrap();
                        flag_subcmd = true;
                    }
                    if let Some(s) = sc.get_short_flag() {
                        write!(sc_names, "|-{}", s).unwrap();
                        flag_subcmd = true;
                    }

                    if flag_subcmd {
                        sc_names = format!("{{{}}}", sc_names);
                    }

                    let usage_name = format!("{}{}{}", self_bin_name, mid_string, sc_names);
                    debug!(
                        "Command::_build_bin_names:iter: Setting usage_name of {} to {:?}",
                        sc.name, usage_name
                    );
                    sc.usage_name = Some(usage_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing usage_name of {} ({:?})",
                        sc.name, sc.usage_name
                    );
                }

                if sc.bin_name.is_none() {
                    let bin_name = format!(
                        "{}{}{}",
                        self_bin_name,
                        if !self_bin_name.is_empty() { " " } else { "" },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting bin_name of {} to {:?}",
                        sc.name, bin_name
                    );
                    sc.bin_name = Some(bin_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing bin_name of {} ({:?})",
                        sc.name, sc.bin_name
                    );
                }

                if sc.display_name.is_none() {
                    let self_display_name = if is_multicall_set {
                        self.display_name.as_deref().unwrap_or("")
                    } else {
                        self.display_name.as_deref().unwrap_or(&self.name)
                    };
                    let display_name = format!(
                        "{}{}{}",
                        self_display_name,
                        if !self_display_name.is_empty() {
                            "-"
                        } else {
                            ""
                        },
                        &*sc.name
                    );
                    debug!(
                        "Command::_build_bin_names:iter: Setting display_name of {} to {:?}",
                        sc.name, display_name
                    );
                    sc.display_name = Some(display_name);
                } else {
                    debug!(
                        "Command::_build_bin_names::iter: Using existing display_name of {} ({:?})",
                        sc.name, sc.display_name
                    );
                }

                sc._build_bin_names_internal();
            }
            self.set(AppSettings::BinNameBuilt);
        } else {
            debug!("Command::_build_bin_names: already built");
        }
    }
More examples
Hide additional examples
src/builder/debug_asserts.rs (line 64)
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
pub(crate) fn assert_app(cmd: &Command) {
    debug!("Command::_debug_asserts");

    let mut short_flags = vec![];
    let mut long_flags = vec![];

    // Invalid version flag settings
    if cmd.get_version().is_none() && cmd.get_long_version().is_none() {
        // PropagateVersion is meaningless if there is no version
        assert!(
            !cmd.is_propagate_version_set(),
            "Command {}: No version information via Command::version or Command::long_version to propagate",
            cmd.get_name(),
        );

        // Used `Command::mut_arg("version", ..) but did not provide any version information to display
        let version_needed = cmd
            .get_arguments()
            .filter(|x| matches!(x.get_action(), ArgAction::Version))
            .map(|x| x.get_id())
            .collect::<Vec<_>>();

        assert_eq!(version_needed, Vec::<&str>::new(), "Command {}: `ArgAction::Version` used without providing Command::version or Command::long_version"
            ,cmd.get_name()
        );
    }

    for sc in cmd.get_subcommands() {
        if let Some(s) = sc.get_short_flag().as_ref() {
            short_flags.push(Flag::Command(format!("-{}", s), sc.get_name()));
        }

        for short_alias in sc.get_all_short_flag_aliases() {
            short_flags.push(Flag::Command(format!("-{}", short_alias), sc.get_name()));
        }

        if let Some(l) = sc.get_long_flag().as_ref() {
            assert!(!l.starts_with('-'), "Command {}: long_flag {:?} must not start with a `-`, that will be handled by the parser", sc.get_name(), l);
            long_flags.push(Flag::Command(format!("--{}", l), sc.get_name()));
        }

        for long_alias in sc.get_all_long_flag_aliases() {
            long_flags.push(Flag::Command(format!("--{}", long_alias), sc.get_name()));
        }
    }

    for arg in cmd.get_arguments() {
        assert_arg(arg);

        assert!(
            !cmd.is_multicall_set(),
            "Command {}: Arguments like {} cannot be set on a multicall command",
            cmd.get_name(),
            arg.get_id()
        );

        if let Some(s) = arg.get_short() {
            short_flags.push(Flag::Arg(format!("-{}", s), arg.get_id().as_str()));
        }

        for (short_alias, _) in &arg.short_aliases {
            short_flags.push(Flag::Arg(
                format!("-{}", short_alias),
                arg.get_id().as_str(),
            ));
        }

        if let Some(l) = arg.get_long() {
            assert!(!l.starts_with('-'), "Argument {}: long {:?} must not start with a `-`, that will be handled by the parser", arg.get_id(), l);
            long_flags.push(Flag::Arg(format!("--{}", l), arg.get_id().as_str()));
        }

        for (long_alias, _) in &arg.aliases {
            long_flags.push(Flag::Arg(
                format!("--{}", long_alias),
                arg.get_id().as_str(),
            ));
        }

        // Name conflicts
        if let Some((first, second)) = cmd.two_args_of(|x| x.get_id() == arg.get_id()) {
            panic!(
            "Command {}: Argument names must be unique, but '{}' is in use by more than one argument or group{}",
            cmd.get_name(),
            arg.get_id(),
            duplicate_tip(cmd, first, second),
        );
        }

        // Long conflicts
        if let Some(l) = arg.get_long() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_long() == Some(l)) {
                panic!(
                    "Command {}: Long option names must be unique for each argument, \
                            but '--{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    l,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second)
                )
            }
        }

        // Short conflicts
        if let Some(s) = arg.get_short() {
            if let Some((first, second)) = cmd.two_args_of(|x| x.get_short() == Some(s)) {
                panic!(
                    "Command {}: Short option names must be unique for each argument, \
                            but '-{}' is in use by both '{}' and '{}'{}",
                    cmd.get_name(),
                    s,
                    first.get_id(),
                    second.get_id(),
                    duplicate_tip(cmd, first, second),
                )
            }
        }

        // Index conflicts
        if let Some(idx) = arg.index {
            if let Some((first, second)) =
                cmd.two_args_of(|x| x.is_positional() && x.get_index() == Some(idx))
            {
                panic!(
                    "Command {}: Argument '{}' has the same index as '{}' \
                    and they are both positional arguments\n\n\t \
                    Use `Arg::num_args(1..)` to allow one \
                    positional argument to take multiple values",
                    cmd.get_name(),
                    first.get_id(),
                    second.get_id()
                )
            }
        }

        // requires, r_if, r_unless
        for req in &arg.requires {
            assert!(
                cmd.id_exists(&req.1),
                "Command {}: Argument or group '{}' specified in 'requires*' for '{}' does not exist",
                cmd.get_name(),
                req.1,
                arg.get_id(),
            );
        }

        for req in &arg.r_ifs {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq*' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_ifs_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_if_eq_all`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(&req.0),
                "Command {}: Argument or group '{}' specified in 'required_if_eq_all' for '{}' does not exist",
                    cmd.get_name(),
                req.0,
                arg.get_id()
            );
        }

        for req in &arg.r_unless {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        for req in &arg.r_unless_all {
            assert!(
                !arg.is_required_set(),
                "Argument {}: `required` conflicts with `required_unless*`",
                arg.get_id()
            );
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'required_unless*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // blacklist
        for req in &arg.blacklist {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'conflicts_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        // overrides
        for req in &arg.overrides {
            assert!(
                cmd.id_exists(req),
                "Command {}: Argument or group '{}' specified in 'overrides_with*' for '{}' does not exist",
                    cmd.get_name(),
                req,
                arg.get_id(),
            );
        }

        if arg.is_last_set() {
            assert!(
                arg.get_long().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a long and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
            assert!(
                arg.get_short().is_none(),
                "Command {}: Flags or Options cannot have last(true) set. '{}' has both a short and last(true) set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }

        assert!(
            !(arg.is_required_set() && arg.is_global_set()),
            "Command {}: Global arguments cannot be required.\n\n\t'{}' is marked as both global and required",
                    cmd.get_name(),
            arg.get_id()
        );

        if arg.get_value_hint() == ValueHint::CommandWithArguments {
            assert!(
                arg.is_positional(),
                "Command {}: Argument '{}' has hint CommandWithArguments and must be positional.",
                cmd.get_name(),
                arg.get_id()
            );

            assert!(
                arg.is_trailing_var_arg_set() || arg.is_last_set(),
                "Command {}: Positional argument '{}' has hint CommandWithArguments, so Command must have `trailing_var_arg(true)` or `last(true)` set.",
                    cmd.get_name(),
                arg.get_id()
            );
        }
    }

    for group in cmd.get_groups() {
        let derive_hint = if cfg!(feature = "derive") {
            " (note: `Args` implicitly creates `ArgGroup`s; disable with `#[group(skip)]`"
        } else {
            ""
        };

        // Name conflicts
        assert!(
            cmd.get_groups().filter(|x| x.id == group.id).count() < 2,
            "Command {}: Argument group name must be unique\n\n\t'{}' is already in use{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        // Groups should not have naming conflicts with Args
        assert!(
            !cmd.get_arguments().any(|x| x.get_id() == group.get_id()),
            "Command {}: Argument group name '{}' must not conflict with argument name{}",
            cmd.get_name(),
            group.get_id(),
            derive_hint
        );

        for arg in &group.args {
            // Args listed inside groups should exist
            assert!(
                cmd.get_arguments().any(|x| x.get_id() == arg),
                "Command {}: Argument group '{}' contains non-existent argument '{}'",
                cmd.get_name(),
                group.get_id(),
                arg
            );
        }
    }

    // Conflicts between flags and subcommands

    long_flags.sort_unstable();
    short_flags.sort_unstable();

    detect_duplicate_flags(&long_flags, "long");
    detect_duplicate_flags(&short_flags, "short");

    let mut subs = FlatSet::new();
    for sc in cmd.get_subcommands() {
        assert!(
            subs.insert(sc.get_name()),
            "Command {}: command name `{}` is duplicated",
            cmd.get_name(),
            sc.get_name()
        );
        for alias in sc.get_all_aliases() {
            assert!(
                subs.insert(alias),
                "Command {}: command `{}` alias `{}` is duplicated",
                cmd.get_name(),
                sc.get_name(),
                alias
            );
        }
    }

    _verify_positionals(cmd);

    #[cfg(feature = "help")]
    if let Some(help_template) = cmd.get_help_template() {
        assert!(
            !help_template.to_string().contains("{flags}"),
            "Command {}: {}",
                    cmd.get_name(),
            "`{flags}` template variable was removed in clap3, they are now included in `{options}`",
        );
        assert!(
            !help_template.to_string().contains("{unified}"),
            "Command {}: {}",
            cmd.get_name(),
            "`{unified}` template variable was removed in clap3, use `{options}` instead"
        );
    }

    cmd._panic_on_missing_help(cmd.is_help_expected_set());
    assert_app_flags(cmd);
}

Prepare for introspecting on all included Commands

Call this on the top-level Command when done building and before reading state for cases like completions, custom help output, etc.

Examples found in repository?
src/builder/command.rs (line 456)
455
456
457
    pub fn debug_assert(mut self) {
        self.build();
    }

Trait Implementations§

Returns a copy of the value. Read more
Performs copy-assignment from source. Read more
Formats the value using the given formatter. Read more
Returns the “default value” for a type. Read more
Formats the value using the given formatter. Read more
Converts to this type from the input type.
The returned type after indexing.
Performs the indexing (container[index]) operation. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more

Returns the argument unchanged.

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more
Converts the given value to a String. Read more
The type returned in the event of a conversion error.
Performs the conversion.
The type returned in the event of a conversion error.
Performs the conversion.