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
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
//! Opening an archive for extraction and working out whether it fits. Shared
//! by the command line and the GUI, so the two never disagree.

use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};
use std::sync::Arc;

use anyhow::{Context, Result, bail};

use crate::archive::storage::{self, Reads, Storage};
use crate::engine::Job;
use crate::fsutil;
use crate::journal::{Journal, Paths, Plan};

/// The first volume of the archive and where its journal lives. Paths are
/// made absolute so a resume works from any directory.
pub fn locate(archive: &Path) -> Result<(PathBuf, Paths)> {
    let primary = std::path::absolute(storage::first_volume(archive))
        .with_context(|| format!("resolving {}", archive.display()))?;
    let paths = Paths::for_archive(&primary);
    Ok((primary, paths))
}

/// The archive a finished run offers to extract for `path`, one of the files
/// in `written`, the files it wrote: the first volume of its set, so a set
/// is offered once whichever volume is asked about. `None` unless `path` and
/// that first volume are archives by name and signature, and every volume of
/// the set is in `written` ([`volumes_written`]). A native split ZIP is
/// found by its `.z01`, whose split marker no other check names.
///
/// An archive with progress files next to it (a journal, its tail or
/// folder list, a split ZIP's stub) is never offered, even when the run
/// wrote them: a resume would follow what they say, not what the person
/// was offered. A split ZIP is also opened read only, so a set whose index
/// names more segments than are there is not offered.
pub fn nested_offer(path: &Path, written: &HashSet<PathBuf>) -> Option<PathBuf> {
    crate::archive::nested_kind(path)?;
    let (primary, paths) = locate(path).ok()?;
    // A `.zip` that happens to start with a local header names the set of
    // the `.z01` next to it, which must itself look like a first segment.
    let kind = crate::archive::nested_kind(&primary)?;
    let side_files = [&paths.journal, &paths.tail, &paths.folders]
        .into_iter()
        .chain(&paths.stub)
        .any(|p| fs::symlink_metadata(p).is_ok());
    if side_files || !volumes_written(&primary, written) {
        return None;
    }
    // Opening reads only the index and the local headers, and checks the
    // segment count against the index. Other formats are not opened here:
    // a compressed tar is decompressed in full to list it.
    if kind == crate::archive::SPLIT_ZIP {
        Job::open(&primary, false, None, Arc::default()).ok()?;
    }
    Some(primary)
}

/// Whether every volume of the set whose first volume is `primary` that
/// exists on disk is in `written`. A set that is not split has one volume.
///
/// Extracting a set in place removes every volume, so an offer to extract it
/// must not take in one the run did not write: a `.zip` next to the person's
/// own `.z01` is the last segment of their set, not of the run's.
///
/// A native split ZIP also needs its `.zip`, which holds the index. A
/// segment in `written` past a missing one, such as a `.z03` without the
/// `.z02`, also makes this false. That only catches the gaps the run's own
/// files show: a set missing its last segments before the `.zip` passes,
/// and only opening it, which checks the index, finds that.
pub fn volumes_written(primary: &Path, written: &HashSet<PathBuf>) -> bool {
    let mut volumes = Vec::new();
    if storage::is_split_zip(primary) {
        for disk in 0.. {
            let Some(segment) = storage::split_zip_segment(primary, disk) else {
                break;
            };
            if !segment.exists() {
                break;
            }
            volumes.push(segment);
        }
        match storage::split_zip_last(primary) {
            Some(last) if last.exists() => volumes.push(last),
            _ => return false,
        }
        let beyond_a_gap = written.iter().any(|w| {
            w.parent() == primary.parent()
                && !volumes.contains(w)
                && storage::first_volume(w) == primary
        });
        if beyond_a_gap {
            return false;
        }
    } else {
        for index in 0.. {
            let Some(volume) = storage::volume_path(primary, index) else {
                break;
            };
            if index > 0 && !volume.exists() {
                break;
            }
            volumes.push(volume);
        }
    }
    volumes
        .iter()
        .filter(|v| v.exists())
        .all(|v| written.contains(v))
        && written.contains(primary)
}

/// Where an extraction goes, and who said so. A half-extracted archive's
/// progress files lie next to it, where whoever supplied the archive could
/// have put them, so a resume follows them only into a folder this
/// computer recorded starting that extraction in (see [`check_output`]).
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Output {
    /// The folder next to the archive ([`default_output`]), or for a
    /// half-extracted archive the folder its journal records.
    Default,
    /// A folder HatchZip worked out itself, such as the one "Extract to
    /// folder" names after the archive. A resume goes there only when the
    /// journal says so too, and is trusted as [`Output::Default`] is.
    Computed(PathBuf),
    /// A folder the person named for this run, typed or picked.
    Named(PathBuf),
}

impl Output {
    pub fn path(&self) -> Option<&Path> {
        match self {
            Self::Default => None,
            Self::Computed(p) | Self::Named(p) => Some(p),
        }
    }
}

// Made once per open and taken apart at once, so the size of the largest
// variant costs nothing worth boxing for.
#[allow(clippy::large_enum_variant)]
pub enum State {
    /// Nothing touched yet. Nothing changes on disk until [`begin`] writes
    /// the journal.
    Fresh(Job, PathBuf),
    Resume(Job, Journal),
    /// The archive is gone but the run died before cleaning up.
    Orphan(Journal),
}

