Skip to main content

ic_query_cli/cli/
clap.rs

1//! Module: cli::clap
2//!
3//! Responsibility: small clap helper wrappers shared by command parsers.
4//! Does not own: command-family specs, report requests, or runtime dispatch.
5//! Boundary: normalizes typed values, parse errors, and help rendering.
6
7use clap::{Arg, ArgAction, ArgMatches, Command, builder::TypedValueParser};
8use std::ffi::OsString;
9
10/// Prepare the complete Clap tree with shared namespace-help and alphabetical
11/// subcommand-display policies.
12#[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
57/// Returns a required string argument that clap has already validated.
58///
59/// # Panics
60///
61/// Panics when `id` is not present in `matches`. Callers should only use this
62/// for arguments declared as required in the same clap command definition.
63pub 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
74/// Returns a required typed argument that clap has already validated.
75///
76/// # Panics
77///
78/// Panics when `id` is not present in `matches`. Callers should only use this
79/// for arguments declared as required in the same clap command definition.
80pub 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
92/// Adapt a domain-owned choice list to Clap without duplicating its vocabulary.
93pub 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}