args_flags_1/
lib.rs

1//! # Flag Detection Crate
2//! this crate detect flag in syntax
3//! command -flag value_of_flag
4//! ## Examples
5//! ```
6//! flagfinder -timeout 1000
7//! ```
8//! # Examples
9//! ```
10//! use std::env;
11//!
12//! let prefix: &str = "-";
13//! let args: env::Args = env::args();
14//! let detect: FlagDetect = FlagDetect::new(prefix).from_args(args);
15//!
16//! // gives back value of the flag
17//! let s_flag: Option<String> = detect.find("-s");
18//! match s_flag {
19//!     Some(x) => {},
20//!     None => {}
21//! }
22//!
23//! ```
24
25
26use std::env::Args;
27
28// #[derive(New)]
29/// Flag 
30/// next value to flag is value for the flag
31/// syntax of command used is <prefix><key> <value>
32///
33/// # Examples 
34/// ```
35/// let flag = Flag::new("s", "1000");
36///
37/// ```
38#[derive(Debug)]
39pub struct Flag {
40    /// key or text of flag
41    key: String,
42    /// value of the flag
43    val: String
44}
45impl Flag {
46    pub fn new(key: &str, val: &str) -> Self {
47        Self {key: key.to_string(), val: val.to_string()}
48    }
49    pub fn same(&self, input: &str) -> bool {
50        self.key == input
51    }
52    pub fn get(&self) -> &str {
53        &self.val
54    }
55}
56
57/// This struct is Vec for our flags
58/// implementation of using flags
59///
60/// show: -s mark
61///
62/// # Examples
63/// ## get all obtained flags
64/// ```
65/// let flags: Vec<Flag> = FlagDetect::get("-", std::env::args())
66/// ```
67///
68/// ## working with specific flag
69/// ```
70/// use std::env;
71///
72/// let prefix: &str = "-";
73/// let args: env::Args = env::args();
74/// let detect: FlagDetect = FlagDetect::new(prefix).from_args(args);
75///
76/// // gives back value of the flag
77/// let s_flag: Option<String> = detect.find("-s");
78/// match s_flag {
79///     Some(x) => {},
80///     None => {}
81/// }
82/// ```
83pub struct FlagDetect {
84    prefix: String,
85    flags: Vec<Flag>
86}
87
88/// # Static Flag Only
89/// basicly getting only flag not their specified values
90/// ```
91/// let prefix = "-";
92/// // basic flag exporter 
93/// StaicOnlyFlag::get(prefix, std::env::args());
94///
95/// // basic one letter exporter
96/// StaicOnlyFlag::getn(prefix, std::env::args());
97/// ```
98pub struct StaticFlagOnly {}
99impl StaticFlagOnly {
100    /// get flags only (ignores everything else and not works with values of them)
101    /// ```
102    /// input: -a -b -c r -avc
103    /// returns vec!['a', 'b', 'c', 'avc']
104    /// ```
105    pub fn get(prefix: &str, args: Args) -> Vec<String> {
106        let size = args.len();
107        args.rev().take(size-prefix.len())
108            .map(|x| x.replace(prefix, ""))
109            .filter(|x| x.contains(prefix))
110            .rev().collect()
111    }
112    /// get all arguments with prefix and then split it by one
113    /// ```
114    /// input: -a -b -c r -kvd
115    /// returns vec!['a', 'b', 'c', 'k', 'v', 'd']
116    /// ```
117    pub fn getn(prefix: &str, args: Args) -> Vec<String> {
118        let x = self::StaticFlagOnly::get(prefix, args).join("");
119        x.split("").map(|x| x.to_string()).collect()
120    }
121}
122
123/// # Static Flag
124/// Just get Arguments without doing anything else
125/// Basicly getting flag (val: String, key: String)
126///
127/// ```
128/// let prefix = "-";
129///
130/// // flag exporter
131/// StaticFlag::get(prefix, std::env::args());
132///
133/// // flag exporter with more prefixes
134/// StaticFlag::getn(vec![prefix], std::env::args());
135/// ```
136pub struct StaticFlag { }
137impl StaticFlag {
138    /// get all Flags from arguments pushed to your program
139    /// Just get Arguments without doing anything else
140    pub fn get(prefix: &str, args: Args) -> Vec<Flag> {
141        let mut next = false;
142        let mut flags = Vec::new();
143        let mut last = "".to_string();
144        for a1 in args {
145            if a1.contains(prefix) {
146                next = true;
147                last = a1;
148            } else if next {
149                flags.push(Flag::new(&last, &a1));
150            }
151        }
152        flags
153    }
154    pub fn getn(prefixn: Vec<&str>, args: Args) -> Vec<Flag> {
155        let mut next = false;
156        let mut flags = Vec::new();
157        let mut last = "".to_string();
158        for a in args {
159            let prefixn = prefixn.clone();
160            for prefix in prefixn {
161                if a.contains(prefix) {
162                    next = true;
163                    last = a.clone();
164                } else if next {
165                    flags.push(Flag::new(&last, &a));
166                }
167            }
168        }
169        flags
170    }
171}
172
173impl FlagDetect {
174    /// # Eample 
175    /// ```
176    /// use args_flag_1::FlagDetect;
177    /// use args_flag_1::Flag;
178    ///
179    /// fn main() {
180    ///     let mut detector: FlagDetect = FlagDetect::new("-")
181    ///     detector.from_args()
182    /// }
183    /// ```
184    pub fn new(prefix: &str) -> Self {
185        Self {prefix: prefix.to_string(), flags: Vec::new()}
186    }
187    pub fn new_args(prefix: &str, args: Args) -> Self {
188        let mut sel = Self::new(prefix);
189        sel.from_args(args);
190        sel
191    }
192
193    /// generates flags from arguments (std::env::Args)
194    pub fn from_args(&mut self, a: Args) {
195        // a1 == String
196        let mut next = false;
197        let mut last = "".to_string();
198        for a1 in a {
199            if a1.contains(&self.prefix) {
200                next = true;
201                last = a1;
202            } else if next {
203                self.flags.push(Flag::new(&last, &a1));
204            }
205        }
206    }
207
208    /// tries to find flag using &str
209    /// ```
210    /// detect.find("-s") 
211    /// ```
212    pub fn find(&self, s: &str) -> Option<String> {
213        for x in self.flags.iter() {
214            if x.same(s) {
215                return Some(x.get().to_string())
216            }
217        }
218        None
219    }
220}
221