Skip to main content

bv_core/
manifest.rs

1use std::collections::BTreeMap;
2use std::fmt;
3use std::path::PathBuf;
4use std::str::FromStr;
5
6use serde::{Deserialize, Serialize};
7
8use bv_types::{Cardinality, TypeRef};
9
10use crate::error::{BvError, Result};
11
12/// Quality and governance tier for a tool in the registry.
13#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Default)]
14#[serde(rename_all = "lowercase")]
15pub enum Tier {
16    /// Typed I/O complete, conformance tests pass, from a recognized publisher, actively maintained.
17    Core,
18    /// Typed I/O present (may be partial), basic checks pass.
19    #[default]
20    Community,
21    /// Basic checks pass; may lack typed I/O. Hidden from default search results.
22    Experimental,
23}
24
25impl Tier {
26    pub fn as_str(&self) -> &'static str {
27        match self {
28            Tier::Core => "core",
29            Tier::Community => "community",
30            Tier::Experimental => "experimental",
31        }
32    }
33}
34
35impl fmt::Display for Tier {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        f.write_str(self.as_str())
38    }
39}
40
41/// Structured CUDA version with ordering (`12.1 < 12.4 < 13.0`).
42#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
43pub struct CudaVersion {
44    pub major: u32,
45    pub minor: u32,
46}
47
48impl fmt::Display for CudaVersion {
49    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
50        write!(f, "{}.{}", self.major, self.minor)
51    }
52}
53
54impl FromStr for CudaVersion {
55    type Err = String;
56
57    fn from_str(s: &str) -> std::result::Result<Self, Self::Err> {
58        let (maj, min) = s
59            .split_once('.')
60            .ok_or_else(|| format!("expected 'major.minor', got '{s}'"))?;
61        Ok(CudaVersion {
62            major: maj
63                .parse()
64                .map_err(|_| format!("invalid major version '{maj}'"))?,
65            minor: min
66                .parse()
67                .map_err(|_| format!("invalid minor version '{min}'"))?,
68        })
69    }
70}
71
72impl TryFrom<String> for CudaVersion {
73    type Error = String;
74    fn try_from(s: String) -> std::result::Result<Self, Self::Error> {
75        s.parse()
76    }
77}
78
79impl From<CudaVersion> for String {
80    fn from(v: CudaVersion) -> String {
81        v.to_string()
82    }
83}
84
85impl Serialize for CudaVersion {
86    fn serialize<S: serde::Serializer>(&self, s: S) -> std::result::Result<S::Ok, S::Error> {
87        s.serialize_str(&self.to_string())
88    }
89}
90
91impl<'de> Deserialize<'de> for CudaVersion {
92    fn deserialize<D: serde::Deserializer<'de>>(d: D) -> std::result::Result<Self, D::Error> {
93        let s = String::deserialize(d)?;
94        s.parse().map_err(serde::de::Error::custom)
95    }
96}
97
98#[derive(Debug, Clone, Serialize, Deserialize)]
99pub struct GpuSpec {
100    pub required: bool,
101    pub min_vram_gb: Option<u32>,
102    pub cuda_version: Option<CudaVersion>,
103}
104
105#[derive(Debug, Clone, Serialize, Deserialize)]
106pub struct HardwareSpec {
107    pub gpu: Option<GpuSpec>,
108    pub cpu_cores: Option<u32>,
109    pub ram_gb: Option<f64>,
110    pub disk_gb: Option<f64>,
111}
112
113impl HardwareSpec {
114    /// Check this manifest's requirements against the host's detected hardware.
115    /// Returns every requirement that is not satisfied.
116    pub fn check_against(
117        &self,
118        detected: &crate::hardware::DetectedHardware,
119    ) -> Vec<crate::hardware::HardwareMismatch> {
120        use crate::hardware::HardwareMismatch;
121        let mut out = Vec::new();
122
123        if let Some(gpu_req) = &self.gpu
124            && gpu_req.required
125        {
126            if detected.gpus.is_empty() {
127                out.push(HardwareMismatch::NoGpu);
128            } else {
129                if let Some(min_vram) = gpu_req.min_vram_gb {
130                    let best_vram_mb = detected.gpus.iter().map(|g| g.vram_mb).max().unwrap_or(0);
131                    // Round to nearest GiB instead of floor: nvidia-smi
132                    // typically reports just-under marketing capacity (e.g.
133                    // 24268 MiB on a "24 GB" RTX 3090). flooring made
134                    // min_vram_gb=24 spuriously fail on real hardware.
135                    let best_vram_gb = ((best_vram_mb as f64) / 1024.0).round() as u32;
136                    if best_vram_gb < min_vram {
137                        out.push(HardwareMismatch::InsufficientVram {
138                            required_gb: min_vram,
139                            available_gb: best_vram_gb,
140                        });
141                    }
142                }
143                if let Some(min_cuda) = &gpu_req.cuda_version {
144                    let best_cuda = detected
145                        .gpus
146                        .iter()
147                        .filter_map(|g| g.cuda_version.as_ref())
148                        .max();
149                    match best_cuda {
150                        None => out.push(HardwareMismatch::NoCuda {
151                            required: min_cuda.clone(),
152                        }),
153                        Some(avail) if avail < min_cuda => {
154                            out.push(HardwareMismatch::CudaTooOld {
155                                required: min_cuda.clone(),
156                                available: avail.clone(),
157                            });
158                        }
159                        _ => {}
160                    }
161                }
162            }
163        }
164
165        if let Some(min_ram) = self.ram_gb {
166            let avail = detected.ram_gb();
167            if avail < min_ram {
168                out.push(HardwareMismatch::InsufficientRam {
169                    required_gb: min_ram,
170                    available_gb: avail,
171                });
172            }
173        }
174
175        if let Some(min_disk) = self.disk_gb {
176            let avail = detected.disk_free_gb();
177            if avail < min_disk {
178                out.push(HardwareMismatch::InsufficientDisk {
179                    required_gb: min_disk,
180                    available_gb: avail,
181                });
182            }
183        }
184
185        out
186    }
187}
188
189#[derive(Debug, Clone, Serialize, Deserialize)]
190pub struct ImageSpec {
191    /// Runtime backend, e.g. `"docker"` or `"apptainer"`.
192    pub backend: String,
193    /// Canonical OCI reference, e.g. `"biocontainers/bwa:0.7.17"`.
194    pub reference: String,
195    /// Optional pinned digest for reproducibility.
196    pub digest: Option<String>,
197}
198
199/// Layer descriptor embedded in a factored manifest.
200/// Mirrors `lockfile::LayerDescriptor` but lives in the registry TOML.
201#[derive(Debug, Clone, Serialize, Deserialize)]
202pub struct FactoredLayerSpec {
203    pub digest: String,
204    pub size: u64,
205    pub media_type: String,
206    #[serde(default, skip_serializing_if = "Option::is_none")]
207    pub conda_package: Option<FactoredCondaPin>,
208}
209
210#[derive(Debug, Clone, Serialize, Deserialize)]
211pub struct FactoredCondaPin {
212    pub name: String,
213    pub version: String,
214    pub build: String,
215    pub channel: String,
216    pub sha256: String,
217}
218
219/// Factored OCI build metadata embedded in the registry manifest.
220///
221/// When `[tool.factored]` is present, clients that support factored images
222/// can pull at layer granularity instead of pulling the monolithic squashed
223/// image in `[tool.image]`. The `[tool.image]` section remains required as
224/// the fallback path for older clients.
225#[derive(Debug, Clone, Serialize, Deserialize)]
226pub struct FactoredSpec {
227    /// Path to the bv-builder spec YAML relative to the registry root.
228    pub spec_path: String,
229    /// Canonical OCI reference for the factored image.
230    pub image_reference: String,
231    /// Pinned digest of the factored image manifest.
232    pub image_digest: String,
233    /// OCI referrer digest of the repodata snapshot artifact.
234    #[serde(default, skip_serializing_if = "Option::is_none")]
235    pub repodata_snapshot_digest: Option<String>,
236    /// Pre-computed per-layer descriptors, in manifest order.
237    #[serde(default, skip_serializing_if = "Vec::is_empty")]
238    pub layers: Vec<FactoredLayerSpec>,
239}
240
241#[derive(Debug, Clone, Serialize, Deserialize)]
242pub struct ReferenceDataSpec {
243    pub id: String,
244    pub version: String,
245    pub required: bool,
246    /// Container path where the dataset directory is mounted read-only.
247    #[serde(default, skip_serializing_if = "Option::is_none")]
248    pub mount_path: Option<String>,
249    /// Approximate compressed size in bytes.
250    #[serde(default, skip_serializing_if = "Option::is_none")]
251    pub size_bytes: Option<u64>,
252}
253
254/// Typed I/O port declaration for a tool.
255#[derive(Debug, Clone, Serialize, Deserialize)]
256pub struct IoSpec {
257    pub name: String,
258    /// Type reference, e.g. `"fasta"` or `"fasta[protein]"`.
259    #[serde(rename = "type")]
260    pub r#type: TypeRef,
261    /// How many values this port accepts.
262    #[serde(default)]
263    pub cardinality: Cardinality,
264    /// Absolute path inside the container where this value is mounted.
265    #[serde(default, skip_serializing_if = "Option::is_none")]
266    pub mount: Option<PathBuf>,
267    #[serde(default, skip_serializing_if = "Option::is_none")]
268    pub description: Option<String>,
269    #[serde(default, skip_serializing_if = "Option::is_none")]
270    pub default: Option<String>,
271}
272
273#[derive(Debug, Clone, Serialize, Deserialize)]
274pub struct EntrypointSpec {
275    pub command: String,
276    pub args_template: Option<String>,
277    #[serde(default)]
278    pub env: BTreeMap<String, String>,
279}
280
281/// Binary names that the tool's container exposes on PATH.
282///
283/// Omitting this block defaults to `exposed = [entrypoint.command]` for
284/// single-binary tools that do not need to declare anything extra.
285#[derive(Debug, Clone, Serialize, Deserialize)]
286pub struct BinariesSpec {
287    pub exposed: Vec<String>,
288}
289
290/// Per-tool overrides for `bv conformance`'s smoke check.
291///
292/// The smoke check tries a small set of probe args (`--version`, `-version`,
293/// `--help`, `-h`, `-v`, `version`) against every binary the tool exposes,
294/// and counts a binary as alive if any probe produces output or exits 0.
295/// Most tools don't need a `[tool.smoke]` block at all; this is the escape
296/// hatch for the unusual cases.
297#[derive(Debug, Clone, Default, Serialize, Deserialize)]
298pub struct SmokeSpec {
299    /// Override probe args for specific binaries, e.g. `{ "blastn" = "-version" }`.
300    /// Each value is a single command-line argument (or empty string for "run
301    /// the binary with no args"). When set, only this probe is tried for that
302    /// binary; the default list is bypassed.
303    #[serde(default, skip_serializing_if = "std::collections::BTreeMap::is_empty")]
304    pub probes: std::collections::BTreeMap<String, String>,
305    /// Binaries to skip entirely (daemons, "no non-destructive invocation"
306    /// tools, etc.). Listed binaries still appear in `[tool.binaries]` and
307    /// get shims; conformance just doesn't probe them.
308    #[serde(default, skip_serializing_if = "Vec::is_empty")]
309    pub skip: Vec<String>,
310}
311
312#[allow(dead_code)]
313fn default_timeout() -> u64 {
314    60
315}
316
317/// Optional Sigstore/cosign signature metadata.
318#[derive(Debug, Clone, Serialize, Deserialize)]
319pub struct SignatureSpec {
320    /// `"sigstore"` to verify the OCI image signature with cosign.
321    #[serde(default, skip_serializing_if = "Option::is_none")]
322    pub image: Option<String>,
323    /// `"sigstore"` to verify the manifest's commit signature.
324    #[serde(default, skip_serializing_if = "Option::is_none")]
325    pub manifest: Option<String>,
326}
327
328#[derive(Debug, Clone, Serialize, Deserialize)]
329pub struct ToolManifest {
330    pub id: String,
331    pub version: String,
332    pub description: Option<String>,
333    pub homepage: Option<String>,
334    pub license: Option<String>,
335    /// Governance tier. Defaults to `community` for new submissions.
336    #[serde(default)]
337    pub tier: Tier,
338    /// GitHub handles of maintainers, e.g. `"github:alice"`.
339    #[serde(default, skip_serializing_if = "Vec::is_empty")]
340    pub maintainers: Vec<String>,
341    /// Set to `true` when a tool is superseded or no longer maintained.
342    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
343    pub deprecated: bool,
344    pub image: ImageSpec,
345    pub hardware: HardwareSpec,
346    #[serde(default)]
347    pub reference_data: BTreeMap<String, ReferenceDataSpec>,
348    /// Typed inputs. Optional; manifests without this section parse unchanged.
349    #[serde(default)]
350    pub inputs: Vec<IoSpec>,
351    /// Typed outputs. Optional; manifests without this section parse unchanged.
352    #[serde(default)]
353    pub outputs: Vec<IoSpec>,
354    /// Default invocation. Required unless `[tool.subcommands]` is non-empty;
355    /// see `validate()`. Multi-script tools may omit this entirely.
356    #[serde(default, skip_serializing_if = "Option::is_none")]
357    pub entrypoint: Option<EntrypointSpec>,
358    /// Tool-namespaced launchers. Reachable as `bv run <toolid> <name> ...args`.
359    /// Each value is the literal argv prefix; user args are appended verbatim.
360    /// Unlike `[tool.binaries]`, names are not exposed on PATH or in the global
361    /// binary index, so generic names (`train`, `eval`) are safe.
362    #[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
363    pub subcommands: BTreeMap<String, Vec<String>>,
364    /// Container paths the tool writes to during normal execution and that
365    /// should therefore be bound to writable host directories. Critical on
366    /// apptainer (read-only SIF root), nice-to-have on docker (lets caches
367    /// outlive `docker rm`). Tool authors declare these; users can override
368    /// the host side via `[[cache]]` in `bv.toml`.
369    #[serde(default, skip_serializing_if = "Vec::is_empty")]
370    pub cache_paths: Vec<String>,
371    /// Binary names this tool exposes on PATH inside its container.
372    /// Omit for single-binary tools; defaults to `[entrypoint.command]`.
373    #[serde(default, skip_serializing_if = "Option::is_none")]
374    pub binaries: Option<BinariesSpec>,
375    /// Smoke-check overrides; consulted by `bv conformance` for unusual binaries.
376    #[serde(default, skip_serializing_if = "Option::is_none")]
377    pub smoke: Option<SmokeSpec>,
378    /// Sigstore / cosign signature declarations.
379    #[serde(default, skip_serializing_if = "Option::is_none")]
380    pub signatures: Option<SignatureSpec>,
381    /// Factored OCI build metadata. Present when the tool has been rebuilt
382    /// by `bv-builder`. Clients that understand factored images use this for
383    /// layer-granularity pulls; older clients fall back to `[tool.image]`.
384    #[serde(default, skip_serializing_if = "Option::is_none")]
385    pub factored: Option<FactoredSpec>,
386}
387
388impl ToolManifest {
389    pub fn has_typed_io(&self) -> bool {
390        !self.inputs.is_empty() || !self.outputs.is_empty()
391    }
392
393    /// Returns the effective list of binary names this tool exposes.
394    ///
395    /// When `[tool.binaries]` is absent, defaults to the entrypoint command's
396    /// basename. Multi-script tools without an entrypoint expose no binaries
397    /// (their subcommands stay namespaced under the tool id).
398    pub fn effective_binaries(&self) -> Vec<&str> {
399        if let Some(b) = &self.binaries {
400            return b.exposed.iter().map(|s| s.as_str()).collect();
401        }
402        let Some(ep) = &self.entrypoint else {
403            return vec![];
404        };
405        let cmd = &ep.command;
406        let name = cmd
407            .rfind('/')
408            .map(|i| &cmd[i + 1..])
409            .unwrap_or(cmd.as_str());
410        vec![name]
411    }
412}
413
414/// Top-level manifest, corresponding to a single `.toml` file in the registry.
415#[derive(Debug, Clone, Serialize, Deserialize)]
416pub struct Manifest {
417    pub tool: ToolManifest,
418}
419
420#[derive(Debug)]
421pub struct ValidationError {
422    pub field: String,
423    pub message: String,
424}
425
426impl fmt::Display for ValidationError {
427    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
428        write!(f, "{}: {}", self.field, self.message)
429    }
430}
431
432impl Manifest {
433    pub fn from_toml_str(s: &str) -> Result<Self> {
434        let m: Manifest = toml::from_str(s).map_err(|e| BvError::ManifestParse(e.to_string()))?;
435        m.validate_types()?;
436        if let Err(errs) = m.validate() {
437            let combined = errs
438                .iter()
439                .map(|e| e.to_string())
440                .collect::<Vec<_>>()
441                .join("; ");
442            return Err(BvError::ManifestParse(format!(
443                "manifest validation failed: {combined}"
444            )));
445        }
446        Ok(m)
447    }
448
449    pub fn to_toml_string(&self) -> Result<String> {
450        toml::to_string_pretty(self).map_err(|e| BvError::ManifestParse(e.to_string()))
451    }
452
453    /// Validates that all TypeRefs in inputs/outputs exist in the bv-types vocabulary.
454    fn validate_types(&self) -> Result<()> {
455        let t = &self.tool;
456        for (side, specs) in [("inputs", &t.inputs), ("outputs", &t.outputs)] {
457            for spec in specs {
458                let id = spec.r#type.base_id();
459                if bv_types::lookup(id).is_none() {
460                    let suggestion = bv_types::suggest(id)
461                        .map(|s| format!(", did you mean `{s}`?"))
462                        .unwrap_or_default();
463                    return Err(BvError::ManifestParse(format!(
464                        "tool.{side}[{}]: unknown type `{id}`{suggestion}",
465                        spec.name
466                    )));
467                }
468            }
469        }
470        Ok(())
471    }
472
473    /// Returns a list of validation errors, or `Ok(())` if the manifest is valid.
474    pub fn validate(&self) -> std::result::Result<(), Vec<ValidationError>> {
475        let mut errors = Vec::new();
476        let t = &self.tool;
477
478        if t.id.is_empty() {
479            errors.push(ValidationError {
480                field: "tool.id".into(),
481                message: "must not be empty".into(),
482            });
483        }
484        if t.version.is_empty() {
485            errors.push(ValidationError {
486                field: "tool.version".into(),
487                message: "must not be empty".into(),
488            });
489        }
490        if t.image.backend.is_empty() {
491            errors.push(ValidationError {
492                field: "tool.image.backend".into(),
493                message: "must not be empty".into(),
494            });
495        }
496        if t.image.reference.is_empty() {
497            errors.push(ValidationError {
498                field: "tool.image.reference".into(),
499                message: "must not be empty".into(),
500            });
501        }
502        match (&t.entrypoint, t.subcommands.is_empty()) {
503            (None, true) => errors.push(ValidationError {
504                field: "tool.entrypoint".into(),
505                message: "must declare either [tool.entrypoint] or [tool.subcommands]".into(),
506            }),
507            (Some(ep), _) if ep.command.is_empty() => errors.push(ValidationError {
508                field: "tool.entrypoint.command".into(),
509                message: "must not be empty".into(),
510            }),
511            _ => {}
512        }
513
514        for (name, cmd) in &t.subcommands {
515            if name.is_empty() {
516                errors.push(ValidationError {
517                    field: "tool.subcommands".into(),
518                    message: "subcommand name must not be empty".into(),
519                });
520                continue;
521            }
522            if name.starts_with('-') {
523                errors.push(ValidationError {
524                    field: format!("tool.subcommands.{name}"),
525                    message: "subcommand name must not start with '-'".into(),
526                });
527            }
528            if cmd.is_empty() {
529                errors.push(ValidationError {
530                    field: format!("tool.subcommands.{name}"),
531                    message: "command vector must not be empty".into(),
532                });
533            }
534        }
535
536        for spec in &t.inputs {
537            if let Some(mount) = &spec.mount
538                && !mount.is_absolute()
539            {
540                errors.push(ValidationError {
541                    field: format!("tool.inputs[{}].mount", spec.name),
542                    message: "must be an absolute path".into(),
543                });
544            }
545        }
546        for spec in &t.outputs {
547            if let Some(mount) = &spec.mount
548                && !mount.is_absolute()
549            {
550                errors.push(ValidationError {
551                    field: format!("tool.outputs[{}].mount", spec.name),
552                    message: "must be an absolute path".into(),
553                });
554            }
555        }
556
557        if let Some(binaries) = &t.binaries {
558            let mut seen = std::collections::HashSet::new();
559            for name in &binaries.exposed {
560                if !seen.insert(name.as_str()) {
561                    errors.push(ValidationError {
562                        field: "tool.binaries.exposed".into(),
563                        message: format!("duplicate binary name '{name}'"),
564                    });
565                }
566            }
567            if !binaries.exposed.is_empty()
568                && let Some(ep) = &t.entrypoint
569            {
570                let cmd = &ep.command;
571                let basename = cmd.rfind('/').map(|i| &cmd[i + 1..]).unwrap_or(cmd);
572                if !binaries.exposed.iter().any(|b| b == basename) {
573                    errors.push(ValidationError {
574                        field: "tool.binaries.exposed".into(),
575                        message: format!(
576                            "entrypoint command '{basename}' must be listed in exposed"
577                        ),
578                    });
579                }
580            }
581        }
582
583        if errors.is_empty() {
584            Ok(())
585        } else {
586            Err(errors)
587        }
588    }
589}
590
591#[cfg(test)]
592mod tests {
593    use super::*;
594
595    const SAMPLE: &str = r#"
596[tool]
597id = "bwa"
598version = "0.7.17"
599description = "BWA short-read aligner"
600homepage = "http://bio-bwa.sourceforge.net/"
601license = "GPL-3.0"
602
603[tool.image]
604backend = "docker"
605reference = "biocontainers/bwa:0.7.17--h5bf99c6_8"
606digest = "sha256:abcdef1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab"
607
608[tool.hardware]
609cpu_cores = 8
610ram_gb = 32.0
611disk_gb = 50.0
612
613[tool.hardware.gpu]
614required = false
615
616[[tool.inputs]]
617name = "reads_r1"
618type = "fastq"
619cardinality = "one"
620description = "Forward reads"
621
622[[tool.inputs]]
623name = "reads_r2"
624type = "fastq"
625cardinality = "optional"
626description = "Reverse reads (paired-end)"
627
628[[tool.outputs]]
629name = "alignment"
630type = "bam"
631description = "Aligned reads"
632
633[tool.entrypoint]
634command = "bwa"
635args_template = "mem -t {cpu_cores} {reference} {reads_r1} {reads_r2}"
636
637[tool.entrypoint.env]
638MALLOC_ARENA_MAX = "4"
639"#;
640
641    const SAMPLE_NO_IO: &str = r#"
642[tool]
643id = "mytool"
644version = "1.0.0"
645
646[tool.image]
647backend = "docker"
648reference = "example/mytool:1.0.0"
649
650[tool.hardware]
651
652[tool.entrypoint]
653command = "mytool"
654"#;
655
656    #[test]
657    fn round_trip() {
658        let manifest = Manifest::from_toml_str(SAMPLE).expect("parse failed");
659        assert_eq!(manifest.tool.id, "bwa");
660        assert_eq!(manifest.tool.version, "0.7.17");
661        assert_eq!(manifest.tool.image.backend, "docker");
662        assert_eq!(manifest.tool.inputs.len(), 2);
663        assert_eq!(manifest.tool.outputs.len(), 1);
664        assert_eq!(manifest.tool.inputs[0].cardinality, Cardinality::One);
665        assert_eq!(manifest.tool.inputs[1].cardinality, Cardinality::Optional);
666
667        let serialised = manifest.to_toml_string().expect("serialise failed");
668        let reparsed = Manifest::from_toml_str(&serialised).expect("reparse failed");
669        assert_eq!(reparsed.tool.id, manifest.tool.id);
670        assert_eq!(reparsed.tool.version, manifest.tool.version);
671    }
672
673    /// Regression: HashMap-backed fields produced non-deterministic TOML
674    /// output, breaking lockfile drift detection. Re-serializing the same
675    /// manifest must always yield identical bytes.
676    #[test]
677    fn to_toml_string_is_deterministic_with_subcommands() {
678        let s = r#"
679[tool]
680id = "multi"
681version = "1.0.0"
682
683[tool.image]
684backend = "docker"
685reference = "example/multi:1.0.0"
686
687[tool.hardware]
688
689[tool.entrypoint]
690command = "main"
691
692[tool.subcommands]
693zebra = ["script_z.py"]
694alpha = ["script_a.py"]
695mango = ["python", "-m", "scripts.mango"]
696beta = ["script_b.py"]
697"#;
698        let m = Manifest::from_toml_str(s).expect("parse");
699        let a = m.to_toml_string().unwrap();
700        // Re-serialize many times to make iteration-order luck unlikely.
701        for _ in 0..32 {
702            assert_eq!(a, m.to_toml_string().unwrap(), "non-deterministic output");
703        }
704        // And the keys must appear in lexicographic order (BTreeMap).
705        let alpha = a.find("alpha = ").unwrap();
706        let beta = a.find("beta = ").unwrap();
707        let mango = a.find("mango = ").unwrap();
708        let zebra = a.find("zebra = ").unwrap();
709        assert!(alpha < beta && beta < mango && mango < zebra);
710    }
711
712    #[test]
713    fn no_io_parses_unchanged() {
714        let m = Manifest::from_toml_str(SAMPLE_NO_IO).expect("parse failed");
715        assert!(m.tool.inputs.is_empty());
716        assert!(m.tool.outputs.is_empty());
717        assert!(!m.tool.has_typed_io());
718    }
719
720    #[test]
721    fn typeref_params_parsed() {
722        let s = r#"
723[tool]
724id = "t"
725version = "1.0.0"
726
727[tool.image]
728backend = "docker"
729reference = "example/t:1.0.0"
730
731[tool.hardware]
732
733[[tool.inputs]]
734name = "seqs"
735type = "fasta[protein]"
736cardinality = "one"
737
738[tool.entrypoint]
739command = "t"
740"#;
741        let m = Manifest::from_toml_str(s).unwrap();
742        assert_eq!(m.tool.inputs[0].r#type.params, vec!["protein"]);
743    }
744
745    #[test]
746    fn unknown_type_error() {
747        let s = r#"
748[tool]
749id = "t"
750version = "1.0.0"
751
752[tool.image]
753backend = "docker"
754reference = "example/t:1.0.0"
755
756[tool.hardware]
757
758[[tool.inputs]]
759name = "seqs"
760type = "protien_fasta"
761cardinality = "one"
762
763[tool.entrypoint]
764command = "t"
765"#;
766        let err = Manifest::from_toml_str(s).unwrap_err();
767        let msg = err.to_string();
768        assert!(msg.contains("unknown type"), "got: {msg}");
769    }
770
771    #[test]
772    fn cuda_version_ordering() {
773        let v12_1: CudaVersion = "12.1".parse().unwrap();
774        let v12_4: CudaVersion = "12.4".parse().unwrap();
775        let v13_0: CudaVersion = "13.0".parse().unwrap();
776        assert!(v12_1 < v12_4);
777        assert!(v12_4 < v13_0);
778        assert_eq!(v12_1, "12.1".parse::<CudaVersion>().unwrap());
779    }
780
781    #[test]
782    fn subcommands_only_parses() {
783        let s = r#"
784[tool]
785id = "genie2"
786version = "1.0.0"
787
788[tool.image]
789backend = "docker"
790reference = "ghcr.io/example/genie2:1.0.0"
791
792[tool.hardware]
793
794[tool.subcommands]
795train                = ["python", "genie/train.py"]
796sample_unconditional = ["python", "genie/sample_unconditional.py"]
797"#;
798        let m = Manifest::from_toml_str(s).unwrap();
799        assert!(m.tool.entrypoint.is_none());
800        assert_eq!(m.tool.subcommands.len(), 2);
801        assert_eq!(
802            m.tool.subcommands.get("train").unwrap(),
803            &vec!["python".to_string(), "genie/train.py".to_string()]
804        );
805        m.validate().expect("subcommand-only manifest is valid");
806        // No entrypoint and no [tool.binaries] => no exposed binaries.
807        assert!(m.tool.effective_binaries().is_empty());
808    }
809
810    #[test]
811    fn validate_requires_entrypoint_or_subcommands() {
812        let s = r#"
813[tool]
814id = "broken"
815version = "1.0.0"
816
817[tool.image]
818backend = "docker"
819reference = "example/broken:1.0.0"
820
821[tool.hardware]
822"#;
823        // from_toml_str now runs validate(); manifest with neither entrypoint
824        // nor subcommands must be rejected at parse time.
825        let err = Manifest::from_toml_str(s).unwrap_err();
826        assert!(
827            err.to_string().contains("tool.entrypoint"),
828            "expected entrypoint-or-subcommands error, got: {err}"
829        );
830    }
831
832    #[test]
833    fn validate_rejects_dash_prefixed_subcommand() {
834        let s = r#"
835[tool]
836id = "t"
837version = "1.0.0"
838
839[tool.image]
840backend = "docker"
841reference = "example/t:1.0.0"
842
843[tool.hardware]
844
845[tool.subcommands]
846"-bad" = ["python", "x.py"]
847"#;
848        let err = Manifest::from_toml_str(s).unwrap_err();
849        assert!(err.to_string().contains("-bad"), "got: {err}");
850    }
851
852    #[test]
853    fn subcommands_round_trip() {
854        let s = r#"
855[tool]
856id = "t"
857version = "1.0.0"
858
859[tool.image]
860backend = "docker"
861reference = "example/t:1.0.0"
862
863[tool.hardware]
864
865[tool.subcommands]
866go = ["python", "main.py"]
867"#;
868        let m = Manifest::from_toml_str(s).unwrap();
869        let serialised = m.to_toml_string().unwrap();
870        let reparsed = Manifest::from_toml_str(&serialised).unwrap();
871        assert_eq!(reparsed.tool.subcommands.len(), 1);
872    }
873
874    #[test]
875    fn validate_catches_empty_id() {
876        let mut manifest = Manifest::from_toml_str(SAMPLE).unwrap();
877        manifest.tool.id = String::new();
878        let errs = manifest.validate().unwrap_err();
879        assert!(errs.iter().any(|e| e.field == "tool.id"));
880    }
881
882    #[test]
883    fn registry_manifests_parse() {
884        let registry = concat!(env!("CARGO_MANIFEST_DIR"), "/../../bv-registry/tools");
885        let Ok(read) = std::fs::read_dir(registry) else {
886            return;
887        };
888        for entry in read {
889            let tool_dir = entry.unwrap().path();
890            if !tool_dir.is_dir() {
891                continue;
892            }
893            for version_entry in std::fs::read_dir(&tool_dir).unwrap() {
894                let path = version_entry.unwrap().path();
895                if path.extension().is_some_and(|e| e == "toml") {
896                    let s = std::fs::read_to_string(&path)
897                        .unwrap_or_else(|_| panic!("failed to read {}", path.display()));
898                    Manifest::from_toml_str(&s)
899                        .unwrap_or_else(|e| panic!("{}: {e}", path.display()));
900                }
901            }
902        }
903    }
904}