Skip to main content

ic_query_cli/
lib.rs

1mod cli;
2mod cloud_engine;
3mod ic;
4mod icrc;
5mod nns;
6mod output;
7mod progress;
8mod sns;
9mod storage;
10mod system;
11
12pub use crate::cli::clap::prepare_command_tree;
13
14use crate::cli::clap::{parse_matches, string_option};
15use clap::{Arg, Command, error::ErrorKind};
16use ic_host_text::escape::terminal_text;
17use ic_query::subnet_catalog::MAINNET_NETWORK;
18use std::ffi::OsString;
19use thiserror::Error as ThisError;
20
21const ENDPOINT_NETWORK_ADVICE: &str =
22    "use the command's --source-endpoint option to select its API endpoint";
23
24const TOP_LEVEL_HELP_TEMPLATE: &str = "{name} {version}\n{about-with-newline}\n{usage-heading} {usage}\n\nCommands:\n{subcommands}\n\nOptions:\n{options}{after-help}\n";
25
26///
27/// IcqCliError
28///
29/// Top-level CLI dispatch error.
30///
31
32#[derive(Debug, ThisError)]
33pub enum IcqCliError {
34    /// Writing command help or version output failed.
35    #[error("{0}")]
36    Io(#[from] std::io::Error),
37    #[error("{0}")]
38    Usage(String),
39
40    #[error("cloud-engine: {0}")]
41    CloudEngine(#[from] cloud_engine::CloudEngineCommandError),
42
43    #[error("nns: {0}{advice}", advice = cli::diagnostics::nns_advice(.0))]
44    Nns(#[from] nns::NnsCommandError),
45
46    #[error("icrc: {0}")]
47    Icrc(#[from] icrc::IcrcCommandError),
48
49    #[error("ic: {0}")]
50    Ic(#[from] ic::IcCommandError),
51
52    #[error("sns: {0}{advice}", advice = cli::diagnostics::sns_advice(.0))]
53    Sns(#[from] sns::SnsCommandError),
54
55    #[error("system: {0}")]
56    System(#[from] system::SystemCommandError),
57}
58
59impl IcqCliError {
60    /// Whether stdout closed before the command finished writing its report.
61    #[must_use]
62    pub fn is_broken_pipe(&self) -> bool {
63        match self {
64            Self::Io(err)
65            | Self::CloudEngine(cloud_engine::CloudEngineCommandError::Io(err))
66            | Self::Ic(ic::IcCommandError::Io(err))
67            | Self::Nns(nns::NnsCommandError::Io(err))
68            | Self::Icrc(icrc::IcrcCommandError::Io(err))
69            | Self::Sns(sns::SnsCommandError::Io(err))
70            | Self::System(system::SystemCommandError::Io(err)) => {
71                err.kind() == std::io::ErrorKind::BrokenPipe
72            }
73            Self::Usage(_)
74            | Self::CloudEngine(_)
75            | Self::Nns(_)
76            | Self::Icrc(_)
77            | Self::Ic(_)
78            | Self::Sns(_)
79            | Self::System(_) => false,
80        }
81    }
82
83    /// Escape runtime error fields while retaining framework layout and local advice.
84    /// `Usage` contains trusted Clap/static layout and is retained verbatim.
85    #[must_use]
86    pub fn diagnostic_text(&self) -> String {
87        match self {
88            // This variant contains Clap-rendered diagnostics or static local usage.
89            Self::Usage(message) => message.clone(),
90            Self::Nns(error) => format!(
91                "nns: {}{}",
92                terminal_text(&error.to_string()),
93                cli::diagnostics::nns_advice(error)
94            ),
95            Self::Sns(error) => format!(
96                "sns: {}{}",
97                terminal_text(&error.to_string()),
98                cli::diagnostics::sns_advice(error)
99            ),
100            _ => terminal_text(&self.to_string()).into_owned(),
101        }
102    }
103
104    /// Process exit code for this command error.
105    #[must_use]
106    pub const fn exit_code(&self) -> i32 {
107        match self {
108            Self::Usage(_)
109            | Self::Ic(ic::IcCommandError::Usage(_))
110            | Self::Nns(nns::NnsCommandError::Usage(_))
111            | Self::Icrc(icrc::IcrcCommandError::Usage(_))
112            | Self::Sns(sns::SnsCommandError::Usage(_))
113            | Self::System(system::SystemCommandError::Usage(_)) => 2,
114            Self::Io(_)
115            | Self::CloudEngine(_)
116            | Self::Nns(_)
117            | Self::Icrc(_)
118            | Self::Ic(_)
119            | Self::Sns(_)
120            | Self::System(_) => 1,
121        }
122    }
123}
124
125/// Run the CLI from process arguments.
126#[expect(
127    clippy::needless_collect,
128    reason = "ArgsOs is not Send; own the arguments before awaiting command dispatch."
129)]
130pub async fn run_from_env() -> Result<(), IcqCliError> {
131    run(std::env::args_os().skip(1).collect::<Vec<_>>()).await
132}
133
134/// Run the CLI from an argument iterator.
135pub async fn run<I>(args: I) -> Result<(), IcqCliError>
136where
137    I: IntoIterator<Item = OsString>,
138{
139    let command = cli_command();
140    let matches = match parse_matches(command.clone(), args) {
141        Ok(matches) => matches,
142        Err(error)
143            if matches!(
144                error.kind(),
145                ErrorKind::DisplayHelp
146                    | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
147                    | ErrorKind::DisplayVersion
148            ) =>
149        {
150            output::write_help(&error.to_string())?;
151            return Ok(());
152        }
153        Err(error) => return Err(IcqCliError::Usage(error.to_string())),
154    };
155
156    if let Some(help) = selected_namespace_help(command, &matches) {
157        output::write_help(&help)?;
158        return Ok(());
159    }
160
161    let selected_network = string_option(&matches, "network");
162    let network = selected_network.as_deref().unwrap_or(MAINNET_NETWORK);
163    let Some((command, matches)) = matches.subcommand() else {
164        return Err(IcqCliError::Usage(usage()));
165    };
166
167    match command {
168        "cloud-engine" => Ok(cloud_engine::run_matches(matches, network).await?),
169        "ic" => {
170            reject_network_option(
171                command,
172                selected_network.as_deref(),
173                ENDPOINT_NETWORK_ADVICE,
174            )?;
175            Ok(ic::run_matches(matches).await?)
176        }
177        "icrc" => {
178            reject_network_option(
179                command,
180                selected_network.as_deref(),
181                ENDPOINT_NETWORK_ADVICE,
182            )?;
183            Ok(icrc::run_matches(matches).await?)
184        }
185        "nns" => Ok(nns::run_matches(matches, network).await?),
186        "sns" => Ok(sns::run_matches(matches, network).await?),
187        "system" => Ok(system::run_matches(matches, network).await?),
188        _ => unreachable!("clap only returns declared top-level commands"),
189    }
190}
191
192fn reject_network_option(
193    command: &str,
194    selected_network: Option<&str>,
195    explanation: &str,
196) -> Result<(), IcqCliError> {
197    if selected_network.is_none() {
198        return Ok(());
199    }
200    Err(IcqCliError::Usage(format!(
201        "--network is not supported by `icq {command}`; {explanation}\n\n{}",
202        usage()
203    )))
204}
205
206fn network_arg() -> Arg {
207    Arg::new("network")
208        .num_args(1)
209        .long("network")
210        .value_name("name")
211        .value_parser([MAINNET_NETWORK])
212        .help("Network identity for CloudEngine, NNS, SNS, and system commands; currently only ic")
213}
214
215fn top_level_command() -> Command {
216    Command::new("icq")
217        .version(env!("CARGO_PKG_VERSION"))
218        .propagate_version(true)
219        .about("Internet Computer metadata query CLI")
220        .arg(network_arg())
221        .subcommand_help_heading("Commands")
222        .help_template(TOP_LEVEL_HELP_TEMPLATE)
223        .after_help("Run `icq <command> --help` for command-specific help.")
224        .subcommand(cloud_engine::command())
225        .subcommand(ic::command())
226        .subcommand(icrc::command())
227        .subcommand(nns::command())
228        .subcommand(sns::command())
229        .subcommand(system::command())
230}
231
232fn cli_command() -> Command {
233    prepare_command_tree(top_level_command())
234}
235
236fn selected_namespace_help(mut command: Command, matches: &clap::ArgMatches) -> Option<String> {
237    let mut selected_command = &mut command;
238    let mut selected_matches = matches;
239    while let Some((name, subcommand_matches)) = selected_matches.subcommand() {
240        selected_command = selected_command.find_subcommand_mut(name)?;
241        selected_matches = subcommand_matches;
242    }
243
244    let has_operational_subcommands = selected_command
245        .get_subcommands()
246        .any(|subcommand| subcommand.get_name() != "help");
247    has_operational_subcommands.then(|| selected_command.render_help().to_string())
248}
249
250fn usage() -> String {
251    let mut command = cli_command();
252    command.render_help().to_string()
253}
254
255#[cfg(test)]
256mod tests;