CommandRegistry

Struct CommandRegistry 

Source
pub struct CommandRegistry { /* private fields */ }
Expand description

Central registry for commands and their handlers

The registry stores all registered commands along with their definitions and handlers. It provides efficient lookup by both command name and alias.

§Thread Safety

The registry is designed to be constructed once during application startup and then shared immutably across the application. For multi-threaded access, wrap it in Arc<CommandRegistry>.

§Example

use dynamic_cli::registry::CommandRegistry;
use dynamic_cli::config::schema::CommandDefinition;
use dynamic_cli::executor::CommandHandler;
use std::collections::HashMap;

let mut registry = CommandRegistry::new();

// Register commands during initialization
registry.register(definition, Box::new(TestCommand))?;

// Use throughout the application
if let Some(handler) = registry.get_handler("test") {
    // Execute the command
}

Implementations§

Source§

impl CommandRegistry

Source

pub fn new() -> Self

Create a new empty registry

§Example
use dynamic_cli::registry::CommandRegistry;

let registry = CommandRegistry::new();
assert_eq!(registry.list_commands().len(), 0);
Source

pub fn register( &mut self, definition: CommandDefinition, handler: Box<dyn CommandHandler>, ) -> Result<()>

Register a command with its handler

This method registers a command definition along with its handler. It also registers all aliases for the command.

§Arguments
  • definition - The command definition from the configuration
  • handler - The handler implementation for this command
§Returns
  • Ok(()) if registration succeeds
  • Err(RegistryError) if:
    • A command with the same name is already registered
    • An alias conflicts with an existing command or alias
§Errors
§Example
use dynamic_cli::registry::CommandRegistry;
use dynamic_cli::config::schema::CommandDefinition;
use dynamic_cli::executor::CommandHandler;
use std::collections::HashMap;

let mut registry = CommandRegistry::new();

let definition = CommandDefinition {
    name: "simulate".to_string(),
    aliases: vec!["sim".to_string(), "run".to_string()],
    description: "Run simulation".to_string(),
    required: false,
    arguments: vec![],
    options: vec![],
    implementation: "sim_handler".to_string(),
};

struct SimCommand;
impl CommandHandler for SimCommand {
    fn execute(
        &self,
        _: &mut dyn dynamic_cli::context::ExecutionContext,
        _: &HashMap<String, String>,
    ) -> dynamic_cli::Result<()> {
        Ok(())
    }
}

// Register the command
registry.register(definition, Box::new(SimCommand))?;

// Can now access by name or alias
assert!(registry.get_handler("simulate").is_some());
assert_eq!(registry.resolve_name("sim"), Some("simulate"));
Source

pub fn resolve_name(&self, name: &str) -> Option<&str>

Resolve a name (command or alias) to the canonical command name

This method checks if the given name is either:

  • A registered command name (returns the name itself)
  • An alias (returns the canonical command name)
§Arguments
  • name - The name or alias to resolve
§Returns
  • Some(&str) - The canonical command name
  • None - If the name is not registered
§Example
use dynamic_cli::registry::CommandRegistry;

let mut registry = CommandRegistry::new();

// Resolve command name
assert_eq!(registry.resolve_name("hello"), Some("hello"));

// Resolve alias
assert_eq!(registry.resolve_name("hi"), Some("hello"));

// Unknown name
assert_eq!(registry.resolve_name("unknown"), None);
Source

pub fn get_definition(&self, name: &str) -> Option<&CommandDefinition>

Get the definition of a command by name or alias

§Arguments
  • name - The command name or alias
§Returns
  • Some(&CommandDefinition) if the command exists
  • None if the command is not registered
§Example
// Get by name
if let Some(def) = registry.get_definition("test") {
    assert_eq!(def.name, "test");
    assert_eq!(def.description, "Test command");
}

// Get by alias
if let Some(def) = registry.get_definition("t") {
    assert_eq!(def.name, "test");
}
Source

pub fn get_handler(&self, name: &str) -> Option<&Box<dyn CommandHandler>>

Get the handler of a command by name or alias

This is the primary method used during command execution to retrieve the handler that will execute the command.

§Arguments
  • name - The command name or alias
§Returns
  • Some(&Box<dyn CommandHandler>) if the command exists
  • None if the command is not registered
§Example
// Get handler by name
if let Some(handler) = registry.get_handler("exec") {
    // Use handler for execution
}

// Get handler by alias
if let Some(handler) = registry.get_handler("x") {
    // Same handler
}
Source

pub fn list_commands(&self) -> Vec<&CommandDefinition>

List all registered command definitions

Returns a vector of references to all command definitions in the registry. The order is not guaranteed.

§Returns

Vector of command definition references

§Example
let commands = registry.list_commands();
assert_eq!(commands.len(), 2);

// Use for help text, command completion, etc.
for cmd in commands {
    println!("{}: {}", cmd.name, cmd.description);
}
Source

pub fn len(&self) -> usize

Get the number of registered commands

§Example
use dynamic_cli::registry::CommandRegistry;

let registry = CommandRegistry::new();
assert_eq!(registry.len(), 0);
Source

pub fn is_empty(&self) -> bool

Check if the registry is empty

§Example
use dynamic_cli::registry::CommandRegistry;

let registry = CommandRegistry::new();
assert!(registry.is_empty());
Source

pub fn contains(&self, name: &str) -> bool

Check if a command is registered (by name or alias)

§Example
assert!(registry.contains("test"));
assert!(registry.contains("t"));
assert!(!registry.contains("unknown"));

Trait Implementations§

Source§

impl Default for CommandRegistry

Source§

fn default() -> Self

Returns the “default value” for a type. Read more

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.