1use clap::{
8 Arg, ArgAction, ArgMatches, Args, Command, FromArgMatches,
9 builder::{Resettable, TypedValueParser},
10};
11use std::ffi::OsString;
12
13#[must_use]
16pub fn prepare_command_tree(command: Command) -> Command {
17 let mut command = default_namespaces_to_help(command);
18 command.build();
19 set_equal_subcommand_display_order(command)
20}
21
22fn default_namespaces_to_help(command: Command) -> Command {
23 let has_subcommands = command.has_subcommands();
24 let command = command.mut_subcommands(default_namespaces_to_help);
25 if has_subcommands {
26 command
27 .arg_required_else_help(true)
28 .subcommand_required(false)
29 } else {
30 command
31 }
32}
33
34fn set_equal_subcommand_display_order(command: Command) -> Command {
35 command.mut_subcommands(|subcommand| {
36 set_equal_subcommand_display_order(subcommand).display_order(0)
37 })
38}
39
40pub fn parse_matches<I>(command: Command, args: I) -> Result<ArgMatches, clap::Error>
41where
42 I: IntoIterator<Item = OsString>,
43{
44 let name = command.get_name().to_string();
45 command.try_get_matches_from(std::iter::once(OsString::from(name)).chain(args))
46}
47
48pub fn parsed_options<T: FromArgMatches>(matches: &ArgMatches) -> T {
49 T::from_arg_matches(matches).expect("Clap admitted the command's typed argument schema")
50}
51
52pub fn with_options<T: Args>(command: Command) -> Command {
54 let about = command
55 .get_about()
56 .cloned()
57 .map_or(Resettable::Reset, Resettable::Value);
58 let long_about = command
59 .get_long_about()
60 .cloned()
61 .map_or(Resettable::Reset, Resettable::Value);
62 T::augment_args(command).about(about).long_about(long_about)
63}
64
65pub fn flag_arg(id: &'static str) -> Arg {
66 Arg::new(id).action(ArgAction::SetTrue)
67}
68
69#[cfg(test)]
70pub use super::tests::render_help;
71
72pub fn principal_text_value_parser() -> impl TypedValueParser<Value = String> {
74 clap::builder::StringValueParser::new().try_map(|value| {
75 value
76 .parse::<ic_platform::candid::contract::Principal>()
77 .map(|principal| principal.to_text())
78 })
79}
80
81pub fn choice_parser<T: Copy + Send + Sync + 'static>(
83 choices: &'static [T],
84 label: fn(T) -> &'static str,
85) -> impl clap::builder::TypedValueParser<Value = T> {
86 clap::builder::PossibleValuesParser::new(choices.iter().copied().map(label)).map(move |value| {
87 choices
88 .iter()
89 .copied()
90 .find(|choice| label(*choice) == value)
91 .expect("Clap admitted a declared choice")
92 })
93}