1use std::{
18 fs,
19 io::{self, Write},
20 path::{Path, PathBuf},
21 sync::atomic::{AtomicU64, Ordering},
22};
23
24use libxml::tree::{Node, SaveOptions};
25
26use crate::{
27 document::{PostDocument, get_xml_id},
28 processor::{PostError, ProcessResult, Processor},
29};
30
31pub fn write_output(content: &str, dest: Option<&str>) -> io::Result<()> {
38 match dest {
39 Some(path) => {
40 ensure_parent_dir(path)?;
41 fs::write(path, content)?;
42 Info!(
43 "writer",
44 "wrote",
45 "Wrote '{}' ({} bytes)",
46 path,
47 content.len()
48 );
49 Ok(())
50 },
51 None => io::stdout().write_all(content.as_bytes()),
52 }
53}
54
55pub fn write_output_segments(segments: &[&str], dest: Option<&str>) -> io::Result<()> {
63 match dest {
64 Some(path) => {
65 ensure_parent_dir(path)?;
66 let mut writer = io::BufWriter::new(fs::File::create(path)?);
67 let mut total = 0usize;
68 for seg in segments {
69 writer.write_all(seg.as_bytes())?;
70 total += seg.len();
71 }
72 writer.flush()?;
73 Info!("writer", "wrote", "Wrote '{}' ({} bytes)", path, total);
74 Ok(())
75 },
76 None => {
77 let stdout = io::stdout();
78 let mut handle = stdout.lock();
79 for seg in segments {
80 handle.write_all(seg.as_bytes())?;
81 }
82 Ok(())
83 },
84 }
85}
86
87pub fn ensure_parent_dir(path: &str) -> io::Result<()> {
91 if let Some(parent) = Path::new(path).parent() {
92 if !parent.as_os_str().is_empty() {
93 fs::create_dir_all(parent)?;
94 }
95 }
96 Ok(())
97}
98
99#[derive(Debug, Default)]
103pub struct MadeDirs(std::collections::HashSet<PathBuf>);
104
105std::thread_local! {
106 static DIRS_MADE: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
107}
108
109pub fn made_dir_count() -> usize { DIRS_MADE.get() }
111
112impl MadeDirs {
113 pub fn ensure_parent(&mut self, path: &str) -> io::Result<()> {
115 let Some(parent) = Path::new(path).parent() else {
116 return Ok(());
117 };
118 if parent.as_os_str().is_empty() || self.0.contains(parent) {
119 return Ok(());
120 }
121 DIRS_MADE.set(DIRS_MADE.get() + 1);
122 fs::create_dir_all(parent)?;
123 self.0.insert(parent.to_path_buf());
124 Ok(())
125 }
126}
127
128static ATOMIC_TMP_SEQ: AtomicU64 = AtomicU64::new(0);
130
131pub struct Staged {
142 path: PathBuf,
143 _on_exit: latexml_core::watchdog::RemoveOnExit,
144}
145
146impl Staged {
147 pub fn beside(dest: &Path) -> Self { Self::at(free_path(dest)) }
150
151 fn create(dest: &Path) -> io::Result<(Self, fs::File)> { Self::create_at(|| free_path(dest)) }
153
154 fn create_at(next: impl Fn() -> PathBuf) -> io::Result<(Self, fs::File)> {
156 loop {
157 let path = next();
158 match fs::OpenOptions::new()
159 .write(true)
160 .create_new(true)
161 .open(&path)
162 {
163 Ok(file) => return Ok((Self::at(path), file)),
164 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
165 Err(e) => return Err(e),
166 }
167 }
168 }
169
170 fn link_at(src: &Path, next: impl Fn() -> PathBuf) -> io::Result<Option<Self>> {
172 loop {
173 let path = next();
174 match fs::hard_link(src, &path) {
175 Ok(()) => return Ok(Some(Self::at(path))),
176 Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue,
177 Err(e)
179 if matches!(
180 e.kind(),
181 io::ErrorKind::CrossesDevices
182 | io::ErrorKind::PermissionDenied
183 | io::ErrorKind::TooManyLinks
184 | io::ErrorKind::Unsupported
185 ) =>
186 {
187 return Ok(None);
188 },
189 Err(e) => return Err(e),
190 }
191 }
192 }
193
194 pub fn alias(src: &Path) -> io::Result<Self> {
197 let ext = src.extension().and_then(|e| e.to_str());
198 let next = || free_alias_path(ext);
199 if let Ok(Some(alias)) = Self::link_at(src, next) {
200 return Ok(alias);
201 }
202 let (alias, file) = Self::create_at(next)?;
203 drop(file);
204 fs::copy(src, alias.path())?;
205 Ok(alias)
206 }
207
208 fn at(path: PathBuf) -> Self {
209 let _on_exit = latexml_core::watchdog::remove_on_exit(&path);
210 Staged { path, _on_exit }
211 }
212
213 pub fn path(&self) -> &Path { &self.path }
214
215 pub fn install(self, dest: &Path) -> io::Result<()> {
220 match fs::rename(&self.path, dest) {
221 Ok(()) => Ok(()),
222 Err(_) if same_bytes(&self.path, dest) => Ok(()),
223 Err(e) => Err(e),
224 }
225 }
226}
227
228const NAME_KEPT: usize = 64;
230
231pub fn bounded_name(name: &str) -> std::borrow::Cow<'_, str> {
235 use std::hash::{Hash, Hasher};
236 if name.len() <= NAME_KEPT {
237 return name.into();
238 }
239 let mut cut = NAME_KEPT;
240 while !name.is_char_boundary(cut) {
241 cut -= 1;
242 }
243 let mut hasher = std::hash::DefaultHasher::new();
244 name.hash(&mut hasher);
245 format!("{}~{:016x}", &name[..cut], hasher.finish()).into()
246}
247
248fn staged_path(dest: &Path, seq: u64) -> PathBuf {
251 let pid = std::process::id();
252 let stem = bounded_name(
253 dest
254 .file_stem()
255 .and_then(|n| n.to_str())
256 .unwrap_or("resource"),
257 );
258 let name = match dest.extension().and_then(|e| e.to_str()) {
259 Some(ext) => format!(".{stem}.tmp.{pid}.{seq}.{ext}"),
260 None => format!(".{stem}.tmp.{pid}.{seq}"),
261 };
262 match dest.parent() {
263 Some(p) if !p.as_os_str().is_empty() => p.join(name),
264 _ => PathBuf::from(name),
265 }
266}
267
268fn free_path(dest: &Path) -> PathBuf {
271 loop {
272 let path = staged_path(dest, ATOMIC_TMP_SEQ.fetch_add(1, Ordering::Relaxed));
273 if fs::symlink_metadata(&path).is_err() {
274 return path;
275 }
276 }
277}
278
279fn free_alias_path(ext: Option<&str>) -> PathBuf {
281 let (dir, pid) = (std::env::temp_dir(), std::process::id());
282 loop {
283 let seq = ATOMIC_TMP_SEQ.fetch_add(1, Ordering::Relaxed);
284 let path = dir.join(match ext {
285 Some(ext) => format!("lx.{pid}.{seq}.{ext}"),
286 None => format!("lx.{pid}.{seq}"),
287 });
288 if fs::symlink_metadata(&path).is_err() {
289 return path;
290 }
291 }
292}
293
294impl Drop for Staged {
295 fn drop(&mut self) { let _ = fs::remove_file(&self.path); }
296}
297
298pub fn same_bytes(a: &Path, b: &Path) -> bool {
300 match (fs::metadata(a), fs::metadata(b)) {
301 (Ok(ma), Ok(mb)) if ma.is_file() && mb.is_file() && ma.len() == mb.len() => {
302 matches!((fs::read(a), fs::read(b)), (Ok(x), Ok(y)) if x == y)
303 },
304 _ => false,
305 }
306}
307
308pub fn needs_write(dest: &Path) -> bool {
312 !fs::metadata(dest).is_ok_and(|m| m.is_file() && m.len() > 0)
313}
314
315pub fn same_file(a: impl AsRef<Path>, b: impl AsRef<Path>) -> bool {
319 latexml_core::util::pathname::same_file(a, b)
320}
321
322pub fn write_atomic(dest: &Path, bytes: &[u8]) -> io::Result<()> {
329 let (staged, mut file) = Staged::create(dest)?;
330 file.write_all(bytes)?;
331 drop(file);
332 staged.install(dest)
333}
334
335pub fn copy_atomic(src: &Path, dest: &Path) -> io::Result<()> {
340 if same_file(src, dest) {
341 return Err(io::Error::other(format!(
342 "{} is the source itself",
343 dest.display()
344 )));
345 }
346 let (staged, file) = Staged::create(dest)?;
347 drop(file);
348 fs::copy(src, staged.path())?;
349 staged.install(dest)
350}
351
352#[derive(Debug, Clone, Copy, PartialEq, Eq)]
354pub enum OutputFormat {
355 Xml,
356 Html,
357}
358
359pub struct Writer {
363 name: String,
364 format: OutputFormat,
365 omit_doctype: bool,
366 is_html: bool,
367}
368
369impl Writer {
370 pub fn new(format: Option<OutputFormat>, omit_doctype: bool, is_html: bool) -> Self {
371 Writer {
372 name: "Writer".to_string(),
373 format: format.unwrap_or(OutputFormat::Xml),
374 omit_doctype,
375 is_html,
376 }
377 }
378}
379
380impl Processor for Writer {
381 fn get_name(&self) -> &str { &self.name }
382
383 fn to_process(&self, doc: &PostDocument) -> Vec<Node> {
384 match doc.get_document_element() {
385 Some(el) => vec![el],
386 None => vec![],
387 }
388 }
389
390 fn process(&mut self, mut doc: PostDocument, nodes: Vec<Node>) -> ProcessResult {
391 let mut root = match nodes.into_iter().next() {
392 Some(r) => r,
393 None => return Ok(vec![doc]),
394 };
395
396 if self.omit_doctype {
401 doc.get_document_mut().remove_internal_subset();
402 }
403
404 if let Some(id) = get_xml_id(&root) {
410 if id == "TEMPORARY_DOCUMENT_ID" {
411 let _ = root.remove_attribute_ns("id", latexml_core::common::xml::XML_NS);
412 }
413 }
414
415 let serialized = if self.is_html {
417 doc.get_document().to_string_with_options(SaveOptions {
418 as_html: true,
419 format: true,
420 ..SaveOptions::default()
421 })
422 } else {
423 doc.get_document().to_string_with_options(SaveOptions {
424 format: true,
425 ..SaveOptions::default()
426 })
427 };
428
429 if let Some(destination) = doc.get_destination() {
430 if let Some(destdir) = doc.get_destination_directory() {
432 fs::create_dir_all(destdir).map_err(|e| {
433 PostError::Io(io::Error::new(
434 e.kind(),
435 format!("Couldn't create directory '{}': {}", destdir, e),
436 ))
437 })?;
438 }
439 fs::write(destination, &serialized).map_err(|e| {
440 PostError::Io(io::Error::new(
441 e.kind(),
442 format!("Couldn't write '{}': {}", destination, e),
443 ))
444 })?;
445 Info!(
446 "writer",
447 "wrote",
448 "Wrote '{}' ({})",
449 destination,
450 serialized.len()
451 );
452 } else {
453 print!("{}", serialized);
454 }
455
456 Ok(vec![doc])
457 }
458}
459
460#[cfg(test)]
461mod tests {
462 use super::*;
463
464 #[test]
465 fn output_format_variants() {
466 let _ = OutputFormat::Xml;
467 let _ = OutputFormat::Html;
468 }
469
470 #[test]
471 fn output_format_partial_eq() {
472 assert_eq!(OutputFormat::Xml, OutputFormat::Xml);
473 assert_ne!(OutputFormat::Xml, OutputFormat::Html);
474 assert_eq!(OutputFormat::Html, OutputFormat::Html);
475 }
476
477 #[test]
478 fn output_format_copy_clone() {
479 let a = OutputFormat::Xml;
481 let b = a;
482 let _ = a; assert_eq!(a, b);
484 }
485
486 #[test]
487 fn writer_new_default_format_xml() {
488 let w = Writer::new(None, false, false);
489 assert_eq!(w.get_name(), "Writer");
490 assert_eq!(w.format, OutputFormat::Xml);
491 assert!(!w.omit_doctype);
492 assert!(!w.is_html);
493 }
494
495 #[test]
496 fn writer_new_explicit_format() {
497 let w = Writer::new(Some(OutputFormat::Html), true, true);
498 assert_eq!(w.format, OutputFormat::Html);
499 assert!(w.omit_doctype);
500 assert!(w.is_html);
501 }
502
503 #[test]
504 fn writer_get_name_is_writer() {
505 let w = Writer::new(None, false, false);
506 assert_eq!(w.get_name(), "Writer");
507 }
508
509 #[test]
510 fn writer_omit_doctype_strips_doctype_preamble() {
514 use crate::document::{PostDocument, PostDocumentOptions};
515
516 let xml = r#"<?xml version="1.0"?>
517<!DOCTYPE root SYSTEM "example.dtd">
518<root><child>hi</child></root>"#;
519 let doc = PostDocument::new_from_string(xml, PostDocumentOptions::default())
520 .expect("parse test fixture");
521
522 let mut writer = Writer::new(
524 None, true, false,
525 );
526 let to_process = writer.to_process(&doc);
527 let result = writer.process(doc, to_process).expect("process");
528 let after = result
529 .into_iter()
530 .next()
531 .expect("at least one doc")
532 .get_document()
533 .to_string();
534 assert!(
535 !after.contains("<!DOCTYPE"),
536 "expected DOCTYPE stripped, got: {after}"
537 );
538 assert!(after.contains("<root>"));
539 }
540
541 #[test]
542 fn writer_default_preserves_doctype() {
545 use crate::document::{PostDocument, PostDocumentOptions};
546
547 let xml = r#"<?xml version="1.0"?>
548<!DOCTYPE root SYSTEM "example.dtd">
549<root><child>hi</child></root>"#;
550 let doc = PostDocument::new_from_string(xml, PostDocumentOptions::default())
551 .expect("parse test fixture");
552
553 let mut writer = Writer::new(
554 None, false, false,
555 );
556 let to_process = writer.to_process(&doc);
557 let result = writer.process(doc, to_process).expect("process");
558 let after = result
559 .into_iter()
560 .next()
561 .expect("at least one doc")
562 .get_document()
563 .to_string();
564 assert!(
565 after.contains("<!DOCTYPE"),
566 "expected DOCTYPE preserved, got: {after}"
567 );
568 }
569
570 #[test]
571 fn write_and_copy_atomic_succeed_and_clean_up_on_error() {
572 let dir = tempfile::tempdir().unwrap();
573 let dst = dir.path().join("LaTeXML.css");
574 write_atomic(&dst, b"body { color: black; }\n").unwrap();
575 assert_eq!(fs::read(&dst).unwrap(), b"body { color: black; }\n");
576
577 let src = dir.path().join("custom.css");
578 fs::write(&src, b".a { color: red; }\n").unwrap();
579 copy_atomic(&src, &dst).unwrap();
580 assert_eq!(fs::read(&dst).unwrap(), b".a { color: red; }\n");
581
582 let bad = dir.path().join("blocked.css");
584 fs::create_dir(&bad).unwrap();
585 assert!(write_atomic(&bad, b"x").is_err());
586 assert!(copy_atomic(&src, &bad).is_err());
587 let strays: Vec<_> = fs::read_dir(dir.path())
588 .unwrap()
589 .filter_map(|e| e.ok())
590 .filter(|e| e.file_name().to_string_lossy().contains(".tmp."))
591 .collect();
592 assert!(strays.is_empty(), "leftover atomic temp files: {strays:?}");
593 }
594
595 #[cfg(unix)]
600 #[test]
601 fn a_refused_install_stands_only_on_identical_bytes() {
602 use std::os::unix::fs::PermissionsExt;
603 let dir = tempfile::tempdir().unwrap();
604 let a = dir.path().join("a.svg");
605 let b = dir.path().join("b.svg");
606 fs::write(&a, b"<svg>1</svg>").unwrap();
607 fs::write(&b, b"<svg>2</svg>").unwrap();
608 assert!(same_bytes(&a, &a.clone()));
609 assert!(!same_bytes(&a, &b), "same length, other bytes");
610 assert!(!same_bytes(&a, &dir.path().join("missing.svg")));
611 assert!(
612 !same_bytes(dir.path(), dir.path()),
613 "a directory holds no bytes"
614 );
615
616 let stage = |bytes: &[u8]| {
617 let staged = Staged::beside(&a);
618 fs::write(staged.path(), bytes).unwrap();
619 staged
620 };
621 let (same, other) = (stage(b"<svg>1</svg>"), stage(b"<svg>9</svg>"));
622 fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o555)).unwrap();
623 let probe = fs::rename(&b, dir.path().join("probe.svg"));
624 let refused = probe.is_err();
625 let (same, other) = (same.install(&a), other.install(&a));
626 fs::set_permissions(dir.path(), fs::Permissions::from_mode(0o755)).unwrap();
627 if !refused {
628 eprintln!(
629 "SKIP a_refused_install_stands_only_on_identical_bytes: renames are not refused (root)"
630 );
631 return;
632 }
633 assert!(same.is_ok(), "{same:?}");
634 assert!(
635 other.is_err(),
636 "a stale file of the same length is not the install"
637 );
638 assert_eq!(fs::read(&a).unwrap(), b"<svg>1</svg>");
639 let staged = Staged::beside(&a);
640 let temp = staged.path().to_path_buf();
641 fs::write(&temp, b"x").unwrap();
642 drop(staged);
643 assert!(
644 !temp.exists(),
645 "an uninstalled stage is removed when dropped"
646 );
647 }
648
649 #[test]
654 fn a_stage_installed_onto_its_own_hard_link_is_removed() {
655 let dir = tempfile::tempdir().unwrap();
656 let a = dir.path().join("fig.svg");
657 fs::write(&a, b"<svg/>").unwrap();
658 let staged = Staged::beside(&a);
659 let temp = staged.path().to_path_buf();
660 fs::hard_link(&a, &temp).unwrap();
661 staged.install(&a).unwrap();
662 assert!(!temp.exists(), "the staged link is left behind");
663 assert_eq!(fs::read(&a).unwrap(), b"<svg/>");
664 }
665
666 #[test]
669 fn an_alias_is_a_short_name_in_the_temporary_directory() {
670 let dir = tempfile::tempdir().unwrap();
671 let figure = dir.path().join(format!("{}.pdf", "f".repeat(200)));
672 fs::write(&figure, b"%PDF-1.4 figure").unwrap();
673 let alias = Staged::alias(&figure).unwrap();
674 let path = alias.path().to_path_buf();
675 assert_eq!(path.parent(), Some(std::env::temp_dir().as_path()));
676 let name = path.file_name().unwrap().to_str().unwrap();
677 assert!(name.len() < 40 && name.ends_with(".pdf"), "{name}");
678 assert_eq!(fs::read(&path).unwrap(), b"%PDF-1.4 figure");
679 drop(alias);
680 assert!(!path.exists(), "the alias outlived its drop");
681 assert_eq!(fs::read_dir(dir.path()).unwrap().count(), 1);
682 }
683
684 #[test]
688 fn the_stages_of_a_long_figure_name_stay_under_name_max() {
689 let dir = tempfile::tempdir().unwrap();
690 let long = dir.path().join(format!("{}.svg", "g".repeat(240)));
691 let stage = Staged::beside(&long);
692 let again = Staged::beside(stage.path());
693 for path in [stage.path(), again.path()] {
694 let name = path.file_name().unwrap().to_str().unwrap();
695 assert!(name.len() <= 128, "{} bytes: {name}", name.len());
696 assert!(name.ends_with(".svg"), "{name}");
697 fs::write(path, b"<svg/>").unwrap();
698 }
699 write_atomic(&long, b"<svg>1</svg>").unwrap();
700 assert_eq!(fs::read(&long).unwrap(), b"<svg>1</svg>");
701 let (a, b) = (
702 format!("{}a", "é".repeat(40)),
703 format!("{}b", "é".repeat(40)),
704 );
705 assert_ne!(bounded_name(&a), bounded_name(&b));
706 assert_eq!(bounded_name("fig.svg"), "fig.svg", "a short name is kept");
707 }
708
709 #[test]
713 fn a_taken_temp_name_is_never_written_through() {
714 let dir = tempfile::tempdir().unwrap();
715 let sentinel = dir.path().join("site.svg");
716 fs::write(&sentinel, b"<svg>site</svg>").unwrap();
717 let src = dir.path().join("cached.svg");
718 fs::write(&src, b"<svg>new</svg>").unwrap();
719 let dests = ["w.svg", "c.svg"].map(|name| dir.path().join(name));
720 let next = ATOMIC_TMP_SEQ.load(Ordering::Relaxed);
721 for dest in &dests {
722 for seq in next..next + 64 {
723 fs::hard_link(&sentinel, staged_path(dest, seq)).unwrap();
724 }
725 }
726 write_atomic(&dests[0], b"<svg>new</svg>").unwrap();
727 copy_atomic(&src, &dests[1]).unwrap();
728 assert_eq!(fs::read(&sentinel).unwrap(), b"<svg>site</svg>");
729 for dest in &dests {
730 assert_eq!(
731 fs::read(dest).unwrap(),
732 b"<svg>new</svg>",
733 "{}",
734 dest.display()
735 );
736 }
737 }
738
739 #[test]
740 fn concurrent_write_atomic_produces_intact_file_without_errors() {
741 let dir = tempfile::tempdir().unwrap();
742 let dst = dir.path().join("shared.css");
743 let payload: Vec<u8> = b"/* css */\n".repeat(4096);
744 std::thread::scope(|s| {
745 for _ in 0..8 {
746 let dst = &dst;
747 let payload = &payload;
748 s.spawn(move || {
749 for _ in 0..16 {
750 write_atomic(dst, payload).expect("concurrent atomic write");
751 }
752 });
753 }
754 });
755 assert_eq!(fs::read(&dst).unwrap(), payload);
756 }
757}