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
304
305
306
307
308
309
310
311
312
313
314
/*!

This crate is usefull if you want to easily have an okay cli interface for your program.

you can use it like this:
```rust
use std::env::args;

type Error = Box<dyn std::error::Error>;

use simple_arguments::Arguments;

fn main() -> Result<(), Error> {
	let mut number: usize = 0;
	let mut string: String = String::new();
	let mut boolean: bool = false;
	let mut help: bool = false;

	let usage;
	// you have to do this because the lifetimes of the references must be
	// greter than the lifetime of the argument struct

	{
		let mut arguments = Arguments::new(Some("args_tester"));
		let mut args = args();
		let exec = args.next().unwrap();
		let a: Vec<_> = args.collect();

		arguments.add(&mut number, "number", "a number");
		arguments.add(&mut boolean, "bool", "a boolean value");
		arguments.add(&mut string, "string", "a string");
		arguments.add_bool(&mut help, "help", "displays the help message");
		usage = arguments.usage();

		if let Err(e) = arguments.parse(&a[..]) {
			println!("{}", e);
			print!("{}", usage);
			return Ok(());
		}
	}

	if help {
		println!("{}", usage);
		return Ok(());
	}
	println!("{} {} {}", number, boolean, string);

	Ok(())
}

```

here, instead of only defining the arguments' names and converting them to the
correct type after, we make use of a special trait `Filler` (which is
implemented for all FromStr types) to automatically convert the arguments.


 */

use std::collections::HashMap;
use std::io::Write;
use std::str::FromStr;

#[derive(Debug, Clone)]
pub enum ArgError {
	Err(String),
	OutOfArgs,
}

impl std::fmt::Display for ArgError {
	fn fmt(&self, fmt: &mut std::fmt::Formatter) -> std::fmt::Result {
		match self {
			ArgError::Err(e) => {
				write!(fmt, "{}", e)?;
			}
			ArgError::OutOfArgs => {
				write!(fmt, "out of arguments");
			}
		}
		Ok(())
	}
}

/// This trait is the one which has to be implemented by every argument passed
/// to the Arguments struct.
pub trait Filler {
	fn fill(&mut self, s: &mut dyn Iterator<Item = &str>) -> Result<(), ArgError>;
	fn type_name(&self) -> &'static str {
		"unknown"
	}
}

struct BooleanFlag<'a> {
	value: &'a mut bool,
}

impl<'a> Filler for BooleanFlag<'a> {
	fn fill(&mut self, s: &mut dyn Iterator<Item = &str>) -> Result<(), ArgError> {
		*self.value = true;
		Ok(())
	}
	fn type_name(&self) -> &'static str {
		"flag"
	}
}

impl<T: FromStr> Filler for &mut T {
	fn fill(&mut self, s: &mut dyn Iterator<Item = &str>) -> Result<(), ArgError> {
		use std::any::type_name;

		let item = s.next().ok_or(ArgError::OutOfArgs)?;

		**self = T::from_str(item)
			.or_else(|err| Err(ArgError::Err(format!("error parsing {}", type_name::<T>()))))?;
		Ok(())
	}

	fn type_name(&self) -> &'static str {
		use std::any::type_name;
		&type_name::<Self>()[5..]
	}
}

struct Flag<'a> {
	description: String,
	value: Box<dyn Filler + 'a>,
}

/// the main struct which is responsible for managing all argument parsing logic
pub struct Arguments<'a> {
	flags: HashMap<String, Flag<'a>>,
	name: Option<String>,
}

impl<'a> Arguments<'a> {
	/// initialises a new `Arguments` struct. You can give it an optional
	/// executable name which will be used to create the usage String.
	pub fn new(name: Option<&str>) -> Self {
		Arguments {
			flags: HashMap::new(),
			name: name.map(|v| v.to_owned()),
		}
	}

	/// adds a new argument to the struct. filler must implement filler (all
	/// &mut T where T: FromStr implement Filler)
	pub fn add<T, S>(&mut self, filler: T, name: S, description: &str)
	where
		T: Filler + 'a,
		S: ToString,
	{
		let new_flag = Flag {
			description: description.to_owned(),
			value: Box::new(filler),
		};

		self.flags.insert(name.to_string(), new_flag);
	}

