Match case-folded TeX dependencies in native resource lookup
This commit is contained in:
1 parent
a1585339b9
commit
9f4cc64c8f
7 files changed
+348
-50
No files matched your search
@@ -12,9 +12,10 @@ pub use project::{ProjectDefinition, ProjectSnapshot, ProjectVersion};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
ffi::{OsStr, OsString},
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
sync::Arc,
|
||||
sync::{Arc, OnceLock},
|
||||
time::SystemTime,
|
||||
};
|
||||
|
||||
@@ -163,6 +164,9 @@ impl SearchPath {
|
||||
pub struct WorldConfig {
|
||||
pub cwd: PathBuf,
|
||||
pub input_policy: InputPolicy,
|
||||
/// Look for a case-insensitive basename after an exact TeX path search.
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub casefold_search: bool,
|
||||
pub texmf_roots: Vec<PathBuf>,
|
||||
pub paths: BTreeMap<ResourceKind, Vec<SearchPath>>,
|
||||
pub max_index_entries: usize,
|
||||
@@ -180,6 +184,7 @@ impl WorldConfig {
|
||||
Self {
|
||||
cwd: cwd.into(),
|
||||
input_policy: InputPolicy::Tex,
|
||||
casefold_search: cfg!(unix),
|
||||
texmf_roots: Vec::new(),
|
||||
paths: BTreeMap::new(),
|
||||
max_index_entries: 1_000_000,
|
||||
@@ -196,6 +201,10 @@ impl WorldConfig {
|
||||
}
|
||||
let mut config = Self::new(cwd);
|
||||
config.texmf_roots = roots;
|
||||
if let Some(value) = std::env::var_os("texmf_casefold_search") {
|
||||
config.casefold_search = cfg!(unix)
|
||||
&& !matches!(value.as_encoded_bytes().first(), Some(b'0' | b'f'));
|
||||
}
|
||||
for kind in ResourceKind::ALL {
|
||||
match std::env::var(kind.environment()) {
|
||||
Ok(value) => {
|
||||
@@ -281,6 +290,8 @@ pub struct ResourceTrace {
|
||||
pub schema: u32,
|
||||
pub cwd: PathBuf,
|
||||
pub input_policy: InputPolicy,
|
||||
#[serde(default, skip_serializing_if = "std::ops::Not::not")]
|
||||
pub casefold_search: bool,
|
||||
pub texmf_roots: Vec<PathBuf>,
|
||||
pub paths: BTreeMap<ResourceKind, Vec<SearchPath>>,
|
||||
pub lookups: Vec<ResourceLookup>,
|
||||
@@ -328,8 +339,51 @@ struct DirectoryIndex {
|
||||
#[serde(default)]
|
||||
directory_aliases: BTreeMap<PathBuf, PathBuf>,
|
||||
#[serde(with = "index_names")]
|
||||
names: BTreeMap<std::ffi::OsString, Vec<PathBuf>>,
|
||||
names: BTreeMap<OsString, Vec<PathBuf>>,
|
||||
// A filesystem decides the order between multiple folded matches in one
|
||||
// directory. Only such ties need an additional snapshot observation.
|
||||
#[serde(default, skip_serializing_if = "BTreeMap::is_empty")]
|
||||
casefold_ties: BTreeMap<PathBuf, Vec<OsString>>,
|
||||
#[serde(skip)]
|
||||
folded_names: OnceLock<BTreeMap<Vec<u8>, Vec<OsString>>>,
|
||||
}
|
||||
|
||||
impl DirectoryIndex {
|
||||
fn matching_paths(&self, name: &OsStr, casefold: bool) -> Vec<PathBuf> {
|
||||
if !casefold {
|
||||
return self.names.get(name).cloned().unwrap_or_default();
|
||||
}
|
||||
let names = self.folded_names.get_or_init(|| {
|
||||
let mut index = BTreeMap::<Vec<u8>, Vec<OsString>>::new();
|
||||
for name in self.names.keys() {
|
||||
index.entry(folded_basename(name)).or_default().push(name.clone());
|
||||
}
|
||||
index
|
||||
});
|
||||
names.get(&folded_basename(name)).into_iter().flatten()
|
||||
.filter(|spelling| spelling.as_os_str() != name)
|
||||
.flat_map(|spelling| self.names[spelling].iter().cloned())
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn order_folded_paths(&self, paths: &mut [PathBuf]) {
|
||||
paths.sort_by(|a, b| {
|
||||
a.parent().cmp(&b.parent()).then_with(|| {
|
||||
let ties = a.parent().and_then(|parent| self.casefold_ties.get(parent));
|
||||
let rank = |path: &Path| {
|
||||
ties.and_then(|names| names.iter().position(|name| Some(name.as_os_str()) == path.file_name()))
|
||||
.unwrap_or(usize::MAX)
|
||||
};
|
||||
rank(a).cmp(&rank(b)).then_with(|| a.cmp(b))
|
||||
})
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn folded_basename(name: &OsStr) -> Vec<u8> {
|
||||
name.as_encoded_bytes().to_ascii_lowercase()
|
||||
}
|
||||
|
||||
fn recursive_index() -> bool {
|
||||
true
|
||||
}
|
||||
@@ -699,6 +753,7 @@ impl FileWorld {
|
||||
schema: 1,
|
||||
cwd: config.cwd.clone(),
|
||||
input_policy: config.input_policy,
|
||||
casefold_search: config.casefold_search,
|
||||
texmf_roots: config.texmf_roots.clone(),
|
||||
paths: config.paths.clone(),
|
||||
configuration_observations: observations,
|
||||
@@ -748,6 +803,7 @@ impl FileWorld {
|
||||
schema: 1,
|
||||
cwd: config.cwd.clone(),
|
||||
input_policy: config.input_policy,
|
||||
casefold_search: config.casefold_search,
|
||||
texmf_roots: config.texmf_roots.clone(),
|
||||
paths: config.paths.clone(),
|
||||
project_version: Some(project.version().clone()),
|
||||
@@ -831,6 +887,7 @@ impl FileWorld {
|
||||
schema: 1,
|
||||
cwd: config.cwd.clone(),
|
||||
input_policy: config.input_policy,
|
||||
casefold_search: config.casefold_search,
|
||||
texmf_roots: config.texmf_roots.clone(),
|
||||
paths: config.paths.clone(),
|
||||
project_version: snapshot.project.as_ref().map(|p| p.version().clone()),
|
||||
@@ -929,7 +986,9 @@ impl FileWorld {
|
||||
if self.pinned {
|
||||
if was_live || self.project.is_some() {
|
||||
let newly_protected = self.protected_paths.insert(resource.version.path.clone());
|
||||
if self.project.is_some() && (was_live || newly_protected) {
|
||||
if self.project.as_ref().is_some_and(|project| {
|
||||
was_live || (newly_protected && project.file(&resource.version.path).is_none())
|
||||
}) {
|
||||
self.current_project_indexes.clear();
|
||||
}
|
||||
}
|
||||
@@ -1431,6 +1490,8 @@ impl FileWorld {
|
||||
directories: Vec::new(),
|
||||
directory_aliases: BTreeMap::new(),
|
||||
names: BTreeMap::new(),
|
||||
casefold_ties: BTreeMap::new(),
|
||||
folded_names: OnceLock::new(),
|
||||
};
|
||||
let built = (|| -> Result<(), String> {
|
||||
let mut queue = vec![(root.to_owned(), Vec::<PathBuf>::new())];
|
||||
@@ -1463,6 +1524,18 @@ impl FileWorld {
|
||||
.map_err(|e| format!("resource directory {}: {e}", dir.display()))?
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.map_err(|e| e.to_string())?;
|
||||
if self.config.casefold_search && self.config.input_policy == InputPolicy::Tex {
|
||||
let mut buckets = BTreeMap::<Vec<u8>, Vec<OsString>>::new();
|
||||
for child in &children {
|
||||
let name = child.file_name();
|
||||
buckets.entry(folded_basename(&name)).or_default().push(name);
|
||||
}
|
||||
let ties: Vec<_> = buckets.into_values()
|
||||
.filter(|names| names.len() > 1).flatten().collect();
|
||||
if !ties.is_empty() {
|
||||
index.casefold_ties.insert(dir.clone(), ties);
|
||||
}
|
||||
}
|
||||
children.sort_by_key(|e| e.file_name());
|
||||
for child in children {
|
||||
count += 1;
|
||||
@@ -1510,6 +1583,69 @@ impl FileWorld {
|
||||
}
|
||||
Ok(&self.indexes[root])
|
||||
}
|
||||
fn indexed_paths(
|
||||
&mut self,
|
||||
root: &Path,
|
||||
tail: &Path,
|
||||
recursive: bool,
|
||||
casefold: bool,
|
||||
) -> Result<Vec<PathBuf>, String> {
|
||||
let Some(name) = tail.file_name() else { return Ok(Vec::new()) };
|
||||
let parent = tail.parent().unwrap_or(Path::new(""));
|
||||
let matches_tail = |candidate: &Path| {
|
||||
if !casefold {
|
||||
return candidate.ends_with(tail);
|
||||
}
|
||||
candidate.parent().is_some_and(|path| {
|
||||
if recursive { path.ends_with(parent) } else { path == root }
|
||||
}) && candidate.file_name().is_some_and(|spelling| {
|
||||
spelling != name && spelling.as_encoded_bytes().eq_ignore_ascii_case(name.as_encoded_bytes())
|
||||
})
|
||||
};
|
||||
self.index_at(root, recursive)?;
|
||||
let index = self.indexes[root].clone();
|
||||
let mut matches = index.matching_paths(name, casefold);
|
||||
matches.retain(|path| matches_tail(path));
|
||||
for live in self.live_paths.union(&self.protected_paths) {
|
||||
if live.starts_with(root) && matches_tail(live) {
|
||||
matches.push(live.clone());
|
||||
}
|
||||
for (logical, canonical) in &index.directory_aliases {
|
||||
if let Ok(relative) = live.strip_prefix(canonical) {
|
||||
let candidate = logical.join(relative);
|
||||
if matches_tail(&candidate)
|
||||
&& self.directory_binding(&candidate).is_some_and(|(bound, _)| bound == *live)
|
||||
{
|
||||
matches.push(candidate);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if casefold {
|
||||
index.order_folded_paths(&mut matches);
|
||||
} else {
|
||||
matches.sort();
|
||||
}
|
||||
matches.dedup();
|
||||
Ok(matches)
|
||||
}
|
||||
|
||||
fn probe_casefolded(
|
||||
&mut self,
|
||||
root: &Path,
|
||||
tail: &Path,
|
||||
recursive: bool,
|
||||
candidates: &mut Vec<PathBuf>,
|
||||
) -> Result<Option<(PathBuf, PathBuf)>, String> {
|
||||
for candidate in self.indexed_paths(root, tail, recursive, true)? {
|
||||
candidates.push(candidate.clone());
|
||||
if let Some(path) = self.probe(&candidate)? {
|
||||
return Ok(Some((path, candidate)));
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub fn resolve(
|
||||
&mut self,
|
||||
kind: ResourceKind,
|
||||
@@ -1541,6 +1677,8 @@ impl FileWorld {
|
||||
let result = (|| {
|
||||
let paths = self.paths(kind, from);
|
||||
let mut found = None;
|
||||
let casefold = self.config.casefold_search && self.config.input_policy == InputPolicy::Tex
|
||||
&& !deferred::directory_only(Path::new(name));
|
||||
let requested = Path::new(name);
|
||||
if requested.is_absolute()
|
||||
|| matches!(
|
||||
@@ -1559,6 +1697,19 @@ impl FileWorld {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if found.is_none() && casefold {
|
||||
for variant in &variants {
|
||||
let direct = self.config.cwd.join(variant);
|
||||
let (Some(parent), Some(basename)) = (direct.parent(), direct.file_name()) else { continue };
|
||||
if let Some((path, selected)) = self.probe_casefolded(parent, Path::new(basename), false, &mut candidates)? {
|
||||
if record_spelling {
|
||||
spelling = Some(variant.with_file_name(selected.file_name().unwrap()));
|
||||
}
|
||||
found = Some(path);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// TeX honors search-path priority before the suffix alternatives.
|
||||
// A recursive path is one entry: search all of it for .tex before
|
||||
@@ -1596,53 +1747,7 @@ impl FileWorld {
|
||||
}
|
||||
if *recursive {
|
||||
let tail = suffix.join(variant);
|
||||
let roles: Vec<_> = self
|
||||
.live_paths
|
||||
.union(&self.protected_paths)
|
||||
.cloned()
|
||||
.collect();
|
||||
let (mut matches, projected) = {
|
||||
let index = self.index(&root)?;
|
||||
let matches = index
|
||||
.names
|
||||
.get(variant.file_name().ok_or("resource needs a filename")?)
|
||||
.cloned()
|
||||
.unwrap_or_default();
|
||||
let mut projected = Vec::new();
|
||||
for live in &roles {
|
||||
for (logical, canonical) in &index.directory_aliases {
|
||||
if let Ok(relative) = live.strip_prefix(canonical) {
|
||||
let candidate = logical.join(relative);
|
||||
if candidate.ends_with(&tail) {
|
||||
projected.push((candidate, live.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
(matches, projected)
|
||||
};
|
||||
for live in &roles {
|
||||
if live.starts_with(&root)
|
||||
&& live.ends_with(&tail)
|
||||
&& !matches.contains(live)
|
||||
{
|
||||
matches.push(live.clone());
|
||||
}
|
||||
}
|
||||
for (candidate, target) in projected {
|
||||
if self
|
||||
.directory_binding(&candidate)
|
||||
.is_some_and(|(bound, _)| bound == target)
|
||||
&& !matches.contains(&candidate)
|
||||
{
|
||||
matches.push(candidate);
|
||||
}
|
||||
}
|
||||
matches.sort();
|
||||
for candidate in matches {
|
||||
if !candidate.ends_with(&tail) {
|
||||
continue;
|
||||
}
|
||||
for candidate in self.indexed_paths(&root, &tail, true, false)? {
|
||||
candidates.push(candidate.clone());
|
||||
if let Some(path) = self.probe(&candidate)? {
|
||||
if record_spelling {
|
||||
@@ -1654,6 +1759,25 @@ impl FileWorld {
|
||||
}
|
||||
}
|
||||
}
|
||||
if casefold {
|
||||
for variant in &variants {
|
||||
let tail = suffix.join(variant);
|
||||
let direct = root.join(&tail);
|
||||
let (Some(parent), Some(basename)) = (direct.parent(), direct.file_name()) else { continue };
|
||||
let selected = if *recursive {
|
||||
self.probe_casefolded(&root, &tail, true, &mut candidates)?
|
||||
} else {
|
||||
self.probe_casefolded(parent, Path::new(basename), false, &mut candidates)?
|
||||
};
|
||||
if let Some((path, candidate)) = selected {
|
||||
if record_spelling {
|
||||
spelling = Some(lookup_name(&self.config.cwd, &candidate));
|
||||
}
|
||||
found = Some(path);
|
||||
break 'paths;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(found)
|
||||
|
||||
@@ -482,6 +482,8 @@ impl ProjectSnapshot {
|
||||
directories: Vec::new(),
|
||||
directory_aliases: BTreeMap::new(),
|
||||
names: BTreeMap::new(),
|
||||
casefold_ties: BTreeMap::new(),
|
||||
folded_names: Default::default(),
|
||||
};
|
||||
let mut pending = vec![(root.to_path_buf(), Vec::<PathBuf>::new())];
|
||||
let mut count = 0;
|
||||
|
||||
@@ -34,6 +34,30 @@ fn file(d: &mut ProjectDefinition, path: PathBuf, data: &[u8]) {
|
||||
d.files.insert(path, Arc::from(data));
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn casefolded_project_lookups_use_the_current_immutable_namespace() {
|
||||
let root = directory().canonicalize().unwrap();
|
||||
let requested = "chapter.tex";
|
||||
let upper = root.join("CHAPTER.TEX");
|
||||
let exact = root.join(requested);
|
||||
let entry = root.join("main.tex");
|
||||
let mut seed = definition(&root);
|
||||
file(&mut seed, upper.clone(), b"initial buffer");
|
||||
let snapshot = ProjectSnapshot::new(seed).unwrap();
|
||||
let mut first = FileWorld::from_project(snapshot.clone()).unwrap();
|
||||
assert!(!upper.exists());
|
||||
assert_eq!(first.read_tex_input(requested, &entry).unwrap().version.path, upper);
|
||||
|
||||
let edited = snapshot.with_file_changes(
|
||||
2, [(exact.clone(), Some(Arc::from(b"exact buffer".as_slice())))].into()
|
||||
).unwrap();
|
||||
let mut next = FileWorld::from_project(edited).unwrap();
|
||||
assert_eq!(next.read_tex_input(requested, &entry).unwrap().version.path, exact);
|
||||
assert_eq!(first.read_tex_input(requested, &entry).unwrap().version.path, upper);
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn immutable_buffer_edits_match_a_rebuilt_project_and_revalidate_imports() {
|
||||
let p = directory();
|
||||
|
||||
@@ -20,6 +20,64 @@ fn put(path: impl AsRef<Path>, data: impl AsRef<[u8]>) {
|
||||
fs::write(p, data).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn tex_casefold_uses_actual_basename_after_exact_search_and_replays_it() {
|
||||
let root = directory().canonicalize().unwrap();
|
||||
let first = root.join("first");
|
||||
let second = root.join("second");
|
||||
let recursive = root.join("tree");
|
||||
let folded = first.join("SLICE.TEX");
|
||||
let exact_later = second.join("slice.tex");
|
||||
put(&folded, b"early folded");
|
||||
put(&exact_later, b"later exact");
|
||||
put(first.join("PREFERENCE.TeX"), b"folded suffix");
|
||||
put(first.join("preference"), b"exact bare");
|
||||
put(root.join("HEADER.STY"), b"explicit path");
|
||||
put(recursive.join("nest/Sub/RECURSE.TEX"), b"nested name");
|
||||
put(first.join("TIES.TEX"), b"tie A");
|
||||
put(first.join("TiEs.TeX"), b"tie B");
|
||||
|
||||
let dir_order = fs::read_dir(&first).unwrap().map(Result::unwrap)
|
||||
.find(|entry| entry.file_name().as_encoded_bytes().eq_ignore_ascii_case(b"ties.tex"))
|
||||
.unwrap().path();
|
||||
let mut config = WorldConfig::new(&root);
|
||||
config.paths.insert(ResourceKind::Tex, vec![
|
||||
SearchPath::directory(&first, false),
|
||||
SearchPath::directory(&second, false),
|
||||
SearchPath::directory(&recursive, true),
|
||||
]);
|
||||
let entry = root.join("main.tex");
|
||||
let mut world = FileWorld::new(config.clone()).unwrap();
|
||||
world.capture_inputs();
|
||||
world.capture_lookup_paths();
|
||||
for (requested, expected) in [
|
||||
("slice.tex", folded.clone()),
|
||||
("preference", first.join("preference")),
|
||||
("./header.sty", root.join("HEADER.STY")),
|
||||
("Sub/recurse.tex", recursive.join("nest/Sub/RECURSE.TEX")),
|
||||
("ties.tex", dir_order.clone()),
|
||||
] {
|
||||
let got = world.read_tex_input(requested, &entry).unwrap();
|
||||
assert_eq!(got.version.path, expected, "request {requested}");
|
||||
}
|
||||
assert!(world.resolve_tex_input("sub/recurse.tex", &entry).unwrap().is_none());
|
||||
assert_eq!(world.trace().lookups[2].lookup_path.as_deref(), Some(Path::new("./HEADER.STY")));
|
||||
|
||||
let snapshot = serde_json::to_vec(world.input_snapshot().as_ref()).unwrap();
|
||||
fs::remove_file(&folded).unwrap();
|
||||
fs::remove_file(&dir_order).unwrap();
|
||||
let mut replay = FileWorld::from_snapshot(serde_json::from_slice(&snapshot).unwrap()).unwrap();
|
||||
assert_eq!(replay.read_tex_input("slice.tex", &entry).unwrap().data, b"early folded");
|
||||
assert_eq!(replay.read_tex_input("ties.tex", &entry).unwrap().version.path, dir_order);
|
||||
|
||||
put(&folded, b"restored physical file");
|
||||
config.casefold_search = false;
|
||||
let mut strict = FileWorld::new(config).unwrap();
|
||||
assert_eq!(strict.read_tex_input("slice.tex", &entry).unwrap().version.path, exact_later);
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn file_modification_capture_replays_original_observation_after_file_edits() {
|
||||
use std::time::{Duration, SystemTime};
|
||||
|
||||
Reference in new issue
Block a user