Skip to main content

aopt/opt/
mod.rs

1pub(crate) mod aopt;
2pub(crate) mod config;
3pub(crate) mod creator;
4pub(crate) mod help;
5pub(crate) mod info;
6pub(crate) mod parser;
7#[cfg(feature = "serde")]
8pub(crate) mod serialize;
9pub(crate) mod value;
10
11pub use self::aopt::AOpt;
12pub use self::config::ConfigBuild;
13pub use self::config::ConfigBuildInfer;
14pub use self::config::ConfigBuildMutable;
15pub use self::config::ConfigBuildWith;
16pub use self::config::ConfigBuilder;
17pub use self::config::ConfigBuilderWith;
18pub use self::config::ConfigValue;
19pub use self::config::OptConfig;
20pub use self::creator::Cid;
21pub use self::creator::Creator;
22pub use self::help::Help;
23pub use self::info::ConstrctInfo;
24pub use self::info::Information;
25pub use self::parser::StrParser;
26#[cfg(feature = "serde")]
27pub use self::serialize::Deserialize;
28#[cfg(feature = "serde")]
29pub use self::serialize::Serde;
30#[cfg(feature = "serde")]
31pub use self::serialize::Serialize;
32pub use self::value::OptValueExt;
33
34pub use crate::acore::opt::Action;
35pub use crate::acore::opt::Index;
36pub use crate::acore::opt::Opt;
37pub use crate::acore::opt::Style;
38pub use crate::acore::opt::BOOL_FALSE;
39pub use crate::acore::opt::BOOL_TRUE;
40
41use std::fmt::Debug;
42use std::ops::Deref;
43use std::ops::DerefMut;
44
45use crate::Error;
46
47/// Cmd represents a sub command flag wrapped the `bool` option, it is force required in default.
48///
49/// See [`cmd_check`](crate::set::SetChecker::cmd_check) of
50/// [`DefaultSetChecker`](crate::parser::DefaultSetChecker) for default checking behavior.
51///
52/// # Example
53///
54/// ```rust
55/// # use aopt::prelude::*;
56/// # use aopt::opt::Cmd;
57/// #
58/// # fn main() -> Result<(), aopt::Error> {
59///     
60/// let mut parser = AFwdParser::default();
61///
62/// // `Cmd` has a default position `@1`.
63/// parser.add_opt("list: Set the list sub command".infer::<Cmd>())?;
64/// parser.parse(Args::from(["app", "list"]))?;
65///
66/// // Get the value by `Infer::Val` type of `bool`.
67/// assert_eq!(parser.find_val::<bool>("list")?, &true);
68///
69/// # Ok(())
70/// # }
71/// ```
72#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
73#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
74pub struct Cmd(pub bool);
75
76impl Cmd {
77    pub fn new(value: bool) -> Self {
78        Self(value)
79    }
80}
81
82impl Deref for Cmd {
83    type Target = bool;
84
85    fn deref(&self) -> &Self::Target {
86        &self.0
87    }
88}
89
90impl DerefMut for Cmd {
91    fn deref_mut(&mut self) -> &mut Self::Target {
92        &mut self.0
93    }
94}
95
96/// Pos is a position option wrapper, it is matching based on position.
97///
98/// See [`pos_check`](crate::set::SetChecker::pos_check) of
99/// [`DefaultSetChecker`](crate::parser::DefaultSetChecker) for default checking behavior.
100///
101/// # Example
102///
103/// ```rust
104/// # use aopt::prelude::*;
105/// # use aopt::opt::Pos;
106/// #
107/// # fn main() -> Result<(), aopt::Error> {
108///     
109/// let mut parser = AFwdParser::default();
110///
111/// // Name is not important.
112/// parser.add_opt("pos_accept_string@1: Set the string value".infer::<Pos<String>>())?;
113///
114/// parser.parse(Args::from(["app", "value"]))?;
115///
116/// // Get the value by `Infer::Val` type of `String`.
117/// assert_eq!(parser.find_val::<String>("pos_accept_string")?, &String::from("value"));
118///
119/// # Ok(())
120/// # }
121/// ```
122#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
123#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
124pub struct Pos<T = bool>(pub T);
125
126impl<T> Pos<T> {
127    pub fn new(value: T) -> Self {
128        Self(value)
129    }
130}
131
132impl<T> Deref for Pos<T> {
133    type Target = T;
134
135    fn deref(&self) -> &Self::Target {
136        &self.0
137    }
138}
139
140impl<T> DerefMut for Pos<T> {
141    fn deref_mut(&mut self) -> &mut Self::Target {
142        &mut self.0
143    }
144}
145
146/// Main are always matched; it is using for running logical before [`Policy`](crate::parser::Policy) ending.
147///
148/// See [`post_check`](crate::set::SetChecker::post_check) of
149/// [`DefaultSetChecker`](crate::parser::DefaultSetChecker) for default checking behavior.
150/// # Example
151///
152/// ```rust
153/// # use aopt::prelude::*;
154/// # use aopt::opt::Main;
155/// # use std::ffi::OsStr;
156/// #
157/// # fn main() -> Result<(), aopt::Error> {
158///     
159/// let mut parser = AFwdParser::default();
160///
161/// // `Main` has a default position `@*`.
162/// parser.add_opt("main_function: Call the main function".infer::<Main>())?
163///       // Main do nothing in default, you must change the `Action` if you want save value
164///       .set_action(Action::Set)
165///       .on(|_, ctx: &mut Ctx|{
166///             let val = ctx.arg()?;
167///             assert_eq!(val.map(|v|v.as_ref()), Some(OsStr::new("app")));
168///             Ok(Some(String::from("main_function called")))
169///       })?;
170///
171/// parser.parse(Args::from(["app", "list"]))?;
172///
173/// // Get the value of main function returned.
174/// assert_eq!(parser.find_val::<String>("main_function")?, &String::from("main_function called"));
175///
176/// # Ok(())
177/// # }
178/// ```
179#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
180#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
181pub struct Main<T = ()>(pub T);
182
183impl<T> Main<T> {
184    pub fn new(value: T) -> Self {
185        Self(value)
186    }
187}
188
189impl<T> Deref for Main<T> {
190    type Target = T;
191
192    fn deref(&self) -> &Self::Target {
193        &self.0
194    }
195}
196
197impl<T> DerefMut for Main<T> {
198    fn deref_mut(&mut self) -> &mut Self::Target {
199        &mut self.0
200    }
201}
202
203/// Simple option type wrapper, implemented [`Infer`](crate::value::Infer).
204/// It works with the types are implemented [`RawValParser`](crate::value::RawValParser).
205///
206/// # Example
207///
208/// ```rust
209/// # use aopt::Error;
210/// # use aopt::value::raw2str;
211/// # use aopt::prelude::*;
212///
213/// #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)]
214/// pub struct Name(String);
215///
216/// impl RawValParser for Name {
217///     type Error = Error;
218///
219///     fn parse(arg: Option<&OsStr>, _: &Ctx) -> Result<Self, Self::Error> {
220///         Ok(Name(raw2str(arg)?.to_owned()))
221///     }
222/// }
223///
224/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
225/// let mut parser = AFwdParser::default();
226///
227/// // add the option wrap with `MutOpt`
228/// parser.add_opt("-e: Set the name".infer::<MutOpt<Name>>())?;
229///
230/// parser.parse(Args::from(["app", "-e=foo"]))?;
231///
232/// // Get the value through value type `Name`
233/// assert_eq!(parser.find_val::<Name>("-e")?, &Name("foo".to_owned()));
234///
235/// #    Ok(())
236/// # }
237/// ```
238#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
239#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
240pub struct MutOpt<T>(pub T);
241
242impl<T> MutOpt<T> {
243    pub fn new(value: T) -> Self {
244        Self(value)
245    }
246}
247
248impl<T> Deref for MutOpt<T> {
249    type Target = T;
250
251    fn deref(&self) -> &Self::Target {
252        &self.0
253    }
254}
255
256impl<T> DerefMut for MutOpt<T> {
257    fn deref_mut(&mut self) -> &mut Self::Target {
258        &mut self.0
259    }
260}
261
262#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
263#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, PartialOrd, Ord)]
264pub struct AnyOpt<T = ()>(pub T);
265
266impl<T> AnyOpt<T> {
267    pub fn new(value: T) -> Self {
268        Self(value)
269    }
270}
271
272impl<T> Deref for AnyOpt<T> {
273    type Target = T;
274
275    fn deref(&self) -> &Self::Target {
276        &self.0
277    }
278}
279
280impl<T> DerefMut for AnyOpt<T> {
281    fn deref_mut(&mut self) -> &mut Self::Target {
282        &mut self.0
283    }
284}
285
286/// Option parser using for parsing option constructor string.
287pub trait OptParser {
288    type Output;
289    type Error: Into<Error>;
290
291    fn parse_opt(&self, pattern: &str) -> Result<Self::Output, Self::Error>;
292}