Optional value of argument #383
Answered
by
pacak
UltraMachine
asked this question in
Q&A
-
How do I make something like this in bpaf? #[derive(Debug, Clone, Bpaf)]
#[bpaf(options)]
struct Options {
// If not present, value is None
// If only --foo is present, value is Some(None)
// If --foo=value is present, value is Some(Some("value"))
foo: Option<Option<String>>,
// Same as above, but instead of Some(None), it fallbacks to some default value
bar: Option<String>,
} |
Beta Was this translation helpful? Give feedback.
Answered by
pacak
Aug 2, 2024
Replies: 1 comment 4 replies
-
This is best expressed with combinatoric API, let's start with // first we handle two cases where command line option is present but use
// a single `Option` layer. This parser is expected to fail if value is missing
// If only --foo is present, value is Some(None)
let foo_flag = long("foo").req_flag(None);
// If --foo=value is present, value is Some(Some("value"))
let foo_arg = long("foo").argument::<String>("FOO").map(Some);
// now we combine it into a single parser that handles both `--foo` and `--foo=value`
let foo = construct!([foo_arg, foo_flag]) // order inside is important.
// and finally allow parser to fail and produce None if it does:
let foo = foo.optional(); To use this construction inside derive macro you place it in a function first: fn foo() -> impl Parser<Option<Option<String>> {
let foo_flag = ...
...
foo.optional()
} And you can use it in your derived parser with #[derive(Debug, Clone, Bpaf)]
#[bpaf(options)]
struct Options {
#[bpaf(external)]
foo: Option<Option<String>>
...
} For |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Same idea, splitting it into primitive parsers.
None
when not present andSome
otherwise means.optional()
goes at the end, and inner parsers produce value withoutOption
, so--bar
should make"default"
and--bar=value
should make"value"
. You achieve former withreq_flag
and later withargument
.