modcli/
shell_commands.rs

1use std::sync::{Mutex, OnceLock};
2
3/// Shell command struct with metadata
4#[derive(Clone)]
5pub struct ShellCommand {
6    pub name: &'static str,
7    pub aliases: &'static [&'static str],
8    pub help: &'static str,
9    pub handler: fn(input: &str) -> bool,
10}
11
12static HOOKS: OnceLock<Mutex<Vec<ShellCommand>>> = OnceLock::new();
13
14/// Register a new shell-only command from a parent application
15pub fn register(cmd: ShellCommand) {
16    HOOKS.get_or_init(|| Mutex::new(Vec::new()))
17        .lock().unwrap()
18        .push(cmd);
19}
20
21/// Dispatches shell input to registered handlers.
22/// Returns true if any handler accepted the input.
23pub fn dispatch(input: &str) -> bool {
24    let input = input.trim();
25    if let Some(cmds) = HOOKS.get() {
26        for cmd in cmds.lock().unwrap().iter() {
27            if cmd.name == input || cmd.aliases.contains(&input) {
28                return (cmd.handler)(input);
29            }
30        }
31    }
32    false
33}
34
35/// Returns all registered shell commands (for dynamic help)
36pub fn list() -> Vec<ShellCommand> {
37    if let Some(cmds) = HOOKS.get() {
38        cmds.lock().unwrap().clone()
39    } else {
40        vec![]
41    }
42}