pyro-artifacts 0.2.0

Cli commands for pyroduct
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
//! Conversions between our manifest and Cargo's

pub use cargo_toml::Dependency;
use cargo_toml::{
    Badges, DependencyDetail, DepsSet, Edition, FeatureSet, Inheritable, InheritedDependencyDetail,
    LintGroups, Manifest, Package, PatchSet, Product, Profiles, TargetDepsSet, Workspace,
};
use serde::{Deserialize, Serialize};
use std::{collections::BTreeMap, path::Path};
use toml::Value;

use crate::artifacts::{CapabilityConfig, PlaybookIdent};

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Eq, PartialOrd, Ord, Hash)]
pub struct CapabilityIdent {
    pub author: String,
    pub package: String,
    pub version: String,
}

impl CapabilityIdent {
    pub fn to_package(self) -> Package<Value> {
        let mut package = Package::new(self.package, self.version);
        package.authors = Inheritable::Set(vec![self.author]);
        package.edition = Inheritable::Set(Edition::E2024);
        package
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(untagged)]
pub enum ProjectManifest {
    Capability(CapabilityManifest),
    Module(ModuleManifest),
}

impl ProjectManifest {
    pub fn ident(&self) -> &CapabilityIdent {
        match self {
            ProjectManifest::Capability(c) => &c.capability,
            ProjectManifest::Module(m) => &m.module,
        }
    }

    pub fn to_cargo_manifest(self, cache_manager: Option<&crate::cache::CacheManager>) -> Manifest {
        match self {
            ProjectManifest::Capability(c) => c.to_capability_manifest(),
            ProjectManifest::Module(m) => m.to_cargo(cache_manager),
        }
    }

    pub fn to_interface_manifest(self) -> Option<Manifest> {
        match self {
            ProjectManifest::Capability(c) => Some(c.to_interface_manifest()),
            ProjectManifest::Module(_) => None,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct CapabilityManifest<Metadata = Value> {
    pub capability: CapabilityIdent,
    pub workspace: Option<Workspace<Metadata>>,
    #[serde(default = "default_pyroduct")]
    pub pyroduct: Dependency,
    #[serde(default)]
    pub dependencies: CapabilityDependencies,
    #[serde(default)]
    pub dev_dependencies: DepsSet,
    #[serde(default)]
    pub build_dependencies: DepsSet,
    #[serde(default)]
    pub target: TargetDepsSet,
    #[serde(default)]
    pub features: FeatureSet,
    #[serde(default)]
    #[deprecated(note = "Cargo recommends patch instead")]
    pub replace: DepsSet,
    #[serde(default)]
    pub patch: PatchSet,
    pub lib: Option<Product>,
    #[serde(default)]
    pub profile: Profiles,
    #[serde(default)]
    pub badges: Badges,
    #[serde(default)]
    pub bin: Vec<Product>,
    #[serde(default)]
    pub bench: Vec<Product>,
    #[serde(default)]
    pub test: Vec<Product>,
    #[serde(default)]
    pub example: Vec<Product>,
    #[serde(default)]
    pub lints: Inheritable<LintGroups>,
}

#[derive(Debug, thiserror::Error)]
pub enum ManifestError {
    #[error("Pyroduct does not support inherited versions (yet!)")]
    InheritedVersionNotSupported,
    #[error("[capability] section is missing")]
    CapabilitySectionMissing,
}

impl std::fmt::Display for CapabilityIdent {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}:{}:{}", self.author, self.package, self.version)
    }
}

#[derive(serde::Serialize, serde::Deserialize, Clone, Debug, PartialEq, Eq, Hash)]
pub struct ConfiguredCapability {
    pub author: String,
    pub package: String,
    pub version: String,
    pub configuration: CapabilityConfig,
}

impl ConfiguredCapability {
    pub fn ident(&self) -> CapabilityIdent {
        CapabilityIdent {
            author: self.author.clone(),
            package: self.package.clone(),
            version: self.version.clone(),
        }
    }
}

#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct ModuleManifest<Metadata = Value> {
    pub module: CapabilityIdent,
    pub workspace: Option<Workspace<Metadata>>,
    #[serde(default = "default_pyroduct")]
    pub pyroduct: Dependency,
    #[serde(default)]
    pub capabilities: BTreeMap<String, ConfiguredCapability>,
    #[serde(default)]
    pub dependencies: DepsSet,
    #[serde(default)]
    pub dev_dependencies: DepsSet,
    #[serde(default)]
    pub build_dependencies: DepsSet,
    #[serde(default)]
    pub target: TargetDepsSet,
    #[serde(default)]
    pub features: FeatureSet,
    #[serde(default)]
    pub patch: PatchSet,
    pub lib: Option<Product>,
    #[serde(default)]
    pub profile: Profiles,
    #[serde(default)]
    pub badges: Badges,
    #[serde(default)]
    pub bin: Vec<Product>,
    #[serde(default)]
    pub bench: Vec<Product>,
    #[serde(default)]
    pub test: Vec<Product>,
    #[serde(default)]
    pub example: Vec<Product>,
    #[serde(default)]
    pub lints: Inheritable<LintGroups>,
    #[serde(default)]
    pub interconnect: BTreeMap<String, PlaybookIdent>,
}

fn default_pyroduct() -> Dependency {
    Dependency::Inherited(InheritedDependencyDetail {
        workspace: true,
        ..Default::default()
    })
}

#[derive(Debug, Default, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub struct CapabilityDependencies {
    #[serde(default)]
    pub host: DepsSet,
    #[serde(default)]
    pub module: DepsSet,
    #[serde(default)]
    pub shared: DepsSet,
}

