lla_plugin_utils/
actions.rs1use std::collections::HashMap;
2
3pub struct Action {
4 pub handler: Box<dyn Fn(&[String]) -> Result<(), String> + Send + Sync>,
5 pub help: ActionHelp,
6}
7
8pub struct ActionHelp {
9 pub usage: String,
10 pub description: String,
11 pub examples: Vec<String>,
12}
13
14pub struct ActionRegistry {
15 actions: HashMap<String, Action>,
16}
17
18impl ActionRegistry {
19 pub fn new() -> Self {
20 Self {
21 actions: HashMap::new(),
22 }
23 }
24
25 pub fn register<F>(&mut self, name: &str, help: ActionHelp, handler: F)
26 where
27 F: Fn(&[String]) -> Result<(), String> + Send + Sync + 'static,
28 {
29 self.actions.insert(
30 name.to_string(),
31 Action {
32 handler: Box::new(handler),
33 help,
34 },
35 );
36 }
37
38 pub fn handle(&self, action: &str, args: &[String]) -> Result<(), String> {
39 match self.actions.get(action) {
40 Some(action) => (action.handler)(args),
41 None => Err(format!("Unknown action: {}", action)),
42 }
43 }
44
45 pub fn get_help(&self) -> Vec<(&str, &ActionHelp)> {
46 self.actions
47 .iter()
48 .map(|(name, action)| (name.as_str(), &action.help))
49 .collect()
50 }
51}
52
53impl Default for ActionRegistry {
54 fn default() -> Self {
55 Self::new()
56 }
57}
58
59#[macro_export]
60macro_rules! define_action {
61 ($registry:expr, $name:expr, $usage:expr, $description:expr, $examples:expr, $handler:expr) => {
62 $registry.register(
63 $name,
64 $crate::actions::ActionHelp {
65 usage: $usage.to_string(),
66 description: $description.to_string(),
67 examples: $examples.iter().map(|s| s.to_string()).collect(),
68 },
69 $handler,
70 );
71 };
72}