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
#![warn(missing_docs)]
#![warn(rustdoc::missing_doc_code_examples)]
#![allow(clippy::needless_doctest_main)]
//! Lightweight and flexible command line argument parser with derive and combinator style API
//! # Derive and combinatoric API
//!
//! `bpaf` supports both combinatoric and derive APIs and it's possible to mix and match both APIs
//! at once. Both APIs provide access to mostly the same features, some things are more convenient
//! to do with derive (usually less typing), some - with combinatoric (usually maximum flexibility
//! and reducing boilerplate structs). In most cases using just one would suffice. Whenever
//! possible APIs share the same keywords and overall structure. Documentation for combinatoric API
//! also explains how to perform the same action in derive style.
//! # Quick links
//!
//! - [Derive tutorial](crate::_derive_tutorial)
//! - [Combinatoric tutorial](crate::_combinatoric_tutorial)
//! - [FAQ](crate::_faq)
//! - [Batteries included](crate::batteries)
//! # Quick start, derive edition
//!
//! 1. Add `bpaf` under `[dependencies]` in your `Cargo.toml`
//! ```toml
//! [dependencies]
//! bpaf = { version = "0.5", features = ["derive"] }
//! ```
//!
//! 2. Define a structure containing command line attributes and run generated function
//! ```no_run
//! use bpaf::Bpaf;
//!
//! #[derive(Clone, Debug, Bpaf)]
//! #[bpaf(options, version)]
//! /// Accept speed and distance, print them
//! struct SpeedAndDistance {
//! /// Speed in KPH
//! speed: f64,
//! /// Distance in miles
//! distance: f64,
//! }
//!
//! fn main() {
//! // #[derive(Bpaf) generates function speed_and_distance
//! let opts = speed_and_distance().run();
//! println!("Options: {:?}", opts);
//! }
//! ```
//!
//! 3. Try to run the app
//! ```console
//! % very_basic --help
//! Accept speed and distance, print them
//!
//! Usage: --speed ARG --distance ARG
//!
//! Available options:
//! --speed <ARG> Speed in KPH
//! --distance <ARG> Distance in miles
//! -h, --help Prints help information
//! -V, --version Prints version information
//!
//! % very_basic --speed 100
//! Expected --distance ARG, pass --help for usage information
//!
//! % very_basic --speed 100 --distance 500
//! Options: SpeedAndDistance { speed: 100.0, distance: 500.0 }
//!
//! % very_basic --version
//! Version: 0.5.0 (taken from Cargo.toml by default)
//!```
//! # Quick start, combinatoric edition
//!
//! 1. Add `bpaf` under `[dependencies]` in your `Cargo.toml`
//! ```toml
//! [dependencies]
//! bpaf = "0.5"
//! ```
//!
//! 2. Declare parsers for components, combine them and run it
//! ```no_run
//! use bpaf::{construct, long, Parser};
//! #[derive(Clone, Debug)]
//! struct SpeedAndDistance {
//! /// Dpeed in KPH
//! speed: f64,
//! /// Distance in miles
//! distance: f64,
//! }
//!
//! fn main() {
//! // primitive parsers
//! let speed = long("speed")
//! .help("Speed in KPG")
//! .argument("SPEED")
//! .from_str::<f64>();
//!
//! let distance = long("distance")
//! .help("Distance in miles")
//! .argument("DIST")
//! .from_str::<f64>();
//!
//! // parser containing information about both speed and distance
//! let parser = construct!(SpeedAndDistance { speed, distance });
//!
//! // option parser with metainformation attached
//! let speed_and_distance
//! = parser
//! .to_options()
//! .descr("Accept speed and distance, print them");
//!
//! let opts = speed_and_distance.run();
//! println!("Options: {:?}", opts);
//! }
//! ```
//!
//! 3. Try to run it, output should be similar to derive edition
//! # Design goals: flexibility, reusability, correctness
//! Library allows to consume command line arguments by building up parsers for individual
//! arguments and combining those primitive parsers using mostly regular Rust code plus one macro.
//! For example it's possible to take a parser that requires a single floating point number and
//! transform it to a parser that takes several of them or takes it optionally so different
//! subcommands or binaries can share a lot of the code:
//! ```rust
//! # use bpaf::*;
//! // a regular function that doesn't depend on anything, you can export it
//! // and share across subcommands and binaries
//! fn speed() -> impl Parser<f64> {
//! long("speed")
//! .help("Speed in KPH")
//! .argument("SPEED")
//! .from_str::<f64>()
//! }
//!
//! // this parser accepts multiple `--speed` flags from a command line when used,
//! // collecting them into a vector
//! fn multiple_args() -> impl Parser<Vec<f64>> {
//! speed().many()
//! }
//!
//! // this parser checks if `--speed` is present and uses value of 42 if it's not
//! fn with_fallback() -> impl Parser<f64> {
//! speed().fallback(42.0)
//! }
//! ```
//!
//! At any point you can apply additional validation or fallback values in terms of current parsed
//! state of each subparser and you can have several stages as well:
//!
//! ```rust
//! # use bpaf::*;
//! #[derive(Clone, Debug)]
//! struct Speed(f64);
//! fn speed() -> impl Parser<Speed> {
//! long("speed")
//! .help("Speed in KPH")
//! .argument("SPEED")
//! // After this point the type is `impl Parser<String>`
//! .from_str::<f64>()
//! // `from_str` uses FromStr trait to transform contained value into `f64`
//!
//! // You can perform additional validation with `parse` and `guard` functions
//! // in as many steps as required.
//! // Before and after next two applications the type is still `impl Parser<f64>`
//! .guard(|&speed| speed >= 0.0, "You need to buy a DLC to move backwards")
//! .guard(|&speed| speed <= 100.0, "You need to buy a DLC to break the speed limits")
//!
//! // You can transform contained values, next line gives `impl Parser<Speed>` as a result
//! .map(|speed| Speed(speed))
//! }
//! ```
//!
//! Library follows parse, don’t validate approach to validation when possible. Usually you parse
//! your values just once and get the results as a rust struct/enum with strict types rather than a
//! stringly typed hashmap with stringly typed values in both combinatoric and derive APIs.
//! # Design goals: restrictions
//!
//! The main restricting library sets is that you can't use parsed values (but not the fact that
//! parser succeeded or failed) to decide how to parse subsequent values. In other words parsers
//! don't have the monadic strength, only the applicative one.
//!
//! To give an example, you can implement this description:
//!
//! > Program takes one of `--stdout` or `--file` flag to specify the output target, when it's `--file`
//! > program also requires `-f` attribute with the filename
//!
//! But not this one:
//!
//! > Program takes an `-o` attribute with possible values of `'stdout'` and `'file'`, when it's `'file'`
//! > program also requires `-f` attribute with the filename
//!
//! This set of restrictions allows to extract information about the structure of the computations
//! to generate help and overall results in less confusing enduser experience
//! # Design non goals: performance
//!
//! Library aims to optimize for flexibility, reusability and compilation time over runtime
//! performance which means it might perform some additional clones, allocations and other less
//! optimal things. In practice unless you are parsing tens of thousands of different parameters
//! and your app exits within microseconds - this won't affect you. That said - any actual
//! performance related problems with real world applications is a bug.
//! # More examples
//!
//! You can find a bunch more examples here: <https://github.com/pacak/bpaf/tree/master/examples>
//!
//!
//! They're usually documented or at least contain an explanation to important bits and you can see
//! how they work by cloning the repo and running
//! ```shell
//! $ cargo run --example example_name
//! ```
//! # Testing your own parsers
//!
//! You can test your own parsers to maintain compatibility or simply checking expected output
//! with [`run_inner`](OptionParser::run_inner)
//!
//! ```rust
//! # use bpaf::*;
//! #[derive(Debug, Clone, Bpaf)]
//! #[bpaf(options)]
//! pub struct Options {
//! pub user: String
//! }
//!
//! #[test]
//! fn test_my_options() {
//! let help = options()
//! .run_inner(Args::from(&["--help"]))
//! .unwrap_err()
//! .unwrap_stdout();
//! let expected_help = "\
//! Usage --user <ARG>
//! <skip>
//! ";
//!
//! assert_eq!(help, expected_help);
//! }
//! ```
//! # Cargo features
//!
//! - `derive`: adds a dependency on [`bpaf_derive`] crate and reexport `Bpaf` derive macro. You
//! need to enable it to use derive API
//!
//! - `extradocs`: used internally to include tutorials to <https://docs.rs/bpaf>, no reason to
//! enable it for local development unless you want to build your own copy of the documentation
//! (<https://github.com/rust-lang/cargo/issues/8905>)
//!
//! - `batteries`: helpers implemented with public `bpaf` API
#[cfg(feature = "extradocs")]
pub mod _combinatoric_tutorial;
#[cfg(feature = "extradocs")]
pub mod _derive_tutorial;
#[cfg(feature = "extradocs")]
pub mod _faq;
mod args;
mod info;
mod item;
mod meta;
mod meta_help;
mod meta_usage;
mod meta_youmean;
mod params;
mod structs;
pub mod batteries;
#[cfg(test)]
mod tests;
#[doc(hidden)]
pub use crate::info::Error;
use crate::item::Item;
use std::marker::PhantomData;
#[doc(hidden)]
pub use structs::PCon;
use structs::{
ParseFail, ParseFallback, ParseFallbackWith, ParseFromStr, ParseGroupHelp, ParseGuard,
ParseHide, ParseMany, ParseMap, ParseOptional, ParseOrElse, ParsePure, ParseSome, ParseWith,
};
#[doc(inline)]
pub use crate::args::Args;
pub use crate::info::OptionParser;
pub use crate::meta::Meta;
#[doc(inline)]
pub use crate::params::{command, env, long, positional, positional_os, short, Command, Named};
#[doc(inline)]
#[cfg(feature = "bpaf_derive")]
pub use bpaf_derive::Bpaf;
/// Compose several parsers to produce a single result
///
/// # Usage reference
/// ```rust
/// # use bpaf::*;
/// # { struct Res(bool, bool, bool);
/// # let a = short('a').switch(); let b = short('b').switch(); let c = short('c').switch();
/// // structs with unnamed fields:
/// construct!(Res(a, b, c));
/// # }
///
/// # { struct Res { a: bool, b: bool, c: bool }
/// # let a = short('a').switch(); let b = short('b').switch(); let c = short('c').switch();
/// // structs with named fields:
/// construct!(Res {a, b, c});
/// # }
///
/// # { enum Ty { Res(bool, bool, bool) }
/// # let a = short('a').switch(); let b = short('b').switch(); let c = short('c').switch();
/// // enums with unnamed fields:
/// construct!(Ty::Res(a, b, c));
/// # }
///
/// # { enum Ty { Res { a: bool, b: bool, c: bool } }
/// # let a = short('a').switch(); let b = short('b').switch(); let c = short('c').switch();
/// // enums with named fields:
/// construct!(Ty::Res {a, b, c});
/// # }
///
/// # { let a = short('a').switch(); let b = short('b').switch(); let c = short('c').switch();
/// // tuples:
/// construct!(a, b, c);
/// # }
///
/// # { let a = short('a').switch(); let b = short('b').switch(); let c = short('c').switch();
/// // parallel composition, tries all parsers, picks succeeding left most one:
/// construct!([a, b, c]);
/// # }
/// ```
///
/// # Combinatoric usage
/// `construct!` can compose parsers sequentially or in parallel.
///
/// Sequential composition runs each parser and if all of them succeed you get a parser object of a
/// new type back. Placeholder names for values inside `construct!` macro must correspond to both
/// struct/enum names and parser names present in scope. In examples below `a` corresponds to a
/// function and `b` corresponds to a variable name. Note parens in `a()`, you must to use them to
/// indicate function parsers.
///
/// ```rust
/// # use bpaf::*;
/// struct Res (u32, u32);
/// enum Ul { T { a: u32, b: u32 } }
///
/// // You can share parameters across multiple construct invocations
/// // if defined as functions
/// fn a() -> impl Parser<u32> {
/// short('a').argument("N").from_str::<u32>()
/// }
///
/// // You can construct structs or enums with unnamed fields
/// fn res() -> impl Parser<Res> {
/// let b = short('b').argument("n").from_str::<u32>();
/// construct!(Res ( a(), b ))
/// }
///
/// // You can construct structs or enums with named fields
/// fn ult() -> impl Parser<Ul> {
/// let b = short('b').argument("n").from_str::<u32>();
/// construct!(Ul::T { a(), b })
/// }
///
/// // You can also construct simple tuples
/// fn tuple() -> impl Parser<(u32, u32)> {
/// let b = short('b').argument("n").from_str::<u32>();
/// construct!(a(), b)
/// }
/// ```
///
/// Parallel composition picks one of several available parsers (result types must match) and returns a
/// parser object of the same type. Similar to sequential composition you can use parsers from variables
/// or functions:
///
/// ```rust
/// # use bpaf::*;
/// fn b() -> impl Parser<u32> {
/// short('b').argument("NUM").from_str::<u32>()
/// }
///
/// fn a_or_b() -> impl Parser<u32> {
/// let a = short('a').argument("NUM").from_str::<u32>();
/// // equivalent way of writing this would be `a.or_else(b())`
/// construct!([a, b()])
/// }
/// ```
///
/// # Derive usage
///
/// `bpaf_derive` would combine fields of struct or enum constructors sequentially and enum
/// variants in parallel.
/// ```rust
/// # use bpaf::*;
/// // to satisfy this parser user needs to pass both -a and -b
/// #[derive(Debug, Clone, Bpaf)]
/// struct Res {
/// a: u32,
/// b: u32,
/// }
///
/// // to satisfy this parser user needs to pass one (and only one) of -a, -b, -c or -d
/// #[derive(Debug, Clone, Bpaf)]
/// enum Enumeraton {
/// A { a: u32 },
/// B { b: u32 },
/// C { c: u32 },
/// D { d: u32 },
/// }
///
/// // here user needs to pass either both -a AND -b or both -c and -d
/// #[derive(Debug, Clone, Bpaf)]
/// enum Ult {
/// AB { a: u32, b: u32 },
/// CD { c: u32, d: u32 }
/// }
/// ```
#[macro_export]
macro_rules! construct {
// construct!(Enum::Cons { a, b, c })
($ns:ident $(:: $con:ident)* { $($tokens:tt)* }) => {{ $crate::construct!(@prepare [named [$ns $(:: $con)*]] [] $($tokens)*) }};
(:: $ns:ident $(:: $con:ident)* { $($tokens:tt)* }) => {{ $crate::construct!(@prepare [named [:: $ns $(:: $con)*]] [] $($tokens)*) }};
// construct!(Enum::Cons ( a, b, c ))
($ns:ident $(:: $con:ident)* ( $($tokens:tt)* )) => {{ $crate::construct!(@prepare [pos [$ns $(:: $con)*]] [] $($tokens)*) }};
(:: $ns:ident $(:: $con:ident)* ( $($tokens:tt)* )) => {{ $crate::construct!(@prepare [pos [:: $ns $(:: $con)*]] [] $($tokens)*) }};
// construct!( a, b, c )
($first:ident , $($tokens:tt)*) => {{ $crate::construct!(@prepare [pos] [] $first , $($tokens)*) }};
($first:ident (), $($tokens:tt)*) => {{ $crate::construct!(@prepare [pos] [] $first (), $($tokens)*) }};
// construct![a, b, c]
([$first:ident $($tokens:tt)*]) => {{ $crate::construct!(@prepare [alt] [] $first $($tokens)*) }};
(@prepare $ty:tt [$($fields:tt)*] $field:ident (), $($rest:tt)*) => {{
let $field = $field();
$crate::construct!(@prepare $ty [$($fields)* $field] $($rest)*)
}};
(@prepare $ty:tt [$($fields:tt)*] $field:ident () $($rest:tt)*) => {{
let $field = $field();
$crate::construct!(@prepare $ty [$($fields)* $field] $($rest)*)
}};
(@prepare $ty:tt [$($fields:tt)*] $field:ident, $($rest:tt)*) => {{
$crate::construct!(@prepare $ty [$($fields)* $field] $($rest)*)
}};
(@prepare $ty:tt [$($fields:tt)*] $field:ident $($rest:tt)*) => {{
$crate::construct!(@prepare $ty [$($fields)* $field] $($rest)*)
}};
(@prepare [alt] [$first:ident $($fields:ident)*]) => {
#[allow(deprecated)]
{ use $crate::Parser; $first $(.or_else($fields))* }
};
(@prepare $ty:tt [$($fields:tt)*]) => {{
use $crate::Parser;
let meta = $crate::Meta::And(vec![ $($fields.meta()),* ]);
let inner = move |args: &mut $crate::Args| {
$(let $fields = $fields.eval(args)?;)*
args.current = None;
::std::result::Result::Ok::<_, $crate::Error>
($crate::construct!(@make $ty [$($fields)*]))
};
$crate::PCon { inner, meta }
}};
(@make [named [$($con:tt)+]] [$($fields:ident)*]) => { $($con)+ { $($fields),* } };
(@make [pos [$($con:tt)+]] [$($fields:ident)*]) => { $($con)+ ( $($fields),* ) };
(@make [pos] [$($fields:ident)*]) => { ( $($fields),* ) };
}
/// Simple or composed argument parser
///
/// # Overview
///
/// It's best to think of an object implementing [`Parser`] trait as a container with a value
/// inside that are composable with other `Parser` containers using [`construct!`] and the only
/// way to extract this value is by transforming it to [`OptionParser`] with
/// [`to_options`](Parser::to_options) and running it with [`run`](OptionParser::run). At which
/// point you either get your value out or `bpaf` would generate a message describing a problem
/// (missing argument, validation failure, user requested help, etc) and the program would
/// exit.
///
/// Values inside can be of any type for as long as they implement `Debug`, `Clone` and
/// there's no lifetimes other than static.
///
/// When consuming the values you usually start with `Parser<String>` or `Parser<OsString>` which
/// you then transform into something that your program would actually use. it's better to perform
/// as much parsing and validation inside the `Parser` as possible so the program itself gets
/// strictly typed and correct value while user gets immediate feedback on what's wrong with the
/// arguments they pass.
///
/// For example suppose your program needs user to specify a dimensions of a rectangle, with sides
/// being 1..20 units long and the total area must not exceed 200 units square. A parser that
/// consumes it might look like this:
///
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Copy, Clone)]
/// struct Rectangle {
/// width: u32,
/// height: u32,
/// }
///
/// fn rectangle() -> impl Parser<Rectangle> {
/// let invalid_size = "Sides of a rectangle must be 1..20 units long";
/// let invalid_area = "Area of a rectangle must not exceed 200 units square";
/// let width = long("width")
/// .help("Width of the rectangle")
/// .argument("PX")
/// .from_str::<u32>()
/// .guard(|&x| 1 <= x && x <= 10, invalid_size);
/// let height = long("height")
/// .help("Height of the rectangle")
/// .argument("PX")
/// .from_str::<u32>()
/// .guard(|&x| 1 <= x && x <= 10, invalid_size);
/// construct!(Rectangle { width, height })
/// .guard(|&r| r.width * r.height <= 400, invalid_area)
/// }
/// ```
///
///
/// # Derive specific considerations
///
/// Every method defined on this trait belongs to the `postprocessing` section of the field
/// annotation. `bpaf_derive` would try to figure out what chain to use for as long as there's no
/// options changing the type: you can use [`fallback`](Parser::fallback_with),
/// [`fallback_with`](Parser::fallback_with), [`guard`](Parser::guard), [`hide`](Parser::hide`) and
/// [`group_help`](Parser::group_help) but not the rest of them.
///
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// struct Options {
/// // no annotation at all - `bpaf_derive` inserts implicit `argument` and `from_str`
/// number_1: u32,
///
/// // fallback isn't changing the type so `bpaf_derive` still handles it
/// #[bpaf(fallback(42))]
/// number_2: u32,
///
/// // `bpaf_derive` inserts implicit `argument`, `optional` and `from_str`
/// number_3: Option<u32>,
///
/// // fails to compile: you need to specify a consumer, `argument` or `argument_os`
/// // #[bpaf(optional)]
/// // number_4: Option<u32>
///
/// // fails to compile: you also need to specify how to go from String to u32
/// // #[bpaf(argument("N"), optional)]
/// // number_5: Option<u32>,
///
/// // explicit consumer and a full postprocessing chain
/// #[bpaf(argument("N"), from_str(u32), optional)]
/// number_6: Option<u32>,
/// }
/// ```
pub trait Parser<T> {
/// Evaluate inner function
///
/// Mostly internal implementation details, you can try using it to test your parsers
// it's possible to move this function from the trait to the structs but having it
// in the trait ensures the composition always works
#[doc(hidden)]
fn eval(&self, args: &mut Args) -> Result<T, Error>;
/// Included information about the parser
///
/// Mostly internal implementation details, you can try using it to test your parsers
// it's possible to move this function from the trait to the structs but having it
// in the trait ensures the composition always works
#[doc(hidden)]
fn meta(&self) -> Meta;
// change shape
// {{{ many
/// Consume zero or more items from a command line and collect them into [`Vec`]
///
/// `many` only collects elements that only consume something from the argument list.
///
/// # Combinatoric usage:
/// ```rust
/// # use bpaf::*;
/// fn numbers() -> impl Parser<Vec<u32>> {
/// short('n')
/// .argument("NUM")
/// .from_str::<u32>()
/// .many()
/// }
/// ```
///
/// # Derive usage:
/// `bpaf` would insert implicit `many` when resulting type is a vector
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// struct Options {
/// #[bpaf(short, argument("NUM"))]
/// numbers: Vec<u32>
/// }
/// ```
/// But it's also possible to specify it explicitly, both cases renerate the same code.
/// Note, since using `many` resets the postprocessing chain - you also need to specify
/// [`from_str`](Parser::from_str)
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// struct Options {
/// #[bpaf(short, argument("NUM"), from_str(u32), many)]
/// numbers: Vec<u32>
/// }
/// ```
///
///
/// # Example
/// ```console
/// $ app -n 1 -n 2 -n 3
/// // [1, 2, 3]
/// ```
///
/// # See also
/// [`some`](Parser::some) also collects results to a vector but requires at least one
/// element to succeed
fn many(self) -> ParseMany<Self>
where
Self: Sized,
{
ParseMany { inner: self }
}
// }}}
// {{{ some
/// Consume one or more items from a command line
///
/// Takes a string used as an error message if there's no specified parameters
///
/// `some` only collects elements that only consume something from the argument list.
///
/// # Combinatoric usage:
/// ```rust
/// # use bpaf::*;
/// let numbers
/// = short('n')
/// .argument("NUM")
/// .from_str::<u32>()
/// .some("Need at least one number");
/// # drop(numbers);
/// ```
///
/// # Derive usage
/// Since using `some` resets the postprocessing chain - you also need to specify
/// [`from_str`](Parser::from_str) or similar, depending on your type
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// struct Options {
/// #[bpaf(short, argument("NUM"), from_str(u32), some("Need at least one number"))]
/// numbers: Vec<u32>
/// }
/// ```
///
///
/// # Example
/// ```console
/// $ app
/// // fails with "Need at least one number"
/// $ app -n 1 -n 2 -n 3
/// // [1, 2, 3]
/// ```
///
/// # See also
/// [`many`](Parser::many) also collects results to a vector but succeeds with
/// no matching values
#[must_use]
fn some(self, message: &'static str) -> ParseSome<Self>
where
Self: Sized + Parser<T>,
{
ParseSome {
inner: self,
message,
}
}
// }}}
// {{{ optional
/// Turn a required argument into optional one
///
/// `optional` converts any failure caused by missing items into is `None` and passes
/// the remaining parsing failures untouched.
///
/// # Combinatoric usage
/// ```rust
/// # use bpaf::*;
/// fn number() -> impl Parser<Option<u32>> {
/// short('n')
/// .argument("NUM")
/// .from_str::<u32>()
/// .optional()
/// }
/// ```
///
/// # Derive usage
///
/// By default `bpaf_derive` would automatically use optional for fields of type `Option<T>`,
/// for as long as it's not prevented from doing so by present postprocessing options
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// struct Options {
/// #[bpaf(short, argument("NUM"))]
/// number: Option<u32>
/// }
/// ```
///
/// But it's also possible to specify it explicitly, in which case you need to specify
/// a full postprocessing chain which starts from [`from_str`](Parser::from_str) in this
/// example.
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// struct Options {
/// #[bpaf(short, argument("NUM"), from_str(u32), optional)]
/// number: Option<u32>
/// }
/// ```
///
/// # Example
/// ```console
/// $ app
/// // None
/// $ app -n 42
/// // Some(42)
/// ```
#[must_use]
fn optional(self) -> ParseOptional<Self>
where
Self: Sized + Parser<T>,
{
ParseOptional { inner: self }
}
// }}}
// parse
// {{{ parse
/// Apply a failing transformation to a contained value
///
/// This is a most general of transforming parsers and you can express remaining ones
/// terms of it: [`map`](Parser::map), [`from_str`](Parser::from_str) and
/// [`guard`](Parser::guard).
///
/// Examples given here are a bit artificail, to parse a value from string you should use
/// [`from_str`](Parser::from_str).
///
/// # Combinatoric usage:
/// ```rust
/// # use bpaf::*;
/// # use std::str::FromStr;
/// fn number() -> impl Parser<u32> {
/// short('n')
/// .argument("NUM")
/// .parse(|s| u32::from_str(&s))
/// }
/// ```
/// # Derive usage:
/// `parse` takes a single parameter: function name to call. Function type should match
/// parameter `F` used by `parse` in combinatoric API.
/// ```rust
/// # use bpaf::*;
/// # use std::str::FromStr;
/// # use std::num::ParseIntError;
/// fn read_number(s: String) -> Result<u32, ParseIntError> {
/// u32::from_str(&s)
/// }
///
/// #[derive(Debug, Clone, Bpaf)]
/// struct Options {
/// #[bpaf(short, argument("NUM"), parse(read_number))]
/// number: u32
/// }
/// ```
///
/// # Example
/// ```console
/// $ app -n 12
/// // 12
/// # app -n pi
/// // fails with "Couldn't parse "pi": invalid numeric literal"
/// ```
///
fn parse<F, R, E>(self, f: F) -> ParseWith<T, Self, F, E, R>
where
Self: Sized + Parser<T>,
F: Fn(T) -> Result<R, E>,
E: ToString,
{
ParseWith {
inner: self,
inner_res: PhantomData,
parse_fn: f,
res: PhantomData,
err: PhantomData,
}
}
// }}}
// {{{ map
/// Apply a pure transformation to a contained value
///
/// A common case of [`parse`](Parser::parse) method, exists mostly for convenience.
///
/// # Combinatoric usage
/// ```rust
/// # use bpaf::*;
/// fn number() -> impl Parser<u32> {
/// short('n')
/// .argument("NUM")
/// .from_str::<u32>()
/// .map(|v| v * 2)
/// }
/// ```
///
/// # Derive usage
/// ```rust
/// # use bpaf::*;
/// fn double(num: u32) -> u32 {
/// num * 2
/// }
///
/// #[derive(Debug, Clone, Bpaf)]
/// struct Options {
/// #[bpaf(short, argument("NUM"), from_str(u32), map(double))]
/// number: u32,
/// }
/// ```
///
/// # Example
/// ```console
/// $ app -n 21
/// // 42
/// ```
fn map<F, R>(self, map: F) -> ParseMap<T, Self, F, R>
where
Self: Sized + Parser<T>,
F: Fn(T) -> R + 'static,
{
ParseMap {
inner: self,
inner_res: PhantomData,
map_fn: map,
res: PhantomData,
}
}
// }}}
// {{{ from_str
/// Parse stored [`String`] using [`FromStr`](std::str::FromStr) instance
///
/// A common case of [`parse`](Parser::parse) method, exists mostly for convenience.
///
/// # Combinatoric usage
/// ```rust
/// # use bpaf::*;
/// fn speed() -> impl Parser<f64> {
/// short('s')
/// .argument("SPEED")
/// .from_str::<f64>()
/// }
/// ```
///
/// # Derive usage
/// By default `bpaf_derive` would use [`from_str`](Parser::from_str) for any time it's not
/// familiar with so you don't need to specify anything
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// struct Options {
/// #[bpaf(short, argument("SPEED"))]
/// speed: f64
/// }
/// ```
///
/// But it's also possible to specify it explicitly
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// struct Options {
/// #[bpaf(short, argument("SPEED"), from_str(f64))]
/// speed: f64
/// }
/// ```
///
/// # Example
/// ```console
/// $ app -s pi
/// // fails with "Couldn't parse "pi": invalid float literal"
/// $ app -s 3.1415
/// // Version: 3.1415
/// ```
///
/// # See also
/// Other parsing and restricting methods include [`parse`](Parser::parse) and
/// [`guard`](Parser). For transformations that can't fail you can use [`map`](Parser::map).
#[must_use]
#[allow(clippy::wrong_self_convention)]
fn from_str<R>(self) -> ParseFromStr<Self, R>
where
Self: Sized + Parser<T>,
{
ParseFromStr {
inner: self,
ty: PhantomData,
}
}
// }}}
// {{{ guard
/// Validate or fail with a message
///
/// If value doesn't satisfy the constraint - parser fails with the specified error message.
///
/// # Combinatoric usage
///
/// ```rust
/// # use bpaf::*;
/// fn number() -> impl Parser<u32> {
/// short('n')
/// .argument("NUM")
/// .from_str::<u32>()
/// .guard(|n| *n <= 10, "Values greater than 10 are only available in the DLC pack!")
/// }
/// ```
///
/// # Derive usage
/// Unlike combinator counterpart, derive variant of `guard` takes a function name instead
/// of a closure, mostly to keep thing clean. Second argument can be either a string literal
/// or a constant name for a static [`str`].
///
/// ```rust
/// # use bpaf::*;
/// fn dlc_check(number: &u32) -> bool {
/// *number <= 10
/// }
///
/// const DLC_NEEDED: &str = "Values greater than 10 are only available in the DLC pack!";
///
/// #[derive(Debug, Clone, Bpaf)]
/// struct Options {
/// #[bpaf(short, argument("NUM"), guard(dlc_check, DLC_NEEDED))]
/// number: u32,
/// }
/// ```
///
/// # Example
/// ```console
/// $ app -n 100
/// // fails with "Values greater than 10 are only available in the DLC pack!"
/// $ app -n 5
/// // 5
/// ```
#[must_use]
fn guard<F>(self, check: F, message: &'static str) -> ParseGuard<Self, F>
where
Self: Sized + Parser<T>,
F: Fn(&T) -> bool,
{
ParseGuard {
inner: self,
check,
message,
}
}
// }}}
// combine
// {{{ fallback
/// Use this value as default if value isn't present on a command line
///
/// Parser would still fail if value is present but failure comes from some transformation
///
/// # Combinatoric usage
/// ```rust
/// # use bpaf::*;
/// fn number() -> impl Parser<u32> {
/// short('n')
/// .argument("NUM")
/// .from_str::<u32>()
/// .fallback(42)
/// }
/// ```
///
/// # Derive usage
/// Expression in parens should have the right type, this example uses `u32` literal,
/// but it can also be your own type if that's what you are parsing, it can also be a function
/// call.
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// struct Options {
/// #[bpaf(short, argument("NUM"), from_str(u32), fallback(42))]
/// number: u32
/// }
/// ```
///
/// # Example
/// ```console
/// $ app -n 100
/// // 10
/// $ app
/// // 42
/// $ app -n pi
/// // fails with "Couldn't parse "pi": invalid numeric literal"
/// ```
///
/// # See also
/// [`fallback_with`](Parser::fallback_with) would allow to try to fallback to a value that
/// comes from a failing computation such as reading a file.
#[must_use]
fn fallback(self, value: T) -> ParseFallback<Self, T>
where
Self: Sized + Parser<T>,
{
ParseFallback { inner: self, value }
}
// }}}
// {{{ fallback_with
/// Use value produced by this function as default if value isn't present
///
/// Would still fail if value is present but failure comes from some earlier transformation
///
/// # Combinatoric usage
/// ```rust
/// # use bpaf::*;
/// fn username() -> impl Parser<String> {
/// long("user")
/// .argument("USER")
/// .fallback_with::<_, Box<dyn std::error::Error>>(||{
/// let output = std::process::Command::new("whoami")
/// .stdout(std::process::Stdio::piped())
/// .spawn()?
/// .wait_with_output()?
/// .stdout;
/// Ok(std::str::from_utf8(&output)?.to_owned())
/// })
/// }
/// ```
///
/// # Derive usage
/// ```rust
/// # use bpaf::*;
/// fn get_current_user() -> Result<String, Box<dyn std::error::Error>> {
/// let output = std::process::Command::new("whoami")
/// .stdout(std::process::Stdio::piped())
/// .spawn()?
/// .wait_with_output()?
/// .stdout;
/// Ok(std::str::from_utf8(&output)?.to_owned())
/// }
///
/// #[derive(Debug, Clone, Bpaf)]
/// struct Options {
/// #[bpaf(long, argument("USER"), fallback_with(get_current_user))]
/// user: String,
/// }
/// ```
///
/// # Example
/// ```console
/// $ app --user bobert
/// // "bobert"
/// $ app
/// // "pacak"
/// ```
///
/// # See also
/// [`fallback`](Parser::fallback) implements similar logic expect that failures
/// aren't expected.
#[must_use]
fn fallback_with<F, E>(self, fallback: F) -> ParseFallbackWith<T, Self, F, E>
where
Self: Sized + Parser<T>,
F: Fn() -> Result<T, E>,
E: ToString,
{
ParseFallbackWith {
inner: self,
inner_res: PhantomData,
fallback,
err: PhantomData,
}
}
// }}}
// {{{ or_else
/// If first parser fails - try the second one
///
/// For parser to succeed eiter of the components needs to succeed. If both succeed - `bpaf`
/// would use output from one that consumed the left most value. The second flag on the command
/// line remains unconsumed by `or_else`.
///
/// # Combinatoric usage:
/// There's two ways to write this combinator with identical results:
/// ```rust
/// # use bpaf::*;
/// fn a() -> impl Parser<u32> {
/// short('a').argument("NUM").from_str::<u32>()
/// }
///
/// fn b() -> impl Parser<u32> {
/// short('b').argument("NUM").from_str::<u32>()
/// }
///
/// fn a_or_b_comb() -> impl Parser<u32> {
/// construct!([a(), b()])
/// }
///
/// fn a_or_b_comb2() -> impl Parser<u32> {
/// a().or_else(b())
/// }
/// ```
///
/// # Example
/// ```console
/// $ app -a 12 -b 3
/// // 12
/// $ app -b 3 -a 12
/// // 3
/// $ app -b 13
/// // 13
/// $ app
/// // fails asking for either -a NUM or -b NUM
/// ```
///
/// # Derive usage:
///
/// `bpaf_derive` translates enum into alternative combinations, different shapes of variants
/// produce different results.
///
///
/// ```bpaf
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// enum Flag {
/// A { a: u32 }
/// B { b: u32 }
/// }
/// ```
///
/// ```console
/// $ app -a 12 -b 3
/// // Flag::A { a: 12 }
/// $ app -b 3 -a 12
/// // Flag::B { b: 3 }
/// $ app -b 3
/// // Flag::B { b: 3 }
/// $ app
/// // fails asking for either -a NUM or -b NUM
/// ```
///
/// # Performance
///
/// `bpaf` tries to evaluate both branches regardless of the successes to produce a
/// better error message for combinations of mutually exclusive parsers:
/// Suppose program accepts one of two mutually exclusive switches `-a` and `-b`
/// and both are present error message should point at the second flag
#[doc(hidden)]
#[deprecated(
since = "0.5.0",
note = "instead of a.or_else(b) you should use construct!([a, b])"
)]
fn or_else<P>(self, alt: P) -> ParseOrElse<Self, P>
where
Self: Sized + Parser<T>,
P: Sized + Parser<T>,
{
ParseOrElse {
this: self,
that: alt,
}
}
// }}}
// misc
// {{{ hide
/// Ignore this parser during any sort of help generation
///
/// Best used for optional parsers or parsers with a defined fallback, usually for implementing
/// backward compatibility or hidden aliases
///
/// # Combinatoric usage
///
/// ```rust
/// # use bpaf::*;
/// /// bpaf would accept both `-W` and `-H` flags, but the help message
/// /// would contain only `-H`
/// fn rectangle() -> impl Parser<(u32, u32)> {
/// let width = short('W')
/// .argument("PX")
/// .from_str::<u32>()
/// .fallback(10)
/// .hide();
/// let height = short('H')
/// .argument("PX")
/// .from_str::<u32>()
/// .fallback(10)
/// .hide();
/// construct!(width, height)
/// }
/// ```
/// # Example
/// ```console
/// $ app -W 12 -H 15
/// // (12, 15)
/// $ app -H 333
/// // (10, 333)
/// $ app --help
/// // contains -H but not -W
/// ```
///
/// # Derive usage
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// struct Rectangle {
/// #[bpaf(short('W'), argument("PX"), from_str(u32), fallback(10), hide)]
/// width: u32,
/// #[bpaf(short('H'), argument("PX"), from_str(u32))]
/// height: u32,
/// }
/// ```
///
/// # Example
/// ```console
/// $ app -W 12 -H 15
/// // Rectangle { width: 12, height: 15 }
/// $ app -H 333
/// // Rectangle { width: 10, height: 333 }
/// $ app --help
/// // contains -H but not -W
/// ```
fn hide(self) -> ParseHide<Self>
where
Self: Sized + Parser<T>,
{
ParseHide { inner: self }
}
// }}}
// {{{ group_help
/// Attach help message to a complex parser
///
/// `bpaf` inserts the group help message before the block with all the fields
/// from the inner parser and an empty line after the block.
///
/// # Combinatoric usage
/// ```rust
/// # use bpaf::*;
/// fn rectangle() -> impl Parser<(u32, u32)> {
/// let width = short('w')
/// .argument("PX")
/// .from_str::<u32>();
/// let height = short('h')
/// .argument("PX")
/// .from_str::<u32>();
/// construct!(width, height)
/// .group_help("Takes a rectangle")
/// }
/// ```
/// # Example
/// ```console
/// $ app --help
/// <skip>
/// Takes a rectangle
/// -w <PX> Width of the rectangle
/// -h <PX> Height of the rectangle
///
/// <skip>
/// ```
///
/// # Derive usage
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// struct Rectangle {
/// width: u32,
/// height: u32,
/// }
///
/// #[derive(Debug, Clone, Bpaf)]
/// struct Options {
/// #[bpaf(external, group_help("Takes a rectangle"))]
/// rectangle: Rectangle
/// }
/// ```
fn group_help(self, message: &'static str) -> ParseGroupHelp<Self>
where
Self: Sized + Parser<T>,
{
ParseGroupHelp {
inner: self,
message,
}
}
// }}}
// consume
// {{{ to_options
/// Transform `Parser` into [`OptionParser`] to attach metadata and run
///
/// # Combinatoric usage
/// ```rust
/// # use bpaf::*;
/// fn parser() -> impl Parser<u32> {
/// short('i')
/// .argument("ARG")
/// .from_str::<u32>()
/// }
///
/// fn option_parser() -> OptionParser<u32> {
/// parser()
/// .to_options()
/// .version("3.1415")
/// .descr("This is a description")
/// }
/// ```
///
/// See [`OptionParser`] for more methods available after conversion.
///
/// # Derive usage
/// Add a top level `options` annotation to generate [`OptionParser`] instead of default
/// [`Parser`].
///
/// In addition to `options` annotation you can also specify either `version` or
/// `version(value)` annotation. Former uses version from `cargo`, later uses the
/// specified value which should be an expression of type `&'static str`, see
/// [`version`](OptionParser::version).
///
/// ```rust
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// #[bpaf(options, version("3.1415"))]
/// /// This is a description
/// struct Options {
/// verbose: bool,
/// }
/// ```
///
/// # Example
/// ```console
/// $ app --version
/// // Version: 3.1415
/// $ app --help
/// <skip>
/// This is a description
/// <skip>
/// ```
fn to_options(self) -> OptionParser<T>
where
Self: Sized + Parser<T> + 'static,
{
OptionParser {
info: info::Info::default(),
inner_type: PhantomData,
inner: Box::new(self),
}
}
// }}}
}
/// Wrap a value into a `Parser`
///
/// This parser produces `T` without consuming anything from the command line, can be useful
/// with [`construct!`]. As with any parsers `T` should be `Clone` and `Debug`.
///
/// # Combinatoric usage
/// ```rust
/// # use bpaf::*;
/// fn pair() -> impl Parser<(bool, u32)> {
/// let a = long("flag-a").switch();
/// let b = pure(42u32);
/// construct!(a, b)
/// }
/// ```
#[must_use]
pub fn pure<T>(val: T) -> ParsePure<T> {
ParsePure(val)
}
/// Fail with a fixed error message
///
/// This parser produces `T` of any type but instead of producing it when asked - it fails
/// with a custom error message. Can be useful for creating custom logic
///
/// # Combinatoric usage
/// ```rust
/// # use bpaf::*;
/// fn must_agree() -> impl Parser<()> {
/// let a = long("accept").req_flag(());
/// let no_a = fail("You must accept the license agreement with --agree before proceeding");
/// construct!([a, no_a])
/// }
/// ```
///
/// # Example
/// ```console
/// $ app
/// // exits with "You must accept the license agreement with --agree before proceeding"
/// $ app --agree
/// // succeeds
/// ```
#[must_use]
pub fn fail<T>(msg: &'static str) -> ParseFail<T> {
ParseFail {
field1: msg,
field2: PhantomData,
}
}
/// Unsuccessful command line parsing outcome, use it for unit tests
///
/// Useful for unit testing for user parsers, consume it with
/// [`ParseFailure::unwrap_stdout`] and [`ParseFailure::unwrap_stdout`]
#[derive(Clone, Debug)]
pub enum ParseFailure {
/// Print this to stdout and exit with success code
Stdout(String),
/// Print this to stderr and exit with failure code
Stderr(String),
}
impl ParseFailure {
/// Returns the contained `stderr` values - for unit tests
///
/// # Panics
///
/// Panics if failure contains `stdout`
#[allow(clippy::must_use_candidate)]
pub fn unwrap_stderr(self) -> String {
match self {
Self::Stderr(err) => err,
Self::Stdout(_) => {
panic!("not an stderr: {:?}", self)
}
}
}
/// Returns the contained `stdout` values - for unit tests
///
/// # Panics
///
/// Panics if failure contains `stderr`
#[allow(clippy::must_use_candidate)]
pub fn unwrap_stdout(self) -> String {
match self {
Self::Stdout(err) => err,
Self::Stderr(_) => {
panic!("not an stdout: {:?}", self)
}
}
}
}
/// Strip a command name if present at the front when used as a `cargo` command
///
/// When implementing a cargo subcommand parser needs to be able to skip the first argument which
/// is always the same as the executable name without `cargo-` prefix. For example if executable name is
/// `cargo-cmd` so first argument would be `cmd`. `cargo_helper` helps to support both invocations:
/// with name present when used via cargo and without it when used locally.
///
/// # Combinatoric usage
/// ```rust
/// # use bpaf::*;
/// fn options() -> OptionParser<(u32, u32)> {
/// let width = short('w').argument("PX").from_str::<u32>();
/// let height = short('h').argument("PX").from_str::<u32>();
/// let parser = construct!(width, height);
/// cargo_helper("cmd", parser).to_options()
/// }
/// ```
///
/// # Derive usage
///
/// If you pass a cargo command name as a parameter to `options` annotation `bpaf_derive` would generate `cargo_helper`.
/// ```no_run
/// # use bpaf::*;
/// #[derive(Debug, Clone, Bpaf)]
/// #[bpaf(options("cmd"))]
/// struct Options {
/// #[bpaf(short, argument("PX"))]
/// width: u32,
/// #[bpaf(short, argument("PX"))]
/// height: u32,
/// }
///
/// fn main() {
/// println!("{:?}", options().run());
/// }
///
/// ```
///
/// # Example
///
/// ```console
/// $ cargo cmd -w 3 -h 5
/// (3, 5)
/// $ cargo run --bin cargo-cmd -- -w 3 -h 5
/// (3, 5)
/// ```
#[must_use]
pub fn cargo_helper<P, T>(cmd: &'static str, parser: P) -> impl Parser<T>
where
T: 'static,
P: Parser<T>,
{
let eat_command =
positional("").parse(move |s| if cmd == s { Ok(()) } else { Err(String::new()) });
let ignore_non_command = pure(());
let skip = construct!([eat_command, ignore_non_command]).hide();
construct!(skip, parser).map(|x| x.1)
}