use serde_json::Value;
use crate::HapError;
use crate::record;
use crate::value::{self, Findings, Line, Note, Obj};
#[derive(Debug, Clone, PartialEq)]
pub struct PkgContextInfo {
packages: Vec<PkgContext>,
pub notes: Vec<Note>,
pub unmodelled: Vec<String>,
raw: Value,
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct PkgContext {
pub name: String,
pub package_name: String,
pub bundle_name: String,
pub module_name: String,
pub version: String,
pub entry_path: String,
pub is_so: bool,
pub dependency_alias: String,
}
impl PkgContext {
pub fn entry_record_name(&self) -> Option<String> {
if self.is_so || self.entry_path.is_empty() || self.entry_path.ends_with('/') {
return None;
}
Some(format!("&{}/{}&{}", self.name, record::strip_source_extension(&self.entry_path), self.version))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RecordOwner<'c, 'r> {
pub package: &'c PkgContext,
pub bundle: &'r str,
pub path: &'r str,
pub version: &'r str,
}
impl PkgContextInfo {
pub fn parse(bytes: &[u8]) -> Result<Self, HapError> {
let map = value::parse_object(bytes)?;
let mut findings = Findings::default();
let mut packages = Vec::with_capacity(map.len());
for (name, entry) in &map {
let Some(entry) = entry.as_object() else {
findings.notes.push(Note { path: name.clone(), message: format!("expected object, found {}", value::kind(entry)) });
continue;
};
let mut scratch = Findings::default();
let mut o = Obj::root(entry, &mut scratch);
packages.push(PkgContext {
name: name.clone(),
package_name: o.str("packageName").unwrap_or_default(),
bundle_name: o.str("bundleName").unwrap_or_default(),
module_name: o.str("moduleName").unwrap_or_default(),
version: o.text("version").unwrap_or_default(),
entry_path: o.str("entryPath").unwrap_or_default(),
is_so: o.bool("isSO").unwrap_or_default(),
dependency_alias: o.str("dependencyAlias").unwrap_or_default(),
});
o.finish();
findings.notes.extend(scratch.notes.into_iter().map(|n| Note { path: format!("{name}.{}", n.path), ..n }));
findings.unmodelled.extend(scratch.unmodelled.into_iter().map(|path| format!("{name}.{path}")));
}
packages.sort_by(|a, b| a.name.cmp(&b.name));
Ok(PkgContextInfo { packages, notes: findings.notes, unmodelled: findings.unmodelled, raw: Value::Object(map) })
}
pub fn packages(&self) -> &[PkgContext] {
&self.packages
}
pub fn get(&self, name: &str) -> Option<&PkgContext> {
self.packages.binary_search_by(|p| p.name.as_str().cmp(name)).ok().map(|i| &self.packages[i])
}
pub fn locate<'r>(&self, record: &'r str) -> Option<RecordOwner<'_, 'r>> {
let (bundle, rest) = record.split_once('&')?;
let (body, version) = rest.rsplit_once('&')?;
let boundaries = body.match_indices('/').map(|(i, _)| i).chain([body.len()]).collect::<Vec<_>>();
boundaries.into_iter().rev().find_map(|end| {
let package = self.get(&body[..end])?;
Some(RecordOwner { package, bundle, path: body[end..].trim_start_matches('/'), version })
})
}
pub fn raw(&self) -> &Value {
&self.raw
}
pub fn pretty(&self) -> String {
value::pretty(&self.raw)
}
pub fn summary_lines(&self) -> Vec<String> {
let text = |s: &str| if s.is_empty() { "-".to_owned() } else { value::token(s).into_owned() };
let mut out: Vec<String> = self
.packages
.iter()
.map(|p| {
let mut line = Line::new("package")
.word(&p.name)
.raw("version", text(&p.version))
.raw("entryPath", text(&p.entry_path))
.raw("isSO", p.is_so)
.raw("bundleName", text(&p.bundle_name))
.raw("moduleName", text(&p.module_name))
.raw("dependencyAlias", text(&p.dependency_alias));
if p.package_name != p.name {
line = line.raw("packageName", text(&p.package_name));
}
line.end()
})
.collect();
out.extend(self.unmodelled.iter().map(|path| Line::new("unmodelled").word(path).end()));
out.extend(self.notes.iter().map(|note| format!("note {note}")));
out
}
pub fn summary(&self) -> String {
crate::join_lines(&self.summary_lines())
}
}