hatchzip-core 0.1.11

The engine behind HatchZip: extract ZIP, 7z and tar archives in place, freeing the archive as it goes.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
//! Progress record that makes an interrupted extraction resumable.
//!
//! ZIP and 7z keep their index at the end of the archive, which is the first
//! thing truncation destroys. So before the first byte is reclaimed the tail
//! of the archive is copied to a side file, and from then on the archive is
//! parsed through a reader that serves the saved tail at its old offsets.

use std::fs;
use std::io::{self, Read, Seek, SeekFrom};
use std::path::{Component, Path, PathBuf};
use std::sync::Arc;

use anyhow::{Context, Result, anyhow, bail};
use serde::{Deserialize, Serialize};

use crate::archive::storage::{self, Storage, Tail};
pub use crate::archive::targz::{StreamPoint, TarAt};
use crate::fsutil;

/// Version 3 added `resume`. A version 2 journal can't hold one, so it reads
/// as is. Older HatchZip builds refuse version 3, which matters: they would
/// delete a half-extracted file whose archive bytes are already freed.
const VERSION: u32 = 3;
/// An extraction that keeps the archive writes version 4, unless a later
/// version below takes over.
/// Builds before `keep` existed refuse it, which matters just as much: they
/// would resume it in place and truncate the archive the user kept. Every
/// other journal stays at version 3, so an older build can still finish it.
const KEEP_VERSION: u32 = 4;
/// An extraction that replaces existing files writes version 5, kept
/// archive or not, unless a later version below takes over. Builds before
/// `replace` existed refuse it: they would delete the person's files at the
/// paths of entries left to do, and a restore would not put the replaced
/// ones back.
const REPLACE_VERSION: u32 = 5;
/// One that keeps some existing files, or both copies of them, writes
/// version 6. A build before that would finish it by deleting the files the
/// person chose to keep.
const CHOOSE_VERSION: u32 = 6;
/// One with names that differ only in case writes version 7. A build before
/// that never asks where it may resume such a run, so on a filesystem that
/// ignores case it would delete an extracted file as its own.
const CASE_VERSION: u32 = 7;
/// One whose archive has folder entries with permissions or times writes
/// version 8, whatever else it does, names that differ only in case included,
/// and keeps them in a side file. A build before that would finish without
/// setting them.
const FOLDERS_VERSION: u32 = 8;
/// One that extracts only selected entries writes version 9, whatever else
/// it does. A build before that would resume it as a whole extraction: it
/// would delete whatever is at the paths of the entries left out, which no
/// check looked at before the run began, and extract them over it.
const SELECT_VERSION: u32 = 9;
const READABLE: [u32; 8] = [2, 3, 4, 5, 6, 7, 8, 9];
/// What an extraction of a native split ZIP keeps at `<stem>.zip.hatchzip`
/// while it runs. Builds before split ZIP support take `<stem>.zip` for a
/// ZIP that is one file and look for its journal there, so they find this
/// and refuse it as a newer journal, instead of extracting the last segment
/// on its own and cutting away the index the rest of the set needs. Builds
/// that know split ZIPs open the set from its `.z01` and never read it.
const STUB_VERSION: u32 = 1000;

#[derive(Serialize, Deserialize, Clone)]
pub struct Link {
    pub path: PathBuf,
    pub target: PathBuf,
    pub hard: bool,
}

/// Where extraction of a large file can pick up again after a crash. Its
/// output up to `written` is flushed to disk, and the archive bytes before
/// the one holding `bit` may already be freed, so this is the only way back.
#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Resume {
    /// The unit, by the offset it starts at.
    pub unit: u64,
    /// Bytes of output in `<name>.hatchzip-part`, flushed. Anything the file
    /// holds past this was written after the point and is thrown away.
    pub written: u64,
    /// Where decoding restarts, in bits from the start of the archive. Deflate
    /// and bzip2 blocks can stop between two bytes.
    pub bit: u64,
    /// CRC-32 of the first `written` bytes of output. Unused for a
    /// compressed tar, whose checksums are per gzip member or bzip2 stream, in `stream`.
    pub crc: u32,
    /// For a compressed tar, where one stream holds every entry: the
    /// decoder's and the tar parser's state at `bit`. `written` is then how
    /// much of the entry being extracted is in its part file, if the point
    /// lies inside a file. Older builds don't know the format and refuse the
    /// journal before reading this.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub stream: Option<Box<StreamPoint>>,
}

