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