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
use std::env;
#[derive(Debug)]
pub enum CLIMakeError {
NoArgumentsPassed,
HelpOverwrite,
}
pub struct CLIMake {
pub name: String,
pub description: Option<String>,
pub args: Vec<Argument>,
pub none_run: Option<Box<dyn Fn()>>,
}
impl CLIMake {
pub fn parse_args(&mut self) {
let passed_args: Vec<String> = env::args().collect();
let check_args = |query: String| passed_args.iter().position(|a| a == &query).is_some();
if passed_args.len() == 1 {
match &self.none_run {
Some(to_run) => {
(to_run)();
std::process::exit(0);
}
None => {
println!("{}No arguments passed!", self.header_text());
std::process::exit(1);
}
}
} else if check_args(String::from("-h"))
|| check_args(String::from("--help"))
|| check_args(String::from("help"))
{
println!("{}", self.help_msg());
std::process::exit(0);
}
let mut valid_count = false;
let mut valid_ind = 0;
for arg in self.args.iter() {
let short_call_pass = match &arg.short_call {
Some(x) => check_args(format!("-{}", x)),
None => false,
};
let standalone_call_pass = match &arg.standalone_call {
Some(x) => check_args(x.clone()),
None => false,
};
if short_call_pass || standalone_call_pass {
valid_count = true;
valid_ind += 1;
let run_args = match arg.got_param {
true => {
if passed_args.len() < valid_ind + 1 {
println!("{}No body given for argument!", self.header_text());
std::process::exit(1);
}
Some(passed_args[valid_ind + 1].clone())
}
false => None,
};
(arg.run)(run_args);
}
}
if !valid_count {
println!("{}Argument(s) passed are invalid!", self.header_text());
std::process::exit(1);
}
std::process::exit(0);
}
pub fn add_existing_arg(&mut self, new_arg: Argument) -> Result<(), CLIMakeError> {
let short_override_check = match &new_arg.short_call {
Some(x) => x == &'h',
None => false,
};
let standalone_override_check = match &new_arg.standalone_call {
Some(x) => x == "help",
None => false,
};
if short_override_check || standalone_override_check {
return Err(CLIMakeError::HelpOverwrite);
}
self.args.push(new_arg);
Ok(())
}
pub fn help_msg(&self) -> String {
let header_text = self.header_text();
let mut generated_help = format!(
"{}Options:\n -h help --help\t | Shows this message\n",
header_text
);
if self.args.len() == 0 {
return format!("{}No arguments made!", header_text);
}
for arg in self.args.iter() {
let mut arg_help = match arg.short_call {
Some(call) => format!(" -{}", call),
None => String::new(),
};
if arg.standalone_call.is_some() {
arg_help.push_str(&format!(" {}", arg.standalone_call.clone().unwrap()));
}
if arg.got_param {
arg_help.push_str(" [PARAM]");
} else {
arg_help.push_str("\t")
}
let ensured_arg_help = match &arg.help {
Some(help) => String::clone(help),
None => String::from("[Help not provided]"),
};
arg_help.push_str(&format!("\t | {}\n", ensured_arg_help));
generated_help.push_str(&arg_help);
}
generated_help
}
fn header_text(&self) -> String {
let exe_name = env::current_exe().unwrap();
let usage_info = format!(
"Usage: ./{} [OPTIONS]",
exe_name.file_name().unwrap().to_str().unwrap()
);
if self.description.is_some() {
format!(
"{}\n\n\t{}\n\t{}\n\n",
usage_info,
self.name,
self.description.clone().unwrap()
)
} else {
format!("{}\n\n\t{}\n\n", usage_info, self.name)
}
}
}
pub struct Argument {
pub short_call: Option<char>,
pub standalone_call: Option<String>,
pub got_param: bool,
pub help: Option<String>,
pub run: Box<dyn Fn(Option<String>)>,
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn basic_argparse() {
fn example_run(_arg: Option<String>) {
println!("Basic argparse working");
}
let new_arg = Argument {
short_call: Some('t'),
got_param: false,
standalone_call: Some(String::from("test")),
help: None,
run: Box::new(example_run),
};
let mut cli = CLIMake {
name: String::from("Test CLI"),
description: None,
args: vec![new_arg],
none_run: None,
};
cli.parse_args();
}
}