wdl-modules 0.2.1

Implementation of the WDL module specification
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
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
//! `module.json` manifest parsing and validation.

use std::collections::BTreeMap;
use std::path::Path;
use std::path::PathBuf;

use semver::Version;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use thiserror::Error;
use url::Url;

use crate::DEFAULT_ENTRYPOINT_FILENAME;
use crate::dependency::DependencyName;
use crate::dependency::DependencySource;
use crate::dependency::DependencySourceError;
use crate::license::LicenseError;
use crate::license::LicenseExpression;
use crate::relative_path::RelativePath;
use crate::relative_path::RelativePathError;

/// An error parsing a [`Manifest`].
///
/// Parsing is strict per the spec; trailing commas, comments, BOM, and
/// duplicate object keys at any nesting depth are all rejected.
#[derive(Debug, Error)]
pub enum ManifestError {
    /// The bytes did not parse as JSON.
    #[error("invalid `module.json` JSON")]
    InvalidJson(#[from] serde_json::Error),

    /// The `name` field is empty.
    #[error("`name` cannot be empty")]
    EmptyName,

    /// The `entrypoint` path failed relative-path validation.
    #[error("`entrypoint` is invalid")]
    InvalidEntrypoint(#[source] RelativePathError),

    /// The `readme` path failed relative-path validation.
    #[error("`readme` is invalid")]
    InvalidReadme(#[source] RelativePathError),

    /// An `exclude` entry failed relative-path validation.
    #[error("`exclude` entry `{pattern}` is invalid")]
    InvalidExclude {
        /// The offending pattern as written in the manifest.
        pattern: String,
        /// The underlying validation error.
        #[source]
        source: RelativePathError,
    },

    /// The `readme` field was set to the literal `true`. The schema only
    /// accepts a string, the literal `false`, or absence; `true` is
    /// rejected with a dedicated message because it is a common authoring
    /// mistake (mirroring `false` to mean "enable the default readme").
    #[error("`readme` cannot be set to `true`; omit the field to use the default `README.md`")]
    ReadmeTrue,

    /// A dependency key is not a valid WDL identifier.
    #[error("`dependencies` key `{0}` is not a valid WDL identifier")]
    InvalidDependencyName(String),

    /// Two dependency keys resolve to the same dependency (either
    /// identical or equivalent after hyphen-to-underscore normalization).
    #[error("duplicate `dependencies` key: `{0}` and `{1}` resolve to the same dependency")]
    DuplicateDependencyName(String, String),

    /// A dependency declaration is invalid.
    #[error(transparent)]
    DependencySource(#[from] DependencySourceError),

    /// The `license` field is not a valid SPDX expression.
    #[error(transparent)]
    License(#[from] LicenseError),
}

/// The `readme` field of a manifest.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Readme {
    /// The `readme` field was omitted; engines look for `README.md`.
    Default,
    /// The `readme` field is a relative path to a markdown file.
    Path(RelativePath),
    /// The `readme` field is the literal `false`; no readme is associated
    /// with the module.
    Disabled,
}

/// A `tools[]` entry.
#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]
pub struct Tool {
    /// The tool name.
    pub name: String,
    /// The tool version.
    pub version: String,
    /// The tool's SPDX license identifier.
    pub license: LicenseExpression,
    /// URL for the tool's homepage or repository.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub homepage: Option<Url>,
    /// DOI for the tool's publication.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub doi: Option<String>,
    /// `bio.tools` registry identifier.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub biotools: Option<String>,
    /// Unknown fields, preserved for round-trip and inspection by
    /// downstream linters.
    #[serde(flatten)]
    pub extra: serde_json::Map<String, serde_json::Value>,
}

/// A parsed `module.json`.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Manifest {
    /// The module's display name. Not used for dependency resolution.
    pub name: String,
    /// The module version.
    pub version: Version,
    /// The module's SPDX license expression.
    pub license: LicenseExpression,
    /// The author descriptions.
    pub authors: Vec<String>,
    /// A brief description of the module.
    pub description: Option<String>,
    /// The canonical Git URL for the module's source repository.
    pub repository: Option<Url>,
    /// A URL for the module's documentation or landing page.
    pub homepage: Option<Url>,
    /// The path to the module's entrypoint WDL file, relative to the
    /// module root. Defaults to [`DEFAULT_ENTRYPOINT_FILENAME`] if absent.
    pub entrypoint: Option<RelativePath>,
    /// The module's readme.
    pub readme: Readme,
    /// Gitignore-style glob patterns identifying files within the module
    /// that consumers may not reach via symbolic import. Each entry is a
    /// validated [`RelativePath`]; absolute paths, `..` segments, and
    /// other invalid forms are rejected at parse time. Has no effect on
    /// content hashing, signing, validation, or quoted within-module
    /// imports.
    pub exclude: Vec<RelativePath>,
    /// The upstream tools wrapped by the module.
    pub tools: Vec<Tool>,
    /// The module's dependencies, keyed by consumer-chosen name.
    pub dependencies: BTreeMap<DependencyName, DependencySource>,
    /// Unknown top-level fields. The spec requires implementations to
    /// ignore unrecognized fields; capturing them here lets downstream
    /// linters surface typos without a re-parse.
    pub extra: serde_json::Map<String, serde_json::Value>,
}

impl Manifest {
    /// Parses a `module.json` from raw bytes.
    pub fn parse(bytes: &[u8]) -> Result<Self, ManifestError> {
        let raw: ManifestFields = crate::strict_json::from_slice(bytes)?;
        raw.try_into()
    }

    /// Returns the entrypoint filename, falling back to
    /// [`DEFAULT_ENTRYPOINT_FILENAME`] when
    /// [`entrypoint`](Self::entrypoint) is unset.
    pub fn entrypoint_filename(&self) -> &Path {
        self.entrypoint
            .as_ref()
            .map(RelativePath::as_path)
            .unwrap_or(Path::new(DEFAULT_ENTRYPOINT_FILENAME))
    }
}

/// Flat field set of a manifest, deserialized straight from JSON before
/// post-deserialization validation projects it onto [`Manifest`].
#[derive(Debug, Deserialize)]
struct ManifestFields {
    /// The module's display name.
    name: String,
    /// The module version.
    version: Version,
    /// The module's SPDX license.
    license: String,
    /// The author descriptions.
    #[serde(default)]
    authors: Vec<String>,
    /// A brief description of the module.
    #[serde(default)]
    description: Option<String>,
    /// The canonical Git URL for the module's source repository.
    #[serde(default)]
    repository: Option<Url>,
    /// A URL for the module's documentation or landing page.
    #[serde(default)]
    homepage: Option<Url>,
    /// The path to the module's entrypoint WDL file.
    #[serde(default)]
    entrypoint: Option<PathBuf>,
    /// The `readme` field, accepting a string, `false`, or absence.
    #[serde(default, deserialize_with = "deserialize_readme")]
    readme: ReadmeFields,
    /// Gitignore-style glob patterns identifying files outside the public
    /// import surface.
    #[serde(default)]
    exclude: Vec<String>,
    /// The upstream tools.
    #[serde(default)]
    tools: Vec<Tool>,
    /// The module's dependencies.
    #[serde(default)]
    dependencies: BTreeMap<String, DependencySource>,
    /// Unknown top-level fields.
    #[serde(flatten)]
    extra: serde_json::Map<String, serde_json::Value>,
}

/// The `readme` field's JSON shape; one of a string, `false`, or absent.
/// The values `null` and `true` are rejected at parse time.
#[derive(Debug, Default)]
enum ReadmeFields {
    /// A relative path to a readme file.
    Path(PathBuf),
    /// The literal `false`, disabling the readme.
    Bool(bool),
    /// The field was absent.
    #[default]
    Default,
}

/// Deserializes the `readme` field, accepting `false` or a string path.
fn deserialize_readme<'de, D>(deserializer: D) -> Result<ReadmeFields, D::Error>
where
    D: Deserializer<'de>,
{
    let value = serde_json::Value::deserialize(deserializer)?;
    match value {
        serde_json::Value::String(s) => Ok(ReadmeFields::Path(PathBuf::from(s))),
        serde_json::Value::Bool(b) => Ok(ReadmeFields::Bool(b)),
        serde_json::Value::Null => Err(serde::de::Error::custom("`readme` cannot be null")),
        other => Err(serde::de::Error::custom(format!(
            "`readme` must be a string or `false`; got {other}"
        ))),
    }
}

impl TryFrom<ManifestFields> for Manifest {
    type Error = ManifestError;

    fn try_from(fields: ManifestFields) -> Result<Self, Self::Error> {
        if fields.name.is_empty() {
            return Err(ManifestError::EmptyName);
        }

        let license = fields.license.parse::<LicenseExpression>()?;

        let entrypoint = fields
            .entrypoint
            .as_deref()
            .map(RelativePath::try_from)
            .transpose()
            .map_err(ManifestError::InvalidEntrypoint)?;

        let readme = match fields.readme {
            ReadmeFields::Default => Readme::Default,
            ReadmeFields::Path(p) => Readme::Path(
                RelativePath::try_from(p.as_path()).map_err(ManifestError::InvalidReadme)?,
            ),
            ReadmeFields::Bool(false) => Readme::Disabled,
            ReadmeFields::Bool(true) => return Err(ManifestError::ReadmeTrue),
        };

        let mut deps: BTreeMap<DependencyName, DependencySource> = BTreeMap::new();
        for (key, value) in fields.dependencies {
            let name = key
                .parse()
                .map_err(|_| ManifestError::InvalidDependencyName(key))?;
            if let Some((existing, _)) = deps.get_key_value(&name) {
                return Err(ManifestError::DuplicateDependencyName(
                    existing.manifest().to_string(),
                    name.manifest().to_string(),
                ));
            }
            deps.insert(name, value);
        }

        let exclude = fields
            .exclude
            .into_iter()
            .map(|pattern| {
                pattern
                    .parse::<RelativePath>()
                    .map_err(|source| ManifestError::InvalidExclude { pattern, source })
            })
            .collect::<Result<Vec<_>, _>>()?;

        Ok(Self {
            name: fields.name,
            version: fields.version,
            license,
            authors: fields.authors,
            description: fields.description,
            repository: fields.repository,
            homepage: fields.homepage,
            entrypoint,
            readme,
            exclude,
            tools: fields.tools,
            dependencies: deps,
            extra: fields.extra,
        })
    }
}

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

    fn parse(s: &str) -> Result<Manifest, ManifestError> {
        Manifest::parse(s.as_bytes())
    }

    #[test]
    fn parses_minimal_manifest() {
        let m = parse(
            r#"{
                "name": "spellbook",
                "version": "1.2.0",
                "license": "MIT"
            }"#,
        )
        .unwrap();
        assert_eq!(m.name, "spellbook");
        assert_eq!(m.version.to_string(), "1.2.0");
        assert_eq!(m.license.as_str(), "MIT");
        assert!(m.authors.is_empty());
        assert!(matches!(m.readme, Readme::Default));
        assert_eq!(m.entrypoint_filename(), Path::new("index.wdl"));
    }

    #[test]
    fn parses_full_example() {
        let m = parse(
            r#"{
                "name": "spellbook",
                "version": "1.2.0",
                "license": "MIT OR Apache-2.0",
                "authors": ["Jane Doe <jane.doe@example.com>"],
                "description": "spellbook wrapper",
                "repository": "https://github.com/openwdl/spellbook",
                "homepage": "https://example.com",
                "tools": [
                    {
                        "name": "spellcheck",
                        "version": "2.0.1",
                        "license": "MIT",
                        "homepage": "https://example.com/sc"
                    }
                ],
                "dependencies": {
                    "common": {
                        "git": "https://github.com/openwdl/common",
                        "version": "^1.0.0"
                    },
                    "local_utils": { "path": "../utils" }
                }
            }"#,
        )
        .unwrap();
        assert_eq!(m.tools.len(), 1);
        assert_eq!(m.dependencies.len(), 2);
    }

