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: "fleet",
56 about: "Manage Canic fleets and roles",
57 scope: CommandScope::Project,
58 },
59 CommandSpec {
60 name: "scaffold",
61 about: "Scaffold Canic source files",
62 scope: CommandScope::Project,
63 },
64 CommandSpec {
65 name: "replica",
66 about: "Manage the local ICP replica",
67 scope: CommandScope::Project,
68 },
69 CommandSpec {
70 name: "install",
71 about: "Install and bootstrap a Canic fleet",
72 scope: CommandScope::Deployment,
73 },
74 CommandSpec {
75 name: "blob-storage",
76 about: "Inspect and provision blob-storage billing",
77 scope: CommandScope::Deployment,
78 },
79 CommandSpec {
80 name: "build",
81 about: "Build one Canic canister artifact",
82 scope: CommandScope::Deployment,
83 },
84 CommandSpec {
85 name: "deploy",
86 about: "Check, inspect, register, and install deployments",
87 scope: CommandScope::Deployment,
88 },
89 CommandSpec {
90 name: "evidence",
91 about: "Evaluate stable evidence envelopes",
92 scope: CommandScope::Deployment,
93 },
94 CommandSpec {
95 name: "cycles",
96 about: "Wrap ICP cycles balance and transfer commands",
97 scope: CommandScope::IcpWallet,
98 },
99 CommandSpec {
100 name: "token",
101 about: "Wrap ICP token balance and transfer commands",
102 scope: CommandScope::IcpWallet,
103 },
104 CommandSpec {
105 name: "info",
106 about: "Query deployed canister information",
107 scope: CommandScope::Deployment,
108 },
109 CommandSpec {
110 name: "snapshot",
111 about: "Capture and download canister snapshots",
112 scope: CommandScope::BackupRestore,
113 },
114 CommandSpec {
115 name: "backup",
116 about: "Plan, inspect, and verify backups",
117 scope: CommandScope::BackupRestore,
118 },
119 CommandSpec {
120 name: "restore",
121 about: "Plan or run snapshot restores",
122 scope: CommandScope::BackupRestore,
123 },
124];
125
126fn is_help_arg(arg: &OsString) -> bool {
127 arg.to_str()
128 .is_some_and(|arg| matches!(arg, "help" | "--help" | "-h"))
129}
130
131fn is_version_arg(arg: &OsString) -> bool {
132 arg.to_str()
133 .is_some_and(|arg| matches!(arg, "version" | "--version" | "-V"))
134}
135
136pub fn first_arg_is_help(args: &[OsString]) -> bool {
138 args.first().is_some_and(is_help_arg)
139}
140
141fn first_arg_is_version(args: &[OsString]) -> bool {
142 args.first().is_some_and(is_version_arg)
143}
144
145pub fn print_help_or_version(
149 args: &[OsString],
150 usage: impl FnOnce() -> String,
151 version_text: &str,
152) -> bool {
153 if first_arg_is_help(args) {
154 println!("{}", usage());
155 return true;
156 }
157 if first_arg_is_version(args) {
158 println!("{version_text}");
159 return true;
160 }
161 false
162}
163
164#[must_use]
165pub fn top_level_command() -> Command {
167 let command = Command::new("canic")
168 .version(env!("CARGO_PKG_VERSION"))
169 .about("Operator CLI for Canic projects, deployments, backups, and ICP wallet workflows")
170 .disable_version_flag(true)
171 .arg(
172 Arg::new("version")
173 .short('V')
174 .long("version")
175 .action(ArgAction::SetTrue)
176 .help("Print version"),
177 )
178 .arg(icp_arg().global(true))
179 .arg(network_arg().global(true))
180 .subcommand_help_heading("Commands")
181 .help_template(TOP_LEVEL_HELP_TEMPLATE)
182 .before_help(grouped_command_section(COMMAND_SPECS).join("\n"))
183 .after_help("Run `canic <command> help` for command-specific help.");
184
185 COMMAND_SPECS.iter().fold(command, |command, spec| {
186 command.subcommand(Command::new(spec.name).about(spec.about))
187 })
188}
189
190pub fn usage() -> String {
192 let mut lines = vec![
193 color(
194 COLOR_HEADING,
195 &format!("Canic Operator CLI v{}", env!("CARGO_PKG_VERSION")),
196 ),
197 String::new(),
198 "Usage: canic [OPTIONS] <COMMAND>".to_string(),
199 String::new(),
200 color(COLOR_HEADING, "Commands:"),
201 ];
202 lines.extend(grouped_command_section(COMMAND_SPECS));
203 lines.extend([
204 String::new(),
205 color(COLOR_HEADING, "Options:"),
206 " --icp <path> Path to the icp executable for ICP-backed commands".to_string(),
207 " --network <name> ICP CLI network for networked commands".to_string(),
208 " -V, --version Print version".to_string(),
209 " -h, --help Print help".to_string(),
210 String::new(),
211 format!(
212 "{}Tip:{} Run {} for command-specific help.",
213 COLOR_TIP,
214 COLOR_RESET,
215 color(COLOR_COMMAND, "`canic <command> help`")
216 ),
217 ]);
218 lines.join("\n")
219}
220
221fn grouped_command_section(specs: &[CommandSpec]) -> Vec<String> {
222 let mut lines = Vec::new();
223 let scopes = [
224 CommandScope::Project,
225 CommandScope::Deployment,
226 CommandScope::IcpWallet,
227 CommandScope::BackupRestore,
228 ];
229 for scope in scopes {
230 let scope_specs = specs
231 .iter()
232 .filter(|spec| spec.scope == scope)
233 .collect::<Vec<_>>();
234 if scope_specs.is_empty() {
235 continue;
236 }
237 if !lines.is_empty() {
238 lines.push(String::new());
239 }
240 lines.push(format!(" {}", color(COLOR_GROUP, scope.heading())));
241 for spec in scope_specs {
242 let command = format!("{:<12}", spec.name);
243 lines.push(format!(
244 " {} {}",
245 color(COLOR_COMMAND, &command),
246 spec.about
247 ));
248 }
249 }
250 lines
251}
252
253fn color(code: &str, text: &str) -> String {
254 format!("{code}{text}{COLOR_RESET}")
255}
256
257#[cfg(test)]
261mod tests {
262 use super::*;
263
264 #[test]
266 fn usage_contains_help_colors() {
267 let text = usage();
268
269 assert!(text.contains(COLOR_HEADING));
270 assert!(text.contains(COLOR_GROUP));
271 assert!(text.contains(COLOR_COMMAND));
272 }
273
274 #[test]
275 fn first_arg_help_and_version_detection_accepts_aliases() {
276 assert!(first_arg_is_help(&[OsString::from("help")]));
277 assert!(first_arg_is_help(&[OsString::from("--help")]));
278 assert!(first_arg_is_help(&[OsString::from("-h")]));
279 assert!(first_arg_is_version(&[OsString::from("version")]));
280 assert!(first_arg_is_version(&[OsString::from("--version")]));
281 assert!(first_arg_is_version(&[OsString::from("-V")]));
282 }
283}