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 fleet templates",
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 deployment truth before mutation",
80        scope: CommandScope::Deployment,
81    },
82    CommandSpec {
83        name: "config",
84        about: "Inspect selected fleet config",
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: "endpoints",
104        about: "List canister Candid endpoints",
105        scope: CommandScope::Deployment,
106    },
107    CommandSpec {
108        name: "medic",
109        about: "Diagnose local Canic deployment target setup",
110        scope: CommandScope::Deployment,
111    },
112    CommandSpec {
113        name: "metrics",
114        about: "Query Canic runtime telemetry",
115        scope: CommandScope::Deployment,
116    },
117    CommandSpec {
118        name: "snapshot",
119        about: "Capture and download canister snapshots",
120        scope: CommandScope::BackupRestore,
121    },
122    CommandSpec {
123        name: "backup",
124        about: "Verify backup directories and journal status",
125        scope: CommandScope::BackupRestore,
126    },
127    CommandSpec {
128        name: "manifest",
129        about: "Validate backup manifests",
130        scope: CommandScope::BackupRestore,
131    },
132    CommandSpec {
133        name: "restore",
134        about: "Plan or run snapshot restores",
135        scope: CommandScope::BackupRestore,
136    },
137];
138
139pub fn is_help_arg(arg: &OsString) -> bool {
140    arg.to_str()
141        .is_some_and(|arg| matches!(arg, "help" | "--help" | "-h"))
142}
143
144pub fn is_version_arg(arg: &OsString) -> bool {
145    arg.to_str()
146        .is_some_and(|arg| matches!(arg, "version" | "--version" | "-V"))
147}
148
149pub fn first_arg_is_help(args: &[OsString]) -> bool {
150    args.first().is_some_and(is_help_arg)
151}
152
153pub fn first_arg_is_version(args: &[OsString]) -> bool {
154    args.first().is_some_and(is_version_arg)
155}
156
157pub fn print_help_or_version(
158    args: &[OsString],
159    usage: impl FnOnce() -> String,
160    version_text: &str,
161) -> bool {
162    if first_arg_is_help(args) {
163        println!("{}", usage());
164        return true;
165    }
166    if first_arg_is_version(args) {
167        println!("{version_text}");
168        return true;
169    }
170    false
171}
172
173#[must_use]
174pub fn top_level_command() -> Command {
175    let command = Command::new("canic")
176        .version(env!("CARGO_PKG_VERSION"))
177        .about("Operator CLI for Canic install, backup, and restore workflows")
178        .disable_version_flag(true)
179        .arg(
180            Arg::new("version")
181                .short('V')
182                .long("version")
183                .action(ArgAction::SetTrue)
184                .help("Print version"),
185        )
186        .arg(icp_arg().global(true))
187        .arg(network_arg().global(true))
188        .subcommand_help_heading("Commands")
189        .help_template(TOP_LEVEL_HELP_TEMPLATE)
190        .before_help(grouped_command_section(COMMAND_SPECS).join("\n"))
191        .after_help("Run `canic <command> help` for command-specific help.");
192
193    COMMAND_SPECS.iter().fold(command, |command, spec| {
194        command.subcommand(Command::new(spec.name).about(spec.about))
195    })
196}
197
198pub fn usage() -> String {
199    let mut lines = vec![
200        color(
201            COLOR_HEADING,
202            &format!("Canic Operator CLI v{}", env!("CARGO_PKG_VERSION")),
203        ),
204        String::new(),
205        "Usage: canic [OPTIONS] <COMMAND>".to_string(),
206        String::new(),
207        color(COLOR_HEADING, "Commands:"),
208    ];
209    lines.extend(grouped_command_section(COMMAND_SPECS));
210    lines.extend([
211        String::new(),
212        color(COLOR_HEADING, "Options:"),
213        "      --icp <path>      Path to the icp executable for ICP-backed commands".to_string(),
214        "      --network <name>  ICP CLI network for networked commands".to_string(),
215        "  -V, --version  Print version".to_string(),
216        "  -h, --help     Print help".to_string(),
217        String::new(),
218        format!(
219            "{}Tip:{} Run {} for command-specific help.",
220            COLOR_TIP,
221            COLOR_RESET,
222            color(COLOR_COMMAND, "`canic <command> help`")
223        ),
224    ]);
225    lines.join("\n")
226}
227
228fn grouped_command_section(specs: &[CommandSpec]) -> Vec<String> {
229    let mut lines = Vec::new();
230    let scopes = [
231        CommandScope::Project,
232        CommandScope::Deployment,
233        CommandScope::IcpWallet,
234        CommandScope::BackupRestore,
235    ];
236    for scope in scopes {
237        let scope_specs = specs
238            .iter()
239            .filter(|spec| spec.scope == scope)
240            .collect::<Vec<_>>();
241        if scope_specs.is_empty() {
242            continue;
243        }
244        if !lines.is_empty() {
245            lines.push(String::new());
246        }
247        lines.push(format!("  {}", color(COLOR_GROUP, scope.heading())));
248        for spec in scope_specs {
249            let command = format!("{:<12}", spec.name);
250            lines.push(format!(
251                "    {} {}",
252                color(COLOR_COMMAND, &command),
253                spec.about
254            ));
255        }
256    }
257    lines
258}
259
260fn color(code: &str, text: &str) -> String {
261    format!("{code}{text}{COLOR_RESET}")
262}
263
264#[cfg(test)]
265mod tests {
266    use super::*;
267
268    // Ensure top-level usage keeps the intended color groups.
269    #[test]
270    fn usage_contains_help_colors() {
271        let text = usage();
272
273        assert!(text.contains(COLOR_HEADING));
274        assert!(text.contains(COLOR_GROUP));
275        assert!(text.contains(COLOR_COMMAND));
276    }
277}