modcli/
loader.rs

1use std::collections::HashMap;
2use crate::command::Command;
3
4#[cfg(feature = "internal-commands")]
5use crate::commands::{PingCommand, EchoCommand, HelloCommand};
6
7/// Registry for available CLI commands
8pub struct CommandRegistry {
9    commands: HashMap<String, Box<dyn Command>>,
10}
11
12impl CommandRegistry {
13    /// Create a new command registry and register internal commands (if enabled)
14    pub fn new() -> Self {
15        let mut reg = Self {
16            commands: HashMap::new(),
17        };
18
19        reg.load_internal_commands();
20        reg
21    }
22
23    /// Register a new command
24    pub fn register(&mut self, cmd: Box<dyn Command>) {
25        self.commands.insert(cmd.name().to_string(), cmd);
26    }
27
28    /// Execute a command if it exists, passing args
29    pub fn execute(&self, cmd: &str, args: &[String]) {
30        if let Some(command) = self.commands.get(cmd) {
31            command.execute(args);
32        } else {
33            eprintln!("Unknown command: {}", cmd);
34        }
35    }
36
37    /// Load built-in internal commands if the feature is enabled
38    fn load_internal_commands(&mut self) {
39        #[cfg(feature = "internal-commands")]
40        {
41            self.register(Box::new(PingCommand));
42            self.register(Box::new(EchoCommand));
43            self.register(Box::new(HelloCommand));
44        }
45    }
46}