Skip to content

Commit 574b3e8

Browse files
committed
Add some convenience helpers to getopts. Close #1837.
1 parent 89aa282 commit 574b3e8

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

src/libstd/getopts.rs

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,9 @@ export match;
7777
export fail_;
7878
export fail_str;
7979
export opt_present;
80+
export opts_present;
8081
export opt_str;
82+
export opts_str;
8183
export opt_strs;
8284
export opt_maybe_str;
8385
export opt_default;
@@ -292,6 +294,18 @@ fn opt_present(m: match, nm: str) -> bool {
292294
ret vec::len::<optval>(opt_vals(m, nm)) > 0u;
293295
}
294296

297+
#[doc = "Returns true if any of several options were matched"]
298+
fn opts_present(m: match, names: [str]) -> bool {
299+
for vec::each(names) {|nm|
300+
alt find_opt(m.opts, mkname(nm)) {
301+
some(_) { ret true; }
302+
_ { }
303+
}
304+
}
305+
ret false;
306+
}
307+
308+
295309
#[doc = "
296310
Returns the string argument supplied to a matching option
297311
@@ -301,6 +315,23 @@ fn opt_str(m: match, nm: str) -> str {
301315
ret alt opt_val(m, nm) { val(s) { s } _ { fail } };
302316
}
303317

318+
#[doc = "
319+
Returns the string argument supplied to one of several matching options
320+
321+
Fails if the no option was provided from the given list, or if the no such
322+
option took an argument
323+
"]
324+
fn opts_str(m: match, names: [str]) -> str {
325+
for vec::each(names) {|nm|
326+
alt opt_val(m, nm) {
327+
val(s) { ret s }
328+
_ { }
329+
}
330+
}
331+
fail;
332+
}
333+
334+
304335
#[doc = "
305336
Returns a vector of the arguments provided to all matches of the given option.
306337
@@ -805,6 +836,26 @@ mod tests {
805836
}
806837
}
807838

839+
#[test]
840+
fn test_multi() {
841+
let args = ["-e", "foo", "--encrypt", "foo"];
842+
let opts = [optopt("e"), optopt("encrypt")];
843+
let match = alt getopts(args, opts) {
844+
result::ok(m) { m }
845+
result::err(f) { fail; }
846+
};
847+
assert opts_present(match, ["e"]);
848+
assert opts_present(match, ["encrypt"]);
849+
assert opts_present(match, ["encrypt", "e"]);
850+
assert opts_present(match, ["e", "encrypt"]);
851+
assert !opts_present(match, ["thing"]);
852+
assert !opts_present(match, []);
853+
854+
assert opts_str(match, ["e"]) == "foo";
855+
assert opts_str(match, ["encrypt"]) == "foo";
856+
assert opts_str(match, ["e", "encrypt"]) == "foo";
857+
assert opts_str(match, ["encrypt", "e"]) == "foo";
858+
}
808859
}
809860

810861
// Local Variables:

0 commit comments

Comments
 (0)