impl CapabilityManifest {
    /// Reads from a file string, processes logic, and returns a standard Manifest
    /// ready for serialization.
    pub fn to_capability_manifest(self) -> Manifest {
        let mut final_deps = BTreeMap::new();
        let mut pyro_dep = self.pyroduct.clone();
        pyro_dep
            .detail_mut()
            .features
            .push("capability".to_string());
        final_deps.insert("pyroduct".to_string(), pyro_dep);
        final_deps.extend(self.dependencies.shared.clone());
        self.augment_deps(&mut final_deps, &self.dependencies.host, true);
        self.augment_deps(&mut final_deps, &self.dependencies.module, true);
        let final_features = self.create_requisite_features(&self.features);

        #[allow(deprecated)]
        Manifest {
            package: Some(self.capability.to_package()),
            workspace: self.workspace,
            dependencies: final_deps,
            dev_dependencies: self.dev_dependencies,
            build_dependencies: self.build_dependencies,
            target: self.target,
            features: final_features,
            patch: self.patch,
            lib: ensure_cdylib(self.lib),
            profile: self.profile,
            badges: self.badges,
            bin: self.bin,
            bench: self.bench,
            test: self.test,
            example: self.example,
            lints: self.lints,
            replace: BTreeMap::default(),
        }
    }

    pub fn to_interface_manifest(self) -> Manifest {
        let mut final_deps = BTreeMap::new();

        // Use a simple version dependency for pyroduct to allow patching by the builder
        let mut pyro_dep = self.pyroduct.clone();
        pyro_dep.detail_mut().features.push("module".to_string());

        // 1. Shared Dependencies (Required)
        final_deps.extend(self.dependencies.shared.clone());
        final_deps.insert("pyroduct".to_string(), pyro_dep);

        // 2. Module Dependencies (Required, NOT optional)
        self.augment_deps(&mut final_deps, &self.dependencies.module, false);

        // 3. Pyroduct

        let final_features = self.features.clone();

        #[allow(deprecated)]
        Manifest {
            package: Some(self.capability.to_package()),
            workspace: self.workspace,
            dependencies: final_deps,
            dev_dependencies: self.dev_dependencies,
            build_dependencies: self.build_dependencies,
            target: self.target,
            features: final_features,
            patch: self.patch,
            lib: self.lib,
            profile: self.profile,
            badges: self.badges,
            bin: Vec::new(),
            bench: self.bench,
            test: self.test,
            example: self.example,
            lints: self.lints,
            replace: BTreeMap::default(),
        }
    }

    /// Helper: Augments dependencies with `optional = true` if requested
    /// and inserts them into the final map.
    fn augment_deps(&self, target_map: &mut DepsSet, source_map: &DepsSet, make_optional: bool) {
        for (name, dep) in source_map {
            let new_dep = if make_optional {
                match dep {
                    // Convert Simple ("1.0") -> Detailed { version = "1.0", optional = true }
                    Dependency::Simple(ver) => Dependency::Detailed(Box::new(DependencyDetail {
                        version: Some(ver.clone()),
                        optional: true,
                        ..Default::default()
                    })),
                    // Update Detailed to ensure optional is true
                    Dependency::Detailed(detail) => {
                        let mut d = detail.clone();
                        d.optional = true;
                        Dependency::Detailed(d)
                    }
                    // Inherited workspace deps also need to become detailed to hold the optional flag
                    Dependency::Inherited(inherited) => {
                        let mut d = inherited.clone();
                        d.optional = true;
                        Dependency::Inherited(d)
                    }
                }
            } else {
                dep.clone()
            };
            target_map.insert(name.clone(), new_dep);
        }
    }

