Skip to main content

hexz_cli/ui/
help.rs

1use clap::Command;
2
3const BOLD: &str = "\x1b[1m";
4const RESET: &str = "\x1b[0m";
5const YELLOW: &str = "\x1b[33m";
6const GREEN: &str = "\x1b[32m";
7const CYAN: &str = "\x1b[36m";
8
9pub struct Printer {
10    cmd: Command,
11}
12
13impl Printer {
14    pub fn new(cmd: Command) -> Self {
15        Self { cmd }
16    }
17
18    /// Prints the top-level help menu (categories and list of commands)
19    pub fn print_help(&mut self) {
20        let bin_name = self.cmd.get_bin_name().unwrap_or("hexz").to_string();
21
22        println!(
23            "{}Usage:{} {}{}{} {}[OPTIONS]{} {}COMMAND{}",
24            BOLD, RESET, GREEN, bin_name, RESET, CYAN, RESET, YELLOW, RESET
25        );
26        println!();
27        if let Some(about) = self.cmd.get_about() {
28            println!("{}", about);
29        }
30        println!();
31
32        let mut archive_cmds = Vec::new();
33        let mut vm_cmds = Vec::new();
34        let mut sys_cmds = Vec::new();
35        let mut other_cmds = Vec::new();
36
37        let subcommands: Vec<Command> = self.cmd.get_subcommands().cloned().collect();
38
39        for sub in subcommands {
40            let name = sub.get_name().to_string();
41            if name == "help" {
42                continue;
43            }
44
45            let about = sub.get_about().map(|a| a.to_string()).unwrap_or_default();
46            let item = (name.clone(), about);
47
48            match name.as_str() {
49                "pack" | "inspect" | "diff" | "build" | "analyze" | "convert" => {
50                    archive_cmds.push(item)
51                }
52                "boot" | "install" | "snap" | "commit" | "mount" | "unmount" => vm_cmds.push(item),
53                "doctor" | "bench" | "serve" | "keygen" | "sign" | "verify" => sys_cmds.push(item),
54                _ => other_cmds.push(item),
55            }
56        }
57
58        self.print_section("Archive Operations", archive_cmds);
59        self.print_section("Virtual Machine Operations", vm_cmds);
60        self.print_section("System & Diagnostics", sys_cmds);
61
62        if !other_cmds.is_empty() {
63            self.print_section("Other Commands", other_cmds);
64        }
65
66        println!("{}Options:{}", BOLD, RESET);
67        println!("  {}{:<15}{} Print help", GREEN, "-h, --help", RESET);
68        println!("  {}{:<15}{} Print version", GREEN, "-V, --version", RESET);
69        println!();
70        println!(
71            "Run '{}{}{} COMMAND --help{}' for more information on a command.",
72            BOLD, YELLOW, bin_name, RESET
73        );
74    }
75
76    fn print_section(&self, header: &str, cmds: Vec<(String, String)>) {
77        if cmds.is_empty() {
78            return;
79        }
80
81        println!("{}{}{}:{}", BOLD, YELLOW, header, RESET);
82
83        for (name, about) in cmds {
84            println!("  {}{:<12}{} {}", GREEN, name, RESET, about);
85        }
86        println!();
87    }
88
89    /// Prints detailed help for a specific subcommand
90    pub fn print_subcommand_help(&mut self, sub_name: &str) {
91        let sub = match self.cmd.find_subcommand(sub_name) {
92            Some(s) => s,
93            None => return,
94        };
95
96        let bin_name = self.cmd.get_bin_name().unwrap_or("hexz");
97
98        // 1. Usage
99        println!(
100            "{}Usage:{} {} {} {} {} {}[OPTIONS] [ARGS]{}",
101            BOLD, RESET, GREEN, bin_name, sub_name, RESET, CYAN, RESET
102        );
103        println!();
104
105        // 2. Detailed Description (long_about)
106        if let Some(about) = sub.get_long_about().or_else(|| sub.get_about()) {
107            println!("{}", about);
108        }
109        println!();
110
111        // Collect all arguments
112        let args: Vec<_> = sub.get_arguments().collect();
113
114        // Partition into Positionals (Arguments) and Options (Flags)
115        // Robust check: Positionals are arguments that have NO short flag AND NO long flag.
116        let (mut positionals, mut flags): (Vec<_>, Vec<_>) = args
117            .into_iter()
118            .filter(|a| a.get_id() != "help" && a.get_id() != "version")
119            .partition(|a| a.get_short().is_none() && a.get_long().is_none());
120
121        // Sort positionals by index (so SOURCE comes before OUTPUT)
122        // If index is missing, we push it to the end.
123        positionals.sort_by_key(|a| a.get_index().unwrap_or(usize::MAX));
124
125        // Sort flags alphabetically
126        flags.sort_by(|a, b| a.get_id().cmp(b.get_id()));
127
128        // 3. Arguments Section (Positional)
129        if !positionals.is_empty() {
130            println!("{}Arguments:{}", BOLD, RESET);
131            for arg in positionals {
132                let name = arg.get_id().as_str().to_uppercase();
133                let help = arg.get_help().map(|h| h.to_string()).unwrap_or_default();
134
135                // Check if required
136                let required_note = if arg.is_required_set() {
137                    format!("{} (required){}", YELLOW, RESET)
138                } else {
139                    String::new()
140                };
141
142                println!("  {}{:<28}{} {}{}", GREEN, name, RESET, help, required_note);
143            }
144            println!();
145        }
146
147        // 4. Options Section (Flags)
148        println!("{}Options:{}", BOLD, RESET);
149
150        for arg in flags {
151            let short = arg
152                .get_short()
153                .map(|s| format!("-{},", s))
154                .unwrap_or_default();
155            let long = arg
156                .get_long()
157                .map(|l| format!("--{}", l))
158                .unwrap_or_default();
159
160            // Handle values like <OUTPUT>
161            let value = if arg.get_action().takes_values() {
162                let val_name = arg
163                    .get_value_names()
164                    .and_then(|names| names.first())
165                    .map(|s| s.to_string())
166                    .unwrap_or_else(|| "VAL".to_string());
167                format!(" <{}>", val_name.to_uppercase())
168            } else {
169                String::new()
170            };
171
172            let flag_str = format!("{} {}{}", short, long, value);
173            let help_text = arg.get_help().map(|h| h.to_string()).unwrap_or_default();
174
175            let required_note = if arg.is_required_set() {
176                format!("{} (required){}", YELLOW, RESET)
177            } else {
178                String::new()
179            };
180
181            println!(
182                "  {}{:<28}{} {}{}",
183                GREEN,
184                flag_str.trim(),
185                RESET,
186                help_text,
187                required_note
188            );
189        }
190
191        // Always show help flag
192        println!("  {}{:<28}{} Print help", GREEN, "-h, --help", RESET);
193        println!();
194
195        // 5. Example Usage
196        println!("{}Example:{}", BOLD, RESET);
197        if let Some(example) = sub.get_after_help() {
198            println!("  {}", example);
199        } else {
200            println!("  {} {} [flags] [args]", bin_name, sub_name);
201        }
202        println!();
203    }
204}