diff options
| author | Yuri Kunde Schlesner <yuriks@yuriks.net> | 2014-02-02 18:52:51 -0200 |
|---|---|---|
| committer | Yuri Kunde Schlesner <yuriks@yuriks.net> | 2014-02-02 18:58:47 -0200 |
| commit | 65a6c7c12cba28ba41c64d7e6a6d66502aeeeb52 (patch) | |
| tree | 1b92c19bba20a95348cc8a8f7f3b2968e1d6f426 | |
| parent | 8d7bd499d2c01dc79d163a7b415a93ab8c22d785 (diff) | |
| download | rust-65a6c7c12cba28ba41c64d7e6a6d66502aeeeb52.tar.gz rust-65a6c7c12cba28ba41c64d7e6a6d66502aeeeb52.zip | |
Add `extra::getopts::short_usage`
This complements `usage` by auto-generating a short one-liner summary of the options.
| -rw-r--r-- | src/libextra/getopts.rs | 64 |
1 files changed, 64 insertions, 0 deletions
diff --git a/src/libextra/getopts.rs b/src/libextra/getopts.rs index 4293f04795e..f29caec5d33 100644 --- a/src/libextra/getopts.rs +++ b/src/libextra/getopts.rs @@ -675,6 +675,51 @@ pub mod groups { ::getopts::getopts(args, opts.map(|x| x.long_to_short())) } + fn format_option(opt: &OptGroup) -> ~str { + let mut line = ~""; + + if opt.occur != Req { + line.push_char('['); + } + + // Use short_name is possible, but fallback to long_name. + if opt.short_name.len() > 0 { + line.push_char('-'); + line.push_str(opt.short_name); + } else { + line.push_str("--"); + line.push_str(opt.long_name); + } + + if opt.hasarg != No { + line.push_char(' '); + if opt.hasarg == Maybe { + line.push_char('['); + } + line.push_str(opt.hint); + if opt.hasarg == Maybe { + line.push_char(']'); + } + } + + if opt.occur != Req { + line.push_char(']'); + } + if opt.occur == Multi { + line.push_str(".."); + } + + line + } + + /// Derive a short one-line usage summary from a set of long options. + pub fn short_usage(program_name: &str, opts: &[OptGroup]) -> ~str { + let mut line = ~"Usage: " + program_name + " "; + line.push_str(opts.iter().map(format_option).to_owned_vec().connect(" ")); + + line + } + /// Derive a usage message from a set of long options. pub fn usage(brief: &str, opts: &[OptGroup]) -> ~str { @@ -1637,4 +1682,23 @@ Options: debug!("generated: <<{}>>", usage); assert!(usage == expected) } + + #[test] + fn test_short_usage() { + let optgroups = ~[ + groups::reqopt("b", "banana", "Desc", "VAL"), + groups::optopt("a", "012345678901234567890123456789", + "Desc", "VAL"), + groups::optflag("k", "kiwi", "Desc"), + groups::optflagopt("p", "", "Desc", "VAL"), + groups::optmulti("l", "", "Desc", "VAL"), + ]; + + let expected = ~"Usage: fruits -b VAL [-a VAL] [-k] [-p [VAL]] [-l VAL].."; + let generated_usage = groups::short_usage("fruits", optgroups); + + debug!("expected: <<{}>>", expected); + debug!("generated: <<{}>>", generated_usage); + assert_eq!(generated_usage, expected); + } } |
