lla_plugin_utils/
actions.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
use std::collections::HashMap;

pub struct Action {
    pub handler: Box<dyn Fn(&[String]) -> Result<(), String> + Send + Sync>,
    pub help: ActionHelp,
}

pub struct ActionHelp {
    pub usage: String,
    pub description: String,
    pub examples: Vec<String>,
}

pub struct ActionRegistry {
    actions: HashMap<String, Action>,
}

impl ActionRegistry {
    pub fn new() -> Self {
        Self {
            actions: HashMap::new(),
        }
    }

    pub fn register<F>(&mut self, name: &str, help: ActionHelp, handler: F)
    where
        F: Fn(&[String]) -> Result<(), String> + Send + Sync + 'static,
    {
        self.actions.insert(
            name.to_string(),
            Action {
                handler: Box::new(handler),
                help,
            },
        );
    }

    pub fn handle(&self, action: &str, args: &[String]) -> Result<(), String> {
        match self.actions.get(action) {
            Some(action) => (action.handler)(args),
            None => Err(format!("Unknown action: {}", action)),
        }
    }

    pub fn get_help(&self) -> Vec<(&str, &ActionHelp)> {
        self.actions
            .iter()
            .map(|(name, action)| (name.as_str(), &action.help))
            .collect()
    }
}

impl Default for ActionRegistry {
    fn default() -> Self {
        Self::new()
    }
}

#[macro_export]
macro_rules! define_action {
    ($registry:expr, $name:expr, $usage:expr, $description:expr, $examples:expr, $handler:expr) => {
        $registry.register(
            $name,
            $crate::actions::ActionHelp {
                usage: $usage.to_string(),
                description: $description.to_string(),
                examples: $examples.iter().map(|s| s.to_string()).collect(),
            },
            $handler,
        );
    };
}