1use std::fs;
9use std::io::{self, Read, Seek, SeekFrom};
10use std::path::{Component, Path, PathBuf};
11use std::sync::Arc;
12
13use anyhow::{Context, Result, anyhow, bail};
14use serde::{Deserialize, Serialize};
15
16use crate::archive::storage::{self, Storage, Tail};
17pub use crate::archive::targz::{StreamPoint, TarAt};
18use crate::fsutil;
19
20const VERSION: u32 = 3;
24const KEEP_VERSION: u32 = 4;
30const REPLACE_VERSION: u32 = 5;
36const CHOOSE_VERSION: u32 = 6;
40const CASE_VERSION: u32 = 7;
44const FOLDERS_VERSION: u32 = 8;
49const SELECT_VERSION: u32 = 9;
54const READABLE: [u32; 8] = [2, 3, 4, 5, 6, 7, 8, 9];
55const STUB_VERSION: u32 = 1000;
62
63#[derive(Serialize, Deserialize, Clone)]
64pub struct Link {
65 pub path: PathBuf,
66 pub target: PathBuf,
67 pub hard: bool,
68}
69
70#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
74pub struct Resume {
75 pub unit: u64,
77 pub written: u64,
80 pub bit: u64,
83 pub crc: u32,
86 #[serde(default, skip_serializing_if = "Option::is_none")]
92 pub stream: Option<Box<StreamPoint>>,
93}
94
95#[derive(Serialize, Deserialize)]
96pub struct Journal {
97 pub version: u32,
98 pub format: String,
99 pub parts: Vec<(PathBuf, u64)>,
101 pub tail_start: u64,
102 pub tail_crc: u32,
103 pub output: PathBuf,
104 pub total_size: u64,
105 pub committed_len: u64,
108 pub links: Vec<Link>,
111 #[serde(default)]
114 pub resume: Option<Resume>,
115 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
120 pub done: bool,
121 #[serde(default, skip_serializing_if = "Option::is_none")]
126 pub restoring: Option<Vec<(u64, Vec<u8>)>>,
127 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
131 pub keep: bool,
132 #[serde(default, skip_serializing_if = "Option::is_none")]
135 pub replace: Option<Replace>,
136 #[serde(default, skip_serializing_if = "Vec::is_empty")]
140 pub case_folders: Vec<PathBuf>,
141 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
145 pub case_beyond_ascii: bool,
146 #[serde(default, skip_serializing_if = "Option::is_none")]
149 pub folders: Option<crate::folders::Saved>,
150 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
155 pub folders_left: bool,
156 #[serde(default, skip_serializing_if = "Option::is_none")]
160 pub only: Option<Vec<PathBuf>>,
161}
162
163#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
164pub struct Replace {
165 pub moved: bool,
169 #[serde(default, skip_serializing_if = "Vec::is_empty")]
172 pub keep: Vec<PathBuf>,
173 #[serde(default, skip_serializing_if = "Vec::is_empty")]
176 pub both: Vec<PathBuf>,
177}
178
179impl Replace {
180 fn chose(&self) -> bool {
181 !self.keep.is_empty() || !self.both.is_empty()
182 }
183}
184
185fn is_stub(path: &Path) -> bool {
187 #[derive(Deserialize)]
188 struct Versioned {
189 version: u32,
190 }
191 fs::read(path)
192 .ok()
193 .and_then(|b| serde_json::from_slice::<Versioned>(&b).ok())
194 .is_some_and(|v| v.version == STUB_VERSION)
195}
196
197pub struct Paths {
198 pub archive: PathBuf,
200 pub journal: PathBuf,
201 pub tail: PathBuf,
202 pub folders: PathBuf,
203 pub stub: Option<PathBuf>,
206}
207
208impl Paths {
209 pub fn for_archive(archive: &Path) -> Self {
210 let with = |suffix: &str| {
211 let mut s = archive.as_os_str().to_owned();
212 s.push(suffix);
213 PathBuf::from(s)
214 };
215 let stub = storage::split_zip_last(archive).map(|last| {
216 let mut s = last.into_os_string();
217 s.push(".hatchzip");
218 PathBuf::from(s)
219 });
220 Self {
221 archive: archive.to_path_buf(),
222 journal: with(".hatchzip"),
223 tail: with(".hatchzip-tail"),
224 folders: with(".hatchzip-folders"),
225 stub,
226 }
227 }
228
229 fn write_stub(&self) -> Result<()> {
232 let Some(stub) = &self.stub else {
233 return Ok(());
234 };
235 self.check_stub()?;
236 let json = serde_json::to_vec(&serde_json::json!({
237 "version": STUB_VERSION,
238 "split_zip": self.archive,
239 }))?;
240 if is_stub(stub) {
241 return fsutil::write_atomic(stub, &json);
242 }
243 {
244 use std::io::Write;
245 let mut f = crate::platform::create_new_no_follow(stub)
246 .with_context(|| format!("creating {}", stub.display()))?;
247 f.write_all(&json)?;
248 f.sync_all()?;
249 }
250 fsutil::sync_dir(stub.parent().unwrap_or(Path::new(".")))
251 }
252
253 pub fn check_stub(&self) -> Result<()> {
258 let Some(stub) = &self.stub else {
259 return Ok(());
260 };
261 match fs::symlink_metadata(stub) {
262 Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
263 Err(e) => Err(e).with_context(|| format!("reading {}", stub.display())),
264 Ok(_) if is_stub(stub) => Ok(()),
265 Ok(_) => {
266 let last = stub.with_extension("");
267 bail!(
268 "{} already has an extraction in progress that opened it on its own, and {} \
269 is its journal. To resume that one, move the other parts of the split ZIP \
270 out of the folder and open {}; or delete {} if no extraction of it is in \
271 progress. Nothing was modified",
272 last.display(),
273 stub.display(),
274 last.display(),
275 stub.display()
276 )
277 }
278 }
279 }
280
281 pub fn remove_stub(&self) -> Result<()> {
284 let Some(stub) = &self.stub else {
285 return Ok(());
286 };
287 if is_stub(stub) {
288 match fs::remove_file(stub) {
289 Err(e) if e.kind() != io::ErrorKind::NotFound => {
290 return Err(e).with_context(|| format!("removing {}", stub.display()));
291 }
292 _ => {}
293 }
294 }
295 Ok(())
296 }
297
298 pub fn exists(&self) -> bool {
299 self.journal.exists()
300 }
301
302 pub fn any_exist(&self) -> bool {
306 [&self.journal, &self.tail, &self.folders]
307 .into_iter()
308 .chain(&self.stub)
309 .any(|p| fs::symlink_metadata(p).is_ok())
310 }
311
312 pub fn remove(&self) -> Result<()> {
313 crate::chosen::forget(&self.archive);
314 for p in [&self.folders, &self.tail, &self.journal] {
315 match fs::remove_file(p) {
316 Err(e) if e.kind() != io::ErrorKind::NotFound => {
317 return Err(e).with_context(|| format!("removing {}", p.display()));
318 }
319 _ => {}
320 }
321 }
322 self.remove_stub()
325 }
326}
327
328pub struct Plan {
329 pub format: &'static str,
330 pub tail_start: u64,
331 pub output: PathBuf,
332 pub total_size: u64,
333 pub keep: bool,
334 pub replace: Option<Replace>,
337 pub case_folders: Vec<PathBuf>,
338 pub case_beyond_ascii: bool,
339 pub folders: Vec<crate::folders::Folder>,
342 pub only: Option<Vec<PathBuf>>,
344}
345
346fn version_for(
347 keep: bool,
348 replace: Option<&Replace>,
349 case_folders: &[PathBuf],
350 folders: bool,
351 only: bool,
352) -> u32 {
353 if only {
354 SELECT_VERSION
355 } else if folders {
356 FOLDERS_VERSION
357 } else if !case_folders.is_empty() {
358 CASE_VERSION
359 } else if replace.is_some_and(Replace::chose) {
360 CHOOSE_VERSION
361 } else if replace.is_some() {
362 REPLACE_VERSION
363 } else if keep {
364 KEEP_VERSION
365 } else {
366 VERSION
367 }
368}
369
370impl Journal {
371 pub fn create(paths: &Paths, storage: &Storage, plan: Plan) -> Result<Self> {
372 if plan.format == crate::archive::SPLIT_ZIP {
375 paths.write_stub()?;
376 }
377 let mut tail = Vec::new();
378 let mut r = storage.reader(None);
379 r.seek(SeekFrom::Start(plan.tail_start))?;
380 r.read_to_end(&mut tail)?;
381 fsutil::write_atomic(&paths.tail, &tail)?;
382 let folders = crate::folders::save(&paths.folders, &plan.folders)?;
383 let journal = Self {
384 version: version_for(
385 plan.keep,
386 plan.replace.as_ref(),
387 &plan.case_folders,
388 folders.is_some(),
389 plan.only.is_some(),
390 ),
391 format: plan.format.to_string(),
392 parts: storage.record(),
393 tail_start: plan.tail_start,
394 tail_crc: crc32fast::hash(&tail),
395 output: plan.output,
396 total_size: plan.total_size,
397 committed_len: storage.original_len(),
398 links: Vec::new(),
399 resume: None,
400 done: false,
401 restoring: None,
402 keep: plan.keep,
403 replace: plan.replace,
404 case_folders: plan.case_folders,
405 case_beyond_ascii: plan.case_beyond_ascii,
406 folders,
407 folders_left: false,
408 only: plan.only,
409 };
410 journal.save(paths)?;
411 Ok(journal)
412 }
413
414 pub fn check_folders(&self, paths: &Paths) -> Result<()> {
419 if let Some(saved) = self.folders {
420 crate::folders::load(&paths.folders, saved).map_err(|e| {
421 anyhow!("{e:#}. Put it back, or run `hatchzip restore` to give the archive back.")
422 })?;
423 }
424 Ok(())
425 }
426
427 pub fn load(paths: &Paths) -> Result<(Self, Arc<Tail>)> {
428 let bytes = fs::read(&paths.journal)
429 .with_context(|| format!("reading {}", paths.journal.display()))?;
430 #[derive(Deserialize)]
433 struct Versioned {
434 version: u32,
435 }
436 let version = serde_json::from_slice::<Versioned>(&bytes)
437 .with_context(|| format!("{} is damaged", paths.journal.display()))?
438 .version;
439 if version == STUB_VERSION {
440 bail!(
441 "{} marks {} as the last part of a split ZIP being extracted from its .z01 part. \
442 Open the .z01 part to continue that extraction, or delete {} if no extraction \
443 of it is in progress. Nothing was modified",
444 paths.journal.display(),
445 paths.archive.display(),
446 paths.journal.display()
447 );
448 }
449 if !READABLE.contains(&version) {
450 let which = if version > VERSION {
451 "a newer"
452 } else {
453 "an older"
454 };
455 bail!(
456 "{} was written by {which} HatchZip version (journal format {version}); \
457 complete the extraction with that version",
458 paths.journal.display()
459 );
460 }
461 let mut journal: Self = serde_json::from_slice(&bytes)
462 .with_context(|| format!("{} is damaged", paths.journal.display()))?;
463 let case = version == CASE_VERSION;
468 let folders = version == FOLDERS_VERSION;
469 let selects = version == SELECT_VERSION;
470 let later = folders || selects;
471 let replaces = version == REPLACE_VERSION || version == CHOOSE_VERSION;
472 if (!selects && journal.folders.is_some() != folders)
473 || (journal.folders_left && journal.folders.is_none())
474 || journal.only.is_some() != selects
475 || (selects && !journal.keep)
476 || journal.only.as_ref().is_some_and(|o| {
477 o.is_empty()
478 || !o.iter().all(|p| {
479 p.components().next().is_some()
480 && p.components().all(|c| matches!(c, Component::Normal(_)))
481 })
482 })
483 || (case && journal.case_folders.is_empty())
484 || (!case && !later && !journal.case_folders.is_empty())
485 || (journal.case_beyond_ascii && journal.case_folders.is_empty())
486 || (!case
487 && !later
488 && (journal.replace.is_some() != replaces
489 || journal.replace.as_ref().is_some_and(Replace::chose)
490 != (version == CHOOSE_VERSION)
491 || (!replaces && journal.keep != (version == KEEP_VERSION))))
492 || journal
494 .case_folders
495 .iter()
496 .any(|p| !p.components().all(|c| matches!(c, Component::Normal(_))))
497 {
498 bail!("{} is damaged", paths.journal.display());
499 }
500 let inside = |p: &PathBuf| {
503 p.components().next().is_some()
504 && p.components().all(|c| matches!(c, Component::Normal(_)))
505 };
506 if let Some(r) = &journal.replace
507 && !r.keep.iter().chain(&r.both).all(inside)
508 {
509 bail!("{} is damaged", paths.journal.display());
510 }
511 journal.version = version_for(
512 journal.keep,
513 journal.replace.as_ref(),
514 &journal.case_folders,
515 journal.folders.is_some(),
516 journal.only.is_some(),
517 );
518 journal.check_bound(paths)?;
519 let tail =
520 fs::read(&paths.tail).with_context(|| format!("reading {}", paths.tail.display()))?;
521 let len: u64 = journal.parts.iter().map(|(_, l)| l).sum();
522 if crc32fast::hash(&tail) != journal.tail_crc
523 || journal.tail_start + tail.len() as u64 != len
524 {
525 bail!("{} does not match its journal", paths.tail.display());
526 }
527 let tail = Arc::new(Tail {
528 start: journal.tail_start,
529 bytes: tail,
530 });
531 Ok((journal, tail))
532 }
533
534 pub fn save(&self, paths: &Paths) -> Result<()> {
535 fsutil::write_atomic(&paths.journal, &serde_json::to_vec(self)?)
536 }
537
538 pub(crate) fn side_files(&self, paths: &Paths) -> String {
541 match self.folders {
542 Some(_) => format!(
543 "{}, {} and {}",
544 paths.journal.display(),
545 paths.tail.display(),
546 paths.folders.display()
547 ),
548 None => format!("{} and {}", paths.journal.display(), paths.tail.display()),
549 }
550 }
551
552 fn check_bound(&self, paths: &Paths) -> Result<()> {
558 let foreign = || {
559 anyhow!(
560 "{} does not belong to {}, so it was not used and nothing was modified. If the \
561 archive was moved during an extraction, move it back to resume; otherwise \
562 delete {}",
563 paths.journal.display(),
564 paths.archive.display(),
565 self.side_files(paths)
566 )
567 };
568 if self.parts.is_empty() {
569 return Err(foreign());
570 }
571 let split = self.format == crate::archive::SPLIT_ZIP;
574 if split != (storage::is_split_zip(&paths.archive) && self.parts.len() > 1) {
575 return Err(foreign());
576 }
577 let count = self.parts.len();
578 for (i, (part, _)) in self.parts.iter().enumerate() {
579 if !storage::volume_path_in(&paths.archive, i, count)
580 .is_some_and(|v| fsutil::same_path(&v, part))
581 {
582 return Err(foreign());
583 }
584 }
585 let len: u64 = self.parts.iter().map(|(_, l)| l).sum();
587 let within = |(at, bytes): &(u64, Vec<u8>)| {
588 at.checked_add(bytes.len() as u64)
589 .is_some_and(|end| end <= len)
590 };
591 if self
592 .restoring
593 .as_ref()
594 .is_some_and(|r| !r.iter().all(within))
595 {
596 bail!(
597 "{} is damaged: it records bytes outside the archive. Nothing was modified",
598 paths.journal.display()
599 );
600 }
601 let inside = |p: &Path| {
602 p.components().next().is_some()
603 && p.components().all(|c| matches!(c, Component::Normal(_)))
604 };
605 for link in &self.links {
606 if !inside(&link.path) || (link.hard && !inside(&link.target)) {
607 bail!(
608 "{} is damaged: it records a link outside the output folder. Nothing was \
609 modified",
610 paths.journal.display()
611 );
612 }
613 }
614 Ok(())
615 }
616}
617
618#[cfg(test)]
619mod tests {
620 use super::*;
621
622 fn write(dir: &Path, version: u32) -> Paths {
623 write_with(dir, version, "")
624 }
625
626 fn write_with(dir: &Path, version: u32, extra: &str) -> Paths {
627 let paths = Paths::for_archive(&dir.join("game.zip"));
628 let tail = b"saved tail";
629 fs::write(&paths.tail, tail).unwrap();
630 let json = format!(
631 r#"{{"version":{version},"format":"zip","parts":[[{},{}]],"tail_start":0,
632 "tail_crc":{},"output":"out","total_size":0,"committed_len":0,"links":[]{extra}}}"#,
633 serde_json::to_string(&dir.join("game.zip")).unwrap(),
634 tail.len(),
635 crc32fast::hash(tail)
636 );
637 fs::write(&paths.journal, json).unwrap();
638 paths
639 }
640
641 #[test]
645 fn a_stub_never_replaces_a_journal() {
646 let dir =
647 std::env::temp_dir().join(format!("hatchzip-journal-stub-{}", std::process::id()));
648 fs::create_dir_all(&dir).unwrap();
649 let lone = write(&dir, 3);
650 let before = fs::read(&lone.journal).unwrap();
651 let split = Paths::for_archive(&dir.join("game.z01"));
652 assert_eq!(split.stub.as_deref(), Some(lone.journal.as_path()));
653
654 let err = split.write_stub().unwrap_err().to_string();
655 assert!(
656 err.contains("already has an extraction in progress"),
657 "{err}"
658 );
659 assert!(split.check_stub().is_err());
660 split.remove_stub().unwrap();
661 assert_eq!(fs::read(&lone.journal).unwrap(), before);
662
663 fs::remove_file(&lone.journal).unwrap();
664 split.write_stub().unwrap();
665 split.check_stub().unwrap();
666 split.write_stub().unwrap();
667 split.remove_stub().unwrap();
668 assert!(!lone.journal.exists());
669 fs::remove_dir_all(&dir).unwrap();
670 }
671
672 #[test]
675 fn keeping_the_archive_is_version_4_and_only_that_is() {
676 let dir =
677 std::env::temp_dir().join(format!("hatchzip-journal-keep-{}", std::process::id()));
678 fs::create_dir_all(&dir).unwrap();
679
680 let (journal, _) = Journal::load(&write_with(&dir, 4, r#","keep":true"#)).unwrap();
681 assert!(journal.keep);
682 assert_eq!(journal.version, KEEP_VERSION);
683 let saved = serde_json::to_string(&journal).unwrap();
684 assert!(saved.contains(r#""version":4"#) && saved.contains(r#""keep":true"#));
685
686 let (journal, _) = Journal::load(&write(&dir, 3)).unwrap();
687 assert!(!journal.keep);
688 assert!(
689 !serde_json::to_string(&journal)
690 .unwrap()
691 .contains(r#""keep":"#)
692 );
693
694 assert!(Journal::load(&write(&dir, 4)).is_err());
696 assert!(Journal::load(&write_with(&dir, 3, r#","keep":true"#)).is_err());
697
698 fs::remove_dir_all(&dir).unwrap();
699 }
700
701 #[test]
704 fn replacing_files_is_version_5_and_only_that_is() {
705 let dir =
706 std::env::temp_dir().join(format!("hatchzip-journal-replace-{}", std::process::id()));
707 fs::create_dir_all(&dir).unwrap();
708
709 let moving = r#","replace":{"moved":false}"#;
710 let (journal, _) = Journal::load(&write_with(&dir, 5, moving)).unwrap();
711 assert_eq!(journal.replace, Some(replace(false)));
712 assert!(!journal.keep);
713 let saved = serde_json::to_string(&journal).unwrap();
714 assert!(saved.contains(r#""version":5"#), "{saved}");
715 assert!(!saved.contains("both"), "{saved}");
716
717 let kept = r#","keep":true,"replace":{"moved":true}"#;
718 let (journal, _) = Journal::load(&write_with(&dir, 5, kept)).unwrap();
719 assert!(journal.keep && journal.replace == Some(replace(true)));
720 assert_eq!(journal.version, REPLACE_VERSION);
721
722 assert!(Journal::load(&write(&dir, 5)).is_err());
723 assert!(Journal::load(&write_with(&dir, 3, moving)).is_err());
724 assert!(Journal::load(&write_with(&dir, 4, &format!(r#","keep":true{moving}"#))).is_err());
725
726 fs::remove_dir_all(&dir).unwrap();
727 }
728
729 fn replace(moved: bool) -> Replace {
730 Replace {
731 moved,
732 keep: Vec::new(),
733 both: Vec::new(),
734 }
735 }
736
737 #[test]
740 fn choosing_per_file_is_version_6_and_only_that_is() {
741 let dir =
742 std::env::temp_dir().join(format!("hatchzip-journal-choose-{}", std::process::id()));
743 fs::create_dir_all(&dir).unwrap();
744
745 let chose = r#","replace":{"moved":false,"keep":["a.txt"],"both":["b/c.txt"]}"#;
746 let (journal, _) = Journal::load(&write_with(&dir, 6, chose)).unwrap();
747 let r = journal.replace.as_ref().unwrap();
748 assert_eq!(r.keep, [PathBuf::from("a.txt")]);
749 assert_eq!(r.both, [PathBuf::from("b/c.txt")]);
750 assert_eq!(journal.version, CHOOSE_VERSION);
751
752 assert!(Journal::load(&write_with(&dir, 5, chose)).is_err());
753 assert!(Journal::load(&write_with(&dir, 6, r#","replace":{"moved":false}"#)).is_err());
754
755 fs::remove_dir_all(&dir).unwrap();
756 }
757
758 #[test]
761 fn reads_case_folders_at_their_version_only() {
762 let dir =
763 std::env::temp_dir().join(format!("hatchzip-journal-case-{}", std::process::id()));
764 fs::create_dir_all(&dir).unwrap();
765
766 for fields in [
767 r#","case_folders":["","a/b"]"#,
768 r#","case_folders":["a"],"keep":true"#,
769 r#","case_folders":["a"],"replace":{"moved":false}"#,
770 ] {
771 let (journal, _) = Journal::load(&write_with(&dir, 7, fields)).unwrap();
772 assert_eq!(journal.version, CASE_VERSION, "{fields}");
773 }
774 assert!(Journal::load(&write_with(&dir, 7, "")).is_err());
775 assert!(Journal::load(&write_with(&dir, 3, r#","case_folders":["a"]"#)).is_err());
776 assert!(Journal::load(&write_with(&dir, 3, r#","case_beyond_ascii":true"#)).is_err());
777 assert!(Journal::load(&write_with(&dir, 7, r#","case_folders":["../a"]"#)).is_err());
778
779 fs::remove_dir_all(&dir).unwrap();
780 }
781
782 #[test]
785 fn saved_folders_are_version_8_and_only_that_is() {
786 let dir =
787 std::env::temp_dir().join(format!("hatchzip-journal-folders-{}", std::process::id()));
788 fs::create_dir_all(&dir).unwrap();
789
790 let list = [crate::folders::Folder {
791 path: PathBuf::from("docs"),
792 mode: Some(0o750),
793 mtime: None,
794 }];
795 let saved = crate::folders::save(&dir.join("game.zip.hatchzip-folders"), &list)
796 .unwrap()
797 .unwrap();
798 let folders = &format!(
799 r#","folders":{{"count":{},"crc":{}}}"#,
800 saved.count, saved.crc
801 );
802 let (journal, _) = Journal::load(&write_with(&dir, 8, folders)).unwrap();
803 assert_eq!(journal.version, FOLDERS_VERSION);
804 let kept = format!(r#","keep":true,"replace":{{"moved":true,"keep":["a.txt"]}}{folders}"#);
805 let (journal, _) = Journal::load(&write_with(&dir, 8, &kept)).unwrap();
806 assert!(journal.keep && journal.replace.as_ref().is_some_and(Replace::chose));
807 assert_eq!(journal.version, FOLDERS_VERSION);
808
809 let both = format!(r#","case_folders":["a"],"case_beyond_ascii":true{folders}"#);
811 let (journal, _) = Journal::load(&write_with(&dir, 8, &both)).unwrap();
812 assert_eq!(journal.case_folders, [PathBuf::from("a")]);
813 assert!(journal.case_beyond_ascii && journal.folders.is_some());
814 assert_eq!(journal.version, FOLDERS_VERSION);
815
816 assert!(Journal::load(&write_with(&dir, 8, "")).is_err());
817 assert!(Journal::load(&write_with(&dir, 3, folders)).is_err());
818 assert!(Journal::load(&write_with(&dir, 7, folders)).is_err());
819 let both = format!(r#","case_folders":["a"]{folders}"#);
820 assert!(Journal::load(&write_with(&dir, 7, &both)).is_err());
821 let ascii = format!(r#","case_beyond_ascii":true{folders}"#);
822 assert!(Journal::load(&write_with(&dir, 8, &ascii)).is_err());
823 let outside = format!(r#","case_folders":["../a"]{folders}"#);
824 assert!(Journal::load(&write_with(&dir, 8, &outside)).is_err());
825 assert!(Journal::load(&write_with(&dir, 3, r#","folders_left":true"#)).is_err());
826
827 fs::write(dir.join("game.zip.hatchzip-folders"), b"[]").unwrap();
830 let paths = write_with(&dir, 8, folders);
831 let (journal, _) = Journal::load(&paths).unwrap();
832 assert!(journal.check_folders(&paths).is_err());
833
834 fs::remove_dir_all(&dir).unwrap();
835 }
836
837 #[test]
840 fn a_selection_is_version_9_and_only_that_is() {
841 let dir =
842 std::env::temp_dir().join(format!("hatchzip-journal-only-{}", std::process::id()));
843 fs::create_dir_all(&dir).unwrap();
844
845 let only = r#","keep":true,"only":["docs","bin/tool"]"#;
846 let (journal, _) = Journal::load(&write_with(&dir, 9, only)).unwrap();
847 assert_eq!(
848 journal.only,
849 Some(vec![PathBuf::from("docs"), PathBuf::from("bin/tool")])
850 );
851 assert_eq!(journal.version, SELECT_VERSION);
852 let saved = serde_json::to_string(&journal).unwrap();
853 assert!(saved.contains(r#""version":9"#), "{saved}");
854 let more = r#","keep":true,"only":["a"],"case_folders":["a"],"replace":{"moved":true}"#;
856 let (journal, _) = Journal::load(&write_with(&dir, 9, more)).unwrap();
857 assert_eq!(journal.version, SELECT_VERSION);
858
859 assert!(Journal::load(&write_with(&dir, 4, only)).is_err());
862 assert!(Journal::load(&write_with(&dir, 8, only)).is_err());
863 assert!(Journal::load(&write_with(&dir, 9, r#","keep":true"#)).is_err());
864 assert!(Journal::load(&write_with(&dir, 9, r#","only":["a"]"#)).is_err());
865 assert!(Journal::load(&write_with(&dir, 9, r#","keep":true,"only":[]"#)).is_err());
866 assert!(Journal::load(&write_with(&dir, 9, r#","keep":true,"only":["../a"]"#)).is_err());
867 assert!(Journal::load(&write_with(&dir, 9, r#","keep":true,"only":["/a"]"#)).is_err());
868 assert!(Journal::load(&write_with(&dir, 9, r#","keep":true,"only":[""]"#)).is_err());
869
870 fs::remove_dir_all(&dir).unwrap();
871 }
872
873 #[test]
876 fn reads_version_2_and_refuses_newer_journals() {
877 let dir = std::env::temp_dir().join(format!("hatchzip-journal-{}", std::process::id()));
878 fs::create_dir_all(&dir).unwrap();
879
880 let (journal, _) = Journal::load(&write(&dir, 2)).unwrap();
881 assert_eq!(journal.resume, None);
882 assert_eq!(journal.version, VERSION);
883
884 let err = Journal::load(&write(&dir, SELECT_VERSION + 1))
885 .err()
886 .unwrap();
887 assert!(format!("{err:#}").contains("newer HatchZip"), "{err:#}");
888 let err = Journal::load(&write(&dir, 1)).err().unwrap();
889 assert!(format!("{err:#}").contains("older HatchZip"), "{err:#}");
890
891 fs::remove_dir_all(&dir).unwrap();
892 }
893}