Bind native format inputs after moving a project tree

This commit is contained in:
gloamxun committed 2026-11-28 01:29:28 +08:00
1 parent c2e1e64a60
commit 1ad9c4db82
8 files changed
+509 -23

No files matched your search

@@ -6,6 +6,8 @@ use crate::{
};
pub(super) mod boxes;
mod images;
mod location;
use location::FormatLocation;
pub(super) use images::{FormatImageKind, FormatPdfImage};
use sha2::{Digest, Sha256};
use std::{
@@ -14,9 +16,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 92;
const COMPATIBLE_SCHEMAS: [u32; 58] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 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, 91, SCHEMA,
const SCHEMA: u32 = 93;
const COMPATIBLE_SCHEMAS: [u32; 59] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 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, 91, 92, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -32,6 +34,8 @@ pub struct FormatImage {
resources: Vec<ResourceVersion>,
stream_reads: Vec<ResourceReadRange>,
file_dates: Vec<FormatFileDate>,
#[serde(default, skip_serializing_if = "Option::is_none")]
location: Option<FormatLocation>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pdf_images: Vec<FormatPdfImage>,
#[serde(skip)]
@@ -117,6 +121,7 @@ impl FormatImage {
stream_reads,
file_dates,
pdf_images,
location: None,
input_checks: OnceLock::new(),
})
}
@@ -157,6 +162,9 @@ impl FormatImage {
{
return Err("incompatible native format image".into());
}
if image.location.as_ref().is_some_and(|location| image.schema < 93 || !location.is_valid()) {
return Err("invalid native format project location".into());
}
if image.state.fonts.has_unrecorded_expansion_limits() {
return Err("native format must be rebuilt to restore automatic expansion font identities".into());
}
@@ -551,6 +559,7 @@ mod tests {
from: "stream.tex".into(),
value: Some("observed date".into()),
}],
location: None,
input_checks: OnceLock::new(),
};
let encoded = image.encode().unwrap();
@@ -0,0 +1,192 @@
use super::FormatImage;
use crate::resources::{ResourceKind, ResourceTrace};
use serde::{Deserialize, Serialize};
use std::{
collections::{BTreeMap, BTreeSet},
path::{Component, Path, PathBuf},
sync::Arc,
};
#[derive(Serialize, Deserialize)]
pub(super) struct FormatLocation {
cwd: PathBuf,
format_directory: PathBuf,
inputs: BTreeMap<PathBuf, BTreeSet<PathBuf>>,
}
impl FormatImage {
/// Save the region of the project tree that contains the format and its
/// relative file inputs. An absolute lookup keeps the physical binding.
pub fn with_project_location(mut self, output: &Path, trace: &ResourceTrace) -> Self {
let Some(directory) = output
.parent()
.and_then(|p| p.strip_prefix(&trace.cwd).ok())
else {
return self;
};
let checked = self.build_input_checks();
let eager_images: BTreeSet<_> = self
.pdf_images
.iter()
.filter(|image| image.kind.reads_at_load())
.map(|image| image.path())
.collect();
let mut inputs = BTreeMap::<PathBuf, BTreeSet<PathBuf>>::new();
let mut pinned = BTreeSet::new();
for lookup in &trace.lookups {
let Some(path) = &lookup.resolved else {
continue;
};
if !path.starts_with(&trace.cwd)
|| !(checked.contains_key(path) || eager_images.contains(path.as_path()))
{
continue;
}
match &lookup.lookup_path {
Some(spelling)
if matches!(lookup.kind, ResourceKind::Tex | ResourceKind::PdfImage)
&& relative_tree_path(spelling)
&& !spelling.as_os_str().is_empty() =>
{
inputs
.entry(path.clone())
.or_default()
.insert(spelling.clone());
}
_ => {
pinned.insert(path);
}
}
}
inputs.retain(|path, _| !pinned.contains(path));
if !inputs.is_empty() {
self.location = Some(FormatLocation {
cwd: trace.cwd.clone(),
format_directory: directory.to_owned(),
inputs,
});
}
self
}
/// Resolve a moved tree as a group. A format copied without its relative
/// inputs still uses the original tree. Once any moved input is present,
/// every recorded input and alias in the moved tree must be available.
pub fn input_bindings(
&self,
format: &Path,
mut resolve: impl FnMut(&Path) -> Result<Option<PathBuf>, String>,
) -> Result<BTreeMap<PathBuf, PathBuf>, String> {
let Some(location) = &self.location else {
return Ok(BTreeMap::new());
};
let Some(mut root) = format.parent() else {
return Ok(BTreeMap::new());
};
for component in location.format_directory.components().rev() {
if root.file_name() != Some(component.as_os_str()) {
return Ok(BTreeMap::new());
}
root = root.parent().ok_or("format path has no project root")?;
}
if root == location.cwd {
return Ok(BTreeMap::new());
}
let mut bindings = BTreeMap::new();
let mut missing = None;
for (original, spellings) in &location.inputs {
let mut selected = None;
for spelling in spellings {
let candidate = root.join(spelling);
if let Some(bound) = resolve(&candidate)? {
if selected.as_ref().is_some_and(|prior| prior != &bound) {
return Err(format!(
"native format input aliases diverged: {}",
original.display()
));
}
selected = Some(bound);
} else {
missing.get_or_insert(candidate);
}
}
if let Some(bound) = selected {
bindings.insert(original.clone(), bound);
}
}
if !bindings.is_empty()
&& let Some(path) = missing
{
return Err(format!(
"native format relocated input not found: {}",
path.display()
));
}
Ok(bindings)
}
/// Bind decoded validation and provenance to the paths observed by the
/// loading job. All original byte and stream checks still run.
pub fn bind_inputs(&mut self, bindings: &BTreeMap<PathBuf, PathBuf>) {
if bindings.is_empty() {
return;
}
for (id, source) in self.sources.iter_mut().enumerate() {
if !self.generated_inputs.contains_key(&id)
&& let Some(path) = bindings.get(Path::new(&source.name))
{
source.name = path.to_string_lossy().into_owned();
}
}
for resource in &mut self.resources {
if let Some(path) = bindings.get(&resource.path) {
resource.path.clone_from(path);
}
}
for range in &mut self.stream_reads {
if let Some(path) = bindings.get(&range.path) {
range.path.clone_from(path);
}
}
for date in &mut self.file_dates {
if let Some(path) = bindings.get(Path::new(&date.from)) {
date.from = path.to_string_lossy().into_owned();
}
}
for image in self
.pdf_images
.iter_mut()
.filter(|image| image.kind.reads_at_load())
{
if let Some(path) = bindings.get(image.path()) {
let place = Arc::make_mut(&mut image.image);
Arc::make_mut(&mut place.image)
.version
.path
.clone_from(path);
}
}
self.input_checks.take();
}
}
impl FormatLocation {
pub(super) fn is_valid(&self) -> bool {
self.cwd.is_absolute()
&& relative_tree_path(&self.format_directory)
&& !self.inputs.is_empty()
&& self.inputs.iter().all(|(path, spellings)| {
path.starts_with(&self.cwd)
&& !spellings.is_empty()
&& spellings
.iter()
.all(|name| relative_tree_path(name) && !name.as_os_str().is_empty())
})
}
}
fn relative_tree_path(path: &Path) -> bool {
path.components()
.all(|part| matches!(part, Component::Normal(_) | Component::CurDir))
}