Skip to content

Commit

Permalink
refactor: improve invalid subcommand error message
Browse files Browse the repository at this point in the history
  • Loading branch information
sigoden committed Jun 8, 2024
1 parent 97ec93b commit ddd2c72
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 8 deletions.
16 changes: 11 additions & 5 deletions src/matcher.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ pub(crate) enum MatchError {
DisplayHelp,
DisplaySubcommandHelp(String),
DisplayVersion,
InvalidSubcommand,
InvalidSubcommand(Option<String>),
UnknownArgument(usize, String),
MissingRequiredArguments(usize, Vec<String>),
MissingRequiredEnvironments(Vec<String>),
Expand Down Expand Up @@ -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()),
));
}
}

Expand Down Expand Up @@ -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}]"###
)
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,11 @@ 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

# BUILD_OUTPUT
error: `prog` requires a subcommand but one was not provided
[subcommands: cmd]


0 comments on commit ddd2c72

Please sign in to comment.