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;
49/// One that extracts only selected entries writes version 9, whatever else
50/// it does. A build before that would resume it as a whole extraction: it
51/// would delete whatever is at the paths of the entries left out, which no
52/// check looked at before the run began, and extract them over it.
53const SELECT_VERSION: u32 = 9;
54const READABLE: [u32; 8] = [2, 3, 4, 5, 6, 7, 8, 9];
55/// What an extraction of a native split ZIP keeps at `<stem>.zip.hatchzip`
56/// while it runs. Builds before split ZIP support take `<stem>.zip` for a
57/// ZIP that is one file and look for its journal there, so they find this
58/// and refuse it as a newer journal, instead of extracting the last segment
59/// on its own and cutting away the index the rest of the set needs. Builds
60/// that know split ZIPs open the set from its `.z01` and never read it.
61const 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/// Where extraction of a large file can pick up again after a crash. Its
71/// output up to `written` is flushed to disk, and the archive bytes before
72/// the one holding `bit` may already be freed, so this is the only way back.
73#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
74pub struct Resume {
75    /// The unit, by the offset it starts at.
76    pub unit: u64,
77    /// Bytes of output in `<name>.hatchzip-part`, flushed. Anything the file
78    /// holds past this was written after the point and is thrown away.
79    pub written: u64,
80    /// Where decoding restarts, in bits from the start of the archive. Deflate
81    /// and bzip2 blocks can stop between two bytes.
82    pub bit: u64,
83    /// CRC-32 of the first `written` bytes of output. Unused for a
84    /// compressed tar, whose checksums are per gzip member or bzip2 stream, in `stream`.
85    pub crc: u32,
86    /// For a compressed tar, where one stream holds every entry: the
87    /// decoder's and the tar parser's state at `bit`. `written` is then how
88    /// much of the entry being extracted is in its part file, if the point
89    /// lies inside a file. Older builds don't know the format and refuse the
90    /// journal before reading this.
91    #[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    /// Every part of the archive with its original length.
100    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    /// The archive is truncated to this once the latest batch is committed.
106    /// Every unit starting at or after it is done.
107    pub committed_len: u64,
108    /// Links are made last, so nothing extracted can be written through one
109    /// and every hard link's target already exists.
110    pub links: Vec<Link>,
111    /// The large file being extracted while its archive bytes are freed, if
112    /// one is in progress. It always belongs to the highest uncommitted unit.
113    #[serde(default)]
114    pub resume: Option<Resume>,
115    /// Every unit was extracted and the final commit was journaled: only the
116    /// archive's removal and the links are left. A compressed stream lands
117    /// here with its archive punched up to its last resume point, so it no
118    /// longer parses from its start and must not be read again.
119    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
120    pub done: bool,
121    /// Set while `restore` turns the archive back into a normal one: the
122    /// bytes it overwrites below `committed_len`, so that an interrupted
123    /// restore can be undone by putting them back and cutting off whatever it
124    /// appended.
125    #[serde(default, skip_serializing_if = "Option::is_none")]
126    pub restoring: Option<Vec<(u64, Vec<u8>)>>,
127    /// The extraction keeps the archive: nothing is truncated, punched or
128    /// deleted, and `committed_len` only records progress. A resume keeps
129    /// it too, whatever it is asked.
130    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
131    pub keep: bool,
132    /// The extraction replaces files that were in the output folder before
133    /// it started; see [`crate::replace`].
134    #[serde(default, skip_serializing_if = "Option::is_none")]
135    pub replace: Option<Replace>,
136    /// The folders, inside the output, where entries' names differ only in
137    /// case. A resume and a restore ask about them again, not trusting the
138    /// answer from when the run began; see [`crate::session::check_recorded_case`].
139    #[serde(default, skip_serializing_if = "Vec::is_empty")]
140    pub case_folders: Vec<PathBuf>,
141    /// Some of those names go outside ASCII, so a system that normalizes
142    /// names may take them for one file, whatever its filesystem says about
143    /// case. Asked again for the same reason.
144    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
145    pub case_beyond_ascii: bool,
146    /// The archive's folder entries are saved in their own file, set once
147    /// every file and link is made; see [`crate::folders`].
148    #[serde(default, skip_serializing_if = "Option::is_none")]
149    pub folders: Option<crate::folders::Saved>,
150    /// Every link is made and every put-back file settled: only the folders
151    /// and the cleanup are left, and a resume does just that. Making a link
152    /// again would need write permission on its folder, which the folder's
153    /// own mode may have taken away by then.
154    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
155    pub folders_left: bool,
156    /// Only these entries, and everything inside the folders among them,
157    /// are extracted, always with the archive kept. A resume continues the
158    /// same selection, whatever it is asked.
159    #[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    /// Every file at the path of an entry left to do is in the replaced
166    /// files folder. Until then nothing is extracted, so whatever sits at
167    /// those paths is still the person's.
168    pub moved: bool,
169    /// Existing files, relative to the output, that go back over what was
170    /// extracted at their paths once the extraction completes.
171    #[serde(default, skip_serializing_if = "Vec::is_empty")]
172    pub keep: Vec<PathBuf>,
173    /// Existing files that go back to their paths once the extraction
174    /// completes, with the extracted copy renamed beside them.
175    #[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
185/// Whether `path` holds a stub journal; see [`STUB_VERSION`].
186fn 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    /// The first volume of the archive the side files belong to.
199    pub archive: PathBuf,
200    pub journal: PathBuf,
201    pub tail: PathBuf,
202    pub folders: PathBuf,
203    /// For a native split ZIP, where its stub journal goes, next to its
204    /// `.zip`; see [`STUB_VERSION`].
205    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    /// Writes the stub journal of a native split ZIP's extraction. Only over
230    /// a stub an earlier run left: see [`Self::check_stub`].
231    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    /// Refuses a native split ZIP whose stub name holds anything but a stub:
254    /// the journal of an extraction of its `.zip` opened on its own, before
255    /// the other parts were next to it. A stub written over it would lose
256    /// the only record of what that run extracted and freed.
257    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    /// Removes the stub journal, if that is what is at its name: a journal
282    /// of a `.zip` of the same name extracted on its own stays.
283    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    /// Whether any progress file is at its name: the journal, its tail or
303    /// folder list, or a split ZIP's stub. A link counts, even a dangling
304    /// one.
305    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        // Last: until the journal is gone, an older build must not take the
323        // `.zip` for a whole archive.
324        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    /// Existing files are moved aside before the first entry is extracted,
335    /// and what to do with each once it completes.
336    pub replace: Option<Replace>,
337    pub case_folders: Vec<PathBuf>,
338    pub case_beyond_ascii: bool,
339    /// Folder entries with a mode or a time, saved before anything is
340    /// extracted.
341    pub folders: Vec<crate::folders::Folder>,
342    /// The selected entries, if not every one is extracted.
343    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        // Before the journal, so no older build ever finds the journal of a
373        // run on a split ZIP without the stub next to its `.zip`.
374        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    /// For a resume, before it changes anything: the list is read at the very
415    /// end, and a resume past a missing or damaged one would free the rest of
416    /// the archive and only then fail. Nothing else needs the list, so a lost
417    /// one stops neither a look at the archive nor a restore.
418    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        // The version is checked before the rest is parsed, so a newer layout
431        // gets the version message rather than a confusing parse error.
432        #[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        // Versions 7, 8 and 9 are written whatever else the run does, so
464        // they say nothing about keeping or replacing. Only 8 and 9 may have
465        // folders, only 9 a selection, which always keeps the archive, and
466        // only those three may have case folders, which 7 is there for.
467        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            // The top of the output, where names can meet, is an empty path.
493            || 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        // Each is joined to the output folder and renamed, so each must stay
501        // inside it.
502        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    /// The progress files this journal has next to the archive, for a
539    /// message that says which ones to delete.
540    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    /// The journal is a file next to the archive, so anyone who could put
553    /// the archive there could have written it too. Whatever it names may
554    /// only be what an extraction of this archive touches: the archive's own
555    /// volumes, and links inside the output folder. The output folder itself
556    /// is checked by [`crate::session::check_output`].
557    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        // A split ZIP's parts are read only through its own index; read as
572        // one file, its offsets would point at the wrong bytes.
573        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        // Restore only ever saves bytes it overwrites inside the archive.
586        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    /// The stub of a split ZIP's extraction never goes over the journal of
642    /// its `.zip` extracted on its own; a stub an earlier run left is
643    /// written over, and only a stub is removed.
644    #[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    /// Only an extraction that keeps the archive writes version 4, so older
673    /// builds, which would truncate it, refuse it; in-place runs stay at 3.
674    #[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        // A mismatch means someone edited the file.
695        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    /// Replacing files is version 5 whether the archive is kept or not, and
702    /// no other journal may say it replaces anything.
703    #[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    /// Keeping some existing files is version 6, which an older build
738    /// refuses rather than deleting the files kept.
739    #[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    /// Folders where names differ only in case come with their own version,
759    /// alongside anything else a run does, and stay inside the output folder.
760    #[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    /// Saved folders make a journal version 8 whatever else the run does, and
783    /// no other journal may claim them.
784    #[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        // A run can have both names that differ only in case and folders.
810        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        // A resume checks the list up front, not when it is read at the very
828        // end, and only a resume does.
829        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    /// A selection makes a journal version 9 whatever else the run does,
838    /// always with the archive kept, and no other journal may hold one.
839    #[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        // Alongside anything else a run records.
855        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        // Older builds would resume it whole; a selection that removes the
860        // archive, or that leaves the output folder, was never written.
861        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    /// A run started by the previous release resumes; one started by a
874    /// release that knows more is refused before anything is touched.
875    #[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}