1use clap::{Arg, ArgAction, ArgMatches, Command, builder::TypedValueParser};
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(command)
17}
18
19fn default_namespaces_to_help(command: Command) -> Command {
20 let has_subcommands = command.has_subcommands();
21 let command = command.mut_subcommands(default_namespaces_to_help);
22 if has_subcommands {
23 command
24 .arg_required_else_help(true)
25 .subcommand_required(false)
26 } else {
27 command
28 }
29}
30
31fn set_equal_subcommand_display_order(command: Command) -> Command {
32 command.mut_subcommands(|subcommand| {
33 set_equal_subcommand_display_order(subcommand).display_order(0)
34 })
35}
36
37pub fn parse_matches<I>(command: Command, args: I) -> Result<ArgMatches, clap::Error>
38where
39 I: IntoIterator<Item = OsString>,
40{
41 let name = command.get_name().to_string();
42 command.try_get_matches_from(std::iter::once(OsString::from(name)).chain(args))
43}
44
45pub fn value_arg(id: &'static str) -> Arg {
46 Arg::new(id).num_args(1)
47}
48
49pub fn flag_arg(id: &'static str) -> Arg {
50 Arg::new(id).action(ArgAction::SetTrue)
51}
52
53pub fn string_option(matches: &ArgMatches, id: &str) -> Option<String> {
54 matches.get_one::<String>(id).cloned()
55}
56
57pub fn required_string(matches: &ArgMatches, id: &str) -> String {
64 string_option(matches, id).unwrap_or_else(|| panic!("clap requires {id}"))
65}
66
67pub fn typed_option<T>(matches: &ArgMatches, id: &str) -> Option<T>
68where
69 T: Clone + Send + Sync + 'static,
70{
71 matches.get_one::<T>(id).cloned()
72}
73
74pub fn required_typed<T>(matches: &ArgMatches, id: &str) -> T
81where
82 T: Clone + Send + Sync + 'static,
83{
84 typed_option(matches, id).unwrap_or_else(|| panic!("clap requires {id}"))
85}
86
87#[cfg(test)]
88pub fn render_help(mut command: Command) -> String {
89 command.render_help().to_string()
90}
91
92pub fn choice_parser<T: Copy + Send + Sync + 'static>(
94 choices: &'static [T],
95 label: fn(T) -> &'static str,
96) -> impl clap::builder::TypedValueParser<Value = T> {
97 clap::builder::PossibleValuesParser::new(choices.iter().copied().map(label)).map(move |value| {
98 choices
99 .iter()
100 .copied()
101 .find(|choice| label(*choice) == value)
102 .expect("Clap admitted a declared choice")
103 })
104}