/// Asks again what a run recorded when it began: see
/// [`crate::engine::check_case_record`].
pub(crate) fn check_recorded_case(journal: &Journal) -> Result<()> {
    crate::engine::check_case_record(
        &journal.output,
        &journal.case_folders,
        journal.case_beyond_ascii,
    )
}

/// Whether names that differ only in case can both exist in `dir`, as far as
/// HatchZip knows.
pub fn case_sensitive(dir: &Path) -> bool {
    crate::platform::case_sensitive(dir)
}

/// `writable` is false for anything that only looks, so it works on
/// read-only media and never takes the lock. For a fresh extraction the
/// output folder may already hold other files, but no folder where the
/// archive has a file or the other way round; files the archive would
/// replace are listed by [`existing`]. `password` only matters for encrypted archives; see
/// [`open_encrypted`] for the ask-and-retry loop front ends want. What
/// opening reads is counted in `reads`, which a front end can show from
/// another thread: a compressed tar is read in full here.
///
/// `only` limits a fresh extraction to those entries and the folders among
/// them (see [`Job::select`]), which [`begin`] then allows only while the
/// archive is kept. A half-extracted archive goes on with the selection its
/// journal records, and one given here must be part of it.
pub fn open(
    primary: &Path,
    paths: &Paths,
    output: Output,
    only: Option<&[PathBuf]>,
    writable: bool,
    password: Option<&str>,
    reads: &Arc<Reads>,
) -> Result<State> {
    if paths.exists() {
        let (mut journal, tail) = Journal::load(paths)?;
        // With every entry out, or the archive gone, this is no resume: it
        // only finishes, and a lost list costs the folders' permissions and
        // times, which the finish warns about.
        if writable && !journal.done && journal.parts[0].0.exists() {
            journal.check_folders(paths)?;
        }
        // Only a writable open deletes or writes anything in the folder.
        if writable || output != Output::Default {
            check_output(&journal, primary, &output)?;
        }
        if writable {
            check_recorded_case(&journal)?;
        }
        if journal.restoring.is_some() {
            if !writable {
                bail!(
                    "a restore of this archive was interrupted. Run restore again to complete \
                     it, or run extract to resume the extraction"
                );
            }
            crate::restore::recover(&mut journal, paths)?;
        }
        if !journal.parts[0].0.exists() {
            check_first_part_gone(&journal)?;
            if journal.keep {
                // Only the person could have removed an archive this run
                // promised to keep, and the rest of it is still to extract.
                bail!(
                    "{} was moved or deleted during an extraction that keeps it. Put it back \
                     to resume, or delete {} to discard the progress",
                    journal.parts[0].0.display(),
                    paths.journal.display()
                );
            }
            return Ok(State::Orphan(journal));
        }
        // The final commit was journaled: every unit is extracted, and only
        // the archive's removal and the links are left. Nothing is read from
        // it again; a compressed stream's start was punched away by then.
        if journal.done {
            return Ok(State::Orphan(journal));
        }
        if let Some(given) = only {
            check_same_selection(&journal, given)?;
        }
        let job = Job::resume(&journal, tail, writable, password, reads.clone())?;
        check_no_links_on_the_way(&job, &journal.output)?;
        return Ok(State::Resume(job, journal));
    }
    let mut job = Job::open(primary, writable, password, reads.clone())?;
    if writable && job.format_name == crate::archive::SPLIT_ZIP {
        paths.check_stub()?;
    }
    if let Some(given) = only {
        job.select(given)?;
    }
    let output = match output {
        Output::Named(o) => std::path::absolute(o)?,
        // A folder worked out from the archive's name, like the default
        // one, may be a link the archive's supplier put there.
        Output::Computed(o) => {
            let output = std::path::absolute(o)?;
            refuse_linked_default(&output)?;
            output
        }
        Output::Default => {
            let output = default_output(primary);
            refuse_linked_default(&output)?;
            output
        }
    };
    check_path_lengths(&job, &output)?;
    if writable {
        check_no_links_on_the_way(&job, &output)?;
        check_collisions(&job, &output)?;
        job.check_case(&output)?;
    }
    Ok(State::Fresh(job, output))
}

/// With the first part of a split archive gone, a run that never journaled
/// its last commit has not deleted it: the first part is only ever shortened,
/// and deleted with the rest once everything is out. So when a later part
/// that still holds entries to extract is there, the first one was moved,
/// and finishing the run as one whose archive is gone would delete the
/// journal and the saved index the rest of the archive needs.
pub(crate) fn check_first_part_gone(journal: &Journal) -> Result<()> {
    if journal.done || journal.keep {
        return Ok(());
    }
    let mut start = 0u64;
    for (i, (part, len)) in journal.parts.iter().enumerate() {
        if i > 0 && start < journal.committed_len && part.exists() {
            bail!(
                "{} was moved or deleted during the extraction, but {} and the rest of the \
                 archive still need it. Put it back to resume. Nothing was modified",
                journal.parts[0].0.display(),
                part.display()
            );
        }
        start = start.saturating_add(*len);
    }
    Ok(())
}

