1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303
use std::iter::Peekable;
/**
Enum allowing to choose the type of argument.
*/
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum ArgType {
Flag,
Value,
ValueList,
}
/**
ArgResult enum is similar to ArgType enum but contains data generated through parsing
*/
#[derive(Debug, PartialEq)]
pub enum ArgResult {
Flag,
Value(String),
ValueList(Vec<String>),
}
///
/// Argument struct allows to specify type of expected argument, its names and after parsing contains results.
/// This is the legacy method of defining arguments. Currently using ParsableValueArgument is preffered.
///
/// # Examples
/// ```
/// use trivial_argument_parser::argument::legacy_argument::*;
/// let mut example_argument = Argument::new(Some('l'), Some("an-list"), ArgType::ValueList).unwrap();
/// ```
#[derive(Debug)]
pub struct Argument {
short: Option<char>,
long: Option<String>,
arg_type: ArgType,
pub arg_result: Option<ArgResult>,
}
impl Argument {
/**
Create new Argument. You need to specify at least one name (short or long) or you can specify both. Parameter arg_type changes how the parsing will treat the argument.
*/
pub fn new(
short: Option<char>,
long: Option<&str>,
arg_type: ArgType,
) -> Result<Argument, String> {
// Check if at least 1 name is specified
if let (Option::None, Option::None) = (short, long) {
return Err(String::from(
"At least one name of argument must be specified (short or long or both)",
));
}
// Check if long name is defined, if so use it
let long_owned: Option<String> = if let Some(text) = long {
Option::Some(String::from(text))
} else {
None
};
Ok(Argument {
short,
long: long_owned,
arg_type,
arg_result: None,
})
}
pub fn new_short(name: char, arg_type: ArgType) -> Argument {
Argument::new(Option::Some(name), Option::None, arg_type).unwrap()
}
pub fn new_long(name: &str, arg_type: ArgType) -> Argument {
Argument::new(Option::None, Option::Some(name), arg_type).unwrap()
}
///
/// Method allowing to simplify reading values of a single value type arguments.
///
///# Examples
///```
/// use trivial_argument_parser::argument::legacy_argument::*;
/// use trivial_argument_parser::ArgumentList;
/// let mut args_list = ArgumentList::new();
/// args_list.append_arg(Argument::new(Some('v'), None, ArgType::Value).unwrap());
/// args_list.parse_args(vec![String::from("-v"), String::from("VALUE")]).unwrap();
/// let value = args_list.search_by_short_name('v').unwrap().get_value().unwrap();
/// println!("Value: {}", value);
///```
pub fn get_value(&self) -> Result<&str, &'static str> {
if let ArgType::Value = self.arg_type {
if let Some(result) = &self.arg_result {
if let ArgResult::Value(ref value) = result {
return Ok(value);
} else {
return Err("Wrong type of result. Something really bad has happened");
}
} else {
return Err("No value assigned to result");
}
} else {
return Err("This argument is not an value");
}
}
///
/// Method allowing to simplify reading values of a value list type argument.
///
///# Examples
///```
/// use trivial_argument_parser::{argument::legacy_argument::*, ArgumentList};
/// let mut args_list = ArgumentList::new();
/// args_list.append_arg(Argument::new(Some('l'), None, ArgType::ValueList).unwrap());
/// args_list.parse_args(vec![String::from("-l"), String::from("cos")]).unwrap();
/// let list = args_list.search_by_short_name('l').unwrap().get_values().unwrap();
/// for e in list
/// {
/// println!("Value: {}", e);
/// }
///```
pub fn get_values(&self) -> Result<&Vec<String>, &'static str> {
if let ArgType::ValueList = self.arg_type {
if let Some(result) = &self.arg_result {
if let ArgResult::ValueList(ref list) = result {
return Ok(list);
} else {
return Err("Wrong type of result. Something really bad happened");
}
} else {
return Err("No result specified");
}
} else {
return Err("This argument is not an value list");
}
}
///
/// Method allowing to simplify reading values of a flag type argument.
///
///# Examples
///```
/// use trivial_argument_parser::{ArgumentList, args_to_string_vector, argument::legacy_argument::*};
/// let mut args_list = ArgumentList::new();
/// args_list.append_arg(Argument::new(Some('d'), None, ArgType::Flag).unwrap());
/// args_list.parse_args(args_to_string_vector(std::env::args())).unwrap();
/// if(args_list.search_by_short_name('d').unwrap().get_flag().unwrap())
/// {
/// println!("Flag was set");
/// }
///```
pub fn get_flag(&self) -> Result<bool, &'static str> {
if let ArgType::Flag = self.arg_type {
return Ok(if let Some(_) = self.arg_result {
true
} else {
false
});
} else {
return Err("Argument is not an flag type");
}
}
pub fn add_value(
&mut self,
input_iter: &mut Peekable<&mut std::slice::Iter<'_, String>>,
) -> Result<(), String> {
match self.arg_type {
ArgType::Flag => {
match self.arg_result {
Some(_) => return Err(String::from("Flag already set")),
_ => (),
}
self.arg_result = Some(ArgResult::Flag);
}
ArgType::Value => {
match self.arg_result {
Some(_) => return Err(String::from("Value already assigned")),
_ => (),
}
match input_iter.next() {
Some(word) => self.arg_result = Some(ArgResult::Value(String::from(word))),
None => return Err(String::from("Expected value")),
}
}
ArgType::ValueList => {
let mut new_result = false;
match self.arg_result {
Some(_) => (),
None => new_result = true,
}
if new_result {
self.arg_result = Some(ArgResult::ValueList(Vec::new()));
}
match input_iter.next() {
Some(word) => match self.arg_result.as_mut().expect("as mut") {
ArgResult::ValueList(ref mut values) => values.push(String::from(word)),
_ => return Err(String::from("WTF")),
},
None => return Err(String::from("Expected value")),
}
}
}
Ok(())
}
pub fn short(&self) -> &Option<char> {
&self.short
}
pub fn long(&self) -> &Option<String> {
&self.long
}
pub fn arg_type(&self) -> &ArgType {
&self.arg_type
}
}
#[cfg(test)]
mod test {
use std::borrow::BorrowMut;
use crate::argument::legacy_argument::{ArgType, Argument};
#[test]
fn new_works() {
assert!(Argument::new(Option::None, Option::Some("parameter"), ArgType::Flag).is_ok());
assert!(Argument::new(Option::Some('x'), Option::None, ArgType::Flag).is_ok());
assert!(Argument::new(Option::Some('x'), Option::Some("parameter"), ArgType::Flag).is_ok());
}
#[test]
fn new_fails() {
assert!(Argument::new(Option::None, Option::None, ArgType::Flag).is_err())
}
#[test]
fn value_works() {
let mut arg =
Argument::new(Option::None, Option::Some("parameter"), ArgType::Value).unwrap();
arg.add_value(
&mut vec![String::from("my value")]
.iter()
.borrow_mut()
.peekable(),
)
.unwrap();
let val = arg.get_value();
assert!(val.is_ok());
assert_eq!(val.unwrap(), "my value");
}
#[test]
fn value_fails_too_many_calls() {
let mut arg =
Argument::new(Option::None, Option::Some("parameter"), ArgType::Value).unwrap();
let inputs_vec = vec![String::from("my value"), String::from("second_value")];
let mut inputs_iter = inputs_vec.iter();
let mut inputs = inputs_iter.borrow_mut().peekable();
arg.add_value(&mut inputs).unwrap();
assert!(arg.add_value(&mut inputs).is_err());
}
#[test]
fn value_list_works() {
let mut arg =
Argument::new(Option::None, Option::Some("parameter"), ArgType::ValueList).unwrap();
let inputs_vec = vec![String::from("my value"), String::from("My second value")];
let mut inputs_iter = inputs_vec.iter();
let mut inputs = inputs_iter.borrow_mut().peekable();
arg.add_value(&mut inputs).unwrap();
arg.add_value(&mut inputs).unwrap();
let val = arg.get_values();
assert!(val.is_ok());
assert_eq!(val.unwrap().len(), 2);
assert_eq!(val.unwrap().get(0).unwrap(), "my value");
assert_eq!(val.unwrap().get(1).unwrap(), "My second value");
}
#[test]
fn flag_works() {
let mut arg =
Argument::new(Option::None, Option::Some("parameter"), ArgType::Flag).unwrap();
arg.add_value(
&mut vec![String::from("my value")]
.iter()
.borrow_mut()
.peekable(),
)
.unwrap();
let val = arg.get_flag();
assert!(val.is_ok());
assert_eq!(val.unwrap(), true);
}
}