1mod cli;
2mod ic;
3mod icrc;
4mod nns;
5mod output;
6mod progress;
7mod sns;
8mod storage;
9mod system;
10
11use crate::cli::clap::{parse_matches, string_option};
12use clap::{Arg, Command, error::ErrorKind};
13use ic_query::subnet_catalog::MAINNET_NETWORK;
14use std::ffi::OsString;
15use thiserror::Error as ThisError;
16
17const 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";
18
19#[derive(Debug, ThisError)]
26pub enum IcqCliError {
27 #[error("{0}")]
28 Usage(String),
29
30 #[error("nns: {0}")]
31 Nns(#[from] nns::NnsCommandError),
32
33 #[error("icrc: {0}")]
34 Icrc(#[from] icrc::IcrcCommandError),
35
36 #[error("ic: {0}")]
37 Ic(#[from] ic::IcCommandError),
38
39 #[error("sns: {0}")]
40 Sns(#[from] sns::SnsCommandError),
41
42 #[error("system: {0}")]
43 System(#[from] system::SystemCommandError),
44}
45
46impl IcqCliError {
47 #[must_use]
49 pub fn is_broken_pipe(&self) -> bool {
50 match self {
51 Self::Ic(ic::IcCommandError::Io(err))
52 | Self::Nns(nns::NnsCommandError::Io(err))
53 | Self::Icrc(icrc::IcrcCommandError::Io(err))
54 | Self::Sns(sns::SnsCommandError::Io(err))
55 | Self::System(system::SystemCommandError::Io(err)) => {
56 err.kind() == std::io::ErrorKind::BrokenPipe
57 }
58 Self::Usage(_)
59 | Self::Nns(_)
60 | Self::Icrc(_)
61 | Self::Ic(_)
62 | Self::Sns(_)
63 | Self::System(_) => false,
64 }
65 }
66
67 #[must_use]
69 pub const fn exit_code(&self) -> i32 {
70 match self {
71 Self::Usage(_)
72 | Self::Ic(ic::IcCommandError::Usage(_))
73 | Self::Nns(nns::NnsCommandError::Usage(_))
74 | Self::Icrc(icrc::IcrcCommandError::Usage(_))
75 | Self::Sns(sns::SnsCommandError::Usage(_))
76 | Self::System(system::SystemCommandError::Usage(_)) => 2,
77 Self::Nns(_) | Self::Icrc(_) | Self::Ic(_) | Self::Sns(_) | Self::System(_) => 1,
78 }
79 }
80}
81
82pub fn run_from_env() -> Result<(), IcqCliError> {
84 run(std::env::args_os().skip(1))
85}
86
87pub fn run<I>(args: I) -> Result<(), IcqCliError>
89where
90 I: IntoIterator<Item = OsString>,
91{
92 let matches = match parse_matches(top_level_command(), args) {
93 Ok(matches) => matches,
94 Err(error)
95 if matches!(
96 error.kind(),
97 ErrorKind::DisplayHelp | ErrorKind::DisplayVersion
98 ) =>
99 {
100 print!("{error}");
101 return Ok(());
102 }
103 Err(error) => return Err(IcqCliError::Usage(error.to_string())),
104 };
105
106 let selected_network = string_option(&matches, "network");
107 let network = selected_network.as_deref().unwrap_or(MAINNET_NETWORK);
108 let Some((command, matches)) = matches.subcommand() else {
109 return Err(IcqCliError::Usage(usage()));
110 };
111
112 match command {
113 "ic" => {
114 reject_network_for_endpoint_family(command, selected_network.as_deref())?;
115 Ok(ic::run_matches(matches)?)
116 }
117 "icrc" => {
118 reject_network_for_endpoint_family(command, selected_network.as_deref())?;
119 Ok(icrc::run_matches(matches)?)
120 }
121 "nns" => Ok(nns::run_matches(matches, network)?),
122 "sns" => Ok(sns::run_matches(matches, network)?),
123 "system" => Ok(system::run_matches(matches, network)?),
124 _ => unreachable!("clap only returns declared top-level commands"),
125 }
126}
127
128fn reject_network_for_endpoint_family(
129 command: &str,
130 selected_network: Option<&str>,
131) -> Result<(), IcqCliError> {
132 if selected_network.is_none() {
133 return Ok(());
134 }
135 Err(IcqCliError::Usage(format!(
136 "--network is not supported by `icq {command}`; use the command's --source-endpoint option to select its API endpoint\n\n{}",
137 usage()
138 )))
139}
140
141fn network_arg() -> Arg {
142 Arg::new("network")
143 .num_args(1)
144 .long("network")
145 .value_name("name")
146 .value_parser([MAINNET_NETWORK])
147 .help("Network identity for NNS, SNS, and system commands; currently only ic")
148}
149
150fn top_level_command() -> Command {
151 Command::new("icq")
152 .version(env!("CARGO_PKG_VERSION"))
153 .propagate_version(true)
154 .about("Internet Computer metadata query CLI")
155 .arg(network_arg())
156 .subcommand_help_heading("Commands")
157 .help_template(TOP_LEVEL_HELP_TEMPLATE)
158 .after_help("Run `icq <command> --help` for command-specific help.")
159 .subcommand(ic::command())
160 .subcommand(icrc::command())
161 .subcommand(nns::command())
162 .subcommand(sns::command())
163 .subcommand(system::command())
164}
165
166fn usage() -> String {
167 let mut command = top_level_command();
168 command.render_help().to_string()
169}
170
171#[cfg(test)]
172mod tests {
173 use super::*;
174
175 #[test]
176 fn usage_lists_query_families_and_native_help_guidance() {
177 let text = usage();
178
179 assert!(text.contains("Usage: icq [OPTIONS] [COMMAND]"));
180 assert!(text.contains("ic"));
181 assert!(text.contains("Inspect official IC Dashboard data"));
182 assert!(text.contains("icrc"));
183 assert!(text.contains("Inspect generic ICRC ledgers"));
184 assert!(text.contains("nns"));
185 assert!(text.contains("Inspect NNS metadata"));
186 assert!(text.contains("sns"));
187 assert!(text.contains("Inspect SNS metadata"));
188 assert!(text.contains("system"));
189 assert!(text.contains("Inspect native IC system-canister metadata"));
190 assert!(text.contains("Run `icq <command> --help`"));
191 }
192
193 #[test]
194 fn native_help_and_propagated_version_return_without_dispatch() {
195 for args in [
196 &["--help"][..],
197 &["ic", "canister", "info", "--help"],
198 &[
199 "icrc",
200 "account",
201 "transaction",
202 "cache",
203 "status",
204 "--help",
205 ],
206 &["nns", "topology", "providers", "--help"],
207 &["sns", "proposal", "cache", "status", "--help"],
208 &["system", "cycles", "--help"],
209 &["--version"],
210 &["nns", "subnet", "list", "--version"],
211 ] {
212 assert_run_ok(args);
213 }
214 }
215
216 #[test]
217 fn every_composed_command_path_supports_native_help() {
218 fn collect_paths(
219 command: &Command,
220 prefix: &mut Vec<OsString>,
221 paths: &mut Vec<Vec<OsString>>,
222 ) {
223 for subcommand in command.get_subcommands() {
224 prefix.push(OsString::from(subcommand.get_name()));
225 paths.push(prefix.clone());
226 collect_paths(subcommand, prefix, paths);
227 prefix.pop();
228 }
229 }
230
231 let mut paths = Vec::new();
232 collect_paths(&top_level_command(), &mut Vec::new(), &mut paths);
233 assert!(!paths.is_empty());
234
235 for mut path in paths {
236 path.push(OsString::from("--help"));
237 let error = parse_matches(top_level_command(), path.clone())
238 .expect_err("native help must stop before typed dispatch");
239 assert_eq!(
240 error.kind(),
241 ErrorKind::DisplayHelp,
242 "unexpected result for {path:?}"
243 );
244 }
245 }
246
247 #[test]
248 fn every_report_leaf_exposes_the_shared_json_flag() {
249 fn assert_leaf_json(command: &Command, path: &mut Vec<String>) {
250 let subcommands = command.get_subcommands().collect::<Vec<_>>();
251 if subcommands.is_empty() {
252 assert!(
253 command
254 .get_arguments()
255 .any(|argument| argument.get_id() == "json"),
256 "missing --json on {}",
257 path.join(" ")
258 );
259 return;
260 }
261
262 for subcommand in subcommands {
263 path.push(subcommand.get_name().to_string());
264 assert_leaf_json(subcommand, path);
265 path.pop();
266 }
267 }
268
269 assert_leaf_json(&top_level_command(), &mut vec!["icq".to_string()]);
270 }
271
272 #[test]
273 fn clap_rejects_non_mainnet_and_command_local_network_options() {
274 let error = run([
275 OsString::from("--network"),
276 OsString::from("local"),
277 OsString::from("nns"),
278 OsString::from("registry"),
279 OsString::from("version"),
280 ])
281 .expect_err("non-mainnet network must fail in Clap");
282 assert_eq!(error.exit_code(), 2);
283 assert!(error.to_string().contains("invalid value 'local'"));
284
285 let error = run([
286 OsString::from("nns"),
287 OsString::from("registry"),
288 OsString::from("version"),
289 OsString::from("--network"),
290 OsString::from("ic"),
291 ])
292 .expect_err("network remains a top-level option");
293 assert_eq!(error.exit_code(), 2);
294 assert!(
295 error
296 .to_string()
297 .contains("unexpected argument '--network'")
298 );
299 }
300
301 #[test]
302 fn network_is_rejected_for_endpoint_identified_families() {
303 for args in [
304 &["--network", "ic", "ic", "canister", "count"][..],
305 &[
306 "--network",
307 "ic",
308 "icrc",
309 "ledger",
310 "token",
311 "ryjl3-tyaaa-aaaaa-aaaba-cai",
312 ],
313 ] {
314 let error = run(args.iter().map(OsString::from))
315 .expect_err("endpoint-identified families must reject --network");
316 assert_eq!(error.exit_code(), 2);
317 assert!(error.to_string().contains("--source-endpoint"));
318 }
319 }
320
321 #[test]
322 fn typed_cli_errors_preserve_exit_and_broken_pipe_semantics() {
323 for usage in [
324 IcqCliError::Ic(ic::IcCommandError::Usage("bad input".to_string())),
325 IcqCliError::Icrc(icrc::IcrcCommandError::Usage("bad input".to_string())),
326 IcqCliError::System(system::SystemCommandError::Usage("bad input".to_string())),
327 ] {
328 assert_eq!(usage.exit_code(), 2);
329 assert!(!usage.is_broken_pipe());
330 }
331
332 for broken_pipe in [
333 IcqCliError::Ic(ic::IcCommandError::Io(std::io::Error::from(
334 std::io::ErrorKind::BrokenPipe,
335 ))),
336 IcqCliError::Icrc(icrc::IcrcCommandError::Io(std::io::Error::from(
337 std::io::ErrorKind::BrokenPipe,
338 ))),
339 IcqCliError::System(system::SystemCommandError::Io(std::io::Error::from(
340 std::io::ErrorKind::BrokenPipe,
341 ))),
342 ] {
343 assert_eq!(broken_pipe.exit_code(), 1);
344 assert!(broken_pipe.is_broken_pipe());
345 }
346 }
347
348 fn assert_run_ok(args: &[&str]) {
349 let args = args.iter().copied().map(OsString::from).collect::<Vec<_>>();
350 if let Err(err) = run(args.clone()) {
351 panic!("expected {args:?} to succeed, got {err}");
352 }
353 }
354}