#[derive(Serialize, Deserialize)]
pub struct Journal {
    pub version: u32,
    pub format: String,
    /// Every part of the archive with its original length.
    pub parts: Vec<(PathBuf, u64)>,
    pub tail_start: u64,
    pub tail_crc: u32,
    pub output: PathBuf,
    pub total_size: u64,
    /// The archive is truncated to this once the latest batch is committed.
    /// Every unit starting at or after it is done.
    pub committed_len: u64,
    /// Links are made last, so nothing extracted can be written through one
    /// and every hard link's target already exists.
    pub links: Vec<Link>,
    /// The large file being extracted while its archive bytes are freed, if
    /// one is in progress. It always belongs to the highest uncommitted unit.
    #[serde(default)]
    pub resume: Option<Resume>,
    /// Every unit was extracted and the final commit was journaled: only the
    /// archive's removal and the links are left. A compressed stream lands
    /// here with its archive punched up to its last resume point, so it no
    /// longer parses from its start and must not be read again.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub done: bool,
    /// Set while `restore` turns the archive back into a normal one: the
    /// bytes it overwrites below `committed_len`, so that an interrupted
    /// restore can be undone by putting them back and cutting off whatever it
    /// appended.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub restoring: Option<Vec<(u64, Vec<u8>)>>,
    /// The extraction keeps the archive: nothing is truncated, punched or
    /// deleted, and `committed_len` only records progress. A resume keeps
    /// it too, whatever it is asked.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub keep: bool,
    /// The extraction replaces files that were in the output folder before
    /// it started; see [`crate::replace`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub replace: Option<Replace>,
    /// The folders, inside the output, where entries' names differ only in
    /// case. A resume and a restore ask about them again, not trusting the
    /// answer from when the run began; see [`crate::session::check_recorded_case`].
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub case_folders: Vec<PathBuf>,
    /// Some of those names go outside ASCII, so a system that normalizes
    /// names may take them for one file, whatever its filesystem says about
    /// case. Asked again for the same reason.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub case_beyond_ascii: bool,
    /// The archive's folder entries are saved in their own file, set once
    /// every file and link is made; see [`crate::folders`].
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub folders: Option<crate::folders::Saved>,
    /// Every link is made and every put-back file settled: only the folders
    /// and the cleanup are left, and a resume does just that. Making a link
    /// again would need write permission on its folder, which the folder's
    /// own mode may have taken away by then.
    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
    pub folders_left: bool,
    /// Only these entries, and everything inside the folders among them,
    /// are extracted, always with the archive kept. A resume continues the
    /// same selection, whatever it is asked.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub only: Option<Vec<PathBuf>>,
}

#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]
pub struct Replace {
    /// Every file at the path of an entry left to do is in the replaced
    /// files folder. Until then nothing is extracted, so whatever sits at
    /// those paths is still the person's.
    pub moved: bool,
    /// Existing files, relative to the output, that go back over what was
    /// extracted at their paths once the extraction completes.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub keep: Vec<PathBuf>,
    /// Existing files that go back to their paths once the extraction
    /// completes, with the extracted copy renamed beside them.
    #[serde(default, skip_serializing_if = "Vec::is_empty")]
    pub both: Vec<PathBuf>,
}

impl Replace {
    fn chose(&self) -> bool {
        !self.keep.is_empty() || !self.both.is_empty()
    }
}

/// Whether `path` holds a stub journal; see [`STUB_VERSION`].
fn is_stub(path: &Path) -> bool {
    #[derive(Deserialize)]
    struct Versioned {
        version: u32,
    }
    fs::read(path)
        .ok()
        .and_then(|b| serde_json::from_slice::<Versioned>(&b).ok())
        .is_some_and(|v| v.version == STUB_VERSION)
}

pub struct Paths {
    /// The first volume of the archive the side files belong to.
    pub archive: PathBuf,
    pub journal: PathBuf,
    pub tail: PathBuf,
    pub folders: PathBuf,
    /// For a native split ZIP, where its stub journal goes, next to its
    /// `.zip`; see [`STUB_VERSION`].
    pub stub: Option<PathBuf>,
}

