metarepo-core 0.77.0

Core interfaces and types for the metarepo multi-project management tool
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use std::path::{Path, PathBuf};

/// Manifest filenames the loader recognizes, in priority order.
pub const MANIFEST_FILENAMES: &[&str] = &[
    "plugin.manifest.toml",
    "plugin.manifest.yaml",
    "plugin.manifest.yml",
    "plugin.manifest.json",
];

/// Plugin manifest structure (plugin.toml)
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginManifest {
    /// Plugin metadata
    pub plugin: PluginInfo,

    /// Commands provided by the plugin
    #[serde(default)]
    pub commands: Vec<ManifestCommand>,

    /// Plugin configuration options
    #[serde(default)]
    pub config: Option<PluginConfig>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginInfo {
    pub name: String,
    pub version: String,
    pub description: String,
    #[serde(default)]
    pub author: String,
    #[serde(default)]
    pub license: String,
    #[serde(default)]
    pub homepage: String,
    #[serde(default)]
    pub repository: String,
    #[serde(default)]
    pub experimental: bool,
    #[serde(default)]
    pub min_meta_version: Option<String>,
    /// Optional long, man-page-style help body for the plugin's top-level command.
    #[serde(
        default,
        alias = "helpDescription",
        skip_serializing_if = "Option::is_none"
    )]
    pub help_description: Option<String>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestCommand {
    pub name: String,
    pub description: String,
    #[serde(default)]
    pub long_description: Option<String>,
    /// Optional long, man-page-style help body rendered as a `Description:`
    /// section on `--help`.
    #[serde(
        default,
        alias = "helpDescription",
        skip_serializing_if = "Option::is_none"
    )]
    pub help_description: Option<String>,
    #[serde(default)]
    pub aliases: Vec<String>,
    #[serde(default)]
    pub args: Vec<ManifestArg>,
    #[serde(default)]
    pub subcommands: Vec<ManifestCommand>,
    #[serde(default)]
    pub examples: Vec<Example>,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct ManifestArg {
    pub name: String,
    #[serde(default)]
    pub short: Option<char>,
    #[serde(default)]
    pub long: Option<String>,
    pub help: String,
    #[serde(default)]
    pub required: bool,
    #[serde(default)]
    pub takes_value: bool,
    #[serde(default)]
    pub default_value: Option<String>,
    #[serde(default)]
    pub possible_values: Vec<String>,
    #[serde(default)]
    pub value_type: ArgValueType,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum ArgValueType {
    #[default]
    String,
    Number,
    Bool,
    Path,
    Url,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Example {
    pub command: String,
    pub description: String,
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PluginConfig {
    /// How the plugin should be executed
    #[serde(default)]
    pub execution: ExecutionConfig,

    /// Plugin capabilities
    #[serde(default)]
    pub capabilities: Vec<String>,

    /// Required environment variables
    #[serde(default)]
    pub required_env: Vec<String>,

    /// Plugin dependencies
    #[serde(default)]
    pub dependencies: Vec<Dependency>,
}

#[derive(Debug, Clone, Serialize, Deserialize, Default)]
pub struct ExecutionConfig {
    /// Execution mode: "process", "wasm", "docker"
    #[serde(default = "default_exec_mode")]
    pub mode: String,

    /// Path to the executable (relative to manifest)
    pub binary: Option<String>,

    /// Docker image for docker mode
    pub docker_image: Option<String>,

    /// WASM module for wasm mode
    pub wasm_module: Option<String>,

    /// Communication protocol: "json-rpc", "cli", "grpc"
    #[serde(default = "default_protocol")]
    pub protocol: String,
}

fn default_exec_mode() -> String {
    "process".to_string()
}

fn default_protocol() -> String {
    "cli".to_string()
}

#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct Dependency {
    pub name: String,
    pub version: String,
    #[serde(default)]
    pub optional: bool,
}

impl PluginManifest {
    /// Load manifest from a TOML file
    pub fn from_file(path: &Path) -> Result<Self> {
        let content = std::fs::read_to_string(path)?;
        Self::from_toml_str(&content)
    }

    /// Load a manifest, choosing the parser by file extension
    /// (`.toml`, `.yaml`/`.yml`, `.json`). Defaults to TOML for unknown
    /// extensions.
    pub fn from_file_auto(path: &Path) -> Result<Self> {
        let content = std::fs::read_to_string(path)
            .with_context(|| format!("Failed to read manifest {}", path.display()))?;
        let ext = path
            .extension()
            .and_then(|e| e.to_str())
            .unwrap_or("")
            .to_ascii_lowercase();
        let manifest: PluginManifest = match ext.as_str() {
            "json" => serde_json::from_str(&content)
                .with_context(|| format!("Invalid JSON manifest {}", path.display()))?,
            "yaml" | "yml" => serde_yaml::from_str(&content)
                .with_context(|| format!("Invalid YAML manifest {}", path.display()))?,
            _ => toml::from_str(&content)
                .with_context(|| format!("Invalid TOML manifest {}", path.display()))?,
        };
        manifest.validate()?;
        Ok(manifest)
    }

    /// Find a `plugin.manifest.*` file directly inside `dir`, if one exists.
    pub fn find_in_dir(dir: &Path) -> Option<PathBuf> {
        MANIFEST_FILENAMES
            .iter()
            .map(|name| dir.join(name))
            .find(|p| p.is_file())
    }

    /// Whether a path is a recognized manifest filename.
    pub fn is_manifest_path(path: &Path) -> bool {
        path.file_name()
            .and_then(|n| n.to_str())
            .map(|n| MANIFEST_FILENAMES.contains(&n))
            .unwrap_or(false)
    }

    /// Parse manifest from TOML string
    pub fn from_toml_str(content: &str) -> Result<Self> {
        let manifest: PluginManifest = toml::from_str(content)?;
        manifest.validate()?;
        Ok(manifest)
    }

    /// Resolve the plugin's executable path relative to the manifest's location.
    /// Uses `config.execution.binary` when set, falling back to a sibling file
    /// named after the plugin.
    pub fn resolve_binary(&self, manifest_path: &Path) -> Result<PathBuf> {
        let dir = manifest_path.parent().unwrap_or_else(|| Path::new("."));
        let rel = self
            .config
            .as_ref()
            .and_then(|c| c.execution.binary.as_deref())
            .unwrap_or(self.plugin.name.as_str());
        Ok(dir.join(rel))
    }

    /// Validate the manifest
    pub fn validate(&self) -> Result<()> {
        // Validate plugin info
        if self.plugin.name.is_empty() {
            return Err(anyhow::anyhow!("Plugin name cannot be empty"));
        }

        if self.plugin.version.is_empty() {
            return Err(anyhow::anyhow!("Plugin version cannot be empty"));
        }

        // Validate commands
        for cmd in &self.commands {
            Self::validate_command(cmd)?;
        }

        // Validate execution config if present
        if let Some(ref config) = self.config {
            let exec = &config.execution;
            match exec.mode.as_str() {
                "process" => {
                    if exec.binary.is_none() {
                        return Err(anyhow::anyhow!("Binary path required for process mode"));
                    }
                }
                "docker" => {
                    if exec.docker_image.is_none() {
                        return Err(anyhow::anyhow!("Docker image required for docker mode"));
                    }
                }
                "wasm" => {
                    if exec.wasm_module.is_none() {
                        return Err(anyhow::anyhow!("WASM module required for wasm mode"));
                    }
                }
                mode => {
                    return Err(anyhow::anyhow!("Unknown execution mode: {}", mode));
                }
            }
        }

        Ok(())
    }

    fn validate_command(cmd: &ManifestCommand) -> Result<()> {
        if cmd.name.is_empty() {
            return Err(anyhow::anyhow!("Command name cannot be empty"));
        }

        // Validate arguments
        for arg in &cmd.args {
            if arg.name.is_empty() {
                return Err(anyhow::anyhow!("Argument name cannot be empty"));
            }

            // Ensure either short or long flag is provided for non-positional args
            if !arg.required && arg.short.is_none() && arg.long.is_none() {
                return Err(anyhow::anyhow!(
                    "Argument '{}' must have either short or long flag",
                    arg.name
                ));
            }
        }

        // Recursively validate subcommands
        for subcmd in &cmd.subcommands {
            Self::validate_command(subcmd)?;
        }

        Ok(())
    }

    /// Generate a sample manifest
    pub fn example() -> Self {
        PluginManifest {
            plugin: PluginInfo {
                name: "example-plugin".to_string(),
                version: "0.1.0".to_string(),
                description: "An example metarepo plugin".to_string(),
                author: "Your Name".to_string(),
                license: "MIT".to_string(),
                homepage: "https://github.com/yourusername/example-plugin".to_string(),
                repository: "https://github.com/yourusername/example-plugin".to_string(),
                experimental: false,
                min_meta_version: Some("0.4.0".to_string()),
                help_description: Some(
                    "The example plugin demonstrates the manifest format.\n\n\
                     This text renders as a man-page-style Description section on \
                     `meta example --help`."
                        .to_string(),
                ),
            },
            commands: vec![ManifestCommand {
                name: "example".to_string(),
                description: "Example command".to_string(),
                long_description: Some(
                    "This is a longer description of the example command.".to_string(),
                ),
                help_description: None,
                aliases: vec!["ex".to_string()],
                args: vec![
                    ManifestArg {
                        name: "verbose".to_string(),
                        short: Some('v'),
                        long: Some("verbose".to_string()),
                        help: "Enable verbose output".to_string(),
                        required: false,
                        takes_value: false,
                        default_value: None,
                        possible_values: vec![],
                        value_type: ArgValueType::Bool,
                    },
                    ManifestArg {
                        name: "input".to_string(),
                        short: Some('i'),
                        long: Some("input".to_string()),
                        help: "Input file path".to_string(),
                        required: true,
                        takes_value: true,
                        default_value: None,
                        possible_values: vec![],
                        value_type: ArgValueType::Path,
                    },
                ],
                subcommands: vec![ManifestCommand {
                    name: "run".to_string(),
                    description: "Run the example".to_string(),
                    long_description: None,
                    help_description: None,
                    aliases: vec![],
                    args: vec![],
                    subcommands: vec![],
                    examples: vec![],
                }],
                examples: vec![Example {
                    command: "meta example -v --input file.txt run".to_string(),
                    description: "Run the example with verbose output".to_string(),
                }],
            }],
            config: Some(PluginConfig {
                execution: ExecutionConfig {
                    mode: "process".to_string(),
                    binary: Some("./bin/example-plugin".to_string()),
                    docker_image: None,
                    wasm_module: None,
                    protocol: "cli".to_string(),
                },
                capabilities: vec!["filesystem".to_string(), "network".to_string()],
                required_env: vec![],
                dependencies: vec![],
            }),
        }
    }

    /// Write example manifest to file
    pub fn write_example(path: &Path) -> Result<()> {
        let manifest = Self::example();
        let content = toml::to_string_pretty(&manifest)?;
        std::fs::write(path, content)?;
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use tempfile::tempdir;

    const TOML_SRC: &str = r#"
[plugin]
name = "foo"
version = "0.1.0"
description = "A foo plugin"

[[commands]]
name = "greet"
description = "Greet someone"

[[commands.args]]
name = "name"
help = "Who to greet"
required = true
takes_value = true

[config.execution]
binary = "./foo.sh"
"#;

    const YAML_SRC: &str = r#"
plugin:
  name: foo
  version: 0.1.0
  description: A foo plugin
commands:
  - name: greet
    description: Greet someone
    args:
      - name: name
        help: Who to greet
        required: true
        takes_value: true
config:
  execution:
    binary: ./foo.sh
"#;

    const JSON_SRC: &str = r#"
{
  "plugin": { "name": "foo", "version": "0.1.0", "description": "A foo plugin" },
  "commands": [
    { "name": "greet", "description": "Greet someone",
      "args": [ { "name": "name", "help": "Who to greet", "required": true, "takes_value": true } ] }
  ],
  "config": { "execution": { "binary": "./foo.sh" } }
}
"#;

    fn write(dir: &Path, name: &str, content: &str) -> PathBuf {
        let p = dir.join(name);
        std::fs::write(&p, content).unwrap();
        p
    }

    #[test]
    fn loads_all_three_formats_equivalently() {
        let dir = tempdir().unwrap();
        for (file, src) in [
            ("plugin.manifest.toml", TOML_SRC),
            ("plugin.manifest.yaml", YAML_SRC),
            ("plugin.manifest.json", JSON_SRC),
        ] {
            let path = write(dir.path(), file, src);
            let m = PluginManifest::from_file_auto(&path).unwrap();
            assert_eq!(m.plugin.name, "foo");
            assert_eq!(m.commands.len(), 1);
            assert_eq!(m.commands[0].name, "greet");
            assert_eq!(m.commands[0].args[0].name, "name");
        }
    }

    #[test]
    fn find_in_dir_prefers_toml_then_yaml_then_json() {
        let dir = tempdir().unwrap();
        write(dir.path(), "plugin.manifest.json", JSON_SRC);
        assert!(PluginManifest::find_in_dir(dir.path())
            .unwrap()
            .ends_with("plugin.manifest.json"));
        write(dir.path(), "plugin.manifest.toml", TOML_SRC);
        assert!(PluginManifest::find_in_dir(dir.path())
            .unwrap()
            .ends_with("plugin.manifest.toml"));
    }

    #[test]
    fn resolve_binary_is_relative_to_manifest() {
        let dir = tempdir().unwrap();
        let path = write(dir.path(), "plugin.manifest.toml", TOML_SRC);
        let m = PluginManifest::from_file_auto(&path).unwrap();
        let bin = m.resolve_binary(&path).unwrap();
        assert_eq!(bin, dir.path().join("foo.sh"));
    }

    #[test]
    fn is_manifest_path_matches_known_names() {
        assert!(PluginManifest::is_manifest_path(Path::new(
            "/x/plugin.manifest.yaml"
        )));
        assert!(!PluginManifest::is_manifest_path(Path::new("/x/foo.sh")));
    }
}