From 3636afc401c2caa966efb5b1869ef4f1ed3384aa Mon Sep 17 00:00:00 2001 From: Kevin K Date: Fri, 10 Apr 2015 10:46:07 -0400 Subject: [PATCH] feat(usage): add ability to get usage string for subcommands too You can now get the usage even for sub-commands by calling the usage() method. Breaking Change ArgMatches::usage() now returns a slice (no longer an Option<&str>) This is to improve ergonomics, as there should always be at least a default usage statement, there should never be None --- src/app.rs | 4 ++-- src/args/argmatches.rs | 10 ++++++---- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/app.rs b/src/app.rs index 117dc373168..6941b43c627 100644 --- a/src/app.rs +++ b/src/app.rs @@ -706,7 +706,6 @@ impl<'a, 'v, 'ab, 'u, 'ar> App<'a, 'v, 'ab, 'u, 'ar>{ } } } - matches.usage = Some(self.create_usage()); self.get_matches_from(&mut matches, &mut it ); matches @@ -879,7 +878,7 @@ impl<'a, 'v, 'ab, 'u, 'ar> App<'a, 'v, 'ab, 'u, 'ar>{ } } } else { - self.report_error(format!("Positional argument \"{}\" was found, but {} wasn't expecting any", arg, self.name), true, true); + self.report_error(format!("Argument \"{}\" isn't a valid argument for {}", arg, self.bin_name.clone().unwrap_or(self.name.clone())), true, true); } } } @@ -899,6 +898,7 @@ impl<'a, 'v, 'ab, 'u, 'ar> App<'a, 'v, 'ab, 'u, 'ar>{ true, true); } + matches.usage = Some(self.create_usage()); if let Some(sc_name) = subcmd_name { if let Some(ref mut sc) = self.subcommands.get_mut(&sc_name) { diff --git a/src/args/argmatches.rs b/src/args/argmatches.rs index 8bae4ace1d1..d6c416af079 100644 --- a/src/args/argmatches.rs +++ b/src/args/argmatches.rs @@ -266,7 +266,7 @@ impl<'a> ArgMatches<'a> { ("", None) } - /// Returns a slice of the default usage for the *top level parent App only* + /// Returns a slice of the usage /// /// /// # Example @@ -276,10 +276,12 @@ impl<'a> ArgMatches<'a> { /// # let app_matches = App::new("myapp").subcommand(SubCommand::new("test")).get_matches(); /// println!("{}",app_matches.usage().unwrap()); /// ``` - pub fn usage(&self) -> Option<&str> { + pub fn usage(&self) -> &str { if let Some( ref u ) = self.usage { - return Some(&u[..]); + return &u[..]; } - None + + // Should be un-reachable + "" } } \ No newline at end of file