1use crate::cli::globals::{DISPATCH_ARGS, environment_arg, icp_arg};
8use clap::{Arg, ColorChoice, Command};
9use std::ffi::OsString;
10
11const TOP_LEVEL_HELP_TEMPLATE: &str = "Canic Operator CLI v{version}\n{about-with-newline}\n{usage-heading} {usage}\n\n{before-help}\x1b[1mOptions:\x1b[0m\n{options}{after-help}\n";
12const COLOR_RESET: &str = "\x1b[0m";
13const COLOR_HEADING: &str = "\x1b[1m";
14const COLOR_COMMAND: &str = "\x1b[38;5;109m";
15const COLOR_TIP: &str = "\x1b[38;5;245m";
16
17#[derive(Clone, Copy, Debug, Eq, PartialEq)]
20pub(super) struct CommandSpec {
21 pub(super) name: &'static str,
22 about: &'static str,
23}
24
25pub(super) const COMMAND_SPECS: &[CommandSpec] = &[
26 CommandSpec {
27 name: "admission",
28 about: "Plan, apply, and inspect Fleet ingress admission",
29 },
30 CommandSpec {
31 name: "app",
32 about: "Manage Canic source apps and roles",
33 },
34 CommandSpec {
35 name: "auth",
36 about: "Inspect delegated-auth operation state",
37 },
38 CommandSpec {
39 name: "backup",
40 about: "Create, inspect, and verify backups",
41 },
42 CommandSpec {
43 name: "blob-storage",
44 about: "Inspect and manage blob-storage billing",
45 },
46 CommandSpec {
47 name: "build",
48 about: "Build Canic App and infrastructure artifacts",
49 },
50 CommandSpec {
51 name: "cycles",
52 about: "Inspect and transfer cycles for current Fleets",
53 },
54 CommandSpec {
55 name: "diagnostic",
56 about: "Look up one compact Canic diagnostic code",
57 },
58 CommandSpec {
59 name: "evidence",
60 about: "Evaluate stable evidence envelopes",
61 },
62 CommandSpec {
63 name: "fleet",
64 about: "Converge one Fleet from current desired state",
65 },
66 CommandSpec {
67 name: "info",
68 about: "Inspect one terminal current Fleet",
69 },
70 CommandSpec {
71 name: "inspect",
72 about: "Inspect one current Fleet canister runtime",
73 },
74 CommandSpec {
75 name: "medic",
76 about: "Diagnose workspace and current-Fleet readiness",
77 },
78 CommandSpec {
79 name: "network",
80 about: "Enroll canonical network trust identities",
81 },
82 CommandSpec {
83 name: "replica",
84 about: "Manage the local ICP replica",
85 },
86 CommandSpec {
87 name: "restore",
88 about: "Plan or run snapshot restores",
89 },
90 CommandSpec {
91 name: "scaffold",
92 about: "Scaffold Canic source roles",
93 },
94 CommandSpec {
95 name: "state",
96 about: "Audit declared Canic state metadata",
97 },
98 CommandSpec {
99 name: "status",
100 about: "Show quick local workspace status",
101 },
102 CommandSpec {
103 name: "token",
104 about: "Wrap ICP token balance and transfer commands",
105 },
106 CommandSpec {
107 name: "toolchain",
108 about: "Install checksum-authoritative release tools",
109 },
110];
111
112fn is_help_arg(arg: &OsString) -> bool {
113 arg.to_str()
114 .is_some_and(|arg| matches!(arg, "--help" | "-h"))
115}
116
117fn is_version_arg(arg: &OsString) -> bool {
118 arg.to_str()
119 .is_some_and(|arg| matches!(arg, "--version" | "-V"))
120}
121
122pub fn first_arg_is_help(args: &[OsString]) -> bool {
124 args.first().is_some_and(is_help_arg)
125}
126
127fn first_arg_is_version(args: &[OsString]) -> bool {
128 args.first().is_some_and(is_version_arg)
129}
130
131pub fn print_help_or_version(
135 args: &[OsString],
136 usage: impl FnOnce() -> String,
137 version_text: &str,
138) -> bool {
139 if first_arg_is_help(args) {
140 println!("{}", usage());
141 return true;
142 }
143 if first_arg_is_version(args) {
144 println!("{version_text}");
145 return true;
146 }
147 false
148}
149
150pub fn print_nested_help(args: &[OsString], mut command: Command) -> bool {
152 let mut path = command
153 .get_bin_name()
154 .unwrap_or_else(|| command.get_name())
155 .to_string();
156 for arg in args {
157 if is_help_arg(arg) {
158 println!("{}", command.bin_name(path).render_help());
159 return true;
160 }
161 let Some(child) = command
162 .get_subcommands()
163 .find(|child| Some(child.get_name()) == arg.to_str())
164 .cloned()
165 else {
166 return false;
167 };
168 path.push(' ');
169 path.push_str(child.get_name());
170 command = child;
171 }
172 false
173}
174
175#[must_use]
176pub fn top_level_command() -> Command {
178 let command = Command::new("canic")
179 .version(env!("CARGO_PKG_VERSION"))
180 .about("Operator CLI for current Canic Apps and Fleets")
181 .color(ColorChoice::Always)
182 .subcommand_required(true)
183 .arg(icp_arg())
184 .arg(environment_arg())
185 .subcommand_help_heading("Commands")
186 .help_template(TOP_LEVEL_HELP_TEMPLATE)
187 .before_help(format!(
188 "{}Commands:{}\n{}",
189 COLOR_HEADING,
190 COLOR_RESET,
191 command_section(COMMAND_SPECS).join("\n")
192 ))
193 .after_help(format!(
194 "\n{}Tip:{} Run {} for command-specific help.",
195 COLOR_TIP,
196 COLOR_RESET,
197 color(COLOR_COMMAND, "`canic <command> --help`")
198 ));
199
200 COMMAND_SPECS.iter().fold(command, |command, spec| {
201 command.subcommand(
202 Command::new(spec.name)
203 .about(spec.about)
204 .disable_help_flag(true)
205 .disable_version_flag(true)
206 .arg(
207 Arg::new(DISPATCH_ARGS)
208 .num_args(0..)
209 .allow_hyphen_values(true)
210 .trailing_var_arg(true)
211 .value_parser(clap::value_parser!(OsString))
212 .hide(true),
213 ),
214 )
215 })
216}
217
218#[cfg(test)]
220pub fn usage() -> String {
221 let help = top_level_command().render_help();
222 help.ansi().to_string()
223}
224
225fn command_section(specs: &[CommandSpec]) -> Vec<String> {
226 specs
227 .iter()
228 .map(|spec| {
229 let command = format!("{:<12}", spec.name);
230 format!(" {} {}", color(COLOR_COMMAND, &command), spec.about)
231 })
232 .collect()
233}
234
235fn color(code: &str, text: &str) -> String {
236 format!("{code}{text}{COLOR_RESET}")
237}
238
239#[cfg(test)]
243mod tests {
244 use super::*;
245
246 #[test]
248 fn usage_contains_help_colors() {
249 let text = usage();
250
251 assert!(text.contains(COLOR_HEADING));
252 assert!(text.contains(COLOR_COMMAND));
253 }
254
255 #[test]
256 fn first_arg_help_and_version_detection_accepts_flags() {
257 assert!(first_arg_is_help(&[OsString::from("--help")]));
258 assert!(first_arg_is_help(&[OsString::from("-h")]));
259 assert!(first_arg_is_version(&[OsString::from("--version")]));
260 assert!(first_arg_is_version(&[OsString::from("-V")]));
261 }
262}