Skip to main content

canic_cli/cli/
help.rs

1//! Module: canic_cli::cli::help
2//!
3//! Responsibility: render top-level CLI help and detect 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: "app",
28        about: "Manage Canic source apps and roles",
29    },
30    CommandSpec {
31        name: "auth",
32        about: "Run delegated-auth operator workflows",
33    },
34    CommandSpec {
35        name: "backup",
36        about: "Plan, inspect, and verify backups",
37    },
38    CommandSpec {
39        name: "blob-storage",
40        about: "Inspect and provision blob-storage billing",
41    },
42    CommandSpec {
43        name: "build",
44        about: "Build Canic App and infrastructure artifacts",
45    },
46    CommandSpec {
47        name: "cycles",
48        about: "Wrap ICP cycles balance and transfer commands",
49    },
50    CommandSpec {
51        name: "deploy",
52        about: "Plan and check deployment truth before mutation",
53    },
54    CommandSpec {
55        name: "evidence",
56        about: "Evaluate stable evidence envelopes",
57    },
58    CommandSpec {
59        name: "info",
60        about: "Query deployed canister information",
61    },
62    CommandSpec {
63        name: "inspect",
64        about: "Inspect runtime-observed status for one deployed canister",
65    },
66    CommandSpec {
67        name: "install",
68        about: "Install and bootstrap a Canic fleet",
69    },
70    CommandSpec {
71        name: "medic",
72        about: "Diagnose workspace and Fleet preflight readiness",
73    },
74    CommandSpec {
75        name: "network",
76        about: "Enroll canonical network trust identities",
77    },
78    CommandSpec {
79        name: "replica",
80        about: "Manage the local ICP replica",
81    },
82    CommandSpec {
83        name: "restore",
84        about: "Plan or run snapshot restores",
85    },
86    CommandSpec {
87        name: "scaffold",
88        about: "Scaffold Canic source files",
89    },
90    CommandSpec {
91        name: "state",
92        about: "Audit declared Canic state metadata",
93    },
94    CommandSpec {
95        name: "status",
96        about: "Show quick local workspace status",
97    },
98    CommandSpec {
99        name: "token",
100        about: "Wrap ICP token balance and transfer commands",
101    },
102];
103
104fn is_help_arg(arg: &OsString) -> bool {
105    arg.to_str()
106        .is_some_and(|arg| matches!(arg, "--help" | "-h"))
107}
108
109fn is_version_arg(arg: &OsString) -> bool {
110    arg.to_str()
111        .is_some_and(|arg| matches!(arg, "--version" | "-V"))
112}
113
114/// Return whether the first CLI argument requests help.
115pub fn first_arg_is_help(args: &[OsString]) -> bool {
116    args.first().is_some_and(is_help_arg)
117}
118
119fn first_arg_is_version(args: &[OsString]) -> bool {
120    args.first().is_some_and(is_version_arg)
121}
122
123/// Print help or version text when the first CLI argument requests it.
124///
125/// Returns `true` when the caller should stop command execution.
126pub fn print_help_or_version(
127    args: &[OsString],
128    usage: impl FnOnce() -> String,
129    version_text: &str,
130) -> bool {
131    if first_arg_is_help(args) {
132        println!("{}", usage());
133        return true;
134    }
135    if first_arg_is_version(args) {
136        println!("{version_text}");
137        return true;
138    }
139    false
140}
141
142#[must_use]
143/// Build the top-level Clap command used for public help rendering.
144pub fn top_level_command() -> Command {
145    let command = Command::new("canic")
146        .version(env!("CARGO_PKG_VERSION"))
147        .about("Operator CLI for Canic Apps, Fleets, backups, and ICP wallet workflows")
148        .color(ColorChoice::Always)
149        .subcommand_required(true)
150        .arg(icp_arg())
151        .arg(environment_arg())
152        .subcommand_help_heading("Commands")
153        .help_template(TOP_LEVEL_HELP_TEMPLATE)
154        .before_help(format!(
155            "{}Commands:{}\n{}",
156            COLOR_HEADING,
157            COLOR_RESET,
158            command_section(COMMAND_SPECS).join("\n")
159        ))
160        .after_help(format!(
161            "\n{}Tip:{} Run {} for command-specific help.",
162            COLOR_TIP,
163            COLOR_RESET,
164            color(COLOR_COMMAND, "`canic <command> --help`")
165        ));
166
167    COMMAND_SPECS.iter().fold(command, |command, spec| {
168        command.subcommand(
169            Command::new(spec.name)
170                .about(spec.about)
171                .disable_help_flag(true)
172                .disable_version_flag(true)
173                .arg(
174                    Arg::new(DISPATCH_ARGS)
175                        .num_args(0..)
176                        .allow_hyphen_values(true)
177                        .trailing_var_arg(true)
178                        .value_parser(clap::value_parser!(OsString))
179                        .hide(true),
180                ),
181        )
182    })
183}
184
185/// Render Canic's custom colorized top-level usage text.
186#[cfg(test)]
187pub fn usage() -> String {
188    let help = top_level_command().render_help();
189    help.ansi().to_string()
190}
191
192fn command_section(specs: &[CommandSpec]) -> Vec<String> {
193    specs
194        .iter()
195        .map(|spec| {
196            let command = format!("{:<12}", spec.name);
197            format!("  {} {}", color(COLOR_COMMAND, &command), spec.about)
198        })
199        .collect()
200}
201
202fn color(code: &str, text: &str) -> String {
203    format!("{code}{text}{COLOR_RESET}")
204}
205
206// -----------------------------------------------------------------------------
207// Tests
208
209#[cfg(test)]
210mod tests {
211    use super::*;
212
213    // Ensure top-level usage keeps the intended help colors.
214    #[test]
215    fn usage_contains_help_colors() {
216        let text = usage();
217
218        assert!(text.contains(COLOR_HEADING));
219        assert!(text.contains(COLOR_COMMAND));
220    }
221
222    #[test]
223    fn first_arg_help_and_version_detection_accepts_flags() {
224        assert!(first_arg_is_help(&[OsString::from("--help")]));
225        assert!(first_arg_is_help(&[OsString::from("-h")]));
226        assert!(first_arg_is_version(&[OsString::from("--version")]));
227        assert!(first_arg_is_version(&[OsString::from("-V")]));
228    }
229}