use std::{ fs, path::{Path, PathBuf}, sync::atomic::{AtomicU64, Ordering}, }; use texrra_tex_core::resources::*; fn directory() -> PathBuf { static ID: AtomicU64 = AtomicU64::new(0); let p = std::env::temp_dir().join(format!( "texrra-world-{}-{}", std::process::id(), ID.fetch_add(1, Ordering::Relaxed) )); fs::create_dir_all(&p).unwrap(); p } fn put(path: impl AsRef, data: impl AsRef<[u8]>) { let p = path.as_ref(); fs::create_dir_all(p.parent().unwrap()).unwrap(); fs::write(p, data).unwrap(); } #[test] fn file_modification_capture_replays_original_observation_after_file_edits() { use std::time::{Duration, SystemTime}; let path = directory().canonicalize().unwrap(); let asset = path.join("asset.dat"); put(&asset, b"same bytes"); let file = fs::File::open(&asset).unwrap(); let modification = |seconds| { file.set_modified(SystemTime::UNIX_EPOCH + Duration::from_secs(seconds)) .unwrap(); }; let config = WorldConfig::new(&path); let mut capture = FileWorld::new(config.clone()).unwrap(); capture.capture_inputs(); let query = |world: &mut FileWorld| { world.file_modification_date("asset.dat", Path::new("entry.tex"), |time| { Ok(time.unix_seconds.to_string()) }) }; modification(1_709_210_096); assert_eq!(query(&mut capture).unwrap().as_deref(), Some("1709210096")); let snapshot = capture.input_snapshot(); assert!(snapshot.file(&asset).is_none()); assert!(capture.trace().reads.is_empty()); let serialized = serde_json::to_vec(snapshot.as_ref()).unwrap(); let mut replay = FileWorld::from_snapshot(serde_json::from_slice(&serialized).unwrap()).unwrap(); modification(1_709_210_193); assert_eq!( replay .file_modification_date("asset.dat", Path::new("entry.tex"), |_| { panic!("replay must use the captured representation") }) .unwrap() .as_deref(), Some("1709210096") ); let mut fresh = FileWorld::new(config).unwrap(); assert_eq!(query(&mut fresh).unwrap().as_deref(), Some("1709210193")); assert_eq!(fs::read(&asset).unwrap(), b"same bytes"); fs::remove_dir_all(path).unwrap(); } #[test] fn atomic_file_modifications_are_versioned_and_do_not_read_disk_metadata() { use std::{collections::BTreeMap, sync::Arc}; let path = directory().canonicalize().unwrap(); let asset = path.join("asset.dat"); let alias = path.join("alias.dat"); let definition = ProjectDefinition { configuration: WorldConfig::new(&path), revision: 1, roots: [path.clone()].into(), files: [(asset.clone(), Arc::from(b"the logical file".as_slice()))].into(), directories: Default::default(), aliases: [(alias, asset.clone())].into(), generated_roots: Default::default(), generated: Default::default(), }; let snapshot = |seconds| { ProjectSnapshot::with_file_modifications( definition.clone(), [( asset.clone(), FileModificationTime { unix_seconds: seconds, nanoseconds: 1, }, )] .into(), ) .unwrap() }; let first = snapshot(-1); let second = snapshot(1); assert_eq!( first.file(&asset).unwrap().version, second.file(&asset).unwrap().version ); assert_ne!(first.version().sha256, second.version().sha256); let query = |world: &mut FileWorld| { world.file_modification_date("alias.dat", Path::new("entry.tex"), |time| { Ok(format!("{}:{}", time.unix_seconds, time.nanoseconds)) }) }; let mut world = FileWorld::from_project(first).unwrap(); assert_eq!(query(&mut world).unwrap().as_deref(), Some("-1:1")); assert_eq!(world.trace().file_modifications[0].path, asset); assert!(world.trace().reads.is_empty()); let mut world = FileWorld::from_project(second).unwrap(); assert_eq!(query(&mut world).unwrap().as_deref(), Some("1:1")); put(&asset, b"disk data is unavailable to the logical namespace"); let mut bytes_only = FileWorld::from_project( ProjectSnapshot::with_file_modifications(definition, BTreeMap::new()).unwrap(), ) .unwrap(); assert!( query(&mut bytes_only) .unwrap_err() .contains("no captured modification time") ); fs::remove_dir_all(path).unwrap(); } #[test] fn directory_priority_suffixes_recursive_paths_and_project_shadowing() { let p = directory(); let a = p.join("a"); let b = p.join("b"); put(a.join("choice"), b"BARE"); put(b.join("choice.tex"), b"TEX"); let mut config = WorldConfig::new(&p); config.paths.insert( ResourceKind::Tex, vec![ SearchPath::directory(&a, false), SearchPath::directory(&b, false), ], ); let mut world = FileWorld::new(config).unwrap(); assert_eq!( world .read(ResourceKind::Tex, "choice", Path::new("main.tex")) .unwrap() .data, b"BARE" ); put(a.join("choice.tex"), b"FIRST-TEX"); assert_eq!( world .read(ResourceKind::Tex, "choice", Path::new("main.tex")) .unwrap() .data, b"FIRST-TEX" ); let mut config = WorldConfig::new(&p); config .paths .insert(ResourceKind::Tex, vec![SearchPath::directory(&p, true)]); let mut world = FileWorld::new(config).unwrap(); assert_eq!( world .read(ResourceKind::Tex, "choice", Path::new("main.tex")) .unwrap() .data, b"FIRST-TEX" ); let texmf = p.join("dist"); put(texmf.join("tex/latex/pkg/same.tex"), b"DIST"); put(p.join("same.tex"), b"PROJECT"); let mut config = WorldConfig::new(&p); config.texmf_roots.push(texmf); let mut world = FileWorld::new(config).unwrap(); assert_eq!( world .read(ResourceKind::Tex, "same", Path::new("main.tex")) .unwrap() .data, b"PROJECT" ); fs::remove_file(p.join("same.tex")).unwrap(); assert_eq!( world .read(ResourceKind::Tex, "same", Path::new("main.tex")) .unwrap() .data, b"DIST" ); fs::remove_dir_all(p).unwrap(); } #[test] fn typed_binary_resources_real_sha256_versions_and_negative_reads() { let p = directory(); let root = p.join("texmf"); for (dir, name) in [ ("tex/pkg", "a.tex"), ("fonts/tfm/pkg", "a.tfm"), ("fonts/vf/pkg", "a.vf"), ("fonts/type1/pkg", "a.pfb"), ("fonts/enc/pkg", "a.enc"), ("fonts/map/pkg", "a.map"), ("web2c/pkg", "a.fmt"), ] { put(root.join(dir).join(name), b"abc"); } let mut config = WorldConfig::new(&p); config.texmf_roots.push(root); let mut world = FileWorld::new(config).unwrap(); for kind in [ ResourceKind::Tex, ResourceKind::Tfm, ResourceKind::Vf, ResourceKind::Type1, ResourceKind::Encoding, ResourceKind::Map, ResourceKind::Format, ] { let r = world.read(kind, "a", Path::new("main.tex")).unwrap(); assert_eq!(r.data, b"abc"); assert_eq!(r.version.bytes, 3); assert_eq!( r.version.sha256, "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" ); } let first = world .read(ResourceKind::Tfm, "a", Path::new("main.tex")) .unwrap(); put(&first.version.path, [0, 255, 7]); let second = world .read(ResourceKind::Tfm, "a", Path::new("main.tex")) .unwrap(); assert_eq!(first.version.path, second.version.path); assert_ne!(first.version.sha256, second.version.sha256); assert_eq!(second.data, [0, 255, 7]); assert!( world .resolve(ResourceKind::Tex, "missing", Path::new("main.tex")) .unwrap() .is_none() ); assert!(world.trace().lookups.last().unwrap().resolved.is_none()); let copy: ResourceTrace = serde_json::from_str(&serde_json::to_string(world.trace()).unwrap()).unwrap(); assert_eq!(©, world.trace()); fs::remove_dir_all(p).unwrap(); } #[test] fn recursive_suffix_new_files_missing_roots_and_bounded_directory_work() { let p = directory(); let missing = p.join("later"); let mut config = WorldConfig::new(&p); config.paths.insert( ResourceKind::Tex, vec![SearchPath::directory(&missing, true)], ); let mut world = FileWorld::new(config).unwrap(); assert!( world .resolve(ResourceKind::Tex, "new", Path::new("main.tex")) .unwrap() .is_none() ); put(missing.join("deep/new.tex"), b"NEW"); assert_eq!( world .read(ResourceKind::Tex, "new", Path::new("main.tex")) .unwrap() .data, b"NEW" ); assert!( world .resolve(ResourceKind::Tex, "next", Path::new("main.tex")) .unwrap() .is_none() ); put(missing.join("deep/next.tex"), b"NEXT"); assert_eq!( world .read(ResourceKind::Tex, "next", Path::new("main.tex")) .unwrap() .data, b"NEXT" ); put(missing.join("prefix/pkg/suffix/filtered.tex"), b"MATCH"); put(missing.join("filtered.tex"), b"WRONG"); let mut config = WorldConfig::new(&p); config.paths.insert( ResourceKind::Tex, SearchPath::parse_list(&format!("{}//suffix", missing.display())).unwrap(), ); let mut world = FileWorld::new(config).unwrap(); assert_eq!( world .read(ResourceKind::Tex, "filtered", Path::new("main.tex")) .unwrap() .data, b"MATCH" ); let mut config = WorldConfig::new(&p); config.paths.insert( ResourceKind::Tex, vec![SearchPath::directory(&missing, true)], ); config.max_index_entries = 1; assert!( FileWorld::new(config) .unwrap() .resolve(ResourceKind::Tex, "absent", Path::new("main.tex")) .unwrap_err() .contains("capacity") ); fs::remove_dir_all(p).unwrap(); } #[test] fn explicit_search_paths_default_expansion_and_unsupported_syntax_fail_closed() { let p = directory(); put(p.join("same.tex"), b"LOCAL"); let custom = p.join("custom"); put(custom.join("same.tex"), b"CUSTOM"); let mut config = WorldConfig::new(&p); config.paths.insert( ResourceKind::Tex, SearchPath::parse_list(&format!("{}:", custom.display())).unwrap(), ); let mut world = FileWorld::new(config).unwrap(); assert_eq!( world .read(ResourceKind::Tex, "same", Path::new("main.tex")) .unwrap() .data, b"CUSTOM" ); put(p.join("local.tex"), b"DEFAULT"); assert_eq!( world .read(ResourceKind::Tex, "local", Path::new("main.tex")) .unwrap() .data, b"DEFAULT" ); for path in [ "$TEXMF/tex//", "!!/texmf/tex//", "/texmf/{a,b}//", "/a//b//c", "~/tex", ] { assert!(SearchPath::parse_list(path).is_err(), "{path}"); } let mut config = WorldConfig::new(&p); config.texmf_roots.push(p.join("no-root")); assert!(FileWorld::new(config).is_err()); fs::remove_dir_all(p).unwrap(); } #[cfg(unix)] #[test] fn symlink_aliases_share_identity_and_directory_cycles_terminate() { use std::os::unix::fs::symlink; let p = directory(); let root = p.join("tree"); put(root.join("deep/a.tex"), b"ALIAS"); symlink(&root, root.join("deep/cycle")).unwrap(); symlink(root.join("deep/a.tex"), p.join("alias.tex")).unwrap(); let mut config = WorldConfig::new(&p); config .paths .insert(ResourceKind::Tex, vec![SearchPath::directory(&root, true)]); let mut world = FileWorld::new(config).unwrap(); let first = world .read(ResourceKind::Tex, "a", Path::new("main.tex")) .unwrap(); let second = world .read( ResourceKind::Tex, p.join("alias.tex").to_str().unwrap(), Path::new("main.tex"), ) .unwrap(); assert_eq!(first.version, second.version); assert!( world .resolve(ResourceKind::Tex, "missing", Path::new("main.tex")) .unwrap() .is_none() ); fs::remove_dir_all(p).unwrap(); } #[test] fn tex_and_project_policies_preserve_explicit_source_lookup_contracts() { let p = directory(); let source = p.join("project/main.tex"); put(source.parent().unwrap().join("child.tex"), b"CHILD"); let mut tex = FileWorld::new(WorldConfig::new(&p)).unwrap(); assert!( tex.resolve(ResourceKind::Tex, "child", &source) .unwrap() .is_none() ); let mut config = WorldConfig::new(&p); config.input_policy = InputPolicy::Project; let mut project = FileWorld::new(config).unwrap(); assert_eq!( project .read(ResourceKind::Tex, "child", &source) .unwrap() .data, b"CHILD" ); let root = p.join("texmf"); put(root.join("tex/latex-dev/base/kernel.tex"), b"DEV"); put(root.join("tex/latex/base/kernel.tex"), b"RELEASE"); let mut config = WorldConfig::new(&p); config.texmf_roots.push(root); let mut tex = FileWorld::new(config).unwrap(); assert_eq!( tex.read(ResourceKind::Tex, "kernel", &source).unwrap().data, b"RELEASE" ); fs::remove_dir_all(p).unwrap(); } #[cfg(unix)] #[test] fn real_empty_devices_and_logical_symlink_suffixes_are_read_without_substitutes() { use std::os::unix::fs::symlink; let p = directory(); let actual = p.join("actual"); put(actual.join("entry.tex"), b"LOGICAL"); let root = p.join("tree"); fs::create_dir_all(root.join("pkg")).unwrap(); symlink(&actual, root.join("pkg/suffix")).unwrap(); let mut config = WorldConfig::new(&p); config.paths.insert( ResourceKind::Tex, SearchPath::parse_list(&format!("{}//suffix", root.display())).unwrap(), ); let mut world = FileWorld::new(config).unwrap(); assert_eq!( world .read(ResourceKind::Tex, "entry", Path::new("main.tex")) .unwrap() .data, b"LOGICAL" ); let empty = world .read(ResourceKind::Tex, "/dev/null", Path::new("main.tex")) .unwrap(); assert!(empty.data.is_empty()); assert_eq!( empty.version.sha256, "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" ); fs::remove_dir_all(p).unwrap(); } #[test] fn frozen_real_reference_resources_are_read_as_their_actual_bytes_and_versions() { use std::process::Command; let manifest: serde_json::Value = serde_json::from_str(include_str!( "../../../tests/fixtures/native-format-stage-reference.json" )) .unwrap(); let project = Path::new(env!("CARGO_MANIFEST_DIR")) .join("../../examples/native-format-stage") .canonicalize() .unwrap(); let p = directory(); let mut world = FileWorld::new(WorldConfig::new(&p)).unwrap(); let mut count = 0; for version in manifest["resources"].as_array().unwrap() { let namespace = version["namespace"].as_str().unwrap(); let relative = version["path"].as_str().unwrap(); let path = match namespace { "PROJECT" => project.join(relative), "EXTERNAL" => PathBuf::from(relative), name => { let result = Command::new("kpsewhich") .arg(format!("--var-value={name}")) .output() .expect("frozen reference installation required"); assert!(result.status.success()); PathBuf::from(String::from_utf8(result.stdout).unwrap().trim()).join(relative) } }; let kind = match path.extension().and_then(|s| s.to_str()) { Some("tfm") => ResourceKind::Tfm, Some("vf") => ResourceKind::Vf, Some("pfb" | "pfa") => ResourceKind::Type1, Some("enc") => ResourceKind::Encoding, Some("map") => ResourceKind::Map, Some("cnf") => ResourceKind::Config, _ => ResourceKind::Tex, }; // Explicit recorded identities check all real bytes, not native format // execution. Filename search choices have their own INITEX oracle. let resource = world .read(kind, path.to_str().unwrap(), Path::new("reference")) .unwrap(); assert_eq!( resource.version.sha256, version["sha256"].as_str().unwrap(), "{}", path.display() ); assert_eq!(resource.version.bytes, version["bytes"].as_u64().unwrap()); count += 1; } assert_eq!(count, 103); assert_eq!(world.trace().reads.len(), count); assert_eq!(world.trace().schema, 1); eprintln!( "{count} real recorder-derived source/config/font/map resource versions verified through native World" ); fs::remove_dir_all(p).unwrap(); }