Skip to main content

ic_query_cli/
lib.rs

1mod cache;
2mod cli;
3mod cloud_engine;
4mod ic;
5mod icrc;
6mod nns;
7mod output;
8mod progress;
9mod sns;
10mod storage;
11mod system;
12
13pub use crate::cli::clap::prepare_command_tree;
14
15use crate::cli::clap::{parse_matches, string_option};
16use clap::{Arg, Command, error::ErrorKind};
17use ic_query::subnet_catalog::MAINNET_NETWORK;
18use std::ffi::OsString;
19use thiserror::Error as ThisError;
20
21const 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";
22
23///
24/// IcqCliError
25///
26/// Top-level CLI dispatch error.
27///
28
29#[derive(Debug, ThisError)]
30pub enum IcqCliError {
31    /// Writing command help or version output failed.
32    #[error("{0}")]
33    Io(#[from] std::io::Error),
34    #[error("{0}")]
35    Usage(String),
36
37    #[error("cache: {0}")]
38    Cache(#[from] cache::CacheCommandError),
39
40    #[error("cloud-engine: {0}")]
41    CloudEngine(#[from] cloud_engine::CloudEngineCommandError),
42
43    #[error("nns: {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}")]
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::Cache(cache::CacheCommandError::Io(err))
66            | Self::CloudEngine(cloud_engine::CloudEngineCommandError::Io(err))
67            | Self::Ic(ic::IcCommandError::Io(err))
68            | Self::Nns(nns::NnsCommandError::Io(err))
69            | Self::Icrc(icrc::IcrcCommandError::Io(err))
70            | Self::Sns(sns::SnsCommandError::Io(err))
71            | Self::System(system::SystemCommandError::Io(err)) => {
72                err.kind() == std::io::ErrorKind::BrokenPipe
73            }
74            Self::Usage(_)
75            | Self::Cache(_)
76            | Self::CloudEngine(_)
77            | Self::Nns(_)
78            | Self::Icrc(_)
79            | Self::Ic(_)
80            | Self::Sns(_)
81            | Self::System(_) => false,
82        }
83    }
84
85    /// Process exit code for this command error.
86    #[must_use]
87    pub const fn exit_code(&self) -> i32 {
88        match self {
89            Self::Usage(_)
90            | Self::Ic(ic::IcCommandError::Usage(_))
91            | Self::Nns(nns::NnsCommandError::Usage(_))
92            | Self::Icrc(icrc::IcrcCommandError::Usage(_))
93            | Self::Sns(sns::SnsCommandError::Usage(_))
94            | Self::System(system::SystemCommandError::Usage(_)) => 2,
95            Self::Io(_)
96            | Self::Cache(_)
97            | Self::CloudEngine(_)
98            | Self::Nns(_)
99            | Self::Icrc(_)
100            | Self::Ic(_)
101            | Self::Sns(_)
102            | Self::System(_) => 1,
103        }
104    }
105}
106
107/// Run the CLI from process arguments.
108#[expect(
109    clippy::needless_collect,
110    reason = "ArgsOs is not Send; own the arguments before awaiting command dispatch."
111)]
112pub async fn run_from_env() -> Result<(), IcqCliError> {
113    run(std::env::args_os().skip(1).collect::<Vec<_>>()).await
114}
115
116/// Run the CLI from an argument iterator.
117pub async fn run<I>(args: I) -> Result<(), IcqCliError>
118where
119    I: IntoIterator<Item = OsString>,
120{
121    let command = cli_command();
122    let matches = match parse_matches(command.clone(), args) {
123        Ok(matches) => matches,
124        Err(error)
125            if matches!(
126                error.kind(),
127                ErrorKind::DisplayHelp
128                    | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
129                    | ErrorKind::DisplayVersion
130            ) =>
131        {
132            output::write_help(&error.to_string())?;
133            return Ok(());
134        }
135        Err(error) => return Err(IcqCliError::Usage(error.to_string())),
136    };
137
138    if let Some(help) = selected_namespace_help(command, &matches) {
139        output::write_help(&help)?;
140        return Ok(());
141    }
142
143    let selected_network = string_option(&matches, "network");
144    let network = selected_network.as_deref().unwrap_or(MAINNET_NETWORK);
145    let Some((command, matches)) = matches.subcommand() else {
146        return Err(IcqCliError::Usage(usage()));
147    };
148
149    match command {
150        "cache" => {
151            reject_network_for_local_family(command, selected_network.as_deref())?;
152            Ok(cache::run_matches(matches)?)
153        }
154        "cloud-engine" => Ok(cloud_engine::run_matches(matches, network).await?),
155        "ic" => {
156            reject_network_for_endpoint_family(command, selected_network.as_deref())?;
157            Ok(ic::run_matches(matches).await?)
158        }
159        "icrc" => {
160            reject_network_for_endpoint_family(command, selected_network.as_deref())?;
161            Ok(icrc::run_matches(matches).await?)
162        }
163        "nns" => Ok(nns::run_matches(matches, network).await?),
164        "sns" => Ok(sns::run_matches(matches, network, selected_network.is_some()).await?),
165        "system" => Ok(system::run_matches(matches, network).await?),
166        _ => unreachable!("clap only returns declared top-level commands"),
167    }
168}
169
170fn reject_network_for_endpoint_family(
171    command: &str,
172    selected_network: Option<&str>,
173) -> Result<(), IcqCliError> {
174    if selected_network.is_none() {
175        return Ok(());
176    }
177    Err(IcqCliError::Usage(format!(
178        "--network is not supported by `icq {command}`; use the command's --source-endpoint option to select its API endpoint\n\n{}",
179        usage()
180    )))
181}
182
183fn reject_network_for_local_family(
184    command: &str,
185    selected_network: Option<&str>,
186) -> Result<(), IcqCliError> {
187    if selected_network.is_none() {
188        return Ok(());
189    }
190    Err(IcqCliError::Usage(format!(
191        "--network is not supported by `icq {command}`; this command inspects every network under the local cache root\n\n{}",
192        usage()
193    )))
194}
195
196fn network_arg() -> Arg {
197    Arg::new("network")
198        .num_args(1)
199        .long("network")
200        .value_name("name")
201        .value_parser([MAINNET_NETWORK])
202        .help("Network identity for CloudEngine, NNS, SNS, and system commands; currently only ic")
203}
204
205fn top_level_command() -> Command {
206    Command::new("icq")
207        .version(env!("CARGO_PKG_VERSION"))
208        .propagate_version(true)
209        .about("Internet Computer metadata query CLI")
210        .arg(network_arg())
211        .subcommand_help_heading("Commands")
212        .help_template(TOP_LEVEL_HELP_TEMPLATE)
213        .after_help("Run `icq <command> --help` for command-specific help.")
214        .subcommand(cache::command())
215        .subcommand(cloud_engine::command())
216        .subcommand(ic::command())
217        .subcommand(icrc::command())
218        .subcommand(nns::command())
219        .subcommand(sns::command())
220        .subcommand(system::command())
221}
222
223fn cli_command() -> Command {
224    prepare_command_tree(top_level_command())
225}
226
227fn selected_namespace_help(mut command: Command, matches: &clap::ArgMatches) -> Option<String> {
228    let mut selected_command = &mut command;
229    let mut selected_matches = matches;
230    while let Some((name, subcommand_matches)) = selected_matches.subcommand() {
231        selected_command = selected_command.find_subcommand_mut(name)?;
232        selected_matches = subcommand_matches;
233    }
234
235    let has_operational_subcommands = selected_command
236        .get_subcommands()
237        .any(|subcommand| subcommand.get_name() != "help");
238    has_operational_subcommands.then(|| selected_command.render_help().to_string())
239}
240
241fn usage() -> String {
242    let mut command = cli_command();
243    command.render_help().to_string()
244}
245
246#[cfg(test)]
247mod tests {
248    use super::*;
249
250    #[test]
251    fn usage_lists_query_families_and_native_help_guidance() {
252        let text = usage();
253
254        assert!(text.contains("Usage: icq [OPTIONS] [COMMAND]"));
255        assert!(text.contains("ic"));
256        assert!(text.contains("Inspect certified IC state and official Dashboard data"));
257        assert!(text.contains("cache"));
258        assert!(text.contains("Inspect the local ic-query cache"));
259        assert!(text.contains("cloud-engine"));
260        assert!(text.contains("Inspect public CloudEngine metadata"));
261        assert!(text.contains("icrc"));
262        assert!(text.contains("Inspect generic ICRC ledgers"));
263        assert!(text.contains("nns"));
264        assert!(text.contains("Inspect NNS metadata"));
265        assert!(text.contains("sns"));
266        assert!(text.contains("Inspect SNS metadata"));
267        assert!(text.contains("system"));
268        assert!(text.contains("Inspect native IC system-canister metadata"));
269        assert!(text.contains("Run `icq <command> --help`"));
270    }
271
272    #[test]
273    fn every_subcommand_uses_alphabetical_help_order() {
274        fn assert_equal_display_order(command: &Command, path: &mut Vec<String>) {
275            for subcommand in command.get_subcommands() {
276                path.push(subcommand.get_name().to_string());
277                assert_eq!(
278                    subcommand.get_display_order(),
279                    0,
280                    "non-alphabetical display rank for {}",
281                    path.join(" ")
282                );
283                assert_equal_display_order(subcommand, path);
284                path.pop();
285            }
286        }
287
288        assert_equal_display_order(&cli_command(), &mut vec!["icq".to_string()]);
289    }
290
291    #[test]
292    fn every_command_namespace_defaults_to_local_help() {
293        fn assert_namespace_policy(command: &Command, path: &mut Vec<String>) {
294            let has_operational_subcommands = command
295                .get_subcommands()
296                .any(|subcommand| subcommand.get_name() != "help");
297            if has_operational_subcommands {
298                assert!(
299                    command.is_arg_required_else_help_set(),
300                    "missing default help policy for {}",
301                    path.join(" ")
302                );
303                assert!(
304                    !command.is_subcommand_required_set(),
305                    "terse missing-subcommand policy remains on {}",
306                    path.join(" ")
307                );
308            }
309
310            for subcommand in command
311                .get_subcommands()
312                .filter(|subcommand| subcommand.get_name() != "help")
313            {
314                path.push(subcommand.get_name().to_string());
315                assert_namespace_policy(subcommand, path);
316                path.pop();
317            }
318        }
319
320        assert_namespace_policy(&cli_command(), &mut vec!["icq".to_string()]);
321    }
322
323    #[tokio::test(flavor = "current_thread")]
324    async fn native_help_and_propagated_version_return_without_dispatch() {
325        for args in [
326            &["--help"][..],
327            &["ic", "canister", "info", "--help"],
328            &["cache", "status", "--help"],
329            &[
330                "icrc",
331                "account",
332                "transaction",
333                "cache",
334                "status",
335                "--help",
336            ],
337            &["cloud-engine", "info", "--help"],
338            &["cloud-engine", "node", "list", "--help"],
339            &["cloud-engine", "provider", "list", "--help"],
340            &["nns", "topology", "providers", "--help"],
341            &["sns", "proposal", "cache", "status", "--help"],
342            &["system", "cycles", "--help"],
343            &["--version"],
344            &["nns", "subnet", "list", "--version"],
345        ] {
346            assert_run_ok(args).await;
347        }
348    }
349
350    #[test]
351    fn every_composed_command_path_supports_native_help() {
352        fn collect_paths(
353            command: &Command,
354            prefix: &mut Vec<OsString>,
355            paths: &mut Vec<Vec<OsString>>,
356        ) {
357            for subcommand in command.get_subcommands() {
358                prefix.push(OsString::from(subcommand.get_name()));
359                paths.push(prefix.clone());
360                collect_paths(subcommand, prefix, paths);
361                prefix.pop();
362            }
363        }
364
365        let mut paths = Vec::new();
366        collect_paths(&top_level_command(), &mut Vec::new(), &mut paths);
367        assert_ne!(paths, Vec::<Vec<OsString>>::new());
368
369        for mut path in paths {
370            path.push(OsString::from("--help"));
371            let error = parse_matches(top_level_command(), path.clone())
372                .expect_err("native help must stop before typed dispatch");
373            assert_eq!(
374                error.kind(),
375                ErrorKind::DisplayHelp,
376                "unexpected result for {path:?}"
377            );
378        }
379    }
380
381    #[test]
382    fn every_report_leaf_exposes_the_shared_json_flag() {
383        fn assert_leaf_json(command: &Command, path: &mut Vec<String>) {
384            let subcommands = command.get_subcommands().collect::<Vec<_>>();
385            if subcommands.is_empty() {
386                assert!(
387                    command
388                        .get_arguments()
389                        .any(|argument| argument.get_id() == "json"),
390                    "missing --json on {}",
391                    path.join(" ")
392                );
393                return;
394            }
395
396            for subcommand in subcommands {
397                path.push(subcommand.get_name().to_string());
398                assert_leaf_json(subcommand, path);
399                path.pop();
400            }
401        }
402
403        assert_leaf_json(&top_level_command(), &mut vec!["icq".to_string()]);
404    }
405
406    #[tokio::test(flavor = "current_thread")]
407    async fn clap_rejects_non_mainnet_and_command_local_network_options() {
408        let error = run([
409            OsString::from("--network"),
410            OsString::from("local"),
411            OsString::from("nns"),
412            OsString::from("registry"),
413            OsString::from("version"),
414        ])
415        .await
416        .expect_err("non-mainnet network must fail in Clap");
417        assert_eq!(error.exit_code(), 2);
418        assert!(error.to_string().contains("invalid value 'local'"));
419
420        let error = run([
421            OsString::from("nns"),
422            OsString::from("registry"),
423            OsString::from("version"),
424            OsString::from("--network"),
425            OsString::from("ic"),
426        ])
427        .await
428        .expect_err("network remains a top-level option");
429        assert_eq!(error.exit_code(), 2);
430        assert!(
431            error
432                .to_string()
433                .contains("unexpected argument '--network'")
434        );
435    }
436
437    #[tokio::test(flavor = "current_thread")]
438    async fn network_is_rejected_for_endpoint_identified_families() {
439        for args in [
440            &["--network", "ic", "ic", "canister", "count"][..],
441            &[
442                "--network",
443                "ic",
444                "icrc",
445                "ledger",
446                "token",
447                "ryjl3-tyaaa-aaaaa-aaaba-cai",
448            ],
449        ] {
450            let error = run(args.iter().map(OsString::from))
451                .await
452                .expect_err("endpoint-identified families must reject --network");
453            assert_eq!(error.exit_code(), 2);
454            assert!(error.to_string().contains("--source-endpoint"));
455        }
456    }
457
458    #[tokio::test(flavor = "current_thread")]
459    async fn explicit_network_is_rejected_for_cross_network_cache_status() {
460        let error = run([
461            OsString::from("--network"),
462            OsString::from("ic"),
463            OsString::from("cache"),
464            OsString::from("status"),
465        ])
466        .await
467        .expect_err("cross-network cache status must reject one selected network");
468
469        assert_eq!(error.exit_code(), 2);
470        assert!(error.to_string().contains("every network"));
471    }
472
473    #[tokio::test(flavor = "current_thread")]
474    async fn explicit_network_is_rejected_for_local_reward_diff() {
475        let error = run([
476            OsString::from("--network"),
477            OsString::from("ic"),
478            OsString::from("sns"),
479            OsString::from("reward"),
480            OsString::from("diff"),
481            OsString::from("before.json"),
482            OsString::from("after.json"),
483        ])
484        .await
485        .expect_err("local reward diff must reject explicit network identity");
486
487        assert_eq!(error.exit_code(), 2);
488        assert!(error.to_string().contains("local-only"));
489    }
490
491    #[tokio::test(flavor = "current_thread")]
492    async fn targeted_sns_leaves_require_their_identifiers() {
493        for args in [
494            &["sns", "neuron", "list"][..],
495            &["sns", "proposal", "refresh"][..],
496            &["sns", "reward", "checkpoint"][..],
497        ] {
498            let error = run(args.iter().map(OsString::from))
499                .await
500                .expect_err("targeted SNS operation must require an SNS selector");
501            assert_eq!(error.exit_code(), 2);
502            assert!(error.to_string().contains("<id|root-principal>"));
503        }
504    }
505
506    #[test]
507    fn typed_cli_errors_preserve_exit_and_broken_pipe_semantics() {
508        for usage in [
509            IcqCliError::Ic(ic::IcCommandError::Usage("bad input".to_string())),
510            IcqCliError::Icrc(icrc::IcrcCommandError::Usage("bad input".to_string())),
511            IcqCliError::System(system::SystemCommandError::Usage("bad input".to_string())),
512        ] {
513            assert_eq!(usage.exit_code(), 2);
514            assert!(!usage.is_broken_pipe());
515        }
516
517        for broken_pipe in [
518            IcqCliError::CloudEngine(cloud_engine::CloudEngineCommandError::Io(
519                std::io::Error::from(std::io::ErrorKind::BrokenPipe),
520            )),
521            IcqCliError::Ic(ic::IcCommandError::Io(std::io::Error::from(
522                std::io::ErrorKind::BrokenPipe,
523            ))),
524            IcqCliError::Icrc(icrc::IcrcCommandError::Io(std::io::Error::from(
525                std::io::ErrorKind::BrokenPipe,
526            ))),
527            IcqCliError::System(system::SystemCommandError::Io(std::io::Error::from(
528                std::io::ErrorKind::BrokenPipe,
529            ))),
530        ] {
531            assert_eq!(broken_pipe.exit_code(), 1);
532            assert!(broken_pipe.is_broken_pipe());
533        }
534    }
535
536    async fn assert_run_ok(args: &[&str]) {
537        let args = args.iter().copied().map(OsString::from).collect::<Vec<_>>();
538        if let Err(err) = run(args.clone()).await {
539            panic!("expected {args:?} to succeed, got {err}");
540        }
541    }
542}