Skip to main content

canic_cli/cli/
help.rs

1//! Module: canic_cli::cli::help
2//!
3//! Responsibility: render the CLI catalog and route help/version requests.
4//! Does not own: command execution, command-specific help text, or global option forwarding.
5//! Boundary: defines the top-level command catalog shared by help and dispatch.
6
7use 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/// One top-level command shown in help and accepted by dispatch.
18
19#[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: "build",
44        about: "Build Canic App and infrastructure artifacts",
45    },
46    CommandSpec {
47        name: "component",
48        about: "Review, create and reconcile one top-level Component",
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 a diagnostic code or inspect a build lock",
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: "frontend",
68        about: "Export and verify exact frontend environment bindings",
69    },
70    CommandSpec {
71        name: "info",
72        about: "Inspect one terminal current Fleet",
73    },
74    CommandSpec {
75        name: "inspect",
76        about: "Inspect one current Fleet canister runtime",
77    },
78    CommandSpec {
79        name: "medic",
80        about: "Diagnose workspace and current-Fleet readiness",
81    },
82    CommandSpec {
83        name: "network",
84        about: "Enroll canonical network trust identities",
85    },
86    CommandSpec {
87        name: "observatory",
88        about: "Collect bounded Fleet observations and public reports",
89    },
90    CommandSpec {
91        name: "replica",
92        about: "Manage the local ICP replica",
93    },
94    CommandSpec {
95        name: "restore",
96        about: "Plan or run snapshot restores",
97    },
98    CommandSpec {
99        name: "scaffold",
100        about: "Scaffold Canic source roles",
101    },
102    CommandSpec {
103        name: "state",
104        about: "Audit declared Canic state metadata",
105    },
106    CommandSpec {
107        name: "status",
108        about: "Show quick local workspace status",
109    },
110    CommandSpec {
111        name: "token",
112        about: "Wrap ICP token balance and transfer commands",
113    },
114    CommandSpec {
115        name: "toolchain",
116        about: "Install checksum-authoritative release tools",
117    },
118];
119
120fn is_help_arg(arg: &OsString) -> bool {
121    arg.to_str()
122        .is_some_and(|arg| matches!(arg, "--help" | "-h"))
123}
124
125fn is_version_arg(arg: &OsString) -> bool {
126    arg.to_str()
127        .is_some_and(|arg| matches!(arg, "--version" | "-V"))
128}
129
130/// Return whether the first CLI argument requests help.
131pub fn first_arg_is_help(args: &[OsString]) -> bool {
132    args.first().is_some_and(is_help_arg)
133}
134
135fn first_arg_is_version(args: &[OsString]) -> bool {
136    args.first().is_some_and(is_version_arg)
137}
138
139/// Print help or version text when the first CLI argument requests it.
140///
141/// Returns `true` when the caller should stop command execution.
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/// Print help for an exact nested command before parsing its required operands.
159pub fn print_nested_help(args: &[OsString], mut command: Command) -> bool {
160    let mut path = command
161        .get_bin_name()
162        .unwrap_or_else(|| command.get_name())
163        .to_string();
164    for arg in args {
165        if is_help_arg(arg) {
166            println!("{}", command.bin_name(path).render_help());
167            return true;
168        }
169        let Some(child) = command
170            .get_subcommands()
171            .find(|child| Some(child.get_name()) == arg.to_str())
172            .cloned()
173        else {
174            return false;
175        };
176        path.push(' ');
177        path.push_str(child.get_name());
178        command = child;
179    }
180    false
181}
182
183#[must_use]
184/// Build the top-level Clap command used for public help rendering.
185pub fn top_level_command() -> Command {
186    let command = Command::new("canic")
187        .version(env!("CARGO_PKG_VERSION"))
188        .about("Operator CLI for current Canic Apps and Fleets")
189        .color(ColorChoice::Always)
190        .subcommand_required(true)
191        .arg(icp_arg())
192        .arg(environment_arg())
193        .subcommand_help_heading("Commands")
194        .help_template(TOP_LEVEL_HELP_TEMPLATE)
195        .before_help(format!(
196            "{}Commands:{}\n{}",
197            COLOR_HEADING,
198            COLOR_RESET,
199            command_section(COMMAND_SPECS).join("\n")
200        ))
201        .after_help(format!(
202            "\n{}Tip:{} Run {} for command-specific help.",
203            COLOR_TIP,
204            COLOR_RESET,
205            color(COLOR_COMMAND, "`canic <command> --help`")
206        ));
207
208    COMMAND_SPECS.iter().fold(command, |command, spec| {
209        command.subcommand(
210            Command::new(spec.name)
211                .about(spec.about)
212                .disable_help_flag(true)
213                .disable_version_flag(true)
214                .arg(
215                    Arg::new(DISPATCH_ARGS)
216                        .num_args(0..)
217                        .allow_hyphen_values(true)
218                        .trailing_var_arg(true)
219                        .value_parser(clap::value_parser!(OsString))
220                        .hide(true),
221                ),
222        )
223    })
224}
225
226/// Render Canic's custom colorized top-level usage text.
227#[cfg(test)]
228pub fn usage() -> String {
229    let help = top_level_command().render_help();
230    help.ansi().to_string()
231}
232
233fn command_section(specs: &[CommandSpec]) -> Vec<String> {
234    specs
235        .iter()
236        .map(|spec| {
237            let command = format!("{:<12}", spec.name);
238            format!("  {} {}", color(COLOR_COMMAND, &command), spec.about)
239        })
240        .collect()
241}
242
243fn color(code: &str, text: &str) -> String {
244    format!("{code}{text}{COLOR_RESET}")
245}
246
247// -----------------------------------------------------------------------------
248// Tests
249
250#[cfg(test)]
251mod tests {
252    use super::*;
253
254    // Ensure top-level usage keeps the intended help colors.
255    #[test]
256    fn usage_contains_help_colors() {
257        let text = usage();
258
259        assert!(text.contains(COLOR_HEADING));
260        assert!(text.contains(COLOR_COMMAND));
261    }
262
263    #[test]
264    fn first_arg_help_and_version_detection_accepts_flags() {
265        assert!(first_arg_is_help(&[OsString::from("--help")]));
266        assert!(first_arg_is_help(&[OsString::from("-h")]));
267        assert!(first_arg_is_version(&[OsString::from("--version")]));
268        assert!(first_arg_is_version(&[OsString::from("-V")]));
269    }
270}