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 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#[derive(Debug, ThisError)]
33pub enum IcqCliError {
34 #[error("{0}")]
36 Io(#[from] std::io::Error),
37 #[error("{0}")]
38 Usage(String),
39
40 #[error("cache: {0}")]
41 Cache(#[from] cache::CacheCommandError),
42
43 #[error("cloud-engine: {0}")]
44 CloudEngine(#[from] cloud_engine::CloudEngineCommandError),
45
46 #[error("nns: {0}{advice}", advice = cli::diagnostics::nns_advice(.0))]
47 Nns(#[from] nns::NnsCommandError),
48
49 #[error("icrc: {0}")]
50 Icrc(#[from] icrc::IcrcCommandError),
51
52 #[error("ic: {0}")]
53 Ic(#[from] ic::IcCommandError),
54
55 #[error("sns: {0}{advice}", advice = cli::diagnostics::sns_advice(.0))]
56 Sns(#[from] sns::SnsCommandError),
57
58 #[error("system: {0}")]
59 System(#[from] system::SystemCommandError),
60}
61
62impl IcqCliError {
63 #[must_use]
65 pub fn is_broken_pipe(&self) -> bool {
66 match self {
67 Self::Io(err)
68 | Self::Cache(cache::CacheCommandError::Io(err))
69 | Self::CloudEngine(cloud_engine::CloudEngineCommandError::Io(err))
70 | Self::Ic(ic::IcCommandError::Io(err))
71 | Self::Nns(nns::NnsCommandError::Io(err))
72 | Self::Icrc(icrc::IcrcCommandError::Io(err))
73 | Self::Sns(sns::SnsCommandError::Io(err))
74 | Self::System(system::SystemCommandError::Io(err)) => {
75 err.kind() == std::io::ErrorKind::BrokenPipe
76 }
77 Self::Usage(_)
78 | Self::Cache(_)
79 | Self::CloudEngine(_)
80 | Self::Nns(_)
81 | Self::Icrc(_)
82 | Self::Ic(_)
83 | Self::Sns(_)
84 | Self::System(_) => false,
85 }
86 }
87
88 #[must_use]
90 pub const fn exit_code(&self) -> i32 {
91 match self {
92 Self::Usage(_)
93 | Self::Ic(ic::IcCommandError::Usage(_))
94 | Self::Nns(nns::NnsCommandError::Usage(_))
95 | Self::Icrc(icrc::IcrcCommandError::Usage(_))
96 | Self::Sns(sns::SnsCommandError::Usage(_))
97 | Self::System(system::SystemCommandError::Usage(_)) => 2,
98 Self::Io(_)
99 | Self::Cache(_)
100 | Self::CloudEngine(_)
101 | Self::Nns(_)
102 | Self::Icrc(_)
103 | Self::Ic(_)
104 | Self::Sns(_)
105 | Self::System(_) => 1,
106 }
107 }
108}
109
110#[expect(
112 clippy::needless_collect,
113 reason = "ArgsOs is not Send; own the arguments before awaiting command dispatch."
114)]
115pub async fn run_from_env() -> Result<(), IcqCliError> {
116 run(std::env::args_os().skip(1).collect::<Vec<_>>()).await
117}
118
119pub async fn run<I>(args: I) -> Result<(), IcqCliError>
121where
122 I: IntoIterator<Item = OsString>,
123{
124 let command = cli_command();
125 let matches = match parse_matches(command.clone(), args) {
126 Ok(matches) => matches,
127 Err(error)
128 if matches!(
129 error.kind(),
130 ErrorKind::DisplayHelp
131 | ErrorKind::DisplayHelpOnMissingArgumentOrSubcommand
132 | ErrorKind::DisplayVersion
133 ) =>
134 {
135 output::write_help(&error.to_string())?;
136 return Ok(());
137 }
138 Err(error) => return Err(IcqCliError::Usage(error.to_string())),
139 };
140
141 if let Some(help) = selected_namespace_help(command, &matches) {
142 output::write_help(&help)?;
143 return Ok(());
144 }
145
146 let selected_network = string_option(&matches, "network");
147 let network = selected_network.as_deref().unwrap_or(MAINNET_NETWORK);
148 let Some((command, matches)) = matches.subcommand() else {
149 return Err(IcqCliError::Usage(usage()));
150 };
151
152 match command {
153 "cache" => {
154 reject_network_option(
155 command,
156 selected_network.as_deref(),
157 "this command inspects every network under the local cache root",
158 )?;
159 Ok(cache::run_matches(matches)?)
160 }
161 "cloud-engine" => Ok(cloud_engine::run_matches(matches, network).await?),
162 "ic" => {
163 reject_network_option(
164 command,
165 selected_network.as_deref(),
166 ENDPOINT_NETWORK_ADVICE,
167 )?;
168 Ok(ic::run_matches(matches).await?)
169 }
170 "icrc" => {
171 reject_network_option(
172 command,
173 selected_network.as_deref(),
174 ENDPOINT_NETWORK_ADVICE,
175 )?;
176 Ok(icrc::run_matches(matches).await?)
177 }
178 "nns" => Ok(nns::run_matches(matches, network).await?),
179 "sns" => Ok(sns::run_matches(matches, network).await?),
180 "system" => Ok(system::run_matches(matches, network).await?),
181 _ => unreachable!("clap only returns declared top-level commands"),
182 }
183}
184
185fn reject_network_option(
186 command: &str,
187 selected_network: Option<&str>,
188 explanation: &str,
189) -> Result<(), IcqCliError> {
190 if selected_network.is_none() {
191 return Ok(());
192 }
193 Err(IcqCliError::Usage(format!(
194 "--network is not supported by `icq {command}`; {explanation}\n\n{}",
195 usage()
196 )))
197}
198
199fn network_arg() -> Arg {
200 Arg::new("network")
201 .num_args(1)
202 .long("network")
203 .value_name("name")
204 .value_parser([MAINNET_NETWORK])
205 .help("Network identity for CloudEngine, NNS, SNS, and system commands; currently only ic")
206}
207
208fn top_level_command() -> Command {
209 Command::new("icq")
210 .version(env!("CARGO_PKG_VERSION"))
211 .propagate_version(true)
212 .about("Internet Computer metadata query CLI")
213 .arg(network_arg())
214 .subcommand_help_heading("Commands")
215 .help_template(TOP_LEVEL_HELP_TEMPLATE)
216 .after_help("Run `icq <command> --help` for command-specific help.")
217 .subcommand(cache::command())
218 .subcommand(cloud_engine::command())
219 .subcommand(ic::command())
220 .subcommand(icrc::command())
221 .subcommand(nns::command())
222 .subcommand(sns::command())
223 .subcommand(system::command())
224}
225
226fn cli_command() -> Command {
227 prepare_command_tree(top_level_command())
228}
229
230fn selected_namespace_help(mut command: Command, matches: &clap::ArgMatches) -> Option<String> {
231 let mut selected_command = &mut command;
232 let mut selected_matches = matches;
233 while let Some((name, subcommand_matches)) = selected_matches.subcommand() {
234 selected_command = selected_command.find_subcommand_mut(name)?;
235 selected_matches = subcommand_matches;
236 }
237
238 let has_operational_subcommands = selected_command
239 .get_subcommands()
240 .any(|subcommand| subcommand.get_name() != "help");
241 has_operational_subcommands.then(|| selected_command.render_help().to_string())
242}
243
244fn usage() -> String {
245 let mut command = cli_command();
246 command.render_help().to_string()
247}
248
249#[cfg(test)]
250mod tests;