/// A resume goes on with what its journal records. Asking for entries now is
/// fine when they are all part of that selection, and refused otherwise,
/// before the archive is opened for writing.
fn check_same_selection(journal: &Journal, given: &[PathBuf]) -> Result<()> {
    let Some(recorded) = &journal.only else {
        bail!(
            "this archive is partially extracted with every entry selected. Resume it without \
             choosing entries, or run restore first. Nothing was modified"
        );
    };
    for g in given {
        let p = crate::engine::selection_path(g)?;
        // A path inside a recorded folder is part of the selection too.
        if !crate::engine::picks(recorded, &p) {
            bail!(
                "this archive is partially extracted with other entries selected, and '{}' is \
                 not one of them. Resume it without choosing entries to finish those, or run \
                 restore first. Nothing was modified",
                p.display()
            );
        }
    }
    Ok(())
}

/// The journal lies next to the archive, where anyone who supplied the
/// archive could have put one, so it is used only for an extraction this
/// computer recorded starting into that folder (see [`crate::chosen`]). A
/// resume deletes what it finds at the paths of the entries left and cuts
/// the archive to what the journal says, so a planted journal could
/// otherwise destroy the archive and replace the person's own files in the
/// folder it names. A folder given now must also be the journal's, and one
/// HatchZip worked out ([`Output::Computed`]) vouches for nothing: a
/// planted journal can name it as easily as the app does. Without the
/// record the journal is never followed, whatever its format says: a
/// planted one can claim to come from a release that kept no record.
pub fn check_output(journal: &Journal, primary: &Path, given: &Output) -> Result<()> {
    let default = default_output(primary);
    let in_default = fsutil::same_path(&default, &journal.output);
    if let Some(o) = given.path()
        && !fsutil::same_path(&std::path::absolute(o)?, &journal.output)
    {
        bail!(
            "this archive is already partially extracted to {}. Complete or restore that \
             extraction first",
            journal.output.display()
        );
    }
    let named = matches!(given, Output::Named(_));
    if crate::chosen::chose(primary, &journal.output) {
        // A folder the person names is theirs to choose, link or not.
        if in_default && !named {
            refuse_linked_default(&default)?;
        }
        return Ok(());
    }
    let paths = Paths::for_archive(primary);
    bail!(
        "{} has progress files next to it for an extraction to {}, but HatchZip on this computer \
         has no record of starting it, so they were not used. If you did not start this \
         extraction, delete {}. Nothing was modified",
        primary.display(),
        journal.output.display(),
        journal.side_files(&paths)
    )
}

/// A link at the default output folder, next to the archive, would send the
/// extraction wherever it points. A folder the person names is theirs to
/// choose.
fn refuse_linked_default(output: &Path) -> Result<()> {
    if fs::symlink_metadata(output).is_ok_and(|m| m.is_symlink()) {
        bail!(
            "{} is a link, so files extracted there would land somewhere else. Remove the link, \
             or choose the destination folder. Nothing was modified",
            output.display()
        );
    }
    Ok(())
}

/// A resume deletes and writes the files of the entries left, and its own
/// links are only made once every entry is done. A link on the way to one of
/// those files was put there by someone else, and following it would leave
/// the output folder.
pub(crate) fn check_no_links_on_the_way(job: &Job, out: &Path) -> Result<()> {
    let mut checked = std::collections::HashSet::new();
    for item in job.units.iter().flat_map(|u| &u.items) {
        for parent in item
            .path
            .ancestors()
            .skip(1)
            .filter(|p| !p.as_os_str().is_empty())
        {
            if !checked.insert(parent.to_path_buf()) {
                break;
            }
            if fs::symlink_metadata(out.join(parent)).is_ok_and(|m| m.is_symlink()) {
                bail!(
                    "{} is a link, and '{}' would be extracted through it. Nothing was modified",
                    out.join(parent).display(),
                    item.path.display()
                );
            }
        }
    }
    Ok(())
}

/// A path the system can't create would only fail halfway through a run,
/// after part of the archive is gone; macOS stops at 1024 bytes.
fn check_path_lengths(job: &Job, out: &Path) -> Result<()> {
    for item in job.units.iter().flat_map(|u| &u.items) {
        if crate::platform::path_len(&out.join(&item.path)) > crate::platform::MAX_PATH_LEN {
            bail!(
                "'{}' cannot be created in {}: the full path would be longer than this system \
                 allows. The archive was not modified. Extract to a folder with a shorter path",
                item.path.display(),
                out.display()
            );
        }
    }
    Ok(())
}

/// Opens an archive that may be encrypted. `ask` is called whenever a
/// password is needed or the last one was wrong, and returns `None` to give
/// up. Archives with a password are proven with [`Job::check_password`]
/// before this returns, so nothing is deleted on a wrong guess. Returns the
/// state and the password that worked.
#[allow(clippy::too_many_arguments)]
pub fn open_encrypted(
    primary: &Path,
    paths: &Paths,
    output: Output,
    only: Option<&[PathBuf]>,
    writable: bool,
    password: Option<String>,
    reads: &Arc<Reads>,
    ask: impl FnMut(bool) -> Option<String>,
) -> Result<(State, Option<String>)> {
    open_encrypted_noting(
        primary,
        paths,
        output,
        only,
        writable,
        password,
        reads,
        ask,
        |_, _| {},
    )
}