impl Paths {
    pub fn for_archive(archive: &Path) -> Self {
        let with = |suffix: &str| {
            let mut s = archive.as_os_str().to_owned();
            s.push(suffix);
            PathBuf::from(s)
        };
        let stub = storage::split_zip_last(archive).map(|last| {
            let mut s = last.into_os_string();
            s.push(".hatchzip");
            PathBuf::from(s)
        });
        Self {
            archive: archive.to_path_buf(),
            journal: with(".hatchzip"),
            tail: with(".hatchzip-tail"),
            folders: with(".hatchzip-folders"),
            stub,
        }
    }

    /// Writes the stub journal of a native split ZIP's extraction. Only over
    /// a stub an earlier run left: see [`Self::check_stub`].
    fn write_stub(&self) -> Result<()> {
        let Some(stub) = &self.stub else {
            return Ok(());
        };
        self.check_stub()?;
        let json = serde_json::to_vec(&serde_json::json!({
            "version": STUB_VERSION,
            "split_zip": self.archive,
        }))?;
        if is_stub(stub) {
            return fsutil::write_atomic(stub, &json);
        }
        {
            use std::io::Write;
            let mut f = crate::platform::create_new_no_follow(stub)
                .with_context(|| format!("creating {}", stub.display()))?;
            f.write_all(&json)?;
            f.sync_all()?;
        }
        fsutil::sync_dir(stub.parent().unwrap_or(Path::new(".")))
    }

    /// Refuses a native split ZIP whose stub name holds anything but a stub:
    /// the journal of an extraction of its `.zip` opened on its own, before
    /// the other parts were next to it. A stub written over it would lose
    /// the only record of what that run extracted and freed.
    pub fn check_stub(&self) -> Result<()> {
        let Some(stub) = &self.stub else {
            return Ok(());
        };
        match fs::symlink_metadata(stub) {
            Err(e) if e.kind() == io::ErrorKind::NotFound => Ok(()),
            Err(e) => Err(e).with_context(|| format!("reading {}", stub.display())),
            Ok(_) if is_stub(stub) => Ok(()),
            Ok(_) => {
                let last = stub.with_extension("");
                bail!(
                    "{} already has an extraction in progress that opened it on its own, and {} \
                     is its journal. To resume that one, move the other parts of the split ZIP \
                     out of the folder and open {}; or delete {} if no extraction of it is in \
                     progress. Nothing was modified",
                    last.display(),
                    stub.display(),
                    last.display(),
                    stub.display()
                )
            }
        }
    }

    /// Removes the stub journal, if that is what is at its name: a journal
    /// of a `.zip` of the same name extracted on its own stays.
    pub fn remove_stub(&self) -> Result<()> {
        let Some(stub) = &self.stub else {
            return Ok(());
        };
        if is_stub(stub) {
            match fs::remove_file(stub) {
                Err(e) if e.kind() != io::ErrorKind::NotFound => {
                    return Err(e).with_context(|| format!("removing {}", stub.display()));
                }
                _ => {}
            }
        }
        Ok(())
    }

    pub fn exists(&self) -> bool {
        self.journal.exists()
    }

    /// Whether any progress file is at its name: the journal, its tail or
    /// folder list, or a split ZIP's stub. A link counts, even a dangling
    /// one.
    pub fn any_exist(&self) -> bool {
        [&self.journal, &self.tail, &self.folders]
            .into_iter()
            .chain(&self.stub)
            .any(|p| fs::symlink_metadata(p).is_ok())
    }

    pub fn remove(&self) -> Result<()> {
        crate::chosen::forget(&self.archive);
        for p in [&self.folders, &self.tail, &self.journal] {
            match fs::remove_file(p) {
                Err(e) if e.kind() != io::ErrorKind::NotFound => {
                    return Err(e).with_context(|| format!("removing {}", p.display()));
                }
                _ => {}
            }
        }
        // Last: until the journal is gone, an older build must not take the
        // `.zip` for a whole archive.
        self.remove_stub()
    }
}

pub struct Plan {
    pub format: &'static str,
    pub tail_start: u64,
    pub output: PathBuf,
    pub total_size: u64,
    pub keep: bool,
    /// Existing files are moved aside before the first entry is extracted,
    /// and what to do with each once it completes.
    pub replace: Option<Replace>,
    pub case_folders: Vec<PathBuf>,
    pub case_beyond_ascii: bool,
    /// Folder entries with a mode or a time, saved before anything is
    /// extracted.
    pub folders: Vec<crate::folders::Folder>,
    /// The selected entries, if not every one is extracted.
    pub only: Option<Vec<PathBuf>>,
}

