1use clap::{Arg, ArgAction, ArgMatches, Command};
8use std::ffi::OsString;
9
10#[must_use]
13pub fn prepare_command_tree(command: Command) -> Command {
14 let mut command = default_namespaces_to_help(command);
15 command.build();
16 set_equal_subcommand_display_order(&mut command);
17 command
18}
19
20fn default_namespaces_to_help(command: Command) -> Command {
21 let has_subcommands = command.has_subcommands();
22 let command = command.mut_subcommands(default_namespaces_to_help);
23 if has_subcommands {
24 command
25 .arg_required_else_help(true)
26 .subcommand_required(false)
27 } else {
28 command
29 }
30}
31
32fn set_equal_subcommand_display_order(command: &mut Command) {
33 for subcommand in command.get_subcommands_mut() {
34 set_equal_subcommand_display_order(subcommand);
35 *subcommand = subcommand.clone().display_order(0);
36 }
37}
38
39pub fn parse_matches<I>(command: Command, args: I) -> Result<ArgMatches, clap::Error>
40where
41 I: IntoIterator<Item = OsString>,
42{
43 let name = command.get_name().to_string();
44 command.try_get_matches_from(std::iter::once(OsString::from(name)).chain(args))
45}
46
47pub fn value_arg(id: &'static str) -> Arg {
48 Arg::new(id).num_args(1)
49}
50
51pub fn flag_arg(id: &'static str) -> Arg {
52 Arg::new(id).action(ArgAction::SetTrue)
53}
54
55pub fn string_option(matches: &ArgMatches, id: &str) -> Option<String> {
56 matches.get_one::<String>(id).cloned()
57}
58
59pub fn required_string(matches: &ArgMatches, id: &str) -> String {
66 string_option(matches, id).unwrap_or_else(|| panic!("clap requires {id}"))
67}
68
69pub fn typed_option<T>(matches: &ArgMatches, id: &str) -> Option<T>
70where
71 T: Clone + Send + Sync + 'static,
72{
73 matches.get_one::<T>(id).cloned()
74}
75
76pub fn required_typed<T>(matches: &ArgMatches, id: &str) -> T
83where
84 T: Clone + Send + Sync + 'static,
85{
86 typed_option(matches, id).unwrap_or_else(|| panic!("clap requires {id}"))
87}
88
89#[cfg(test)]
90pub fn render_help(mut command: Command) -> String {
91 command.render_help().to_string()
92}