allow mutating command in CliApp before running

This commit is contained in:
Aiden McClelland
2026-01-16 14:01:33 -07:00
parent 406ee9e88b
commit 39e547ff99

View File

@@ -27,6 +27,7 @@ pub struct CliApp<Context: crate::Context + Clone, Config: CommandFactory + From
_phantom: PhantomData<(Context, Config)>,
make_ctx: Box<dyn FnOnce(Config) -> Result<Context, RpcError> + Send + Sync>,
root_handler: ParentHandler<Context>,
mut_cmd: Option<Box<dyn FnOnce(clap::Command) -> clap::Command + Send + Sync>>,
}
impl<Context: crate::Context + Clone, Config: CommandFactory + FromArgMatches>
CliApp<Context, Config>
@@ -39,8 +40,16 @@ impl<Context: crate::Context + Clone, Config: CommandFactory + FromArgMatches>
_phantom: PhantomData::new(),
make_ctx: Box::new(make_ctx),
root_handler,
mut_cmd: None,
}
}
pub fn mutate_command(
mut self,
f: impl FnOnce(clap::Command) -> clap::Command + Send + Sync + 'static,
) -> Self {
self.mut_cmd = Some(Box::new(f));
self
}
pub fn run(self, args: impl IntoIterator<Item = OsString>) -> Result<(), RpcError> {
let mut cmd = Config::command();
for (name, handler) in &self.root_handler.subcommands.1 {
@@ -48,6 +57,9 @@ impl<Context: crate::Context + Clone, Config: CommandFactory + FromArgMatches>
cmd = cmd.subcommand(cli.cli_command().name(name));
}
}
if let Some(f) = self.mut_cmd {
cmd = f(cmd);
}
let matches = cmd.get_matches_from(args);
let config = Config::from_arg_matches(&matches)?;
let ctx = (self.make_ctx)(config)?;