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