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))
}
+32 -7
View File
@@ -214,6 +214,8 @@ pub struct ResourceLookup {
pub from: PathBuf,
pub candidates: Vec<PathBuf>,
pub resolved: Option<PathBuf>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub lookup_path: Option<PathBuf>,
pub error: Option<String>,
}
/// Bytes delivered by a stream read, rather than a snapshot of the whole file.
@@ -271,6 +273,8 @@ pub struct ResourceTrace {
pub texmf_roots: Vec<PathBuf>,
pub paths: BTreeMap<ResourceKind, Vec<SearchPath>>,
pub lookups: Vec<ResourceLookup>,
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
pub format_input_bindings: BTreeMap<PathBuf, PathBuf>,
/// Versions of bytes actually read, not hashes guessed from input strings.
pub reads: Vec<ResourceVersion>,
pub stream_reads: Vec<ResourceReadRange>,
@@ -531,6 +535,7 @@ impl InputSnapshot {
pub struct FileWorld {
config: WorldConfig,
tex_suffix_fallback: bool,
capture_lookup_paths: bool,
indexes: BTreeMap<PathBuf, Arc<DirectoryIndex>>,
current_project_indexes: BTreeSet<PathBuf>,
index_failures: BTreeMap<PathBuf, DirectoryFailure>,
@@ -670,6 +675,7 @@ impl FileWorld {
Ok(Self {
config,
tex_suffix_fallback: true,
capture_lookup_paths: false,
indexes: BTreeMap::new(),
current_project_indexes: BTreeSet::new(),
index_failures: BTreeMap::new(),
@@ -697,6 +703,11 @@ impl FileWorld {
}
self.pinned = true;
}
/// Record the selected lookup spelling for a persisted format's inputs.
pub fn capture_lookup_paths(&mut self) {
self.capture_lookup_paths = true;
}
pub fn from_project(project: Arc<ProjectSnapshot>) -> Result<Self, String> {
project.validate()?;
let config = project.configuration();
@@ -713,6 +724,7 @@ impl FileWorld {
Ok(Self {
config,
tex_suffix_fallback: true,
capture_lookup_paths: false,
indexes: BTreeMap::new(),
current_project_indexes: BTreeSet::new(),
index_failures: BTreeMap::new(),
@@ -793,6 +805,7 @@ impl FileWorld {
Ok(Self {
config,
tex_suffix_fallback: snapshot.tex_suffix_fallback,
capture_lookup_paths: false,
indexes: snapshot.indexes.clone(),
current_project_indexes: BTreeSet::new(),
index_failures: snapshot.index_failures.clone(),
@@ -1219,6 +1232,10 @@ impl FileWorld {
error
})
}
pub fn record_format_input_bindings(&mut self, bindings: &BTreeMap<PathBuf, PathBuf>) {
self.trace.format_input_bindings.clone_from(bindings);
}
pub fn trace(&self) -> &ResourceTrace {
&self.trace
}
@@ -1463,9 +1480,11 @@ impl FileWorld {
name: &str,
from: &Path,
variants: Vec<PathBuf>,
mut lookup_path: Option<&mut PathBuf>,
lookup_path: Option<&mut PathBuf>,
) -> Result<Option<PathBuf>, String> {
let mut candidates = Vec::new();
let record_spelling = self.capture_lookup_paths || lookup_path.is_some();
let mut spelling = None;
let result = (|| {
let paths = self.paths(kind, from);
let mut found = None;
@@ -1480,8 +1499,8 @@ impl FileWorld {
let path = self.config.cwd.join(variant);
candidates.push(path.clone());
if let Some(path) = self.probe(&path)? {
if let Some(lookup_path) = lookup_path.as_deref_mut() {
lookup_path.clone_from(variant);
if record_spelling {
spelling = Some(variant.clone());
}
found = Some(path);
break;
@@ -1516,8 +1535,8 @@ impl FileWorld {
let direct = root.join(suffix).join(variant);
candidates.push(direct.clone());
if let Some(path) = self.probe(&direct)? {
if let Some(lookup_path) = lookup_path.as_deref_mut() {
*lookup_path = lookup_name(&self.config.cwd, &direct);
if record_spelling {
spelling = Some(lookup_name(&self.config.cwd, &direct));
}
found = Some(path);
break 'paths;
@@ -1573,8 +1592,8 @@ impl FileWorld {
}
candidates.push(candidate.clone());
if let Some(path) = self.probe(&candidate)? {
if let Some(lookup_path) = lookup_path.as_deref_mut() {
*lookup_path = lookup_name(&self.config.cwd, &candidate);
if record_spelling {
spelling = Some(lookup_name(&self.config.cwd, &candidate));
}
found = Some(path);
break 'paths;
@@ -1586,12 +1605,18 @@ impl FileWorld {
}
Ok(found)
})();
if let Some(lookup_path) = lookup_path
&& let Some(selected) = &spelling
{
lookup_path.clone_from(selected);
}
self.trace.lookups.push(ResourceLookup {
kind,
name: name.into(),
from: from.into(),
candidates,
resolved: result.as_ref().ok().cloned().flatten(),
lookup_path: spelling.filter(|_| self.capture_lookup_paths),
error: result.as_ref().err().cloned(),
});
result
@@ -191,6 +191,7 @@ impl FileWorld {
.ok()
.and_then(|result| result.as_ref())
.map(|font| font.resource.version.path.clone()),
lookup_path: None,
error: result.as_ref().err().cloned(),
});
result