summary refs log tree commit diff
path: root/src/lib.rs
blob: 7e3842d1a84282855c3b0d5e9231ad56f8001d0f (plain)
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
use std::{borrow::Cow, cell::Cell, str::FromStr};

use formula::Formula;

pub mod formula;

pub struct Scurvy {
	free: Vec<String>,
	pairs: Vec<Pair>,
	unknown: Vec<(String, String)>,
	print_help: bool,
	print_version: bool,
	missing_string: Cell<Cow<'static, str>>,
}

struct Pair {
	key: Argument,
	values: Vec<String>,
}

impl Scurvy {
	pub fn make(args: Vec<Argument>) -> Self {
		let mut free = vec![];
		let mut pairs: Vec<Pair> = args.into_iter().map(|a| a.into()).collect();
		let mut unknown = vec![];

		let mut print_help = false;
		let mut print_version = false;

		for arg in std::env::args().skip(1) {
			if arg == "-h" || arg == "--help" || arg == "help=" {
				print_help = true;
			} else if arg == "-V" || arg == "--version" || arg == "version=" {
				print_version = true;
			}

			match arg.split_once('=') {
				None => free.push(arg),
				Some((key, value)) => {
					if let Some(pair) = pairs.iter_mut().find(|p| p.key.matches(key)) {
						pair.values.push(value.to_owned());
					} else {
						unknown.push((key.to_owned(), value.to_owned()));
					}
				}
			}
		}

		Self {
			free,
			pairs,
			unknown,
			print_help,
			print_version,
			missing_string: Cell::new(Cow::Borrowed("An argument for '[opt]' is required")),
		}
	}

	pub fn should_print_help(&self) -> bool {
		self.print_help
	}

	pub fn should_print_version(&self) -> bool {
		self.print_version
	}

	pub fn free(&self) -> &[String] {
		&self.free
	}

	fn get_pair(&self, key: &str) -> Option<&Pair> {
		self.pairs.iter().find(|p| p.key.matches(key))
	}

	pub fn get(&self, key: &str) -> Option<&str> {
		self.pairs
			.iter()
			.find(|p| p.key.matches(key))
			.map(|p| p.values.first().map(|s| s.as_str()))
			.flatten()
	}

	pub fn get_req(&self, key: &str) -> &str {
		match self.get(key) {
			None => {
				let pair = self.get_pair(key).unwrap();
				self.print_missing_and_die(pair.key.preferred_key());
			}
			Some(s) => s,
		}
	}

	pub fn parse<T: FromStr, F: Into<Formula<T>>>(&self, key: &str, formula: F) -> Option<T> {
		let formula = formula.into();
		let Some(got) = self.get(key) else {
			return None;
		};

		match got.parse::<T>() {
			Ok(o) => {
				if let Some((fail, mut check)) = formula.check_fn {
					if !check(&o) {
						let pair = self.get_pair(key).unwrap();
						let parsefail =
							format_parse_fail(fail.into(), pair.key.preferred_key(), got);

						eprintln!("{parsefail}");
						std::process::exit(-1);
					}

					return Some(o);
				};

				Some(o)
			}
			Err(_e) => {
				let pair = self.get_pair(key).unwrap();
				let fail = format_parse_fail(formula.failure.into(), pair.key.preferred_key(), got);

				eprintln!("{fail}");
				std::process::exit(-1);
			}
		}
	}

	/// Shorthand for [Scurvy::parse] followed by `unwrap_or()`
	pub fn parse_or<T: FromStr, F: Into<Formula<T>>>(
		&self,
		key: &str,
		formula: F,
		default: T,
	) -> T {
		self.parse(key, formula).unwrap_or(default)
	}

	pub fn parse_req<T: FromStr, F: Into<Formula<T>>>(&self, key: &str, formula: F) -> T {
		let formula = formula.into();
		let missing = formula.missing.clone();

		match self.parse(key, formula) {
			None => match missing {
				None => {
					let pair = self.get_pair(key).unwrap();
					self.print_missing_and_die(pair.key.preferred_key());
				}
				Some(misstr) => {
					let pair = self.get_pair(key).unwrap();
					let str = misstr.replace("[opt]", pair.key.preferred_key());

					eprintln!("{str}");
					std::process::exit(-1);
				}
			},
			Some(o) => o,
		}
	}

	pub fn set_missing_string<S: Into<Cow<'static, str>>>(&self, msg: S) {
		self.missing_string.set(msg.into());
	}

	fn print_missing_and_die(&self, key: &str) -> ! {
		// We can straight up take() here because of how we use this string,
		// because we exit right after it
		let str = self.missing_string.take().replace("[opt]", key);
		eprintln!("{str}");
		std::process::exit(-1);
	}
}

pub(crate) fn format_parse_fail(string: Cow<'static, str>, key: &str, arg: &str) -> String {
	string.replace("[opt]", key).replace("[arg]", arg)
}

pub struct Argument {
	keys: Vec<String>,
	arg_name: Option<&'static str>,
	help: &'static str,
}

impl Argument {
	pub fn new<'s, K: Into<SingleOrMultiple<'s>>>(key: K) -> Self {
		let keys = match key.into() {
			SingleOrMultiple::Single(s) => vec![s],
			SingleOrMultiple::Multiple(m) => m.to_vec(),
		};

		Self {
			keys: keys.into_iter().map(<_>::to_owned).collect(),
			arg_name: None,
			help: "",
		}
	}

	pub fn arg(mut self, name: &'static str) -> Self {
		self.arg_name = Some(name);
		self
	}

	pub fn help(mut self, help: &'static str) -> Self {
		self.help = help;
		self
	}

	fn matches(&self, key: &str) -> bool {
		self.keys.iter().find(|k| k.as_str() == key).is_some()
	}

	fn preferred_key(&self) -> &str {
		self.keys.first().unwrap().as_str()
	}
}

impl Into<Pair> for Argument {
	fn into(self) -> Pair {
		Pair {
			key: self,
			values: vec![],
		}
	}
}

pub enum SingleOrMultiple<'s> {
	Single(&'s str),
	Multiple(&'s [&'s str]),
}

impl<'s> From<&'s str> for SingleOrMultiple<'s> {
	fn from(value: &'s str) -> Self {
		Self::Single(value)
	}
}

impl<'s> From<&'s [&'s str]> for SingleOrMultiple<'s> {
	fn from(value: &'s [&'s str]) -> Self {
		Self::Multiple(value)
	}
}

impl<'s, const N: usize> From<&'s [&'s str; N]> for SingleOrMultiple<'s> {
	fn from(value: &'s [&'s str; N]) -> Self {
		Self::Multiple(value.as_slice())
	}
}