use larust_core::AppError;
use std::collections::HashMap;
use std::future::Future;
use std::pin::Pin;
pub trait Command: Send + Sync + 'static {
const NAME: &'static str;
const DESCRIPTION: &'static str = "";
fn handle(args: &[String]) -> impl Future<Output = Result<(), AppError>> + Send;
}
type BoxedHandler = Box<
dyn Fn(Vec<String>) -> Pin<Box<dyn Future<Output = Result<(), AppError>> + Send>> + Send + Sync,
>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct CommandInfo {
pub name: &'static str,
pub description: &'static str,
}
#[must_use]
#[derive(Default)]
pub struct CommandRegistry {
commands: HashMap<&'static str, (CommandInfo, BoxedHandler)>,
}
impl CommandRegistry {
pub fn new() -> Self {
Self::default()
}
pub fn register<C: Command>(mut self) -> Self {
let handler: BoxedHandler =
Box::new(|args: Vec<String>| Box::pin(async move { C::handle(&args).await }));
let info = CommandInfo {
name: C::NAME,
description: C::DESCRIPTION,
};
let existing = self.commands.insert(C::NAME, (info, handler));
assert!(
existing.is_none(),
"duplicate CommandRegistry::register for NAME {:?} - each command name must be \
registered exactly once",
C::NAME,
);
self
}
pub async fn dispatch(&self, name: &str, args: &[String]) -> Result<bool, AppError> {
match self.commands.get(name) {
Some((_, handler)) => {
handler(args.to_vec()).await?;
Ok(true)
}
None => Ok(false),
}
}
pub fn list(&self) -> Vec<CommandInfo> {
let mut commands: Vec<CommandInfo> =
self.commands.values().map(|(info, _)| *info).collect();
commands.sort_by_key(|info| info.name);
commands
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
struct Ping;
impl Command for Ping {
const NAME: &'static str = "ping";
const DESCRIPTION: &'static str = "Replies pong";
async fn handle(_args: &[String]) -> Result<(), AppError> {
Ok(())
}
}
static CALLS: AtomicUsize = AtomicUsize::new(0);
static LAST_ARGS: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
struct Echo;
impl Command for Echo {
const NAME: &'static str = "echo";
async fn handle(args: &[String]) -> Result<(), AppError> {
CALLS.fetch_add(1, Ordering::SeqCst);
*LAST_ARGS.lock().unwrap() = args.to_vec();
Ok(())
}
}
struct Failing;
impl Command for Failing {
const NAME: &'static str = "failing";
async fn handle(_args: &[String]) -> Result<(), AppError> {
Err(AppError::Internal(Box::new(std::io::Error::other(
"deliberately failing",
))))
}
}
#[tokio::test]
async fn dispatch_runs_the_matching_registered_command() {
let registry = CommandRegistry::new().register::<Ping>();
let ran = registry.dispatch("ping", &[]).await.unwrap();
assert!(ran);
}
#[tokio::test]
async fn dispatch_forwards_args_to_the_command() {
CALLS.store(0, Ordering::SeqCst);
let registry = CommandRegistry::new().register::<Echo>();
let args = vec!["--dry-run".to_string(), "42".to_string()];
registry.dispatch("echo", &args).await.unwrap();
assert_eq!(CALLS.load(Ordering::SeqCst), 1);
assert_eq!(*LAST_ARGS.lock().unwrap(), args);
}
#[tokio::test]
async fn dispatch_returns_false_for_an_unregistered_name() {
let registry = CommandRegistry::new().register::<Ping>();
let ran = registry.dispatch("not:registered", &[]).await.unwrap();
assert!(!ran);
}
#[tokio::test]
async fn dispatch_propagates_the_commands_own_error() {
let registry = CommandRegistry::new().register::<Failing>();
let result = registry.dispatch("failing", &[]).await;
assert!(result.is_err());
}
#[test]
#[should_panic(expected = "duplicate CommandRegistry::register for NAME \"ping\"")]
fn register_panics_on_a_duplicate_name() {
struct AlsoPing;
impl Command for AlsoPing {
const NAME: &'static str = "ping";
async fn handle(_args: &[String]) -> Result<(), AppError> {
Ok(())
}
}
let _ = CommandRegistry::new()
.register::<Ping>()
.register::<AlsoPing>();
}
#[test]
fn list_is_sorted_by_name_regardless_of_registration_order() {
struct Zebra;
impl Command for Zebra {
const NAME: &'static str = "zebra";
async fn handle(_args: &[String]) -> Result<(), AppError> {
Ok(())
}
}
struct Apple;
impl Command for Apple {
const NAME: &'static str = "apple";
async fn handle(_args: &[String]) -> Result<(), AppError> {
Ok(())
}
}
let registry = CommandRegistry::new()
.register::<Zebra>()
.register::<Apple>();
let names: Vec<&str> = registry.list().iter().map(|info| info.name).collect();
assert_eq!(names, vec!["apple", "zebra"]);
}
#[test]
fn list_includes_each_commands_description() {
let registry = CommandRegistry::new().register::<Ping>();
let list = registry.list();
assert_eq!(list.len(), 1);
assert_eq!(list[0].name, "ping");
assert_eq!(list[0].description, "Replies pong");
}
}