1use std::{
24 fs::File,
25 io::{self, BufWriter, Write},
26 path::Path,
27};
28
29use zip::{CompressionMethod, ZipWriter, write::SimpleFileOptions};
30
31const ZIP_WRITE_BUF: usize = 64 * 1024;
38
39pub struct PackOptions<'a> {
41 pub zip_path: &'a str,
43 pub html_filename: &'a str,
46 pub html: &'a str,
48 pub log_filename: Option<&'a str>,
50 pub log: &'a str,
52 pub status: &'a str,
54 pub resource_dir: Option<&'a Path>,
58 pub telemetry_json: Option<&'a str>,
63 pub source_date_epoch: Option<u64>,
69}
70
71pub fn pack_archive(opts: &PackOptions) -> io::Result<()> {
82 let file = File::create(opts.zip_path)?;
83 let buf_file = BufWriter::with_capacity(ZIP_WRITE_BUF, file);
84 let mut zip = ZipWriter::new(buf_file);
85 let mut zip_options =
86 SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
87 if let Some(epoch) = opts.source_date_epoch {
93 if let Some(dt) = epoch_to_zip_datetime(epoch) {
94 zip_options = zip_options.last_modified_time(dt);
95 }
96 }
97
98 zip
100 .start_file(opts.html_filename, zip_options)
101 .map_err(io_err)?;
102 zip.write_all(opts.html.as_bytes())?;
103
104 if let Some(dir) = opts.resource_dir {
106 if dir.exists() {
107 add_dir_to_zip(&mut zip, dir, dir, &zip_options)?;
108 }
109 }
110
111 if let Some(log_name) = opts.log_filename {
113 if !opts.log.is_empty() {
114 zip.start_file(log_name, zip_options).map_err(io_err)?;
115 zip.write_all(opts.log.as_bytes())?;
116 }
117 }
118
119 zip.start_file("status", zip_options).map_err(io_err)?;
121 zip.write_all(opts.status.as_bytes())?;
122
123 if let Some(tjson) = opts.telemetry_json {
125 zip
126 .start_file("telemetry.json", zip_options)
127 .map_err(io_err)?;
128 zip.write_all(tjson.as_bytes())?;
129 }
130
131 zip.finish().map_err(io_err)?;
132 Ok(())
133}
134
135pub fn pack_directory(
138 dir: &Path,
139 zip_path: &str,
140 source_date_epoch: Option<u64>,
141) -> io::Result<()> {
142 let file = File::create(zip_path)?;
143 let mut zip = ZipWriter::new(BufWriter::with_capacity(ZIP_WRITE_BUF, file));
144 let mut deflated = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated);
145 if let Some(dt) = source_date_epoch.and_then(epoch_to_zip_datetime) {
146 deflated = deflated.last_modified_time(dt);
147 }
148 let stored = deflated.compression_method(CompressionMethod::Stored);
149 let mut files = Vec::new();
150 let mut subdirs = Vec::new();
151 for entry in std::fs::read_dir(dir)? {
152 let entry = entry?;
153 let name = entry.file_name().to_string_lossy().into_owned();
154 if name.starts_with('.') {
155 continue;
156 }
157 if entry.path().is_dir() {
158 subdirs.push(name);
159 } else if entry.path().is_file() && !is_excluded_archive_entry(&name) {
160 files.push(name);
161 }
162 }
163 files.sort_by_key(|name| (name != "mimetype", name.clone()));
164 subdirs.sort();
165 for name in &files {
166 let options = if name == "mimetype" { stored } else { deflated };
167 zip.start_file(name.as_str(), options).map_err(io_err)?;
168 io::copy(&mut File::open(dir.join(name))?, &mut zip)?;
169 }
170 for name in &subdirs {
171 add_tree_to_zip(&mut zip, &dir.join(name), name, &deflated)?;
172 }
173 zip.finish().map_err(io_err)?;
174 Ok(())
175}
176
177fn add_tree_to_zip<W: Write + io::Seek>(
179 zip: &mut ZipWriter<W>,
180 dir: &Path,
181 name: &str,
182 options: &SimpleFileOptions,
183) -> io::Result<()> {
184 zip.add_directory(name, *options).map_err(io_err)?;
185 let mut entries: Vec<_> = std::fs::read_dir(dir)?.collect::<io::Result<_>>()?;
186 entries.sort_by_key(|entry| entry.file_name());
187 for entry in entries {
188 let basename = entry.file_name().to_string_lossy().into_owned();
189 if is_excluded_archive_entry(&basename) {
190 continue;
191 }
192 let member = format!("{name}/{basename}");
193 if entry.path().is_dir() {
194 add_tree_to_zip(zip, &entry.path(), &member, options)?;
195 } else {
196 zip.start_file(member.as_str(), *options).map_err(io_err)?;
197 io::copy(&mut File::open(entry.path())?, zip)?;
198 }
199 }
200 Ok(())
201}
202
203fn add_dir_to_zip<W: Write + io::Seek>(
217 zip: &mut ZipWriter<W>,
218 dir: &Path,
219 base: &Path,
220 options: &SimpleFileOptions,
221) -> io::Result<()> {
222 for entry in std::fs::read_dir(dir)? {
223 let entry = entry?;
224 let path = entry.path();
225 let rel = path.strip_prefix(base).unwrap_or(&path);
226 let name = rel
231 .to_string_lossy()
232 .replace(std::path::MAIN_SEPARATOR, "/");
233 let basename = entry.file_name().to_string_lossy().to_string();
234
235 if path.is_dir() {
236 if !is_excluded_archive_entry(&basename) {
240 add_dir_to_zip(zip, &path, base, options)?;
241 }
242 } else if !name.ends_with(".html") && !is_excluded_archive_entry(&basename) {
243 zip.start_file(&name, *options).map_err(io_err)?;
244 let f = File::open(&path)?;
245 let mut buf_reader = io::BufReader::with_capacity(ZIP_WRITE_BUF, f);
246 io::copy(&mut buf_reader, zip)?;
247 }
248 }
249 Ok(())
250}
251
252fn is_excluded_archive_entry(basename: &str) -> bool {
261 if basename.starts_with('.') || basename.ends_with('~') {
262 return true;
263 }
264 if crate::document::is_cache_file(basename) {
266 return true;
267 }
268 match basename.rsplit_once('.') {
271 Some((_, ext)) => matches!(
272 ext.to_ascii_lowercase().as_str(),
273 "zip" | "gz" | "epub" | "tex" | "bib" | "mobi" | "cache"
274 ),
275 None => false,
276 }
277}
278
279fn epoch_to_zip_datetime(epoch: u64) -> Option<zip::DateTime> {
286 let days = (epoch / 86_400) as i64;
287 let secs_of_day = (epoch % 86_400) as u32;
288 let (hour, minute, second) = (
289 (secs_of_day / 3600) as u8,
290 ((secs_of_day % 3600) / 60) as u8,
291 (secs_of_day % 60) as u8,
292 );
293 let z = days + 719_468;
295 let era = if z >= 0 { z } else { z - 146_096 } / 146_097;
296 let doe = z - era * 146_097; let yoe = (doe - doe / 1460 + doe / 36524 - doe / 146_096) / 365; let year = yoe + era * 400;
299 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100); let mp = (5 * doy + 2) / 153; let day = (doy - (153 * mp + 2) / 5 + 1) as u8; let month = (if mp < 10 { mp + 3 } else { mp - 9 }) as u8; let year = year + i64::from(month <= 2);
304 if !(1980..=2107).contains(&year) {
305 return None;
306 }
307 zip::DateTime::from_date_and_time(year as u16, month, day, hour, minute, second).ok()
308}
309
310fn io_err(e: zip::result::ZipError) -> io::Error {
314 match e {
315 zip::result::ZipError::Io(inner) => inner,
316 other => io::Error::other(other.to_string()),
317 }
318}
319
320#[cfg(test)]
321mod tests {
322 use std::io::Read;
323
324 use super::*;
325
326 fn zip_entry_names(zip_path: &Path) -> Vec<String> {
328 let f = File::open(zip_path).expect("open zip");
329 let mut archive = zip::ZipArchive::new(f).expect("parse zip");
330 (0..archive.len())
331 .map(|i| {
332 archive
333 .by_index(i)
334 .expect("entry")
335 .name()
336 .expect("entry name")
337 .to_string()
338 })
339 .collect()
340 }
341
342 #[test]
343 fn excludes_perl_archive_ext_set() {
344 assert!(is_excluded_archive_entry("paper.tex"));
347 assert!(is_excluded_archive_entry("refs.bib"));
348 assert!(is_excluded_archive_entry("bundle.zip"));
349 assert!(is_excluded_archive_entry("page.gz"));
350 assert!(is_excluded_archive_entry("book.epub"));
351 assert!(is_excluded_archive_entry("book.mobi"));
352 assert!(is_excluded_archive_entry("LaTeXML.cache"));
353 assert!(is_excluded_archive_entry(".hidden"));
354 assert!(is_excluded_archive_entry("backup~"));
355 assert!(!is_excluded_archive_entry("fig1.png"));
357 assert!(!is_excluded_archive_entry("diagram.svg"));
358 assert!(!is_excluded_archive_entry("LaTeXML.css"));
359 assert!(!is_excluded_archive_entry("logo.jpg"));
360 }
361
362 #[test]
363 fn pack_archive_bundles_resources_minus_excluded() {
364 let staging = tempfile::tempdir().expect("tempdir");
365 let p = staging.path();
366 std::fs::write(p.join("fig1.png"), b"PNGDATA").unwrap();
368 std::fs::write(p.join("LaTeXML.css"), b"body{}").unwrap();
369 std::fs::create_dir(p.join("sub")).unwrap();
370 std::fs::write(p.join("sub").join("img.svg"), b"<svg/>").unwrap();
371 std::fs::write(p.join("paper.tex"), b"\\documentclass{article}").unwrap();
373 std::fs::write(p.join("refs.bib"), b"@book{x}").unwrap();
374 std::fs::write(p.join("LaTeXML.cache"), b"cache").unwrap();
375 std::fs::write(p.join("LaTeXML-oxide.cache"), b"cache").unwrap();
376 std::fs::write(p.join("LaTeXML-oxide.cache-wal"), b"wal").unwrap();
377 std::fs::write(p.join("LaTeXML-oxide.cache-shm"), b"shm").unwrap();
378 std::fs::write(p.join("LaTeXML-oxide.cache-journal"), b"journal").unwrap();
379 std::fs::write(p.join(".hidden"), b"secret").unwrap();
380 std::fs::write(p.join("backup~"), b"old").unwrap();
381 std::fs::write(p.join("doc.html"), b"<html>staging copy</html>").unwrap();
384
385 let out = tempfile::tempdir().expect("out dir");
386 let zip_path = out.path().join("bundle.zip");
387 let zip_path_str = zip_path.to_string_lossy().to_string();
388
389 pack_archive(&PackOptions {
390 zip_path: &zip_path_str,
391 html_filename: "doc.html",
392 html: "<html>real document</html>",
393 log_filename: Some("doc.log"),
394 log: "log line",
395 status: "Status:conversion:0",
396 resource_dir: Some(p),
397 telemetry_json: None,
398 source_date_epoch: None,
399 })
400 .expect("pack archive");
401
402 let names = zip_entry_names(&zip_path);
403 assert!(names.iter().any(|n| n == "fig1.png"), "names: {names:?}");
405 assert!(names.iter().any(|n| n == "LaTeXML.css"), "names: {names:?}");
406 assert!(
407 names.iter().any(|n| n == "sub/img.svg"),
408 "subdir resource missing; names: {names:?}"
409 );
410 assert!(names.iter().any(|n| n == "doc.html"));
412 assert!(names.iter().any(|n| n == "doc.log"));
413 assert!(names.iter().any(|n| n == "status"));
414 for forbidden in [
416 "paper.tex",
417 "refs.bib",
418 "LaTeXML.cache",
419 "LaTeXML-oxide.cache",
420 "LaTeXML-oxide.cache-wal",
421 "LaTeXML-oxide.cache-shm",
422 "LaTeXML-oxide.cache-journal",
423 ".hidden",
424 "backup~",
425 ] {
426 assert!(
427 !names.iter().any(|n| n == forbidden),
428 "{forbidden} must be excluded; names: {names:?}"
429 );
430 }
431 assert_eq!(
433 names.iter().filter(|n| n.as_str() == "doc.html").count(),
434 1,
435 "doc.html must not be double-added; names: {names:?}"
436 );
437 let f = File::open(&zip_path).unwrap();
439 let mut archive = zip::ZipArchive::new(f).unwrap();
440 let mut html_entry = archive.by_name("doc.html").unwrap();
441 let mut body = String::new();
442 html_entry.read_to_string(&mut body).unwrap();
443 assert_eq!(body, "<html>real document</html>");
444 }
445
446 #[test]
447 fn source_date_epoch_sets_member_timestamp() {
448 let staging = tempfile::tempdir().expect("tempdir");
452 std::fs::write(staging.path().join("fig.png"), b"x").unwrap();
453 let out = tempfile::tempdir().expect("out");
454 let zip_path = out.path().join("ts.zip");
455 let zip_path_str = zip_path.to_string_lossy().to_string();
456 pack_archive(&PackOptions {
457 zip_path: &zip_path_str,
458 html_filename: "d.html",
459 html: "<html/>",
460 log_filename: None,
461 log: "",
462 status: "ok",
463 resource_dir: Some(staging.path()),
464 telemetry_json: None,
465 source_date_epoch: Some(1_609_459_200),
466 })
467 .expect("pack");
468
469 let f = File::open(&zip_path).unwrap();
470 let mut archive = zip::ZipArchive::new(f).unwrap();
471 let entry = archive.by_name("fig.png").unwrap();
472 let dt = entry.last_modified().expect("has mod time");
473 assert_eq!(dt.year(), 2021, "year");
474 assert_eq!(dt.month(), 1, "month");
475 assert_eq!(dt.day(), 1, "day");
476 }
477}