/// [`open_encrypted`], calling `slow` with a file and its size before a
/// password check that decodes all of it (see [`Job::slow_password_check`]),
/// so a front end can say it may take a while.
#[allow(clippy::too_many_arguments)]
pub fn open_encrypted_noting(
    primary: &Path,
    paths: &Paths,
    output: Output,
    only: Option<&[PathBuf]>,
    writable: bool,
    mut password: Option<String>,
    reads: &Arc<Reads>,
    mut ask: impl FnMut(bool) -> Option<String>,
    mut slow: impl FnMut(&Path, u64),
) -> Result<(State, Option<String>)> {
    let mut wrong = false;
    loop {
        let attempt = open(
            primary,
            paths,
            output.clone(),
            only,
            writable,
            password.as_deref(),
            reads,
        );
        let failure = match attempt {
            Ok(State::Orphan(j)) => return Ok((State::Orphan(j), password)),
            Ok(state) => {
                let job = match &state {
                    State::Fresh(job, _) | State::Resume(job, _) => job,
                    State::Orphan(_) => unreachable!(),
                };
                if !job.encrypted() {
                    return Ok((state, password));
                }
                if password.is_some()
                    && let Some((file, size)) = job.slow_password_check()
                {
                    slow(file, size);
                }
                match job.check_password() {
                    Ok(()) => return Ok((state, password)),
                    Err(e) => e,
                }
            }
            Err(e) => e,
        };
        if failure.is::<crate::archive::WrongPassword>() {
            wrong = true;
        } else if !failure.is::<crate::archive::PasswordNeeded>() {
            return Err(failure);
        }
        // Drop the open archive before asking, so nothing stays locked while
        // a person types.
        match ask(wrong) {
            Some(p) => password = Some(p),
            None => return Err(failure),
        }
    }
}

/// Refuses what no extraction into `out` can get past: a folder where the
/// archive has a file, which is never deleted or replaced, a file where it
/// needs a folder, which would only fail halfway, and anything at the name a
/// file is first written under. That last one would be in the way of the
/// file, or would be deleted as the run's own by a resume.
fn check_collisions(job: &Job, out: &Path) -> Result<()> {
    if !out.exists() {
        return Ok(());
    }
    check_own_files(job, out)?;
    let mut checked = std::collections::HashSet::new();
    for item in job.units.iter().flat_map(|u| &u.items) {
        let dest = out.join(&item.path);
        let part = crate::engine::part_path(&dest);
        if item.kind == crate::archive::Kind::File && fs::symlink_metadata(&part).is_ok() {
            bail!(
                "{} already exists. HatchZip first writes '{}' under that name and does not \
                 replace a file it did not create. Move it or choose another destination. Nothing \
                 was modified",
                part.display(),
                item.path.display()
            );
        }
        if let Ok(meta) = fs::symlink_metadata(&dest) {
            let dir = item.kind == crate::archive::Kind::Dir;
            if dir && !meta.is_dir() {
                bail!(
                    "{} is a file, but the archive requires a folder at that location",
                    dest.display()
                );
            }
            if !dir && meta.is_dir() {
                bail!(
                    "{} is a folder, but the archive has a file at that location. Move the \
                     folder or choose another destination",
                    dest.display()
                );
            }
        }
        for parent in item
            .path
            .ancestors()
            .skip(1)
            .filter(|p| !p.as_os_str().is_empty())
        {
            if !checked.insert(parent.to_path_buf()) {
                break;
            }
            if let Ok(meta) = fs::symlink_metadata(out.join(parent))
                && !meta.is_dir()
            {
                bail!(
                    "{} is a file, but the archive requires a folder at that location",
                    out.join(parent).display()
                );
            }
        }
    }
    Ok(())
}

/// Refuses an entry that would land on one of the archive's own files: a
/// volume, or a progress file next to the first volume (`<archive>.hatchzip`,
/// `<archive>.hatchzip-tail` and any later one). Written over, a volume would
/// be lost before it was read, and a progress file would be trusted by the
/// next resume as HatchZip's own. That can only happen when the archive's
/// folder is inside the output folder. Names are compared ignoring case, as
/// a case-insensitive filesystem would.
fn check_own_files(job: &Job, out: &Path) -> Result<()> {
    let text = |p: &Path| p.to_string_lossy().to_lowercase();
    let folder = |p: &Path| {
        let dir = p.parent().filter(|d| !d.as_os_str().is_empty());
        fs::canonicalize(dir.unwrap_or(Path::new(".")))
            .ok()
            .map(|d| text(&d))
    };
    let lower = |p: &Path| p.file_name().map(|n| text(Path::new(n)));
    let Ok(out) = fs::canonicalize(out) else {
        return Ok(());
    };
    let primary = job.storage.primary();
    let own_folder = folder(primary);
    let side = lower(primary).map(|n| format!("{n}.hatchzip"));
    let volumes: Vec<_> = job
        .storage
        .parts()
        .iter()
        .map(|p| (folder(&p.path), lower(&p.path)))
        .collect();
    for item in job.units.iter().flat_map(|u| &u.items) {
        let dest = out.join(&item.path);
        let dir = dest.parent().map(text);
        let name = lower(&dest);
        let (Some(dir), Some(name)) = (dir, name) else {
            continue;
        };
        let volume = volumes
            .iter()
            .any(|(d, n)| d.as_ref() == Some(&dir) && n.as_ref() == Some(&name));
        let progress = own_folder.as_ref() == Some(&dir)
            && side.as_ref().is_some_and(|s| name.starts_with(s.as_str()));
        if volume || progress {
            bail!(
                "'{}' would be extracted onto {}, one of the archive's own files. Choose another \
                 destination. Nothing was modified",
                item.path.display(),
                dest.display()
            );
        }
    }
    Ok(())
}

