lp/
lib.rs

1use std::fs;
2use toml;
3use serde::Deserialize;
4
5pub trait PluginManager {
6    fn register(&self, f: impl Fn(Plugin));
7    fn unregister(&self, f: impl Fn(Plugin));
8    fn run(&self, f: impl Fn(Plugin));
9}
10
11// Toml Manifest
12#[derive(Debug, Deserialize)]
13pub struct Toml {
14    pub plugin: Plugin,
15}
16 
17// Ron Manifest
18#[derive(Debug, Deserialize)]
19pub struct Ron {
20    pub plugin: Plugin,
21}
22
23// Json Manifest
24#[derive(Debug, Deserialize)]
25pub struct Json {
26    pub plugin: Plugin,
27}
28
29#[derive(Debug, Deserialize, Clone)]
30pub struct Plugin {
31    pub authors: Option<Vec<String>>,
32    pub name: String,
33    pub version: String,
34    pub description: Option<String>,
35    pub license: Option<String>,
36    pub path: Option<String>,
37}
38
39// Plugin Management
40impl PluginManager for Plugin {
41    /// Registers the plugin, adding it to the appropriate directory
42    fn register(&self, f: impl Fn(Plugin)) {
43        f(self.clone());
44    }
45
46    /// Unregisters the plugin, removing it from the directory
47    fn unregister(&self, f: impl Fn(Plugin)) {
48        f(self.clone());
49    }
50
51    /// Executes the plugin
52    fn run(&self, f: impl Fn(Plugin)) {
53        f(self.clone());
54    }
55}
56
57impl Toml {
58    pub fn parse(path: &str) -> Result<Self, toml::de::Error> {
59        let toml = fs::read_to_string(path).unwrap();
60        toml::from_str(&toml)
61    }
62}
63
64impl Ron {
65    pub fn parse(path: &str) -> Result<Self, ron::error::SpannedError> {
66        let ron = fs::read_to_string(path).unwrap();
67        ron::from_str(&ron)
68    }
69}
70
71impl Json {
72    pub fn parse(path: &str) -> Result<Self, serde_json::Error> {
73        let json = fs::read_to_string(path).unwrap();
74        serde_json::from_str(&json)
75    }
76}
77
78mod tests {
79    #[test]
80    fn test_plugin() {
81        use super::*;
82        use std::path::Path;
83
84        let toml = Toml::parse("test_asset/plugin.toml").unwrap();
85        let ron = Ron::parse("test_asset/plugin.ron").unwrap();
86        let json = Json::parse("test_asset/plugin.json").unwrap();
87
88        assert_eq!(ron.plugin.name, "test_asset");
89        assert_eq!(json.plugin.name, "test_asset");
90        toml.plugin.register(|plugin| {
91            if let Some(path) = &plugin.path {
92               if !Path::new(path).exists() {
93                    println!("Plugin directory does not exist, creating @: {:?}", path);
94                    // set up plugin dir
95                    // move plugin files to dir
96                    assert_eq!(plugin.path, Some("/path/to/test_asset".to_string()));
97                } else {
98                    println!("Plugin directory already exists: {:?}", path);
99                }
100            }
101        });
102    }
103}