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