Skip to content

Commit d8c4e78

Browse files
committed
auto merge of #12001 : yuriks/rust/getopts-tweaks, r=brson
This complements `usage` by auto-generating a short one-liner summary of the options. (First timer here, be gentle... :)
2 parents 8dc0680 + 65a6c7c commit d8c4e78

File tree

1 file changed

+64
-0
lines changed

1 file changed

+64
-0
lines changed

src/libextra/getopts.rs

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -675,6 +675,51 @@ pub mod groups {
675675
::getopts::getopts(args, opts.map(|x| x.long_to_short()))
676676
}
677677

678+
fn format_option(opt: &OptGroup) -> ~str {
679+
let mut line = ~"";
680+
681+
if opt.occur != Req {
682+
line.push_char('[');
683+
}
684+
685+
// Use short_name is possible, but fallback to long_name.
686+
if opt.short_name.len() > 0 {
687+
line.push_char('-');
688+
line.push_str(opt.short_name);
689+
} else {
690+
line.push_str("--");
691+
line.push_str(opt.long_name);
692+
}
693+
694+
if opt.hasarg != No {
695+
line.push_char(' ');
696+
if opt.hasarg == Maybe {
697+
line.push_char('[');
698+
}
699+
line.push_str(opt.hint);
700+
if opt.hasarg == Maybe {
701+
line.push_char(']');
702+
}
703+
}
704+
705+
if opt.occur != Req {
706+
line.push_char(']');
707+
}
708+
if opt.occur == Multi {
709+
line.push_str("..");
710+
}
711+
712+
line
713+
}
714+
715+
/// Derive a short one-line usage summary from a set of long options.
716+
pub fn short_usage(program_name: &str, opts: &[OptGroup]) -> ~str {
717+
let mut line = ~"Usage: " + program_name + " ";
718+
line.push_str(opts.iter().map(format_option).to_owned_vec().connect(" "));
719+
720+
line
721+
}
722+
678723
/// Derive a usage message from a set of long options.
679724
pub fn usage(brief: &str, opts: &[OptGroup]) -> ~str {
680725
@@ -1637,4 +1682,23 @@ Options:
16371682
debug!("generated: <<{}>>", usage);
16381683
assert!(usage == expected)
16391684
}
1685+
1686+
#[test]
1687+
fn test_short_usage() {
1688+
let optgroups = ~[
1689+
groups::reqopt("b", "banana", "Desc", "VAL"),
1690+
groups::optopt("a", "012345678901234567890123456789",
1691+
"Desc", "VAL"),
1692+
groups::optflag("k", "kiwi", "Desc"),
1693+
groups::optflagopt("p", "", "Desc", "VAL"),
1694+
groups::optmulti("l", "", "Desc", "VAL"),
1695+
];
1696+
1697+
let expected = ~"Usage: fruits -b VAL [-a VAL] [-k] [-p [VAL]] [-l VAL]..";
1698+
let generated_usage = groups::short_usage("fruits", optgroups);
1699+
1700+
debug!("expected: <<{}>>", expected);
1701+
debug!("generated: <<{}>>", generated_usage);
1702+
assert_eq!(generated_usage, expected);
1703+
}
16401704
}

0 commit comments

Comments
 (0)