Skip to main content

canic_cli/cli/
help.rs

1use crate::cli::globals::{icp_arg, network_arg};
2use clap::{Arg, ArgAction, Command};
3use std::ffi::OsString;
4
5const 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";
6const COLOR_RESET: &str = "\x1b[0m";
7const COLOR_HEADING: &str = "\x1b[1m";
8const COLOR_GROUP: &str = "\x1b[38;5;245m";
9const COLOR_COMMAND: &str = "\x1b[38;5;109m";
10const COLOR_TIP: &str = "\x1b[38;5;245m";
11
12///
13/// CommandScope
14///
15
16#[derive(Clone, Copy, Debug, Eq, PartialEq)]
17enum CommandScope {
18    Project,
19    Deployment,
20    IcpWallet,
21    BackupRestore,
22}
23
24impl CommandScope {
25    const fn heading(self) -> &'static str {
26        match self {
27            Self::Project => "Project commands",
28            Self::Deployment => "Deployment commands",
29            Self::IcpWallet => "ICP wallet commands",
30            Self::BackupRestore => "Backup and restore commands",
31        }
32    }
33}
34
35///
36/// CommandSpec
37///
38
39#[derive(Clone, Copy, Debug, Eq, PartialEq)]
40pub(super) struct CommandSpec {
41    pub(super) name: &'static str,
42    about: &'static str,
43    scope: CommandScope,
44}
45
46pub(super) const COMMAND_SPECS: &[CommandSpec] = &[
47    CommandSpec {
48        name: "status",
49        about: "Show quick Canic project status",
50        scope: CommandScope::Project,
51    },
52    CommandSpec {
53        name: "fleet",
54        about: "Manage Canic fleets and roles",
55        scope: CommandScope::Project,
56    },
57    CommandSpec {
58        name: "scaffold",
59        about: "Scaffold Canic source files",
60        scope: CommandScope::Project,
61    },
62    CommandSpec {
63        name: "replica",
64        about: "Manage the local ICP replica",
65        scope: CommandScope::Project,
66    },
67    CommandSpec {
68        name: "install",
69        about: "Install and bootstrap a Canic fleet",
70        scope: CommandScope::Deployment,
71    },
72    CommandSpec {
73        name: "build",
74        about: "Build one Canic canister artifact",
75        scope: CommandScope::Deployment,
76    },
77    CommandSpec {
78        name: "deploy",
79        about: "Check, inspect, register, and install deployments",
80        scope: CommandScope::Deployment,
81    },
82    CommandSpec {
83        name: "evidence",
84        about: "Evaluate stable evidence envelopes",
85        scope: CommandScope::Deployment,
86    },
87    CommandSpec {
88        name: "cycles",
89        about: "Wrap ICP cycles balance and transfer commands",
90        scope: CommandScope::IcpWallet,
91    },
92    CommandSpec {
93        name: "token",
94        about: "Wrap ICP token balance and transfer commands",
95        scope: CommandScope::IcpWallet,
96    },
97    CommandSpec {
98        name: "info",
99        about: "Query deployed canister information",
100        scope: CommandScope::Deployment,
101    },
102    CommandSpec {
103        name: "snapshot",
104        about: "Capture and download canister snapshots",
105        scope: CommandScope::BackupRestore,
106    },
107    CommandSpec {
108        name: "backup",
109        about: "Plan, inspect, and verify backups",
110        scope: CommandScope::BackupRestore,
111    },
112    CommandSpec {
113        name: "restore",
114        about: "Plan or run snapshot restores",
115        scope: CommandScope::BackupRestore,
116    },
117];
118
119fn is_help_arg(arg: &OsString) -> bool {
120    arg.to_str()
121        .is_some_and(|arg| matches!(arg, "help" | "--help" | "-h"))
122}
123
124fn is_version_arg(arg: &OsString) -> bool {
125    arg.to_str()
126        .is_some_and(|arg| matches!(arg, "version" | "--version" | "-V"))
127}
128
129pub fn first_arg_is_help(args: &[OsString]) -> bool {
130    args.first().is_some_and(is_help_arg)
131}
132
133fn first_arg_is_version(args: &[OsString]) -> bool {
134    args.first().is_some_and(is_version_arg)
135}
136
137pub fn print_help_or_version(
138    args: &[OsString],
139    usage: impl FnOnce() -> String,
140    version_text: &str,
141) -> bool {
142    if first_arg_is_help(args) {
143        println!("{}", usage());
144        return true;
145    }
146    if first_arg_is_version(args) {
147        println!("{version_text}");
148        return true;
149    }
150    false
151}
152
153#[must_use]
154pub fn top_level_command() -> Command {
155    let command = Command::new("canic")
156        .version(env!("CARGO_PKG_VERSION"))
157        .about("Operator CLI for Canic projects, deployments, backups, and ICP wallet workflows")
158        .disable_version_flag(true)
159        .arg(
160            Arg::new("version")
161                .short('V')
162                .long("version")
163                .action(ArgAction::SetTrue)
164                .help("Print version"),
165        )
166        .arg(icp_arg().global(true))
167        .arg(network_arg().global(true))
168        .subcommand_help_heading("Commands")
169        .help_template(TOP_LEVEL_HELP_TEMPLATE)
170        .before_help(grouped_command_section(COMMAND_SPECS).join("\n"))
171        .after_help("Run `canic <command> help` for command-specific help.");
172
173    COMMAND_SPECS.iter().fold(command, |command, spec| {
174        command.subcommand(Command::new(spec.name).about(spec.about))
175    })
176}
177
178pub fn usage() -> String {
179    let mut lines = vec![
180        color(
181            COLOR_HEADING,
182            &format!("Canic Operator CLI v{}", env!("CARGO_PKG_VERSION")),
183        ),
184        String::new(),
185        "Usage: canic [OPTIONS] <COMMAND>".to_string(),
186        String::new(),
187        color(COLOR_HEADING, "Commands:"),
188    ];
189    lines.extend(grouped_command_section(COMMAND_SPECS));
190    lines.extend([
191        String::new(),
192        color(COLOR_HEADING, "Options:"),
193        "      --icp <path>      Path to the icp executable for ICP-backed commands".to_string(),
194        "      --network <name>  ICP CLI network for networked commands".to_string(),
195        "  -V, --version  Print version".to_string(),
196        "  -h, --help     Print help".to_string(),
197        String::new(),
198        format!(
199            "{}Tip:{} Run {} for command-specific help.",
200            COLOR_TIP,
201            COLOR_RESET,
202            color(COLOR_COMMAND, "`canic <command> help`")
203        ),
204    ]);
205    lines.join("\n")
206}
207
208fn grouped_command_section(specs: &[CommandSpec]) -> Vec<String> {
209    let mut lines = Vec::new();
210    let scopes = [
211        CommandScope::Project,
212        CommandScope::Deployment,
213        CommandScope::IcpWallet,
214        CommandScope::BackupRestore,
215    ];
216    for scope in scopes {
217        let scope_specs = specs
218            .iter()
219            .filter(|spec| spec.scope == scope)
220            .collect::<Vec<_>>();
221        if scope_specs.is_empty() {
222            continue;
223        }
224        if !lines.is_empty() {
225            lines.push(String::new());
226        }
227        lines.push(format!("  {}", color(COLOR_GROUP, scope.heading())));
228        for spec in scope_specs {
229            let command = format!("{:<12}", spec.name);
230            lines.push(format!(
231                "    {} {}",
232                color(COLOR_COMMAND, &command),
233                spec.about
234            ));
235        }
236    }
237    lines
238}
239
240fn color(code: &str, text: &str) -> String {
241    format!("{code}{text}{COLOR_RESET}")
242}
243
244#[cfg(test)]
245mod tests {
246    use super::*;
247
248    // Ensure top-level usage keeps the intended color groups.
249    #[test]
250    fn usage_contains_help_colors() {
251        let text = usage();
252
253        assert!(text.contains(COLOR_HEADING));
254        assert!(text.contains(COLOR_GROUP));
255        assert!(text.contains(COLOR_COMMAND));
256    }
257}