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