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: &mut 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_mut(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 with_source_options<T: Args>(
67 command: Command,
68 endpoint: &'static str,
69 help: &'static str,
70) -> Command {
71 with_options::<T>(command).mut_arg("source-endpoint", |arg| {
72 arg.default_value(endpoint).help(help)
73 })
74}
75
76pub fn flag_arg(id: &'static str) -> Arg {
77 Arg::new(id).action(ArgAction::SetTrue)
78}
79
80#[cfg(test)]
81pub use super::tests::render_help;
82
83pub fn principal_text_value_parser() -> impl TypedValueParser<Value = String> {
85 clap::builder::StringValueParser::new().try_map(|value| {
86 value
87 .parse::<ic_platform_types::Principal>()
88 .map(|principal| principal.to_text())
89 })
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}