	/// fills every argument with the given arguments and returns a vector of
	/// all the arguments that weren't taken by any flag. If it fails, returns a
	/// string describing a parsing error or a lack of remaining arguments
	pub fn parse<S: AsRef<str>>(&mut self, arguments: &[S]) -> Result<Vec<String>, String> {
		let mut free_args: Vec<&str> = Vec::new();

		let mut flags: Vec<(&str, Vec<&str>)> = Vec::new();
		let mut cur_flag = "";
		let mut cur_args = Vec::new();

		let mut got_first_flag = false;
		for a in arguments.iter().map(|s| s.as_ref()) {
			if a.starts_with("--") {
				if got_first_flag {
					flags.push((cur_flag, cur_args));
					cur_args = Vec::new();
				} else {
					got_first_flag = true;
				}
				cur_flag = &a[2..];
			} else if !got_first_flag {
				free_args.push(a);
			} else {
				cur_args.push(a);
			}
		}
		if got_first_flag {
			flags.push((cur_flag, cur_args));
		}

		for (f, mut v) in flags.into_iter() {
			let mut iterator = v.into_iter();
			let mut flag = self
				.flags
				.get_mut(f)
				.ok_or_else(|| format!("invalid flag: {}", &f))?;

			flag.value
				.fill(&mut iterator)
				.or_else(|err| Err(format!("{}: {}", f, err)))?;
			for v in iterator {
				free_args.push(v);
			}
		}

		Ok(free_args.into_iter().map(|s| s.to_owned()).collect())
	}

	/// generates a usage string
	pub fn usage(&self) -> String {
		let mut o = String::new();

		let mut flags: Vec<_> = self.flags.iter().collect();
		flags.sort_by_key(|(name, fl)| name.to_owned());

		let max_len = flags.iter().fold(0, |acc, v| acc + v.0.len());
		if let Some(exec) = &self.name {
			o.push_str(&format!("usage:\n{} [flags] args...\n", exec));
		}
		for i in flags {
			o.push_str(&format!(
				"\t--{: <20} ({}) {}\n",
				i.0,
				i.1.value.type_name(),
				i.1.description,
				//width = max_len + 4
			));
		}
		o
	}

	/// since the default implementation of Filller for &mut bool would require
	/// the user tu write `./program --boolean-flag true` instead of just
	/// `./program --boolean-flag`, this functions adds a flag that, when given,
	/// will autmatically set the given variable to true
	pub fn add_bool<S: ToString>(&mut self, b: &'a mut bool, name: S, description: &str) {
		let filler = BooleanFlag { value: b };
		let flag = Flag {
			description: description.to_owned(),
			value: Box::new(filler),
		};
		self.flags.insert(name.to_string(), flag);
	}
}

#[test]
fn simple_test() {
	let mut number: usize = 12;
	let mut string: String = String::new();
	let mut boolean: bool = false;

	let a = &["--bool", "true", "--number", "123", "--string", "penis"];

	let mut arguments = Arguments::new(None);
	arguments.add(&mut number, "number", "a number");
	arguments.add(&mut boolean, "bool", "a boolean value");
	arguments.add(&mut string, "string", "a string");
	arguments.parse(a).unwrap();
	drop(arguments);

	assert_eq!(number, 123);
	assert_eq!(boolean, true);
	assert_eq!(string, "penis");
}

#[test]
fn _test() {
	let mut boolean: bool = false;

	let a = &["--bool"];

	let mut arguments = Arguments::new(None);
	arguments.add_bool(&mut boolean, "bool", "flag");
	arguments.parse(a).unwrap();
	drop(arguments);

	assert_eq!(boolean, true);
}

#[test]
fn free_args_test() {
	let mut number: usize = 12;
	let mut string: String = String::new();
	let mut boolean: bool = false;

	let a = &[
		"--bool",
		"true",
		"marmelade1",
		"--number",
		"123",
		"marmelade2",
		"--string",
		"penis",
		"marmelade3",
		"marmelade4",
	];

	let mut arguments = Arguments::new(None);
	arguments.add(&mut number, "number", "a number");
	arguments.add(&mut boolean, "bool", "a boolean value");
	arguments.add(&mut string, "string", "a string");
	let frees = arguments.parse(a).unwrap();
	drop(arguments);

	assert_eq!(number, 123);
	assert_eq!(boolean, true);
	assert_eq!(string, "penis");
	let mut i = frees.into_iter();
	assert_eq!(Some("marmelade1"), i.next().as_ref().map(|s| s.as_str()));
	assert_eq!(Some("marmelade2"), i.next().as_ref().map(|s| s.as_str()));
	assert_eq!(Some("marmelade3"), i.next().as_ref().map(|s| s.as_str()));
	assert_eq!(Some("marmelade4"), i.next().as_ref().map(|s| s.as_str()));
	assert_eq!(None, i.next().as_ref().map(|s| s.as_str()));
}