use std::{ collections::{BTreeMap, BTreeSet}, fs, path::PathBuf, sync::Arc, }; use texrra_engine::native::CompileFailure; use texrra_tex_core::resources::{FileWorld, ProjectSnapshot, ResourceKind, SearchPath}; #[derive(Default)] pub(super) struct ResourceCapture { resources: BTreeMap>, host: Option, } impl ResourceCapture { pub(super) fn apply( &self, project: &Arc, ) -> Result, String> { project.with_external_resources(&self.resources) } pub(super) fn expand( &mut self, project: &Arc, failure: &CompileFailure, ) -> Option> { let trace = failure.trace.as_ref()?; let config = project.configuration(); let search_roots = config .texmf_roots .iter() .cloned() .chain( config .paths .values() .flatten() .filter_map(|path| match path { SearchPath::Directory { path, .. } => Some(config.cwd.join(path)), SearchPath::Defaults => None, }), ) .collect::>(); let host = match &mut self.host { Some(host) => host, slot => slot.insert(FileWorld::new(config.clone()).ok()?), }; let mut queried = BTreeSet::new(); let mut added = BTreeMap::new(); for lookup in trace .lookups .iter() .filter(|lookup| lookup.resolved.is_none()) { if !queried.insert((lookup.kind, &lookup.name, &lookup.from)) { continue; } let resolved = if lookup.kind == ResourceKind::Tex { host.resolve_tex_input(&lookup.name, &lookup.from) } else { host.resolve(lookup.kind, &lookup.name, &lookup.from) }; if let Ok(Some(path)) = resolved && !path.starts_with(&config.cwd) && search_roots.iter().any(|root| path.starts_with(root)) && project.file(&path).is_none() && fs::metadata(&path).is_ok_and(|metadata| metadata.is_file()) && let Ok(bytes) = fs::read(&path) { added.insert(path, Arc::from(bytes)); } } if added.is_empty() { return None; } let expanded = project.with_external_resources(&added).ok()?; self.resources.extend(added); Some(expanded) } }