    /// Helper: Generates the "capability" feature and defaults
    fn create_requisite_features(&self, existing_features: &FeatureSet) -> FeatureSet {
        let mut new_features = existing_features.clone();

        // Generate "dep:xxx" entries for all Host dependencies
        let capability_feature: Vec<String> = self
            .dependencies
            .host
            .keys()
            .map(|name| format!("dep:{}", name))
            .collect();

        let module_feature: Vec<String> = self
            .dependencies
            .module
            .keys()
            .map(|name| format!("dep:{}", name))
            .collect();

        new_features.insert("capability".to_string(), capability_feature);
        new_features.insert("module".to_string(), module_feature);

        // Ensure default and module exist (if not provided in input)
        new_features.entry("default".to_string()).or_default();

        new_features
    }
}

impl ModuleManifest {
    pub fn to_cargo(self, cache_manager: Option<&crate::cache::CacheManager>) -> Manifest {
        let mut final_deps = BTreeMap::new();
        let mut pyro_dep = self.pyroduct.clone();
        pyro_dep.detail_mut().features.push("module".to_string());
        final_deps.insert("pyroduct".to_string(), pyro_dep);
        final_deps.extend(self.dependencies.clone());
        self.augment_deps(&mut final_deps, &self.capabilities, cache_manager);

        #[allow(deprecated)]
        Manifest {
            package: Some(self.module.to_package()),
            workspace: self.workspace,
            dependencies: final_deps,
            dev_dependencies: self.dev_dependencies,
            build_dependencies: self.build_dependencies,
            target: self.target,
            features: BTreeMap::default(),
            patch: self.patch,
            lib: ensure_cdylib(self.lib),
            profile: self.profile,
            badges: self.badges,
            bin: self.bin,
            bench: self.bench,
            test: self.test,
            example: self.example,
            lints: self.lints,
            replace: BTreeMap::default(),
        }
    }

    fn augment_deps(
        &self,
        target_map: &mut DepsSet,
        capabilities: &BTreeMap<String, ConfiguredCapability>,
        cache_manager: Option<&crate::cache::CacheManager>,
    ) {
        for (name, cap) in capabilities.iter() {
            let path = if let Some(cm) = cache_manager {
                cm.interface_dir(&cap.author, &cap.package, &cap.version)
                    .to_string_lossy()
                    .into()
            } else {
                Path::new("..")
                    .join(&cap.author)
                    .join(&cap.package)
                    .join(&cap.version)
                    .to_string_lossy()
                    .into()
            };
            let dep = Dependency::Detailed(Box::new(DependencyDetail {
                path: Some(path),
                ..Default::default()
            }));
            target_map.insert(name.clone(), dep);
        }
    }
}

pub fn ensure_cdylib(lib: Option<Product>) -> Option<Product> {
    let lib = if let Some(mut lib) = lib {
        if !lib.crate_type.iter().any(|s| s.as_str() == "cdylib") {
            lib.crate_type.push("cdylib".to_string());
            lib
        } else {
            lib
        }
    } else {
        Product {
            crate_type: vec!["cdylib".to_string()],
            ..Default::default()
        }
    };
    Some(lib)
}

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

    #[test]
    fn test_full_transformation() {
        let input_toml = r#"
[capability]
package = "my-capability"
version = "0.1.0"
author = "Me"

[pyroduct]
path = "../../lib/pyroduct"

[dependencies.host]
tokio = "1.0"
uuid = { version = "1.0", features = ["v4"] }

[dependencies.module]
wasm-bindgen = "0.2"

[dependencies.shared]
serde = { version = "1.0", features = ["derive"] }
"#;

        // 1. Deserialize into Custom Struct
        let cap_manifest: CapabilityManifest = toml::from_str(input_toml).unwrap();

        // 2. Convert to Standard Manifest (Augment logic runs here)
        let standard_manifest = cap_manifest.to_capability_manifest();

        // 3. Verify Dependencies
        let deps = &standard_manifest.dependencies;

        // Check Host (converted to optional)
        match deps.get("tokio").unwrap() {
            Dependency::Detailed(d) => assert!(d.optional),
            _ => panic!("tokio should be detailed"),
        }

        // Check Shared (remains not optional)
        match deps.get("serde").unwrap() {
            Dependency::Detailed(d) => assert!(!d.optional),
            _ => panic!("serde should be detailed"),
        }

        // Check Pyroduct added
        assert!(deps.contains_key("pyroduct"));

        // 4. Verify Features
        let features = &standard_manifest.features;
        let cap_feat = features.get("capability").unwrap();

        assert!(cap_feat.contains(&"dep:tokio".to_string()));
        assert!(cap_feat.contains(&"dep:uuid".to_string()));
        // Module deps should NOT be in capability feature
        assert!(!cap_feat.contains(&"dep:wasm-bindgen".to_string()));

        // 5. Serialize back to String
        let output = toml::to_string_pretty(&standard_manifest).unwrap();
        println!("{}", output);
    }
}