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