1use std::{fs::File, path::Path};
21
22use chrono::NaiveDate;
23
24const DOS_EPOCH: i64 = 315_532_800;
26
27fn 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
38fn dated(epoch: i64) -> Option<i64> { (epoch > DOS_EPOCH).then_some(epoch) }
40
41fn 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
66pub 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
114fn 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
124pub 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 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
154pub 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 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 assert_eq!(
190 of_archive(zip.path(), Some("paper.tex")),
191 Some(1_516_273_500)
192 );
193 }
194
195 #[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 let ut: u32 = 1_516_314_600;
204 let mut field = vec![1u8]; 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 #[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}