Skip to main content

hatchzip_core/
journal.rs

1//! Progress record that makes an interrupted extraction resumable.
2//!
3//! ZIP and 7z keep their index at the end of the archive, which is the first
4//! thing truncation destroys. So before the first byte is reclaimed the tail
5//! of the archive is copied to a side file, and from then on the archive is
6//! parsed through a reader that serves the saved tail at its old offsets.
7
8use 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
20/// Version 3 added `resume`. A version 2 journal can't hold one, so it reads
21/// as is. Older HatchZip builds refuse version 3, which matters: they would
22/// delete a half-extracted file whose archive bytes are already freed.
23const VERSION: u32 = 3;
24/// An extraction that keeps the archive writes version 4, unless a later
25/// version below takes over.
26/// Builds before `keep` existed refuse it, which matters just as much: they
27/// would resume it in place and truncate the archive the user kept. Every
28/// other journal stays at version 3, so an older build can still finish it.
29const KEEP_VERSION: u32 = 4;
30/// An extraction that replaces existing files writes version 5, kept
31/// archive or not, unless a later version below takes over. Builds before
32/// `replace` existed refuse it: they would delete the person's files at the
33/// paths of entries left to do, and a restore would not put the replaced
34/// ones back.
35const REPLACE_VERSION: u32 = 5;
36/// One that keeps some existing files, or both copies of them, writes
37/// version 6. A build before that would finish it by deleting the files the
38/// person chose to keep.
39const CHOOSE_VERSION: u32 = 6;
40/// One with names that differ only in case writes version 7. A build before
41/// that never asks where it may resume such a run, so on a filesystem that
42/// ignores case it would delete an extracted file as its own.
43const CASE_VERSION: u32 = 7;
44/// One whose archive has folder entries with permissions or times writes
45/// version 8, whatever else it does, names that differ only in case included,
46/// and keeps them in a side file. A build before that would finish without
47/// setting them.
48const FOLDERS_VERSION: u32 = 8;
49const READABLE: [u32; 7] = [2, 3, 4, 5, 6, 7, 8];
50
51#[derive(Serialize, Deserialize, Clone)]
52pub struct Link {
53    pub path: PathBuf,
54    pub target: PathBuf,
55    pub hard: bool,
56}
57
58/// Where extraction of a large file can pick up again after a crash. Its
59/// output up to `written` is flushed to disk, and the archive bytes before
60/// the one holding `bit` may already be freed, so this is the only way back.
61#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
62pub struct Resume {
63    /// The unit, by the offset it starts at.
64    pub unit: u64,
65    /// Bytes of output in `<name>.hatchzip-part`, flushed. Anything the file
66    /// holds past this was written after the point and is thrown away.
67    pub written: u64,
68    /// Where decoding restarts, in bits from the start of the archive. Only
69    /// deflate streams ever stop between two bytes.
70    pub bit: u64,
71    /// CRC-32 of the first `written` bytes of output. Unused for a
72    /// compressed tar, whose checksums are per gzip member, in `stream`.
73    pub crc: u32,
74    /// For a compressed tar, where one stream holds every entry: the
75    /// decoder's and the tar parser's state at `bit`. `written` is then how
76    /// much of the entry being extracted is in its part file, if the point
77    /// lies inside a file. Older builds don't know the format and refuse the
78    /// journal before reading this.
79    #[serde(default, skip_serializing_if = "Option::is_none")]
80    pub stream: Option<Box<StreamPoint>>,
81}
82
83#[derive(Serialize, Deserialize)]
84pub struct Journal {
85    pub version: u32,
86    pub format: String,
87    /// Every part of the archive with its original length.
88    pub parts: Vec<(PathBuf, u64)>,
89    pub tail_start: u64,
90    pub tail_crc: u32,
91    pub output: PathBuf,
92    pub total_size: u64,
93    /// The archive is truncated to this once the latest batch is committed.
94    /// Every unit starting at or after it is done.
95    pub committed_len: u64,
96    /// Links are made last, so nothing extracted can be written through one
97    /// and every hard link's target already exists.
98    pub links: Vec<Link>,
99    /// The large file being extracted while its archive bytes are freed, if
100    /// one is in progress. It always belongs to the highest uncommitted unit.
101    #[serde(default)]
102    pub resume: Option<Resume>,
103    /// Every unit was extracted and the final commit was journaled: only the
104    /// archive's removal and the links are left. A compressed stream lands
105    /// here with its archive punched up to its last resume point, so it no
106    /// longer parses from its start and must not be read again.
107    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
108    pub done: bool,
109    /// Set while `restore` turns the archive back into a normal one: the
110    /// bytes it overwrites below `committed_len`, so that an interrupted
111    /// restore can be undone by putting them back and cutting off whatever it
112    /// appended.
113    #[serde(default, skip_serializing_if = "Option::is_none")]
114    pub restoring: Option<Vec<(u64, Vec<u8>)>>,
115    /// The extraction keeps the archive: nothing is truncated, punched or
116    /// deleted, and `committed_len` only records progress. A resume keeps
117    /// it too, whatever it is asked.
118    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
119    pub keep: bool,
120    /// The extraction replaces files that were in the output folder before
121    /// it started; see [`crate::replace`].
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub replace: Option<Replace>,
124    /// The folders, inside the output, where entries' names differ only in
125    /// case. A resume and a restore ask about them again, not trusting the
126    /// answer from when the run began; see [`crate::session::check_recorded_case`].
127    #[serde(default, skip_serializing_if = "Vec::is_empty")]
128    pub case_folders: Vec<PathBuf>,
129    /// Some of those names go outside ASCII, so a system that normalizes
130    /// names may take them for one file, whatever its filesystem says about
131    /// case. Asked again for the same reason.
132    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
133    pub case_beyond_ascii: bool,
134    /// The archive's folder entries are saved in their own file, set once
135    /// every file and link is made; see [`crate::folders`].
136    #[serde(default, skip_serializing_if = "Option::is_none")]
137    pub folders: Option<crate::folders::Saved>,
138    /// Every link is made and every put-back file settled: only the folders
139    /// and the cleanup are left, and a resume does just that. Making a link
140    /// again would need write permission on its folder, which the folder's
141    /// own mode may have taken away by then.
142    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
143    pub folders_left: bool,
144}
145
146#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
147pub struct Replace {
148    /// Every file at the path of an entry left to do is in the replaced
149    /// files folder. Until then nothing is extracted, so whatever sits at
150    /// those paths is still the person's.
151    pub moved: bool,
152    /// Existing files, relative to the output, that go back over what was
153    /// extracted at their paths once the extraction completes.
154    #[serde(default, skip_serializing_if = "Vec::is_empty")]
155    pub keep: Vec<PathBuf>,
156    /// Existing files that go back to their paths once the extraction
157    /// completes, with the extracted copy renamed beside them.
158    #[serde(default, skip_serializing_if = "Vec::is_empty")]
159    pub both: Vec<PathBuf>,
160}
161
162impl Replace {
163    fn chose(&self) -> bool {
164        !self.keep.is_empty() || !self.both.is_empty()
165    }
166}
167
168pub struct Paths {
169    /// The first volume of the archive the side files belong to.
170    pub archive: PathBuf,
171    pub journal: PathBuf,
172    pub tail: PathBuf,
173    pub folders: PathBuf,
174}
175
176impl Paths {
177    pub fn for_archive(archive: &Path) -> Self {
178        let with = |suffix: &str| {
179            let mut s = archive.as_os_str().to_owned();
180            s.push(suffix);
181            PathBuf::from(s)
182        };
183        Self {
184            archive: archive.to_path_buf(),
185            journal: with(".hatchzip"),
186            tail: with(".hatchzip-tail"),
187            folders: with(".hatchzip-folders"),
188        }
189    }
190
191    pub fn exists(&self) -> bool {
192        self.journal.exists()
193    }
194
195    pub fn remove(&self) -> Result<()> {
196        crate::chosen::forget(&self.archive);
197        for p in [&self.folders, &self.tail, &self.journal] {
198            match fs::remove_file(p) {
199                Err(e) if e.kind() != io::ErrorKind::NotFound => {
200                    return Err(e).with_context(|| format!("removing {}", p.display()));
201                }
202                _ => {}
203            }
204        }
205        Ok(())
206    }
207}
208
209pub struct Plan {
210    pub format: &'static str,
211    pub tail_start: u64,
212    pub output: PathBuf,
213    pub total_size: u64,
214    pub keep: bool,
215    /// Existing files are moved aside before the first entry is extracted,
216    /// and what to do with each once it completes.
217    pub replace: Option<Replace>,
218    pub case_folders: Vec<PathBuf>,
219    pub case_beyond_ascii: bool,
220    /// Folder entries with a mode or a time, saved before anything is
221    /// extracted.
222    pub folders: Vec<crate::folders::Folder>,
223}
224
225fn version_for(
226    keep: bool,
227    replace: Option<&Replace>,
228    case_folders: &[PathBuf],
229    folders: bool,
230) -> u32 {
231    if folders {
232        FOLDERS_VERSION
233    } else if !case_folders.is_empty() {
234        CASE_VERSION
235    } else if replace.is_some_and(Replace::chose) {
236        CHOOSE_VERSION
237    } else if replace.is_some() {
238        REPLACE_VERSION
239    } else if keep {
240        KEEP_VERSION
241    } else {
242        VERSION
243    }
244}
245
246impl Journal {
247    pub fn create(paths: &Paths, storage: &Storage, plan: Plan) -> Result<Self> {
248        let mut tail = Vec::new();
249        let mut r = storage.reader(None);
250        r.seek(SeekFrom::Start(plan.tail_start))?;
251        r.read_to_end(&mut tail)?;
252        fsutil::write_atomic(&paths.tail, &tail)?;
253        let folders = crate::folders::save(&paths.folders, &plan.folders)?;
254        let journal = Self {
255            version: version_for(
256                plan.keep,
257                plan.replace.as_ref(),
258                &plan.case_folders,
259                folders.is_some(),
260            ),
261            format: plan.format.to_string(),
262            parts: storage.record(),
263            tail_start: plan.tail_start,
264            tail_crc: crc32fast::hash(&tail),
265            output: plan.output,
266            total_size: plan.total_size,
267            committed_len: storage.original_len(),
268            links: Vec::new(),
269            resume: None,
270            done: false,
271            restoring: None,
272            keep: plan.keep,
273            replace: plan.replace,
274            case_folders: plan.case_folders,
275            case_beyond_ascii: plan.case_beyond_ascii,
276            folders,
277            folders_left: false,
278        };
279        journal.save(paths)?;
280        Ok(journal)
281    }
282
283    /// For a resume, before it changes anything: the list is read at the very
284    /// end, and a resume past a missing or damaged one would free the rest of
285    /// the archive and only then fail. Nothing else needs the list, so a lost
286    /// one stops neither a look at the archive nor a restore.
287    pub fn check_folders(&self, paths: &Paths) -> Result<()> {
288        if let Some(saved) = self.folders {
289            crate::folders::load(&paths.folders, saved).map_err(|e| {
290                anyhow!("{e:#}. Put it back, or run `hatchzip restore` to give the archive back.")
291            })?;
292        }
293        Ok(())
294    }
295
296    pub fn load(paths: &Paths) -> Result<(Self, Arc<Tail>)> {
297        let bytes = fs::read(&paths.journal)
298            .with_context(|| format!("reading {}", paths.journal.display()))?;
299        // The version is checked before the rest is parsed, so a newer layout
300        // gets the version message rather than a confusing parse error.
301        #[derive(Deserialize)]
302        struct Versioned {
303            version: u32,
304        }
305        let version = serde_json::from_slice::<Versioned>(&bytes)
306            .with_context(|| format!("{} is damaged", paths.journal.display()))?
307            .version;
308        if !READABLE.contains(&version) {
309            let which = if version > VERSION {
310                "a newer"
311            } else {
312                "an older"
313            };
314            bail!(
315                "{} was written by {which} HatchZip version (journal format {version}); \
316                 complete the extraction with that version",
317                paths.journal.display()
318            );
319        }
320        let mut journal: Self = serde_json::from_slice(&bytes)
321            .with_context(|| format!("{} is damaged", paths.journal.display()))?;
322        // Versions 7 and 8 are written whatever else the run does, so they say
323        // nothing about keeping or replacing. Only 8 has folders, and only
324        // those two may have case folders, which 7 is there for.
325        let case = version == CASE_VERSION;
326        let folders = version == FOLDERS_VERSION;
327        let replaces = version == REPLACE_VERSION || version == CHOOSE_VERSION;
328        if journal.folders.is_some() != folders
329            || (journal.folders_left && !folders)
330            || (case && journal.case_folders.is_empty())
331            || (!case && !folders && !journal.case_folders.is_empty())
332            || (journal.case_beyond_ascii && journal.case_folders.is_empty())
333            || (!case
334                && !folders
335                && (journal.replace.is_some() != replaces
336                    || journal.replace.as_ref().is_some_and(Replace::chose)
337                        != (version == CHOOSE_VERSION)
338                    || (!replaces && journal.keep != (version == KEEP_VERSION))))
339            // The top of the output, where names can meet, is an empty path.
340            || journal
341                .case_folders
342                .iter()
343                .any(|p| !p.components().all(|c| matches!(c, Component::Normal(_))))
344        {
345            bail!("{} is damaged", paths.journal.display());
346        }
347        // Each is joined to the output folder and renamed, so each must stay
348        // inside it.
349        let inside = |p: &PathBuf| {
350            p.components().next().is_some()
351                && p.components().all(|c| matches!(c, Component::Normal(_)))
352        };
353        if let Some(r) = &journal.replace
354            && !r.keep.iter().chain(&r.both).all(inside)
355        {
356            bail!("{} is damaged", paths.journal.display());
357        }
358        journal.version = version_for(
359            journal.keep,
360            journal.replace.as_ref(),
361            &journal.case_folders,
362            journal.folders.is_some(),
363        );
364        journal.check_bound(paths)?;
365        let tail =
366            fs::read(&paths.tail).with_context(|| format!("reading {}", paths.tail.display()))?;
367        let len: u64 = journal.parts.iter().map(|(_, l)| l).sum();
368        if crc32fast::hash(&tail) != journal.tail_crc
369            || journal.tail_start + tail.len() as u64 != len
370        {
371            bail!("{} does not match its journal", paths.tail.display());
372        }
373        let tail = Arc::new(Tail {
374            start: journal.tail_start,
375            bytes: tail,
376        });
377        Ok((journal, tail))
378    }
379
380    pub fn save(&self, paths: &Paths) -> Result<()> {
381        fsutil::write_atomic(&paths.journal, &serde_json::to_vec(self)?)
382    }
383
384    /// The journal is a file next to the archive, so anyone who could put
385    /// the archive there could have written it too. Whatever it names may
386    /// only be what an extraction of this archive touches: the archive's own
387    /// volumes, and links inside the output folder. The output folder itself
388    /// is checked by [`crate::session::check_output`].
389    fn check_bound(&self, paths: &Paths) -> Result<()> {
390        let foreign = || {
391            let files = match self.folders {
392                Some(_) => format!(
393                    "{}, {} and {}",
394                    paths.journal.display(),
395                    paths.tail.display(),
396                    paths.folders.display()
397                ),
398                None => format!("{} and {}", paths.journal.display(), paths.tail.display()),
399            };
400            anyhow!(
401                "{} does not belong to {}, so it was not used and nothing was modified. If the \
402                 archive was moved during an extraction, move it back to resume; otherwise \
403                 delete {files}",
404                paths.journal.display(),
405                paths.archive.display(),
406            )
407        };
408        if self.parts.is_empty() {
409            return Err(foreign());
410        }
411        for (i, (part, _)) in self.parts.iter().enumerate() {
412            if !storage::volume_path(&paths.archive, i).is_some_and(|v| fsutil::same_path(&v, part))
413            {
414                return Err(foreign());
415            }
416        }
417        // Restore only ever saves bytes it overwrites inside the archive.
418        let len: u64 = self.parts.iter().map(|(_, l)| l).sum();
419        let within = |(at, bytes): &(u64, Vec<u8>)| {
420            at.checked_add(bytes.len() as u64)
421                .is_some_and(|end| end <= len)
422        };
423        if self
424            .restoring
425            .as_ref()
426            .is_some_and(|r| !r.iter().all(within))
427        {
428            bail!(
429                "{} is damaged: it records bytes outside the archive. Nothing was modified",
430                paths.journal.display()
431            );
432        }
433        let inside = |p: &Path| {
434            p.components().next().is_some()
435                && p.components().all(|c| matches!(c, Component::Normal(_)))
436        };
437        for link in &self.links {
438            if !inside(&link.path) || (link.hard && !inside(&link.target)) {
439                bail!(
440                    "{} is damaged: it records a link outside the output folder. Nothing was \
441                     modified",
442                    paths.journal.display()
443                );
444            }
445        }
446        Ok(())
447    }
448}
449
450#[cfg(test)]
451mod tests {
452    use super::*;
453
454    fn write(dir: &Path, version: u32) -> Paths {
455        write_with(dir, version, "")
456    }
457
458    fn write_with(dir: &Path, version: u32, extra: &str) -> Paths {
459        let paths = Paths::for_archive(&dir.join("game.zip"));
460        let tail = b"saved tail";
461        fs::write(&paths.tail, tail).unwrap();
462        let json = format!(
463            r#"{{"version":{version},"format":"zip","parts":[[{},{}]],"tail_start":0,
464                "tail_crc":{},"output":"out","total_size":0,"committed_len":0,"links":[]{extra}}}"#,
465            serde_json::to_string(&dir.join("game.zip")).unwrap(),
466            tail.len(),
467            crc32fast::hash(tail)
468        );
469        fs::write(&paths.journal, json).unwrap();
470        paths
471    }
472
473    /// Only an extraction that keeps the archive writes version 4, so older
474    /// builds, which would truncate it, refuse it; in-place runs stay at 3.
475    #[test]
476    fn keeping_the_archive_is_version_4_and_only_that_is() {
477        let dir =
478            std::env::temp_dir().join(format!("hatchzip-journal-keep-{}", std::process::id()));
479        fs::create_dir_all(&dir).unwrap();
480
481        let (journal, _) = Journal::load(&write_with(&dir, 4, r#","keep":true"#)).unwrap();
482        assert!(journal.keep);
483        assert_eq!(journal.version, KEEP_VERSION);
484        let saved = serde_json::to_string(&journal).unwrap();
485        assert!(saved.contains(r#""version":4"#) && saved.contains(r#""keep":true"#));
486
487        let (journal, _) = Journal::load(&write(&dir, 3)).unwrap();
488        assert!(!journal.keep);
489        assert!(
490            !serde_json::to_string(&journal)
491                .unwrap()
492                .contains(r#""keep":"#)
493        );
494
495        // A mismatch means someone edited the file.
496        assert!(Journal::load(&write(&dir, 4)).is_err());
497        assert!(Journal::load(&write_with(&dir, 3, r#","keep":true"#)).is_err());
498
499        fs::remove_dir_all(&dir).unwrap();
500    }
501
502    /// Replacing files is version 5 whether the archive is kept or not, and
503    /// no other journal may say it replaces anything.
504    #[test]
505    fn replacing_files_is_version_5_and_only_that_is() {
506        let dir =
507            std::env::temp_dir().join(format!("hatchzip-journal-replace-{}", std::process::id()));
508        fs::create_dir_all(&dir).unwrap();
509
510        let moving = r#","replace":{"moved":false}"#;
511        let (journal, _) = Journal::load(&write_with(&dir, 5, moving)).unwrap();
512        assert_eq!(journal.replace, Some(replace(false)));
513        assert!(!journal.keep);
514        let saved = serde_json::to_string(&journal).unwrap();
515        assert!(saved.contains(r#""version":5"#), "{saved}");
516        assert!(!saved.contains("both"), "{saved}");
517
518        let kept = r#","keep":true,"replace":{"moved":true}"#;
519        let (journal, _) = Journal::load(&write_with(&dir, 5, kept)).unwrap();
520        assert!(journal.keep && journal.replace == Some(replace(true)));
521        assert_eq!(journal.version, REPLACE_VERSION);
522
523        assert!(Journal::load(&write(&dir, 5)).is_err());
524        assert!(Journal::load(&write_with(&dir, 3, moving)).is_err());
525        assert!(Journal::load(&write_with(&dir, 4, &format!(r#","keep":true{moving}"#))).is_err());
526
527        fs::remove_dir_all(&dir).unwrap();
528    }
529
530    fn replace(moved: bool) -> Replace {
531        Replace {
532            moved,
533            keep: Vec::new(),
534            both: Vec::new(),
535        }
536    }
537
538    /// Keeping some existing files is version 6, which an older build
539    /// refuses rather than deleting the files kept.
540    #[test]
541    fn choosing_per_file_is_version_6_and_only_that_is() {
542        let dir =
543            std::env::temp_dir().join(format!("hatchzip-journal-choose-{}", std::process::id()));
544        fs::create_dir_all(&dir).unwrap();
545
546        let chose = r#","replace":{"moved":false,"keep":["a.txt"],"both":["b/c.txt"]}"#;
547        let (journal, _) = Journal::load(&write_with(&dir, 6, chose)).unwrap();
548        let r = journal.replace.as_ref().unwrap();
549        assert_eq!(r.keep, [PathBuf::from("a.txt")]);
550        assert_eq!(r.both, [PathBuf::from("b/c.txt")]);
551        assert_eq!(journal.version, CHOOSE_VERSION);
552
553        assert!(Journal::load(&write_with(&dir, 5, chose)).is_err());
554        assert!(Journal::load(&write_with(&dir, 6, r#","replace":{"moved":false}"#)).is_err());
555
556        fs::remove_dir_all(&dir).unwrap();
557    }
558
559    /// Folders where names differ only in case come with their own version,
560    /// alongside anything else a run does, and stay inside the output folder.
561    #[test]
562    fn reads_case_folders_at_their_version_only() {
563        let dir =
564            std::env::temp_dir().join(format!("hatchzip-journal-case-{}", std::process::id()));
565        fs::create_dir_all(&dir).unwrap();
566
567        for fields in [
568            r#","case_folders":["","a/b"]"#,
569            r#","case_folders":["a"],"keep":true"#,
570            r#","case_folders":["a"],"replace":{"moved":false}"#,
571        ] {
572            let (journal, _) = Journal::load(&write_with(&dir, 7, fields)).unwrap();
573            assert_eq!(journal.version, CASE_VERSION, "{fields}");
574        }
575        assert!(Journal::load(&write_with(&dir, 7, "")).is_err());
576        assert!(Journal::load(&write_with(&dir, 3, r#","case_folders":["a"]"#)).is_err());
577        assert!(Journal::load(&write_with(&dir, 3, r#","case_beyond_ascii":true"#)).is_err());
578        assert!(Journal::load(&write_with(&dir, 7, r#","case_folders":["../a"]"#)).is_err());
579
580        fs::remove_dir_all(&dir).unwrap();
581    }
582
583    /// Saved folders make a journal version 8 whatever else the run does, and
584    /// no other journal may claim them.
585    #[test]
586    fn saved_folders_are_version_8_and_only_that_is() {
587        let dir =
588            std::env::temp_dir().join(format!("hatchzip-journal-folders-{}", std::process::id()));
589        fs::create_dir_all(&dir).unwrap();
590
591        let list = [crate::folders::Folder {
592            path: PathBuf::from("docs"),
593            mode: Some(0o750),
594            mtime: None,
595        }];
596        let saved = crate::folders::save(&dir.join("game.zip.hatchzip-folders"), &list)
597            .unwrap()
598            .unwrap();
599        let folders = &format!(
600            r#","folders":{{"count":{},"crc":{}}}"#,
601            saved.count, saved.crc
602        );
603        let (journal, _) = Journal::load(&write_with(&dir, 8, folders)).unwrap();
604        assert_eq!(journal.version, FOLDERS_VERSION);
605        let kept = format!(r#","keep":true,"replace":{{"moved":true,"keep":["a.txt"]}}{folders}"#);
606        let (journal, _) = Journal::load(&write_with(&dir, 8, &kept)).unwrap();
607        assert!(journal.keep && journal.replace.as_ref().is_some_and(Replace::chose));
608        assert_eq!(journal.version, FOLDERS_VERSION);
609
610        // A run can have both names that differ only in case and folders.
611        let both = format!(r#","case_folders":["a"],"case_beyond_ascii":true{folders}"#);
612        let (journal, _) = Journal::load(&write_with(&dir, 8, &both)).unwrap();
613        assert_eq!(journal.case_folders, [PathBuf::from("a")]);
614        assert!(journal.case_beyond_ascii && journal.folders.is_some());
615        assert_eq!(journal.version, FOLDERS_VERSION);
616
617        assert!(Journal::load(&write_with(&dir, 8, "")).is_err());
618        assert!(Journal::load(&write_with(&dir, 3, folders)).is_err());
619        assert!(Journal::load(&write_with(&dir, 7, folders)).is_err());
620        let both = format!(r#","case_folders":["a"]{folders}"#);
621        assert!(Journal::load(&write_with(&dir, 7, &both)).is_err());
622        let ascii = format!(r#","case_beyond_ascii":true{folders}"#);
623        assert!(Journal::load(&write_with(&dir, 8, &ascii)).is_err());
624        let outside = format!(r#","case_folders":["../a"]{folders}"#);
625        assert!(Journal::load(&write_with(&dir, 8, &outside)).is_err());
626        assert!(Journal::load(&write_with(&dir, 3, r#","folders_left":true"#)).is_err());
627
628        // A resume checks the list up front, not when it is read at the very
629        // end, and only a resume does.
630        fs::write(dir.join("game.zip.hatchzip-folders"), b"[]").unwrap();
631        let paths = write_with(&dir, 8, folders);
632        let (journal, _) = Journal::load(&paths).unwrap();
633        assert!(journal.check_folders(&paths).is_err());
634
635        fs::remove_dir_all(&dir).unwrap();
636    }
637
638    /// A run started by the previous release resumes; one started by a
639    /// release that knows more is refused before anything is touched.
640    #[test]
641    fn reads_version_2_and_refuses_newer_journals() {
642        let dir = std::env::temp_dir().join(format!("hatchzip-journal-{}", std::process::id()));
643        fs::create_dir_all(&dir).unwrap();
644
645        let (journal, _) = Journal::load(&write(&dir, 2)).unwrap();
646        assert_eq!(journal.resume, None);
647        assert_eq!(journal.version, VERSION);
648
649        let err = Journal::load(&write(&dir, FOLDERS_VERSION + 1))
650            .err()
651            .unwrap();
652        assert!(format!("{err:#}").contains("newer HatchZip"), "{err:#}");
653        let err = Journal::load(&write(&dir, 1)).err().unwrap();
654        assert!(format!("{err:#}").contains("older HatchZip"), "{err:#}");
655
656        fs::remove_dir_all(&dir).unwrap();
657    }
658}