@@ -4,12 +4,12 @@ Simple getopt alternative.
4
4
Construct a vector of options, either by using reqopt, optopt, and optflag or
5
5
by building them from components yourself, and pass them to getopts, along
6
6
with a vector of actual arguments (not including argv[0]). You'll either get a
7
- failure code back, or a match. You'll have to verify whether the amount of
7
+ failure code back, or a match. You'll have to verify whether the amount of
8
8
'free' arguments in the match is what you expect. Use opt_* accessors to get
9
9
argument values out of the match object.
10
10
11
11
Single-character options are expected to appear on the command line with a
12
- single preceeding dash; multiple-character options are expected to be
12
+ single preceding dash; multiple-character options are expected to be
13
13
proceeded by two dashes. Options that expect an argument accept their argument
14
14
following either a space or an equals sign.
15
15
@@ -19,27 +19,45 @@ The following example shows simple command line parsing for an application
19
19
that requires an input file to be specified, accepts an optional output file
20
20
name following -o, and accepts both -h and --help as optional flags.
21
21
22
+ use std;
23
+ import std::getopts::{optopt,optflag,getopts,opt_present,opt_maybe_str,
24
+ fail_str};
25
+
26
+ fn do_work(in: str, out: option<str>) {
27
+ // ...
28
+ }
29
+
30
+ fn print_usage(program: str) {
31
+ io::println(\" Usage: \" + program + \" [options]\" );
32
+ io::println(\" -o\t \t Output\" );
33
+ io::println(\" -h --help\t Usage\" );
34
+ }
35
+
22
36
fn main(args: [str]) {
37
+ check vec::is_not_empty(args);
38
+
39
+ let program : str = vec::head(args);
40
+
23
41
let opts = [
24
42
optopt(\" o\" ),
25
43
optflag(\" h\" ),
26
44
optflag(\" help\" )
27
45
];
28
- let match = alt getopts(vec::shift (args), opts) {
29
- ok(m) { m }
30
- err(f) { fail fail_str(f) }
46
+ let match = alt getopts(vec::tail (args), opts) {
47
+ result:: ok(m) { m }
48
+ result:: err(f) { fail fail_str(f) }
31
49
};
32
50
if opt_present(match, \" h\" ) || opt_present(match, \" help\" ) {
33
- print_usage();
51
+ print_usage(program );
34
52
ret;
35
53
}
36
54
let output = opt_maybe_str(match, \" o\" );
37
- let input = if ! vec::is_empty (match.free) {
55
+ let input = if vec::is_not_empty (match.free) {
38
56
match.free[0]
39
57
} else {
40
- print_usage();
58
+ print_usage(program );
41
59
ret;
42
- }
60
+ };
43
61
do_work(input, output);
44
62
}
45
63
0 commit comments