-
Notifications
You must be signed in to change notification settings - Fork 12.1k
/
getopts.rs
1383 lines (1238 loc) · 39.8 KB
/
getopts.rs
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012-2013 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
* Simple getopt alternative.
*
* Construct a vector of options, either by using reqopt, optopt, and optflag
* or by building them from components yourself, and pass them to getopts,
* along with a vector of actual arguments (not including argv[0]). You'll
* either get a failure code back, or a match. You'll have to verify whether
* the amount of 'free' arguments in the match is what you expect. Use opt_*
* accessors to get argument values out of the matches object.
*
* Single-character options are expected to appear on the command line with a
* single preceding dash; multiple-character options are expected to be
* proceeded by two dashes. Options that expect an argument accept their
* argument following either a space or an equals sign. Single-character
* options don't require the space.
*
* # Example
*
* The following example shows simple command line parsing for an application
* that requires an input file to be specified, accepts an optional output
* file name following -o, and accepts both -h and --help as optional flags.
*
* ```
* extern mod extra;
* use extra::getopts::*;
*
* fn do_work(in: &str, out: Option<~str>) {
* io::println(in);
* io::println(match out {
* Some(x) => x,
* None => ~"No Output"
* });
* }
*
* fn print_usage(program: &str, _opts: &[extra::getopts::Opt]) {
* io::println(fmt!("Usage: %s [options]", program));
* io::println("-o\t\tOutput");
* io::println("-h --help\tUsage");
* }
*
* fn main() {
* let args = os::args();
*
* let program = copy args[0];
*
* let opts = ~[
* optopt("o"),
* optflag("h"),
* optflag("help")
* ];
* let matches = match getopts(vec::tail(args), opts) {
* result::Ok(m) => { m }
* result::Err(f) => { fail!(fail_str(f)) }
* };
* if opt_present(&matches, "h") || opt_present(&matches, "help") {
* print_usage(program, opts);
* return;
* }
* let output = opt_maybe_str(&matches, "o");
* let input: &str = if !matches.free.is_empty() {
* copy matches.free[0]
* } else {
* print_usage(program, opts);
* return;
* };
* do_work(input, output);
* }
* ```
*/
#[allow(missing_doc)];
use core::prelude::*;
use core::cmp::Eq;
use core::result::{Err, Ok};
use core::result;
use core::option::{Some, None};
use core::str;
use core::vec;
#[deriving(Eq)]
pub enum Name {
Long(~str),
Short(char),
}
#[deriving(Eq)]
pub enum HasArg { Yes, No, Maybe, }
#[deriving(Eq)]
pub enum Occur { Req, Optional, Multi, }
/// A description of a possible option
#[deriving(Eq)]
pub struct Opt {
name: Name,
hasarg: HasArg,
occur: Occur
}
fn mkname(nm: &str) -> Name {
if nm.len() == 1u {
Short(str::char_at(nm, 0u))
} else {
Long(nm.to_owned())
}
}
/// Create an option that is required and takes an argument
pub fn reqopt(name: &str) -> Opt {
return Opt {name: mkname(name), hasarg: Yes, occur: Req};
}
/// Create an option that is optional and takes an argument
pub fn optopt(name: &str) -> Opt {
return Opt {name: mkname(name), hasarg: Yes, occur: Optional};
}
/// Create an option that is optional and does not take an argument
pub fn optflag(name: &str) -> Opt {
return Opt {name: mkname(name), hasarg: No, occur: Optional};
}
/// Create an option that is optional and does not take an argument
pub fn optflagmulti(name: &str) -> Opt {
return Opt {name: mkname(name), hasarg: No, occur: Multi};
}
/// Create an option that is optional and takes an optional argument
pub fn optflagopt(name: &str) -> Opt {
return Opt {name: mkname(name), hasarg: Maybe, occur: Optional};
}
/**
* Create an option that is optional, takes an argument, and may occur
* multiple times
*/
pub fn optmulti(name: &str) -> Opt {
return Opt {name: mkname(name), hasarg: Yes, occur: Multi};
}
#[deriving(Eq)]
enum Optval { Val(~str), Given, }
/**
* The result of checking command line arguments. Contains a vector
* of matches and a vector of free strings.
*/
#[deriving(Eq)]
pub struct Matches {
opts: ~[Opt],
vals: ~[~[Optval]],
free: ~[~str]
}
fn is_arg(arg: &str) -> bool {
return arg.len() > 1 && arg[0] == '-' as u8;
}
fn name_str(nm: &Name) -> ~str {
return match *nm {
Short(ch) => str::from_char(ch),
Long(ref s) => copy *s
};
}
fn find_opt(opts: &[Opt], nm: Name) -> Option<uint> {
vec::position(opts, |opt| opt.name == nm)
}
/**
* The type returned when the command line does not conform to the
* expected format. Pass this value to <fail_str> to get an error message.
*/
#[deriving(Eq)]
pub enum Fail_ {
ArgumentMissing(~str),
UnrecognizedOption(~str),
OptionMissing(~str),
OptionDuplicated(~str),
UnexpectedArgument(~str),
}
/// Convert a `fail_` enum into an error string
pub fn fail_str(f: Fail_) -> ~str {
return match f {
ArgumentMissing(ref nm) => {
fmt!("Argument to option '%s' missing.", *nm)
}
UnrecognizedOption(ref nm) => {
fmt!("Unrecognized option: '%s'.", *nm)
}
OptionMissing(ref nm) => {
fmt!("Required option '%s' missing.", *nm)
}
OptionDuplicated(ref nm) => {
fmt!("Option '%s' given more than once.", *nm)
}
UnexpectedArgument(ref nm) => {
fmt!("Option '%s' does not take an argument.", *nm)
}
};
}
/**
* The result of parsing a command line with a set of options
* (result::t<Matches, Fail_>)
*/
pub type Result = result::Result<Matches, Fail_>;
/**
* Parse command line arguments according to the provided options
*
* On success returns `ok(Opt)`. Use functions such as `opt_present`
* `opt_str`, etc. to interrogate results. Returns `err(Fail_)` on failure.
* Use <fail_str> to get an error message.
*/
pub fn getopts(args: &[~str], opts: &[Opt]) -> Result {
let n_opts = opts.len();
fn f(_x: uint) -> ~[Optval] { return ~[]; }
let mut vals = vec::from_fn(n_opts, f);
let mut free: ~[~str] = ~[];
let l = args.len();
let mut i = 0;
while i < l {
let cur = copy args[i];
let curlen = cur.len();
if !is_arg(cur) {
free.push(cur);
} else if cur == ~"--" {
let mut j = i + 1;
while j < l { free.push(copy args[j]); j += 1; }
break;
} else {
let mut names;
let mut i_arg = None;
if cur[1] == '-' as u8 {
let tail = str::slice(cur, 2, curlen);
let mut tail_eq = ~[];
for str::each_splitn_char(tail, '=', 1) |s| { tail_eq.push(s.to_owned()) }
if tail_eq.len() <= 1 {
names = ~[Long(tail.to_owned())];
} else {
names =
~[Long(copy tail_eq[0])];
i_arg = Some(copy tail_eq[1]);
}
} else {
let mut j = 1;
let mut last_valid_opt_id = None;
names = ~[];
while j < curlen {
let range = str::char_range_at(cur, j);
let opt = Short(range.ch);
/* In a series of potential options (eg. -aheJ), if we
see one which takes an argument, we assume all
subsequent characters make up the argument. This
allows options such as -L/usr/local/lib/foo to be
interpreted correctly
*/
match find_opt(opts, copy opt) {
Some(id) => last_valid_opt_id = Some(id),
None => {
let arg_follows =
last_valid_opt_id.is_some() &&
match opts[last_valid_opt_id.get()]
.hasarg {
Yes | Maybe => true,
No => false
};
if arg_follows && j < curlen {
i_arg = Some(cur.slice(j, curlen).to_owned());
break;
} else {
last_valid_opt_id = None;
}
}
}
names.push(opt);
j = range.next;
}
}
let mut name_pos = 0;
for names.each() |nm| {
name_pos += 1;
let optid = match find_opt(opts, copy *nm) {
Some(id) => id,
None => return Err(UnrecognizedOption(name_str(nm)))
};
match opts[optid].hasarg {
No => {
if !i_arg.is_none() {
return Err(UnexpectedArgument(name_str(nm)));
}
vals[optid].push(Given);
}
Maybe => {
if !i_arg.is_none() {
vals[optid].push(Val((copy i_arg).get()));
} else if name_pos < names.len() ||
i + 1 == l || is_arg(args[i + 1]) {
vals[optid].push(Given);
} else { i += 1; vals[optid].push(Val(copy args[i])); }
}
Yes => {
if !i_arg.is_none() {
vals[optid].push(Val((copy i_arg).get()));
} else if i + 1 == l {
return Err(ArgumentMissing(name_str(nm)));
} else { i += 1; vals[optid].push(Val(copy args[i])); }
}
}
}
}
i += 1;
}
i = 0u;
while i < n_opts {
let n = vals[i].len();
let occ = opts[i].occur;
if occ == Req {
if n == 0 {
return Err(OptionMissing(name_str(&(opts[i].name))));
}
}
if occ != Multi {
if n > 1 {
return Err(OptionDuplicated(name_str(&(opts[i].name))));
}
}
i += 1;
}
return Ok(Matches {opts: vec::to_owned(opts),
vals: vals,
free: free});
}
fn opt_vals(mm: &Matches, nm: &str) -> ~[Optval] {
return match find_opt(mm.opts, mkname(nm)) {
Some(id) => copy mm.vals[id],
None => {
error!("No option '%s' defined", nm);
fail!()
}
};
}
fn opt_val(mm: &Matches, nm: &str) -> Optval { copy opt_vals(mm, nm)[0] }
/// Returns true if an option was matched
pub fn opt_present(mm: &Matches, nm: &str) -> bool {
!opt_vals(mm, nm).is_empty()
}
/// Returns the number of times an option was matched
pub fn opt_count(mm: &Matches, nm: &str) -> uint {
opt_vals(mm, nm).len()
}
/// Returns true if any of several options were matched
pub fn opts_present(mm: &Matches, names: &[~str]) -> bool {
for names.each |nm| {
match find_opt(mm.opts, mkname(*nm)) {
Some(id) if !mm.vals[id].is_empty() => return true,
_ => (),
};
}
false
}
/**
* Returns the string argument supplied to a matching option
*
* Fails if the option was not matched or if the match did not take an
* argument
*/
pub fn opt_str(mm: &Matches, nm: &str) -> ~str {
return match opt_val(mm, nm) { Val(s) => s, _ => fail!() };
}
/**
* Returns the string argument supplied to one of several matching options
*
* Fails if the no option was provided from the given list, or if the no such
* option took an argument
*/
pub fn opts_str(mm: &Matches, names: &[~str]) -> ~str {
for names.each |nm| {
match opt_val(mm, *nm) {
Val(ref s) => return copy *s,
_ => ()
}
}
fail!();
}
/**
* Returns a vector of the arguments provided to all matches of the given
* option.
*
* Used when an option accepts multiple values.
*/
pub fn opt_strs(mm: &Matches, nm: &str) -> ~[~str] {
let mut acc: ~[~str] = ~[];
for vec::each(opt_vals(mm, nm)) |v| {
match *v { Val(ref s) => acc.push(copy *s), _ => () }
}
return acc;
}
/// Returns the string argument supplied to a matching option or none
pub fn opt_maybe_str(mm: &Matches, nm: &str) -> Option<~str> {
let vals = opt_vals(mm, nm);
if vals.is_empty() { return None::<~str>; }
return match vals[0] {
Val(ref s) => Some(copy *s),
_ => None
};
}
/**
* Returns the matching string, a default, or none
*
* Returns none if the option was not present, `def` if the option was
* present but no argument was provided, and the argument if the option was
* present and an argument was provided.
*/
pub fn opt_default(mm: &Matches, nm: &str, def: &str) -> Option<~str> {
let vals = opt_vals(mm, nm);
if vals.is_empty() { return None::<~str>; }
return match vals[0] { Val(ref s) => Some::<~str>(copy *s),
_ => Some::<~str>(str::to_owned(def)) }
}
#[deriving(Eq)]
pub enum FailType {
ArgumentMissing_,
UnrecognizedOption_,
OptionMissing_,
OptionDuplicated_,
UnexpectedArgument_,
}
/** A module which provides a way to specify descriptions and
* groups of short and long option names, together.
*/
pub mod groups {
use getopts::{HasArg, Long, Maybe, Multi, No, Occur, Opt, Optional, Req};
use getopts::{Short, Yes};
use core::str;
use core::vec;
/** one group of options, e.g., both -h and --help, along with
* their shared description and properties
*/
#[deriving(Eq)]
pub struct OptGroup {
short_name: ~str,
long_name: ~str,
hint: ~str,
desc: ~str,
hasarg: HasArg,
occur: Occur
}
/// Create a long option that is required and takes an argument
pub fn reqopt(short_name: &str, long_name: &str,
desc: &str, hint: &str) -> OptGroup {
let len = short_name.len();
assert!(len == 1 || len == 0);
return OptGroup { short_name: str::to_owned(short_name),
long_name: str::to_owned(long_name),
hint: str::to_owned(hint),
desc: str::to_owned(desc),
hasarg: Yes,
occur: Req};
}
/// Create a long option that is optional and takes an argument
pub fn optopt(short_name: &str, long_name: &str,
desc: &str, hint: &str) -> OptGroup {
let len = short_name.len();
assert!(len == 1 || len == 0);
return OptGroup {short_name: str::to_owned(short_name),
long_name: str::to_owned(long_name),
hint: str::to_owned(hint),
desc: str::to_owned(desc),
hasarg: Yes,
occur: Optional};
}
/// Create a long option that is optional and does not take an argument
pub fn optflag(short_name: &str, long_name: &str,
desc: &str) -> OptGroup {
let len = short_name.len();
assert!(len == 1 || len == 0);
return OptGroup {short_name: str::to_owned(short_name),
long_name: str::to_owned(long_name),
hint: ~"",
desc: str::to_owned(desc),
hasarg: No,
occur: Optional};
}
/// Create a long option that is optional and takes an optional argument
pub fn optflagopt(short_name: &str, long_name: &str,
desc: &str, hint: &str) -> OptGroup {
let len = short_name.len();
assert!(len == 1 || len == 0);
return OptGroup {short_name: str::to_owned(short_name),
long_name: str::to_owned(long_name),
hint: str::to_owned(hint),
desc: str::to_owned(desc),
hasarg: Maybe,
occur: Optional};
}
/**
* Create a long option that is optional, takes an argument, and may occur
* multiple times
*/
pub fn optmulti(short_name: &str, long_name: &str,
desc: &str, hint: &str) -> OptGroup {
let len = short_name.len();
assert!(len == 1 || len == 0);
return OptGroup {short_name: str::to_owned(short_name),
long_name: str::to_owned(long_name),
hint: str::to_owned(hint),
desc: str::to_owned(desc),
hasarg: Yes,
occur: Multi};
}
// translate OptGroup into Opt
// (both short and long names correspond to different Opts)
pub fn long_to_short(lopt: &OptGroup) -> ~[Opt] {
let OptGroup{short_name: short_name,
long_name: long_name,
hasarg: hasarg,
occur: occur,
_} = copy *lopt;
match (short_name.len(), long_name.len()) {
(0,0) => fail!("this long-format option was given no name"),
(0,_) => ~[Opt {name: Long((long_name)),
hasarg: hasarg,
occur: occur}],
(1,0) => ~[Opt {name: Short(str::char_at(short_name, 0)),
hasarg: hasarg,
occur: occur}],
(1,_) => ~[Opt {name: Short(str::char_at(short_name, 0)),
hasarg: hasarg,
occur: occur},
Opt {name: Long((long_name)),
hasarg: hasarg,
occur: occur}],
(_,_) => fail!("something is wrong with the long-form opt")
}
}
/*
* Parse command line args with the provided long format options
*/
pub fn getopts(args: &[~str], opts: &[OptGroup]) -> ::getopts::Result {
::getopts::getopts(args, vec::flat_map(opts, long_to_short))
}
/**
* Derive a usage message from a set of long options
*/
pub fn usage(brief: &str, opts: &[OptGroup]) -> ~str {
let desc_sep = ~"\n" + str::repeat(" ", 24);
let rows = vec::map(opts, |optref| {
let OptGroup{short_name: short_name,
long_name: long_name,
hint: hint,
desc: desc,
hasarg: hasarg,
_} = copy *optref;
let mut row = str::repeat(" ", 4);
// short option
row += match short_name.len() {
0 => ~"",
1 => ~"-" + short_name + " ",
_ => fail!("the short name should only be 1 ascii char long"),
};
// long option
row += match long_name.len() {
0 => ~"",
_ => ~"--" + long_name + " ",
};
// arg
row += match hasarg {
No => ~"",
Yes => hint,
Maybe => ~"[" + hint + "]",
};
// FIXME: #5516
// here we just need to indent the start of the description
let rowlen = row.len();
row += if rowlen < 24 {
str::repeat(" ", 24 - rowlen)
} else {
copy desc_sep
};
// Normalize desc to contain words separated by one space character
let mut desc_normalized_whitespace = ~"";
for str::each_word(desc) |word| {
desc_normalized_whitespace.push_str(word);
desc_normalized_whitespace.push_char(' ');
}
// FIXME: #5516
let mut desc_rows = ~[];
for str::each_split_within(desc_normalized_whitespace, 54) |substr| {
desc_rows.push(substr.to_owned());
}
// FIXME: #5516
// wrapped description
row += str::connect(desc_rows, desc_sep);
row
});
return str::to_owned(brief) +
"\n\nOptions:\n" +
str::connect(rows, "\n") +
"\n\n";
}
} // end groups module
#[cfg(test)]
mod tests {
use getopts::groups::OptGroup;
use getopts::*;
use core::result::{Err, Ok};
use core::result;
fn check_fail_type(f: Fail_, ft: FailType) {
match f {
ArgumentMissing(_) => assert!(ft == ArgumentMissing_),
UnrecognizedOption(_) => assert!(ft == UnrecognizedOption_),
OptionMissing(_) => assert!(ft == OptionMissing_),
OptionDuplicated(_) => assert!(ft == OptionDuplicated_),
UnexpectedArgument(_) => assert!(ft == UnexpectedArgument_)
}
}
// Tests for reqopt
#[test]
fn test_reqopt_long() {
let args = ~[~"--test=20"];
let opts = ~[reqopt("test")];
let rs = getopts(args, opts);
match rs {
Ok(ref m) => {
assert!((opt_present(m, "test")));
assert_eq!(opt_str(m, "test"), ~"20");
}
_ => { fail!("test_reqopt_long failed"); }
}
}
#[test]
fn test_reqopt_long_missing() {
let args = ~[~"blah"];
let opts = ~[reqopt("test")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionMissing_),
_ => fail!()
}
}
#[test]
fn test_reqopt_long_no_arg() {
let args = ~[~"--test"];
let opts = ~[reqopt("test")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
}
}
#[test]
fn test_reqopt_long_multi() {
let args = ~[~"--test=20", ~"--test=30"];
let opts = ~[reqopt("test")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
_ => fail!()
}
}
#[test]
fn test_reqopt_short() {
let args = ~[~"-t", ~"20"];
let opts = ~[reqopt("t")];
let rs = getopts(args, opts);
match rs {
Ok(ref m) => {
assert!((opt_present(m, "t")));
assert_eq!(opt_str(m, "t"), ~"20");
}
_ => fail!()
}
}
#[test]
fn test_reqopt_short_missing() {
let args = ~[~"blah"];
let opts = ~[reqopt("t")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionMissing_),
_ => fail!()
}
}
#[test]
fn test_reqopt_short_no_arg() {
let args = ~[~"-t"];
let opts = ~[reqopt("t")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
}
}
#[test]
fn test_reqopt_short_multi() {
let args = ~[~"-t", ~"20", ~"-t", ~"30"];
let opts = ~[reqopt("t")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
_ => fail!()
}
}
// Tests for optopt
#[test]
fn test_optopt_long() {
let args = ~[~"--test=20"];
let opts = ~[optopt("test")];
let rs = getopts(args, opts);
match rs {
Ok(ref m) => {
assert!((opt_present(m, "test")));
assert_eq!(opt_str(m, "test"), ~"20");
}
_ => fail!()
}
}
#[test]
fn test_optopt_long_missing() {
let args = ~[~"blah"];
let opts = ~[optopt("test")];
let rs = getopts(args, opts);
match rs {
Ok(ref m) => assert!(!opt_present(m, "test")),
_ => fail!()
}
}
#[test]
fn test_optopt_long_no_arg() {
let args = ~[~"--test"];
let opts = ~[optopt("test")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
}
}
#[test]
fn test_optopt_long_multi() {
let args = ~[~"--test=20", ~"--test=30"];
let opts = ~[optopt("test")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
_ => fail!()
}
}
#[test]
fn test_optopt_short() {
let args = ~[~"-t", ~"20"];
let opts = ~[optopt("t")];
let rs = getopts(args, opts);
match rs {
Ok(ref m) => {
assert!((opt_present(m, "t")));
assert_eq!(opt_str(m, "t"), ~"20");
}
_ => fail!()
}
}
#[test]
fn test_optopt_short_missing() {
let args = ~[~"blah"];
let opts = ~[optopt("t")];
let rs = getopts(args, opts);
match rs {
Ok(ref m) => assert!(!opt_present(m, "t")),
_ => fail!()
}
}
#[test]
fn test_optopt_short_no_arg() {
let args = ~[~"-t"];
let opts = ~[optopt("t")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, ArgumentMissing_),
_ => fail!()
}
}
#[test]
fn test_optopt_short_multi() {
let args = ~[~"-t", ~"20", ~"-t", ~"30"];
let opts = ~[optopt("t")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
_ => fail!()
}
}
// Tests for optflag
#[test]
fn test_optflag_long() {
let args = ~[~"--test"];
let opts = ~[optflag("test")];
let rs = getopts(args, opts);
match rs {
Ok(ref m) => assert!(opt_present(m, "test")),
_ => fail!()
}
}
#[test]
fn test_optflag_long_missing() {
let args = ~[~"blah"];
let opts = ~[optflag("test")];
let rs = getopts(args, opts);
match rs {
Ok(ref m) => assert!(!opt_present(m, "test")),
_ => fail!()
}
}
#[test]
fn test_optflag_long_arg() {
let args = ~[~"--test=20"];
let opts = ~[optflag("test")];
let rs = getopts(args, opts);
match rs {
Err(f) => {
error!(fail_str(copy f));
check_fail_type(f, UnexpectedArgument_);
}
_ => fail!()
}
}
#[test]
fn test_optflag_long_multi() {
let args = ~[~"--test", ~"--test"];
let opts = ~[optflag("test")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
_ => fail!()
}
}
#[test]
fn test_optflag_short() {
let args = ~[~"-t"];
let opts = ~[optflag("t")];
let rs = getopts(args, opts);
match rs {
Ok(ref m) => assert!(opt_present(m, "t")),
_ => fail!()
}
}
#[test]
fn test_optflag_short_missing() {
let args = ~[~"blah"];
let opts = ~[optflag("t")];
let rs = getopts(args, opts);
match rs {
Ok(ref m) => assert!(!opt_present(m, "t")),
_ => fail!()
}
}
#[test]
fn test_optflag_short_arg() {
let args = ~[~"-t", ~"20"];
let opts = ~[optflag("t")];
let rs = getopts(args, opts);
match rs {
Ok(ref m) => {
// The next variable after the flag is just a free argument
assert!(m.free[0] == ~"20");
}
_ => fail!()
}
}
#[test]
fn test_optflag_short_multi() {
let args = ~[~"-t", ~"-t"];
let opts = ~[optflag("t")];
let rs = getopts(args, opts);
match rs {
Err(f) => check_fail_type(f, OptionDuplicated_),
_ => fail!()
}
}
// Tests for optflagmulti
#[test]
fn test_optflagmulti_short1() {
let args = ~[~"-v"];
let opts = ~[optflagmulti("v")];
let rs = getopts(args, opts);
match rs {
Ok(ref m) => {
assert_eq!(opt_count(m, "v"), 1);
}
_ => fail!()
}
}
#[test]
fn test_optflagmulti_short2a() {
let args = ~[~"-v", ~"-v"];
let opts = ~[optflagmulti("v")];
let rs = getopts(args, opts);
match rs {
Ok(ref m) => {
assert_eq!(opt_count(m, "v"), 2);
}
_ => fail!()
}
}
#[test]
fn test_optflagmulti_short2b() {
let args = ~[~"-vv"];