Cleanup code for EarlyExit during help triggers

This commit is contained in:
topjohnwu
2025-10-18 20:32:59 -07:00
committed by John Wu
parent c94bd49a89
commit 52d8910bdd
3 changed files with 10 additions and 21 deletions

View File

@@ -525,21 +525,15 @@ pub trait DynamicSubCommand: Sized {
pub struct EarlyExit {
/// The output to display to the user of the commandline tool.
pub output: String,
/// Status of argument parsing.
///
/// `Ok` if the command was parsed successfully and the early exit is due
/// to a flag like `--help` causing early exit with output.
///
/// `Err` if the arguments were not successfully parsed.
// TODO replace with std::process::ExitCode when stable.
pub status: Result<(), ()>,
/// If the early exit is caused by help triggers.
pub is_help: bool,
}
impl From<String> for EarlyExit {
fn from(err_msg: String) -> Self {
Self {
output: err_msg,
status: Err(()),
is_help: false,
}
}
}
@@ -695,7 +689,6 @@ pub fn parse_struct_args(
mut parse_options: ParseStructOptions<'_>,
mut parse_positionals: ParseStructPositionals<'_>,
mut parse_subcommand: Option<ParseStructSubCommand<'_>>,
help_func: &dyn Fn() -> String,
) -> Result<(), EarlyExit> {
let mut help = false;
let mut remaining_args = args;
@@ -738,8 +731,8 @@ pub fn parse_struct_args(
if help {
Err(EarlyExit {
output: help_func(),
status: Ok(()),
output: String::new(),
is_help: true,
})
} else {
Ok(())
@@ -869,7 +862,7 @@ impl ParseStructPositionals<'_> {
} else {
Err(EarlyExit {
output: unrecognized_arg(arg),
status: Err(()),
is_help: false,
})
}
}

View File

@@ -374,8 +374,6 @@ fn impl_from_args_struct_from_args<'a>(
let help_triggers = get_help_triggers(type_attrs);
let help = quote! { String::new() };
let method_impl = quote_spanned! { impl_span =>
fn from_args(__cmd_name: &[&str], __args: &[&str])
-> std::result::Result<Self, argh::EarlyExit>
@@ -405,7 +403,6 @@ fn impl_from_args_struct_from_args<'a>(
last_is_greedy: #last_positional_is_greedy,
},
#parse_subcommands,
&|| #help,
)?;
let mut #missing_requirements_ident = argh::MissingRequirements::default();

View File

@@ -84,17 +84,16 @@ impl<T> EarlyExitExt<T> for Result<T, EarlyExit> {
fn on_early_exit<F: FnOnce()>(self, print_help_msg: F) -> T {
match self {
Ok(t) => t,
Err(EarlyExit { output, status }) => match status {
Ok(_) => {
Err(EarlyExit { output, is_help }) => {
if is_help {
print_help_msg();
exit(0)
}
Err(_) => {
} else {
eprintln!("{output}");
print_help_msg();
exit(1)
}
},
}
}
}
}