1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 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
#[cfg(debug_assertions)]
mod debug_asserts;
mod settings;
#[cfg(test)]
mod tests;
pub use self::settings::AppSettings;
// Std
use std::{
collections::HashMap,
env,
ffi::OsString,
fmt,
io::{self, BufRead, Write},
ops::Index,
path::Path,
};
// Third Party
#[cfg(feature = "yaml")]
use yaml_rust::Yaml;
// Internal
use crate::{
build::{app::settings::AppFlags, arg::ArgProvider, Arg, ArgGroup, ArgSettings},
mkeymap::MKeyMap,
output::{fmt::Colorizer, Help, HelpWriter, Usage},
parse::{ArgMatcher, ArgMatches, Input, Parser},
util::{safe_exit, termcolor::ColorChoice, ArgStr, Id, Key, USAGE_CODE},
Result as ClapResult, INTERNAL_ERROR_MSG,
};
/// Represents a command line interface which is made up of all possible
/// command line arguments and subcommands. Interface arguments and settings are
/// configured using the "builder pattern." Once all configuration is complete,
/// the [`App::get_matches`] family of methods starts the runtime-parsing
/// process. These methods then return information about the user supplied
/// arguments (or lack thereof).
///
/// **NOTE:** There aren't any mandatory "options" that one must set. The "options" may
/// also appear in any order (so long as one of the [`App::get_matches`] methods is the last method
/// called).
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// let m = App::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").index(1)
/// )
/// .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...
/// ```
/// [`App::get_matches`]: App::get_matches()
#[derive(Default, Debug, Clone, PartialEq, Eq)]
pub struct App<'help> {
pub(crate) id: Id,
pub(crate) name: String,
pub(crate) long_flag: Option<&'help str>,
pub(crate) short_flag: Option<char>,
pub(crate) bin_name: Option<String>,
pub(crate) author: Option<&'help str>,
pub(crate) version: Option<&'help str>,
pub(crate) long_version: Option<&'help str>,
pub(crate) license: Option<&'help str>,
pub(crate) about: Option<&'help str>,
pub(crate) long_about: Option<&'help str>,
pub(crate) before_help: Option<&'help str>,
pub(crate) before_long_help: Option<&'help str>,
pub(crate) after_help: Option<&'help str>,
pub(crate) after_long_help: Option<&'help str>,
pub(crate) aliases: Vec<(&'help str, bool)>, // (name, visible)
pub(crate) short_flag_aliases: Vec<(char, bool)>, // (name, visible)
pub(crate) long_flag_aliases: Vec<(&'help str, bool)>, // (name, visible)
pub(crate) usage_str: Option<&'help str>,
pub(crate) usage: Option<String>,
pub(crate) help_str: Option<&'help str>,
pub(crate) disp_ord: usize,
pub(crate) term_w: Option<usize>,
pub(crate) max_w: Option<usize>,
pub(crate) template: Option<&'help str>,
pub(crate) settings: AppFlags,
pub(crate) g_settings: AppFlags,
pub(crate) args: MKeyMap<'help>,
pub(crate) subcommands: Vec<App<'help>>,
pub(crate) replacers: HashMap<&'help str, &'help [&'help str]>,
pub(crate) groups: Vec<ArgGroup<'help>>,
pub(crate) current_help_heading: Option<&'help str>,
pub(crate) subcommand_placeholder: Option<&'help str>,
pub(crate) subcommand_header: Option<&'help str>,
}
impl<'help> App<'help> {
/// Get the name of the app.
#[inline]
pub fn get_name(&self) -> &str {
&self.name
}
/// 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
}
/// 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<S: Into<String>>(&mut self, name: S) {
self.bin_name = Some(name.into());
}
/// Get the help message specified via [`App::about`].
///
/// [`App::about`]: App::about()
#[inline]
pub fn get_about(&self) -> Option<&str> {
self.about.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)
}
/// 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 = &'help str> + '_ {
self.long_flag_aliases
.iter()
.filter(|(_, vis)| *vis)
.map(|a| a.0)
}
/// 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)
}
/// 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 = &'help str> + '_ {
self.long_flag_aliases.iter().map(|a| a.0)
}
/// Iterate through the set of subcommands, getting a reference to each.
#[inline]
pub fn get_subcommands(&self) -> impl Iterator<Item = &App<'help>> {
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 App<'help>> {
self.subcommands.iter_mut()
}
/// Iterate through the set of arguments.
#[inline]
pub fn get_arguments(&self) -> impl Iterator<Item = &Arg<'help>> {
self.args.args()
}
/// Iterate through the *positionals*.
#[inline]
pub fn get_positionals(&self) -> impl Iterator<Item = &Arg<'help>> {
self.get_arguments().filter(|a| a.is_positional())
}
/// Iterate through the *flags*.
pub fn get_flags(&self) -> impl Iterator<Item = &Arg<'help>> {
self.get_arguments()
.filter(|a| !a.is_set(ArgSettings::TakesValue) && a.get_index().is_none())
}
/// Iterate through the *options*.
pub fn get_opts(&self) -> impl Iterator<Item = &Arg<'help>> {
self.get_arguments()
.filter(|a| a.is_set(ArgSettings::TakesValue) && a.get_index().is_none())
}
/// Iterate through the *positionals* that don't have custom heading.
pub fn get_positionals_with_no_heading(&self) -> impl Iterator<Item = &Arg<'help>> {
self.get_positionals()
.filter(|a| a.get_help_heading().is_none())
}
/// Iterate through the *flags* that don't have custom heading.
pub fn get_flags_with_no_heading(&self) -> impl Iterator<Item = &Arg<'help>> {
self.get_flags().filter(|a| a.get_help_heading().is_none())
}
/// Iterate through the *options* that don't have custom heading.
pub fn get_opts_with_no_heading(&self) -> impl Iterator<Item = &Arg<'help>> {
self.get_opts().filter(|a| a.get_help_heading().is_none())
}
// 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<&App<'help>> {
let mut vec = std::vec::Vec::new();
for idx in 0..self.subcommands.len() {
if self.subcommands[idx].args.args().any(|ar| ar.id == arg.id) {
vec.push(&self.subcommands[idx]);
vec.append(&mut self.subcommands[idx].get_subcommands_containing(arg));
}
}
vec
}
// 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 `App`.
fn get_global_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg<'help>> // 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.id == *id)
.expect(
"App::get_arg_conflicts_with: \
The passed arg conflicts with an arg unknown to the app",
)
})
.collect()
}
/// 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 `App`.
pub fn get_arg_conflicts_with(&self, arg: &Arg) -> Vec<&Arg<'help>> // FIXME: This could probably have been an iterator
{
if arg.global {
self.get_global_arg_conflicts_with(arg)
} else {
arg.blacklist
.iter()
.map(|id| {
self.args.args().find(|arg| arg.id == *id).expect(
"App::get_arg_conflicts_with: \
The passed arg conflicts with an arg unknown to the app",
)
})
.collect()
}
}
/// Returns `true` if the given [`AppSettings`] variant is currently set in
/// this `App` (checks both [local] and [global settings]).
///
/// [local]: App::setting()
/// [global settings]: App::global_setting()
#[inline]
pub fn is_set(&self, s: AppSettings) -> bool {
self.settings.is_set(s) || self.g_settings.is_set(s)
}
/// Returns `true` if this `App` has subcommands.
#[inline]
pub fn has_subcommands(&self) -> bool {
!self.subcommands.is_empty()
}
/// 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<T>(&self, name: &T) -> Option<&App<'help>>
where
T: PartialEq<str> + ?Sized,
{
self.get_subcommands().find(|s| s.aliases_to(name))
}
}
impl<'help> App<'help> {
/// Creates a new instance of an `App` requiring a `name`.
///
/// 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.
///
/// An `App` represents a command line interface (CLI) which is made up of
/// all possible command line arguments and subcommands. "Subcommands" are
/// sub-CLIs with their own arguments, settings, and even subcommands
/// forming a sort of hierarchy.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("My Program")
/// # ;
/// ```
pub fn new<S: Into<String>>(name: S) -> Self {
let name = name.into();
App {
id: Id::from(&*name),
name,
disp_ord: 999,
..Default::default()
}
.arg(
Arg::new("help")
.long("help")
.about("Print help information")
.global(true)
.generated(),
)
.arg(
Arg::new("version")
.long("version")
.about("Print version information")
.global(true)
.generated(),
)
}
/// Sets a string of author(s) that will be displayed to the user when they
/// request 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.
///
/// See the [`examples/`] directory for more information.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .author("Me, me@mymain.com")
/// # ;
/// ```
/// [`crate_authors!`]: ./macro.crate_authors!.html
/// [`examples/`]: https://github.com/clap-rs/clap/tree/master/examples
pub fn author<S: Into<&'help str>>(mut self, author: S) -> Self {
self.author = Some(author.into());
self
}
/// Overrides the runtime-determined name of the binary. 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.
///
/// Normally, the binary name is used in help and error messages. `clap`
/// automatically determines the binary name at runtime, however by manually
/// setting the binary name, one can effectively override what will be
/// displayed in the help or error messages.
///
/// **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::App;
/// App::new("My Program")
/// .bin_name("my_binary")
/// # ;
/// ```
pub fn bin_name<S: Into<String>>(mut self, name: S) -> Self {
self.bin_name = Some(name.into());
self
}
/// Sets a string describing what the program does. This will be displayed
/// when the user requests the short format help message (`-h`).
///
/// `clap` can display two different help messages, a [long format] and a
/// [short format] depending on whether the user used `-h` (short) or
/// `--help` (long). This method sets the message during the short format
/// (`-h`) message. However, if no long format message is configured, this
/// message will be displayed for *both* the long format, or short format
/// help message.
///
/// **NOTE:** Only [`App::about`] (short format) is used in completion
/// script generation in order to be concise.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .about("Does really amazing things for great people")
/// # ;
/// ```
/// [long format]: App::long_about()
/// [short format]: App::about()
/// [`App::about`]: App::about()
pub fn about<S: Into<&'help str>>(mut self, about: S) -> Self {
self.about = Some(about.into());
self
}
/// Sets a long format string describing what the program does. This will be
/// displayed when the user requests the long format help message (`--help`).
///
/// ## Advanced
///
/// `clap` can display two different help messages, a [long format] and a
/// [short format] depending on whether the user used `-h` (short) or
/// `--help` (long). This method sets the message during the long format
/// (`--help`) message. However, if no short format message is configured,
/// this message will be displayed for *both* the long format, or short
/// format help message.
///
/// **NOTE:** Only [`App::about`] (short format) is used in completion
/// script generation in order to be concise.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::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!")
/// # ;
/// ```
/// [long format]: App::long_about()
/// [short format]: App::about()
/// [`App::about`]: App::about()
pub fn long_about<S: Into<&'help str>>(mut self, about: S) -> Self {
self.long_about = Some(about.into());
self
}
/// (Re)Sets the program's name. This will be displayed when displaying help
/// or version messages.
///
/// **Pro-tip:** This function is particularly useful when configuring a
/// program via `App::from(yaml)` in conjunction with the [`crate_name!`]
/// macro to derive the program's name from its `Cargo.toml`.
///
/// # Examples
///
/// ```ignore
/// # use clap::{App, load_yaml};
/// let yaml = load_yaml!("app.yaml");
/// let app = App::from(yaml)
/// .name(crate_name!());
///
/// // continued logic goes here, such as `app.get_matches()` etc.
/// ```
///
pub fn name<S: Into<String>>(mut self, name: S) -> Self {
self.name = name.into();
self
}
/// Adds additional help information to be displayed at the end of the
/// auto-generated help. This is often used to describe how to use the
/// arguments, caveats to be noted, or license and contact information.
///
/// **NOTE:** If only `after_long_help` is provided, and not [`App::after_help`] but the user requests
/// `-h` clap will still display the contents of `after_help` appropriately.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .after_help("Does really amazing things for great people... but be careful with -R!")
/// # ;
/// ```
///
/// [`App::after_help`]: App::after_help()
pub fn after_help<S: Into<&'help str>>(mut self, help: S) -> Self {
self.after_help = Some(help.into());
self
}
/// Adds additional help information to be displayed in addition to auto-generated help. This
/// information is displayed **after** the auto-generated help information and is meant to be
/// more verbose than `after_help`. This is often used to describe how to use the arguments, or
/// caveats to be noted in man pages.
///
/// **NOTE:** If only `after_help` is provided, and not [`App::after_long_help`] but the user
/// requests `--help`, clap will still display the contents of `after_help` appropriately.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .after_long_help("Does really amazing things to great people... but be careful with -R, \
/// like, for real, be careful with this!")
/// # ;
/// ```
/// [`App::after_long_help`]: App::after_long_help()
pub fn after_long_help<S: Into<&'help str>>(mut self, help: S) -> Self {
self.after_long_help = Some(help.into());
self
}
/// Adds additional help information to be displayed prior to the
/// auto-generated help. This is often used for header, copyright, or
/// license information.
///
/// **NOTE:** If only `before_long_help` is provided, and not [`App::before_help`] but the user
/// requests `-h` clap will still display the contents of `before_long_help` appropriately.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .before_help("Some info I'd like to appear before the help info")
/// # ;
/// ```
/// [`App::before_help`]: App::before_help()
pub fn before_help<S: Into<&'help str>>(mut self, help: S) -> Self {
self.before_help = Some(help.into());
self
}
/// Adds additional help information to be displayed prior to the
/// auto-generated help. This is often used for header, copyright, or
/// license information.
///
/// **NOTE:** If only `before_help` is provided, and not [`App::before_long_help`] but the user
/// requests `--help`, clap will still display the contents of `before_help` appropriately.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .before_long_help("Some verbose and long info I'd like to appear before the help info")
/// # ;
/// ```
/// [`App::before_long_help`]: App::before_long_help()
pub fn before_long_help<S: Into<&'help str>>(mut self, help: S) -> Self {
self.before_long_help = Some(help.into());
self
}
/// Allows the subcommand to be used as if it were an [`Arg::short`].
///
/// Sets the short version of the subcommand flag without the preceding `-`.
///
/// # Examples
///
/// ```
/// # use clap::{App, Arg};
/// let matches = App::new("pacman")
/// .subcommand(
/// App::new("sync").short_flag('S').arg(
/// Arg::new("search")
/// .short('s')
/// .long("search")
/// .about("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.is_present("search"));
/// ```
/// [`Arg::short`]: Arg::short()
pub fn short_flag(mut self, short: char) -> Self {
self.short_flag = Some(short);
self
}
/// Allows the subcommand to be used as if it were an [`Arg::long`].
///
/// Sets the long version of the subcommand flag without the preceding `--`.
///
/// **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::{App, Arg};
/// let matches = App::new("pacman")
/// .subcommand(
/// App::new("sync").long_flag("sync").arg(
/// Arg::new("search")
/// .short('s')
/// .long("search")
/// .about("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.is_present("search"));
/// ```
///
/// [`Arg::long`]: Arg::long()
pub fn long_flag(mut self, long: &'help str) -> Self {
self.long_flag = Some(long.trim_start_matches(|c| c == '-'));
self
}
/// Sets a string of the version number to be displayed when displaying the
/// short format version message (`-V`) or the help message.
///
/// **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. See the [`examples/`] directory for more
/// information.
///
/// `clap` can display two different version messages, a [long format] and a
/// [short format] depending on whether the user used `-V` (short) or
/// `--version` (long). This method sets the message during the short format
/// (`-V`). However, if no long format message is configured, this
/// message will be displayed for *both* the long format, or short format
/// version message.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .version("v0.1.24")
/// # ;
/// ```
/// [`crate_version!`]: ./macro.crate_version!.html
/// [`examples/`]: https://github.com/clap-rs/clap/tree/master/examples
/// [`App::long_version`]: App::long_version()
pub fn version<S: Into<&'help str>>(mut self, ver: S) -> Self {
self.version = Some(ver.into());
self
}
/// Sets a string of the version number to be displayed when the user
/// requests the long format version message (`--version`) or the help
/// message.
///
/// This is often used to display things such as commit ID, or compile time
/// configured options.
///
/// **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. See the [`examples/`] directory for more
/// information.
///
/// `clap` can display two different version messages, a [long format] and a
/// [short format] depending on whether the user used `-V` (short) or
/// `--version` (long). This method sets the message during the long format
/// (`--version`). However, if no short format message is configured, this
/// message will be displayed for *both* the long format, or short format
/// version message.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .long_version(
/// "v0.1.24
/// commit: abcdef89726d
/// revision: 123
/// release: 2
/// binary: myprog")
/// # ;
/// ```
/// [`crate_version!`]: ./macro.crate_version!.html
/// [`examples/`]: https://github.com/kbknapp/clap-rs/tree/master/examples
/// [`App::version`]: App::version()
pub fn long_version<S: Into<&'help str>>(mut self, ver: S) -> Self {
self.long_version = Some(ver.into());
self
}
/// Sets a string of the license to be displayed when displaying help information.
///
/// **Pro-tip:** Use `clap`s convenience macro [`crate_license!`] to automatically set your
/// application's license to the same thing as your crate at compile time. See the
/// [`examples/`] directory for more information
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// App::new("myprog")
/// .license("MIT OR Apache-2.0")
/// # ;
/// ```
/// [`crate_license!`]: ./macro.crate_license!.html
/// [`examples/`]: https://github.com/clap-rs/clap/tree/master/examples
pub fn license<S: Into<&'help str>>(mut self, license: S) -> Self {
self.license = Some(license.into());
self
}
/// Overrides the `clap` generated usage string.
///
/// This will be displayed to the user when errors are found in argument parsing.
///
/// **CAUTION:** 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:** This will not replace the entire help message, *only* the portion
/// showing the usage.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// App::new("myprog")
/// .override_usage("myapp [-clDas] <some_file>")
/// # ;
/// ```
/// [`ArgMatches::usage`]: ArgMatches::usage()
pub fn override_usage<S: Into<&'help str>>(mut self, usage: S) -> Self {
self.usage_str = Some(usage.into());
self
}
/// Overrides the `clap` generated help message. This should only be used
/// when the auto-generated message does not suffice.
///
/// This will be displayed to the user when they use `--help` or `-h`.
///
/// **NOTE:** This replaces the **entire** help message, so nothing will be
/// auto-generated.
///
/// **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 [`App::override_help`] for
/// them as well.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// App::new("myapp")
/// .override_help("myapp v1.0\n\
/// Does awesome things\n\
/// (C) me@mail.com\n\n\
///
/// USAGE: myapp <opts> <comamnd>\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\
///
/// Commmands:\n\
/// help Print this message\n\
/// work Do some work")
/// # ;
/// ```
pub fn override_help<S: Into<&'help str>>(mut self, help: S) -> Self {
self.help_str = Some(help.into());
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:
///
/// * `{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 [`App::about`] or
/// [`App::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.
/// * `{unified}` - Unified help for options and flags. Note, you must *also*
/// set [`AppSettings::UnifiedHelpMessage`] to fully merge both
/// options and flags, otherwise the ordering is "best effort".
/// * `{flags}` - Help for flags.
/// * `{options}` - Help for options.
/// * `{positionals}` - Help for positional arguments.
/// * `{subcommands}` - Help for subcommands.
/// * `{after-help}` - Help from [`App::after_help`] or [`App::after_long_help`].
/// * `{before-help}` - Help from [`App::before_help`] or [`App::before_long_help`].
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .version("1.0")
/// .help_template("{bin} ({version}) - {usage}")
/// # ;
/// ```
/// [`App::about`]: App::about()
/// [`App::long_about`]: App::long_about()
/// [`App::after_help`]: App::after_help()
/// [`App::after_long_help`]: App::after_long_help()
/// [`App::before_help`]: App::before_help()
/// [`App::before_long_help`]: App::before_long_help()
pub fn help_template<S: Into<&'help str>>(mut self, s: S) -> Self {
self.template = Some(s.into());
self
}
/// Enables a single settings for the current (this `App` instance) command or subcommand.
///
/// See [`AppSettings`] for a full list of possibilities and examples.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, AppSettings};
/// App::new("myprog")
/// .setting(AppSettings::SubcommandRequired)
/// .setting(AppSettings::WaitOnError)
/// # ;
/// ```
#[inline]
pub fn setting(mut self, setting: AppSettings) -> Self {
self.settings.set(setting);
self
}
/// Disables a single setting for the current (this `App` instance) command or subcommand.
///
/// See [`AppSettings`] for a full list of possibilities and examples.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, AppSettings};
/// App::new("myprog")
/// .unset_setting(AppSettings::ColorAuto)
/// # ;
/// ```
#[inline]
pub fn unset_setting(mut self, setting: AppSettings) -> Self {
self.settings.unset(setting);
self
}
/// Enables a single setting that is propagated **down** through all child
/// subcommands.
///
/// See [`AppSettings`] for a full list of possibilities and examples.
///
/// **NOTE**: The setting is *only* propagated *down* and not up through parent commands.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, AppSettings};
/// App::new("myprog")
/// .global_setting(AppSettings::SubcommandRequired)
/// # ;
/// ```
#[inline]
pub fn global_setting(mut self, setting: AppSettings) -> Self {
self.settings.set(setting);
self.g_settings.set(setting);
self
}
/// Disables a global setting, and stops propagating down to child
/// subcommands.
///
/// See [`AppSettings`] for a full list of possibilities and examples.
///
/// **NOTE:** The setting being unset will be unset from both local and
/// [global] settings.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, AppSettings};
/// App::new("myprog")
/// .unset_global_setting(AppSettings::ColorAuto)
/// # ;
/// ```
/// [global]: App::global_setting()
#[inline]
pub fn unset_global_setting(mut self, setting: AppSettings) -> Self {
self.settings.unset(setting);
self.g_settings.unset(setting);
self
}
/// Sets the terminal width at which to wrap help messages. Defaults to
/// `100`. Using `0` will ignore terminal widths and use source formatting.
///
/// `clap` automatically tries to determine the terminal width on Unix,
/// Linux, OSX and Windows if the `wrap_help` cargo "feature" has been enabled
/// at compile time. If the terminal width cannot be determined, `clap`
/// fall back to `100`.
///
/// **NOTE:** This setting applies globally and *not* on a per-command basis.
///
/// **NOTE:** This setting must be set **before** any subcommands are added!
///
/// # Platform Specific
///
/// Only Unix, Linux, OSX and Windows support automatic determination of
/// terminal width. Even on those platforms, this setting is useful if for
/// any reason the terminal width cannot be determined.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .term_width(80)
/// # ;
/// ```
#[inline]
pub fn term_width(mut self, width: usize) -> Self {
self.term_w = Some(width);
self
}
/// Sets the maximum terminal width at which to wrap help messages. Using `0`
/// will ignore terminal widths and use source formatting.
///
/// `clap` automatically tries to determine the terminal width on Unix,
/// Linux, OSX and Windows if the `wrap_help` cargo "feature" has been
/// enabled at compile time, but one might want to limit the size to some
/// maximum (e.g. when the terminal is running fullscreen).
///
/// **NOTE:** This setting applies globally and *not* on a per-command basis.
///
/// **NOTE:** This setting must be set **before** any subcommands are added!
///
/// # Platform Specific
///
/// Only Unix, Linux, OSX and Windows support automatic determination of terminal width.
///
/// # Examples
///
/// ```no_run
/// # use clap::App;
/// App::new("myprog")
/// .max_term_width(100)
/// # ;
/// ```
#[inline]
pub fn max_term_width(mut self, w: usize) -> Self {
self.max_w = Some(w);
self
}
/// Adds an [argument] to the list of valid possibilities.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// App::new("myprog")
/// // Adding a single "flag" argument with a short and help text, using Arg::new()
/// .arg(
/// Arg::new("debug")
/// .short('d')
/// .about("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::from("-c --config=[CONFIG] 'Optionally sets a config file to use'")
/// )
/// # ;
/// ```
/// [argument]: Arg
pub fn arg<A: Into<Arg<'help>>>(mut self, a: A) -> Self {
let mut arg = a.into();
if let Some(help_heading) = self.current_help_heading {
arg = arg.help_heading(Some(help_heading));
}
self.args.push(arg);
self
}
/// Set a custom section heading for future args. Every call to [`App::arg`]
/// (and its related methods) will use this header (instead of the default
/// header for the specified argument type) until a subsequent call to
/// [`App::help_heading`] or [`App::stop_custom_headings`].
///
/// This is useful if the default `FLAGS`, `OPTIONS`, or `ARGS` headings are
/// not specific enough for one's use case.
///
/// [`App::arg`]: App::arg()
/// [`App::help_heading`]: App::help_heading()
/// [`App::stop_custom_headings`]: App::stop_custom_headings()
#[inline]
pub fn help_heading(mut self, heading: &'help str) -> Self {
self.current_help_heading = Some(heading);
self
}
/// Stop using [custom argument headings] and return to default headings.
///
/// [custom argument headings]: App::help_heading()
#[inline]
pub fn stop_custom_headings(mut self) -> Self {
self.current_help_heading = None;
self
}
/// Adds multiple [arguments] to the list of valid possibilities.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// App::new("myprog")
/// .args(&[
/// Arg::from("[debug] -d 'turns on debugging info'"),
/// Arg::new("input").index(1).about("the input file to use")
/// ])
/// # ;
/// ```
/// [arguments]: Arg
pub fn args<I, T>(mut self, args: I) -> Self
where
I: IntoIterator<Item = T>,
T: Into<Arg<'help>>,
{
// @TODO @perf @p4 @v3-beta: maybe extend_from_slice would be possible and perform better?
// But that may also not let us do `&["-a 'some'", "-b 'other']` because of not Into<Arg>
for arg in args.into_iter() {
self.args.push(arg.into());
}
self
}
/// If this `App` instance is a subcommand, this method adds an alias, which
/// allows this 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 [`App::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::{App, Arg, };
/// let m = App::new("myprog")
/// .subcommand(App::new("test")
/// .alias("do-stuff"))
/// .get_matches_from(vec!["myprog", "do-stuff"]);
/// assert_eq!(m.subcommand_name(), Some("test"));
/// ```
/// [`App::visible_alias`]: App::visible_alias()
pub fn alias<S: Into<&'help str>>(mut self, name: S) -> Self {
self.aliases.push((name.into(), false));
self
}
/// Allows adding an alias, which function as "hidden" short flag subcommands that
/// 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::{App, Arg, };
/// let m = App::new("myprog")
/// .subcommand(App::new("test").short_flag('t')
/// .short_flag_alias('d'))
/// .get_matches_from(vec!["myprog", "-d"]);
/// assert_eq!(m.subcommand_name(), Some("test"));
/// ```
pub fn short_flag_alias(mut self, name: char) -> Self {
if name == '-' {
panic!("short alias name cannot be `-`");
}
self.short_flag_aliases.push((name, false));
self
}
/// Allows adding an alias, which function as "hidden" long flag subcommands that
/// 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::{App, Arg, };
/// let m = App::new("myprog")
/// .subcommand(App::new("test").long_flag("test")
/// .long_flag_alias("testing"))
/// .get_matches_from(vec!["myprog", "--testing"]);
/// assert_eq!(m.subcommand_name(), Some("test"));
/// ```
pub fn long_flag_alias(mut self, name: &'help str) -> Self {
self.long_flag_aliases.push((name, false));
self
}
/// If this `App` instance is a subcommand, this method adds a multiple
/// aliases, which allows this 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 [`App::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::{App, Arg};
/// let m = App::new("myprog")
/// .subcommand(App::new("test")
/// .aliases(&["do-stuff", "do-tests", "tests"]))
/// .arg(Arg::new("input")
/// .about("the file to add")
/// .index(1)
/// .required(false))
/// .get_matches_from(vec!["myprog", "do-tests"]);
/// assert_eq!(m.subcommand_name(), Some("test"));
/// ```
/// [`App::visible_aliases`]: App::visible_aliases()
pub fn aliases(mut self, names: &[&'help str]) -> Self {
self.aliases.extend(names.iter().map(|n| (*n, false)));
self
}
/// Allows adding aliases, which function as "hidden" short flag subcommands that
/// 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::{App, Arg, };
/// let m = App::new("myprog")
/// .subcommand(App::new("test").short_flag('t')
/// .short_flag_aliases(&['a', 'b', 'c']))
/// .arg(Arg::new("input")
/// .about("the file to add")
/// .index(1)
/// .required(false))
/// .get_matches_from(vec!["myprog", "-a"]);
/// assert_eq!(m.subcommand_name(), Some("test"));
/// ```
pub fn short_flag_aliases(mut self, names: &[char]) -> Self {
for s in names {
if s == &'-' {
panic!("short alias name cannot be `-`");
}
self.short_flag_aliases.push((*s, false));
}
self
}
/// Allows adding aliases, which function as "hidden" long flag subcommands that
/// 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::{App, Arg, };
/// let m = App::new("myprog")
/// .subcommand(App::new("test").long_flag("test")
/// .long_flag_aliases(&["testing", "testall", "test_all"]))
/// .arg(Arg::new("input")
/// .about("the file to add")
/// .index(1)
/// .required(false))
/// .get_matches_from(vec!["myprog", "--testing"]);
/// assert_eq!(m.subcommand_name(), Some("test"));
/// ```
pub fn long_flag_aliases(mut self, names: &[&'help str]) -> Self {
for s in names {
self.long_flag_aliases.push((s, false));
}
self
}
/// If this `App` instance is a subcommand, this method adds a visible
/// alias, which allows this 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
/// [`App::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::{App, Arg};
/// let m = App::new("myprog")
/// .subcommand(App::new("test")
/// .visible_alias("do-stuff"))
/// .get_matches_from(vec!["myprog", "do-stuff"]);
/// assert_eq!(m.subcommand_name(), Some("test"));
/// ```
/// [`App::alias`]: App::alias()
pub fn visible_alias<S: Into<&'help str>>(mut self, name: S) -> Self {
self.aliases.push((name.into(), true));
self
}
/// Allows adding an alias that functions exactly like those defined with
/// [`App::short_flag_alias`], except that they are visible inside the help message.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg, };
/// let m = App::new("myprog")
/// .subcommand(App::new("test").short_flag('t')
/// .visible_short_flag_alias('d'))
/// .get_matches_from(vec!["myprog", "-d"]);
/// assert_eq!(m.subcommand_name(), Some("test"));
/// ```
/// [`App::short_flag_alias`]: App::short_flag_alias()
pub fn visible_short_flag_alias(mut self, name: char) -> Self {
if name == '-' {
panic!("short alias name cannot be `-`");
}
self.short_flag_aliases.push((name, true));
self
}
/// Allows adding an alias that functions exactly like those defined with
/// [`App::long_flag_alias`], except that they are visible inside the help message.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg, };
/// let m = App::new("myprog")
/// .subcommand(App::new("test").long_flag("test")
/// .visible_long_flag_alias("testing"))
/// .get_matches_from(vec!["myprog", "--testing"]);
/// assert_eq!(m.subcommand_name(), Some("test"));
/// ```
/// [`App::long_flag_alias`]: App::long_flag_alias()
pub fn visible_long_flag_alias(mut self, name: &'help str) -> Self {
self.long_flag_aliases.push((name, true));
self
}
/// If this `App` instance is a subcommand, this method adds multiple visible
/// aliases, which allows this 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
/// [`App::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::{App, Arg, };
/// let m = App::new("myprog")
/// .subcommand(App::new("test")
/// .visible_aliases(&["do-stuff", "tests"]))
/// .get_matches_from(vec!["myprog", "do-stuff"]);
/// assert_eq!(m.subcommand_name(), Some("test"));
/// ```
/// [`App::alias`]: App::alias()
pub fn visible_aliases(mut self, names: &[&'help str]) -> Self {
self.aliases.extend(names.iter().map(|n| (*n, true)));
self
}
/// Allows adding multiple short flag aliases that functions exactly like those defined
/// with [`App::short_flag_aliases`], except that they are visible inside the help message.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg, };
/// let m = App::new("myprog")
/// .subcommand(App::new("test").short_flag('b')
/// .visible_short_flag_aliases(&['t']))
/// .get_matches_from(vec!["myprog", "-t"]);
/// assert_eq!(m.subcommand_name(), Some("test"));
/// ```
/// [`App::short_flag_aliases`]: App::short_flag_aliases()
pub fn visible_short_flag_aliases(mut self, names: &[char]) -> Self {
for s in names {
if s == &'-' {
panic!("short alias name cannot be `-`");
}
self.short_flag_aliases.push((*s, true));
}
self
}
/// Allows adding multiple long flag aliases that functions exactly like those defined
/// with [`App::long_flag_aliases`], except that they are visible inside the help message.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg, };
/// let m = App::new("myprog")
/// .subcommand(App::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"));
/// ```
/// [`App::long_flag_aliases`]: App::long_flag_aliases()
pub fn visible_long_flag_aliases(mut self, names: &[&'help str]) -> Self {
for s in names {
self.long_flag_aliases.push((s, true));
}
self
}
/// Replaces an argument or subcommand used on the CLI at runtime with other arguments or subcommands.
///
/// 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.
///
/// Some examples may help to clear this up.
///
/// # 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 `app module`. Now let's also assume `module` also has a subcommand
/// called `install` which can be invoked `app module install`. If for some
/// reason users needed to be able to reach `app module install` via the
/// short-hand `app 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 `app module install` handling code. This is error prone and
/// tedious.
///
/// We could instead use [`App::replace`] so that, when the user types `app
/// 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::App;
/// let m = App::new("app")
/// .subcommand(App::new("module")
/// .subcommand(App::new("install")))
/// .replace("install", &["module", "install"])
/// .get_matches_from(vec!["app", "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 `app --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 [`App::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::{App, Arg};
/// let m = App::new("app")
/// .arg(Arg::new("save-context")
/// .long("save-context"))
/// .arg(Arg::new("save-runtime")
/// .long("save-runtime"))
/// .replace("--save-all", &["--save-context", "--save-runtime"])
/// .get_matches_from(vec!["app", "--save-all"]);
///
/// assert!(m.is_present("save-context"));
/// assert!(m.is_present("save-runtime"));
/// ```
///
/// 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::{App, Arg};
/// let m = App::new("app")
/// .arg(Arg::new("save-context")
/// .long("save-context"))
/// .arg(Arg::new("save-runtime")
/// .long("save-runtime"))
/// .arg(Arg::new("format")
/// .long("format")
/// .takes_value(true)
/// .possible_values(&["txt", "json"]))
/// .replace("--save-all", &["--save-context", "--save-runtime", "--format=json"])
/// .get_matches_from(vec!["app", "--save-all"]);
///
/// assert!(m.is_present("save-context"));
/// assert!(m.is_present("save-runtime"));
/// assert_eq!(m.value_of("format"), Some("json"));
/// ```
///
/// [`App::replace`]: App::replace()
#[inline]
pub fn replace(mut self, name: &'help str, target: &'help [&'help str]) -> Self {
self.replacers.insert(name, target);
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.
/// For instance, you can make an entire [`ArgGroup`] required, meaning that one (and *only*
/// one) argument from that group must be present at runtime.
///
/// You can also do things such as 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.
///
/// Another added benefit of [`ArgGroup`]s is that you can extract a value from a group instead
/// of determining exactly which argument was used.
///
/// Finally, using [`ArgGroup`]s to ensure exclusion between arguments is another very common
/// use.
///
/// # 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::{App, ArgGroup};
/// App::new("app")
/// .arg("--set-ver [ver] 'set the version manually'")
/// .arg("--major 'auto increase major'")
/// .arg("--minor 'auto increase minor'")
/// .arg("--patch 'auto increase patch'")
/// .group(ArgGroup::new("vers")
/// .args(&["set-ver", "major", "minor","patch"])
/// .required(true))
/// # ;
/// ```
#[inline]
pub fn group<G: Into<ArgGroup<'help>>>(mut self, group: G) -> Self {
self.groups.push(group.into());
self
}
/// Adds multiple [`ArgGroup`]s to the [`App`] at once.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, ArgGroup};
/// App::new("app")
/// .arg("--set-ver [ver] 'set the version manually'")
/// .arg("--major 'auto increase major'")
/// .arg("--minor 'auto increase minor'")
/// .arg("--patch 'auto increase patch'")
/// .arg("-c [FILE] 'a config file'")
/// .arg("-i [IFACE] 'an interface'")
/// .groups(&[
/// ArgGroup::new("vers")
/// .args(&["set-ver", "major", "minor","patch"])
/// .required(true),
/// ArgGroup::new("input")
/// .args(&["c", "i"])
/// ])
/// # ;
/// ```
pub fn groups<I, T>(mut self, groups: I) -> Self
where
I: IntoIterator<Item = T>,
T: Into<ArgGroup<'help>>,
{
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-[`App`]s, because they can contain their own arguments, subcommands, version, usage,
/// etc. They also function just like [`App`]s, in that they get their own auto generated help,
/// version, and usage.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg, };
/// App::new("myprog")
/// .subcommand(App::new("config")
/// .about("Controls configuration features")
/// .arg("<config> 'Required configuration file to use'"))
/// # ;
/// ```
#[inline]
pub fn subcommand<S: Into<App<'help>>>(mut self, subcmd: S) -> Self {
self.subcommands.push(subcmd.into());
self
}
/// Adds multiple subcommands to the list of valid possibilities by iterating over an
/// [`IntoIterator`] of [`App`]s.
///
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg, };
/// # App::new("myprog")
/// .subcommands( vec![
/// App::new("config").about("Controls configuration functionality")
/// .arg(Arg::new("config_file").index(1)),
/// App::new("debug").about("Controls debug functionality")])
/// # ;
/// ```
/// [`IntoIterator`]: std::iter::IntoIterator
pub fn subcommands<I, T>(mut self, subcmds: I) -> Self
where
I: IntoIterator<Item = T>,
T: Into<App<'help>>,
{
for subcmd in subcmds.into_iter() {
self.subcommands.push(subcmd.into());
}
self
}
/// Allows custom ordering of subcommands within the help message. Subcommands with a lower
/// value will be displayed first in the help message. This is helpful when one would like to
/// emphasize frequently used subcommands, or prioritize those towards the top of the list.
/// Duplicate values **are** allowed. Subcommands with duplicate display orders will be
/// displayed in alphabetical order.
///
/// **NOTE:** The default is 999 for all subcommands.
///
/// # Examples
///
/// ```rust
/// # use clap::{App, };
/// let m = App::new("cust-ord")
/// .subcommand(App::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(App::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 [FLAGS] [OPTIONS]
///
/// FLAGS:
/// -h, --help Print help information
/// -V, --version Print version information
///
/// SUBCOMMANDS:
/// beta I should be first!
/// alpha Some help and text
/// ```
#[inline]
pub fn display_order(mut self, ord: usize) -> Self {
self.disp_ord = ord;
self
}
/// Allows one to mutate an [`Arg`] after it's been added to an [`App`].
///
/// # Examples
///
/// ```rust
/// # use clap::{App, Arg};
///
/// let mut app = App::new("foo")
/// .arg(Arg::new("bar")
/// .short('b'))
/// .mut_arg("bar", |a| a.short('B'));
///
/// let res = app.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 = app.try_get_matches_from_mut(vec!["foo", "-B"]);
/// assert!(res.is_ok());
/// ```
pub fn mut_arg<T, F>(mut self, arg_id: T, f: F) -> Self
where
F: FnOnce(Arg<'help>) -> Arg<'help>,
T: Key + Into<&'help str>,
{
let arg_id: &str = arg_id.into();
let id = Id::from(arg_id);
let mut a = self.args.remove_by_name(&id).unwrap_or_else(|| Arg {
id,
name: arg_id,
..Arg::default()
});
if a.provider == ArgProvider::Generated {
a.provider = ArgProvider::GeneratedMutated;
}
self.args.push(f(a));
self
}
/// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same
/// method as if someone ran `-h` to request the help message.
///
/// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
/// depending on if the user ran [`-h` (short)] or [`--help` (long)].
///
/// # Examples
///
/// ```rust
/// # use clap::App;
/// let mut app = App::new("myprog");
/// app.print_help();
/// ```
/// [`io::stdout()`]: std::io::stdout()
/// [`BufWriter`]: std::io::BufWriter
/// [`-h` (short)]: Arg::about()
/// [`--help` (long)]: Arg::long_about()
pub fn print_help(&mut self) -> io::Result<()> {
self._build();
let p = Parser::new(self);
let mut c = Colorizer::new(false, p.color_help());
Help::new(HelpWriter::Buffer(&mut c), &p, false).write_help()?;
c.print()
}
/// Prints the full help message to [`io::stdout()`] using a [`BufWriter`] using the same
/// method as if someone ran `--help` to request the help message.
///
/// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
/// depending on if the user ran [`-h` (short)] or [`--help` (long)].
///
/// # Examples
///
/// ```rust
/// # use clap::App;
/// let mut app = App::new("myprog");
/// app.print_long_help();
/// ```
/// [`io::stdout()`]: std::io::stdout()
/// [`BufWriter`]: std::io::BufWriter
/// [`-h` (short)]: Arg::about()
/// [`--help` (long)]: Arg::long_about()
pub fn print_long_help(&mut self) -> io::Result<()> {
self._build();
let p = Parser::new(self);
let mut c = Colorizer::new(false, p.color_help());
Help::new(HelpWriter::Buffer(&mut c), &p, true).write_help()?;
c.print()
}
/// Writes the full help message to the user to a [`io::Write`] object in the same method as if
/// the user ran `-h`.
///
/// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
/// depending on if the user ran [`-h` (short)] or [`--help` (long)].
///
/// # Examples
///
/// ```rust
/// # use clap::App;
/// use std::io;
/// let mut app = App::new("myprog");
/// let mut out = io::stdout();
/// app.write_help(&mut out).expect("failed to write to stdout");
/// ```
/// [`io::Write`]: std::io::Write
/// [`-h` (short)]: Arg::about()
/// [`--help` (long)]: Arg::long_about()
pub fn write_help<W: Write>(&mut self, w: &mut W) -> io::Result<()> {
self._build();
let p = Parser::new(self);
Help::new(HelpWriter::Normal(w), &p, false).write_help()?;
w.flush()
}
/// Writes the full help message to the user to a [`io::Write`] object in the same method as if
/// the user ran `--help`.
///
/// **NOTE:** clap has the ability to distinguish between "short" and "long" help messages
/// depending on if the user ran [`-h` (short)] or [`--help` (long)].
///
/// # Examples
///
/// ```rust
/// # use clap::App;
/// use std::io;
/// let mut app = App::new("myprog");
/// let mut out = io::stdout();
/// app.write_long_help(&mut out).expect("failed to write to stdout");
/// ```
/// [`io::Write`]: std::io::Write
/// [`-h` (short)]: Arg::about()
/// [`--help` (long)]: Arg::long_about()
pub fn write_long_help<W: Write>(&mut self, w: &mut W) -> io::Result<()> {
self._build();
let p = Parser::new(self);
Help::new(HelpWriter::Normal(w), &p, true).write_help()?;
w.flush()
}
/// Returns the version message rendered as if the user ran `-V`.
///
/// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages
/// depending on if the user ran [`-V` (short)] or [`--version` (long)].
///
/// ### Coloring
///
/// This function does not try to color the message nor it inserts any [ANSI escape codes].
///
/// ### Examples
///
/// ```rust
/// # use clap::App;
/// use std::io;
/// let app = App::new("myprog");
/// println!("{}", app.render_version());
/// ```
/// [`io::Write`]: std::io::Write
/// [`-V` (short)]: App::version()
/// [`--version` (long)]: App::long_version()
/// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
pub fn render_version(&self) -> String {
self._render_version(false)
}
/// Returns the version message rendered as if the user ran `--version`.
///
/// **NOTE:** clap has the ability to distinguish between "short" and "long" version messages
/// depending on if the user ran [`-V` (short)] or [`--version` (long)].
///
/// ### Coloring
///
/// This function does not try to color the message nor it inserts any [ANSI escape codes].
///
/// ### Examples
///
/// ```rust
/// # use clap::App;
/// use std::io;
/// let app = App::new("myprog");
/// println!("{}", app.render_long_version());
/// ```
/// [`io::Write`]: std::io::Write
/// [`-V` (short)]: App::version()
/// [`--version` (long)]: App::long_version()
/// [ANSI escape codes]: https://en.wikipedia.org/wiki/ANSI_escape_code
pub fn render_long_version(&self) -> String {
self._render_version(true)
}
/// @TODO-v3-alpha @docs @p2: write docs
pub fn generate_usage(&mut self) -> String {
// 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();
let mut parser = Parser::new(self);
parser._build();
Usage::new(&parser).create_usage_with_title(&[])
}
/// Starts the parsing process, upon a failed parse an error will be displayed to the user and
/// the process will exit with the appropriate error code. By default this method gets all user
/// provided arguments from [`env::args_os`] in order to allow for invalid UTF-8 code points,
/// which are legal on many platforms.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// let matches = App::new("myprog")
/// // Args and options go here...
/// .get_matches();
/// ```
/// [`env::args_os`]: std::env::args_os()
#[inline]
pub fn get_matches(self) -> ArgMatches {
self.get_matches_from(&mut env::args_os())
}
/// Starts the parsing process, just like [`App::get_matches`] but doesn't consume the `App`.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// let mut app = App::new("myprog")
/// // Args and options go here...
/// ;
/// let matches = app.get_matches_mut();
/// ```
/// [`env::args_os`]: std::env::args_os()
/// [`App::get_matches`]: App::get_matches()
pub fn get_matches_mut(&mut self) -> ArgMatches {
self.try_get_matches_from_mut(&mut env::args_os())
.unwrap_or_else(|e| {
// Otherwise, write to stderr and exit
if e.use_stderr() {
e.message.print().expect("Error writing Error to stderr");
if self.settings.is_set(AppSettings::WaitOnError) {
wlnerr!("\nPress [ENTER] / [RETURN] to continue...");
let mut s = String::new();
let i = io::stdin();
i.lock().read_line(&mut s).unwrap();
}
drop(e);
safe_exit(USAGE_CODE);
}
e.exit()
})
}
/// Starts the parsing process. This method will return a [`clap::Result`] type instead of exiting
/// the process on failed parse. By default this method gets matches from [`env::args_os`].
///
/// **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`].
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// let matches = App::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::ErrorKind::DisplayHelp
/// [`ErrorKind::DisplayVersion`]: crate::ErrorKind::DisplayVersion
#[inline]
pub fn try_get_matches(self) -> ClapResult<ArgMatches> {
// Start the parsing
self.try_get_matches_from(&mut env::args_os())
}
/// Starts the parsing process. Like [`App::get_matches`] this method does not return a [`clap::Result`]
/// and will automatically exit with an error message. This method, however, lets you specify
/// what iterator to use when performing matches, such as a [`Vec`] of your making.
///
/// **NOTE:** The first argument will be parsed as the binary name unless
/// [`AppSettings::NoBinaryName`] is used.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
///
/// let matches = App::new("myprog")
/// // Args and options go here...
/// .get_matches_from(arg_vec);
/// ```
/// [`App::get_matches`]: App::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| {
// Otherwise, write to stderr and exit
if e.use_stderr() {
e.message.print().expect("Error writing Error to stderr");
if self.settings.is_set(AppSettings::WaitOnError) {
wlnerr!("\nPress [ENTER] / [RETURN] to continue...");
let mut s = String::new();
let i = io::stdin();
i.lock().read_line(&mut s).unwrap();
}
drop(self);
drop(e);
safe_exit(2);
}
drop(self);
e.exit()
})
}
/// Starts the parsing process. A combination of [`App::get_matches_from`], and
/// [`App::try_get_matches`].
///
/// **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
/// [`AppSettings::NoBinaryName`] is used.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
///
/// let matches = App::new("myprog")
/// // Args and options go here...
/// .try_get_matches_from(arg_vec)
/// .unwrap_or_else(|e| e.exit());
/// ```
/// [`App::get_matches_from`]: App::get_matches_from()
/// [`App::try_get_matches`]: App::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::ErrorKind::DisplayHelp
/// [`ErrorKind::DisplayVersion`]: crate::ErrorKind::DisplayVersion
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)
}
/// Starts the parsing process without consuming the [`App`] struct `self`. This is normally not
/// the desired functionality, instead prefer [`App::try_get_matches_from`] which *does*
/// consume `self`.
///
/// **NOTE:** The first argument will be parsed as the binary name unless
/// [`AppSettings::NoBinaryName`] is used.
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// let arg_vec = vec!["my_prog", "some", "args", "to", "parse"];
///
/// let mut app = App::new("myprog");
/// // Args and options go here...
/// let matches = app.try_get_matches_from_mut(arg_vec)
/// .unwrap_or_else(|e| e.exit());
/// ```
/// [`App::try_get_matches_from`]: App::try_get_matches_from()
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 it = Input::from(itr.into_iter());
// 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, _)) = it.next() {
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 it)
}
/// Sets the placeholder text used for subcommands when printing usage and help.
/// By default, this is "SUBCOMMAND" with a header of "SUBCOMMANDS".
///
/// # Examples
///
/// ```no_run
/// # use clap::{App, Arg};
/// App::new("myprog")
/// .subcommand(App::new("sub1"))
/// .print_help()
/// # ;
/// ```
///
/// will produce
///
/// ```text
/// myprog
///
/// USAGE:
/// myprog [SUBCOMMAND]
///
/// FLAGS:
/// -h, --help Print help information
/// -V, --version Print version information
///
/// SUBCOMMANDS:
/// help Print this message or the help of the given subcommand(s)
/// sub1
/// ```
///
/// but usage of `subcommand_placeholder`
///
/// ```no_run
/// # use clap::{App, Arg};
/// App::new("myprog")
/// .subcommand(App::new("sub1"))
/// .subcommand_placeholder("THING", "THINGS")
/// .print_help()
/// # ;
/// ```
///
/// will produce
///
/// ```text
/// myprog
///
/// USAGE:
/// myprog [THING]
///
/// FLAGS:
/// -h, --help Print help information
/// -V, --version Print version information
///
/// THINGS:
/// help Print this message or the help of the given subcommand(s)
/// sub1
/// ```
pub fn subcommand_placeholder<S, T>(mut self, placeholder: S, header: T) -> Self
where
S: Into<&'help str>,
T: Into<&'help str>,
{
self.subcommand_placeholder = Some(placeholder.into());
self.subcommand_header = Some(header.into());
self
}
}
// Internally used only
impl<'help> App<'help> {
fn get_used_global_args(&self, matcher: &ArgMatcher) -> Vec<Id> {
let global_args: Vec<_> = self
.args
.args()
.filter(|a| a.global)
.map(|ga| ga.id.clone())
.collect();
if let Some(used_subcommand) = matcher.0.subcommand.as_ref() {
if let Some(used_subcommand) = self
.subcommands
.iter()
.find(|subcommand| subcommand.id == used_subcommand.id)
{
return [global_args, used_subcommand.get_used_global_args(matcher)].concat();
}
}
global_args
}
fn _do_parse(&mut self, it: &mut Input) -> ClapResult<ArgMatches> {
debug!("App::_do_parse");
let mut matcher = ArgMatcher::default();
// 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();
// do the real parsing
let mut parser = Parser::new(self);
if let Err(error) = parser.get_matches_with(&mut matcher, it) {
if self.is_set(AppSettings::IgnoreErrors) {
debug!("App::_do_parse: ignoring error: {}", error);
} else {
return Err(error);
}
}
let global_arg_vec: Vec<Id> = self.get_used_global_args(&matcher);
matcher.propagate_globals(&global_arg_vec);
Ok(matcher.into_inner())
}
// used in clap_generate (https://github.com/clap-rs/clap_generate)
#[doc(hidden)]
pub fn _build(&mut self) {
debug!("App::_build");
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;
self._propagate();
self._check_help_and_version();
self._propagate_global_args();
self._derive_display_order();
let mut pos_counter = 1;
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.id.clone());
} else {
let mut ag = ArgGroup::with_id(g.clone());
ag.args.push(a.id.clone());
self.groups.push(ag);
}
}
// Figure out implied settings
if a.is_set(ArgSettings::Last) {
// if an arg has `Last` set, we need to imply DontCollapseArgsInUsage so that args
// in the usage string don't get confused or left out.
self.settings.set(AppSettings::DontCollapseArgsInUsage);
}
a._build();
if a.is_positional() && a.index.is_none() {
a.index = Some(pos_counter);
pos_counter += 1;
}
}
self.args._build();
#[cfg(debug_assertions)]
self::debug_asserts::assert_app(self);
self.settings.set(AppSettings::Built);
} else {
debug!("App::_build: already built");
}
}
fn _panic_on_missing_help(&self, help_required_globally: bool) {
if self.is_set(AppSettings::HelpRequired) || help_required_globally {
let args_missing_help: Vec<String> = self
.args
.args()
.filter(|arg| arg.about.is_none() && arg.long_about.is_none())
.map(|arg| String::from(arg.name))
.collect();
if !args_missing_help.is_empty() {
panic!(
"AppSettings::HelpRequired is enabled for the App {}, 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)]
fn two_args_of<F>(&self, condition: F) -> Option<(&Arg<'help>, &Arg<'help>)>
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!("App::_propagate_global_args:{}", self.name);
for sc in &mut self.subcommands {
for a in self.args.args().filter(|a| a.global) {
let mut propagate = false;
let is_generated = matches!(
a.provider,
ArgProvider::Generated | ArgProvider::GeneratedMutated
);
// Remove generated help and version args in the subcommand
//
// Don't remove if those args are futher mutated
if is_generated {
let generated_pos = sc
.args
.args()
.position(|x| x.id == a.id && x.provider == ArgProvider::Generated);
if let Some(index) = generated_pos {
sc.args.remove(index);
propagate = true;
}
}
if propagate || sc.find(&a.id).is_none() {
sc.args.push(a.clone());
}
}
}
}
/// Propagate settings
pub(crate) fn _propagate(&mut self) {
macro_rules! propagate_subcmd {
($_self:expr, $sc:expr) => {{
// 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::DisableVersionForSubcommands)
{
$sc.set(AppSettings::DisableVersionFlag);
}
if $_self.settings.is_set(AppSettings::PropagateVersion)
&& $sc.version.is_none()
&& $_self.version.is_some()
{
$sc.version = Some($_self.version.unwrap());
}
$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;
}
}};
}
debug!("App::_propagate:{}", self.name);
for sc in &mut self.subcommands {
propagate_subcmd!(self, sc);
}
}
#[allow(clippy::blocks_in_if_conditions)]
pub(crate) fn _check_help_and_version(&mut self) {
debug!("App::_check_help_and_version");
if self.is_set(AppSettings::DisableHelpFlag)
|| self.args.args().any(|x| {
x.provider == ArgProvider::User
&& (x.long == Some("help") || x.id == Id::help_hash())
})
|| self
.subcommands
.iter()
.any(|sc| sc.long_flag == Some("help"))
{
debug!("App::_check_help_and_version: Removing generated help");
let generated_help_pos = self
.args
.args()
.position(|x| x.id == Id::help_hash() && x.provider == ArgProvider::Generated);
if let Some(index) = generated_help_pos {
self.args.remove(index);
}
} else {
let other_arg_has_short = self.args.args().any(|x| x.short == Some('h'));
let help = self
.args
.args_mut()
.find(|x| x.id == Id::help_hash())
.expect(INTERNAL_ERROR_MSG);
if !(help.short.is_some()
|| other_arg_has_short
|| self.subcommands.iter().any(|sc| sc.short_flag == Some('h')))
{
help.short = Some('h');
}
}
if self.is_set(AppSettings::DisableVersionFlag)
|| self.args.args().any(|x| {
x.provider == ArgProvider::User
&& (x.long == Some("version") || x.id == Id::version_hash())
})
|| self
.subcommands
.iter()
.any(|sc| sc.long_flag == Some("version"))
{
debug!("App::_check_help_and_version: Removing generated version");
let generated_version_pos = self
.args
.args()
.position(|x| x.id == Id::version_hash() && x.provider == ArgProvider::Generated);
if let Some(index) = generated_version_pos {
self.args.remove(index);
}
} else {
let other_arg_has_short = self.args.args().any(|x| x.short == Some('V'));
let version = self
.args
.args_mut()
.find(|x| x.id == Id::version_hash())
.expect(INTERNAL_ERROR_MSG);
if !(version.short.is_some()
|| other_arg_has_short
|| self.subcommands.iter().any(|sc| sc.short_flag == Some('V')))
{
version.short = Some('V');
}
}
if !self.is_set(AppSettings::DisableHelpSubcommand)
&& self.has_subcommands()
&& !self.subcommands.iter().any(|s| s.id == Id::help_hash())
{
debug!("App::_check_help_and_version: Building help subcommand");
self.subcommands.push(
App::new("help").about("Print this message or the help of the given subcommand(s)"),
);
}
}
pub(crate) fn _derive_display_order(&mut self) {
debug!("App::_derive_display_order:{}", self.name);
if self.settings.is_set(AppSettings::DeriveDisplayOrder) {
for (i, a) in self
.args
.args_mut()
.filter(|a| !a.is_positional())
.filter(|a| a.disp_ord == 999)
.enumerate()
{
a.disp_ord = i;
}
for (i, mut sc) in &mut self
.subcommands
.iter_mut()
.enumerate()
.filter(|&(_, ref sc)| sc.disp_ord == 999)
{
sc.disp_ord = i;
}
}
for sc in &mut self.subcommands {
sc._derive_display_order();
}
}
// used in clap_generate (https://github.com/clap-rs/clap_generate)
#[doc(hidden)]
pub fn _build_bin_names(&mut self) {
debug!("App::_build_bin_names");
if !self.is_set(AppSettings::BinNameBuilt) {
for mut sc in &mut self.subcommands {
debug!("App::_build_bin_names:iter: bin_name set...");
if sc.bin_name.is_none() {
debug!("No");
let bin_name = format!(
"{}{}{}",
self.bin_name.as_ref().unwrap_or(&self.name.clone()),
if self.bin_name.is_some() { " " } else { "" },
&*sc.name
);
debug!(
"App::_build_bin_names:iter: Setting bin_name of {} to {}",
self.name, bin_name
);
sc.bin_name = Some(bin_name);
} else {
debug!("yes ({:?})", sc.bin_name);
}
debug!(
"App::_build_bin_names:iter: Calling build_bin_names from...{}",
sc.name
);
sc._build_bin_names();
}
self.set(AppSettings::BinNameBuilt);
} else {
debug!("App::_build_bin_names: already built");
}
}
pub(crate) fn _render_version(&self, use_long: bool) -> String {
debug!("App::_render_version");
let ver = if use_long {
self.long_version
.unwrap_or_else(|| self.version.unwrap_or(""))
} else {
self.version
.unwrap_or_else(|| self.long_version.unwrap_or(""))
};
if let Some(bn) = self.bin_name.as_ref() {
if bn.contains(' ') {
// In case we're dealing with subcommands i.e. git mv is translated to git-mv
format!("{} {}\n", bn.replace(" ", "-"), ver)
} else {
format!("{} {}\n", &self.name[..], ver)
}
} else {
format!("{} {}\n", &self.name[..], ver)
}
}
pub(crate) fn format_group(&self, g: &Id) -> String {
let g_string = self
.unroll_args_in_group(g)
.iter()
.filter_map(|x| self.find(x))
.map(|x| {
if x.index.is_some() {
// Print val_name for positional arguments. e.g. <file_name>
x.name_no_brackets().to_string()
} else {
// Print useage string for flags arguments, e.g. <--help>
x.to_string()
}
})
.collect::<Vec<_>>()
.join("|");
format!("<{}>", &*g_string)
}
}
/// 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<'help> App<'help> {
pub(crate) fn find(&self, arg_id: &Id) -> Option<&Arg<'help>> {
self.args.args().find(|a| a.id == *arg_id)
}
#[inline]
// Should we color the output?
pub(crate) fn color(&self) -> ColorChoice {
debug!("App::color: Color setting...");
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
}
}
#[inline]
pub(crate) fn contains_short(&self, s: char) -> bool {
if !self.is_set(AppSettings::Built) {
panic!("If App::_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_args(&self) -> bool {
!self.args.is_empty()
}
pub(crate) fn has_positionals(&self) -> bool {
self.args.keys().any(|x| x.is_position())
}
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<T>(&self, name: &T) -> bool
where
T: PartialEq<str> + ?Sized,
{
*name == *self.get_name() || self.get_all_aliases().any(|alias| *name == *alias)
}
/// 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<T>(&self, flag: &T) -> bool
where
T: PartialEq<str> + ?Sized,
{
match self.long_flag {
Some(long_flag) => {
flag == long_flag || self.get_all_long_flag_aliases().any(|alias| flag == alias)
}
None => self.get_all_long_flag_aliases().any(|alias| flag == alias),
}
}
#[cfg(debug_assertions)]
pub(crate) fn id_exists(&self, id: &Id) -> bool {
self.args.args().any(|x| x.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!("App::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())
}
/// 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<'help> {
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 unroll_args_in_group(&self, group: &Id) -> Vec<Id> {
debug!("App::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!("App::unroll_args_in_group:iter: entity={:?}", n);
if !args.contains(n) {
if self.find(n).is_some() {
debug!("App::unroll_args_in_group:iter: this is an arg");
args.push(n.clone())
} else {
debug!("App::unroll_args_in_group:iter: this is a group");
g_vec.push(n);
}
}
}
}
args
}
pub(crate) fn unroll_requirements_for_arg(&self, arg: &Id, matcher: &ArgMatcher) -> Vec<Id> {
let requires_if_or_not = |(val, req_arg): &(Option<&str>, Id)| -> Option<Id> {
if let Some(v) = val {
if matcher
.get(arg)
.map(|ma| ma.contains_val(v))
.unwrap_or(false)
{
Some(req_arg.clone())
} else {
None
}
} else {
Some(req_arg.clone())
}
};
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(requires_if_or_not) {
if let Some(req) = self.find(&r) {
if !req.requires.is_empty() {
r_vec.push(&req.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: &ArgStr) -> Option<&str> {
self.get_subcommands()
.find(|sc| sc.long_flag_aliases_to(long))
.map(|sc| sc.get_name())
}
}
impl<'help> Index<&'_ Id> for App<'help> {
type Output = Arg<'help>;
fn index(&self, key: &Id) -> &Self::Output {
self.find(key).expect(INTERNAL_ERROR_MSG)
}
}
#[cfg(feature = "yaml")]
impl<'help> From<&'help Yaml> for App<'help> {
#[allow(clippy::cognitive_complexity)]
fn from(y: &'help Yaml) -> Self {
let yaml_file_hash = y.as_hash().expect("YAML file must be a hash");
// We WANT this to panic on error...so expect() is good.
let (mut a, yaml, err) = if let Some(name) = y["name"].as_str() {
(App::new(name), yaml_file_hash, "app".into())
} else {
let (name_yaml, value_yaml) = yaml_file_hash
.iter()
.next()
.expect("There must be one subcommand in the YAML file");
let name_str = name_yaml
.as_str()
.expect("Subcommand name must be a string");
(
App::new(name_str),
value_yaml.as_hash().expect("Subcommand must be a hash"),
format!("subcommand '{}'", name_str),
)
};
let mut has_metadata = false;
for (k, v) in yaml {
a = match k.as_str().expect("App fields must be strings") {
"_has_metadata" => {
has_metadata = true;
a
}
"bin_name" => yaml_to_str!(a, v, bin_name),
"version" => yaml_to_str!(a, v, version),
"long_version" => yaml_to_str!(a, v, long_version),
"author" => yaml_to_str!(a, v, author),
"about" => yaml_to_str!(a, v, about),
"before_help" => yaml_to_str!(a, v, before_help),
"before_long_help" => yaml_to_str!(a, v, before_long_help),
"after_help" => yaml_to_str!(a, v, after_help),
"after_long_help" => yaml_to_str!(a, v, after_long_help),
"help_heading" => yaml_to_str!(a, v, help_heading),
"help_template" => yaml_to_str!(a, v, help_template),
"override_help" => yaml_to_str!(a, v, override_help),
"override_usage" => yaml_to_str!(a, v, override_usage),
"alias" => yaml_to_str!(a, v, alias),
"aliases" => yaml_vec_or_str!(a, v, alias),
"visible_alias" => yaml_to_str!(a, v, visible_alias),
"visible_aliases" => yaml_vec_or_str!(a, v, visible_alias),
"display_order" => yaml_to_usize!(a, v, display_order),
"term_width" => yaml_to_usize!(a, v, term_width),
"max_term_width" => yaml_to_usize!(a, v, max_term_width),
"args" => {
if let Some(vec) = v.as_vec() {
for arg_yaml in vec {
a = a.arg(Arg::from(arg_yaml));
}
} else {
panic!("Failed to convert YAML value {:?} to a vec", v);
}
a
}
"subcommands" => {
if let Some(vec) = v.as_vec() {
for sc_yaml in vec {
a = a.subcommand(App::from(sc_yaml));
}
} else {
panic!("Failed to convert YAML value {:?} to a vec", v);
}
a
}
"groups" => {
if let Some(vec) = v.as_vec() {
for ag_yaml in vec {
a = a.group(ArgGroup::from(ag_yaml));
}
} else {
panic!("Failed to convert YAML value {:?} to a vec", v);
}
a
}
"setting" | "settings" => yaml_to_setting!(a, v, setting, "AppSetting", err),
"global_setting" | "global_settings" => {
yaml_to_setting!(a, v, global_setting, "AppSetting", err)
}
"name" => continue,
s => {
if !has_metadata {
panic!("Unknown setting '{}' in YAML file for {}", s, err)
}
continue;
}
}
}
a
}
}
impl fmt::Display for App<'_> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{}", self.name)
}
}
fn two_elements_of<I, T>(mut iter: I) -> Option<(T, T)>
where
I: Iterator<Item = T>,
{
let first = iter.next();
let second = iter.next();
match (first, second) {
(Some(first), Some(second)) => Some((first, second)),
_ => None,
}
}