pub struct Parser<S, P: Policy<Set = S>> {
pub policy: P,
pub optset: S,
}Expand description
Parser manage the components are using in parse of Policy.
§Example
let mut parser1 = Parser::new_policy(AFwdPolicy::default());
parser1.add_opt("Where=c")?;
parser1.add_opt("question=m")?.on(question)?;
let mut parser2 = Parser::new_policy(AFwdPolicy::default());
parser2.add_opt("Who=c")?;
parser2.add_opt("question=m")?.on(question)?;
fn question(_: &mut AHCSet, ctx: &mut Ctx) -> Result<Option<()>, Error> {
let args = ctx.args();
// Output: The question is: Where are you from ?
println!(
"The question is: {}",
args.iter().skip(1)
.map(|v| v.to_str().unwrap().to_owned())
.collect::<Vec<String>>()
.join(" ")
);
Ok(Some(()))
}
let ret = getopt!(
Args::from(["app", "Where", "are", "you", "from", "?"]),
&mut parser1,
&mut parser2
)?;
let parser = ret.parser;
assert_eq!(
parser[0].name(),
"Where",
"Parser with `Where` cmd matched"
);Using it with macro getopt,
which can process multiple Parser with same type Policy.
Fields§
§policy: P§optset: SImplementations§
Source§impl<S, P: Policy<Set = S>> Parser<S, P>
impl<S, P: Policy<Set = S>> Parser<S, P>
pub fn new(policy: P, optset: S) -> Self
pub fn policy(&self) -> &P
pub fn policy_mut(&mut self) -> &mut P
pub fn set_policy(&mut self, policy: P) -> &mut Self
pub fn optset(&self) -> &S
pub fn optset_mut(&mut self) -> &mut S
pub fn set_optset(&mut self, optset: S) -> &mut Self
Source§impl<'a, S, P> Parser<HCOptSet<'a, S>, P>
impl<'a, S, P> Parser<HCOptSet<'a, S>, P>
Sourcepub fn parse(&mut self, args: Args) -> Result<<P as Policy>::Ret, Error>
pub fn parse(&mut self, args: Args) -> Result<<P as Policy>::Ret, Error>
Examples found in repository?
examples/02_option_value.rs (lines 12-14)
3pub fn main() -> Result<(), aopt::Error> {
4 let mut parser = AFwdParser::default();
5
6 // add option need argument with type `i`, i.e. i64
7 parser.add_opt("-f=i")?;
8 parser.add_opt("--flag=s")?;
9 parser.add_opt("-flag".infer::<f32>())?;
10
11 parser
12 .parse(Args::from(
13 ["app", "-f42", "--flag", "foo", "-flag=2.1"].into_iter(),
14 ))?
15 .ok()?;
16
17 assert_eq!(parser.find_val::<i64>("-f")?, &42);
18 assert_eq!(parser.find_val::<String>("--flag")?, "foo");
19 assert_eq!(parser.find_val::<f32>("-flag")?, &2.1);
20
21 Ok(())
22}More examples
examples/06_callback.rs (line 16)
3pub fn main() -> Result<(), aopt::Error> {
4 let mut parser = AFwdParser::default();
5
6 parser.add_opt("-flag".infer::<i32>())?.on(|_, _| {
7 println!("ignore the value set from command line");
8 Ok(Some(42))
9 })?;
10 parser
11 .add_opt("--/flag".infer::<bool>())?
12 .set_value(true)
13 .on(|_, ctx| Ok(Some(!ctx.value::<bool>()?)))?;
14
15 parser
16 .parse(Args::from(["app", "-flag=foo", "--/flag"].into_iter()))?
17 .ok()?;
18
19 assert_eq!(parser.find_val::<i32>("-flag")?, &42);
20 assert_eq!(parser.find_val::<bool>("--/flag")?, &false);
21
22 Ok(())
23}examples/07_callback.rs (line 20)
11pub fn main() -> Result<(), aopt::Error> {
12 let mut parser = AFwdParser::default();
13
14 parser.add_opt("-flag;--flag=b")?.on(changed("--/flag"))?;
15 parser
16 .add_opt("-/flag;--/flag=b")?
17 .set_value_t(true)
18 .on(changed("--flag"))?;
19 parser
20 .parse(Args::from(["app", "-flag"].into_iter()))?
21 .ok()?;
22
23 assert_eq!(parser.find_val::<bool>("-flag")?, &true);
24 assert_eq!(parser.find_val::<bool>("--/flag")?, &false);
25
26 parser
27 .parse(Args::from(["app", "--/flag"].into_iter()))?
28 .ok()?;
29
30 assert_eq!(parser.find_val::<bool>("-flag")?, &false);
31 assert_eq!(parser.find_val::<bool>("--/flag")?, &true);
32
33 Ok(())
34}examples/05_overload.rs (lines 13-15)
3pub fn main() -> Result<(), aopt::Error> {
4 let mut parser = AFwdParser::default();
5
6 parser.add_opt("-flag".infer::<i32>())?;
7 parser.add_opt("-flag".infer::<String>())?;
8 parser.add_opt("-flag".infer::<bool>())?;
9
10 // enable combination style
11 parser.set_overload(true);
12 parser
13 .parse(Args::from(
14 ["app", "-flag=foo", "-flag=42", "-flag"].into_iter(),
15 ))?
16 .ok()?;
17
18 assert_eq!(parser.find("-flag".infer::<i32>())?.val::<i32>()?, &42);
19 assert_eq!(
20 parser.find("-flag".infer::<String>())?.val::<String>()?,
21 "foo"
22 );
23 assert_eq!(parser.find("-flag".infer::<bool>())?.val::<bool>()?, &true);
24
25 Ok(())
26}examples/04_positional.rs (lines 18-20)
3pub fn main() -> Result<(), aopt::Error> {
4 let mut parser = AFwdParser::default();
5
6 parser.add_opt("--flag=b")?;
7 parser.add_opt("--foo=s")?;
8 // In default, positional has bool value
9 parser.add_opt("first=p@1")?;
10 // A special positional argument match the name, and force required
11 parser.add_opt("list=c")?;
12 // Add a positional argument has String value
13 parser.add_opt("second@2".infer::<Pos<String>>())?;
14
15 // enable combination style
16 parser.enable_combined();
17 parser
18 .parse(Args::from(
19 ["app", "list", "--foo", "value", "bar"].into_iter(),
20 ))?
21 .ok()?;
22
23 assert_eq!(parser.find_val::<bool>("list")?, &true);
24 assert_eq!(parser.find_val::<bool>("first")?, &true);
25 assert_eq!(parser.find_val::<String>("second")?, "bar");
26
27 Ok(())
28}examples/01_prefix_option.rs (line 10)
3pub fn main() -> Result<(), aopt::Error> {
4 let mut parser = AFwdParser::default();
5
6 // add option with value type `b`, i.e. option with bool value or flag
7 parser.add_opt("-f=b")?;
8 parser.add_opt("--flag".infer::<bool>())?;
9
10 parser.parse(Args::from(["app", "-f"].into_iter()))?.ok()?;
11
12 // option with bool type has default value `false`
13 assert_eq!(parser.find_val::<bool>("-f")?, &true);
14 assert_eq!(parser.find_val::<bool>("--flag")?, &false);
15
16 parser.add_opt("-flag=b!")?;
17 parser.add_opt("--/flag=b")?;
18
19 parser
20 .parse(Args::from(["app", "-flag", "--/flag"].into_iter()))?
21 .ok()?;
22
23 // option with bool type has default value `false`
24 assert_eq!(parser.find_val::<bool>("-flag")?, &true);
25 assert_eq!(parser.find_val::<bool>("--/flag")?, &true);
26
27 Ok(())
28}Additional examples can be found in:
Source§impl<S, P> Parser<S, P>where
P: Policy<Set = S> + PolicySettings,
impl<S, P> Parser<S, P>where
P: Policy<Set = S> + PolicySettings,
Sourcepub fn enable_combined(&mut self) -> &mut Self
pub fn enable_combined(&mut self) -> &mut Self
Enable CombinedOption option set style.
This can support option style like -abc which set -a, -b and -c both.
Examples found in repository?
examples/04_positional.rs (line 16)
3pub fn main() -> Result<(), aopt::Error> {
4 let mut parser = AFwdParser::default();
5
6 parser.add_opt("--flag=b")?;
7 parser.add_opt("--foo=s")?;
8 // In default, positional has bool value
9 parser.add_opt("first=p@1")?;
10 // A special positional argument match the name, and force required
11 parser.add_opt("list=c")?;
12 // Add a positional argument has String value
13 parser.add_opt("second@2".infer::<Pos<String>>())?;
14
15 // enable combination style
16 parser.enable_combined();
17 parser
18 .parse(Args::from(
19 ["app", "list", "--foo", "value", "bar"].into_iter(),
20 ))?
21 .ok()?;
22
23 assert_eq!(parser.find_val::<bool>("list")?, &true);
24 assert_eq!(parser.find_val::<bool>("first")?, &true);
25 assert_eq!(parser.find_val::<String>("second")?, "bar");
26
27 Ok(())
28}More examples
examples/03_combination_style.rs (line 15)
3pub fn main() -> Result<(), aopt::Error> {
4 let mut parser = AFwdParser::default();
5
6 // combination style only support bool type
7 parser.add_opt("-a=b")?;
8 parser.add_opt("-b=b")?;
9 parser.add_opt("-c".infer::<bool>())?;
10 parser.add_opt("d=b")?;
11 parser.add_opt("e=b")?;
12 parser.add_opt("f".infer::<bool>())?;
13
14 // enable combination style
15 parser.enable_combined();
16 parser
17 .parse(Args::from(["app", "-abc", "def"].into_iter()))?
18 .ok()?;
19
20 assert_eq!(parser.find_val::<bool>("-a")?, &true);
21 assert_eq!(parser.find_val::<bool>("-b")?, &true);
22 assert_eq!(parser.find_val::<bool>("-c")?, &true);
23 assert_eq!(parser.find_val::<bool>("d")?, &false);
24 assert_eq!(parser.find_val::<bool>("e")?, &false);
25 assert_eq!(parser.find_val::<bool>("f")?, &false);
26
27 // for support non-prefix option, need add prefix `""`,
28 // and disable the strict flag of policy
29 parser.validator_mut().add_prefix("");
30 parser.set_strict(false);
31 parser
32 .parse(Args::from(["app", "-abc", "def"].into_iter()))?
33 .ok()?;
34
35 assert_eq!(parser.find_val::<bool>("-a")?, &true);
36 assert_eq!(parser.find_val::<bool>("-b")?, &true);
37 assert_eq!(parser.find_val::<bool>("-c")?, &true);
38 assert_eq!(parser.find_val::<bool>("d")?, &true);
39 assert_eq!(parser.find_val::<bool>("e")?, &true);
40 assert_eq!(parser.find_val::<bool>("f")?, &true);
41
42 Ok(())
43}Sourcepub fn enable_embedded_plus(&mut self) -> &mut Self
pub fn enable_embedded_plus(&mut self) -> &mut Self
Enable EmbeddedValuePlus option set style.
This can support option style like --opt42 which set --opt value to 42.
In default the EmbeddedValue style only support
one letter option such as -i.
Sourcepub fn enable_flag(&mut self) -> &mut Self
pub fn enable_flag(&mut self) -> &mut Self
Enable Flag option set style.
It will support set style like --flag, but the value will be set to None.
Trait Implementations§
Source§impl<S, P> OptValidator for Parser<S, P>where
S: OptValidator,
P: Policy<Set = S>,
impl<S, P> OptValidator for Parser<S, P>where
S: OptValidator,
P: Policy<Set = S>,
Source§impl<S, P: Policy<Set = S>> PolicyParser<P> for Parser<S, P>
impl<S, P: Policy<Set = S>> PolicyParser<P> for Parser<S, P>
type Error = Error
fn parse(&mut self, args: Args) -> Result<<P as Policy>::Ret, Self::Error>where
P: Default,
fn parse_policy( &mut self, args: Args, policy: &mut P, ) -> Result<<P as Policy>::Ret, Self::Error>
fn parse_env(&mut self) -> Result<P::Ret, Self::Error>where
P: Default,
fn parse_env_policy(&mut self, policy: &mut P) -> Result<P::Ret, Self::Error>
Source§impl<S, P> PolicySettings for Parser<S, P>where
P: Policy<Set = S> + PolicySettings,
impl<S, P> PolicySettings for Parser<S, P>where
P: Policy<Set = S> + PolicySettings,
fn style_manager(&self) -> &OptStyleManager
fn style_manager_mut(&mut self) -> &mut OptStyleManager
fn strict(&self) -> bool
fn styles(&self) -> &[UserStyle]
fn no_delay(&self) -> Option<&[String]>
fn overload(&self) -> bool
fn prepolicy(&self) -> bool
fn set_strict(&mut self, strict: bool) -> &mut Self
fn set_styles(&mut self, styles: Vec<UserStyle>) -> &mut Self
fn set_no_delay(&mut self, name: impl Into<String>) -> &mut Self
fn set_overload(&mut self, overload: bool) -> &mut Self
fn set_prepolicy(&mut self, ignore_failure: bool) -> &mut Self
Source§impl<S, P> PrefixedValidator for Parser<S, P>where
S: PrefixedValidator,
P: Policy<Set = S>,
impl<S, P> PrefixedValidator for Parser<S, P>where
S: PrefixedValidator,
P: Policy<Set = S>,
Auto Trait Implementations§
impl<S, P> Freeze for Parser<S, P>
impl<S, P> RefUnwindSafe for Parser<S, P>where
P: RefUnwindSafe,
S: RefUnwindSafe,
impl<S, P> Send for Parser<S, P>
impl<S, P> Sync for Parser<S, P>
impl<S, P> Unpin for Parser<S, P>
impl<S, P> UnwindSafe for Parser<S, P>where
P: UnwindSafe,
S: UnwindSafe,
Blanket Implementations§
Source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
Source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more
Source§impl<T> ConstructIntoOp for T
impl<T> ConstructIntoOp for T
Source§fn into_box(self) -> WrappedTy<BoxedCtor<T>>
fn into_box(self) -> WrappedTy<BoxedCtor<T>>
Return a type that wraps Ctor with Box.
§Example
let re = b'+'
.or(b'-')
.then(u8::is_ascii_hexdigit)
.then(u8::is_ascii_hexdigit.repeat_times::<3>())
.pat()
.map(|v: &[u8]| String::from_utf8(v.to_vec()).map_err(|_| Error::Uid(0)))
.into_box();
assert_eq!(BytesCtx::new(b"+AE00").ctor(&re)?, "+AE00");
assert!(BytesCtx::new(b"-GH66").ctor(&re).is_err());
assert_eq!(BytesCtx::new(b"-83FD").ctor(&re)?, "-83FD");
Ok(())Source§fn into_rc(self) -> WrappedTy<Rc<T>>
fn into_rc(self) -> WrappedTy<Rc<T>>
Return a type that wrap Ctor with Rc.
§Example
color_eyre::install()?;
let year = char::is_ascii_digit.repeat_times::<4>();
let num = char::is_ascii_digit.repeat_times::<2>();
let date = year.sep_once("-", num.sep_once("-", num)).into_rc();
let time = num.sep_once(":", num.sep_once(":", num));
let datetime = date.clone().sep_once(" ", time);
assert_eq!(
CharsCtx::new("2024-01-08").ctor(&date)?,
("2024", ("01", "08"))
);
assert_eq!(
CharsCtx::new("2024-01-08 10:01:13").ctor(&datetime)?,
(("2024", ("01", "08")), ("10", ("01", "13")))
);
Ok(())Source§fn into_dyn<'a, 'b, C, M, O, H, A>(
self,
) -> WrappedTy<DynamicBoxedCtor<'a, 'b, C, M, O, H, A>>
fn into_dyn<'a, 'b, C, M, O, H, A>( self, ) -> WrappedTy<DynamicBoxedCtor<'a, 'b, C, M, O, H, A>>
§Example 2
color_eyre::install()?;
let num = u8::is_ascii_digit
.repeat_one()
.map(|v: &[u8]| String::from_utf8(v.to_vec()).map_err(|_| Error::Uid(0)))
.map(map::from_str::<usize>());
let num = num.clone().sep_once(b",", num);
let re = num.into_dyn();
assert_eq!(BytesCtx::new(b"3,0").ctor(&re)?, (3, 0));
assert_eq!(BytesCtx::new(b"2,1").ctor(&re)?, (2, 1));
assert_eq!(BytesCtx::new(b"0,3").ctor(&re)?, (0, 3));
Ok(())fn into_arc(self) -> WrappedTy<Arc<T>>
fn into_cell(self) -> WrappedTy<Cell<T>>
fn into_refcell(self) -> WrappedTy<RefCell<T>>
fn into_mutex(self) -> WrappedTy<Mutex<T>>
fn into_dyn_sync<'a, 'b, C, M, O, H, A>( self, ) -> WrappedTy<DynamicBoxedCtorSync<'a, 'b, C, M, O, H, A>>
fn into_dyn_arc<'a, 'b, C, M, O, H, A>( self, ) -> WrappedTy<DynamicArcCtor<'a, 'b, C, M, O, H, A>>
fn into_dyn_rc<'a, 'b, C, M, O, H, A>( self, ) -> WrappedTy<DynamicRcCtor<'a, 'b, C, M, O, H, A>>
Source§impl<'a, C, T> DynamicCreateCtorThenHelper<'a, C> for T
impl<'a, C, T> DynamicCreateCtorThenHelper<'a, C> for T
Source§fn dyn_then_ctor<F>(self, func: F) -> DynamicCreateCtorThen<C, T, F>
fn dyn_then_ctor<F>(self, func: F) -> DynamicCreateCtorThen<C, T, F>
Construct a new regex with Ctor implementation based on previous result.
§Example
let num = u8::is_ascii_digit
.repeat_one()
.map(|v: &[u8]| String::from_utf8(v.to_vec()).map_err(|_| Error::Uid(0)))
.map(map::from_str::<usize>());
let num = num.clone().sep_once(b",", num);
let re = num.dyn_then_ctor(|a: &(usize, usize)| {
// leave the a's type empty cause rustc reject compile
Ok(b'+'
.repeat_range(a.0..a.0 + 1)
.then(b'-'.repeat_range(a.1..a.1 + 1)))
});
assert_eq!(
BytesCtx::new(b"3,0+++").ctor(&re)?,
((3, 0), ([43, 43, 43].as_slice(), [].as_slice()))
);
assert_eq!(
BytesCtx::new(b"2,1++-").ctor(&re)?,
((2, 1), ([43, 43].as_slice(), [45].as_slice()))
);
assert_eq!(
BytesCtx::new(b"0,3---").ctor(&re)?,
((0, 3), ([].as_slice(), [45, 45, 45].as_slice()))
);
Ok(())