1use crate::cli::globals::{icp_arg, network_arg};
8use clap::{Arg, ArgAction, Command};
9use std::ffi::OsString;
10
11const TOP_LEVEL_HELP_TEMPLATE: &str = "{name} {version}\n{about-with-newline}\n{usage-heading} {usage}\n\n{before-help}Options:\n{options}{after-help}\n";
12const COLOR_RESET: &str = "\x1b[0m";
13const COLOR_HEADING: &str = "\x1b[1m";
14const COLOR_GROUP: &str = "\x1b[38;5;245m";
15const COLOR_COMMAND: &str = "\x1b[38;5;109m";
16const COLOR_TIP: &str = "\x1b[38;5;245m";
17
18#[derive(Clone, Copy, Debug, Eq, PartialEq)]
21enum CommandScope {
22 Project,
23 Deployment,
24 IcpWallet,
25 BackupRestore,
26}
27
28impl CommandScope {
29 const fn heading(self) -> &'static str {
30 match self {
31 Self::Project => "Project commands",
32 Self::Deployment => "Deployment commands",
33 Self::IcpWallet => "ICP wallet commands",
34 Self::BackupRestore => "Backup and restore commands",
35 }
36 }
37}
38
39#[derive(Clone, Copy, Debug, Eq, PartialEq)]
42pub(super) struct CommandSpec {
43 pub(super) name: &'static str,
44 about: &'static str,
45 scope: CommandScope,
46}
47
48pub(super) const COMMAND_SPECS: &[CommandSpec] = &[
49 CommandSpec {
50 name: "status",
51 about: "Show quick Canic project status",
52 scope: CommandScope::Project,
53 },
54 CommandSpec {
55 name: "medic",
56 about: "Diagnose project and deployment preflight readiness",
57 scope: CommandScope::Project,
58 },
59 CommandSpec {
60 name: "fleet",
61 about: "Manage Canic fleets and roles",
62 scope: CommandScope::Project,
63 },
64 CommandSpec {
65 name: "scaffold",
66 about: "Scaffold Canic source files",
67 scope: CommandScope::Project,
68 },
69 CommandSpec {
70 name: "replica",
71 about: "Manage the local ICP replica",
72 scope: CommandScope::Project,
73 },
74 CommandSpec {
75 name: "install",
76 about: "Install and bootstrap a Canic fleet",
77 scope: CommandScope::Deployment,
78 },
79 CommandSpec {
80 name: "blob-storage",
81 about: "Inspect and provision blob-storage billing",
82 scope: CommandScope::Deployment,
83 },
84 CommandSpec {
85 name: "auth",
86 about: "Run delegated-auth operator workflows",
87 scope: CommandScope::Deployment,
88 },
89 CommandSpec {
90 name: "build",
91 about: "Build one Canic canister artifact",
92 scope: CommandScope::Deployment,
93 },
94 CommandSpec {
95 name: "deploy",
96 about: "Check, inspect, register, and install deployments",
97 scope: CommandScope::Deployment,
98 },
99 CommandSpec {
100 name: "evidence",
101 about: "Evaluate stable evidence envelopes",
102 scope: CommandScope::Deployment,
103 },
104 CommandSpec {
105 name: "cycles",
106 about: "Wrap ICP cycles balance and transfer commands",
107 scope: CommandScope::IcpWallet,
108 },
109 CommandSpec {
110 name: "token",
111 about: "Wrap ICP token balance and transfer commands",
112 scope: CommandScope::IcpWallet,
113 },
114 CommandSpec {
115 name: "info",
116 about: "Query deployed canister information",
117 scope: CommandScope::Deployment,
118 },
119 CommandSpec {
120 name: "snapshot",
121 about: "Capture and download canister snapshots",
122 scope: CommandScope::BackupRestore,
123 },
124 CommandSpec {
125 name: "backup",
126 about: "Plan, inspect, and verify backups",
127 scope: CommandScope::BackupRestore,
128 },
129 CommandSpec {
130 name: "restore",
131 about: "Plan or run snapshot restores",
132 scope: CommandScope::BackupRestore,
133 },
134];
135
136fn is_help_arg(arg: &OsString) -> bool {
137 arg.to_str()
138 .is_some_and(|arg| matches!(arg, "help" | "--help" | "-h"))
139}
140
141fn is_version_arg(arg: &OsString) -> bool {
142 arg.to_str()
143 .is_some_and(|arg| matches!(arg, "version" | "--version" | "-V"))
144}
145
146pub fn first_arg_is_help(args: &[OsString]) -> bool {
148 args.first().is_some_and(is_help_arg)
149}
150
151fn first_arg_is_version(args: &[OsString]) -> bool {
152 args.first().is_some_and(is_version_arg)
153}
154
155pub fn print_help_or_version(
159 args: &[OsString],
160 usage: impl FnOnce() -> String,
161 version_text: &str,
162) -> bool {
163 if first_arg_is_help(args) {
164 println!("{}", usage());
165 return true;
166 }
167 if first_arg_is_version(args) {
168 println!("{version_text}");
169 return true;
170 }
171 false
172}
173
174#[must_use]
175pub fn top_level_command() -> Command {
177 let command = Command::new("canic")
178 .version(env!("CARGO_PKG_VERSION"))
179 .about("Operator CLI for Canic projects, deployments, backups, and ICP wallet workflows")
180 .disable_version_flag(true)
181 .arg(
182 Arg::new("version")
183 .short('V')
184 .long("version")
185 .action(ArgAction::SetTrue)
186 .help("Print version"),
187 )
188 .arg(icp_arg().global(true))
189 .arg(network_arg().global(true))
190 .subcommand_help_heading("Commands")
191 .help_template(TOP_LEVEL_HELP_TEMPLATE)
192 .before_help(grouped_command_section(COMMAND_SPECS).join("\n"))
193 .after_help("Run `canic <command> help` for command-specific help.");
194
195 COMMAND_SPECS.iter().fold(command, |command, spec| {
196 command.subcommand(Command::new(spec.name).about(spec.about))
197 })
198}
199
200pub fn usage() -> String {
202 let mut lines = vec![
203 color(
204 COLOR_HEADING,
205 &format!("Canic Operator CLI v{}", env!("CARGO_PKG_VERSION")),
206 ),
207 String::new(),
208 "Usage: canic [OPTIONS] <COMMAND>".to_string(),
209 String::new(),
210 color(COLOR_HEADING, "Commands:"),
211 ];
212 lines.extend(grouped_command_section(COMMAND_SPECS));
213 lines.extend([
214 String::new(),
215 color(COLOR_HEADING, "Options:"),
216 " --icp <path> Path to the icp executable for ICP-backed commands".to_string(),
217 " --network <name> ICP CLI network for networked commands".to_string(),
218 " -V, --version Print version".to_string(),
219 " -h, --help Print help".to_string(),
220 String::new(),
221 format!(
222 "{}Tip:{} Run {} for command-specific help.",
223 COLOR_TIP,
224 COLOR_RESET,
225 color(COLOR_COMMAND, "`canic <command> help`")
226 ),
227 ]);
228 lines.join("\n")
229}
230
231fn grouped_command_section(specs: &[CommandSpec]) -> Vec<String> {
232 let mut lines = Vec::new();
233 let scopes = [
234 CommandScope::Project,
235 CommandScope::Deployment,
236 CommandScope::IcpWallet,
237 CommandScope::BackupRestore,
238 ];
239 for scope in scopes {
240 let scope_specs = specs
241 .iter()
242 .filter(|spec| spec.scope == scope)
243 .collect::<Vec<_>>();
244 if scope_specs.is_empty() {
245 continue;
246 }
247 if !lines.is_empty() {
248 lines.push(String::new());
249 }
250 lines.push(format!(" {}", color(COLOR_GROUP, scope.heading())));
251 for spec in scope_specs {
252 let command = format!("{:<12}", spec.name);
253 lines.push(format!(
254 " {} {}",
255 color(COLOR_COMMAND, &command),
256 spec.about
257 ));
258 }
259 }
260 lines
261}
262
263fn color(code: &str, text: &str) -> String {
264 format!("{code}{text}{COLOR_RESET}")
265}
266
267#[cfg(test)]
271mod tests {
272 use super::*;
273
274 #[test]
276 fn usage_contains_help_colors() {
277 let text = usage();
278
279 assert!(text.contains(COLOR_HEADING));
280 assert!(text.contains(COLOR_GROUP));
281 assert!(text.contains(COLOR_COMMAND));
282 }
283
284 #[test]
285 fn first_arg_help_and_version_detection_accepts_aliases() {
286 assert!(first_arg_is_help(&[OsString::from("help")]));
287 assert!(first_arg_is_help(&[OsString::from("--help")]));
288 assert!(first_arg_is_help(&[OsString::from("-h")]));
289 assert!(first_arg_is_version(&[OsString::from("version")]));
290 assert!(first_arg_is_version(&[OsString::from("--version")]));
291 assert!(first_arg_is_version(&[OsString::from("-V")]));
292 }
293}