/// The files and links already in `out` at paths the archive extracts to,
/// relative to `out`. A fresh extraction may only replace them when asked
/// to; see [`begin`]. When there are any, what would keep them from being
/// replaced is refused here, before a front end asks.
pub fn existing(job: &Job, out: &Path) -> Result<Vec<PathBuf>> {
    let found = crate::replace::found(job, out);
    if !found.is_empty() {
        crate::replace::check(job, out, &found)?;
    }
    Ok(found)
}

/// Whether everything in the archive sits under one name at its top, one
/// folder or a single file. "Extract here" puts such an archive next to
/// itself; anything else would scatter loose files, so it gets a folder.
pub fn single_root(job: &Job) -> bool {
    let mut roots = job
        .units
        .iter()
        .flat_map(|u| &u.items)
        .filter_map(|i| i.path.components().next());
    let Some(first) = roots.next() else {
        return false;
    };
    roots.all(|r| r == first)
}

/// Moves a fresh extraction opened writable by [`open`] to another folder,
/// checking it as [`open`] checks the one it was given.
pub fn retarget(job: &Job, out: &Path) -> Result<PathBuf> {
    let out = std::path::absolute(out)?;
    check_path_lengths(job, &out)?;
    check_no_links_on_the_way(job, &out)?;
    check_collisions(job, &out)?;
    job.check_case(&out)?;
    Ok(out)
}

/// `game.zip`, `game.7z.001`, `game.tar.gz`, `game.part1.rar` and `game.z01`
/// all extract into `game`, next to them.
pub fn default_output(primary: &Path) -> PathBuf {
    let file_name = primary
        .file_name()
        .unwrap_or_default()
        .to_string_lossy()
        .into_owned();
    let mut name = file_name.clone();
    if let Some((stem, digits)) = name.rsplit_once('.')
        && digits.len() >= 3
        && digits.bytes().all(|b| b.is_ascii_digit())
    {
        name = stem.to_string();
    }
    // `game.z01` is the first segment of the split ZIP `game.zip`.
    if let Some((stem, ext)) = name.rsplit_once('.')
        && ext.len() >= 3
        && ext.as_bytes()[0].eq_ignore_ascii_case(&b'z')
        && ext.bytes().skip(1).all(|b| b.is_ascii_digit())
    {
        name = stem.to_string();
    }
    let lower = name.to_ascii_lowercase();
    // `game.part2.rar` and `game.part02.rar` are volumes of `game`.
    if let Some(stem) = lower.strip_suffix(".rar")
        && let Some((_, digits)) = stem.rsplit_once(".part")
        && !digits.is_empty()
        && digits.bytes().all(|b| b.is_ascii_digit())
    {
        name.truncate(stem.len() - digits.len() - ".part".len());
    } else {
        for ext in [
            ".zip", ".7z", ".tar.xz", ".txz", ".tar.bz2", ".tbz2", ".tbz", ".tar.zst", ".tzst",
            ".tar", ".tar.gz", ".tgz", ".rar", ".exe",
        ] {
            if lower.ends_with(ext) && name.len() > ext.len() {
                name.truncate(name.len() - ext.len());
                break;
            }
        }
    }
    // What is left names a folder next to the archive, so it must be an
    // ordinary name. `...zip` would leave `..`, the folder above, and `..zip`
    // would leave `.`, the archive's own folder, where its entries could
    // replace its progress files. Windows drops trailing dots and spaces, so
    // `. .zip` is `.` there too.
    if name == file_name || name.chars().all(|c| c == '.' || c == ' ') {
        name = file_name;
        name.push_str("-extracted");
    }
    primary.with_file_name(name)
}

/// `game.zip`, or `game.7z.001 (+4 more parts)` for a split archive.
pub fn display_name(job: &Job) -> String {
    let parts = job.storage.parts();
    let first = parts[0]
        .path
        .file_name()
        .unwrap_or_default()
        .to_string_lossy()
        .into_owned();
    match parts.len() {
        1 => first,
        n => format!("{first} (+{} more parts)", n - 1),
    }
}

/// Whether the extraction of a half-extracted archive keeps it, given what
/// the person asked for now. The journal decides: an extraction that keeps
/// the archive goes on keeping it, and one that has already removed part of
/// it can't start keeping it.
pub fn keeps_archive(journal: &Journal, asked: bool) -> Result<bool> {
    if asked && !journal.keep {
        bail!(
            "this archive is partially extracted in place, so part of it is already removed and \
             it cannot be kept. Resume without --keep-archive, or run restore first"
        );
    }
    Ok(journal.keep)
}

/// Whether an extraction fits, in the numbers a person needs to decide.
pub struct SpacePlan {
    /// Usable free space, counting files a crashed run left that will be
    /// deleted before continuing.
    pub free: u64,
    /// Free space the extraction needs at its busiest moment, in the mode
    /// asked for.
    pub needed: u64,
    pub keep_free: u64,
    pub fits: bool,
    /// Free space once finished, if it fits.
    pub free_after: u64,
    /// The plan is for an extraction that keeps the archive.
    pub keep_archive: bool,
    /// What an extraction that keeps the archive needs free: every
    /// extracted file, as for any other extractor, plus the saved index.
    pub normal_needs: u64,
    /// What extracting in place needs free. Equal to `needed` unless the
    /// archive is kept.
    pub in_place_needs: u64,
    /// Nothing is extracted yet, so either mode can still be chosen. A
    /// half-extracted archive continues in the mode it started in.
    pub either: bool,
    /// False when the output is on another disk, so freeing the archive
    /// doesn't help it.
    pub reclaims: bool,
    /// The shortfall comes from one solid block that can only be freed once
    /// all of it is out.
    pub solid_block_bound: bool,
    /// The archive is one compressed stream (a `.tar.gz`) on a filesystem
    /// that can't free space inside a file, such as FAT32 or exFAT, so it
    /// stays whole until the extraction completes: `needed` is room for
    /// every extracted file next to it.
    pub archive_kept_whole: bool,
}

