From ddd2c72befab8d8a803519f69fda0af8f2f1e1e6 Mon Sep 17 00:00:00 2001 From: sigoden Date: Sat, 8 Jun 2024 13:15:27 +0000 Subject: [PATCH] refactor: improve invalid subcommand error message --- src/matcher.rs | 16 +++++++++++----- ...integration__main_fn__global_without_arg.snap | 4 +--- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/src/matcher.rs b/src/matcher.rs index b86c865b..fdc5cc17 100644 --- a/src/matcher.rs +++ b/src/matcher.rs @@ -61,7 +61,7 @@ pub(crate) enum MatchError { DisplayHelp, DisplaySubcommandHelp(String), DisplayVersion, - InvalidSubcommand, + InvalidSubcommand(Option), UnknownArgument(usize, String), MissingRequiredArguments(usize, Vec), MissingRequiredEnvironments(Vec), @@ -798,10 +798,12 @@ impl<'a, 'b, T: Runtime> Matcher<'a, 'b, T> { if self.positional_args.is_empty() && last_args.is_empty() { return Some(MatchError::DisplayHelp); } else { - return Some(MatchError::InvalidSubcommand); + return Some(MatchError::InvalidSubcommand(None)); } } else if last_cmd.positional_params.is_empty() && !self.positional_args.is_empty() { - return Some(MatchError::InvalidSubcommand); + return Some(MatchError::InvalidSubcommand( + self.positional_args.first().map(|v| v.to_string()), + )); } } @@ -980,13 +982,17 @@ impl<'a, 'b, T: Runtime> Matcher<'a, 'b, T> { let cmd = self.last_cmd(); cmd.render_version() } - MatchError::InvalidSubcommand => { + MatchError::InvalidSubcommand(name) => { exit = 1; let cmd = self.last_cmd(); let cmd_str = cmd.cmd_paths().join("-"); let names = cmd.list_subcommand_names().join(", "); + let details = match name { + Some(name) => format!("but '{name}' is not one of them"), + None => "but one was not provided".to_string(), + }; format!( - r###"error: `{cmd_str}` requires a subcommand but one was not provided + r###"error: `{cmd_str}` requires a subcommand {details} [subcommands: {names}]"### ) } diff --git a/tests/snapshots/integration__main_fn__global_without_arg.snap b/tests/snapshots/integration__main_fn__global_without_arg.snap index 5e4d0d0a..3225eafc 100644 --- a/tests/snapshots/integration__main_fn__global_without_arg.snap +++ b/tests/snapshots/integration__main_fn__global_without_arg.snap @@ -7,7 +7,7 @@ prog abc # OUTPUT command cat >&2 <<-'EOF' -error: `prog` requires a subcommand but one was not provided +error: `prog` requires a subcommand but 'abc' is not one of them [subcommands: cmd] EOF exit 1 @@ -15,5 +15,3 @@ exit 1 # BUILD_OUTPUT error: `prog` requires a subcommand but one was not provided [subcommands: cmd] - -