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
315
316
|
use derive_builder::Builder;
use std::collections::HashMap;
#[allow(dead_code)]
pub enum ValueRequirement {
None,
Required(&'static str),
Optional(&'static str),
}
#[derive(Builder)]
#[builder(pattern = "owned")]
pub struct Option {
#[builder(setter(into), default = "'\\0'")]
short: char,
long: &'static str,
#[builder(setter(into), default = "\"\"")]
description: &'static str,
#[builder(setter(name = "value"), default = "ValueRequirement::None")]
value_req: ValueRequirement,
#[builder(setter(skip))]
is_set: bool,
#[builder(setter(skip))]
value: std::option::Option<String>,
}
pub struct Options {
options: Vec<Option>,
short: HashMap<char, usize>,
long: HashMap<&'static str, usize>,
}
impl Option {
pub fn short(&self) -> char {
self.short
}
pub fn long(&self) -> &'static str {
self.long
}
pub fn description(&self) -> &'static str {
self.description
}
pub fn is_set(&self) -> bool {
self.is_set
}
pub fn value(&self) -> &std::option::Option<String> {
&self.value
}
fn set(&mut self, value: std::option::Option<String>) {
self.is_set = true;
self.value = value;
}
}
impl Options {
pub fn new() -> Self {
Options {
options: Vec::new(),
short: HashMap::new(),
long: HashMap::new(),
}
}
pub fn push(&mut self, option: Option) -> usize {
let index = self.options.len();
if option.short != '\0' {
self.short.insert(option.short, index);
}
if option.long != "" {
self.long.insert(option.long, index);
}
self.options.push(option);
index
}
}
impl std::ops::Index<usize> for Options {
type Output = Option;
fn index(&self, index: usize) -> &Self::Output {
self.options.index(index)
}
}
pub struct Arguments {
pub program: std::option::Option<String>,
pub args: Vec<String>,
}
pub trait Parser {
fn run(
&self,
options: &mut Options,
args: impl IntoIterator<Item = String>,
) -> Result<Arguments, String>;
fn print_help(&self, options: &Options);
}
#[allow(dead_code)]
pub struct LongOnlyParser {}
#[allow(dead_code)]
pub struct ShortAndLongParser {}
fn print_list(list: Vec<(String, &str)>) {
let mut left_len: usize = 0;
for (left, _) in &list {
left_len = std::cmp::max(left_len, left.len());
}
for (left, right) in &list {
println!("{left:<left_len$} {right}");
}
}
#[allow(dead_code)]
impl LongOnlyParser {
pub fn new() -> LongOnlyParser {
LongOnlyParser {}
}
}
impl Parser for LongOnlyParser {
fn run(
&self,
options: &mut Options,
args: impl IntoIterator<Item = String>,
) -> Result<Arguments, String> {
let mut ret = Vec::new();
let mut args_iter = args.into_iter();
let program = args_iter.next();
while let Some(arg) = args_iter.next() {
if arg.starts_with("-") {
if arg == "--" {
// All following arguments are just that.
while let Some(arg) = args_iter.next() {
ret.push(arg)
}
break;
}
let start = 1;
let name;
let mut value;
if let Some(end) = arg.find('=') {
name = arg.get(start..end).unwrap();
value = Some(arg.get(end + 1..).unwrap().to_string());
} else {
name = arg.get(start..).unwrap();
value = None;
}
if let Some(index) = options.long.get(name) {
let ref mut option = options.options[*index];
match option.value_req {
ValueRequirement::None => {
if value.is_some() {
return Err(format!("option '{}' doesn't allow an argument", arg));
}
}
ValueRequirement::Required(_) => {
if value.is_none() {
value = args_iter.next();
if value.is_none() {
return Err(format!("option '{}' requires an argument", arg));
}
}
}
ValueRequirement::Optional(_) => {}
}
option.set(value);
} else {
return Err(format!("unrecognized option '{}'", arg));
}
} else {
ret.push(arg)
}
}
Ok(Arguments { program, args: ret })
}
fn print_help(&self, options: &Options) {
let mut lines = Vec::new();
for (_, index) in &options.long {
let ref option = options[*index];
let left = match option.value_req {
ValueRequirement::None => format!("-{}", option.long()),
ValueRequirement::Required(name) => format!("-{}={}", option.long(), name),
ValueRequirement::Optional(name) => format!("-{}[={}]", option.long(), name),
};
lines.push((left, option.description()));
}
print_list(lines);
}
}
#[allow(dead_code)]
impl ShortAndLongParser {
pub fn new() -> ShortAndLongParser {
ShortAndLongParser {}
}
}
impl Parser for ShortAndLongParser {
fn run(
&self,
options: &mut Options,
args: impl IntoIterator<Item = String>,
) -> Result<Arguments, String> {
let mut ret = Vec::new();
let mut args_iter = args.into_iter();
let program = args_iter.next();
while let Some(arg) = args_iter.next() {
if arg.starts_with("--") {
if arg.len() == 2 {
// All following arguments are just that.
while let Some(arg) = args_iter.next() {
ret.push(arg)
}
break;
}
let start = 2;
let name;
let mut value;
if let Some(end) = arg.find('=') {
name = arg.get(start..end).unwrap();
value = Some(arg.get(end + 1..).unwrap().to_string());
} else {
name = arg.get(start..).unwrap();
value = None;
}
if let Some(index) = options.long.get(name) {
let ref mut option = options.options[*index];
match option.value_req {
ValueRequirement::None => {
if value.is_some() {
return Err(format!("option '{}' doesn't allow an argument", arg));
}
}
ValueRequirement::Required(_) => {
if value.is_none() {
value = args_iter.next();
if value.is_none() {
return Err(format!("option '{}' requires an argument", arg));
}
}
}
ValueRequirement::Optional(_) => {}
}
option.set(value);
} else {
return Err(format!("unrecognized option '{}'", arg));
}
} else if arg.starts_with("-") && arg.len() > 1 {
for c in arg.get(1..).unwrap().chars() {
if let Some(index) = options.short.get(&c) {
let ref mut option = options.options[*index];
let mut value = None;
match option.value_req {
ValueRequirement::None => {}
ValueRequirement::Required(_) => {
value = args_iter.next();
if value.is_none() {
return Err(format!("option requires an argument -- '{}", c));
}
}
ValueRequirement::Optional(_) => {}
}
option.set(value);
} else {
return Err(format!("invalid option -- '{}'", c));
}
}
} else {
ret.push(arg)
}
}
Ok(Arguments { program, args: ret })
}
fn print_help(&self, options: &Options) {
let mut lines = Vec::new();
for option in &options.options {
let left: String;
if option.short() == '\0' {
left = match option.value_req {
ValueRequirement::None => format!(" --{}", option.long()),
ValueRequirement::Required(name) => format!(" --{}={}", option.long(), name),
ValueRequirement::Optional(name) => {
format!(" --{}[={}]", option.long(), name)
}
};
} else if option.long() == "" {
left = match option.value_req {
ValueRequirement::None => format!("-{}", option.short()),
ValueRequirement::Required(name) => format!("-{}={}", option.short(), name),
ValueRequirement::Optional(name) => format!("-{}[={}]", option.short(), name),
};
} else {
left = match option.value_req {
ValueRequirement::None => format!("-{}, --{}", option.short(), option.long()),
ValueRequirement::Required(name) => {
format!("-{}, --{}={}", option.short(), option.long(), name)
}
ValueRequirement::Optional(name) => {
format!("-{}, --{}[={}]", option.short(), option.long(), name)
}
};
}
lines.push((left, option.description()));
}
print_list(lines);
}
}
|