Skip to main content

FwdPolicy

Struct FwdPolicy 

Source
pub struct FwdPolicy<S, Chk> { /* private fields */ }
Expand description

FwdPolicy matching the command line arguments with Opt in the Set. The option would match failed if any special Error raised during option processing. FwdPolicy will return Some(Return) if match successful. FwdPolicy process the option before any NOA(Cmd, Pos and Main). During parsing, you can get the value of any option in the handler of NOA.

§Examples

let mut policy = AFwdPolicy::default();
let mut set = AHCSet::default();
let mut inv = AInvoker::default();
let filter_id = set.add_opt("--/filter=b")?.run()?;
let pos_id = set.add_opt("pos=p@*")?
                .set_pos_type::<String>()
                .set_values(vec![])
                .run()?;

inv.entry(pos_id).on(
    move |set, ctx| {
        let filter = set.app_data::<Vec<&str>>()?;
        let value = ctx.value::<String>()?;
        let not_filter = set[filter_id].val::<bool>()?;
        let valid = if !*not_filter {
            !filter.iter().any(|&v| v == value.as_str())
        } else {
            true
        };

        Ok(valid.then(|| value))
    },
);

let args = Args::from(["app", "set", "42", "foo", "bar"]);

for opt in set.iter_mut() {
    opt.init()?;
}
set.set_app_data(vec!["foo", "bar"]);
policy.parse(&mut set, &mut inv, args)?;

let values = set[pos_id].vals::<String>()?;

assert_eq!(values[0], "set");
assert_eq!(values[1], "42");

let args = Args::from(["app", "--/filter", "set", "42", "foo", "bar"]);

for opt in set.iter_mut() {
    opt.init()?;
}

policy.parse(&mut set, &mut inv, args)?;
let values = set[pos_id].vals::<String>()?;

assert_eq!(values[0], "set");
assert_eq!(values[1], "42");
assert_eq!(values[2], "foo");
assert_eq!(values[3], "bar");

When prepolicy is enabled, FwdPolicy will skip any special Error during parse process.

§Example

let mut parser = AFwdParser::default();
let mut cfg_loader = AFwdParser::default();

cfg_loader.set_prepolicy(true);
parser
    .add_opt("-check=s")?
    .on(|set, ctx| {
        let ext = ctx.value::<String>()?;
        let mut found = false;

        for name in ["-c", "-cxx"] {
            if let Ok(opt) = set.find(name) {
                if let Ok(file) = opt.vals::<String>() {
                    if file.contains(&ext) {
                        found = true;
                    }
                }
            }
        }
        Ok(Some(found))
    })?;
cfg_loader.set_app_data(parser);
cfg_loader.add_opt("--load=s")?.on(
    |set, ctx| {
        let cfg = ctx.value::<String>()?;
        let parser = set.app_data_mut::<AFwdParser>()?;

        match cfg.as_str() {
            "cxx" => {
                parser.add_opt("-cxx".infer::<String>())?.set_values(
                    ["cxx", "cpp", "c++", "cc", "hpp", "hxx", "h"]
                        .map(|v| v.to_owned())
                        .to_vec(),
                );
            }
            "c" => {
                parser
                    .add_opt("-c=s")?
                    .set_values_t(["c", "h"].map(|v| v.to_owned()).to_vec());
            }
            _ => {
                panic!("Unknow configuration name")
            }
        }

        Ok(Some(cfg))
    },
)?;

let ret = getopt!(
    Args::from(["--load", "cxx", "-check", "cc"]),
    &mut cfg_loader
)?;
let next_args = ret.ret.clone_args();
let mut parser = cfg_loader.take_app_data::<AFwdParser>()?;

getopt!(Args::from(next_args), &mut parser)?;

assert!(*parser.find_val::<bool>("-check")?);

// pass the parser to AppService
cfg_loader.set_app_data(parser);

let ret = getopt!(
    Args::from(["--load", "c", "-check", "c"]),
    &mut cfg_loader
)?;
let next_args = ret.ret.clone_args();
let mut parser = cfg_loader.service_mut().take_app_data::<AFwdParser>()?;

getopt!(Args::from(next_args), &mut parser)?;

assert!(*parser.find_val::<bool>("-check")?);

Implementations§

Source§

impl<S, Chk> FwdPolicy<S, Chk>
where Chk: Default,

Source

pub fn new(strict: bool, style: OptStyleManager) -> Self

Source§

impl<S, Chk> FwdPolicy<S, Chk>

Source

pub fn with_strict(self, strict: bool) -> Self

In strict mode, if an argument looks like an option (it matched any option prefix), then it must matched.

Source

pub fn with_styles(self, styles: Vec<UserStyle>) -> Self

