Module traits

Module traits 

Source
Expand description

Command handler trait and related types

This module defines the core trait that all command implementations must implement. The trait is designed to be object-safe, meaning it can be used as a trait object (&dyn CommandHandler), which is critical for dynamic command registration.

§Design Principles

§Object Safety

The CommandHandler trait is intentionally kept simple and object-safe:

  • No generic methods (would prevent trait object usage)
  • No associated types with type parameters
  • All methods use concrete types or trait objects

This allows the registry to store handlers as Box<dyn CommandHandler>, enabling dynamic command registration at runtime.

§Simple Type Signatures

Arguments are passed as HashMap<String, String> rather than generic types. This design choice:

  • Maintains object safety
  • Provides flexibility in argument types
  • Delegates type parsing to the parser module

§Thread Safety

All handlers must be Send + Sync to support:

  • Shared access across threads
  • Potential async execution in the future
  • Safe usage in multi-threaded contexts

§Example

use std::collections::HashMap;
use dynamic_cli::executor::CommandHandler;
use dynamic_cli::context::ExecutionContext;
use dynamic_cli::Result;

// Define a simple command handler
struct HelloCommand;

impl CommandHandler for HelloCommand {
    fn execute(
        &self,
        _context: &mut dyn ExecutionContext,
        args: &HashMap<String, String>,
    ) -> Result<()> {
        let name = args.get("name").map(|s| s.as_str()).unwrap_or("World");
        println!("Hello, {}!", name);
        Ok(())
    }
}

Traits§

CommandHandler
Trait for command implementations