commandargs/option/mod.rs
1pub mod option_pattern;
2
3/// Value generated from matching against `OptionPattern` accordingly. `Option`'s are used as
4/// containers.
5pub enum Option {
6 /// Standalone option is an option with no required argument, (e.g. `-force`).
7 ///
8 /// ### Fields
9 /// - `&'static str`: Name of the option.
10 Standalone(&'static str),
11
12 /// Argumented option is an option that requires a value, the value which was either positional
13 /// or any, (e.g. `-warning-level all`).
14 ///
15 /// ### Fields
16 /// - `&'static str`: Name of the option.
17 /// - `String`: Value of the option.
18 Argumented(&'static str, String),
19}
20
21/// Wrapper around `Option` values. A container that is primarily used to improve user access in
22/// `callback` via its methods.
23pub struct Options {
24 options: Vec<Option>,
25}
26
27impl Option {
28 pub fn name(&self) -> &str {
29 match self {
30 Self::Standalone(name) => name,
31 Self::Argumented(name, ..) => name,
32 }
33 }
34}
35
36impl Options {
37 /// Attempts to find a standalone option by its name, if it fails to find an option with that
38 /// name OR the name referred to an option that is NOT a standalone, it returns `false`,
39 /// otherwise returns `true`.
40 pub fn get_standalone(&self, name: &'static str) -> bool {
41 for option in self.options.iter() {
42 if let Option::Standalone(optname) = option
43 && *optname == name
44 {
45 return true;
46 }
47 }
48
49 false
50 }
51
52 /// Attempts to find an argumented option by its name, if it fails to find an option with that
53 /// name OR the name referred to an option that is NOT an argumented, it returns `None`,
54 /// otherwise returns the value of the option.
55 pub fn get_argumented(&self, name: &'static str) -> std::option::Option<&str> {
56 for option in self.options.iter() {
57 if let Option::Argumented(optname, value) = option
58 && *optname == name
59 {
60 return Some(value);
61 }
62 }
63
64 None
65 }
66
67 /// Returns all options matched without check.
68 pub fn values(&self) -> &Vec<Option> {
69 &self.options
70 }
71}
72
73impl From<Vec<Option>> for Options {
74 fn from(value: Vec<Option>) -> Self {
75 Self { options: value }
76 }
77}