126 lines
4.5 KiB
Rust
126 lines
4.5 KiB
Rust
//! The parts of a package URL (purl), as far as the SBOM documents need them:
|
|
//! `pkg:type/namespace/name@version?qualifiers#subpath`
|
|
//! (<https://github.com/package-url/purl-spec>).
|
|
|
|
/// A parsed purl. Every part is percent-decoded.
|
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
pub struct Purl {
|
|
/// The package type, lowercased (`npm`, `maven`, `nuget`).
|
|
pub ty: String,
|
|
/// The namespace: a Maven group id, an npm scope (`@angular`).
|
|
pub namespace: Option<String>,
|
|
pub name: String,
|
|
pub version: Option<String>,
|
|
/// The qualifiers in their order (`type=jar`, `classifier=sources`).
|
|
pub qualifiers: Vec<(String, String)>,
|
|
}
|
|
|
|
impl Purl {
|
|
/// Parse `purl`; `None` for anything that is not a `pkg:` URL with a type
|
|
/// and a name.
|
|
pub fn parse(purl: &str) -> Option<Self> {
|
|
let rest = purl.strip_prefix("pkg:")?.trim_start_matches('/');
|
|
// The subpath is not needed; the qualifiers end where it starts.
|
|
let rest = rest.split('#').next().unwrap_or(rest);
|
|
let (rest, qualifiers) = match rest.split_once('?') {
|
|
Some((rest, query)) => (rest, query),
|
|
None => (rest, ""),
|
|
};
|
|
let (path, version) = match rest.rsplit_once('@') {
|
|
// An `@` in the path is an encoded npm scope (`%40angular`), so the
|
|
// version separator is the last one, after the last `/`.
|
|
Some((path, version)) if !version.contains('/') => (path, Some(decode(version))),
|
|
_ => (rest, None),
|
|
};
|
|
let (ty, path) = path.split_once('/')?;
|
|
let (namespace, name) = match path.rsplit_once('/') {
|
|
Some((namespace, name)) => (Some(namespace), name),
|
|
None => (None, path),
|
|
};
|
|
if ty.is_empty() || name.is_empty() {
|
|
return None;
|
|
}
|
|
Some(Self {
|
|
ty: ty.to_ascii_lowercase(),
|
|
namespace: namespace
|
|
.filter(|n| !n.is_empty())
|
|
.map(|n| n.split('/').map(decode).collect::<Vec<_>>().join("/")),
|
|
name: decode(name),
|
|
version: version.filter(|v| !v.is_empty()),
|
|
qualifiers: qualifiers
|
|
.split('&')
|
|
.filter_map(|pair| pair.split_once('='))
|
|
.map(|(k, v)| (k.to_ascii_lowercase(), decode(v)))
|
|
.collect(),
|
|
})
|
|
}
|
|
|
|
/// The value of qualifier `key`, if given.
|
|
pub fn qualifier(&self, key: &str) -> Option<&str> {
|
|
self.qualifiers
|
|
.iter()
|
|
.find(|(k, _)| k == key)
|
|
.map(|(_, v)| v.as_str())
|
|
}
|
|
}
|
|
|
|
/// `text` with its `%XX` escapes decoded; an invalid escape is kept as is.
|
|
fn decode(text: &str) -> String {
|
|
let bytes = text.as_bytes();
|
|
let mut out = Vec::with_capacity(bytes.len());
|
|
let mut i = 0;
|
|
while i < bytes.len() {
|
|
let escaped = (bytes[i] == b'%')
|
|
.then(|| text.get(i + 1..i + 3))
|
|
.flatten()
|
|
.and_then(|hex| u8::from_str_radix(hex, 16).ok());
|
|
match escaped {
|
|
Some(byte) => {
|
|
out.push(byte);
|
|
i += 3;
|
|
}
|
|
None => {
|
|
out.push(bytes[i]);
|
|
i += 1;
|
|
}
|
|
}
|
|
}
|
|
String::from_utf8_lossy(&out).into_owned()
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn the_parts_are_read_and_decoded() {
|
|
let p = Purl::parse("pkg:npm/%40angular/core@16.2.0").unwrap();
|
|
assert_eq!(p.ty, "npm");
|
|
assert_eq!(p.namespace.as_deref(), Some("@angular"));
|
|
assert_eq!(p.name, "core");
|
|
assert_eq!(p.version.as_deref(), Some("16.2.0"));
|
|
|
|
let p = Purl::parse(
|
|
"pkg:maven/org.apache.logging.log4j/log4j-core@2.14.1?classifier=tests&type=test-jar",
|
|
)
|
|
.unwrap();
|
|
assert_eq!(p.namespace.as_deref(), Some("org.apache.logging.log4j"));
|
|
assert_eq!(p.qualifier("type"), Some("test-jar"));
|
|
assert_eq!(p.qualifier("classifier"), Some("tests"));
|
|
|
|
let p = Purl::parse("pkg:golang/github.com/gin-gonic/gin@v1.9.1").unwrap();
|
|
assert_eq!(p.namespace.as_deref(), Some("github.com/gin-gonic"));
|
|
assert_eq!(p.name, "gin");
|
|
|
|
let p = Purl::parse("pkg:nuget/Newtonsoft.Json").unwrap();
|
|
assert_eq!((p.namespace, p.version), (None, None));
|
|
}
|
|
|
|
#[test]
|
|
fn what_is_not_a_purl_is_refused() {
|
|
assert_eq!(Purl::parse("npm:lodash@4.17.20"), None);
|
|
assert_eq!(Purl::parse("pkg:npm"), None);
|
|
assert_eq!(Purl::parse("pkg:/lodash"), None);
|
|
}
|
|
}
|