Skip to main content

asc_hap/
pkg_context.rs

1//! `pkgContextInfo.json`: the table of every package (the module itself,
2//! HARs, npm-style dependencies, native libraries) compiled into the
3//! module's `.abc`.
4//!
5//! It is written when the build uses normalized OHM URLs, and it is what
6//! links the manifest to the code: record names and import requests in
7//! the `.abc` then read `[bundle]&<packageName>/<path>&<version>`.
8
9use serde_json::Value;
10
11use crate::HapError;
12use crate::record;
13use crate::value::{self, Findings, Line, Note, Obj};
14
15/// A parsed `pkgContextInfo.json`.
16#[derive(Debug, Clone, PartialEq)]
17pub struct PkgContextInfo {
18    /// Sorted by [`PkgContext::name`].
19    packages: Vec<PkgContext>,
20    /// Fields that were present but wrongly typed, and so skipped.
21    pub notes: Vec<Note>,
22    /// JSON paths of fields this model has no place for.
23    pub unmodelled: Vec<String>,
24    raw: Value,
25}
26
27/// One package. Strings the file leaves empty stay empty here: the file
28/// itself writes `""` for "none".
29#[derive(Debug, Clone, Default, PartialEq, Eq)]
30pub struct PkgContext {
31    /// The key of the entry: the name code refers to the package by.
32    pub name: String,
33    /// `packageName`; equal to [`PkgContext::name`] in every file seen.
34    pub package_name: String,
35    /// Owning bundle; empty for packages compiled into this module.
36    pub bundle_name: String,
37    pub module_name: String,
38    /// Empty for the module itself and for native libraries.
39    pub version: String,
40    /// The package's entry file relative to its root (`Index.ets`), or
41    /// for the module's own package its source root (`src/main/`).
42    pub entry_path: String,
43    /// A native library (`libfoo.so`) rather than compiled code.
44    pub is_so: bool,
45    pub dependency_alias: String,
46}
47
48impl PkgContext {
49    /// The record a bare import of this package resolves to:
50    /// `&<name>/<entryPath without extension>&<version>`. `None` for
51    /// native libraries and packages without an entry file.
52    ///
53    /// The record may be absent from the `.abc` when nothing imports the
54    /// package's entry.
55    pub fn entry_record_name(&self) -> Option<String> {
56        if self.is_so || self.entry_path.is_empty() || self.entry_path.ends_with('/') {
57            return None;
58        }
59        Some(format!("&{}/{}&{}", self.name, record::strip_source_extension(&self.entry_path), self.version))
60    }
61}
62
63/// A normalized record name split against the package table.
64#[derive(Debug, Clone, Copy, PartialEq, Eq)]
65pub struct RecordOwner<'c, 'r> {
66    pub package: &'c PkgContext,
67    /// Text before the first `&`; empty for records of this bundle.
68    pub bundle: &'r str,
69    /// Path inside the package, without extension; empty when the record
70    /// is the package name alone.
71    pub path: &'r str,
72    /// Text after the last `&`.
73    pub version: &'r str,
74}
75
76impl PkgContextInfo {
77    /// Read a `pkgContextInfo.json`.
78    ///
79    /// # Errors
80    ///
81    /// Only when `bytes` is not JSON or its root is not an object.
82    pub fn parse(bytes: &[u8]) -> Result<Self, HapError> {
83        let map = value::parse_object(bytes)?;
84        let mut findings = Findings::default();
85        let mut packages = Vec::with_capacity(map.len());
86        for (name, entry) in &map {
87            let Some(entry) = entry.as_object() else {
88                findings.notes.push(Note { path: name.clone(), message: format!("expected object, found {}", value::kind(entry)) });
89                continue;
90            };
91            // Each entry is read as its own root so that note paths start
92            // at the package name.
93            let mut scratch = Findings::default();
94            let mut o = Obj::root(entry, &mut scratch);
95            packages.push(PkgContext {
96                name: name.clone(),
97                package_name: o.str("packageName").unwrap_or_default(),
98                bundle_name: o.str("bundleName").unwrap_or_default(),
99                module_name: o.str("moduleName").unwrap_or_default(),
100                version: o.text("version").unwrap_or_default(),
101                entry_path: o.str("entryPath").unwrap_or_default(),
102                is_so: o.bool("isSO").unwrap_or_default(),
103                dependency_alias: o.str("dependencyAlias").unwrap_or_default(),
104            });
105            o.finish();
106            findings.notes.extend(scratch.notes.into_iter().map(|n| Note { path: format!("{name}.{}", n.path), ..n }));
107            findings.unmodelled.extend(scratch.unmodelled.into_iter().map(|path| format!("{name}.{path}")));
108        }
109        packages.sort_by(|a, b| a.name.cmp(&b.name));
110        Ok(PkgContextInfo { packages, notes: findings.notes, unmodelled: findings.unmodelled, raw: Value::Object(map) })
111    }
112
113    /// Every package, sorted by name.
114    pub fn packages(&self) -> &[PkgContext] {
115        &self.packages
116    }
117
118    /// The package code refers to as `name`.
119    pub fn get(&self, name: &str) -> Option<&PkgContext> {
120        self.packages.binary_search_by(|p| p.name.as_str().cmp(name)).ok().map(|i| &self.packages[i])
121    }
122
123    /// Split a normalized record name (`&@ohos/crypto-js/src/main/js/aes&2.0.0`)
124    /// and find the package it belongs to: the longest package name that
125    /// is a whole-segment prefix of the part between the `&`s. Import
126    /// requests work too once their `@normalized:N&<module>&` head is cut
127    /// off.
128    ///
129    /// `None` for names without two `&` (the `bundle/module/ets/…` form)
130    /// and for packages missing from the table.
131    pub fn locate<'r>(&self, record: &'r str) -> Option<RecordOwner<'_, 'r>> {
132        let (bundle, rest) = record.split_once('&')?;
133        let (body, version) = rest.rsplit_once('&')?;
134        let boundaries = body.match_indices('/').map(|(i, _)| i).chain([body.len()]).collect::<Vec<_>>();
135        boundaries.into_iter().rev().find_map(|end| {
136            let package = self.get(&body[..end])?;
137            Some(RecordOwner { package, bundle, path: body[end..].trim_start_matches('/'), version })
138        })
139    }
140
141    /// The whole document as parsed.
142    pub fn raw(&self) -> &Value {
143        &self.raw
144    }
145
146    /// The document pretty-printed.
147    pub fn pretty(&self) -> String {
148        value::pretty(&self.raw)
149    }
150
151    /// One `package` line per package, sorted by name, then `unmodelled`
152    /// and `note` lines.
153    pub fn summary_lines(&self) -> Vec<String> {
154        let text = |s: &str| if s.is_empty() { "-".to_owned() } else { value::token(s).into_owned() };
155        let mut out: Vec<String> = self
156            .packages
157            .iter()
158            .map(|p| {
159                let mut line = Line::new("package")
160                    .word(&p.name)
161                    .raw("version", text(&p.version))
162                    .raw("entryPath", text(&p.entry_path))
163                    .raw("isSO", p.is_so)
164                    .raw("bundleName", text(&p.bundle_name))
165                    .raw("moduleName", text(&p.module_name))
166                    .raw("dependencyAlias", text(&p.dependency_alias));
167                if p.package_name != p.name {
168                    line = line.raw("packageName", text(&p.package_name));
169                }
170                line.end()
171            })
172            .collect();
173        out.extend(self.unmodelled.iter().map(|path| Line::new("unmodelled").word(path).end()));
174        out.extend(self.notes.iter().map(|note| format!("note {note}")));
175        out
176    }
177
178    /// [`PkgContextInfo::summary_lines`] joined, each line
179    /// newline-terminated.
180    pub fn summary(&self) -> String {
181        crate::join_lines(&self.summary_lines())
182    }
183}