Skip to content

Commit

Permalink
Make Commander::run{_with_args} exit on errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Trung Nguyen committed May 29, 2020
1 parent 6b613a6 commit ed73d00
Show file tree
Hide file tree
Showing 4 changed files with 19 additions and 13 deletions.
3 changes: 1 addition & 2 deletions examples/clap_nested/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,5 @@ fn main() {
println!("No subcommand matched");
Ok(())
})
.run()
.unwrap();
.run();
}
17 changes: 12 additions & 5 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -80,8 +80,7 @@
//! println!("No subcommand matched");
//! Ok(())
//! })
//! .run()
//! .unwrap();
//! .run();
//! }
//! ```
//!
Expand Down Expand Up @@ -358,11 +357,19 @@ impl<'a, S: ?Sized, T: ?Sized> Commander<'a, S, T> {
}

impl<'a, T: ?Sized> Commander<'a, (), T> {
pub fn run(&self) -> Result {
self.run_with_args(std::env::args_os())
pub fn run(&self) {
self.run_result().unwrap_or_else(|error| error.exit())
}

pub fn run_with_args(
pub fn run_with_args(&self, args: impl IntoIterator<Item = impl Into<OsString> + Clone>) {
self.run_with_args_result(args).unwrap_or_else(|error| error.exit())
}

pub fn run_result(&self) -> Result {
self.run_with_args_result(std::env::args_os())
}

pub fn run_with_args_result(
&self,
args: impl IntoIterator<Item = impl Into<OsString> + Clone>,
) -> Result {
Expand Down
2 changes: 1 addition & 1 deletion tests/common/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ pub fn assert_output<T>(
out: &str,
use_stderr: bool,
) {
assert_result(commander.run_with_args(args), out, use_stderr);
assert_result(commander.run_with_args_result(args), out, use_stderr);
}

pub fn assert_result(res: Result<(), clap::Error>, out: &str, use_stderr: bool) {
Expand Down
10 changes: 5 additions & 5 deletions tests/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -66,13 +66,13 @@ fn two_level_commander() {
.add_cmd(show)
.add_cmd(what);

assert!(commander.run_with_args(&["program", "show"]).is_ok());
assert!(commander.run_with_args(&["program", "show", "foo"]).is_ok());
assert!(commander.run_with_args(&["program", "show", "bar"]).is_ok());
assert!(commander.run_with_args(&["program", "what"]).is_ok());
assert!(commander.run_with_args_result(&["program", "show"]).is_ok());
assert!(commander.run_with_args_result(&["program", "show", "foo"]).is_ok());
assert!(commander.run_with_args_result(&["program", "show", "bar"]).is_ok());
assert!(commander.run_with_args_result(&["program", "what"]).is_ok());

assert_result(
commander.run(),
commander.run_result(),
"error: program __VERSION__
__AUTHOR__
__DESC__
Expand Down

0 comments on commit ed73d00

Please sign in to comment.