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