Skip to main content

wdl_modules/
symbolic_path.rs

1//! Symbolic-module-path parsing.
2
3use std::fmt;
4use std::path::Path;
5use std::path::PathBuf;
6use std::str::FromStr;
7
8use thiserror::Error;
9use wdl_grammar::lexer::v1::is_ident;
10
11use crate::dependency::DependencyName;
12
13/// An error parsing a [`SymbolicPath`].
14#[derive(Debug, Error)]
15#[error(
16    "symbolic module path `{0}` does not match `<dep-name>[/<sub-path>]` with non-empty, \
17     non-`.`/`..` segments"
18)]
19pub struct SymbolicPathError(String);
20
21/// A symbolic module path.
22///
23/// The string form is `<dep-name>[/<sub-path>]`. The `<dep-name>` is the
24/// key declared under `dependencies` in the consumer's `module.json`; the
25/// optional `<sub-path>` addresses a specific document within a module.
26///
27/// Path components are case-sensitive.
28#[derive(Clone, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)]
29pub struct SymbolicPath {
30    /// The dependency name component.
31    dep_name: DependencyName,
32    /// The optional sub-path within the dependency source.
33    sub_path: Option<PathBuf>,
34}
35
36impl SymbolicPath {
37    /// Returns the dependency name component.
38    pub fn dep_name(&self) -> &DependencyName {
39        &self.dep_name
40    }
41
42    /// Returns the sub-path component, if present.
43    pub fn sub_path(&self) -> Option<&Path> {
44        self.sub_path.as_deref()
45    }
46}
47
48/// Validates that a string matches `<dep-name>[/<sub-path>]` where every
49/// component (the dep name and each sub-path segment) is a WDL identifier.
50fn validate(s: &str) -> Result<SymbolicPath, SymbolicPathError> {
51    let mut iter = s.split('/');
52    // SAFETY: `str::split` always yields at least one item, even on the
53    // empty string.
54    let head = iter.next().unwrap();
55
56    let dep_name = head.parse().map_err(|_| SymbolicPathError(s.to_string()))?;
57
58    let mut sub_path = PathBuf::new();
59    let mut has_tail = false;
60    for segment in iter {
61        if !is_ident(segment) {
62            return Err(SymbolicPathError(s.to_string()));
63        }
64        sub_path.push(segment);
65        has_tail = true;
66    }
67
68    Ok(SymbolicPath {
69        dep_name,
70        sub_path: if has_tail { Some(sub_path) } else { None },
71    })
72}
73
74impl FromStr for SymbolicPath {
75    type Err = SymbolicPathError;
76
77    fn from_str(s: &str) -> Result<Self, Self::Err> {
78        validate(s)
79    }
80}
81
82impl fmt::Display for SymbolicPath {
83    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
84        f.write_str(self.dep_name.identifier())?;
85        if let Some(sub) = &self.sub_path {
86            for component in sub.iter() {
87                f.write_str("/")?;
88                f.write_str(&component.to_string_lossy())?;
89            }
90        }
91        Ok(())
92    }
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[test]
100    fn parses_dep_only() {
101        let p: SymbolicPath = "spellbook".parse().unwrap();
102        assert_eq!(p.dep_name().identifier(), "spellbook");
103        assert!(p.sub_path().is_none());
104    }
105
106    #[test]
107    fn parses_with_sub_path() {
108        let p: SymbolicPath = "spellbook/cauldron".parse().unwrap();
109        assert_eq!(p.dep_name().identifier(), "spellbook");
110        assert_eq!(p.sub_path().unwrap(), Path::new("cauldron"));
111    }
112
113    #[test]
114    fn parses_multi_segment_sub_path() {
115        let p: SymbolicPath = "spellbook/cauldron/runes".parse().unwrap();
116        assert_eq!(p.sub_path().unwrap(), Path::new("cauldron/runes"));
117    }
118
119    #[test]
120    fn rejects_invalid_format() {
121        for bad in [
122            "spellbook/",
123            "spellbook//cauldron",
124            "spellbook/cauldron/",
125            "spellbook/..",
126            "spellbook/.",
127            "1spellbook/cauldron",
128            "spellbook/has-dash",       // non-identifier sub-path segment
129            "spellbook/has space",      // whitespace
130            "spellbook/cauldron.runes", // non-identifier
131        ] {
132            assert!(bad.parse::<SymbolicPath>().is_err(), "accepted `{bad}`");
133        }
134    }
135
136    #[test]
137    fn case_sensitive() {
138        let lower: SymbolicPath = "spellbook/cauldron".parse().unwrap();
139        let mixed: SymbolicPath = "spellbook/Cauldron".parse().unwrap();
140        assert_ne!(lower.sub_path(), mixed.sub_path());
141    }
142
143    #[test]
144    fn round_trips_via_display() {
145        for s in [
146            "spellbook",
147            "spellbook/cauldron",
148            "spellbook/cauldron/runes",
149        ] {
150            let p: SymbolicPath = s.parse().unwrap();
151            assert_eq!(p.to_string(), s);
152        }
153    }
154}