Skip to main content

ic_query_cli/
lib.rs

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