fn version_for(
    keep: bool,
    replace: Option<&Replace>,
    case_folders: &[PathBuf],
    folders: bool,
    only: bool,
) -> u32 {
    if only {
        SELECT_VERSION
    } else if folders {
        FOLDERS_VERSION
    } else if !case_folders.is_empty() {
        CASE_VERSION
    } else if replace.is_some_and(Replace::chose) {
        CHOOSE_VERSION
    } else if replace.is_some() {
        REPLACE_VERSION
    } else if keep {
        KEEP_VERSION
    } else {
        VERSION
    }
}

impl Journal {
    pub fn create(paths: &Paths, storage: &Storage, plan: Plan) -> Result<Self> {
        // Before the journal, so no older build ever finds the journal of a
        // run on a split ZIP without the stub next to its `.zip`.
        if plan.format == crate::archive::SPLIT_ZIP {
            paths.write_stub()?;
        }
        let mut tail = Vec::new();
        let mut r = storage.reader(None);
        r.seek(SeekFrom::Start(plan.tail_start))?;
        r.read_to_end(&mut tail)?;
        fsutil::write_atomic(&paths.tail, &tail)?;
        let folders = crate::folders::save(&paths.folders, &plan.folders)?;
        let journal = Self {
            version: version_for(
                plan.keep,
                plan.replace.as_ref(),
                &plan.case_folders,
                folders.is_some(),
                plan.only.is_some(),
            ),
            format: plan.format.to_string(),
            parts: storage.record(),
            tail_start: plan.tail_start,
            tail_crc: crc32fast::hash(&tail),
            output: plan.output,
            total_size: plan.total_size,
            committed_len: storage.original_len(),
            links: Vec::new(),
            resume: None,
            done: false,
            restoring: None,
            keep: plan.keep,
            replace: plan.replace,
            case_folders: plan.case_folders,
            case_beyond_ascii: plan.case_beyond_ascii,
            folders,
            folders_left: false,
            only: plan.only,
        };
        journal.save(paths)?;
        Ok(journal)
    }

    /// For a resume, before it changes anything: the list is read at the very
    /// end, and a resume past a missing or damaged one would free the rest of
    /// the archive and only then fail. Nothing else needs the list, so a lost
    /// one stops neither a look at the archive nor a restore.
    pub fn check_folders(&self, paths: &Paths) -> Result<()> {
        if let Some(saved) = self.folders {
            crate::folders::load(&paths.folders, saved).map_err(|e| {
                anyhow!("{e:#}. Put it back, or run `hatchzip restore` to give the archive back.")
            })?;
        }
        Ok(())
    }

