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)]
17pub enum 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 struct CommandSpec {
39    pub name: &'static str,
40    pub about: &'static str,
41    scope: CommandScope,
42}
43
44pub 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: "config",
67        about: "Inspect selected fleet config",
68        scope: CommandScope::FleetContext,
69    },
70    CommandSpec {
71        name: "list",
72        about: "List deployed fleet canisters",
73        scope: CommandScope::FleetContext,
74    },
75    CommandSpec {
76        name: "endpoints",
77        about: "List canister Candid endpoints",
78        scope: CommandScope::FleetContext,
79    },
80    CommandSpec {
81        name: "medic",
82        about: "Diagnose local Canic fleet setup",
83        scope: CommandScope::FleetContext,
84    },
85    CommandSpec {
86        name: "cycles",
87        about: "Summarize fleet cycle history",
88        scope: CommandScope::FleetContext,
89    },
90    CommandSpec {
91        name: "metrics",
92        about: "Query Canic runtime telemetry",
93        scope: CommandScope::FleetContext,
94    },
95    CommandSpec {
96        name: "snapshot",
97        about: "Capture and download canister snapshots",
98        scope: CommandScope::BackupRestore,
99    },
100    CommandSpec {
101        name: "backup",
102        about: "Verify backup directories and journal status",
103        scope: CommandScope::BackupRestore,
104    },
105    CommandSpec {
106        name: "manifest",
107        about: "Validate fleet backup manifests",
108        scope: CommandScope::BackupRestore,
109    },
110    CommandSpec {
111        name: "restore",
112        about: "Plan or run snapshot restores",
113        scope: CommandScope::BackupRestore,
114    },
115];
116
117pub fn is_help_arg(arg: &OsString) -> bool {
118    arg.to_str()
119        .is_some_and(|arg| matches!(arg, "help" | "--help" | "-h"))
120}
121
122pub fn is_version_arg(arg: &OsString) -> bool {
123    arg.to_str()
124        .is_some_and(|arg| matches!(arg, "version" | "--version" | "-V"))
125}
126
127pub fn first_arg_is_help(args: &[OsString]) -> bool {
128    args.first().is_some_and(is_help_arg)
129}
130
131pub fn first_arg_is_version(args: &[OsString]) -> bool {
132    args.first().is_some_and(is_version_arg)
133}
134
135pub fn print_help_or_version(
136    args: &[OsString],
137    usage: impl FnOnce() -> String,
138    version_text: &str,
139) -> bool {
140    if first_arg_is_help(args) {
141        println!("{}", usage());
142        return true;
143    }
144    if first_arg_is_version(args) {
145        println!("{version_text}");
146        return true;
147    }
148    false
149}
150
151#[must_use]
152pub fn top_level_command() -> Command {
153    let command = Command::new("canic")
154        .version(env!("CARGO_PKG_VERSION"))
155        .about("Operator CLI for Canic install, backup, and restore workflows")
156        .disable_version_flag(true)
157        .arg(
158            Arg::new("version")
159                .short('V')
160                .long("version")
161                .action(ArgAction::SetTrue)
162                .help("Print version"),
163        )
164        .arg(icp_arg().global(true))
165        .arg(network_arg().global(true))
166        .subcommand_help_heading("Commands")
167        .help_template(TOP_LEVEL_HELP_TEMPLATE)
168        .before_help(grouped_command_section(COMMAND_SPECS).join("\n"))
169        .after_help("Run `canic <command> help` for command-specific help.");
170
171    COMMAND_SPECS.iter().fold(command, |command, spec| {
172        command.subcommand(Command::new(spec.name).about(spec.about))
173    })
174}
175
176pub fn usage() -> String {
177    let mut lines = vec![
178        color(
179            COLOR_HEADING,
180            &format!("Canic Operator CLI v{}", env!("CARGO_PKG_VERSION")),
181        ),
182        String::new(),
183        "Usage: canic [OPTIONS] <COMMAND>".to_string(),
184        String::new(),
185        color(COLOR_HEADING, "Commands:"),
186    ];
187    lines.extend(grouped_command_section(COMMAND_SPECS));
188    lines.extend([
189        String::new(),
190        color(COLOR_HEADING, "Options:"),
191        "      --icp <path>      Path to the icp executable for ICP-backed commands".to_string(),
192        "      --network <name>  ICP CLI network for networked commands".to_string(),
193        "  -V, --version  Print version".to_string(),
194        "  -h, --help     Print help".to_string(),
195        String::new(),
196        format!(
197            "{}Tip:{} Run {} for command-specific help.",
198            COLOR_TIP,
199            COLOR_RESET,
200            color(COLOR_COMMAND, "`canic <command> help`")
201        ),
202    ]);
203    lines.join("\n")
204}
205
206fn grouped_command_section(specs: &[CommandSpec]) -> Vec<String> {
207    let mut lines = Vec::new();
208    let scopes = [
209        CommandScope::Global,
210        CommandScope::FleetContext,
211        CommandScope::BackupRestore,
212    ];
213    for scope in scopes {
214        let scope_specs = specs
215            .iter()
216            .filter(|spec| spec.scope == scope)
217            .collect::<Vec<_>>();
218        if scope_specs.is_empty() {
219            continue;
220        }
221        if !lines.is_empty() {
222            lines.push(String::new());
223        }
224        lines.push(format!("  {}", color(COLOR_GROUP, scope.heading())));
225        for spec in scope_specs {
226            let command = format!("{:<12}", spec.name);
227            lines.push(format!(
228                "    {} {}",
229                color(COLOR_COMMAND, &command),
230                spec.about
231            ));
232        }
233    }
234    lines
235}
236
237fn color(code: &str, text: &str) -> String {
238    format!("{code}{text}{COLOR_RESET}")
239}
240
241#[cfg(test)]
242pub fn strip_ansi(text: &str) -> String {
243    let mut plain = String::new();
244    let mut chars = text.chars().peekable();
245    while let Some(ch) = chars.next() {
246        if ch == '\x1b' && chars.peek() == Some(&'[') {
247            chars.next();
248            for ch in chars.by_ref() {
249                if ch == 'm' {
250                    break;
251                }
252            }
253            continue;
254        }
255        plain.push(ch);
256    }
257    plain
258}
259
260#[cfg(test)]
261pub const fn color_heading() -> &'static str {
262    COLOR_HEADING
263}
264
265#[cfg(test)]
266pub const fn color_group() -> &'static str {
267    COLOR_GROUP
268}
269
270#[cfg(test)]
271pub const fn color_command() -> &'static str {
272    COLOR_COMMAND
273}