impl SpacePlan {
    /// Whether an extraction that keeps the archive would fit too.
    pub fn normal_fits(&self) -> bool {
        self.free >= self.normal_needs + self.keep_free
    }

    pub fn in_place_fits(&self) -> bool {
        self.free >= self.in_place_needs + self.keep_free
    }
}

/// Refuses a destination that cannot become a folder: a file or a dangling
/// link at its path, or where one of its folders would go. Called before
/// anything is written, so a run cannot leave a journal that only promises a
/// resume that would fail the same way.
fn check_destination(out: &Path, resuming: bool) -> Result<()> {
    let untouched = if resuming {
        ""
    } else {
        ". Nothing was modified"
    };
    // Walk up until something exists. `exists` follows links, so a dangling
    // one looks absent and `create_dir_all` would fail on it later; metadata
    // that is not a folder stops the run here instead.
    let mut path = out.to_path_buf();
    loop {
        match path.symlink_metadata() {
            Ok(meta) => {
                if path.is_dir() {
                    return Ok(());
                }
                let what = if meta.is_file() {
                    "is a file, not a folder"
                } else {
                    "is not a folder"
                };
                if path == out {
                    bail!("the destination {} {what}{untouched}", out.display());
                }
                bail!(
                    "the destination {} cannot be created: {} {what}{untouched}",
                    out.display(),
                    path.display()
                );
            }
            Err(_) => {
                if !path.pop() {
                    return Ok(());
                }
            }
        }
    }
}

/// The space plan for extracting `job` into `out`, keeping the archive or
/// not. For a half-extracted archive, `keep_archive` must be what its
/// journal says; see [`keeps_archive`].
pub fn plan(
    job: &Job,
    out: &Path,
    resuming: bool,
    keep_free: u64,
    keep_archive: bool,
) -> Result<SpacePlan> {
    job.check_case(out)?;
    check_destination(out, resuming)?;
    let reclaims = fsutil::same_filesystem(job.storage.primary(), out);
    let stale: u64 =
        job.uncommitted(out).iter().map(|(_, n)| n).sum::<u64>() + job.past_resume_point(out);
    let free = fsutil::available_space(out)? + stale;
    // Keeping the archive frees nothing, as if the output were on another
    // disk: the replay counts every file and gives nothing back.
    let (normal_needs, normal_end) = job.space_needed(!resuming, false);
    let (in_place_needs, in_place_end) = if keep_archive && resuming {
        (normal_needs, normal_end)
    } else {
        job.space_needed(!resuming, reclaims)
    };
    // The saved index is deleted at the end, when the archive is kept too.
    let tail = job.storage.original_len().saturating_sub(job.tail_start) as i128;
    let normal_end = normal_end - if reclaims { tail } else { 0 };
    let (needed, end) = if keep_archive {
        (normal_needs, normal_end)
    } else {
        (in_place_needs, in_place_end)
    };
    let fits = free >= needed + keep_free;
    Ok(SpacePlan {
        free,
        needed,
        keep_free,
        fits,
        free_after: (free as i128 - end).max(0) as u64,
        keep_archive,
        normal_needs,
        in_place_needs,
        either: !resuming,
        reclaims,
        solid_block_bound: !fits
            && !keep_archive
            && !job.is_stream()
            && job
                .units
                .iter()
                .any(|u| u.items.len() > 1 && u.size() > free),
        archive_kept_whole: !keep_archive && job.kept_whole(reclaims),
    })
}

/// Commits to a fresh extraction: saves the archive's tail and writes the
/// journal. From here on the archive may be truncated, unless `keep_archive`
/// is set, in which case nothing ever changes it. Files in the way (see
/// [`existing`]) are refused unless `replace` is given; then the run moves
/// them aside before it extracts anything, and once it is complete deletes
/// them or puts back the ones the choices keep.
pub fn begin(
    job: &Job,
    paths: &Paths,
    output: PathBuf,
    keep_archive: bool,
    replace: Option<&crate::replace::Choices>,
) -> Result<Journal> {
    // Front ends ask earlier; the folder may have changed since.
    job.check_case(&output)?;
    check_destination(&output, false)?;
    let found = existing(job, &output)?;
    if let Some(first) = found.first()
        && replace.is_none()
    {
        let what = match found.len() {
            1 => format!("{} already exists", output.join(first).display()),
            n => format!(
                "{} and {} other {} already exist",
                output.join(first).display(),
                n - 1,
                if n == 2 { "file" } else { "files" }
            ),
        };
        bail!(
            "{what}. Existing files are only replaced when that is requested. Move the files or \
             choose another destination. Nothing was modified"
        );
    }
    if job.selection().is_some() && !keep_archive {
        // Truncating would destroy the entries left out.
        bail!(
            "only some entries are selected, and those are extracted only while the archive is \
             kept. Nothing was modified"
        );
    }
    if keep_archive {
        job.storage.protect();
    } else if let Some(why) = job.in_place_refusal() {
        // Front ends say this earlier; this is the last line.
        bail!("{why}. It can be extracted while keeping the archive");
    }
    crate::sfv::check_volumes(&job.storage)?;
    // Whatever the folder: a resume trusts the journal only when this
    // computer recorded starting the extraction (see [`check_output`]), so
    // a run that can't be recorded could never be resumed.
    crate::chosen::remember(&paths.archive, &output)?;
    // A choice for a file that has gone since it was made has nothing to
    // keep.
    let only_found = |paths: &[PathBuf]| -> Vec<PathBuf> {
        paths
            .iter()
            .filter(|p| found.contains(p))
            .cloned()
            .collect()
    };
    let replace = replace
        .filter(|_| !found.is_empty())
        .map(|c| crate::journal::Replace {
            moved: false,
            keep: only_found(&c.keep),
            both: only_found(&c.both),
        });
    let folders = crate::folders::of(&job.units, &output);
    let plan = Plan {
        format: job.format_name,
        tail_start: job.tail_start,
        output,
        total_size: job.remaining_size(),
        keep: keep_archive,
        replace,
        case_folders: job.case_folders(),
        case_beyond_ascii: job.case_beyond_ascii(),
        folders,
        only: job.selection().map(<[PathBuf]>::to_vec),
    };
    Journal::create(paths, &job.storage, plan)
}