    pub fn load(paths: &Paths) -> Result<(Self, Arc<Tail>)> {
        let bytes = fs::read(&paths.journal)
            .with_context(|| format!("reading {}", paths.journal.display()))?;
        // The version is checked before the rest is parsed, so a newer layout
        // gets the version message rather than a confusing parse error.
        #[derive(Deserialize)]
        struct Versioned {
            version: u32,
        }
        let version = serde_json::from_slice::<Versioned>(&bytes)
            .with_context(|| format!("{} is damaged", paths.journal.display()))?
            .version;
        if version == STUB_VERSION {
            bail!(
                "{} marks {} as the last part of a split ZIP being extracted from its .z01 part. \
                 Open the .z01 part to continue that extraction, or delete {} if no extraction \
                 of it is in progress. Nothing was modified",
                paths.journal.display(),
                paths.archive.display(),
                paths.journal.display()
            );
        }
        if !READABLE.contains(&version) {
            let which = if version > VERSION {
                "a newer"
            } else {
                "an older"
            };
            bail!(
                "{} was written by {which} HatchZip version (journal format {version}); \
                 complete the extraction with that version",
                paths.journal.display()
            );
        }
        let mut journal: Self = serde_json::from_slice(&bytes)
            .with_context(|| format!("{} is damaged", paths.journal.display()))?;
        // Versions 7, 8 and 9 are written whatever else the run does, so
        // they say nothing about keeping or replacing. Only 8 and 9 may have
        // folders, only 9 a selection, which always keeps the archive, and
        // only those three may have case folders, which 7 is there for.
        let case = version == CASE_VERSION;
        let folders = version == FOLDERS_VERSION;
        let selects = version == SELECT_VERSION;
        let later = folders || selects;
        let replaces = version == REPLACE_VERSION || version == CHOOSE_VERSION;
        if (!selects && journal.folders.is_some() != folders)
            || (journal.folders_left && journal.folders.is_none())
            || journal.only.is_some() != selects
            || (selects && !journal.keep)
            || journal.only.as_ref().is_some_and(|o| {
                o.is_empty()
                    || !o.iter().all(|p| {
                        p.components().next().is_some()
                            && p.components().all(|c| matches!(c, Component::Normal(_)))
                    })
            })
            || (case && journal.case_folders.is_empty())
            || (!case && !later && !journal.case_folders.is_empty())
            || (journal.case_beyond_ascii && journal.case_folders.is_empty())
            || (!case
                && !later
                && (journal.replace.is_some() != replaces
                    || journal.replace.as_ref().is_some_and(Replace::chose)
                        != (version == CHOOSE_VERSION)
                    || (!replaces && journal.keep != (version == KEEP_VERSION))))
            // The top of the output, where names can meet, is an empty path.
            || journal
                .case_folders
                .iter()
                .any(|p| !p.components().all(|c| matches!(c, Component::Normal(_))))
        {
            bail!("{} is damaged", paths.journal.display());
        }
        // Each is joined to the output folder and renamed, so each must stay
        // inside it.
        let inside = |p: &PathBuf| {
            p.components().next().is_some()
                && p.components().all(|c| matches!(c, Component::Normal(_)))
        };
        if let Some(r) = &journal.replace
            && !r.keep.iter().chain(&r.both).all(inside)
        {
            bail!("{} is damaged", paths.journal.display());
        }
        journal.version = version_for(
            journal.keep,
            journal.replace.as_ref(),
            &journal.case_folders,
            journal.folders.is_some(),
            journal.only.is_some(),
        );
        journal.check_bound(paths)?;
        let tail =
            fs::read(&paths.tail).with_context(|| format!("reading {}", paths.tail.display()))?;
        let len: u64 = journal.parts.iter().map(|(_, l)| l).sum();
        if crc32fast::hash(&tail) != journal.tail_crc
            || journal.tail_start + tail.len() as u64 != len
        {
            bail!("{} does not match its journal", paths.tail.display());
        }
        let tail = Arc::new(Tail {
            start: journal.tail_start,
            bytes: tail,
        });
        Ok((journal, tail))
    }

    pub fn save(&self, paths: &Paths) -> Result<()> {
        fsutil::write_atomic(&paths.journal, &serde_json::to_vec(self)?)
    }

    /// The progress files this journal has next to the archive, for a
    /// message that says which ones to delete.
    pub(crate) fn side_files(&self, paths: &Paths) -> String {
        match self.folders {
            Some(_) => format!(
                "{}, {} and {}",
                paths.journal.display(),
                paths.tail.display(),
                paths.folders.display()
            ),
            None => format!("{} and {}", paths.journal.display(), paths.tail.display()),
        }
    }

    /// The journal is a file next to the archive, so anyone who could put
    /// the archive there could have written it too. Whatever it names may
    /// only be what an extraction of this archive touches: the archive's own
    /// volumes, and links inside the output folder. The output folder itself
    /// is checked by [`crate::session::check_output`].
    fn check_bound(&self, paths: &Paths) -> Result<()> {
        let foreign = || {
            anyhow!(
                "{} does not belong to {}, so it was not used and nothing was modified. If the \
                 archive was moved during an extraction, move it back to resume; otherwise \
                 delete {}",
                paths.journal.display(),
                paths.archive.display(),
                self.side_files(paths)
            )
        };
        if self.parts.is_empty() {
            return Err(foreign());
        }
        // A split ZIP's parts are read only through its own index; read as
        // one file, its offsets would point at the wrong bytes.
        let split = self.format == crate::archive::SPLIT_ZIP;
        if split != (storage::is_split_zip(&paths.archive) && self.parts.len() > 1) {
            return Err(foreign());
        }
        let count = self.parts.len();
        for (i, (part, _)) in self.parts.iter().enumerate() {
            if !storage::volume_path_in(&paths.archive, i, count)
                .is_some_and(|v| fsutil::same_path(&v, part))
            {
                return Err(foreign());
            }
        }
        // Restore only ever saves bytes it overwrites inside the archive.
        let len: u64 = self.parts.iter().map(|(_, l)| l).sum();
        let within = |(at, bytes): &(u64, Vec<u8>)| {
            at.checked_add(bytes.len() as u64)
                .is_some_and(|end| end <= len)
        };
        if self
            .restoring
            .as_ref()
            .is_some_and(|r| !r.iter().all(within))
        {
            bail!(
                "{} is damaged: it records bytes outside the archive. Nothing was modified",
                paths.journal.display()
            );
        }
        let inside = |p: &Path| {
            p.components().next().is_some()
                && p.components().all(|c| matches!(c, Component::Normal(_)))
        };
        for link in &self.links {
            if !inside(&link.path) || (link.hard && !inside(&link.target)) {
                bail!(
                    "{} is damaged: it records a link outside the output folder. Nothing was \
                     modified",
                    paths.journal.display()
                );
            }
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn write(dir: &Path, version: u32) -> Paths {
        write_with(dir, version, "")
    }

    fn write_with(dir: &Path, version: u32, extra: &str) -> Paths {
        let paths = Paths::for_archive(&dir.join("game.zip"));
        let tail = b"saved tail";
        fs::write(&paths.tail, tail).unwrap();
        let json = format!(
            r#"{{"version":{version},"format":"zip","parts":[[{},{}]],"tail_start":0,
                "tail_crc":{},"output":"out","total_size":0,"committed_len":0,"links":[]{extra}}}"#,
            serde_json::to_string(&dir.join("game.zip")).unwrap(),
            tail.len(),
            crc32fast::hash(tail)
        );
        fs::write(&paths.journal, json).unwrap();
        paths
    }

