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