vanguard-plugin-sdk 0.1.4

SDK for developing Vanguard plugins
Documentation
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
use std::{fs, path::Path};
use thiserror::Error;

/// Plugin template generation errors
#[derive(Error, Debug)]
pub enum TemplateError {
    #[error("Invalid plugin name: {0}")]
    InvalidName(String),

    #[error("I/O error: {0}")]
    Io(#[from] std::io::Error),
}

/// Result type for template operations
pub type TemplateResult<T> = Result<T, TemplateError>;

/// Options for plugin generation
#[derive(Debug, Clone)]
pub struct PluginOptions {
    /// Plugin name (crate name)
    pub name: String,
    /// Plugin description
    pub description: String,
    /// Plugin author
    pub author: String,
    /// Plugin version
    pub version: String,
    /// Minimum required Vanguard version
    pub min_vanguard_version: Option<String>,
    /// Template to use (basic or commands)
    pub template: Option<String>,
}

/// Convert a string to PascalCase
///
/// - "my-plugin" -> "MyPlugin"
/// - "my_plugin" -> "MyPlugin"
/// - "my plugin" -> "MyPlugin"
fn to_pascal_case(s: &str) -> String {
    let mut result = String::new();
    let mut capitalize_next = true;

    for c in s.chars() {
        if c.is_alphanumeric() {
            if capitalize_next {
                result.push(c.to_ascii_uppercase());
                capitalize_next = false;
            } else {
                result.push(c);
            }
        } else {
            capitalize_next = true;
        }
    }

    result
}

/// Detect if we're running inside the Vanguard repo
fn is_inside_vanguard_repo() -> bool {
    // Try to find the Vanguard repo root by checking for specific directories and files
    let current_dir = std::env::current_dir().ok();
    if let Some(dir) = current_dir {
        // Look for markers of the Vanguard repo
        let mut path = dir.clone();
        loop {
            // Check if this directory contains crates/vanguard-plugin-sdk
            if path.join("crates").join("vanguard-plugin-sdk").exists() {
                return true;
            }

            // Try parent directory
            if let Some(parent) = path.parent() {
                path = parent.to_path_buf();
            } else {
                break;
            }
        }
    }
    false
}

/// Generate the Cargo.toml template
fn generate_cargo_toml(
    plugin_name: &str,
    description: &str,
    _author: &str,
    version: &str,
) -> String {
    let inside_vanguard_repo = is_inside_vanguard_repo();

    // Determine the SDK dependency line based on whether we're inside the repo
    let sdk_dependency = if inside_vanguard_repo {
        // Use local path dependency if inside the Vanguard repo
        "vanguard-plugin-sdk = { path = \"../../crates/vanguard-plugin-sdk\" }".to_string()
    } else {
        // Use published version from crates.io
        "vanguard-plugin-sdk = \"0.1.4\"".to_string()
    };

    format!(
        r#"[package]
name = "{plugin_name}"
version = "{version}"
edition = "2021"
description = "{description}"
license = "MIT"

[lib]
crate-type = ["cdylib"]

[dependencies]
{sdk_dependency}
async-trait = "0.1"
serde = {{ version = "1.0", features = ["derive"] }}
serde_json = "1.0"
tokio = {{ version = "1.0", features = ["full"] }}

[dev-dependencies]
tokio-test = "0.4"

# Make this plugin independent from the parent workspace
[workspace]
"#
    )
}

/// Generate a basic plugin README
fn generate_readme(plugin_name: &str, description: &str, author: &str) -> String {
    let inside_vanguard_repo = is_inside_vanguard_repo();

    let installation_note = if inside_vanguard_repo {
        "This plugin is configured to work within the Vanguard repository. If you want to use it outside the repository, you'll need to update the dependency in Cargo.toml."
    } else {
        "This plugin uses the vanguard-plugin-sdk from crates.io and can be built anywhere without requiring the Vanguard source code."
    };

    format!(
        r#"# {plugin_name}

{description}

## Author

{author}

## Installation

1. Build the plugin:
   ```bash
   cargo build --release
   ```

2. Install the plugin in Vanguard:
   ```bash
   # On macOS:
   vanguard plugin install ./target/release/lib{plugin_name}.dylib
   
   # On Linux:
   vanguard plugin install ./target/release/lib{plugin_name}.so
   
   # On Windows:
   vanguard plugin install ./target/release/{plugin_name}.dll
   ```

## Notes

{installation_note}
"#
    )
}

/// Generate lib.rs content
fn generate_lib_rs(
    plugin_name: &str,
    struct_name: &str,
    description: &str,
    author: &str,
    version: &str,
    min_vanguard_version: Option<&str>,
) -> String {
    let min_version = min_vanguard_version.unwrap_or("0.1.0");

    format!(
        r#"use serde::{{Deserialize, Serialize}};
use vanguard_plugin_sdk::{{metadata, plugin, plugin_config, PluginMetadata, PluginMetadataBuilder}};

/// Configuration for the {plugin_name} plugin
#[derive(Debug, Serialize, Deserialize)]
pub struct {struct_name}Config {{
    /// Example configuration field
    pub value: String,
}}

plugin_config!({struct_name}Config, serde_json::json!({{
    "type": "object",
    "required": ["value"],
    "properties": {{
        "value": {{
            "type": "string",
            "description": "Example configuration value"
        }}
    }}
}}));

/// A plugin that {description}
#[derive(Debug)]
pub struct {struct_name}Plugin {{
    metadata: PluginMetadata,
    config: Option<{struct_name}Config>,
}}

impl {struct_name}Plugin {{
    /// Create a new plugin instance
    pub fn new() -> Self {{
        Self {{
            metadata: metadata()
                .name("{plugin_name}")
                .version("{version}")
                .description("{description}")
                .author("{author}")
                .min_vanguard_version("{min_version}")
                .build(),
            config: None,
        }}
    }}
}}

plugin!({struct_name}Plugin, {struct_name}Config);

#[cfg(test)]
mod tests {{
    use super::*;
    use vanguard_plugin_sdk::{{ValidationResult, VanguardPlugin}};

    #[tokio::test]
    async fn test_plugin_metadata() {{
        let plugin = {struct_name}Plugin::new();
        assert_eq!(plugin.metadata().name, "{plugin_name}");
        assert_eq!(plugin.metadata().version, "{version}");
    }}

    #[tokio::test]
    async fn test_plugin_validation() {{
        let plugin = {struct_name}Plugin::new();
        assert!(matches!(plugin.validate().await, ValidationResult::Passed));
    }}
}}
"#
    )
}

/// Generate lib.rs content with command support
fn generate_lib_rs_with_commands(
    plugin_name: &str,
    struct_name: &str,
    description: &str,
    author: &str,
    version: &str,
    min_vanguard_version: Option<&str>,
) -> String {
    let min_version = min_vanguard_version.unwrap_or("0.1.0");

    format!(
        r#"use serde::{{Deserialize, Serialize}};
use vanguard_plugin_sdk::{{
    command::{{Command, CommandContext, CommandResult, VanguardCommand}},
    command_handler, metadata, plugin, plugin_config, PluginMetadata, PluginMetadataBuilder
}};

/// Configuration for the {plugin_name} plugin
#[derive(Debug, Serialize, Deserialize)]
pub struct {struct_name}Config {{
    /// Example configuration field
    pub value: String,
}}

plugin_config!({struct_name}Config, serde_json::json!({{
    "type": "object",
    "required": ["value"],
    "properties": {{
        "value": {{
            "type": "string",
            "description": "Example configuration value"
        }}
    }}
}}));

/// A plugin that {description}
#[derive(Debug)]
pub struct {struct_name}Plugin {{
    metadata: PluginMetadata,
    config: Option<{struct_name}Config>,
}}

impl {struct_name}Plugin {{
    /// Create a new plugin instance
    pub fn new() -> Self {{
        Self {{
            metadata: metadata()
                .name("{plugin_name}")
                .version("{version}")
                .description("{description}")
                .author("{author}")
                .min_vanguard_version("{min_version}")
                .build(),
            config: None,
        }}
    }}

    /// Example command handler function
    fn handle_hello_command(&self, args: &[String]) -> String {{
        let name = args.get(0).cloned().unwrap_or_else(|| "World".to_string());
        format!("Hello, {{}}! This message is from the {plugin_name} plugin!", name)
    }}
}}

plugin!({struct_name}Plugin, {struct_name}Config);

// Implement command handling for the plugin
command_handler!({struct_name}Plugin, 
    vec![
        Command {{
            name: "hello".to_string(),
            description: "Says hello from the plugin".to_string(),
            usage: "{plugin_name} hello [name]".to_string(),
            aliases: vec!["hi".to_string(), "greet".to_string()],
        }}
    ],
    |plugin: &{struct_name}Plugin, command: &VanguardCommand, _ctx: &CommandContext| {{
        // Handle the command synchronously
        let result = match command.name.as_str() {{
            "hello" | "hi" | "greet" => {{
                let message = plugin.handle_hello_command(&command.args);
                println!("{{}}", message);
                CommandResult::Success
            }},
            _ => CommandResult::NotHandled,
        }};
        
        // Return a future that resolves to the result
        Box::pin(async move {{ result }})
    }}
);

#[cfg(test)]
mod tests {{
    use super::*;
    use vanguard_plugin_sdk::{{ValidationResult, VanguardPlugin}};

    #[tokio::test]
    async fn test_plugin_metadata() {{
        let plugin = {struct_name}Plugin::new();
        assert_eq!(plugin.metadata().name, "{plugin_name}");
        assert_eq!(plugin.metadata().version, "{version}");
    }}

    #[tokio::test]
    async fn test_plugin_validation() {{
        let plugin = {struct_name}Plugin::new();
        assert!(matches!(plugin.validate().await, ValidationResult::Passed));
    }}

    #[tokio::test]
    async fn test_command_handling() {{
        let plugin = {struct_name}Plugin::new();
        let cmd = VanguardCommand {{
            name: "hello".to_string(),
            args: vec!["Tester".to_string()],
            original: "hello Tester".to_string(),
        }};
        let ctx = CommandContext::default();
        let result = plugin.handle_command(&cmd, &ctx).await;
        assert!(matches!(result, CommandResult::Success));
    }}
}}
"#
    )
}

/// Generate a new plugin from a template
pub fn generate_plugin(path: impl AsRef<Path>, options: PluginOptions) -> TemplateResult<()> {
    let path = path.as_ref();

    // Validate plugin name
    let name = options.name.to_lowercase();
    if name.is_empty()
        || !name
            .chars()
            .all(|c| c.is_alphanumeric() || c == '_' || c == '-')
    {
        return Err(TemplateError::InvalidName(name));
    }

    // Create plugin directory
    fs::create_dir_all(path)?;

    // Generate plugin files
    let struct_name = to_pascal_case(&options.name);

    // Create the src directory
    let src_dir = path.join("src");
    fs::create_dir_all(&src_dir)?;

    // Create the README.md
    let readme_path = path.join("README.md");
    let readme_content = generate_readme(&options.name, &options.description, &options.author);
    fs::write(readme_path, readme_content)?;

    // Create Cargo.toml
    let cargo_toml_path = path.join("Cargo.toml");
    let cargo_toml_content = generate_cargo_toml(
        &options.name,
        &options.description,
        &options.author,
        &options.version,
    );
    fs::write(cargo_toml_path, cargo_toml_content)?;

    // Create lib.rs with the appropriate template
    let lib_rs_path = src_dir.join("lib.rs");
    let lib_rs_content = match options.template.as_deref() {
        Some("commands") => generate_lib_rs_with_commands(
            &options.name,
            &struct_name,
            &options.description,
            &options.author,
            &options.version,
            options.min_vanguard_version.as_deref(),
        ),
        _ => generate_lib_rs(
            &options.name,
            &struct_name,
            &options.description,
            &options.author,
            &options.version,
            options.min_vanguard_version.as_deref(),
        ),
    };
    fs::write(lib_rs_path, lib_rs_content)?;

    Ok(())
}