use serde_json::Value;
use crate::error::ParseError;
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PackageIndex {
workspace_root: String,
packages: Vec<(String, String, String)>,
}
impl PackageIndex {
#[must_use]
pub fn len(&self) -> usize {
self.packages.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.packages.is_empty()
}
#[must_use]
pub fn package_at(&self, source_path: &str) -> Option<(&str, &str)> {
if source_path.is_empty() {
return None;
}
let normalised = normalise(source_path);
let absolute = if is_absolute(&normalised) {
normalised
} else {
let root = normalise(&self.workspace_root);
format!("{}/{}", root.trim_end_matches('/'), normalised)
};
self.packages
.iter()
.find(|(directory, _, _)| under(&absolute, directory))
.map(|(_, name, version)| (name.as_str(), version.as_str()))
}
}
pub fn parse(text: &str) -> Result<PackageIndex, ParseError> {
let value: Value = serde_json::from_str(text).map_err(|e| ParseError::Metadata {
detail: e.to_string(),
})?;
let packages = value
.get("packages")
.and_then(Value::as_array)
.ok_or_else(|| ParseError::Metadata {
detail: "there is no `packages` array".to_owned(),
})?;
let mut entries: Vec<(String, String, String)> = Vec::with_capacity(packages.len());
for package in packages {
let (Some(name), Some(version), Some(manifest)) = (
package.get("name").and_then(Value::as_str),
package.get("version").and_then(Value::as_str),
package.get("manifest_path").and_then(Value::as_str),
) else {
continue;
};
entries.push((
normalise(parent_of(manifest)),
name.to_owned(),
version.to_owned(),
));
}
if entries.is_empty() {
return Err(ParseError::Metadata {
detail: "the `packages` array names no package with a manifest path".to_owned(),
});
}
entries.sort_by(|a, b| {
b.0.len()
.cmp(&a.0.len())
.then_with(|| a.1.cmp(&b.1))
.then_with(|| a.2.cmp(&b.2))
});
Ok(PackageIndex {
workspace_root: value
.get("workspace_root")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned(),
packages: entries,
})
}
fn normalise(path: &str) -> String {
path.replace('\\', "/")
}
fn is_absolute(path: &str) -> bool {
if path.starts_with('/') {
return true;
}
let mut chars = path.chars();
matches!(
(chars.next(), chars.next(), chars.next()),
(Some(letter), Some(':'), Some('/')) if letter.is_ascii_alphabetic()
)
}
fn under(path: &str, directory: &str) -> bool {
let directory = directory.trim_end_matches('/');
match path.strip_prefix(directory) {
Some(rest) => rest.is_empty() || rest.starts_with('/'),
None => false,
}
}
fn parent_of(path: &str) -> &str {
match path.rfind(['/', '\\']) {
Some(at) => path.get(..at).unwrap_or(""),
None => "",
}
}