pub fn positional<T>(metavar: &'static str) -> ParsePositional<T>Expand description
Parse a positional argument
For named flags and arguments ordering generally doesn’t matter: most programs would
understand -O2 -v the same way as -v -O2, but for positional items order matters: in *nix
cat hello world and cat world hello would display contents of the same two files but in
a different order.
When using combinatoric API you can specify the type with turbofish, for parsing types
that don’t implement FromStr you can use consume a String/OsString first and parse
it by hand.
fn parse_pos() -> impl Parser<usize> {
positional::<usize>("POS")
}§Important restriction
To parse positional arguments from a command line you should place parsers for all your
named values before parsers for positional items and commands. In derive API fields parsed as
positional items or commands should be at the end of your struct/enum. The same rule applies
to parsers with positional fields or commands inside: such parsers should go to the end as well.
Use check_invariants in your test to ensure correctness.
For example for non-positional non_pos and positional pos parsers
let valid = construct!(non_pos(), pos());
let invalid = construct!(pos(), non_pos());bpaf panics during help generation unless this restriction holds
Without using -- bpaf would only accept items that don’t start with - as positional, you
can use any to work around this restriction.
By default bpaf accepts positional items with or without -- where values permit, you can
further restrict the parser to accept positional items only on the right side of -- using
strict.
Combinatoric example
#[derive(Debug, Clone)]
pub struct Options {
verbose: bool,
crate_name: String,
feature_name: Option<String>,
}
pub fn options() -> OptionParser<Options> {
let verbose = short('v')
.long("verbose")
.help("Display detailed information")
.switch();
let crate_name = positional("CRATE").help("Crate name to use");
let feature_name = positional("FEATURE")
.help("Display information about this feature")
.optional();
construct!(Options {
verbose,
// You must place positional items and commands after
// all other parsers
crate_name,
feature_name
})
.to_options()
}
fn main() {
println!("{:?}", options().run())
}Derive example
#[derive(Debug, Clone, Bpaf)]
#[bpaf(options)]
pub struct Options {
/// Display detailed information
#[bpaf(short, long)]
verbose: bool,
// You must place positional items and commands after
// all other parsers
#[bpaf(positional("CRATE"))]
/// Crate name to use
crate_name: String,
#[bpaf(positional("FEATURE"))]
/// Display information about this feature
feature_name: Option<String>,
}
fn main() {
println!("{:?}", options().run())
}Output
Positional items show up in a separate group of arguments if they contain a help message, otherwise they will show up only in Usage part.
Usage: app [-v] CRATE [FEATURE]
- CRATE
- Crate name to use
- FEATURE
- Display information about this feature
- -v, --verbose
- Display detailed information
- -h, --help
- Prints help information
You can mix positional items with regular items
Options { verbose: true, crate_name: "bpaf", feature_name: None }
And since bpaf API expects to have non positional items consumed before positional ones - you
can use them in a different order. In this example bpaf corresponds to a crate_name field and
--verbose – to verbose.
Options { verbose: true, crate_name: "bpaf", feature_name: None }
In previous examples optional field feature was missing, this one contains it.
Options { verbose: false, crate_name: "bpaf", feature_name: Some("autocomplete") }
Users can use -- to tell bpaf to treat remaining items as positionals - this might be
required to handle unusual items.
Options { verbose: false, crate_name: "bpaf", feature_name: Some("--verbose") }
Options { verbose: false, crate_name: "bpaf", feature_name: Some("--verbose") }
Without using -- bpaf would only accept items that don’t start with - as positional.
Error: expected CRATE, got --detailed. Pass --help for usage information
Error: expected CRATE, pass --help for usage information
You can use any to work around this restriction.
Examples found in repository?
More examples
31fn user() -> impl Parser<Option<String>> {
32 // match only literal "-user"
33 let tag = literal("-user").anywhere();
34 let value = positional("USER").help("User name");
35 construct!(tag, value)
36 .adjacent()
37 .map(|pair| pair.1)
38 .optional()
39}
40
41// parsers -exec xxx yyy zzz ;
42fn exec() -> impl Parser<Option<Vec<OsString>>> {
43 let tag = literal("-exec")
44 .help("for every file find finds execute a separate shell command")
45 .anywhere();
46
47 let item = any::<OsString, _, _>("ITEM", |s| (s != ";").then_some(s))
48 .help("command with its arguments, find will replace {} with a file name")
49 .many();
50
51 let endtag = any::<String, _, _>(";", |s| (s == ";").then_some(()))
52 .help("anything after literal \";\" will be considered a regular option again");
53
54 construct!(tag, item, endtag)
55 .adjacent()
56 .map(|triple| triple.1)
57 .optional()
58}
59
60/// parses symbolic permissions `-perm -mode`, `-perm /mode` and `-perm mode`
61fn perm() -> impl Parser<Option<Perm>> {
62 fn parse_mode(input: &str) -> Result<Perms, String> {
63 let mut perms = Perms::default();
64 for c in input.chars() {
65 match c {
66 'r' => perms.read = true,
67 'w' => perms.write = true,
68 'x' => perms.exec = true,
69 _ => return Err(format!("{} is not a valid permission string", input)),
70 }
71 }
72 Ok(perms)
73 }
74
75 let tag = literal("-mode").anywhere();
76
77 // `any` here is used to parse an arbitrary string that can also start with dash (-)
78 // regular positional parser won't work here
79 let mode = any("MODE", Some)
80 .help("(perm | -perm | /perm), where perm is any subset of rwx characters, ex +rw")
81 .parse::<_, _, String>(|s: String| {
82 if let Some(m) = s.strip_prefix('-') {
83 Ok(Perm::All(parse_mode(m)?))
84 } else if let Some(m) = s.strip_prefix('/') {
85 Ok(Perm::Any(parse_mode(m)?))
86 } else {
87 Ok(Perm::Exact(parse_mode(&s)?))
88 }
89 });
90
91 construct!(tag, mode)
92 .adjacent()
93 .map(|pair| pair.1)
94 .optional()
95}
96
97pub fn options() -> OptionParser<Options> {
98 let paths = positional::<PathBuf>("PATH").many();
99
100 construct!(Options {
101 exec(),
102 user(),
103 perm(),
104 paths,
105 })
106 .to_options()
107}28fn extension() -> impl Parser<(String, bool)> {
29 let state = any("(+|-)ext", |s: String| match s.as_str() {
30 "-ext" => Some(false),
31 "+ext" => Some(true),
32 _ => None,
33 })
34 .anywhere();
35
36 let name = positional::<String>("EXT")
37 .help("Extension to enable or disable, see documentation for the full list");
38 construct!(state, name).adjacent().map(|(a, b)| (b, a))
39}