    /// The stub of a split ZIP's extraction never goes over the journal of
    /// its `.zip` extracted on its own; a stub an earlier run left is
    /// written over, and only a stub is removed.
    #[test]
    fn a_stub_never_replaces_a_journal() {
        let dir =
            std::env::temp_dir().join(format!("hatchzip-journal-stub-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        let lone = write(&dir, 3);
        let before = fs::read(&lone.journal).unwrap();
        let split = Paths::for_archive(&dir.join("game.z01"));
        assert_eq!(split.stub.as_deref(), Some(lone.journal.as_path()));

        let err = split.write_stub().unwrap_err().to_string();
        assert!(
            err.contains("already has an extraction in progress"),
            "{err}"
        );
        assert!(split.check_stub().is_err());
        split.remove_stub().unwrap();
        assert_eq!(fs::read(&lone.journal).unwrap(), before);

        fs::remove_file(&lone.journal).unwrap();
        split.write_stub().unwrap();
        split.check_stub().unwrap();
        split.write_stub().unwrap();
        split.remove_stub().unwrap();
        assert!(!lone.journal.exists());
        fs::remove_dir_all(&dir).unwrap();
    }

    /// Only an extraction that keeps the archive writes version 4, so older
    /// builds, which would truncate it, refuse it; in-place runs stay at 3.
    #[test]
    fn keeping_the_archive_is_version_4_and_only_that_is() {
        let dir =
            std::env::temp_dir().join(format!("hatchzip-journal-keep-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();

        let (journal, _) = Journal::load(&write_with(&dir, 4, r#","keep":true"#)).unwrap();
        assert!(journal.keep);
        assert_eq!(journal.version, KEEP_VERSION);
        let saved = serde_json::to_string(&journal).unwrap();
        assert!(saved.contains(r#""version":4"#) && saved.contains(r#""keep":true"#));

        let (journal, _) = Journal::load(&write(&dir, 3)).unwrap();
        assert!(!journal.keep);
        assert!(
            !serde_json::to_string(&journal)
                .unwrap()
                .contains(r#""keep":"#)
        );

        // A mismatch means someone edited the file.
        assert!(Journal::load(&write(&dir, 4)).is_err());
        assert!(Journal::load(&write_with(&dir, 3, r#","keep":true"#)).is_err());

        fs::remove_dir_all(&dir).unwrap();
    }

    /// Replacing files is version 5 whether the archive is kept or not, and
    /// no other journal may say it replaces anything.
    #[test]
    fn replacing_files_is_version_5_and_only_that_is() {
        let dir =
            std::env::temp_dir().join(format!("hatchzip-journal-replace-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();

        let moving = r#","replace":{"moved":false}"#;
        let (journal, _) = Journal::load(&write_with(&dir, 5, moving)).unwrap();
        assert_eq!(journal.replace, Some(replace(false)));
        assert!(!journal.keep);
        let saved = serde_json::to_string(&journal).unwrap();
        assert!(saved.contains(r#""version":5"#), "{saved}");
        assert!(!saved.contains("both"), "{saved}");

        let kept = r#","keep":true,"replace":{"moved":true}"#;
        let (journal, _) = Journal::load(&write_with(&dir, 5, kept)).unwrap();
        assert!(journal.keep && journal.replace == Some(replace(true)));
        assert_eq!(journal.version, REPLACE_VERSION);

        assert!(Journal::load(&write(&dir, 5)).is_err());
        assert!(Journal::load(&write_with(&dir, 3, moving)).is_err());
        assert!(Journal::load(&write_with(&dir, 4, &format!(r#","keep":true{moving}"#))).is_err());

        fs::remove_dir_all(&dir).unwrap();
    }

    fn replace(moved: bool) -> Replace {
        Replace {
            moved,
            keep: Vec::new(),
            both: Vec::new(),
        }
    }

    /// Keeping some existing files is version 6, which an older build
    /// refuses rather than deleting the files kept.
    #[test]
    fn choosing_per_file_is_version_6_and_only_that_is() {
        let dir =
            std::env::temp_dir().join(format!("hatchzip-journal-choose-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();

        let chose = r#","replace":{"moved":false,"keep":["a.txt"],"both":["b/c.txt"]}"#;
        let (journal, _) = Journal::load(&write_with(&dir, 6, chose)).unwrap();
        let r = journal.replace.as_ref().unwrap();
        assert_eq!(r.keep, [PathBuf::from("a.txt")]);
        assert_eq!(r.both, [PathBuf::from("b/c.txt")]);
        assert_eq!(journal.version, CHOOSE_VERSION);

        assert!(Journal::load(&write_with(&dir, 5, chose)).is_err());
        assert!(Journal::load(&write_with(&dir, 6, r#","replace":{"moved":false}"#)).is_err());

        fs::remove_dir_all(&dir).unwrap();
    }

    /// Folders where names differ only in case come with their own version,
    /// alongside anything else a run does, and stay inside the output folder.
    #[test]
    fn reads_case_folders_at_their_version_only() {
        let dir =
            std::env::temp_dir().join(format!("hatchzip-journal-case-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();

        for fields in [
            r#","case_folders":["","a/b"]"#,
            r#","case_folders":["a"],"keep":true"#,
            r#","case_folders":["a"],"replace":{"moved":false}"#,
        ] {
            let (journal, _) = Journal::load(&write_with(&dir, 7, fields)).unwrap();
            assert_eq!(journal.version, CASE_VERSION, "{fields}");
        }
        assert!(Journal::load(&write_with(&dir, 7, "")).is_err());
        assert!(Journal::load(&write_with(&dir, 3, r#","case_folders":["a"]"#)).is_err());
        assert!(Journal::load(&write_with(&dir, 3, r#","case_beyond_ascii":true"#)).is_err());
        assert!(Journal::load(&write_with(&dir, 7, r#","case_folders":["../a"]"#)).is_err());

        fs::remove_dir_all(&dir).unwrap();
    }

    /// Saved folders make a journal version 8 whatever else the run does, and
    /// no other journal may claim them.
    #[test]
    fn saved_folders_are_version_8_and_only_that_is() {
        let dir =
            std::env::temp_dir().join(format!("hatchzip-journal-folders-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();

        let list = [crate::folders::Folder {
            path: PathBuf::from("docs"),
            mode: Some(0o750),
            mtime: None,
        }];
        let saved = crate::folders::save(&dir.join("game.zip.hatchzip-folders"), &list)
            .unwrap()
            .unwrap();
        let folders = &format!(
            r#","folders":{{"count":{},"crc":{}}}"#,
            saved.count, saved.crc
        );
        let (journal, _) = Journal::load(&write_with(&dir, 8, folders)).unwrap();
        assert_eq!(journal.version, FOLDERS_VERSION);
        let kept = format!(r#","keep":true,"replace":{{"moved":true,"keep":["a.txt"]}}{folders}"#);
        let (journal, _) = Journal::load(&write_with(&dir, 8, &kept)).unwrap();
        assert!(journal.keep && journal.replace.as_ref().is_some_and(Replace::chose));
        assert_eq!(journal.version, FOLDERS_VERSION);

        // A run can have both names that differ only in case and folders.
        let both = format!(r#","case_folders":["a"],"case_beyond_ascii":true{folders}"#);
        let (journal, _) = Journal::load(&write_with(&dir, 8, &both)).unwrap();
        assert_eq!(journal.case_folders, [PathBuf::from("a")]);
        assert!(journal.case_beyond_ascii && journal.folders.is_some());
        assert_eq!(journal.version, FOLDERS_VERSION);

        assert!(Journal::load(&write_with(&dir, 8, "")).is_err());
        assert!(Journal::load(&write_with(&dir, 3, folders)).is_err());
        assert!(Journal::load(&write_with(&dir, 7, folders)).is_err());
        let both = format!(r#","case_folders":["a"]{folders}"#);
        assert!(Journal::load(&write_with(&dir, 7, &both)).is_err());
        let ascii = format!(r#","case_beyond_ascii":true{folders}"#);
        assert!(Journal::load(&write_with(&dir, 8, &ascii)).is_err());
        let outside = format!(r#","case_folders":["../a"]{folders}"#);
        assert!(Journal::load(&write_with(&dir, 8, &outside)).is_err());
        assert!(Journal::load(&write_with(&dir, 3, r#","folders_left":true"#)).is_err());

        // A resume checks the list up front, not when it is read at the very
        // end, and only a resume does.
        fs::write(dir.join("game.zip.hatchzip-folders"), b"[]").unwrap();
        let paths = write_with(&dir, 8, folders);
        let (journal, _) = Journal::load(&paths).unwrap();
        assert!(journal.check_folders(&paths).is_err());

        fs::remove_dir_all(&dir).unwrap();
    }

    /// A selection makes a journal version 9 whatever else the run does,
    /// always with the archive kept, and no other journal may hold one.
    #[test]
    fn a_selection_is_version_9_and_only_that_is() {
        let dir =
            std::env::temp_dir().join(format!("hatchzip-journal-only-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();

        let only = r#","keep":true,"only":["docs","bin/tool"]"#;
        let (journal, _) = Journal::load(&write_with(&dir, 9, only)).unwrap();
        assert_eq!(
            journal.only,
            Some(vec![PathBuf::from("docs"), PathBuf::from("bin/tool")])
        );
        assert_eq!(journal.version, SELECT_VERSION);
        let saved = serde_json::to_string(&journal).unwrap();
        assert!(saved.contains(r#""version":9"#), "{saved}");
        // Alongside anything else a run records.
        let more = r#","keep":true,"only":["a"],"case_folders":["a"],"replace":{"moved":true}"#;
        let (journal, _) = Journal::load(&write_with(&dir, 9, more)).unwrap();
        assert_eq!(journal.version, SELECT_VERSION);

        // Older builds would resume it whole; a selection that removes the
        // archive, or that leaves the output folder, was never written.
        assert!(Journal::load(&write_with(&dir, 4, only)).is_err());
        assert!(Journal::load(&write_with(&dir, 8, only)).is_err());
        assert!(Journal::load(&write_with(&dir, 9, r#","keep":true"#)).is_err());
        assert!(Journal::load(&write_with(&dir, 9, r#","only":["a"]"#)).is_err());
        assert!(Journal::load(&write_with(&dir, 9, r#","keep":true,"only":[]"#)).is_err());
        assert!(Journal::load(&write_with(&dir, 9, r#","keep":true,"only":["../a"]"#)).is_err());
        assert!(Journal::load(&write_with(&dir, 9, r#","keep":true,"only":["/a"]"#)).is_err());
        assert!(Journal::load(&write_with(&dir, 9, r#","keep":true,"only":[""]"#)).is_err());

        fs::remove_dir_all(&dir).unwrap();
    }

    /// A run started by the previous release resumes; one started by a
    /// release that knows more is refused before anything is touched.
    #[test]
    fn reads_version_2_and_refuses_newer_journals() {
        let dir = std::env::temp_dir().join(format!("hatchzip-journal-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();

        let (journal, _) = Journal::load(&write(&dir, 2)).unwrap();
        assert_eq!(journal.resume, None);
        assert_eq!(journal.version, VERSION);

        let err = Journal::load(&write(&dir, SELECT_VERSION + 1))
            .err()
            .unwrap();
        assert!(format!("{err:#}").contains("newer HatchZip"), "{err:#}");
        let err = Journal::load(&write(&dir, 1)).err().unwrap();
        assert!(format!("{err:#}").contains("older HatchZip"), "{err:#}");

        fs::remove_dir_all(&dir).unwrap();
    }
}