Skip to main content

latexml/
source_date.rs

1//! The date of a paper's source: the newest modification time among the TeX source files of the bundle it came in
2//! (`Config::source_date_epoch`), the clock ar5iv's archival preload gives the job so `\today` prints the paper's own
3//! date — the one arXiv's PDF shows — and never the conversion's (user ruling 2026-10-10).
4//!
5//! Only the files the paper is typeset from count: the `.tex` sources, the macro files shipped beside them and the
6//! `.bbl`/`.bib` (a `.bbl` is written by the author's last compile), plus the detected main file whatever its
7//! extension. Figures, compile by-products (`.aux`, `.log`, `.synctex`) and directories do not: a figure regenerated
8//! after the paper, or a directory the packer touched, is not the paper's date. A time at or before the DOS epoch
9//! (1980-01-01, a zip entry's "no time" — arXiv's single-file submissions arrive so) is no date.
10//!
11//! An archive's entries are read for their recorded times, not the extracted files' (extraction stamps its own
12//! clock): a zip entry's Info-ZIP extended timestamp (`0x5455`, UTC) when it has one, else its DOS date and time read
13//! as UTC; a tar entry's `mtime`. The result is deterministic per archive. A directory or single-file input reads the
14//! filesystem's mtimes instead, which a checkout or a copy resets: deterministic only while the files are untouched.
15//!
16//! Known limits: an entry dated in the future still wins (no clock is consulted, so the result stays deterministic); a
17//! single-file input counts only that file, not the files it `\input`s; a directory walk skips version-control
18//! directories (`.git`, `.svn`, `.hg`, `CVS`); a `.tar.gz` is decompressed a second time for its dates.
19
20use std::{fs::File, path::Path};
21
22use chrono::NaiveDate;
23
24/// The DOS epoch, 1980-01-01T00:00:00Z: a zip entry at (or a time before) it carries no date.
25const DOS_EPOCH: i64 = 315_532_800;
26
27/// Whether a source file named `name` is one the paper is typeset from (case-insensitive extension).
28fn is_tex_source(name: &str) -> bool {
29  const EXTENSIONS: &[&str] = &[
30    "tex", "ltx", "latex", "sty", "cls", "clo", "def", "cfg", "fd", "bbl", "bib",
31  ];
32  Path::new(name)
33    .extension()
34    .and_then(|ext| ext.to_str())
35    .is_some_and(|ext| EXTENSIONS.iter().any(|e| ext.eq_ignore_ascii_case(e)))
36}
37
38/// `epoch` when it is a date (after the DOS epoch).
39fn dated(epoch: i64) -> Option<i64> { (epoch > DOS_EPOCH).then_some(epoch) }
40
41/// A zip entry's recorded modification time: its extended timestamp (UTC) when present, else its DOS date and time
42/// read as UTC.
43fn zip_entry_epoch<R: std::io::Read>(entry: &zip::read::ZipFile<'_, R>) -> Option<i64> {
44  let extended = entry.extra_data_fields().find_map(|field| match field {
45    zip::ExtraField::ExtendedTimestamp(ts) => ts.mod_time(),
46    _ => None,
47  });
48  if let Some(epoch) = extended {
49    return dated(i64::from(epoch));
50  }
51  let dos = entry.last_modified()?;
52  let utc = NaiveDate::from_ymd_opt(
53    i32::from(dos.year()),
54    u32::from(dos.month()),
55    u32::from(dos.day()),
56  )?
57  .and_hms_opt(
58    u32::from(dos.hour()),
59    u32::from(dos.minute()),
60    u32::from(dos.second()),
61  )?
62  .and_utc();
63  dated(utc.timestamp())
64}
65
66/// The source date of an archive (`.zip`, `.tar.gz`/`.tgz`, `.tar`): the newest recorded time among its TeX source
67/// entries and `main` (the detected main file's path inside the archive). `None` when no such entry carries a date, or
68/// the archive cannot be read.
69pub fn of_archive(archive: &Path, main: Option<&str>) -> Option<i64> {
70  let counts =
71    |name: &str| is_tex_source(name) || main.is_some_and(|m| name.trim_start_matches("./") == m);
72  let name = archive.to_string_lossy();
73  if name.ends_with(".zip") {
74    let mut zip = zip::ZipArchive::new(File::open(archive).ok()?).ok()?;
75    let mut newest = None;
76    for i in 0..zip.len() {
77      let Ok(entry) = zip.by_index_raw(i) else {
78        continue;
79      };
80      if entry.is_file() && entry.name().is_ok_and(|name| counts(&name)) {
81        newest = newest.max(zip_entry_epoch(&entry));
82      }
83    }
84    newest
85  } else if name.ends_with(".tar.gz") || name.ends_with(".tgz") {
86    tar_newest(
87      tar::Archive::new(flate2::read::GzDecoder::new(File::open(archive).ok()?)),
88      &counts,
89    )
90  } else if name.ends_with(".tar") {
91    tar_newest(tar::Archive::new(File::open(archive).ok()?), &counts)
92  } else {
93    None
94  }
95}
96
97fn tar_newest<R: std::io::Read>(
98  mut tar: tar::Archive<R>,
99  counts: &dyn Fn(&str) -> bool,
100) -> Option<i64> {
101  let mut newest = None;
102  for entry in tar.entries().ok()?.flatten() {
103    let header = entry.header();
104    let is_file = header.entry_type().is_file();
105    let name = entry.path().ok().map(|p| p.to_string_lossy().into_owned());
106    if is_file && name.as_deref().is_some_and(counts) {
107      let epoch = header.mtime().ok().and_then(|t| i64::try_from(t).ok());
108      newest = newest.max(epoch.and_then(dated));
109    }
110  }
111  newest
112}
113
114/// A file's modification time as Unix seconds, when it is a date.
115fn file_epoch(path: &Path) -> Option<i64> {
116  let modified = path.metadata().ok()?.modified().ok()?;
117  let secs = modified
118    .duration_since(std::time::UNIX_EPOCH)
119    .ok()?
120    .as_secs();
121  dated(i64::try_from(secs).ok()?)
122}
123
124/// The source date of a directory input: the newest modification time among the TeX source files beneath `dir` and
125/// `main`.
126pub fn of_directory(dir: &Path, main: Option<&Path>) -> Option<i64> {
127  fn walk(dir: &Path, newest: &mut Option<i64>) {
128    let Ok(entries) = std::fs::read_dir(dir) else {
129      return;
130    };
131    for entry in entries.flatten() {
132      let path = entry.path();
133      let Ok(kind) = entry.file_type() else {
134        continue;
135      };
136      if kind.is_dir() {
137        // A version-control directory holds no source the paper is typeset from.
138        if !matches!(
139          entry.file_name().to_str(),
140          Some(".git" | ".svn" | ".hg" | "CVS")
141        ) {
142          walk(&path, newest);
143        }
144      } else if kind.is_file() && is_tex_source(&entry.file_name().to_string_lossy()) {
145        *newest = (*newest).max(file_epoch(&path));
146      }
147    }
148  }
149  let mut newest = main.and_then(file_epoch);
150  walk(dir, &mut newest);
151  newest
152}
153
154/// The source date of a single-file input: its modification time.
155pub fn of_file(file: &Path) -> Option<i64> { file_epoch(file) }
156
157#[cfg(test)]
158mod tests {
159  use std::io::Write;
160
161  use super::*;
162
163  /// A zip of `(name, DOS time)` entries, none with an extended timestamp.
164  fn zip_with(entries: &[(&str, zip::DateTime)]) -> tempfile::NamedTempFile {
165    let file = tempfile::Builder::new().suffix(".zip").tempfile().unwrap();
166    let mut zip = zip::ZipWriter::new(file.reopen().unwrap());
167    for (name, time) in entries {
168      let options = zip::write::SimpleFileOptions::default().last_modified_time(*time);
169      zip.start_file(*name, options).unwrap();
170      zip.write_all(b"x").unwrap();
171    }
172    zip.finish().unwrap();
173    file
174  }
175
176  fn dos(y: u16, mo: u8, d: u8, h: u8, mi: u8) -> zip::DateTime {
177    zip::DateTime::from_date_and_time(y, mo, d, h, mi, 0).unwrap()
178  }
179
180  #[test]
181  fn newest_tex_source_entry_wins_over_figures() {
182    let zip = zip_with(&[
183      ("paper.tex", dos(2018, 1, 18, 10, 30)),
184      ("ptapap.cls", dos(2017, 12, 1, 0, 0)),
185      ("paper.bbl", dos(2018, 1, 18, 11, 5)),
186      ("fig1.pdf", dos(2019, 6, 1, 0, 0)),
187    ]);
188    // 2018-01-18T11:05:00Z, the .bbl's time; the later figure does not count.
189    assert_eq!(
190      of_archive(zip.path(), Some("paper.tex")),
191      Some(1_516_273_500)
192    );
193  }
194
195  /// arxmliv's zips record each entry twice: an Info-ZIP extended timestamp (`0x5455`, UTC) and a DOS time in the
196  /// packer's local zone (UTC+2: 2105.04321's `rlrd_rev1.tex`, DOS 17:46 against UT 15:46Z). The UT time wins, even
197  /// across a day boundary.
198  #[test]
199  fn extended_timestamp_wins_over_the_dos_time() {
200    let file = tempfile::Builder::new().suffix(".zip").tempfile().unwrap();
201    let mut zip = zip::ZipWriter::new(file.reopen().unwrap());
202    // 2018-01-18T22:30:00Z, written by a packer at UTC+2 as a DOS 2018-01-19 00:30.
203    let ut: u32 = 1_516_314_600;
204    let mut field = vec![1u8]; // flags: modification time present
205    field.extend_from_slice(&ut.to_le_bytes());
206    let mut options =
207      zip::write::FullFileOptions::default().last_modified_time(dos(2018, 1, 19, 0, 30));
208    options.add_extra_field(0x5455, field, false).unwrap();
209    zip.start_file("paper.tex", options).unwrap();
210    zip.write_all(b"x").unwrap();
211    zip.finish().unwrap();
212    assert_eq!(
213      of_archive(file.path(), Some("paper.tex")),
214      Some(1_516_314_600)
215    );
216  }
217
218  /// A tar entry's `mtime`, among its TeX sources only.
219  #[test]
220  fn tar_entries_date_by_their_mtime() {
221    let file = tempfile::Builder::new().suffix(".tar").tempfile().unwrap();
222    let mut tar = tar::Builder::new(file.reopen().unwrap());
223    for (name, mtime) in [("paper.tex", 983_682_360u64), ("fig.eps", 1_516_314_600)] {
224      let mut header = tar::Header::new_gnu();
225      header.set_size(1);
226      header.set_mtime(mtime);
227      header.set_mode(0o644);
228      header.set_entry_type(tar::EntryType::Regular);
229      tar.append_data(&mut header, name, &b"x"[..]).unwrap();
230    }
231    tar.finish().unwrap();
232    assert_eq!(
233      of_archive(file.path(), Some("paper.tex")),
234      Some(983_682_360)
235    );
236  }
237
238  #[test]
239  fn undated_entries_give_no_date() {
240    let zip = zip_with(&[("paper.tex", zip::DateTime::default())]);
241    assert_eq!(of_archive(zip.path(), Some("paper.tex")), None);
242  }
243
244  #[test]
245  fn the_main_file_counts_whatever_its_extension() {
246    let zip = zip_with(&[("paper.txt", dos(2001, 3, 4, 5, 6))]);
247    assert_eq!(of_archive(zip.path(), Some("paper.txt")), Some(983_682_360));
248    assert_eq!(of_archive(zip.path(), None), None);
249  }
250}