提交 0642cbbd 编写于 作者: H Huon Wilson

getopts: format failure messages with `Show`.

This obsoletes the old `to_err_msg` method. Replace

    println!("Error: {}", failure.to_err_msg())

    let string = failure.to_err_msg();

with

    println!("Error: {}", failure)

    let string = failure.to_str();

[breaking-change]
上级 3851d68a
...@@ -110,7 +110,7 @@ pub fn parse_config(args: Vec<String> ) -> Config { ...@@ -110,7 +110,7 @@ pub fn parse_config(args: Vec<String> ) -> Config {
let matches = let matches =
&match getopts::getopts(args_.as_slice(), groups.as_slice()) { &match getopts::getopts(args_.as_slice(), groups.as_slice()) {
Ok(m) => m, Ok(m) => m,
Err(f) => fail!("{}", f.to_err_msg()) Err(f) => fail!("{}", f)
}; };
if matches.opt_present("h") || matches.opt_present("help") { if matches.opt_present("h") || matches.opt_present("help") {
......
...@@ -61,7 +61,7 @@ ...@@ -61,7 +61,7 @@
//! ]; //! ];
//! let matches = match getopts(args.tail(), opts) { //! let matches = match getopts(args.tail(), opts) {
//! Ok(m) => { m } //! Ok(m) => { m }
//! Err(f) => { fail!(f.to_err_msg()) } //! Err(f) => { fail!(f.to_str()) }
//! }; //! };
//! if matches.opt_present("h") { //! if matches.opt_present("h") {
//! print_usage(program.as_slice(), opts); //! print_usage(program.as_slice(), opts);
...@@ -94,6 +94,7 @@ ...@@ -94,6 +94,7 @@
#[cfg(test, not(stage0))] #[phase(plugin, link)] extern crate log; #[cfg(test, not(stage0))] #[phase(plugin, link)] extern crate log;
use std::cmp::PartialEq; use std::cmp::PartialEq;
use std::fmt;
use std::result::{Err, Ok}; use std::result::{Err, Ok};
use std::result; use std::result;
use std::string::String; use std::string::String;
...@@ -182,9 +183,9 @@ pub struct Matches { ...@@ -182,9 +183,9 @@ pub struct Matches {
} }
/// The type returned when the command line does not conform to the /// The type returned when the command line does not conform to the
/// expected format. Call the `to_err_msg` method to retrieve the /// expected format. Use the `Show` implementation to output detailed
/// error as a string. /// information.
#[deriving(Clone, PartialEq, Show)] #[deriving(Clone, PartialEq)]
pub enum Fail_ { pub enum Fail_ {
/// The option requires an argument but none was passed. /// The option requires an argument but none was passed.
ArgumentMissing(String), ArgumentMissing(String),
...@@ -498,22 +499,29 @@ pub fn opt(short_name: &str, ...@@ -498,22 +499,29 @@ pub fn opt(short_name: &str,
impl Fail_ { impl Fail_ {
/// Convert a `Fail_` enum into an error string. /// Convert a `Fail_` enum into an error string.
#[deprecated="use `Show` (`{}` format specifier)"]
pub fn to_err_msg(self) -> String { pub fn to_err_msg(self) -> String {
match self { self.to_str()
}
}
impl fmt::Show for Fail_ {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
match *self {
ArgumentMissing(ref nm) => { ArgumentMissing(ref nm) => {
format!("Argument to option '{}' missing.", *nm) write!(f, "Argument to option '{}' missing.", *nm)
} }
UnrecognizedOption(ref nm) => { UnrecognizedOption(ref nm) => {
format!("Unrecognized option: '{}'.", *nm) write!(f, "Unrecognized option: '{}'.", *nm)
} }
OptionMissing(ref nm) => { OptionMissing(ref nm) => {
format!("Required option '{}' missing.", *nm) write!(f, "Required option '{}' missing.", *nm)
} }
OptionDuplicated(ref nm) => { OptionDuplicated(ref nm) => {
format!("Option '{}' given more than once.", *nm) write!(f, "Option '{}' given more than once.", *nm)
} }
UnexpectedArgument(ref nm) => { UnexpectedArgument(ref nm) => {
format!("Option '{}' does not take an argument.", *nm) write!(f, "Option '{}' does not take an argument.", *nm)
} }
} }
} }
...@@ -522,8 +530,9 @@ pub fn to_err_msg(self) -> String { ...@@ -522,8 +530,9 @@ pub fn to_err_msg(self) -> String {
/// Parse command line arguments according to the provided options. /// Parse command line arguments according to the provided options.
/// ///
/// On success returns `Ok(Opt)`. Use methods such as `opt_present` /// On success returns `Ok(Opt)`. Use methods such as `opt_present`
/// `opt_str`, etc. to interrogate results. Returns `Err(Fail_)` on failure. /// `opt_str`, etc. to interrogate results. Returns `Err(Fail_)` on
/// Use `to_err_msg` to get an error message. /// failure: use the `Show` implementation of `Fail_` to display
/// information about it.
pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result { pub fn getopts(args: &[String], optgrps: &[OptGroup]) -> Result {
let opts: Vec<Opt> = optgrps.iter().map(|x| x.long_to_short()).collect(); let opts: Vec<Opt> = optgrps.iter().map(|x| x.long_to_short()).collect();
let n_opts = opts.len(); let n_opts = opts.len();
...@@ -1110,7 +1119,6 @@ fn test_optflag_long_arg() { ...@@ -1110,7 +1119,6 @@ fn test_optflag_long_arg() {
let rs = getopts(args.as_slice(), opts.as_slice()); let rs = getopts(args.as_slice(), opts.as_slice());
match rs { match rs {
Err(f) => { Err(f) => {
error!("{:?}", f.clone().to_err_msg());
check_fail_type(f, UnexpectedArgument_); check_fail_type(f, UnexpectedArgument_);
} }
_ => fail!() _ => fail!()
......
...@@ -792,7 +792,7 @@ fn test_switch_implies_cfg_test() { ...@@ -792,7 +792,7 @@ fn test_switch_implies_cfg_test() {
let matches = let matches =
&match getopts(["--test".to_string()], optgroups().as_slice()) { &match getopts(["--test".to_string()], optgroups().as_slice()) {
Ok(m) => m, Ok(m) => m,
Err(f) => fail!("test_switch_implies_cfg_test: {}", f.to_err_msg()) Err(f) => fail!("test_switch_implies_cfg_test: {}", f)
}; };
let sessopts = build_session_options(matches); let sessopts = build_session_options(matches);
let sess = build_session(sessopts, None); let sess = build_session(sessopts, None);
...@@ -809,8 +809,7 @@ fn test_switch_implies_cfg_test_unless_cfg_test() { ...@@ -809,8 +809,7 @@ fn test_switch_implies_cfg_test_unless_cfg_test() {
optgroups().as_slice()) { optgroups().as_slice()) {
Ok(m) => m, Ok(m) => m,
Err(f) => { Err(f) => {
fail!("test_switch_implies_cfg_test_unless_cfg_test: {}", fail!("test_switch_implies_cfg_test_unless_cfg_test: {}", f)
f.to_err_msg());
} }
}; };
let sessopts = build_session_options(matches); let sessopts = build_session_options(matches);
......
...@@ -205,7 +205,7 @@ pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> { ...@@ -205,7 +205,7 @@ pub fn handle_options(mut args: Vec<String>) -> Option<getopts::Matches> {
match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) { match getopts::getopts(args.as_slice(), config::optgroups().as_slice()) {
Ok(m) => m, Ok(m) => m,
Err(f) => { Err(f) => {
early_error(f.to_err_msg().as_slice()); early_error(f.to_str().as_slice());
} }
}; };
......
...@@ -148,7 +148,7 @@ pub fn main_args(args: &[String]) -> int { ...@@ -148,7 +148,7 @@ pub fn main_args(args: &[String]) -> int {
let matches = match getopts::getopts(args.tail(), opts().as_slice()) { let matches = match getopts::getopts(args.tail(), opts().as_slice()) {
Ok(m) => m, Ok(m) => m,
Err(err) => { Err(err) => {
println!("{}", err.to_err_msg()); println!("{}", err);
return 1; return 1;
} }
}; };
......
...@@ -367,7 +367,7 @@ pub fn parse_opts(args: &[String]) -> Option<OptRes> { ...@@ -367,7 +367,7 @@ pub fn parse_opts(args: &[String]) -> Option<OptRes> {
let matches = let matches =
match getopts::getopts(args_.as_slice(), optgroups().as_slice()) { match getopts::getopts(args_.as_slice(), optgroups().as_slice()) {
Ok(m) => m, Ok(m) => m,
Err(f) => return Some(Err(f.to_err_msg().to_string())) Err(f) => return Some(Err(f.to_str()))
}; };
if matches.opt_present("h") { usage(args[0].as_slice()); return None; } if matches.opt_present("h") { usage(args[0].as_slice()); return None; }
......
...@@ -20,7 +20,7 @@ pub fn main() { ...@@ -20,7 +20,7 @@ pub fn main() {
match getopts(args.as_slice(), opts.as_slice()) { match getopts(args.as_slice(), opts.as_slice()) {
Ok(ref m) => Ok(ref m) =>
assert!(!m.opt_present("b")), assert!(!m.opt_present("b")),
Err(ref f) => fail!("{:?}", (*f).clone().to_err_msg()) Err(ref f) => fail!("{}", *f)
}; };
} }
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册