/// Checks the archive's volumes against an `.sfv` file next to it, if present.
pub fn check_sfv(storage: &Storage, cancelled: &dyn Fn() -> bool) -> Result<Option<PathBuf>> {
    crate::sfv::check_volumes_cancellable(storage, cancelled)
}

/// Before continuing a crashed run, deletes what it wrote for batches it
/// never committed.
pub fn clear_uncommitted(job: &Job, out: &Path) -> Result<()> {
    clear_output(job, out, false)
}

/// Discards a kept run's uncommitted output, including its open file. The
/// untouched archive holds that file; normal resume must preserve it.
pub(crate) fn clear_discarded(job: &Job, out: &Path) -> Result<()> {
    clear_output(job, out, true)
}

fn clear_output(job: &Job, out: &Path, discard: bool) -> Result<()> {
    check_no_links_on_the_way(job, out)?;
    let found = if discard {
        job.discarded_output(out)
    } else {
        job.uncommitted(out)
    };
    let mut listed = std::collections::HashMap::new();
    for (p, _) in &found {
        check_spelling(out, p, &mut listed)?;
    }
    for (p, _) in found {
        fs::remove_file(&p).with_context(|| format!("removing stale {}", p.display()))?;
    }
    Ok(())
}

/// Refuses to delete `path` unless every name from `out` down to it is
/// spelled on disk as in the entry. Where the filesystem folds names,
/// `makefile` also finds a `Makefile` that another program, or another
/// archive, put there after this run began, and that one isn't this run's
/// to delete. Spellings are compared decomposed and nothing else, since
/// HFS+ stores names decomposed whatever they were created as.
fn check_spelling(
    out: &Path,
    path: &Path,
    listed: &mut std::collections::HashMap<PathBuf, std::collections::HashSet<String>>,
) -> Result<()> {
    use unicode_normalization::UnicodeNormalization;
    let spelling = |n: &std::ffi::OsStr| n.to_string_lossy().nfd().collect::<String>();
    let Ok(rel) = path.strip_prefix(out) else {
        return Ok(());
    };
    let mut dir = out.to_path_buf();
    for name in rel.iter() {
        let names = match listed.entry(dir.clone()) {
            std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
            std::collections::hash_map::Entry::Vacant(e) => e.insert(
                fs::read_dir(&dir)
                    .with_context(|| format!("listing {}", dir.display()))?
                    .map(|e| e.map(|e| spelling(&e.file_name())))
                    .collect::<std::io::Result<_>>()
                    .with_context(|| format!("listing {}", dir.display()))?,
            ),
        };
        if !names.contains(&spelling(name)) {
            bail!(
                "{} is spelled differently on disk than in the archive, so it was not made by \
                 this extraction and is left alone. Move it out of the way, then run the command \
                 again",
                dir.join(name).display()
            );
        }
        dir.push(name);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use std::io::Write;

    use ::zip::write::{SimpleFileOptions, ZipWriter};

    use super::*;

    /// A resume only deletes what is spelled as its entry: a `Makefile` on
    /// disk isn't `makefile`'s, even where the filesystem would find it.
    #[test]
    fn a_resume_leaves_names_spelled_differently_alone() {
        let dir = tempfile::tempdir().unwrap();
        let out = dir.path();
        fs::create_dir(out.join("Src")).unwrap();
        fs::write(out.join("Src/Makefile"), b"theirs").unwrap();
        fs::write(out.join("Src/caf\u{e9}.txt"), b"ours").unwrap();
        let mut listed = std::collections::HashMap::new();
        assert!(check_spelling(out, &out.join("Src/makefile"), &mut listed).is_err());
        assert!(check_spelling(out, &out.join("src/Makefile"), &mut listed).is_err());
        assert!(check_spelling(out, &out.join("Src/Makefile"), &mut listed).is_ok());
        // HFS+ hands back the decomposed form of what was created composed.
        assert!(check_spelling(out, &out.join("Src/cafe\u{301}.txt"), &mut listed).is_ok());
    }

    #[test]
    fn output_folder_drops_the_volume_and_format_suffixes() {
        let name = |n: &str| default_output(Path::new(n));
        assert_eq!(name("game.zip"), Path::new("game"));
        assert_eq!(name("game.7z.001"), Path::new("game"));
        assert_eq!(name("game.part1.rar"), Path::new("game"));
        assert_eq!(name("game.PART02.RAR"), Path::new("game"));
        assert_eq!(name("game.rar"), Path::new("game"));
        assert_eq!(name("game.tar.xz"), Path::new("game"));
        assert_eq!(name("game.txz"), Path::new("game"));
        assert_eq!(name("game.tar.zst"), Path::new("game"));
        assert_eq!(name("game.tzst"), Path::new("game"));
        assert_eq!(name("game.part.rar"), Path::new("game.part"));
        assert_eq!(name("notes.txt"), Path::new("notes.txt-extracted"));
    }

    /// A name that would leave only dots, the folder above or the archive's
    /// own, gets a folder of its own instead.
    #[test]
    fn output_folder_is_never_the_folder_above_or_the_archives_own() {
        let name = |n: &str| default_output(&Path::new("dl").join(n));
        for n in [
            "...zip",
            "..zip",
            ".zip",
            ". .zip",
            "...tar.gz",
            "...7z.001",
            "...part1.rar",
            "..part2.rar",
        ] {
            assert_eq!(
                name(n),
                Path::new("dl").join(format!("{n}-extracted")),
                "{n}"
            );
        }
        assert_eq!(name("...game.zip"), Path::new("dl/...game"));
    }

    /// Eight stored entries, so extracting in place frees the archive entry
    /// by entry and needs far less than keeping it.
    fn sample_zip(dir: &Path) -> PathBuf {
        let path = dir.join("plan.zip");
        let mut w = ZipWriter::new(fs::File::create(&path).unwrap());
        let opts =
            SimpleFileOptions::default().compression_method(::zip::CompressionMethod::Stored);
        for i in 0..8u8 {
            w.start_file(format!("data/{i}.bin"), opts).unwrap();
            w.write_all(&vec![i; 200_000 + usize::from(i)]).unwrap();
        }
        w.finish().unwrap();
        path
    }

    #[test]
    fn keeping_the_archive_plans_for_every_file() {
        let dir = std::env::temp_dir().join(format!("hatchzip-plan-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        let archive = sample_zip(&dir);
        let out = dir.join("out");
        let job = Job::open(&archive, false, None, Default::default()).unwrap();
        let files: u64 = job
            .units
            .iter()
            .flat_map(|u| &u.items)
            .map(|i| i.size.next_multiple_of(4096))
            .sum();
        let tail = job.storage.original_len() - job.tail_start;

        let keep = plan(&job, &out, false, 0, true).unwrap();
        assert!(keep.keep_archive && keep.either);
        // Every file, plus the copy of the index a resume would need.
        assert_eq!(keep.needed, files + tail);
        assert_eq!(keep.normal_needs, keep.needed);
        assert!(!keep.solid_block_bound && !keep.archive_kept_whole);
        // Nothing of the archive comes back; the saved index does.
        assert_eq!(keep.free.saturating_sub(keep.free_after), files);

        let in_place = plan(&job, &out, false, 0, false).unwrap();
        assert!(!in_place.keep_archive);
        assert_eq!(in_place.normal_needs, keep.needed);
        assert_eq!(in_place.in_place_needs, in_place.needed);
        assert_eq!(keep.in_place_needs, in_place.needed);
        assert!(
            in_place.needed < keep.needed / 2,
            "in place {} vs kept {}",
            in_place.needed,
            keep.needed
        );
        drop(job);
        fs::remove_dir_all(&dir).unwrap();
    }

    /// Once an extraction that keeps the archive has begun, nothing can
    /// change it, whatever the caller does.
    #[test]
    fn a_kept_archive_refuses_every_change() {
        let dir = std::env::temp_dir().join(format!("hatchzip-protect-{}", std::process::id()));
        fs::create_dir_all(&dir).unwrap();
        let archive = sample_zip(&dir);
        let before = fs::read(&archive).unwrap();
        let (primary, paths) = locate(&archive).unwrap();
        let reads = Arc::default();
        let State::Fresh(job, out) =
            open(&primary, &paths, Output::Default, None, true, None, &reads).unwrap()
        else {
            panic!("a new archive opens fresh");
        };
        let journal = begin(&job, &paths, out, true, None).unwrap();
        assert!(journal.keep);
        let len = job.storage.original_len();
        assert!(job.storage.set_len(len / 2).is_err());
        assert!(job.storage.punch(0, len / 2).is_err());
        assert!(job.storage.write_at(0, b"PK").is_err());
        assert!(job.storage.cut_to(0).is_err());
        drop(job);
        assert_eq!(fs::read(&archive).unwrap(), before);

        // The journal says so, and a resumed job is protected as well.
        let (journal, tail) = Journal::load(&paths).unwrap();
        let job = Job::resume(&journal, tail, true, None, Default::default()).unwrap();
        assert!(job.storage.set_len(0).is_err());
        assert_eq!(job.units.len(), 8, "nothing is committed yet");
        drop(job);
        assert_eq!(fs::read(&archive).unwrap(), before);
        assert!(keeps_archive(&journal, false).unwrap());
        assert!(keeps_archive(&journal, true).unwrap());
        fs::remove_dir_all(&dir).unwrap();
    }
}