Source

pub fn with_checker(self, checker: Chk) -> Self

Source

pub fn with_overload(self, overload: bool) -> Self

Source

pub fn with_prepolicy(self, prepolicy: bool) -> Self

Source

pub fn set_checker(&mut self, checker: Chk) -> &mut Self

Source

pub fn checker(&self) -> &Chk

Source

pub fn checker_mut(&mut self) -> &mut Chk

Trait Implementations§

Source§

impl<S, Chk> Clone for FwdPolicy<S, Chk>
where Chk: Clone,

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl<S, Chk> Debug for FwdPolicy<S, Chk>
where Chk: Debug,

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result

Formats the value using the given formatter. Read more
Source§

impl<S, Chk> Default for FwdPolicy<S, Chk>
where Chk: Default,

Source§

fn default() -> Self

Returns the “default value” for a type. Read more
Source§

impl<S, Chk> Policy for FwdPolicy<S, Chk>
where SetOpt<S>: Opt, Chk: SetChecker<S>, S: Set + OptParser + OptValidator,

Source§

type Ret = Return

Source§

type Set = S

Source§

type Inv<'a> = Invoker<'a, S>

Source§

type Error = Error

Source§

fn parse( &mut self, set: &mut Self::Set, inv: &mut Self::Inv<'_>, orig: Args, ) -> Result<Self::Ret, Self::Error>

Source§

impl<Set, Chk> PolicySettings for FwdPolicy<Set, Chk>

Source§

fn style_manager(&self) -> &OptStyleManager

Source§

fn style_manager_mut(&mut self) -> &mut OptStyleManager

Source§

fn strict(&self) -> bool

Source§

fn styles(&self) -> &[UserStyle]

Source§

fn no_delay(&self) -> Option<&[String]>

Source§

fn overload(&self) -> bool

Source§

fn prepolicy(&self) -> bool

Source§

fn set_strict(&mut self, strict: bool) -> &mut Self

Source§

fn set_styles(&mut self, styles: Vec<UserStyle>) -> &mut Self

Source§

fn set_no_delay(&mut self, _: impl Into<String>) -> &mut Self

Source§

fn set_overload(&mut self, overload: bool) -> &mut Self

Source§

fn set_prepolicy(&mut self, prepolicy: bool) -> &mut Self

Auto Trait Implementations§

§

impl<S, Chk> Freeze for FwdPolicy<S, Chk>
where Chk: Freeze,

§

impl<S, Chk> RefUnwindSafe for FwdPolicy<S, Chk>

§

impl<S, Chk> Send for FwdPolicy<S, Chk>
where Chk: Send, S: Send,

§

impl<S, Chk> Sync for FwdPolicy<S, Chk>
where Chk: Sync, S: Sync,

§

impl<S, Chk> Unpin for FwdPolicy<S, Chk>
where Chk: Unpin, S: Unpin,

§

impl<S, Chk> UnsafeUnpin for FwdPolicy<S, Chk>
where Chk: UnsafeUnpin,

§

impl<S, Chk> UnwindSafe for FwdPolicy<S, Chk>
where Chk: UnwindSafe, S: UnwindSafe,

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<ST, DT> CastableFrom<ST, Initialized, Initialized> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<ST, DT> CastableFrom<ST, Uninit, Uninit> for DT
where ST: ?Sized, DT: ?Sized,

Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<'a, C, T> DynamicCtorThenBuilderHelper<'a, C> for T
where C: Match<'a>,

Source§

fn into_ctor_then_builder<F, O1, R>( self, func: F, ) -> DynamicCtorThenBuilder<C, T, F>
where F: Fn(&mut C, &O1) -> Result<R, Error>,

Source§

impl<T> ErasedTy for T
where T: Any + Debug + Sync + Send + 'static,

Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T> Instrument for T

Source§

fn instrument(self, span: Span) -> Instrumented<Self>

Instruments this type with the provided Span, returning an Instrumented wrapper. Read more
Source§

fn in_current_span(self) -> Instrumented<Self>

Instruments this type with the current Span, returning an Instrumented wrapper. Read more
Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> MayDebug for T

Source§

impl<T> Read<Exclusive, BecauseExclusive> for T
where T: ?Sized,

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.
Source§

impl<T> WithSubscriber for T

Source§

fn with_subscriber<S>(self, subscriber: S) -> WithDispatch<Self>
where S: Into<Dispatch>,

Attaches the provided Subscriber to this type, returning a WithDispatch wrapper. Read more
Source§

fn with_current_subscriber(self) -> WithDispatch<Self>

Attaches the current default Subscriber to this type, returning a WithDispatch wrapper. Read more