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
use std::borrow::Cow;
use std::collections::HashMap;
use std::str::FromStr;
use std::string::ToString;

use percent_encoding::USERINFO_ENCODE_SET;

use super::errors;
use super::parser;
use super::utils::PercentCodec;

/// A Package URL.
#[derive(Debug, Clone)]
pub struct PackageUrl<'a> {
    /// The package URL type.
    pub ty: Cow<'a, str>,
    /// The optional namespace
    pub namespace: Option<Cow<'a, str>>,
    /// The package name.
    pub name: Cow<'a, str>,
    /// The optional package version.
    pub version: Option<Cow<'a, str>>,
    /// The package qualifiers.
    pub qualifiers: HashMap<Cow<'a, str>, Cow<'a, str>>,
    /// The package subpath.
    pub subpath: Option<Cow<'a, str>>,
}

impl<'a> PackageUrl<'a> {
    /// Create a new Package URL with the provided type and name.
    pub fn new<T, N>(ty: T, name: N) -> Self
    where
        T: Into<Cow<'a, str>>,
        N: Into<Cow<'a, str>>,
    {
        Self {
            ty: ty.into(),
            namespace: None,
            name: name.into(),
            version: None,
            qualifiers: HashMap::new(),
            subpath: None,
        }
    }

    /// Assign a namespace to the package.
    pub fn with_namespace<N>(&mut self, namespace: N) -> &mut Self
    where
        N: Into<Cow<'a, str>>,
    {
        self.namespace = Some(namespace.into());
        self
    }

    /// Assign a version to the package.
    pub fn with_version<V>(&mut self, version: V) -> &mut Self
    where
        V: Into<Cow<'a, str>>,
    {
        self.version = Some(version.into());
        self
    }

    /// Assign a subpath to the package.
    pub fn with_subpath<S>(&mut self, subpath: S) -> &mut Self
    where
        S: Into<Cow<'a, str>>,
    {
        self.subpath = Some(subpath.into());
        self
    }

    /// Add a qualifier to the package.
    pub fn add_qualifier<K, V>(&mut self, key: K, value: V) -> &mut Self
    where
        K: Into<Cow<'a, str>>,
        V: Into<Cow<'a, str>>,
    {
        self.qualifiers.insert(key.into(), value.into());
        self
    }
}

impl FromStr for PackageUrl<'static> {
    type Err = errors::Error;

    fn from_str(s: &str) -> errors::Result<Self> {
        // Parse all components into strings (since we don't know infer from `s` lifetime)
        let (s, _) = parser::owned::parse_scheme(s)?;
        let (s, subpath) = parser::owned::parse_subpath(s)?;
        let (s, ql) = parser::owned::parse_qualifiers(s)?;
        let (s, version) = parser::owned::parse_version(s)?;
        let (s, ty) = parser::owned::parse_type(s)?;
        let (s, mut name) = parser::owned::parse_name(s)?;
        let (_, mut namespace) = parser::owned::parse_namespace(s)?;

        // Special rules for some types
        match ty.as_ref() {
            "bitbucket" | "github" => {
                name = name.to_lowercase().into();
                namespace = namespace.map(|ns| ns.to_lowercase().into());
            }
            "pypi" => {
                name = name.replace('_', "-").to_lowercase().into();
            }
            _ => {}
        };

        let mut purl = Self::new(ty, name);
        if let Some(ns) = namespace {
            purl.with_namespace(ns);
        }
        if let Some(v) = version {
            purl.with_version(v);
        }
        if let Some(sp) = subpath {
            purl.with_subpath(sp);
        }
        for (k, v) in ql.into_iter() {
            purl.add_qualifier(k, v);
        }

        // The obtained package url
        Ok(purl)
    }
}

impl<'a> ToString for PackageUrl<'a> {
    fn to_string(&self) -> String {
        let mut url = String::new();

        // Scheme: constant
        url.push_str("pkg");
        url.push(':');

        // Type: no encoding needed
        url.push_str(&self.ty);
        url.push('/');

        // Namespace: percent-encode each component
        if let Some(ref ns) = self.namespace {
            ns.split('/')
                .filter(|s| !s.is_empty())
                .map(|s| s.encode(USERINFO_ENCODE_SET))
                .for_each(|pe| {
                    pe.for_each(|s| url.push_str(s));
                    url.push('/')
                });
        }

        // Name: percent-encode the name
        self.name
            .encode(USERINFO_ENCODE_SET)
            .for_each(|s| url.push_str(s));

        // Version: percent-encode the version
        if let Some(ref v) = self.version {
            url.push('@');
            v.encode(USERINFO_ENCODE_SET).for_each(|s| url.push_str(s));
        }

        // Qualifiers: percent-encode the values
        if !self.qualifiers.is_empty() {
            url.push('?');

            let mut items = self.qualifiers.iter().collect::<Vec<_>>();
            items.sort();
            let ref mut it = items.iter().peekable();

            while let Some(&(k, v)) = it.next() {
                url.push_str(&k);
                url.push('=');
                &v.encode(USERINFO_ENCODE_SET).for_each(|s| url.push_str(s));
                if it.peek().is_some() {
                    url.push('&')
                };
            }
        }

        // Subpath: percent-encode the components
        if let Some(ref sp) = self.subpath {
            url.push('#');
            let components = sp
                .split('/')
                .filter(|&s| match s {
                    "" | "." | ".." => false,
                    _ => true,
                })
                .map(|s| s.encode(USERINFO_ENCODE_SET));
            let ref mut it = components.peekable();
            while let Some(component) = it.next() {
                component.for_each(|s| url.push_str(s));
                if it.peek().is_some() {
                    url.push('/')
                }
            }
        }

        url
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn test_from_str() {
        let raw_purl = "pkg:type/name/space/name@version?k1=v1&k2=v2#sub/path";
        let purl = PackageUrl::from_str(raw_purl).unwrap();
        assert_eq!(purl.ty, "type");
        assert_eq!(purl.namespace, Some(Cow::Borrowed("name/space")));
        assert_eq!(purl.name, "name");
        assert_eq!(purl.version, Some(Cow::Borrowed("version")));
        assert_eq!(purl.qualifiers.get("k1"), Some(&Cow::Borrowed("v1")));
        assert_eq!(purl.qualifiers.get("k2"), Some(&Cow::Borrowed("v2")));
        assert_eq!(purl.subpath, Some(Cow::Borrowed("sub/path")));
    }

    #[test]
    fn test_to_str() {
        let canonical = "pkg:type/name/space/name@version?k1=v1&k2=v2#sub/path";
        let purl_string = PackageUrl::new("type", "name")
            .with_namespace("name/space")
            .with_version("version")
            .with_subpath("sub/path")
            .add_qualifier("k1", "v1")
            .add_qualifier("k2", "v2")
            .to_string();
        assert_eq!(&purl_string, canonical);
    }

}