    #[test]
    fn parses_readme_disabled() {
        let m = parse(
            r#"{
                "name": "spellbook",
                "version": "1.0.0",
                "license": "MIT",
                "readme": false
            }"#,
        )
        .unwrap();
        assert!(matches!(m.readme, Readme::Disabled));
    }

    #[test]
    fn parses_readme_path() {
        let m = parse(
            r#"{
                "name": "spellbook",
                "version": "1.0.0",
                "license": "MIT",
                "readme": "docs/README.md"
            }"#,
        )
        .unwrap();
        assert!(matches!(m.readme, Readme::Path(_)));
    }

    #[test]
    fn captures_unknown_top_level_fields() {
        let m = parse(
            r#"{
                "name": "spellbook",
                "version": "1.0.0",
                "license": "MIT",
                "extra_field": 42,
                "metadata": {"key": "value"}
            }"#,
        )
        .unwrap();
        assert!(m.extra.contains_key("extra_field"));
        assert!(m.extra.contains_key("metadata"));
    }

    #[test]
    fn rejects_empty_name() {
        let err = parse(r#"{ "name": "", "version": "1.0.0", "license": "MIT" }"#).unwrap_err();
        assert!(matches!(err, ManifestError::EmptyName));
    }

    #[test]
    fn rejects_invalid_license() {
        let err = parse(r#"{ "name": "spellbook", "version": "1.0.0", "license": "MIT-2.0" }"#)
            .unwrap_err();
        assert!(matches!(err, ManifestError::License(_)));
    }

    #[test]
    fn rejects_absolute_entrypoint() {
        let err = parse(
            r#"{
                "name": "spellbook",
                "version": "1.0.0",
                "license": "MIT",
                "entrypoint": "/abs/path.wdl"
            }"#,
        )
        .unwrap_err();
        assert!(matches!(err, ManifestError::InvalidEntrypoint(_)));
    }

    #[test]
    fn rejects_readme_true() {
        let err = parse(
            r#"{
                "name": "spellbook",
                "version": "1.0.0",
                "license": "MIT",
                "readme": true
            }"#,
        )
        .unwrap_err();
        assert!(matches!(err, ManifestError::ReadmeTrue));
    }

    #[test]
    fn rejects_readme_null() {
        let err = parse(
            r#"{
                "name": "spellbook",
                "version": "1.0.0",
                "license": "MIT",
                "readme": null
            }"#,
        )
        .unwrap_err();
        assert!(matches!(err, ManifestError::InvalidJson(_)));
    }

    #[test]
    fn parses_exclude_field() {
        let m = parse(
            r#"{
                "name": "spellbook",
                "version": "1.0.0",
                "license": "MIT",
                "exclude": ["internal/**", "scratch/*.wdl"]
            }"#,
        )
        .unwrap();
        assert_eq!(
            m.exclude
                .iter()
                .map(RelativePath::as_str)
                .collect::<Vec<_>>(),
            vec!["internal/**", "scratch/*.wdl"]
        );
    }

    #[test]
    fn rejects_invalid_exclude_entry() {
        let err = parse(
            r#"{
                "name": "spellbook",
                "version": "1.0.0",
                "license": "MIT",
                "exclude": ["internal/**", "/abs/path"]
            }"#,
        )
        .unwrap_err();
        match err {
            ManifestError::InvalidExclude { pattern, .. } => {
                assert_eq!(pattern, "/abs/path");
            }
            other => panic!("expected `InvalidExclude` variant; got {other:?}"),
        }
    }

    #[test]
    fn rejects_parent_dir_in_readme() {
        let err = parse(
            r#"{
                "name": "spellbook",
                "version": "1.0.0",
                "license": "MIT",
                "readme": "../escape.md"
            }"#,
        )
        .unwrap_err();
        assert!(matches!(err, ManifestError::InvalidReadme(_)));
    }

    fn assert_duplicate_key_error(err: ManifestError) {
        let inner = match err {
            ManifestError::InvalidJson(e) => e.to_string(),
            other => panic!("expected `InvalidJson` variant; got {other:?}"),
        };
        assert!(
            inner.contains("duplicate object key"),
            "wrong inner message: {inner}"
        );
    }

    #[test]
    fn rejects_duplicate_top_level_keys() {
        assert_duplicate_key_error(
            parse(
                r#"{
                    "name": "spellbook",
                    "name": "duplicate",
                    "version": "1.0.0",
                    "license": "MIT"
                }"#,
            )
            .unwrap_err(),
        );
    }

    #[test]
    fn rejects_duplicate_nested_keys() {
        assert_duplicate_key_error(
            parse(
                r#"{
                    "name": "spellbook",
                    "version": "1.0.0",
                    "license": "MIT",
                    "tools": [
                        {"name": "x", "name": "y", "version": "1", "license": "MIT"}
                    ]
                }"#,
            )
            .unwrap_err(),
        );
    }

    #[test]
    fn accepts_hyphenated_dep_key() {
        let m = parse(
            r#"{
                "name": "spellbook",
                "version": "1.0.0",
                "license": "MIT",
                "dependencies": { "my-dep": {"path": "../local"} }
            }"#,
        )
        .unwrap();
        let key: DependencyName = "my-dep".parse().unwrap();
        assert!(m.dependencies.contains_key(&key));
        assert_eq!(key.manifest(), "my-dep");
        assert_eq!(key.identifier(), "my_dep");
    }

    #[test]
    fn rejects_exact_duplicate_dep_keys() {
        let err = parse(
            r#"{
                "name": "spellbook",
                "version": "1.0.0",
                "license": "MIT",
                "dependencies": {
                    "dep": {"path": "../a"},
                    "dep": {"path": "../b"}
                }
            }"#,
        )
        .unwrap_err();
        assert!(
            matches!(err, ManifestError::InvalidJson(_)),
            "exact duplicate JSON keys should be rejected by strict JSON parsing, got: {err}"
        );
    }

    #[test]
    fn rejects_duplicate_hyphen_underscore_dep_keys() {
        let err = parse(
            r#"{
                "name": "spellbook",
                "version": "1.0.0",
                "license": "MIT",
                "dependencies": {
                    "spell-book": {"path": "../a"},
                    "spell_book": {"path": "../b"}
                }
            }"#,
        )
        .unwrap_err();
        assert!(
            matches!(err, ManifestError::DuplicateDependencyName(..)),
            "expected `DuplicateDependencyName`, got: {err}"
        );
    }

    #[test]
    fn rejects_non_identifier_dep_key() {
        let err = parse(
            r#"{
                "name": "spellbook",
                "version": "1.0.0",
                "license": "MIT",
                "dependencies": { "1bad": {"path": "../local"} }
            }"#,
        )
        .unwrap_err();
        assert!(matches!(err, ManifestError::InvalidDependencyName(_)));
    }
}