just_getopt/lib.rs
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
#![warn(missing_docs)]
//! # Introduction
//!
//! This library crate implements a Posix `getopt`-like command-line
//! option parser with simple programming interface. More specifically
//! the parser is like `getopt`'s GNU extension called `getopt_long`
//! which is familiar command-line option format for users of
//! Linux-based operating systems.
//!
//! The name is `just_getopt` because this is *just a getopt parser* and
//! (almost) nothing more. The intent is to provide just the parsed
//! output and methods for examining the output. There will not be
//! anything for interpreting the output or for printing messages to
//! program's user. The responsibility of interpretation is left to your
//! program.
//!
//! In getopt logic there are two types of command-line options:
//!
//! 1. short options with a single letter name (`-f`)
//! 2. long options with more than one letter as their name (`--file`).
//!
//! Both option types may accept an optional value or they may require a
//! value. Values are given after the option. See the section **Parsing
//! Rules** below for more information.
//!
//! Programming examples are in the **Examples** section below and in
//! the source code repository's "examples" directory.
//!
//! # Parsing Rules
//!
//! By default, all options are expected to come first in the command
//! line. Other arguments (non-options) come after options. Therefore
//! the first argument that does not look like an option stops option
//! parsing and the rest of the command line is parsed as non-options.
//! This default can be changed, so that options and non-options can be
//! mixed in their order in the command line. See [`OptSpecs::flag`]
//! method for more information.
//!
//! In command line the "pseudo option" `--` (two dashes) always stops
//! the option parser. Then the rest of the command line is parsed as
//! regular arguments (non-options).
//!
//! ## Short Options
//!
//! Short options in the command line start with the `-` character which
//! is followed by option's name character (`-c`), usually a letter.
//!
//! If option requires a value the value must be entered either directly
//! after the option character (`-cVALUE`) or as the next command-line
//! argument (`-c VALUE`). In the latter case anything that follows `-c`
//! will be parsed as option's value.
//!
//! If option accepts an optional value the value must always be entered
//! directly after the option character (`-cVALUE`). Otherwise there is
//! no value for this option.
//!
//! Several short options can be entered together after one `-`
//! character (`-abc`) but then only the last option in the series may
//! have required or optional value.
//!
//! ## Long Options
//!
//! Long options start with `--` characters and the option name comes
//! directly after it (`--foo`). The name must be at least two
//! characters long.
//!
//! If option requires a value the value must be entered either directly
//! after the option name and `=` character (`--foo=VALUE`) or as the
//! next command-line argument (`--foo VALUE`). In the latter case
//! anything that follows `--foo` will be parsed as option's value.
//!
//! If option accepts an optional value the value must always be entered
//! directly after the option name and `=` character (`--foo=VALUE`).
//! Otherwise (like in `--foo`) there is no value for this option.
//!
//! Option `--foo=` is valid format when the option requires a value or
//! accepts an optional value. It means that the value is empty string.
//! It is not valid format when the option does not accept a value.
//!
//! # Examples
//!
//! Following examples will guide through a typical use of this library
//! crate and command-line parsing.
//!
//! ## Prepare
//!
//! First we bring some important paths into the scope of our program.
//!
//! ```
//! use just_getopt::{OptFlags, OptSpecs, OptValueType};
//! ```
//!
//! Then we define which command-line options are valid for the program.
//! We do this by creating an instance of [`OptSpecs`] struct by calling
//! function [`OptSpecs::new`]. Then we modify the struct instance with
//! [`option`](OptSpecs::option) and [`flag`](OptSpecs::flag) methods.
//!
//! ```
//! # use just_getopt::{OptFlags, OptSpecs, OptValueType};
//! let specs = OptSpecs::new()
//! .option("help", "h", OptValueType::None) // Arguments: (id, name, value_type)
//! .option("help", "help", OptValueType::None)
//! .option("file", "f", OptValueType::Required)
//! .option("file", "file", OptValueType::Required)
//! .option("verbose", "v", OptValueType::Optional)
//! .option("verbose", "verbose", OptValueType::Optional)
//! .flag(OptFlags::OptionsEverywhere);
//! ```
//!
//! The [`option`](OptSpecs::option) methods above add a single option
//! information to the option specification. Method's arguments are:
//!
//! 1. `id`: Programmer's identifier string for the option. The same
//! identifier is used later to check if this particular option was
//! present in the command line.
//!
//! 2. `name`: Option's name string in the command line, without
//! prefix. A single-character name (like `h`) defines a short
//! option which is entered like `-h` in the command line. Longer
//! name defines a long option which is entered like `--help` in the
//! command line.
//!
//! 3. `value_type`: Whether or not this option accepts a value and is
//! the value optional or required. The argument is a variant of
//! enum [`OptValueType`].
//!
//! The [`flag`](OptSpecs::flag) method above adds a configuration flag
//! for the command-line parser. It is a variant of enum [`OptFlags`].
//! This variant [`OptionsEverywhere`](OptFlags::OptionsEverywhere)
//! changes the command-line parser to accept options and other
//! arguments in mixed order in the command line. That is, options can
//! come after non-option arguments.
//!
//! For better explanation see the documentation of [`OptSpecs`] struct
//! and its methods [`option`](OptSpecs::option) and
//! [`flag`](OptSpecs::flag). Also see methods
//! [`limit_options`](OptSpecs::limit_options),
//! [`limit_other_args`](OptSpecs::limit_other_args) and
//! [`limit_unknown_options`](OptSpecs::limit_unknown_options).
//!
//! ## Parse the Command Line
//!
//! We are ready to parse program's command-line arguments. We do this
//! with [`OptSpecs::getopt`] method. Arguments we get from
//! [`std::env::args`] function which returns an iterator.
//!
//! ```
//! # use just_getopt::{OptFlags, OptSpecs, OptValueType};
//! # let specs = OptSpecs::new();
//! let mut args = std::env::args(); // Get arguments iterator from operating system.
//! args.next(); // Consume the first item which is this program's file path.
//! let parsed = specs.getopt(args); // Getopt! Use the "specs" variable defined above.
//! ```
//!
//! If you want to try [`getopt`](OptSpecs::getopt) method without
//! program's real command-line arguments you can also run it with other
//! iterator argument or with a vector or an array as an argument. Like
//! this:
//!
//! ```
//! # use just_getopt::{OptFlags, OptSpecs, OptValueType};
//! # let specs = OptSpecs::new();
//! let parsed = specs.getopt(["--file=123", "-f456", "foo", "-av", "bar"]);
//! ```
//!
//! ## Examine the Parsed Output
//!
//! The command line is now parsed and the variable `parsed` (see above)
//! owns an [`Args`] struct which represents the parsed output in
//! organized form. It is a public struct and it can be examined
//! manually. There are some methods for convenience, though, and some
//! of them are shown in the following examples.
//!
//! At this stage it is useful to see the returned [`Args`] struct. One
//! of its fields may contain some [`Opt`] structs too if the parser
//! found valid command-line options. Let's print it:
//!
//! ```
//! # use just_getopt::{OptFlags, OptSpecs, OptValueType};
//! # let specs = OptSpecs::new();
//! # let parsed = specs.getopt(["--file=123", "-f456", "foo", "-av", "bar"]);
//! eprintln!("{:#?}", parsed);
//! ```
//!
//! That could print something like this:
//!
//! ```text
//! Args {
//! options: [
//! Opt {
//! id: "file",
//! name: "file",
//! value_required: true,
//! value: Some(
//! "123",
//! ),
//! },
//! Opt {
//! id: "file",
//! name: "f",
//! value_required: true,
//! value: Some(
//! "456",
//! ),
//! },
//! Opt {
//! id: "verbose",
//! name: "v",
//! value_required: false,
//! value: None,
//! },
//! ],
//! other: [
//! "foo",
//! "bar",
//! ],
//! unknown: [
//! "a",
//! ],
//! }
//! ```
//!
//! ### Unknown Options
//!
//! We probably want to tell program's user if there were unknown
//! options. An error message to [`std::io::stderr`] stream is usually
//! enough. No need to panic.
//!
//! ```
//! # use just_getopt::{OptFlags, OptSpecs, OptValueType};
//! # let specs = OptSpecs::new();
//! # let parsed = specs.getopt(["--file=123", "-f456", "foo", "-av", "bar"]);
//! for u in &parsed.unknown {
//! eprintln!("Unknown option: {}", u);
//! }
//! ```
//!
//! ### Required Value Missing
//!
//! More serious error is a missing value to an option which requires a
//! value (like `file` option in our example, see above). That can be a
//! good reason to exit the program.
//!
//! ```no_run
//! # use just_getopt::{OptFlags, OptSpecs, OptValueType};
//! # let specs = OptSpecs::new();
//! # let parsed = specs.getopt(["--file=123", "-f456", "foo", "-av", "bar"]);
//! for o in &parsed.required_value_missing() {
//! eprintln!("Value is required for option '{}'.", o.name);
//! std::process::exit(1);
//! }
//! ```
//!
//! ### Print Help Message
//!
//! Command-line programs always have `-h` or `--help` option for
//! printing a friendly help message. The following example shows how to
//! detect that option.
//!
//! ```no_run
//! # use just_getopt::{OptFlags, OptSpecs, OptValueType};
//! # let specs = OptSpecs::new();
//! # let parsed = specs.getopt(["--file=123", "-f456", "foo", "-av", "bar"]);
//! if let Some(_) = parsed.options_first("help") {
//! println!("Print friendly help about program's usage.");
//! std::process::exit(2);
//! }
//! ```
//!
//! The `"help"` string in the first line above is the identifier string
//! (`id`) for the option. It was defined with [`OptSpecs::option`]
//! method in the example code earlier. Identifier strings are used to
//! find if a specific option was given in the command line.
//!
//! ### Collect Values and Other Arguments
//!
//! The rest depends very much on individual program's needs. Probably
//! often we would collect what values were given to options. In our
//! example program there are `-f` and `--file` options that require a
//! value. We could collect all those values next.
//!
//! ```
//! # use just_getopt::{OptFlags, OptSpecs, OptValueType};
//! # let specs = OptSpecs::new();
//! # let parsed = specs.getopt(["--file=123", "-f456", "foo", "-av", "bar"]);
//! for f in &parsed.options_value_all("file") {
//! println!("File name: {:?}", f);
//! }
//! ```
//!
//! Notice if `-v` or `--verbose` was given, even without a value. Then
//! collect all (optional) values for the option.
//!
//! ```
//! # use just_getopt::{OptFlags, OptSpecs, OptValueType};
//! # let specs = OptSpecs::new();
//! # let parsed = specs.getopt(["--file=123", "-f456", "foo", "-av", "bar"]);
//! if let Some(_) = parsed.options_first("verbose") {
//! println!("Option 'verbose' was given.");
//!
//! for v in &parsed.options_value_all("verbose") {
//! println!("Verbose level: {:?}", v);
//! }
//! }
//! ```
//!
//! Finally, our example program will handle all other arguments, that
//! is, non-option arguments.
//!
//! ```
//! # use just_getopt::{OptFlags, OptSpecs, OptValueType};
//! # let specs = OptSpecs::new();
//! # let parsed = specs.getopt(["--file=123", "-f456", "foo", "-av", "bar"]);
//! for o in &parsed.other {
//! println!("Other argument: {:?}", o);
//! }
//! ```
//!
//! # More Help
//!
//! A complete working example code -- very similar to previous examples
//! -- is in the source code repository's "examples" directory. It can
//! be run with command `cargo run --example basic -- your arguments`.
//! Try it with different command-line arguments.
//!
//! Further reading:
//!
//! - [`OptSpecs`] struct and its methods.
//! - [`Args`] struct and its methods.
mod parser;
/// Specification for program's valid command-line options.
///
/// An instance of this struct is needed before command-line options can
/// be parsed. Instances are created with function [`OptSpecs::new`] and
/// they are modified with [`option`](OptSpecs::option) and other
/// methods
///
/// The struct instance is used when parsing the command line given by
/// program's user. The parser methods is [`getopt`](OptSpecs::getopt).
#[derive(Debug, PartialEq)]
pub struct OptSpecs {
options: Vec<OptSpec>,
flags: Vec<OptFlags>,
option_limit: u32,
other_limit: u32,
unknown_limit: u32,
}
const COUNTER_LIMIT: u32 = u32::MAX;
#[derive(Debug, PartialEq)]
struct OptSpec {
id: String,
name: String,
value_type: OptValueType,
}
/// Option's value type.
///
/// See [`OptSpecs::option`] method for more information.
#[derive(Debug, PartialEq)]
pub enum OptValueType {
/// Option does not accept a value.
None,
/// Option accepts an optional value.
Optional,
/// Option requires a value.
Required,
}
/// Flags for changing command-line parser's behavior.
///
/// See [`OptSpecs::flag`] method for more information.
#[derive(Debug, PartialEq)]
pub enum OptFlags {
/// Accept command-line options and other arguments in mixed order
/// in the command line. That is, options can come after non-option
/// arguments.
///
/// This is not the default behavior. By default the first
/// non-option argument in the command line stops option parsing and
/// the rest of the command line is parsed as non-options (other
/// arguments), even if they look like options.
OptionsEverywhere,
/// Long options don't need to be written in full in the command
/// line. They can be shortened as long as there are enough
/// characters to find a unique prefix match. If there are more than
/// one match the option given in the command line is classified as
/// unknown.
PrefixMatchLongOptions,
}
impl OptSpecs {
/// Create and return a new instance of [`OptSpecs`] struct.
///
/// The created instance is "empty" and does not contain any
/// specifications for command-line options. Apply
/// [`option`](OptSpecs::option) or other methods to make it useful
/// for parsing command-line.
pub fn new() -> Self {
Self {
options: Vec::new(),
flags: Vec::new(),
option_limit: COUNTER_LIMIT,
other_limit: COUNTER_LIMIT,
unknown_limit: COUNTER_LIMIT,
}
}
/// Add an option specification for [`OptSpecs`].
///
/// The method requires three arguments:
///
/// 1. `id`: Programmer's identifier string for the option. Later,
/// after parsing the command line, the identifier is used to
/// match if this particular option was present in the
/// command-line.
///
/// Several options may have the same identifier string. This
/// makes sense when different option names in the command line
/// represent the same meaning, like `-h` and `--help` for
/// printing program's help message.
///
/// 2. `name`: Option's name string in the command line (without
/// prefix). If the string is a single character (like `h`) it
/// defines a short option which is entered as `-h` in the
/// command line. If there are more than one character in the
/// string it defines a long option name (like `help`) which is
/// entered as `--help` in the command line.
///
/// All options must have a unique `name` string. This method
/// will panic if the same `name` is added twice. The method
/// will also panic if the `name` string contains illegal
/// characters. Space characters are not accepted. A short
/// option name can't be `-` and long option names can't have
/// any `=` characters nor `-` as their first character.
///
/// 3. `value_type`: A variant of enum [`OptValueType`] which
/// defines if this option accepts a value. If not, use
/// [`OptValueType::None`] as method's argument. If an optional
/// value is accepted, use [`OptValueType::Optional`]. If the
/// option requires a value, use [`OptValueType::Required`].
///
/// The return value is the same struct instance which was modified.
pub fn option(mut self, id: &str, name: &str, value_type: OptValueType) -> Self {
assert!(
id.chars().count() > 0,
"Option's \"id\" must be at least 1 character long."
);
let name_count = name.chars().count();
if name_count == 1 {
assert!(
parser::is_valid_short_option_name(name),
"Not a valid short option name."
);
} else if name_count >= 2 {
assert!(
parser::is_valid_long_option_name(name),
"Not a valid long option name."
);
} else {
panic!("Option's \"name\" must be at least 1 character long.");
}
for e in &self.options {
assert!(
e.name != name,
"No duplicates allowed for option's \"name\"."
);
}
self.options.push(OptSpec {
id: id.to_string(),
name: name.to_string(),
value_type,
});
self
}
/// Add a flag that changes parser's behavior.
///
/// Method's only argument `flag` is a variant of enum [`OptFlags`].
/// Their names and meanings are:
///
/// - [`OptFlags::OptionsEverywhere`]: Accept command-line options
/// and other arguments in mixed order in the command line. That
/// is, options can come after non-option arguments.
///
/// This is not the default behavior. By default the first
/// non-option argument in the command line stops option parsing
/// and the rest of the command line is parsed as non-options
/// (other arguments), even if they look like options.
///
/// - [`OptFlags::PrefixMatchLongOptions`]: With this flag long
/// options don't need to be written in full in the command
/// line. They can be shortened as long as there are enough
/// characters to find a unique prefix match. If there are more
/// than one match the option which was given in the command
/// line is classified as unknown.
///
/// The return value is the same struct instance which was modified.
pub fn flag(mut self, flag: OptFlags) -> Self {
if !self.flags.contains(&flag) {
self.flags.push(flag);
}
self
}
fn is_flag(&self, flag: OptFlags) -> bool {
self.flags.contains(&flag)
}
/// Maximum number of valid options.
///
/// Method's argument `limit` sets the maximum number of valid
/// options to collect from the command line. The rest is ignored.
/// This doesn't include unknown options (see
/// [`limit_unknown_options`](OptSpecs::limit_unknown_options)).
///
/// The return value is the same struct instance which was modified.
pub fn limit_options(mut self, limit: u32) -> Self {
self.option_limit = limit;
self
}
/// Maximum number of other command-line arguments.
///
/// Method's argument `limit` sets the maximum number of other
/// (non-option) arguments to collect from the command line. The
/// rest is ignored.
///
/// Note: If your program accepts *n* number of command-line
/// argument (apart from options) you could set this limit to *n +
/// 1*. This way you know if there were more arguments than needed
/// and can inform program's user about that. There is no need to
/// collect more arguments.
///
/// The return value is the same struct instance which was modified.
pub fn limit_other_args(mut self, limit: u32) -> Self {
self.other_limit = limit;
self
}
/// Maximum number of unknown options.
///
/// Method's argument `limit` sets the maximum number of unique
/// unknown options to collect from the command line. Duplicates are
/// not collected.
///
/// Note: If you want to stop your program if it notices just one
/// unknown option you can set this limit to 1. There is probably no
/// need to collect more of them.
///
/// The return value is the same struct instance which was modified.
pub fn limit_unknown_options(mut self, limit: u32) -> Self {
self.unknown_limit = limit;
self
}
/// Getopt-parse an iterable item as command line arguments.
///
/// This method's argument `args` is of any type that implements
/// trait [`IntoIterator`] and that has items of type that
/// implements trait [`ToString`]. For example, argument `args` can
/// be a vector or an iterator such as command-line arguments
/// returned by [`std::env::args`].
///
/// The return value is an [`Args`] struct which represents the
/// command-line information in organized form.
pub fn getopt<I, S>(&self, args: I) -> Args
where
I: IntoIterator<Item = S>,
S: ToString,
{
parser::parse(self, args.into_iter().map(|i| i.to_string()))
}
fn get_short_option_match(&self, name: &str) -> Option<&OptSpec> {
if name.chars().count() != 1 {
return None;
}
self.options.iter().find(|&e| e.name == name)
}
fn get_long_option_match(&self, name: &str) -> Option<&OptSpec> {
if name.chars().count() < 2 {
return None;
}
self.options.iter().find(|&e| e.name == name)
}
fn get_long_option_prefix_matches(&self, name: &str) -> Option<Vec<&OptSpec>> {
if name.chars().count() < 2 {
return None;
}
let mut v = Vec::new();
for e in &self.options {
if e.name.starts_with(name) {
v.push(e);
}
}
if v.is_empty() {
None
} else {
Some(v)
}
}
}
impl Default for OptSpecs {
fn default() -> Self {
Self::new()
}
}
/// Parsed command line in organized form.
///
/// Instances of this struct are usually created with
/// [`OptSpecs::getopt`] method and an instance represents the parsed
/// output in organized form. See each field's documentation for more
/// information.
///
/// Programmers can use the parsed output ([`Args`] struct) any way they
/// like. There are some methods for convenience.
#[derive(Debug, PartialEq)]
pub struct Args {
/// A vector of valid command-line options.
///
/// Elements of this vector are [`Opt`] structs which each
/// represents a single command-line option. Elements are in the
/// same order as given (by program's user) in the command line. The
/// vector is empty if the parser didn't find any valid command-line
/// options.
pub options: Vec<Opt>,
/// A vector of other arguments (non-options).
///
/// Each element of the vector is a single non-option argument
/// string in the same order as given (by program's user) in the
/// command line. The vector is empty if the parser didn't find any
/// non-option arguments.
pub other: Vec<String>,
/// Unknown options.
///
/// Command-line arguments that look like options but were not part
/// of [`OptSpecs`] specification are classified as unknown. They
/// are listed in this vector. Possible duplicate unknown options
/// have been filtered out.
///
/// Each element is the name string for the option (without `-` or
/// `--` prefix). For unknown short options the element is a
/// single-character string. For unknown long options the string has
/// more than one character. The whole vector is empty if there were
/// no unknown options.
///
/// If a long option does not accept a value (that is, its value
/// type is [`OptValueType::None`]) but user gives it a value with
/// equal sign notation (`--foo=`), that option is classified as
/// unknown and it will be in this field's vector with name `foo=`.
pub unknown: Vec<String>,
}
impl Args {
fn new() -> Self {
Args {
options: Vec::new(),
other: Vec::new(),
unknown: Vec::new(),
}
}
/// Find options with missing required value.
///
/// This method finds all (otherwise valid) options which require a
/// value but the value is missing. That is, [`OptSpecs`] struct
/// specification defined that an option requires a value but
/// program's user didn't give one in the command line. Such thing
/// can happen if an option like `--file` is the last argument in
/// the command line and that option requires a value. Empty string
/// `""` is not classified as missing value because it can be valid
/// user input in many situations.
///
/// This method returns a vector (possibly empty) and each element
/// is a reference to an [`Opt`] struct in the original
/// [`Args::options`] field contents.
pub fn required_value_missing(&self) -> Vec<&Opt> {
let mut vec = Vec::new();
for opt in &self.options {
if opt.value_required && opt.value.is_none() {
vec.push(opt);
}
}
vec
}
/// Find all options with the given `id`.
///
/// Find all options which have the identifier `id`. (Option
/// identifiers have been defined in [`OptSpecs`] struct before
/// parsing.) The return value is a vector (possibly empty, if no
/// matches) and each element is a reference to [`Opt`] struct in
/// the original [`Args`] struct. Elements in the vector are in the
/// same order as in the parsed command line.
pub fn options_all(&self, id: &str) -> Vec<&Opt> {
let mut vec = Vec::new();
for opt in &self.options {
if opt.id == id {
vec.push(opt);
}
}
vec
}
/// Find the first option with the given `id`.
///
/// Find and return the first match for option `id` in command-line
/// arguments' order. (Options' identifiers have been defined in
/// [`OptSpecs`] struct before parsing.)
///
/// The return value is a variant of enum [`Option`]. Their
/// meanings:
///
/// - `None`: No options found with the given `id`.
///
/// - `Some(&Opt)`: An option was found with the given `id` and a
/// reference to its [`Opt`] struct in the original [`Args`]
/// struct is provided.
pub fn options_first(&self, id: &str) -> Option<&Opt> {
self.options.iter().find(|&opt| opt.id == id)
}
/// Find the last option with the given `id`.
///
/// This is similar to [`options_first`](Args::options_first) method
/// but this returns the last match in command-line arguments'
/// order.
pub fn options_last(&self, id: &str) -> Option<&Opt> {
self.options.iter().rev().find(|&opt| opt.id == id)
}
/// Find and return all values for options with the given `id`.
///
/// Find all options which match the identifier `id` and which also
/// have a value assigned. (Options' identifiers have been defined
/// in [`OptSpecs`] struct before parsing.) Collect options' values
/// into a new vector in the same order as they were given in the
/// command line. Vector's elements are references to the value
/// strings in the original [`Args`] struct. The returned vector is
/// empty if there were no matches.
pub fn options_value_all(&self, id: &str) -> Vec<&String> {
let mut vec = Vec::new();
let opt_vec = self.options_all(id);
for opt in opt_vec {
if let Some(s) = &opt.value {
vec.push(s);
}
}
vec
}
/// Find the first option with a value for given option `id`.
///
/// Find the first option with the identifier `id` and which has a
/// value assigned. (Options' identifiers have been defined in
/// [`OptSpecs`] struct before parsing.) Method's return value is a
/// variant of enum [`Option`] which are:
///
/// - `None`: No options found with the given `id` and a value
/// assigned. Note that there could be options for the same `id`
/// but they don't have a value.
///
/// - `Some(&String)`: An option was found with the given `id` and
/// the option has a value assigned. A reference to the string
/// value in the original [`Args`] struct is provided.
pub fn options_value_first(&self, id: &str) -> Option<&String> {
match self
.options
.iter()
.find(|&opt| opt.id == id && opt.value.is_some())
{
Some(o) => o.value.as_ref(),
None => None,
}
}
/// Find the last option with a value for given option `id`.
///
/// This is similar to
/// [`options_value_first`](Args::options_value_first) method but
/// this method finds and returns the last option's value.
///
/// Note: Program's user may give the same option several times in
/// the command line. If the option accepts a value it may be
/// suitable to consider only the last value relevant. (Or the
/// first, or maybe print an error message for providing several,
/// possibly conflicting, values.)
pub fn options_value_last(&self, id: &str) -> Option<&String> {
match self
.options
.iter()
.rev()
.find(|&opt| opt.id == id && opt.value.is_some())
{
Some(o) => o.value.as_ref(),
None => None,
}
}
}
/// Structured option information.
///
/// This [`Opt`] struct represents organized information about single
/// command-line option. Instances of this struct are usually created by
/// [`OptSpecs::getopt`] method which returns an [`Args`] struct which
/// have these [`Opt`] structs inside.
///
/// A programmer may need these when examining parsed command-line
/// options. See the documentation of individual fields for more
/// information. Also see [`Args`] struct and its methods.
#[derive(Debug, PartialEq)]
pub struct Opt {
/// Identifier for the option.
///
/// Identifiers are defined with [`OptSpecs::option`] method before
/// parsing command-line arguments. After [`OptSpecs::getopt`]
/// parsing the same identifier is copied here and it confirms that
/// the option was indeed given in the command line.
pub id: String,
/// Option's name in the parsed command line.
///
/// Option's name that was used in the command line. For short
/// options this is a single-character string. For long options the
/// name has more than one characters.
pub name: String,
/// The option requires a value.
///
/// `true` means that the option was defined with value type
/// [`OptValueType::Required`]. See [`OptSpecs::flag`] method for
/// more information. This field does not guarantee that there
/// actually was a value for the option in the command line.
pub value_required: bool,
/// Option's value.
///
/// The value is a variant of enum [`Option`]. Value `None` means
/// that there is no value for the option. Value `Some(String)`
/// provides a value.
pub value: Option<String>,
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn t_create_optspecs_01() {
let mut spec;
let mut expect;
spec = OptSpecs::new().option("help", "help", OptValueType::None);
expect = OptSpec {
id: String::from("help"),
name: String::from("help"),
value_type: OptValueType::None,
};
assert_eq!(1, spec.options.len());
assert_eq!(&expect, &spec.options[0]);
assert_eq!(COUNTER_LIMIT, spec.option_limit);
assert_eq!(COUNTER_LIMIT, spec.other_limit);
assert_eq!(COUNTER_LIMIT, spec.unknown_limit);
spec = spec.option("file", "f", OptValueType::Optional);
expect = OptSpec {
id: String::from("file"),
name: String::from("f"),
value_type: OptValueType::Optional,
};
assert_eq!(2, spec.options.len());
assert_eq!(&expect, &spec.options[1]);
spec = spec.option("file", "file", OptValueType::Required);
expect = OptSpec {
id: String::from("file"),
name: String::from("file"),
value_type: OptValueType::Required,
};
assert_eq!(3, spec.options.len());
assert_eq!(&expect, &spec.options[2]);
spec = spec.flag(OptFlags::OptionsEverywhere);
assert_eq!(1, spec.flags.len()); // Length 1
assert_eq!(true, spec.is_flag(OptFlags::OptionsEverywhere));
spec = spec.flag(OptFlags::PrefixMatchLongOptions);
assert_eq!(2, spec.flags.len()); // Length 2
assert_eq!(true, spec.is_flag(OptFlags::PrefixMatchLongOptions));
spec = spec.flag(OptFlags::OptionsEverywhere);
spec = spec.flag(OptFlags::PrefixMatchLongOptions);
assert_eq!(2, spec.flags.len()); // Length still 2
spec = spec.limit_options(9);
spec = spec.limit_other_args(10);
spec = spec.limit_unknown_options(3);
assert_eq!(9, spec.option_limit);
assert_eq!(10, spec.other_limit);
assert_eq!(3, spec.unknown_limit);
}
#[test]
#[should_panic]
fn t_create_optspecs_02() {
let _spec = OptSpecs::new().option("", "h", OptValueType::None);
}
#[test]
#[should_panic]
fn t_create_optspecs_03() {
let _spec = OptSpecs::new().option("h", "h", OptValueType::None).option(
"h",
"h",
OptValueType::None,
);
}
#[test]
#[should_panic]
fn t_create_optspecs_04() {
let _spec = OptSpecs::new().option("h", "", OptValueType::None);
}
#[test]
fn t_is_flag() {
let mut spec = OptSpecs::new().flag(OptFlags::OptionsEverywhere);
assert_eq!(true, spec.is_flag(OptFlags::OptionsEverywhere));
spec = spec.flag(OptFlags::PrefixMatchLongOptions);
assert_eq!(true, spec.is_flag(OptFlags::PrefixMatchLongOptions));
}
#[test]
fn t_parsed_output_010() {
let parsed = OptSpecs::new()
.option("help", "h", OptValueType::None)
.option("help", "help", OptValueType::None)
.option("file", "f", OptValueType::Required)
.option("file", "file", OptValueType::Required)
.getopt(["-h", "--help", "-f123", "-f", "456", "foo", "bar"]);
assert_eq!("h", parsed.options_first("help").unwrap().name);
assert_eq!("help", parsed.options_last("help").unwrap().name);
assert_eq!("help", parsed.options_first("help").unwrap().id);
assert_eq!("help", parsed.options_last("help").unwrap().id);
assert_eq!(false, parsed.options_first("help").unwrap().value_required);
assert_eq!(false, parsed.options_last("help").unwrap().value_required);
assert_eq!("f", parsed.options_first("file").unwrap().name);
assert_eq!(
"123",
parsed.options_first("file").unwrap().value.clone().unwrap()
);
assert_eq!(
"456",
parsed.options_last("file").unwrap().value.clone().unwrap()
);
assert_eq!(true, parsed.options_first("file").unwrap().value_required);
assert_eq!("foo", parsed.other[0]);
assert_eq!("bar", parsed.other[1]);
}
#[test]
fn t_parsed_output_020() {
let parsed = OptSpecs::new()
.limit_options(1)
.limit_other_args(2)
.option("help", "h", OptValueType::None)
.getopt(["-h", "foo", "-h"]);
assert_eq!("h", parsed.options_first("help").unwrap().name);
assert_eq!(2, parsed.other.len());
assert_eq!("foo", parsed.other[0]);
assert_eq!("-h", parsed.other[1]);
}
#[test]
fn t_parsed_output_030() {
let parsed = OptSpecs::new()
.flag(OptFlags::OptionsEverywhere)
.option("help", "h", OptValueType::None)
.option("help", "help", OptValueType::None)
.option("file", "f", OptValueType::Required)
.option("file", "file", OptValueType::Required)
.getopt(["-h", "foo", "--help", "--file=123", "bar", "--file", "456"]);
assert_eq!("h", parsed.options_first("help").unwrap().name);
assert_eq!("help", parsed.options_last("help").unwrap().name);
assert_eq!(
"123",
parsed.options_first("file").unwrap().value.clone().unwrap()
);
assert_eq!(
"456",
parsed.options_last("file").unwrap().value.clone().unwrap()
);
assert_eq!("foo", parsed.other[0]);
assert_eq!("bar", parsed.other[1]);
}
#[test]
fn t_parsed_output_040() {
let parsed = OptSpecs::new()
.option("debug", "d", OptValueType::Optional)
.option("verbose", "verbose", OptValueType::Optional)
.getopt(["-d1", "-d", "--verbose", "--verbose=123"]);
assert_eq!(
"1",
parsed
.options_first("debug")
.unwrap()
.value
.clone()
.unwrap()
);
assert_eq!(None, parsed.options_last("debug").unwrap().value);
assert_eq!(false, parsed.options_last("debug").unwrap().value_required);
assert_eq!(None, parsed.options_first("verbose").unwrap().value);
assert_eq!(
"123",
parsed
.options_last("verbose")
.unwrap()
.value
.clone()
.unwrap()
);
assert_eq!(
false,
parsed.options_last("verbose").unwrap().value_required
);
}
#[test]
fn t_parsed_output_050() {
let parsed = OptSpecs::new()
.option("debug", "d", OptValueType::Optional)
.getopt(["-abcd", "-adbc"]);
assert_eq!(None, parsed.options_first("debug").unwrap().value);
assert_eq!(
"bc",
parsed.options_last("debug").unwrap().value.clone().unwrap()
);
assert_eq!(3, parsed.unknown.len());
assert_eq!("a", parsed.unknown[0]);
assert_eq!("b", parsed.unknown[1]);
assert_eq!("c", parsed.unknown[2]);
}
#[test]
fn t_parsed_output_060() {
let parsed = OptSpecs::new()
.option("aaa", "bbb", OptValueType::None)
.option("aaa", "c", OptValueType::None)
.option("aaa", "d", OptValueType::None)
.option("aaa", "eee", OptValueType::None)
.getopt(["--bbb", "-cd", "--eee"]);
let m = parsed.options_all("aaa");
assert_eq!("bbb", m[0].name);
assert_eq!("c", m[1].name);
assert_eq!("d", m[2].name);
assert_eq!("eee", m[3].name);
}
#[test]
fn t_parsed_output_070() {
let parsed = OptSpecs::new()
.flag(OptFlags::PrefixMatchLongOptions)
.option("version", "version", OptValueType::None)
.option("verbose", "verbose", OptValueType::None)
.getopt(["--ver", "--verb", "--versi", "--verbose"]);
assert_eq!("ver", parsed.unknown[0]);
assert_eq!("verb", parsed.options_first("verbose").unwrap().name);
assert_eq!("verbose", parsed.options_last("verbose").unwrap().name);
assert_eq!("version", parsed.options_first("version").unwrap().id);
assert_eq!("versi", parsed.options_first("version").unwrap().name);
}
#[test]
fn t_parsed_output_080() {
let parsed = OptSpecs::new()
// .flag(OptFlags::PrefixMatchLongOptions) Must be commented!
.option("version", "version", OptValueType::None)
.option("verbose", "verbose", OptValueType::None)
.getopt(["--version", "--ver", "--verb", "--versi", "--verbose"]);
assert_eq!("ver", parsed.unknown[0]);
assert_eq!("verb", parsed.unknown[1]);
assert_eq!("versi", parsed.unknown[2]);
assert_eq!("version", parsed.options_first("version").unwrap().name);
assert_eq!("verbose", parsed.options_first("verbose").unwrap().name);
}
#[test]
fn t_parsed_output_090() {
let parsed = OptSpecs::new()
.flag(OptFlags::OptionsEverywhere)
.option("help", "h", OptValueType::None)
.option("file", "file", OptValueType::Required)
.getopt(["-h", "foo", "--file=123", "--", "bar", "--file", "456"]);
assert_eq!("h", parsed.options_first("help").unwrap().name);
assert_eq!("file", parsed.options_first("file").unwrap().name);
assert_eq!(
"123",
parsed.options_first("file").unwrap().value.clone().unwrap()
);
assert_eq!(4, parsed.other.len());
assert_eq!("foo", parsed.other[0]);
assert_eq!("bar", parsed.other[1]);
assert_eq!("--file", parsed.other[2]);
assert_eq!("456", parsed.other[3]);
}
#[test]
fn t_parsed_output_100() {
let parsed = OptSpecs::new()
.option("file", "file", OptValueType::Required)
.getopt(["--file=", "--file"]);
assert_eq!(true, parsed.options_first("file").unwrap().value_required);
assert_eq!(
"",
parsed.options_first("file").unwrap().value.clone().unwrap()
);
assert_eq!(None, parsed.options_last("file").unwrap().value);
}
#[test]
fn t_parsed_output_110() {
let parsed = OptSpecs::new()
.option("file", "f", OptValueType::Required)
.option("debug", "d", OptValueType::Required)
.getopt(["-fx", "-d", "", "-f"]);
assert_eq!(true, parsed.options_first("file").unwrap().value_required);
assert_eq!(
"x",
parsed.options_first("file").unwrap().value.clone().unwrap()
);
assert_eq!(None, parsed.options_last("file").unwrap().value);
assert_eq!(
"",
parsed
.options_first("debug")
.unwrap()
.value
.clone()
.unwrap()
);
}
#[test]
fn t_parsed_output_120() {
let parsed = OptSpecs::new()
.option("file", "f", OptValueType::Required)
.option("debug", "d", OptValueType::Required)
.getopt(["-f123", "-d", "", "-f", "456", "-f"]);
let f = parsed.options_value_all("file");
let d = parsed.options_value_all("debug");
assert_eq!(2, f.len());
assert_eq!("123", f[0]);
assert_eq!("456", f[1]);
assert_eq!(1, d.len());
assert_eq!("", d[0]);
assert_eq!(None, parsed.options_last("file").unwrap().value);
let m = parsed.required_value_missing();
assert_eq!(1, m.len());
assert_eq!("f", m[0].name);
}
#[test]
fn t_parsed_output_130() {
let parsed = OptSpecs::new()
.option("file", "file", OptValueType::Required)
.option("debug", "debug", OptValueType::Required)
.getopt(["--file=123", "--debug", "", "--file", "456", "--file"]);
let f = parsed.options_value_all("file");
let d = parsed.options_value_all("debug");
assert_eq!(2, f.len());
assert_eq!("123", f[0]);
assert_eq!("456", f[1]);
assert_eq!(1, d.len());
assert_eq!("", d[0]);
assert_eq!(None, parsed.options_last("file").unwrap().value);
let m = parsed.required_value_missing();
assert_eq!(1, m.len());
assert_eq!("file", m[0].name);
}
#[test]
fn t_parsed_output_140() {
let parsed = OptSpecs::new()
.flag(OptFlags::OptionsEverywhere)
.option("debug", "d", OptValueType::Optional)
.option("debug", "debug", OptValueType::Optional)
.getopt([
"-d",
"-d123",
"-d",
"--debug",
"--debug=",
"foo",
"--debug=456",
"-d",
]);
let d = parsed.options_all("debug");
assert_eq!(7, d.len());
let d = parsed.options_value_all("debug");
assert_eq!(3, d.len());
assert_eq!("123", d[0]);
assert_eq!("", d[1]);
assert_eq!("456", d[2]);
assert_eq!("123", parsed.options_value_first("debug").unwrap());
assert_eq!("456", parsed.options_value_last("debug").unwrap());
assert_eq!(None, parsed.options_value_first("not-at-all"));
assert_eq!(None, parsed.options_value_last("not-at-all"));
assert_eq!("foo", parsed.other[0]);
}
#[test]
fn t_parsed_output_150() {
let parsed = OptSpecs::new().limit_unknown_options(6).getopt([
"-abcd",
"-e",
"--debug",
"-x", // Won't be listed in unknown because of limit.
"--",
"--debug=",
"foo",
"--debug=456",
]);
assert_eq!(0, parsed.options.len());
assert_eq!(3, parsed.other.len());
assert_eq!(6, parsed.unknown.len());
assert_eq!(vec!["a", "b", "c", "d", "e", "debug"], parsed.unknown);
}
#[test]
fn t_parsed_output_160() {
let parsed = OptSpecs::new()
.option("file", "file", OptValueType::Required)
.getopt(["--file", "--", "--", "--"]);
assert_eq!(
"--",
parsed.options_first("file").unwrap().value.clone().unwrap()
);
assert_eq!(1, parsed.other.len());
assert_eq!("--", parsed.other[0]);
assert_eq!(0, parsed.required_value_missing().len());
}
#[test]
fn t_parsed_output_170() {
let parsed = OptSpecs::new().getopt(["foo", "bar"]);
assert_eq!(None, parsed.options_first("not-at-all"));
assert_eq!(None, parsed.options_last("not-at-all"));
}
#[test]
fn t_parsed_output_180() {
let parsed = OptSpecs::new()
.limit_unknown_options(3)
.option("bar", "bar", OptValueType::None)
.getopt(["-aaa", "--foo", "--foo", "--bar=", "--bar=", "-x"]);
assert_eq!(3, parsed.unknown.len());
assert_eq!("a", parsed.unknown[0]);
assert_eq!("foo", parsed.unknown[1]);
assert_eq!("bar=", parsed.unknown[2]);
}
#[test]
fn t_parsed_output_190() {
let parsed = OptSpecs::new()
.option("äiti", "äiti", OptValueType::Required)
.option("€uro", "€uro", OptValueType::Required)
.getopt(["--äiti=ööö", "--€uro", "€€€", "--äiti", "ää", "--äiti"]);
let a = parsed.options_value_all("äiti");
let e = parsed.options_value_all("€uro");
assert_eq!(2, a.len());
assert_eq!("ööö", a[0]);
assert_eq!("ää", a[1]);
assert_eq!("ööö", parsed.options_value_first("äiti").unwrap());
assert_eq!("ää", parsed.options_value_last("äiti").unwrap());
assert_eq!(1, e.len());
assert_eq!("€€€", e[0]);
assert_eq!("€€€", parsed.options_value_first("€uro").unwrap());
assert_eq!("€€€", parsed.options_value_last("€uro").unwrap());
assert_eq!(None, parsed.options_last("äiti").unwrap().value);
let m = parsed.required_value_missing();
assert_eq!(1, m.len());
assert_eq!("äiti", m[0].name);
assert_eq!(None, m[0].value);
}
#[test]
fn t_parsed_output_195() {
let parsed = OptSpecs::new().getopt(["-ä€", "--€uro", "äää", "€€€"]);
assert_eq!(2, parsed.other.len());
assert_eq!("äää", parsed.other[0]);
assert_eq!("€€€", parsed.other[1]);
assert_eq!(3, parsed.unknown.len());
assert_eq!("ä", parsed.unknown[0]);
assert_eq!("€", parsed.unknown[1]);
assert_eq!("€uro", parsed.unknown[2]);
}
#[test]
fn t_parsed_output_200() {
let parsed = OptSpecs::new().limit_other_args(5).getopt(1..10);
assert_eq!(5, parsed.other.len());
assert_eq!(vec!["1", "2", "3", "4", "5"], parsed.other);
}
#[test]
fn t_parsed_output_210() {
let parsed = OptSpecs::new().limit_other_args(0).getopt(1..10);
assert_eq!(0, parsed.other.len());
}
#[test]
fn t_parsed_output_220() {
let parsed = OptSpecs::new()
.option("file", "f", OptValueType::Required)
.option("file", "file", OptValueType::Required)
.option("help", "help", OptValueType::None)
.limit_options(3)
.limit_other_args(1)
.limit_unknown_options(3)
.getopt([
"--unknown",
"--help=",
"-ab",
"-f",
"one",
"-ftwo",
"--file",
"three",
"--file",
"four",
"other1",
"other2",
]);
assert_eq!(3, parsed.options.len());
assert_eq!(
vec!["one", "two", "three"],
parsed.options_value_all("file")
);
assert_eq!(1, parsed.other.len());
assert_eq!("other1", parsed.other[0]);
assert_eq!(3, parsed.unknown.len());
assert_eq!(vec!["unknown", "help=", "a"], parsed.unknown);
}
#[test]
fn t_parsed_output_230() {
let parsed = OptSpecs::new()
.option("file", "f", OptValueType::Required)
.option("file", "file", OptValueType::Required)
.limit_options(3)
.getopt(["-f", "one", "-ftwo", "--file=three", "--unknown"]);
assert_eq!(
vec!["one", "two", "three"],
parsed.options_value_all("file")
);
assert_eq!(1, parsed.unknown.len());
assert_eq!("unknown", parsed.unknown[0]);
}
#[test]
fn t_parsed_output_240() {
let parsed = OptSpecs::new()
.option("help", "h", OptValueType::None)
.limit_options(3)
.getopt(["-xhhhh"]);
assert_eq!(3, parsed.options.len());
assert_eq!(true, parsed.options_first("help").is_some());
assert_eq!(1, parsed.unknown.len());
assert_eq!("x", parsed.unknown[0]);
}
#[test]
fn t_parsed_output_250() {
let parsed = OptSpecs::new()
.option("help", "h", OptValueType::None)
.limit_options(3)
.getopt(["-x", "-h", "-h", "-h", "-h"]);
assert_eq!(3, parsed.options.len());
assert_eq!(true, parsed.options_first("help").is_some());
assert_eq!(1, parsed.unknown.len());
assert_eq!("x", parsed.unknown[0]);
}
#[test]
fn t_parsed_output_260() {
let parsed = OptSpecs::new()
.option("help", "h", OptValueType::None)
.limit_options(3)
.getopt(["-x", "-h", "-h", "--", "-h", "-h"]);
assert_eq!(2, parsed.options.len());
assert_eq!(true, parsed.options_first("help").is_some());
assert_eq!(2, parsed.other.len());
assert_eq!(vec!["-h", "-h"], parsed.other);
assert_eq!(1, parsed.unknown.len());
assert_eq!("x", parsed.unknown[0]);
}
#[test]
fn t_parsed_output_270() {
let parsed = OptSpecs::new()
.flag(OptFlags::OptionsEverywhere)
.option("help", "h", OptValueType::None)
.option("file", "f", OptValueType::Required)
.limit_options(1)
.limit_other_args(2)
.limit_unknown_options(1)
.getopt(["bar", "-habf", "123", "foo"]);
// "123" must be parsed as "f" option's value even though it is
// beyond limit_options.
assert_eq!(true, parsed.options_first("help").is_some());
assert_eq!(false, parsed.options_first("file").is_some());
assert_eq!(2, parsed.other.len());
assert_eq!("bar", parsed.other[0]);
assert_eq!("foo", parsed.other[1]);
assert_eq!(1, parsed.unknown.len());
assert_eq!("a", parsed.unknown[0]);
}
#[test]
fn t_parsed_output_280() {
let parsed = OptSpecs::new()
.flag(OptFlags::OptionsEverywhere)
.option("help", "help", OptValueType::None)
.option("file", "file", OptValueType::Required)
.limit_options(1)
.limit_other_args(2)
.limit_unknown_options(1)
.getopt(["bar", "--help", "-ab", "--file", "123", "foo"]);
// "123" must be parsed as "--file" option's value even though
// it is beyond limit_options.
assert_eq!(true, parsed.options_first("help").is_some());
assert_eq!(false, parsed.options_first("file").is_some());
assert_eq!(2, parsed.other.len());
assert_eq!("bar", parsed.other[0]);
assert_eq!("foo", parsed.other[1]);
assert_eq!(1, parsed.unknown.len());
assert_eq!("a", parsed.unknown[0]);
}
}