Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for options that take no arguments and may be repeated. #3998

Merged
merged 1 commit into from
Nov 18, 2012
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
75 changes: 75 additions & 0 deletions src/libstd/getopts.rs
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,11 @@ pub fn optflag(name: &str) -> Opt {
return {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 {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 {name: mkname(name), hasarg: Maybe, occur: Optional};
Expand Down Expand Up @@ -417,6 +422,11 @@ pub fn opt_present(mm: Matches, nm: &str) -> bool {
return vec::len::<Optval>(opt_vals(mm, nm)) > 0u;
}

/// Returns the number of times an option was matched
pub fn opt_count(mm: Matches, nm: &str) -> uint {
return vec::len::<Optval>(opt_vals(mm, nm));
}

/// Returns true if any of several options were matched
pub fn opts_present(mm: Matches, names: &[~str]) -> bool {
for vec::each(names) |nm| {
Expand Down Expand Up @@ -1003,6 +1013,71 @@ mod tests {
}
}

// Tests for optflagmulti
#[test]
fn test_optflagmulti_short1() {
let args = ~[~"-v"];
let opts = ~[optflagmulti(~"v")];
let rs = getopts(args, opts);
match rs {
Ok(copy m) => {
assert (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(copy m) => {
assert (opt_count(m, ~"v") == 2);
}
_ => fail
}
}

#[test]
fn test_optflagmulti_short2b() {
let args = ~[~"-vv"];
let opts = ~[optflagmulti(~"v")];
let rs = getopts(args, opts);
match rs {
Ok(copy m) => {
assert (opt_count(m, ~"v") == 2);
}
_ => fail
}
}

#[test]
fn test_optflagmulti_long1() {
let args = ~[~"--verbose"];
let opts = ~[optflagmulti(~"verbose")];
let rs = getopts(args, opts);
match rs {
Ok(copy m) => {
assert (opt_count(m, ~"verbose") == 1);
}
_ => fail
}
}

#[test]
fn test_optflagmulti_long2() {
let args = ~[~"--verbose", ~"--verbose"];
let opts = ~[optflagmulti(~"verbose")];
let rs = getopts(args, opts);
match rs {
Ok(copy m) => {
assert (opt_count(m, ~"verbose") == 2);
}
_ => fail
}
}

// Tests for optmulti
#[test]
Expand Down