1use std::{
24 path::{Path, PathBuf},
25 sync::LazyLock,
26};
27
28use regex::Regex;
29
30pub fn find_main_tex(dir: &Path, confined: bool) -> Result<PathBuf, String> {
38 main_tex_in(dir, true, confined)
39}
40
41pub fn main_tex_in(dir: &Path, report: bool, confined: bool) -> Result<PathBuf, String> {
44 if let Some(main_path) =
47 parse_readme_json(dir, confined).and_then(|name| entry_in(dir, &name, report))
48 {
49 return Ok(main_path);
50 }
51
52 let mut ignored_names: rustc_hash::FxHashSet<PathBuf> = rustc_hash::FxHashSet::default();
61 if let Some(content) = readme_text(dir, "00README.XXX", confined) {
62 for line in content.lines() {
63 let parts: Vec<&str> = line.split_whitespace().collect();
64 if parts.len() < 2 {
65 continue;
66 }
67 match parts[1] {
68 "toplevelfile" => {
69 if let Some(main_path) = entry_in(dir, parts[0], report) {
70 return Ok(main_path);
71 }
72 },
73 "ignore" => {
74 ignored_names.insert(dir.join(parts[0]));
75 },
76 _ => {},
77 }
78 }
79 }
80
81 let mut tex_files: Vec<PathBuf> = Vec::new();
83 collect_tex_files(dir, &mut tex_files, false, confined);
84 if !ignored_names.is_empty() {
85 tex_files.retain(|p| !ignored_names.contains(p));
86 }
87 let candidates_before_pdf_filter = tex_files.len();
88 tex_files.retain(|p| !is_pdf_magic(p));
89 if tex_files.is_empty() && candidates_before_pdf_filter > 0 {
90 return Err(s(
91 "Fatal:invalid:not_tex_source PDF magic detected in source file (no TeX-format files in archive)",
92 ));
93 }
94 if tex_files.is_empty() {
95 collect_tex_files(dir, &mut tex_files, true, confined);
96 tex_files.retain(|p| !is_pdf_magic(p));
97 if !ignored_names.is_empty() {
98 tex_files.retain(|p| !ignored_names.contains(p));
99 }
100 }
101 if tex_files.is_empty() {
102 return Err(s("No .tex files found in directory"));
103 }
104
105 let mut likelihood: rustc_hash::FxHashMap<PathBuf, f32> = rustc_hash::FxHashMap::default();
107 let mut vetoed: Vec<(PathBuf, PathBuf)> = Vec::new();
112 let mut drivers: rustc_hash::FxHashSet<PathBuf> = rustc_hash::FxHashSet::default();
117 let mut had_auto_ignore = false;
118
119 for tex_file in &tex_files {
120 if !tex_file.exists() {
121 continue;
122 }
123 let Ok(raw) = std::fs::read(tex_file) else {
124 continue;
125 };
126 let content = String::from_utf8_lossy(&raw);
127 let mut maybe_tex = false;
128 let mut maybe_tex_priority = false;
129 let mut maybe_tex_priority2 = false;
130 let mut determined = false;
131
132 for (lineno, raw_line) in content.lines().enumerate() {
133 let lineno1 = lineno + 1;
134 if lineno1 <= 10
136 && (RE_AUTOIGNORE.is_match(raw_line)
137 || RE_TEXINFO.is_match(raw_line)
138 || RE_AUTOINCLUDE.is_match(raw_line))
139 {
140 likelihood.insert(tex_file.clone(), 0.0);
141 if RE_AUTOIGNORE.is_match(raw_line) {
142 had_auto_ignore = true;
143 }
144 determined = true;
145 break;
146 }
147 if lineno1 <= 12
148 && let Some(cap) = RE_FORMAT_HINT.captures(raw_line)
149 {
150 let fmt = &cap[1];
151 if fmt == "latex209" || fmt == "biglatex" || fmt == "latex" || fmt == "LaTeX" {
152 likelihood.insert(tex_file.clone(), 3.0);
153 } else {
154 likelihood.insert(tex_file.clone(), 1.0);
155 }
156 determined = true;
157 break;
158 }
159 let stripped: std::borrow::Cow<str> = RE_STRIP_COMMENT.replacen(raw_line, 1, "");
163 let line: &str = &stripped;
164
165 if RE_DOCCLASS.is_match(line) {
166 likelihood.insert(tex_file.clone(), 3.0);
167 determined = true;
168 break;
169 }
170 if RE_MAYBE_TEX.is_match(line) {
171 maybe_tex = true;
172 }
173 if RE_BEGIN_DOCUMENT.is_match(line) {
174 drivers.insert(tex_file.clone());
175 }
176 if let Some(cap) = RE_INPUT_INCLUDE.captures(line) {
178 maybe_tex = true;
179 let mut vetoed_name = cap[1].to_string();
180 if RE_AMSTEX.is_match(&vetoed_name) {
181 likelihood.insert(tex_file.clone(), 2.0);
182 determined = true;
183 break;
184 }
185 if !vetoed_name.contains('.') {
186 vetoed_name = vetoed_name.trim_end().to_string() + ".tex";
187 }
188 let base_dir = tex_file.parent().unwrap_or(dir);
189 vetoed.push((base_dir.join(&vetoed_name), tex_file.clone()));
190 }
191 if RE_END_BYE.is_match(line) {
192 maybe_tex_priority = true;
193 }
194 if RE_END_BYE2.is_match(line) {
195 maybe_tex_priority2 = true;
196 }
197 if RE_MAC_TEX.is_match(line) {
198 likelihood.insert(tex_file.clone(), 1.0);
199 determined = true;
200 break;
201 }
202 if RE_METAFONT.is_match(line) {
203 likelihood.insert(tex_file.clone(), 0.0);
204 determined = true;
205 break;
206 }
207 if RE_BIBTEX.is_match(raw_line) {
208 likelihood.insert(tex_file.clone(), 0.0);
209 determined = true;
210 break;
211 }
212 if RE_UUENCODE.is_match(raw_line) {
213 if maybe_tex_priority {
214 likelihood.insert(tex_file.clone(), 2.0);
215 } else if maybe_tex {
216 likelihood.insert(tex_file.clone(), 1.0);
217 } else {
218 likelihood.insert(tex_file.clone(), 0.0);
219 }
220 determined = true;
221 break;
222 }
223 if RE_WITHDRAWN.is_match(line) {
224 likelihood.insert(tex_file.clone(), 0.0);
225 determined = true;
226 break;
227 }
228 }
229 if !determined {
230 let score = if maybe_tex_priority {
231 2.0
232 } else if maybe_tex_priority2 {
233 1.5
234 } else if maybe_tex {
235 1.0
236 } else {
237 0.0
238 };
239 likelihood.insert(tex_file.clone(), score);
240 }
241 }
242
243 for (vetee, vetoer) in &vetoed {
244 let vetee_score = likelihood.get(vetee).copied().unwrap_or(0.0);
245 let vetoer_score = likelihood.get(vetoer).copied().unwrap_or(0.0);
246 if vetoer_score >= vetee_score || drivers.contains(vetoer) {
247 likelihood.remove(vetee);
248 }
249 }
250
251 let mut candidates: Vec<PathBuf> = likelihood
252 .keys()
253 .filter(|f| likelihood[*f] > 0.0)
254 .cloned()
255 .collect();
256 candidates.sort_by(|a, b| likelihood[b].partial_cmp(&likelihood[a]).unwrap());
257
258 if candidates.is_empty() {
259 if had_auto_ignore {
260 let dir_name = dir.file_name().and_then(|s| s.to_str()).unwrap_or_default();
269 let auto_ignore_main = tex_files
270 .iter()
271 .find(|p| {
272 p.file_stem()
273 .and_then(|s| s.to_str())
274 .is_some_and(|stem| stem == dir_name)
275 })
276 .cloned()
277 .or_else(|| tex_files.first().cloned());
278 if let Some(p) = auto_ignore_main {
279 return Ok(p);
280 }
281 }
282 return Err(s("No viable .tex files found in directory"));
283 }
284
285 let max_score = likelihood[&candidates[0]];
286 candidates.retain(|f| (likelihood[f] - max_score).abs() < f32::EPSILON);
287
288 if candidates.len() > 1 {
289 let min_depth = candidates
290 .iter()
291 .map(|f| f.strip_prefix(dir).unwrap_or(f).components().count())
292 .min()
293 .unwrap_or(0);
294 candidates.retain(|f| f.strip_prefix(dir).unwrap_or(f).components().count() == min_depth);
295 }
296
297 if candidates.len() > 1 {
317 let bbl_candidates: Vec<PathBuf> = candidates
318 .iter()
319 .filter(|f| has_bbl(f, dir, confined))
320 .cloned()
321 .collect();
322 if !bbl_candidates.is_empty() {
323 candidates = bbl_candidates;
324 }
325 }
326
327 if candidates.len() > 1 {
328 let pdf_candidates: Vec<PathBuf> = candidates
329 .iter()
330 .filter(|f| has_pdftex_marker(f))
331 .cloned()
332 .collect();
333 if !pdf_candidates.is_empty() {
334 candidates = pdf_candidates;
335 }
336 }
337
338 if candidates.len() > 1 {
339 let common: Vec<PathBuf> = candidates
340 .iter()
341 .filter(|f| {
342 f.file_name().is_some_and(|n| {
343 let n = n.to_str().unwrap_or("");
344 n == "main.tex" || n == "ms.tex" || n == "paper.tex"
345 })
346 })
347 .cloned()
348 .collect();
349 if !common.is_empty() {
350 candidates = common;
351 }
352 }
353
354 candidates.sort();
355 Ok(
356 candidates
357 .into_iter()
358 .next()
359 .expect("non-empty after filtering"),
360 )
361}
362
363pub fn find_top_level_texs(dir: &Path, confined: bool) -> Result<Vec<PathBuf>, String> {
385 let explicit = explicit_top_levels(dir, confined);
387 if explicit.len() >= 2 {
388 return Ok(order_main_first(explicit, dir));
389 }
390 let main = main_tex_in(dir, false, confined)?;
392 let mut set = top_level_bbl_docs(dir, &main, confined);
396 if !set.contains(&main) {
397 set.push(main.clone());
398 }
399 let (mut supps, mains): (Vec<PathBuf>, Vec<PathBuf>) =
404 set.into_iter().partition(|f| is_supplement(f));
405 if mains.len() == 1 && !supps.is_empty() {
406 supps.sort();
407 supps.dedup();
408 let mut tops = mains;
409 tops.extend(supps);
410 return Ok(tops);
411 }
412 Ok(vec![main])
414}
415
416fn s(msg: &str) -> String { msg.to_string() }
421
422pub fn readme_entry(dir: &Path, name: &str) -> Option<PathBuf> { entry_in(dir, name, true) }
426
427fn entry_in(dir: &Path, name: &str, report: bool) -> Option<PathBuf> {
429 use std::path::Component;
430 let climbs = Path::new(name).components().any(|c| {
431 matches!(
432 c,
433 Component::ParentDir | Component::RootDir | Component::Prefix(_)
434 )
435 });
436 let path = dir.join(name);
437 if !climbs && !path.is_file() {
438 return None;
439 }
440 let inside = !climbs && latexml_core::util::pathname::opens_inside(&path, dir) == Some(true);
441 if inside {
442 return Some(path);
443 }
444 if report {
445 latexml_core::common::error::warn_at_session_start(
446 "archive",
447 "path",
448 format!(
449 "the 00README names '{name}' as a top-level file outside the source directory; ignored"
450 ),
451 );
452 }
453 None
454}
455
456fn explicit_top_levels(dir: &Path, confined: bool) -> Vec<PathBuf> {
460 let mut out: Vec<PathBuf> = Vec::new();
461 for name in parse_readme_json_all(dir, confined) {
462 if let Some(p) = readme_entry(dir, &name)
463 && !out.contains(&p)
464 {
465 out.push(p);
466 }
467 }
468 if let Some(content) = readme_text(dir, "00README.XXX", confined) {
469 for line in content.lines() {
470 let parts: Vec<&str> = line.split_whitespace().collect();
471 if parts.len() >= 2
472 && parts[1] == "toplevelfile"
473 && let Some(p) = readme_entry(dir, parts[0])
474 && !out.contains(&p)
475 {
476 out.push(p);
477 }
478 }
479 }
480 out
481}
482
483fn top_level_bbl_docs(dir: &Path, main: &Path, confined: bool) -> Vec<PathBuf> {
488 let main_depth = main.strip_prefix(dir).unwrap_or(main).components().count();
489 let ignored = readme_ignored(dir, confined);
490 let mut tex_files: Vec<PathBuf> = Vec::new();
491 collect_tex_files(dir, &mut tex_files, false, confined);
492 tex_files
493 .into_iter()
494 .filter(|f| f.strip_prefix(dir).unwrap_or(f).components().count() == main_depth)
495 .filter(|f| !ignored.contains(f))
496 .filter(|f| !has_auto_ignore(f))
497 .filter(|f| has_bbl(f, dir, confined))
498 .filter(|f| file_has_documentclass(f))
499 .collect()
500}
501
502fn readme_ignored(dir: &Path, confined: bool) -> rustc_hash::FxHashSet<PathBuf> {
505 let mut ignored = rustc_hash::FxHashSet::default();
506 if let Some(content) = readme_text(dir, "00README.XXX", confined) {
507 for line in content.lines() {
508 let parts: Vec<&str> = line.split_whitespace().collect();
509 if parts.len() >= 2 && parts[1] == "ignore" {
510 ignored.insert(dir.join(parts[0]));
511 }
512 }
513 }
514 ignored
515}
516
517fn has_auto_ignore(path: &Path) -> bool {
520 let Ok(raw) = std::fs::read(path) else {
521 return false;
522 };
523 String::from_utf8_lossy(&raw)
524 .lines()
525 .take(10)
526 .any(|l| RE_AUTOIGNORE.is_match(l))
527}
528
529fn order_main_first(mut files: Vec<PathBuf>, _dir: &Path) -> Vec<PathBuf> {
533 files.sort();
534 files.dedup();
535 let (supps, mut mains): (Vec<PathBuf>, Vec<PathBuf>) =
536 files.into_iter().partition(|f| is_supplement(f));
537 if let Some(pos) = mains.iter().position(|f| is_common_main_name(f)) {
538 let m = mains.remove(pos);
539 mains.insert(0, m);
540 }
541 mains.extend(supps);
542 mains
543}
544
545fn is_common_main_name(path: &Path) -> bool {
548 path
549 .file_name()
550 .and_then(|n| n.to_str())
551 .is_some_and(|n| n == "main.tex" || n == "ms.tex" || n == "paper.tex")
552}
553
554fn is_supplement(path: &Path) -> bool {
560 if let Some(stem) = path.file_stem().and_then(|s| s.to_str())
561 && RE_SUPP_NAME.is_match(stem)
562 {
563 return true;
564 }
565 if let Some(title) = first_title(path)
566 && RE_SUPP_TITLE.is_match(&title)
567 {
568 return true;
569 }
570 false
571}
572
573fn file_has_documentclass(path: &Path) -> bool {
576 let Ok(raw) = std::fs::read(path) else {
577 return false;
578 };
579 let content = String::from_utf8_lossy(&raw);
580 content.lines().any(|l| {
581 let stripped = RE_STRIP_COMMENT.replacen(l, 1, "");
582 RE_DOCCLASS.is_match(&stripped)
583 })
584}
585
586fn first_title(path: &Path) -> Option<String> {
589 let raw = std::fs::read(path).ok()?;
590 let content = String::from_utf8_lossy(&raw);
591 let stripped: String = content
594 .lines()
595 .map(|l| RE_STRIP_COMMENT.replacen(l, 1, "").into_owned())
596 .collect::<Vec<_>>()
597 .join("\n");
598 RE_TITLE_ARG
599 .captures(&stripped)
600 .map(|c| c[1].chars().take(120).collect())
601}
602
603fn parse_readme_json_all(dir: &Path, confined: bool) -> Vec<String> {
607 let mut out = Vec::new();
608 let Some(content) = readme_text(dir, "00README.json", confined) else {
609 return out;
610 };
611 let Some(sources_start) = content.find("\"sources\"") else {
612 return out;
613 };
614 let rest = &content[sources_start..];
615 let (Some(arr_start), Some(arr_end)) = (rest.find('['), rest.find(']')) else {
616 return out;
617 };
618 let arr = &rest[arr_start + 1..arr_end];
619 for obj_str in arr.split('}') {
620 if !obj_str.contains("\"toplevel\"") {
621 continue;
622 }
623 if let Some(fn_pos) = obj_str.find("\"filename\"") {
624 let after = obj_str[fn_pos + 10..].trim_start();
625 if let Some(after) = after.strip_prefix(':') {
626 let after = after.trim_start();
627 if let Some(after) = after.strip_prefix('"') {
628 let name: String = after
629 .chars()
630 .take_while(|&c| c != '"')
631 .filter(|&c| c != '\\')
632 .collect();
633 if !name.is_empty() {
634 out.push(name);
635 }
636 }
637 }
638 }
639 }
640 out
641}
642
643fn collect_tex_files(dir: &Path, files: &mut Vec<PathBuf>, fallback: bool, confined: bool) {
650 let mut found = Vec::new();
651 collect_tex_files_under(dir, &mut found, fallback);
652 files.extend(
653 found
654 .into_iter()
655 .filter(|file| opens_in(file, dir, confined)),
656 );
657}
658
659fn opens_in(file: &Path, dir: &Path, confined: bool) -> bool {
661 !confined || latexml_core::util::pathname::opens_inside(file, dir) == Some(true)
662}
663
664fn has_bbl(file: &Path, dir: &Path, confined: bool) -> bool {
667 let bbl = file.with_extension("bbl");
668 if confined {
669 opens_in(&bbl, dir, true)
670 } else {
671 bbl.exists()
672 }
673}
674
675pub fn readme_text(dir: &Path, name: &str, confined: bool) -> Option<String> {
678 let path = dir.join(name);
679 opens_in(&path, dir, confined)
680 .then(|| std::fs::read_to_string(&path).ok())
681 .flatten()
682}
683
684fn collect_tex_files_under(dir: &Path, files: &mut Vec<PathBuf>, fallback: bool) {
685 if let Ok(entries) = std::fs::read_dir(dir) {
686 for entry in entries.flatten() {
687 let path = entry.path();
688 if entry.file_type().is_ok_and(|kind| kind.is_dir()) {
691 collect_tex_files_under(&path, files, fallback);
692 } else if path.is_dir() {
693 continue;
694 } else if !fallback {
695 if path.extension().is_some_and(|e| {
696 let e = e.to_ascii_lowercase();
697 e == "tex" || e == "txt" || e == "ltx"
698 }) {
699 files.push(path);
700 }
701 } else {
702 let ext_opt = path.extension().and_then(|e| e.to_str());
703 let keep = match ext_opt {
704 None => true,
705 Some(ext) => ext.len() >= 4,
706 };
707 if keep {
708 files.push(path);
709 }
710 }
711 }
712 }
713}
714
715fn has_pdftex_marker(path: &Path) -> bool {
733 let Ok(raw) = std::fs::read(path) else {
734 return false;
735 };
736 let content = String::from_utf8_lossy(&raw);
737 content
738 .lines()
739 .any(|line| RE_PDF_INCLUDE.is_match(line) || RE_PDFOUTPUT.is_match(line))
740}
741
742pub fn is_pdf_magic(path: &Path) -> bool {
745 let mut buf = [0u8; 5];
746 if let Ok(mut f) = std::fs::File::open(path) {
747 use std::io::Read;
748 if f.read(&mut buf).is_ok_and(|n| n == 5) {
749 return &buf == b"%PDF-";
750 }
751 }
752 false
753}
754
755fn parse_readme_json(dir: &Path, confined: bool) -> Option<String> {
760 parse_readme_json_all(dir, confined).into_iter().next()
761}
762
763static RE_AUTOIGNORE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"%auto-ignore").unwrap());
770static RE_TEXINFO: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"\\input texinfo").unwrap());
771static RE_AUTOINCLUDE: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"%auto-include").unwrap());
772static RE_FORMAT_HINT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^\r?%&(\S+)").unwrap());
773static RE_DOCCLASS: LazyLock<Regex> =
774 LazyLock::new(|| Regex::new(r"(?:^|\r)\s*\\document(?:style|class)").unwrap());
775static RE_MAYBE_TEX: LazyLock<Regex> = LazyLock::new(|| {
776 Regex::new(r"(?:^|\r)\s*\\(?:font|magnification|input|def|special|baselineskip|begin)").unwrap()
777});
778static RE_INPUT_INCLUDE: LazyLock<Regex> =
779 LazyLock::new(|| Regex::new(r"\\(?:input|include)(?:\s+|\{)([^ \}]+)").unwrap());
780static RE_END_BYE: LazyLock<Regex> =
781 LazyLock::new(|| Regex::new(r"(?:^|\r)\s*\\(?:end|bye)(?:\s|$)").unwrap());
782static RE_END_BYE2: LazyLock<Regex> =
783 LazyLock::new(|| Regex::new(r"\\(?:end|bye)(?:\s|$)").unwrap());
784static RE_BEGIN_DOCUMENT: LazyLock<Regex> =
785 LazyLock::new(|| Regex::new(r"\\begin\s*\{document\}").unwrap());
786static RE_MAC_TEX: LazyLock<Regex> =
787 LazyLock::new(|| Regex::new(r"\\input *(?:harv|lanl)mac|\\input\s+phyzzx").unwrap());
788static RE_METAFONT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"beginchar\(").unwrap());
789static RE_BIBTEX: LazyLock<Regex> =
790 LazyLock::new(|| Regex::new(r"(?i)(?:^|\r)@(?:book|article|inbook|unpublished)\{").unwrap());
791static RE_UUENCODE: LazyLock<Regex> =
792 LazyLock::new(|| Regex::new(r"^begin \d{1,4}\s+\S+\r?$").unwrap());
793static RE_WITHDRAWN: LazyLock<Regex> =
794 LazyLock::new(|| Regex::new(r"paper deliberately replaced by what little").unwrap());
795static RE_AMSTEX: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"^amstex$").unwrap());
796static RE_PDF_INCLUDE: LazyLock<Regex> = LazyLock::new(|| {
799 Regex::new(r"(?i)^[^%]*\\includegraphics[^%]*\.(?:pdf|png|gif|jpg)\s?\}").unwrap()
800});
801static RE_PDFOUTPUT: LazyLock<Regex> =
803 LazyLock::new(|| Regex::new(r"^[^%]*\\pdfoutput\s*=\s*1").unwrap());
804static RE_SUPP_NAME: LazyLock<Regex> = LazyLock::new(|| {
808 Regex::new(r"(?i)(^|[_-])(supp(lement(ary|al)?)?|supporting|supplemental|appendix|si|sm)([_-]|$)")
809 .unwrap()
810});
811static RE_SUPP_TITLE: LazyLock<Regex> = LazyLock::new(|| {
814 Regex::new(r"(?i)(supplement|supporting\s+information|supplemental|appendix)").unwrap()
815});
816static RE_TITLE_ARG: LazyLock<Regex> =
818 LazyLock::new(|| Regex::new(r"\\(?:icml)?title\s*(?:\[[^\]]*\])?\s*\{([^}]*)").unwrap());
819static RE_STRIP_COMMENT: LazyLock<Regex> = LazyLock::new(|| Regex::new(r"%[^\r]*").unwrap());
822
823#[cfg(test)]
824mod tests {
825 use tempfile::tempdir;
826
827 use super::*;
828
829 fn write(dir: &Path, name: &str, body: &str) { std::fs::write(dir.join(name), body).unwrap(); }
830
831 #[test]
832 fn picks_documentclass_over_input_only_file() {
833 let d = tempdir().unwrap();
834 write(
835 d.path(),
836 "main.tex",
837 "\\documentclass{article}\n\\begin{document}x\\end{document}",
838 );
839 write(d.path(), "intro.tex", "\\input{intro_body}\n");
840 let pick = find_main_tex(d.path(), false).unwrap();
841 assert_eq!(pick.file_name().unwrap(), "main.tex");
842 }
843
844 #[test]
848 fn driver_vetoes_the_preamble_it_inputs() {
849 let d = tempdir().unwrap();
850 write(
851 d.path(),
852 "paper.tex",
853 "\\input{preamble}\n\\begin{document}\nMain body text.\n\\end{document}\n",
854 );
855 write(
856 d.path(),
857 "preamble.tex",
858 "\\documentclass{article}\n\\usepackage{amsmath}\n",
859 );
860 let pick = find_main_tex(d.path(), false).unwrap();
861 assert_eq!(pick.file_name().unwrap(), "paper.tex");
862 }
863
864 #[test]
865 fn wrapper_without_begin_document_keeps_its_main() {
866 let d = tempdir().unwrap();
867 write(d.path(), "wrapper.tex", "%\n\\input{main}\n");
868 write(
869 d.path(),
870 "main.tex",
871 "\\documentclass{article}\n\\begin{document}x\\end{document}\n",
872 );
873 let pick = find_main_tex(d.path(), false).unwrap();
874 assert_eq!(pick.file_name().unwrap(), "main.tex");
875 }
876
877 #[test]
878 fn errors_when_directory_has_no_tex() {
879 let d = tempdir().unwrap();
880 let err = find_main_tex(d.path(), false).unwrap_err();
881 assert!(err.contains("No .tex files"));
882 }
883
884 #[test]
885 fn prefers_main_over_other_documentclass_files() {
886 let d = tempdir().unwrap();
887 write(d.path(), "draft.tex", "\\documentclass{article}\n");
888 write(d.path(), "main.tex", "\\documentclass{article}\n");
889 let pick = find_main_tex(d.path(), false).unwrap();
890 assert_eq!(pick.file_name().unwrap(), "main.tex");
891 }
892
893 #[test]
894 fn readme_xxx_toplevelfile_directive_short_circuits() {
895 let d = tempdir().unwrap();
896 write(d.path(), "draft.tex", "\\documentclass{article}\n");
899 write(d.path(), "main.tex", "\\documentclass{article}\n");
900 write(d.path(), "00README.XXX", "draft.tex toplevelfile\n");
901 let pick = find_main_tex(d.path(), false).unwrap();
902 assert_eq!(pick.file_name().unwrap(), "draft.tex");
903 }
904
905 #[test]
906 fn readme_xxx_ignore_directive_excludes_candidate() {
907 let d = tempdir().unwrap();
908 write(d.path(), "old.tex", "\\documentclass{article}\n");
913 write(d.path(), "main.tex", "\\documentclass{article}\n");
914 write(d.path(), "00README.XXX", "main.tex ignore\n");
915 let pick = find_main_tex(d.path(), false).unwrap();
916 assert_eq!(pick.file_name().unwrap(), "old.tex");
917 }
918
919 #[test]
920 fn readme_xxx_mixed_directives() {
921 let d = tempdir().unwrap();
922 write(d.path(), "intro.tex", "\\documentclass{article}\n");
923 write(d.path(), "paper.tex", "\\documentclass{article}\n");
924 write(d.path(), "junk.tex", "\\documentclass{article}\n");
925 write(
929 d.path(),
930 "00README.XXX",
931 "junk.tex ignore\npaper.tex toplevelfile\n",
932 );
933 let pick = find_main_tex(d.path(), false).unwrap();
934 assert_eq!(pick.file_name().unwrap(), "paper.tex");
935 }
936
937 #[test]
944 fn bbl_sibling_outranks_pdf_include_marker() {
945 let d = tempdir().unwrap();
946 write(
947 d.path(),
948 "main.tex",
949 "\\documentclass{IEEEtran}\n\\input{sections/intro}\n\\begin{document}\\title{Real}\\end{document}",
950 );
951 write(
952 d.path(),
953 "New_IEEEtran_how-to.tex",
954 "\\documentclass{IEEEtran}\n\\includegraphics[width=1in]{fig1.png}\n\\begin{document}How to.\\end{document}",
955 );
956 write(
957 d.path(),
958 "main.bbl",
959 "\\begin{thebibliography}{1}\\end{thebibliography}\n",
960 );
961 let pick = find_main_tex(d.path(), false).unwrap();
962 assert_eq!(pick.file_name().unwrap(), "main.tex");
963 }
964
965 #[test]
969 fn reorder_preserves_common_name_when_multiple_bbl() {
970 let d = tempdir().unwrap();
971 write(
972 d.path(),
973 "aaa.tex",
974 "\\documentclass{article}\n\\includegraphics{x.png}\n",
975 );
976 write(
977 d.path(),
978 "main.tex",
979 "\\documentclass{article}\n\\includegraphics{y.png}\n",
980 );
981 write(d.path(), "aaa.bbl", "");
982 write(d.path(), "main.bbl", "");
983 let pick = find_main_tex(d.path(), false).unwrap();
984 assert_eq!(pick.file_name().unwrap(), "main.tex");
985 }
986
987 #[test]
993 fn strict_pdf_marker_rejects_extensionless_eps_and_comments() {
994 let d = tempdir().unwrap();
995 write(
997 d.path(),
998 "example_paper.tex",
999 "\\centerline{\\includegraphics[width=\\columnwidth]{icml_numpapers}}\nResults saved as results.png.\n",
1000 );
1001 write(
1003 d.path(),
1004 "rebuttal.tex",
1005 "\\includegraphics[width=0.8\\linewidth]{egfigure.eps}\n",
1006 );
1007 write(d.path(), "commented.tex", "%\\includegraphics{fig.png}\n");
1009 assert!(!has_pdftex_marker(&d.path().join("example_paper.tex")));
1010 assert!(!has_pdftex_marker(&d.path().join("rebuttal.tex")));
1011 assert!(!has_pdftex_marker(&d.path().join("commented.tex")));
1012 }
1013
1014 #[test]
1015 fn strict_pdf_marker_accepts_arg_extension_and_pdfoutput() {
1016 let d = tempdir().unwrap();
1017 write(
1018 d.path(),
1019 "fig.tex",
1020 "\\includegraphics[width=2in]{diagram.pdf}\n",
1021 );
1022 write(d.path(), "gif.tex", "\\includegraphics{anim.gif}\n"); write(
1024 d.path(),
1025 "pdfout.tex",
1026 "\\pdfoutput=1\n\\includegraphics{noext}\n",
1027 );
1028 assert!(has_pdftex_marker(&d.path().join("fig.tex")));
1029 assert!(has_pdftex_marker(&d.path().join("gif.tex")));
1030 assert!(has_pdftex_marker(&d.path().join("pdfout.tex")));
1031 }
1032
1033 #[test]
1037 fn top_level_texs_appends_supplement() {
1038 let d = tempdir().unwrap();
1039 write(
1040 d.path(),
1041 "main.tex",
1042 "\\documentclass{article}\n\\title{Quantum error correction}\n",
1043 );
1044 write(
1045 d.path(),
1046 "supplement.tex",
1047 "\\documentclass{article}\n\\title{Supplementary Information for Quantum error correction}\n",
1048 );
1049 write(d.path(), "main.bbl", "");
1050 write(d.path(), "supplement.bbl", "");
1051 let tops = find_top_level_texs(d.path(), false).unwrap();
1052 let names: Vec<_> = tops
1053 .iter()
1054 .map(|p| p.file_name().unwrap().to_str().unwrap())
1055 .collect();
1056 assert_eq!(names, vec!["main.tex", "supplement.tex"]);
1057 assert_eq!(find_main_tex(d.path(), false).unwrap(), tops[0]);
1059 }
1060
1061 #[test]
1064 fn top_level_texs_orders_main_first_despite_alpha() {
1065 let d = tempdir().unwrap();
1066 write(
1067 d.path(),
1068 "Note.tex",
1069 "\\documentclass{article}\n\\title{Bayesian Inference of the Landau Parameter}\n",
1070 );
1071 write(
1072 d.path(),
1073 "Appendix.tex",
1074 "\\documentclass{article}\n\\title{SUPPLEMENTAL MATERIALS}\n",
1075 );
1076 write(d.path(), "Note.bbl", "");
1077 write(d.path(), "Appendix.bbl", "");
1078 let tops = find_top_level_texs(d.path(), false).unwrap();
1079 let names: Vec<_> = tops
1080 .iter()
1081 .map(|p| p.file_name().unwrap().to_str().unwrap())
1082 .collect();
1083 assert_eq!(names, vec!["Note.tex", "Appendix.tex"]);
1084 }
1085
1086 #[test]
1089 fn top_level_texs_excludes_template_without_bbl() {
1090 let d = tempdir().unwrap();
1091 write(
1092 d.path(),
1093 "main.tex",
1094 "\\documentclass{IEEEtran}\n\\input{sec}\n\\title{Real Paper}\n",
1095 );
1096 write(
1097 d.path(),
1098 "New_IEEEtran_how-to.tex",
1099 "\\documentclass{IEEEtran}\n\\includegraphics{fig1.png}\n\\title{How to Use the IEEEtran Templates}\n",
1100 );
1101 write(d.path(), "main.bbl", "");
1102 let tops = find_top_level_texs(d.path(), false).unwrap();
1103 let names: Vec<_> = tops
1104 .iter()
1105 .map(|p| p.file_name().unwrap().to_str().unwrap())
1106 .collect();
1107 assert_eq!(names, vec!["main.tex"]);
1108 }
1109
1110 #[test]
1113 fn supplement_without_bbl_is_not_detected() {
1114 let d = tempdir().unwrap();
1115 write(
1116 d.path(),
1117 "main.tex",
1118 "\\documentclass{article}\n\\title{Real Paper}\n",
1119 );
1120 write(
1121 d.path(),
1122 "supp.tex",
1123 "\\documentclass{article}\n\\title{Supplementary Information}\n",
1124 );
1125 write(d.path(), "main.bbl", "");
1126 let tops = find_top_level_texs(d.path(), false).unwrap();
1127 assert_eq!(tops.len(), 1);
1128 assert_eq!(tops[0].file_name().unwrap(), "main.tex");
1129 }
1130
1131 #[test]
1134 fn readme_two_toplevelfiles_ordered_main_first() {
1135 let d = tempdir().unwrap();
1136 write(
1137 d.path(),
1138 "main.tex",
1139 "\\documentclass{article}\n\\title{Paper}\n",
1140 );
1141 write(
1142 d.path(),
1143 "si.tex",
1144 "\\documentclass{article}\n\\title{Supporting Information}\n",
1145 );
1146 write(
1147 d.path(),
1148 "00README.XXX",
1149 "si.tex toplevelfile\nmain.tex toplevelfile\n",
1150 );
1151 let tops = find_top_level_texs(d.path(), false).unwrap();
1152 let names: Vec<_> = tops
1153 .iter()
1154 .map(|p| p.file_name().unwrap().to_str().unwrap())
1155 .collect();
1156 assert_eq!(names, vec!["main.tex", "si.tex"]);
1157 }
1158
1159 #[test]
1162 fn readme_entries_outside_the_source_directory_are_ignored() {
1163 use latexml_core::common::error::{LogStatus, get_status, log_session_warnings};
1164 let root = tempdir().unwrap();
1165 let (src, out) = (root.path().join("src"), root.path().join("x"));
1166 std::fs::create_dir_all(src.join("sub")).unwrap();
1167 std::fs::create_dir_all(&out).unwrap();
1168 let canary = out.join("canary.tex");
1169 write(&out, "canary.tex", "\\documentclass{article}\n");
1170 let abs = canary.to_string_lossy().into_owned();
1171 #[cfg(unix)]
1172 std::os::unix::fs::symlink(&canary, src.join("link.tex")).unwrap();
1173 let json =
1174 |name: &str| format!(r#"{{"sources":[{{"filename":"{name}","usage":"toplevel"}}]}}"#);
1175 let mut rows: Vec<(&str, String, &str, usize)> = vec![
1176 ("00README.json", json("../x/canary.tex"), "main.tex", 1),
1177 ("00README.json", json(&abs), "main.tex", 1),
1178 (
1179 "00README.XXX",
1180 "../x/canary.tex toplevelfile\n".into(),
1181 "main.tex",
1182 1,
1183 ),
1184 (
1185 "00README.XXX",
1186 format!("{abs} toplevelfile\n"),
1187 "main.tex",
1188 1,
1189 ),
1190 ("00README.json", json("sub/../sub/paper.tex"), "main.tex", 1),
1191 ("00README.json", json("sub/paper.tex"), "sub/paper.tex", 0),
1192 ("00README.json", json("absent.tex"), "main.tex", 0),
1193 ("00README.XXX", ". toplevelfile\n".into(), "main.tex", 0),
1194 ("00README.json", json("sub"), "main.tex", 0),
1195 ];
1196 #[cfg(unix)]
1197 rows.push((
1198 "00README.XXX",
1199 "link.tex toplevelfile\n".into(),
1200 "main.tex",
1201 1,
1202 ));
1203 #[cfg(windows)]
1204 rows.push((
1205 "00README.XXX",
1206 "..\\x\\canary.tex toplevelfile\n".into(),
1207 "main.tex",
1208 1,
1209 ));
1210 let deep = [
1213 "d".repeat(60),
1214 "e".repeat(60),
1215 "f".repeat(60),
1216 "g".repeat(60),
1217 ]
1218 .join("/");
1219 std::fs::create_dir_all(src.join(&deep)).unwrap();
1220 write(&src.join(&deep), "paper.tex", "\\input{x}\n");
1221 let deep = format!("{deep}/paper.tex");
1222 rows.push(("00README.json", json(&deep), deep.as_str(), 0));
1223 for (readme, body, pick, warnings) in rows {
1224 for name in ["00README.json", "00README.XXX"] {
1225 let _ = std::fs::remove_file(src.join(name));
1226 }
1227 write(
1228 &src,
1229 "main.tex",
1230 "\\documentclass{article}\n\\begin{document}x\\end{document}\n",
1231 );
1232 write(&src.join("sub"), "paper.tex", "\\input{x}\n");
1233 write(&src, readme, &body);
1234 let before = get_status(LogStatus::Warning);
1235 let main = find_main_tex(&src, true).unwrap();
1236 let tops = find_top_level_texs(&src, true).unwrap();
1238 log_session_warnings();
1239 assert_eq!(main, src.join(pick), "{readme}: {body}");
1240 assert_eq!(tops, vec![main], "{readme}: {body}");
1241 assert_eq!(
1242 get_status(LogStatus::Warning) - before,
1243 2 * warnings,
1244 "{readme}: {body}"
1245 );
1246 }
1247 }
1248}