//! Native filesystem resource lookup. No external TeX/kpathsea subprocess. mod deferred; mod named_fonts; pub use named_fonts::{FontStyle, NamedFont}; pub(crate) use named_fonts::{PdfSfntKind, cff_program, exact_pdf_sfnt_name}; mod project; pub use deferred::{ DeferredProbe, DirectoryAbsence, GeneratedLookup, GeneratedLookupOrigin, GeneratedLookupRole, NamespaceCaptureFailure, NamespaceKind, NamespaceMetadata, NamespaceObservation, }; pub use project::{ProjectDefinition, ProjectSnapshot, ProjectVersion}; use sha2::{Digest, Sha256}; use std::{ collections::{BTreeMap, BTreeSet}, fs, path::{Path, PathBuf}, sync::Arc, time::SystemTime, }; #[derive( Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, serde::Serialize, serde::Deserialize, )] pub enum ResourceKind { Tex, Tfm, Vf, Type1, OpenType, TrueType, Pk, Encoding, Map, Format, Config, FontMapping, PdfImage, Sfd, } impl ResourceKind { fn directory(self) -> &'static str { match self { Self::Tex | Self::PdfImage => "tex", Self::Tfm => "fonts/tfm", Self::Vf => "fonts/vf", Self::Type1 => "fonts/type1", Self::OpenType => "fonts/opentype", Self::TrueType => "fonts/truetype", Self::Pk => "fonts/pk", Self::Encoding => "fonts/enc", Self::Map => "fonts/map", Self::Format | Self::Config => "web2c", Self::FontMapping => "fonts/misc", Self::Sfd => "fonts/sfd", } } fn environment(self) -> &'static str { match self { Self::Tex | Self::PdfImage => "TEXINPUTS", Self::Tfm => "TFMFONTS", Self::Vf => "VFFONTS", Self::Type1 => "T1FONTS", Self::OpenType => "OPENTYPEFONTS", Self::TrueType => "TTFONTS", Self::Pk => "PKFONTS", Self::Encoding => "ENCFONTS", Self::Map => "TEXFONTMAPS", Self::Format => "TEXFORMATS", Self::Config => "TEXMFCNF", Self::FontMapping => "MISCFONTS", Self::Sfd => "SFDFONTS", } } fn extensions(self) -> &'static [&'static str] { match self { Self::Tex | Self::PdfImage => &["tex"], Self::Tfm => &["tfm"], Self::Vf => &["vf"], Self::Type1 => &["pfb", "pfa"], Self::OpenType => &["otf", "otc"], Self::TrueType => &["ttf", "ttc"], Self::Pk => &["pk"], Self::Encoding => &["enc"], Self::Map => &["map"], Self::Format => &["fmt"], Self::Config => &["cnf"], Self::FontMapping => &["tec"], Self::Sfd => &["sfd"], } } const ALL: [Self; 13] = [ Self::Tex, Self::Tfm, Self::Vf, Self::Type1, Self::OpenType, Self::TrueType, Self::Pk, Self::Encoding, Self::Map, Self::Format, Self::Config, Self::FontMapping, Self::Sfd, ]; } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum SearchPath { Defaults, Directory { path: PathBuf, recursive: bool, suffix: PathBuf, }, } impl SearchPath { pub fn directory(path: impl Into, recursive: bool) -> Self { Self::Directory { path: path.into(), recursive, suffix: PathBuf::new(), } } pub fn parse_list(value: &str) -> Result, String> { let mut result = Vec::new(); for field in std::env::split_paths(value) { let s = field .to_str() .ok_or("resource search paths must be UTF-8")?; if s.is_empty() { result.push(Self::Defaults); continue; } if s.contains(['{', '}', '$', '~']) || s.starts_with("!!") { return Err(format!( "resource search path needs explicit expanded directories: {s}" )); } if let Some((prefix, suffix)) = s.split_once("//") { if suffix.contains("//") { return Err(format!( "multiple recursive components are not implemented in resource path: {s}" )); } result.push(Self::Directory { path: PathBuf::from(if prefix.is_empty() { "/" } else { prefix }), recursive: true, suffix: PathBuf::from(suffix), }); } else { result.push(Self::directory(field, false)); } } Ok(result) } } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct WorldConfig { pub cwd: PathBuf, pub input_policy: InputPolicy, pub texmf_roots: Vec, pub paths: BTreeMap>, pub max_index_entries: usize, /// Explicit host PDF-device policy when the TeX parameter is zero. pub default_pk_resolution: i32, } #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum InputPolicy { #[default] Tex, Project, } impl WorldConfig { pub fn new(cwd: impl Into) -> Self { Self { cwd: cwd.into(), input_policy: InputPolicy::Tex, texmf_roots: Vec::new(), paths: BTreeMap::new(), max_index_entries: 1_000_000, default_pk_resolution: 72, } } /// Host policy is explicit. No installed distribution is silently selected. pub fn from_environment( cwd: impl Into, mut roots: Vec, ) -> Result { if let Some(value) = std::env::var_os("TEXRRA_TEXMF") { roots.extend(std::env::split_paths(&value).filter(|p| !p.as_os_str().is_empty())); } let mut config = Self::new(cwd); config.texmf_roots = roots; for kind in ResourceKind::ALL { match std::env::var(kind.environment()) { Ok(value) => { config.paths.insert(kind, SearchPath::parse_list(&value)?); } Err(std::env::VarError::NotPresent) => {} Err(e) => return Err(format!("resource {}: {e}", kind.environment())), } } Ok(config) } } #[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] pub struct ResourceVersion { pub path: PathBuf, pub sha256: String, pub bytes: u64, } pub struct LoadedResource { pub version: ResourceVersion, pub data: Vec, } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct ResourceLookup { pub kind: ResourceKind, pub name: String, pub from: PathBuf, pub candidates: Vec, pub resolved: Option, #[serde(default, skip_serializing_if = "Option::is_none")] pub lookup_path: Option, pub error: Option, } /// Bytes delivered by a stream read, rather than a snapshot of the whole file. #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct ResourceReadRange { pub path: PathBuf, pub offset: u64, pub bytes: u64, pub sha256: String, pub eof: bool, } /// A metadata version, independent of the resource's byte version. #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct FileModificationTime { pub unix_seconds: i64, pub nanoseconds: u32, } impl FileModificationTime { fn from_system_time(time: SystemTime) -> Result { let nanos = match time.duration_since(SystemTime::UNIX_EPOCH) { Ok(duration) => duration.as_nanos() as i128, Err(error) => -(error.duration().as_nanos() as i128), }; let seconds = nanos.div_euclid(1_000_000_000); Ok(Self { unix_seconds: i64::try_from(seconds) .map_err(|_| "file modification time out of range")?, nanoseconds: nanos.rem_euclid(1_000_000_000) as u32, }) } fn valid(self) -> bool { self.nanoseconds < 1_000_000_000 } } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct FileModificationObservation { pub path: PathBuf, pub result: Result, String>, } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct FileModificationDate { pub time: FileModificationTime, pub text: String, } #[derive(Clone, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub struct ResourceTrace { pub schema: u32, pub cwd: PathBuf, pub input_policy: InputPolicy, pub texmf_roots: Vec, pub paths: BTreeMap>, pub lookups: Vec, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] pub format_input_bindings: BTreeMap, /// Versions of bytes actually read, not hashes guessed from input strings. pub reads: Vec, pub stream_reads: Vec, #[serde(default, skip_serializing_if = "Vec::is_empty")] pub file_modifications: Vec, pub read_errors: Vec<(PathBuf, String)>, #[serde(default)] pub configuration_observations: Vec, #[serde(default)] pub project_version: Option, #[serde(default)] pub generated_lookups: Vec, #[serde(default)] pub namespace_capture_failures: Vec, #[serde(default)] pub directory_absences: Vec, } #[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)] pub enum WorldObservation { Canonicalize { path: PathBuf, result: Result, }, Directory { path: PathBuf, result: Result, }, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct WorldFailure { pub error: String, pub configuration: WorldConfig, pub observations: Vec, } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] struct DirectoryIndex { #[serde(default = "recursive_index", skip_serializing_if = "recursive_index_value")] recursive: bool, directories: Vec<(PathBuf, SystemTime)>, #[serde(default)] directory_aliases: BTreeMap, #[serde(with = "index_names")] names: BTreeMap>, } fn recursive_index() -> bool { true } fn recursive_index_value(recursive: &bool) -> bool { *recursive } // OsString has a platform-tagged serde representation, so it cannot be a JSON // object key. Preserve exact filename values as entries rather than lossy text. mod index_names { use super::*; use serde::{Deserialize, Serialize}; pub fn serialize( names: &BTreeMap>, serializer: S, ) -> Result { names.iter().collect::>().serialize(serializer) } pub fn deserialize<'de, D: serde::Deserializer<'de>>( deserializer: D, ) -> Result>, D::Error> { let entries = Vec::<(std::ffi::OsString, Vec)>::deserialize(deserializer)?; let mut names = BTreeMap::new(); for (name, paths) in entries { if names.insert(name, paths).is_some() { return Err(serde::de::Error::custom( "duplicate snapshot index filename", )); } } Ok(names) } } /// An immutable set of observed external inputs and lookup decisions. Initial /// acquisition is lazy, not a claim of an atomic filesystem-wide instant. /// Replay never reads an unrecorded external dependency from the filesystem. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct InputSnapshot { schema: u32, config: WorldConfig, files: BTreeMap>, #[serde(default, skip_serializing_if = "BTreeMap::is_empty")] file_modifications: BTreeMap>, probes: BTreeMap, String>>, #[serde(default)] deferred_probes: BTreeMap, indexes: BTreeMap>, #[serde(default)] index_failures: BTreeMap, lookups: Vec, replay_gaps: Vec, #[serde(default)] project: Option>, // Older captures only probed the supplied name when it had a suffix. #[serde(default)] tex_suffix_fallback: bool, #[serde(default, skip_serializing_if = "Option::is_none")] system_fonts: Option, String>>, #[serde(default, skip_serializing_if = "Option::is_none")] named_font_directories: Option>, } /// A failed enumeration is not a complete namespace. Retain the usable prefix /// only as evidence and replay its actual error, never as a successful index. #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct DirectoryFailure { pub error: String, partial: Arc, } impl DirectoryFailure { pub fn observed_files(&self) -> impl Iterator { self.partial.names.values().flatten().map(PathBuf::as_path) } pub fn visited_directories(&self) -> &[(PathBuf, SystemTime)] { &self.partial.directories } } #[derive(Clone, Debug, serde::Serialize, serde::Deserialize)] pub struct SnapshotFile { pub version: ResourceVersion, pub data: Arc<[u8]>, } impl SnapshotFile { fn into_loaded(self) -> LoadedResource { LoadedResource { version: self.version, data: self.data.to_vec(), } } } impl InputSnapshot { pub fn project(&self) -> Option<&Arc> { self.project.as_ref() } pub fn configuration(&self) -> WorldConfig { self.config.clone() } pub fn lookups(&self) -> &[ResourceLookup] { &self.lookups } pub fn deferred_probes(&self) -> &BTreeMap { &self.deferred_probes } pub fn replay_gaps(&self) -> &[String] { &self.replay_gaps } pub fn failed_directories(&self) -> impl Iterator { self.index_failures.iter().map(|(p, f)| (p.as_path(), f)) } pub fn files(&self) -> impl Iterator)> { self.files .iter() .map(|(p, v)| (p.as_path(), v.as_ref().map_err(String::as_str))) .chain( self.project .iter() .flat_map(|p| p.files()) .filter(|(p, _)| !self.files.contains_key(*p)) .map(|(p, f)| (p, Ok(f))), ) } pub fn file(&self, path: &Path) -> Option<&SnapshotFile> { match self.files.get(path) { Some(value) => value.as_ref().ok(), None => self.project.as_ref().and_then(|p| p.file(path)), } } pub fn validate(&self) -> Result<(), String> { if self.schema != 1 || !self.config.cwd.is_absolute() { return Err("incompatible native input snapshot".into()); } if self.project.is_some() && self.system_fonts.is_some() { return Err("atomic project cannot import a live system font catalogue".into()); } if let Some(Ok(faces)) = &self.system_fonts && (faces.len() > self.config.max_index_entries || faces.iter().any(|face| !face.valid_capture())) { return Err("invalid captured font catalogue".into()); } if let Some(directories) = &self.named_font_directories && (self.project.is_some() && !directories.is_empty() || directories.iter().enumerate().any(|(i, directory)| { !directory.valid_capture(self.config.max_index_entries) || directories[..i].iter().any(|prior| prior.scope == directory.scope) })) { return Err("invalid captured named font directory".into()); } if let Some(project) = &self.project { project.validate()?; if project.configuration() != self.config { return Err("atomic project and captured configuration differ".into()); } if !self.deferred_probes.is_empty() { return Err("atomic project cannot import physical deferred probes".into()); } } for (candidate, value) in &self.probes { if !candidate.is_absolute() || matches!(value,Ok(Some(target)) if !deferred::canonical_path(target)) { return Err( "captured probe paths must be absolute with canonical destinations".into(), ); } } let mut observations = 0usize; for (path, probe) in &self.deferred_probes { if !path.is_absolute() || self.probes.get(path) != Some(&Ok(None)) { return Err( "deferred namespace probe must describe a captured missing candidate".into(), ); } probe.validate()?; observations = observations.saturating_add(probe.observations.len().max(1)); if observations > deferred::MAX_OBSERVATIONS { return Err("deferred namespace observation capacity exceeded".into()); } } for index in self .indexes .values() .chain(self.index_failures.values().map(|f| &f.partial)) { if index.directory_aliases.len() > deferred::MAX_OBSERVATIONS || index.directory_aliases.iter().any(|(logical, canonical)| { !logical.is_absolute() || !deferred::canonical_path(canonical) || !index.directories.iter().any(|(p, _)| p == canonical) }) { return Err("invalid captured directory namespace".into()); } } for (path, value) in &self.files { if !path.is_absolute() { return Err("snapshot input path must be absolute".into()); } if let Some(project) = &self.project { project.validate_captured_file(path, value)?; } if let Ok(file) = value { if &file.version.path != path || file.version.bytes != file.data.len() as u64 || file.version.sha256 != format!("{:x}", Sha256::digest(&file.data)) { return Err(format!( "native input snapshot content mismatch: {}", path.display() )); } } } for (path, modified) in &self.file_modifications { if !deferred::canonical_path(path) || modified.as_ref().is_some_and(|date| !date.time.valid()) { return Err("invalid captured file modification time".into()); } if let Some(project) = &self.project { if !modified .as_ref() .is_some_and(|date| project.modification_time(path) == Some(date.time)) { return Err( "captured file modification time conflicts with atomic project".into(), ); } } } Ok(()) } } pub struct FileWorld { config: WorldConfig, tex_suffix_fallback: bool, capture_lookup_paths: bool, indexes: BTreeMap>, current_project_indexes: BTreeSet, index_failures: BTreeMap, trace: ResourceTrace, pinned: bool, replay: bool, input_files: BTreeMap>, file_modifications: BTreeMap>, input_probes: BTreeMap, String>>, deferred_probes: BTreeMap, namespace_observations: usize, live_paths: BTreeSet, staged_generated: BTreeMap, /// Actual host resource promotions, never inferred from serialized cache. protected_paths: BTreeSet, replay_gaps: Vec, project: Option>, system_fonts: Option, String>>, project_named_fonts: Option>, named_font_directories: Option>, } impl FileWorld { pub fn default_pk_resolution(&self) -> i32 { self.config.default_pk_resolution } /// Standard density-bearing filenames plus a directly configured PK file. /// Lookup never runs mktexpk, selects another font, or guesses a density. pub fn read_pk(&mut self, name: &str, dpi: u32, from: &Path) -> Result { if dpi == 0 || dpi > 1_000_000 { return Err("native PK density request exceeds capacity".into()); } let stem = Path::new(name); let base = stem .file_name() .ok_or("PK font requires a filename")? .to_string_lossy(); let parent = stem.parent().unwrap_or(Path::new("")); let tolerance = dpi / 500 + 1; let densities = std::iter::once(dpi).chain( (dpi.saturating_sub(tolerance)..=dpi.saturating_add(tolerance)).filter(|v| *v != dpi), ); for density in densities { let variants = vec![ parent.join(format!("dpi{density}/{base}.pk")), parent.join(format!("{base}.{density}pk")), ]; if let Some(path) = self.resolve_variants( ResourceKind::Pk, &format!("{name}@{density}dpi"), from, variants, None, )? { return self.read_path(path); } } // A bare file may be explicitly supplied by a directory path. Never // recursively pick an arbitrary dpiNNN/name.pk from another density. for (entry, _) in self.paths(ResourceKind::Pk, from) { if let SearchPath::Directory { path, suffix, .. } = entry { let candidate = self .config .cwd .join(path) .join(suffix) .join(parent) .join(format!("{base}.pk")); if let Some(path) = self.resolve(ResourceKind::Pk, &candidate.to_string_lossy(), from)? { let resource = self.read_path(path)?; let (h, v) = crate::pk::PkFont::density(&resource.data)?; if h.abs_diff(dpi) <= tolerance && v.abs_diff(dpi) <= tolerance { return Ok(resource); } return Err(format!( "native bare PK font {name} has {h}x{v} dpi, not requested {dpi} dpi" )); } } } Err(format!("native PK font {name} at {dpi} dpi not found")) } pub fn new(config: WorldConfig) -> Result { Self::new_detailed(config).map_err(|failure| failure.error) } pub fn new_detailed(mut config: WorldConfig) -> Result { let requested = config.clone(); let mut observations = Vec::new(); let prepared = (|| -> Result<(), String> { let resolved = config.cwd.canonicalize(); observations.push(WorldObservation::Canonicalize { path: config.cwd.clone(), result: resolved .as_ref() .map(Clone::clone) .map_err(ToString::to_string), }); config.cwd = resolved.map_err(|e| format!("resource cwd: {e}"))?; for root in &mut config.texmf_roots { let candidate = config.cwd.join(&*root); let resolved = candidate.canonicalize(); observations.push(WorldObservation::Canonicalize { path: candidate, result: resolved .as_ref() .map(Clone::clone) .map_err(ToString::to_string), }); *root = resolved.map_err(|e| format!("TEXMF root {}: {e}", root.display()))?; let directory = root.metadata().map(|m| m.is_dir()); observations.push(WorldObservation::Directory { path: root.clone(), result: directory.as_ref().copied().map_err(ToString::to_string), }); if !directory.unwrap_or(false) { return Err(format!("TEXMF root is not a directory: {}", root.display())); } } Ok(()) })(); if let Err(error) = prepared { return Err(WorldFailure { error, configuration: requested, observations, }); } let trace = ResourceTrace { schema: 1, cwd: config.cwd.clone(), input_policy: config.input_policy, texmf_roots: config.texmf_roots.clone(), paths: config.paths.clone(), configuration_observations: observations, ..ResourceTrace::default() }; Ok(Self { config, tex_suffix_fallback: true, capture_lookup_paths: false, indexes: BTreeMap::new(), current_project_indexes: BTreeSet::new(), index_failures: BTreeMap::new(), trace, pinned: false, replay: false, input_files: BTreeMap::new(), file_modifications: BTreeMap::new(), input_probes: BTreeMap::new(), deferred_probes: BTreeMap::new(), namespace_observations: 0, live_paths: BTreeSet::new(), staged_generated: BTreeMap::new(), protected_paths: BTreeSet::new(), replay_gaps: Vec::new(), project: None, system_fonts: None, project_named_fonts: None, named_font_directories: Some(Vec::new()), }) } pub fn capture_inputs(&mut self) { if !self.pinned && !self.trace.lookups.is_empty() { self.replay_gaps .push("input capture began after resource observations".into()); } 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) -> Result { project.validate()?; let config = project.configuration(); let trace = ResourceTrace { schema: 1, cwd: config.cwd.clone(), input_policy: config.input_policy, texmf_roots: config.texmf_roots.clone(), paths: config.paths.clone(), project_version: Some(project.version().clone()), ..Default::default() }; let live_paths = project.generated().map(Path::to_path_buf).collect(); Ok(Self { config, tex_suffix_fallback: true, capture_lookup_paths: false, indexes: BTreeMap::new(), current_project_indexes: BTreeSet::new(), index_failures: BTreeMap::new(), trace, pinned: true, replay: true, input_files: BTreeMap::new(), file_modifications: BTreeMap::new(), input_probes: BTreeMap::new(), deferred_probes: BTreeMap::new(), namespace_observations: 0, live_paths, staged_generated: BTreeMap::new(), protected_paths: BTreeSet::new(), replay_gaps: Vec::new(), project: Some(project), system_fonts: None, project_named_fonts: None, named_font_directories: Some(Vec::new()), }) } pub fn project(&self) -> Option<&Arc> { self.project.as_ref() } pub fn configuration(&self) -> &WorldConfig { &self.config } pub fn check_artifact_output(&self, path: &Path) -> Result<(), String> { if self .project .as_ref() .is_some_and(|p| p.protects_artifact(path) || self.protected_paths.contains(path)) { return Err("host output would overwrite an atomic project input or alias".into()); } if self.protected_paths.contains(path) { return Err("host output would overwrite a promoted generated resource".into()); } Ok(()) } pub fn check_generated_output(&self, logical: &Path, physical: &Path) -> Result<(), String> { if let Some(project) = &self.project { self.check_artifact_output(physical)?; project.check_generated_output(logical, physical, &self.project_paths())?; } Ok(()) } /// Resolve in the caller's logical namespace first. The host must then /// normalize this target and call check_generated_output before opening it. pub fn generated_output_path(&self, logical: &Path) -> Result { if let Some(project) = &self.project { let known = self.project_paths(); let target = project.locate(logical, &known)?.path; project.check_generated_output(logical, &target, &known)?; self.check_artifact_output(&target)?; Ok(target) } else { Ok(logical.to_owned()) } } pub fn from_snapshot(snapshot: Arc) -> Result { snapshot.validate()?; if !snapshot.replay_gaps.is_empty() { return Err(format!( "native input snapshot cannot be replayed: {}", snapshot.replay_gaps.join("; ") )); } let config = snapshot.config.clone(); let trace = ResourceTrace { schema: 1, cwd: config.cwd.clone(), input_policy: config.input_policy, texmf_roots: config.texmf_roots.clone(), paths: config.paths.clone(), project_version: snapshot.project.as_ref().map(|p| p.version().clone()), ..Default::default() }; 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(), trace, pinned: true, replay: true, input_files: snapshot.files.clone(), file_modifications: snapshot.file_modifications.clone(), input_probes: snapshot.probes.clone(), deferred_probes: snapshot.deferred_probes.clone(), namespace_observations: snapshot .deferred_probes .values() .map(|p| p.observations.len().max(1)) .sum(), live_paths: snapshot .project .as_ref() .map(|p| p.generated().map(Path::to_path_buf).collect()) .unwrap_or_default(), staged_generated: BTreeMap::new(), protected_paths: BTreeSet::new(), replay_gaps: Vec::new(), project: snapshot.project.clone(), system_fonts: snapshot.system_fonts.clone(), project_named_fonts: None, named_font_directories: snapshot.named_font_directories.clone(), }) } pub fn input_snapshot(&self) -> Arc { let mut gaps = self.replay_gaps.clone(); if !self.pinned { gaps.push("input capture was not enabled".into()); } Arc::new(InputSnapshot { schema: 1, tex_suffix_fallback: self.tex_suffix_fallback, config: self.config.clone(), files: self.input_files.clone(), file_modifications: self.file_modifications.clone(), probes: self.input_probes.clone(), deferred_probes: self.deferred_probes.clone(), indexes: self.indexes.clone(), index_failures: self.index_failures.clone(), lookups: self.trace.lookups.clone(), replay_gaps: gaps, project: self.project.clone(), system_fonts: self.system_fonts.clone(), named_font_directories: self.named_font_directories.clone(), }) } /// Only the authorized host may mark its generated-file paths live. These /// bytes keep real TeX read/write semantics and are never snapshot inputs. pub fn mark_live(&mut self, path: &Path) { if self.pinned && (self.input_files.contains_key(path) || self.file_modifications.contains_key(path)) && !self.live_paths.contains(path) { self.replay_gaps.push(format!( "external input became mutable during the job: {}", path.display() )); } if self.live_paths.insert(path.to_owned()) && self.project.is_some() { self.current_project_indexes.clear(); } } pub fn mark_generated_initial(&mut self, path: &Path) -> Result<(), String> { if self .project .as_ref() .is_some_and(|p| !p.permits_generated(path)) { return Ok(()); } if self.replay && self.input_files.contains_key(path) { return Err(format!( "native input snapshot ownership changed: {}", path.display() )); } self.mark_live(path); Ok(()) } pub fn protect_resource(&mut self, resource: &LoadedResource) { let was_live = self.live_paths.remove(&resource.version.path); 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) { self.current_project_indexes.clear(); } } if was_live { self.replay_gaps.push(format!( "generated input became protected during the job: {}", resource.version.path.display() )); } if self .project .as_ref() .and_then(|p| p.file(&resource.version.path)) .is_some_and(|f| f.version == resource.version) { return; } if self .input_files .get(&resource.version.path) .and_then(|v| v.as_ref().ok()) .is_some_and(|old| old.version == resource.version) { return; } if self .input_files .get(&resource.version.path) .and_then(|v| v.as_ref().ok()) .is_some_and(|old| old.version != resource.version) { self.replay_gaps.push(format!( "input changed roles/versions during the job: {}", resource.version.path.display() )); } self.input_files.insert( resource.version.path.clone(), Ok(SnapshotFile { version: resource.version.clone(), data: Arc::from(resource.data.clone()), }), ); } } fn live(&self, path: &Path) -> bool { // Only an actual host-authorized path owns a mutable byte role. // A captured probe describes a lookup destination, not a role for its // key. In particular, imported cache data must never make that key's // current physical bytes bypass input_file/stream_snapshot pinning. // Cached aliases still return their recorded canonical destination; // input_file then checks that destination's actual role independently. self.live_paths.contains(path) } /// Known mutable roles at this boundary. This does not read filesystem /// state or grant ownership; only the actual host establishes these roles. pub fn generated_paths(&self) -> impl Iterator { self.live_paths.iter().map(PathBuf::as_path) } /// Bind private storage to a host-authorized mutable project path. Resource /// resolution, observations and source names still use the project path. pub fn stage_generated(&mut self, path: &Path, storage: PathBuf) -> Result<(), String> { if !self.live(path) || !self.project.as_ref().is_some_and(|p| p.permits_generated(path)) || self.protected_paths.contains(path) { return Err("staged native storage requires a mutable project file".into()); } self.staged_generated.insert(path.to_owned(), storage); Ok(()) } pub fn generated_storage<'a>(&'a self, path: &'a Path) -> &'a Path { self.staged_generated.get(path).map_or(path, PathBuf::as_path) } fn project_paths(&self) -> BTreeSet { self.live_paths .union(&self.protected_paths) .cloned() .collect() } fn probe(&mut self, path: &Path) -> Result, String> { // PathBuf equality drops `/.` and trailing separators. Such spellings // require a directory and cannot be a resource file, even if a cached // key compares equal to a generated file's spelling. if self.project.is_none() && self.pinned && deferred::directory_only(path) { if let Some((key, Err(error))) = self.input_probes.get_key_value(path) { if key.as_os_str() == path.as_os_str() { return Err(error.clone()); } } return Ok(None); } if self.project.is_none() && (!self.pinned || self.live(path)) { return Self::existing(path); } if let Some(project) = &self.project { let location = project.locate(path, &self.project_paths())?; let result = if location.kind == Some(project::NodeKind::File) { if self.live_paths.contains(&location.path) { if let Some(storage) = self.staged_generated.get(&location.path) { Self::existing(storage).map(|found| found.map(|_| location.path)) } else { Self::existing(&location.path) } } else { Ok(Some(location.path)) } } else { Ok(None) }; self.input_probes.insert(path.into(), result.clone()); return result; } if let Some(probe) = self.deferred_probes.get(path) { if let Ok(Some(target)) = &probe.target { if self.generated_role(target).is_some() { return self.generated_lookup( path, target.clone(), GeneratedLookupOrigin::Deferred(probe.clone()), ); } } } if let Some(value) = self.input_probes.get(path) { return value.clone(); } if let Some((target, origin)) = self.directory_binding(path) { return self.generated_lookup(path, target, origin); } // A live capture must let the host resolve names: directory listings // alone do not describe case folding, short names or other host aliases. if self.replay { if let Some(absence) = self.directory_absence(path) { self.trace.directory_absences.push(absence); return Ok(None); } } if self.replay { return Err(format!( "native input snapshot has no lookup observation for {}", path.display() )); } let value = Self::existing(path); if value == Ok(None) { let probe = DeferredProbe::observe(path); let count = self .namespace_observations .saturating_add(probe.observations.len().max(1)); if count > deferred::MAX_OBSERVATIONS { let error = "deferred namespace observation capacity exceeded".to_owned(); self.trace .namespace_capture_failures .push(NamespaceCaptureFailure { candidate: path.into(), probe, error: error.clone(), }); self.input_probes.insert(path.into(), Err(error.clone())); return Err(error); } self.namespace_observations = count; self.deferred_probes.insert(path.into(), probe); } self.input_probes.insert(path.to_owned(), value.clone()); // Apply the same overlay rule to a first observation and to subsequent // uses. The captured probe now exists, so this cannot acquire it twice. if value == Ok(None) { return self.probe(path); } value } fn generated_role(&self, target: &Path) -> Option { if self.live_paths.contains(target) { Some(GeneratedLookupRole::Mutable) } else if self.protected_paths.contains(target) { Some(GeneratedLookupRole::PromotedResource) } else { None } } fn generated_lookup( &mut self, path: &Path, target: PathBuf, origin: GeneratedLookupOrigin, ) -> Result, String> { let role = self.generated_role(&target).unwrap(); let observed = (role == GeneratedLookupRole::Mutable).then(|| Self::existing(&target)); let result = match &observed { Some(Ok(Some(actual))) if actual != &target => Err(format!( "captured generated target changed physical path: {} -> {}", target.display(), actual.display() )), Some(result) => result.clone(), None => Ok(Some(target.clone())), }; self.trace.generated_lookups.push(GeneratedLookup { candidate: path.into(), target, origin, role, replayed_namespace: self.replay, observed, result: result.clone(), }); result } fn directory_binding(&self, path: &Path) -> Option<(PathBuf, GeneratedLookupOrigin)> { let mut best = None; let mut length = 0; for (root, index) in &self.indexes { // Query ancestors rather than scanning an installed directory tree // on every candidate. The closest recorded parent wins before // checking its role; a live shallower parent cannot override it. for logical in path.ancestors().skip(1) { let Some(canonical) = index.directory_aliases.get(logical) else { continue; }; let relative = path.strip_prefix(logical).unwrap(); if relative.as_os_str().is_empty() || !relative .components() .all(|c| matches!(c, std::path::Component::Normal(_))) { break; } let target = canonical.join(relative); let components = logical.components().count(); if components > length { best = Some(( target, GeneratedLookupOrigin::Directory { root: root.clone(), logical_directory: logical.into(), canonical_directory: canonical.clone(), }, )); length = components; } break; } } best.filter(|(target, _)| self.generated_role(target).is_some()) } fn directory_absence(&self, path: &Path) -> Option { // Without a captured host name-equivalence contract, only an empty // file namespace can prove a new ordinary name absent. Otherwise an // unrecorded spelling might name one of the listed files on this host. // Native Windows also has device/stream names not covered by listing. if cfg!(windows) { return None; } let name = path.file_name()?.to_str()?; if name.is_empty() || name.ends_with('.') || !name .bytes() .all(|b| b.is_ascii_alphanumeric() || b"._-".contains(&b)) { return None; } let parent = path.parent()?; for (root, index) in &self.indexes { let Some(canonical) = index.directory_aliases.get(parent) else { continue; }; if index .names .values() .flatten() .any(|p| p.parent() == Some(parent)) { return None; } let listed = path .file_name() .and_then(|name| index.names.get(name)) .is_some_and(|paths| paths.iter().any(|p| p == path)); if !listed { return Some(DirectoryAbsence { candidate: path.into(), root: root.clone(), logical_directory: parent.into(), canonical_directory: canonical.clone(), replayed_namespace: self.replay, }); } } None } fn input_file(&mut self, path: PathBuf) -> Result { let live = self.live(&path); if self.pinned && !live { if let Some(value) = self.input_files.get(&path) { return value.clone(); } if let Some(file) = self.project.as_ref().and_then(|p| p.file(&path)) { return Ok(file.clone()); } if self.replay { return Err(format!( "native input snapshot has no captured bytes for {}", path.display() )); } } let value = self.read_input_from_disk(&path); if self.pinned && !live { self.input_files.insert(path, value.clone()); } value } fn read_input_from_disk(&self, path: &Path) -> Result { fs::read(self.generated_storage(path)) .map(|data| SnapshotFile { version: ResourceVersion { path: path.to_owned(), sha256: format!("{:x}", Sha256::digest(&data)), bytes: data.len() as u64, }, data: Arc::from(data), }) .map_err(|e| format!("resource {}: {e}", path.display())) } /// Pins bytes for an external stream without claiming that its whole /// contents were delivered to TeX. Consumption remains in stream_reads. pub fn stream_snapshot(&mut self, path: &Path) -> Result, String> { if deferred::directory_only(path) { return Err("directory spelling cannot name a resource stream".into()); } if !self.pinned || self.live(path) { return Ok(None); } self.input_file(path.to_owned()).map(Some).map_err(|error| { self.observe_read_error(path, error.clone()); error }) } pub fn record_format_input_bindings(&mut self, bindings: &BTreeMap) { self.trace.format_input_bindings.clone_from(bindings); } pub fn trace(&self) -> &ResourceTrace { &self.trace } pub fn observe_stream_read(&mut self, path: &Path, offset: u64, bytes: Option<&[u8]>) { self.trace.stream_reads.push(ResourceReadRange { path: path.to_owned(), offset, bytes: bytes.map_or(0, |b| b.len() as u64), sha256: format!("{:x}", Sha256::digest(bytes.unwrap_or_default())), eof: bytes.is_none(), }); } pub fn observe_read_error(&mut self, path: &Path, error: String) { self.trace.read_errors.push((path.to_owned(), error)); } pub fn invalidate_directories(&mut self) { if !self.pinned { self.indexes.clear(); } } fn paths(&self, kind: ResourceKind, from: &Path) -> Vec<(SearchPath, bool)> { // Images use the TeX namespace and have their own dependency role. let kind = if kind == ResourceKind::PdfImage { ResourceKind::Tex } else { kind }; // Keep default job-relative paths distinct from explicitly configured // absolute search entries, even when they name the same directory. let mut defaults = vec![(SearchPath::directory(&self.config.cwd, false), true)]; if kind == ResourceKind::Tex && self.config.input_policy == InputPolicy::Project { if let Some(parent) = from.parent() { let path = self.config.cwd.join(parent); if path != self.config.cwd { let job_relative = path.starts_with(&self.config.cwd); defaults.push((SearchPath::directory(path, false), job_relative)); } } } let directories: &[&str] = if kind == ResourceKind::Tex { &["tex/latex", "tex/generic", "tex"] } else { &[kind.directory()] }; for directory in directories { defaults.extend( self.config .texmf_roots .iter() .map(|r| (SearchPath::directory(r.join(directory), true), false)), ); } let mut paths = Vec::new(); for entry in self .config .paths .get(&kind) .map(Vec::as_slice) .unwrap_or(&[SearchPath::Defaults]) { match entry { SearchPath::Defaults => paths.extend(defaults.clone()), e => paths.push((e.clone(), false)), } } paths } fn variants(kind: ResourceKind, name: &str, tex_suffix_fallback: bool) -> Vec { let path = Path::new(name); let mut values = Vec::new(); if path.extension().is_none() { values.extend( kind.extensions() .iter() .map(|extension| path.with_extension(extension)), ); } else if tex_suffix_fallback && !deferred::directory_only(path) { // Kpathsea tries the standard suffix before an unrecognized one // within a search path entry. The recognized TeX suffixes are // tried as supplied. const TEX_SUFFIXES: &[&str] = &["tex", "sty", "cls", "fd", "aux", "bbl", "def", "clo", "ldf"]; let extension = path.extension().and_then(|extension| extension.to_str()); let recognized = extension.is_some_and(|extension| { TEX_SUFFIXES.iter().any(|known| { extension == *known || (cfg!(windows) && extension.eq_ignore_ascii_case(known)) }) }); if !recognized { values.push(PathBuf::from(format!("{name}.tex"))); } } values.push(path.to_owned()); values } fn existing(path: &Path) -> Result, String> { match path.metadata() { Ok(m) if !m.is_dir() => path .canonicalize() .map(Some) .map_err(|e| format!("resource {}: {e}", path.display())), Ok(_) => Ok(None), Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(None), Err(e) => Err(format!("resource {}: {e}", path.display())), } } fn index(&mut self, root: &Path) -> Result<&DirectoryIndex, String> { self.index_at(root, true) } fn index_at(&mut self, root: &Path, recursive: bool) -> Result<&DirectoryIndex, String> { if let Some(project) = &self.project { // The index tracks the logical namespace. Each candidate's live // existence and staged bytes are still checked by probe(). if !self.current_project_indexes.contains(root) || (recursive && !self.indexes[root].recursive) { let index = project.index(root, &self.project_paths(), self.config.max_index_entries, recursive)?; self.indexes.insert(root.into(), Arc::new(index)); self.current_project_indexes.insert(root.into()); } return Ok(&self.indexes[root]); } if self.pinned && let Some(failure) = self.index_failures.get(root) && (recursive || !failure.partial.recursive) { return Err(failure.error.clone()); } // Live worlds revalidate directory timestamps; captured worlds freeze // observed enumeration. Neither mode authorizes execution/layout reuse. let fresh = self.indexes.get(root).is_some_and(|index| { (!recursive || index.recursive) && (self.pinned || (!index.directories.is_empty() && index.directories.iter().all(|(p, t)| { p.metadata() .and_then(|m| m.modified()) .is_ok_and(|v| v == *t) }))) }); if !fresh { if self.replay { return Err(format!( "native input snapshot has no directory observation for {}", root.display() )); } let mut index = DirectoryIndex { recursive, directories: Vec::new(), directory_aliases: BTreeMap::new(), names: BTreeMap::new(), }; let built = (|| -> Result<(), String> { let mut queue = vec![(root.to_owned(), Vec::::new())]; let mut visited = BTreeSet::new(); let mut count = 0usize; while let Some((dir, mut ancestors)) = queue.pop() { let canonical = match dir.canonicalize() { Ok(v) => v, Err(e) if e.kind() == std::io::ErrorKind::NotFound => continue, Err(e) => return Err(format!("resource directory {}: {e}", dir.display())), }; if ancestors.contains(&canonical) { continue; } ancestors.push(canonical.clone()); let metadata = canonical.metadata().map_err(|e| e.to_string())?; if !metadata.is_dir() { continue; } if visited.insert(canonical.clone()) { index.directories.push(( canonical.clone(), metadata.modified().map_err(|e| e.to_string())?, )); } index .directory_aliases .insert(dir.clone(), canonical.clone()); let mut children = fs::read_dir(&dir) .map_err(|e| format!("resource directory {}: {e}", dir.display()))? .collect::, _>>() .map_err(|e| e.to_string())?; children.sort_by_key(|e| e.file_name()); for child in children { count += 1; if count > self.config.max_index_entries { return Err("native resource directory capacity exceeded".into()); } let path = child.path(); match path.metadata() { Ok(m) if m.is_dir() => { if recursive { queue.push((path, ancestors.clone())); } } Ok(_) => index.names.entry(child.file_name()).or_default().push(path), Err(e) if e.kind() == std::io::ErrorKind::NotFound => { if path .symlink_metadata() .is_ok_and(|m| m.file_type().is_symlink()) { index.names.entry(child.file_name()).or_default().push(path); } } Err(e) => return Err(format!("resource {}: {e}", path.display())), } } } for paths in index.names.values_mut() { paths.sort(); } Ok(()) })(); if let Err(error) = built { if self.pinned { self.index_failures.insert( root.into(), DirectoryFailure { error: error.clone(), partial: Arc::new(index), }, ); } return Err(error); } self.indexes.insert(root.to_owned(), Arc::new(index)); } Ok(&self.indexes[root]) } pub fn resolve( &mut self, kind: ResourceKind, name: &str, from: &Path, ) -> Result, String> { self.resolve_variants(kind, name, from, Self::variants(kind, name, false), None) } /// Apply the TeX input scanner's default suffix alternatives. Raw host /// files and recorded format dependencies still keep their names. pub fn resolve_tex_input(&mut self, name: &str, from: &Path) -> Result, String> { let kind = ResourceKind::Tex; let fallback = self.config.input_policy == InputPolicy::Tex && self.tex_suffix_fallback; self.resolve_variants(kind, name, from, Self::variants(kind, name, fallback), None) } fn resolve_variants( &mut self, kind: ResourceKind, name: &str, from: &Path, variants: Vec, lookup_path: Option<&mut PathBuf>, ) -> Result, 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; let requested = Path::new(name); if requested.is_absolute() || matches!( requested.components().next(), Some(std::path::Component::CurDir | std::path::Component::ParentDir) ) { for variant in &variants { let path = self.config.cwd.join(variant); candidates.push(path.clone()); if let Some(path) = self.probe(&path)? { if record_spelling { spelling = Some(variant.clone()); } 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 // trying the bare name, rather than flattening it into directories. 'paths: for (entry, job_relative) in &paths { let SearchPath::Directory { path, recursive, suffix, } = entry else { unreachable!() }; let root = self.config.cwd.join(path); let lookup_name = |cwd: &Path, candidate: &Path| { if *job_relative && let Ok(relative) = candidate.strip_prefix(cwd) { return Path::new(".").join(relative); } if path.is_relative() && let Ok(relative) = candidate.strip_prefix(&root) { return path.join(relative); } candidate.to_owned() }; for variant in &variants { let direct = root.join(suffix).join(variant); candidates.push(direct.clone()); if let Some(path) = self.probe(&direct)? { if record_spelling { spelling = Some(lookup_name(&self.config.cwd, &direct)); } found = Some(path); break 'paths; } 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; } candidates.push(candidate.clone()); if let Some(path) = self.probe(&candidate)? { if record_spelling { spelling = Some(lookup_name(&self.config.cwd, &candidate)); } found = Some(path); break 'paths; } } } } } } 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 } pub fn read( &mut self, kind: ResourceKind, name: &str, from: &Path, ) -> Result { self.read_shared(kind, name, from) .map(SnapshotFile::into_loaded) } /// Read a resource and return the path spelling selected by the lookup. /// Its version records the resolved identity independently. pub fn read_with_lookup_path( &mut self, kind: ResourceKind, name: &str, from: &Path, ) -> Result<(LoadedResource, PathBuf), String> { let mut lookup_path = PathBuf::new(); let path = self.resolve_variants( kind, name, from, Self::variants(kind, name, false), Some(&mut lookup_path), )?; let resource = self.read_shared_resolved(kind, name, from, path)?; Ok((resource.into_loaded(), lookup_path)) } /// Resolve and record a resource read while sharing the captured bytes. pub fn read_shared( &mut self, kind: ResourceKind, name: &str, from: &Path, ) -> Result { let path = self.resolve(kind, name, from)?; self.read_shared_resolved(kind, name, from, path) } /// Read a normal TeX source, including an unrecognized suffix's .tex /// alternative when supported by the active input policy. pub fn read_tex_input(&mut self, name: &str, from: &Path) -> Result { let path = self.resolve_tex_input(name, from)?; self.read_shared_resolved(ResourceKind::Tex, name, from, path) .map(SnapshotFile::into_loaded) } /// TeX file queries use the same lookup as TeX input. A missing lookup /// is returned as None without opening an arbitrary fallback file. pub fn read_tex_input_optional( &mut self, name: &str, from: &Path, ) -> Result, String> { let name = if name.is_empty() { ".tex" } else { name }; self.resolve_tex_input(name, from)? .map(|path| self.read_path(path)) .transpose() } fn read_shared_resolved( &mut self, kind: ResourceKind, name: &str, from: &Path, path: Option, ) -> Result { let path = path.ok_or_else(|| { format!( "native {kind:?} resource {name} not found from {}", from.display() ) })?; self.read_shared_path(path) } pub fn read_optional( &mut self, kind: ResourceKind, name: &str, from: &Path, ) -> Result, String> { let name = if name.is_empty() && kind == ResourceKind::Tex { ".tex" } else { name }; self.resolve(kind, name, from)? .map(|path| self.read_path(path)) .transpose() } /// Resolve using TeX's input namespace and observe only the metadata TeX /// queried. Reading candidate bytes is neither required nor implied. pub fn file_modification_date( &mut self, name: &str, from: &Path, format: impl FnOnce(FileModificationTime) -> Result, ) -> Result, String> { let name = if name.is_empty() { ".tex" } else { name }; let Some(path) = self.resolve(ResourceKind::Tex, name, from)? else { return Ok(None); }; let result = self.modification_at(&path, format); self.trace .file_modifications .push(FileModificationObservation { path, result: result.clone(), }); result.map(|date| date.map(|date| date.text)) } fn modification_at( &mut self, path: &Path, format: impl FnOnce(FileModificationTime) -> Result, ) -> Result, String> { let capture = self.pinned && !self.live(path); let project_time = self .project .as_ref() .and_then(|p| p.modification_time(path)); if capture { if let Some(modified) = self.file_modifications.get(path) { return Ok(modified.clone()); } if self.replay && project_time.is_none() { return Err(format!( "native input snapshot has no captured modification time for {}", path.display() )); } } let time = match project_time { Some(time) => Some(time), None => fs::metadata(self.generated_storage(path)) .and_then(|metadata| metadata.modified()) .ok() .map(FileModificationTime::from_system_time) .transpose()?, }; let modified = time .map(|time| format(time).map(|text| FileModificationDate { time, text })) .transpose()?; if capture { self.file_modifications .insert(path.to_owned(), modified.clone()); } Ok(modified) } fn read_path(&mut self, path: PathBuf) -> Result { self.read_shared_path(path).map(SnapshotFile::into_loaded) } fn read_shared_path(&mut self, path: PathBuf) -> Result { let file = self.input_file(path.clone()).map_err(|error| { self.trace.read_errors.push((path.clone(), error.clone())); error })?; self.trace.reads.push(file.version.clone()); Ok(file) } }