Skip to main content

hatchzip_core/
session.rs

1//! Opening an archive for extraction and working out whether it fits. Shared
2//! by the command line and the GUI, so the two never disagree.
3
4use std::fs;
5use std::path::{Path, PathBuf};
6use std::sync::Arc;
7
8use anyhow::{Context, Result, bail};
9
10use crate::archive::storage::{self, Reads, Storage};
11use crate::engine::Job;
12use crate::fsutil;
13use crate::journal::{Journal, Paths, Plan};
14
15/// The first volume of the archive and where its journal lives. Paths are
16/// made absolute so a resume works from any directory.
17pub fn locate(archive: &Path) -> Result<(PathBuf, Paths)> {
18    let primary = std::path::absolute(storage::first_volume(archive))
19        .with_context(|| format!("resolving {}", archive.display()))?;
20    let paths = Paths::for_archive(&primary);
21    Ok((primary, paths))
22}
23
24pub enum State {
25    /// Nothing touched yet. Nothing changes on disk until [`begin`] writes
26    /// the journal.
27    Fresh(Job, PathBuf),
28    Resume(Job, Journal),
29    /// The archive is gone but the run died before cleaning up.
30    Orphan(Journal),
31}
32
33/// `writable` is false for anything that only looks, so it works on
34/// read-only media and never takes the lock. For a fresh extraction the
35/// output folder may already hold other files, but no folder where the
36/// archive has a file or the other way round; files the archive would
37/// replace are listed by [`existing`]. `password` only matters for encrypted archives; see
38/// [`open_encrypted`] for the ask-and-retry loop front ends want. What
39/// opening reads is counted in `reads`, which a front end can show from
40/// another thread: a compressed tar is read in full here.
41pub fn open(
42    primary: &Path,
43    paths: &Paths,
44    output: Option<PathBuf>,
45    writable: bool,
46    password: Option<&str>,
47    reads: &Arc<Reads>,
48) -> Result<State> {
49    if paths.exists() {
50        let (mut journal, tail) = Journal::load(paths)?;
51        // Only a writable open deletes or writes anything in the folder.
52        if writable || output.is_some() {
53            check_output(&journal, primary, output.as_deref(), "extract")?;
54        }
55        if journal.restoring.is_some() {
56            if !writable {
57                bail!(
58                    "a restore of this archive was interrupted. Run restore again to complete \
59                     it, or run extract to resume the extraction"
60                );
61            }
62            crate::restore::recover(&mut journal, paths)?;
63        }
64        if !journal.parts[0].0.exists() {
65            if journal.keep {
66                // Only the person could have removed an archive this run
67                // promised to keep, and the rest of it is still to extract.
68                bail!(
69                    "{} was moved or deleted during an extraction that keeps it. Put it back \
70                     to resume, or delete {} to discard the progress",
71                    journal.parts[0].0.display(),
72                    paths.journal.display()
73                );
74            }
75            return Ok(State::Orphan(journal));
76        }
77        let job = Job::resume(&journal, tail, writable, password, reads.clone())?;
78        check_no_links_on_the_way(&job, &journal.output)?;
79        return Ok(State::Resume(job, journal));
80    }
81    let job = Job::open(primary, writable, password, reads.clone())?;
82    let output = match output {
83        Some(o) => std::path::absolute(o)?,
84        None => {
85            let output = default_output(primary);
86            refuse_linked_default(&output)?;
87            output
88        }
89    };
90    check_path_lengths(&job, &output)?;
91    if writable {
92        check_no_links_on_the_way(&job, &output)?;
93        check_collisions(&job, &output)?;
94    }
95    Ok(State::Fresh(job, output))
96}
97
98/// The journal lies next to the archive, where anyone who supplied the
99/// archive could have put one, so it is used only for an extraction this
100/// computer recorded starting into that folder (see [`crate::chosen`]), or
101/// when the person names the folder again (`given`). A resume deletes what
102/// it finds at the paths of the entries left, so a planted journal could
103/// otherwise have it delete and write files anywhere, and even in the
104/// default folder it would replace the person's own files there.
105/// `command` is the one to run again, with `-o`.
106pub fn check_output(
107    journal: &Journal,
108    primary: &Path,
109    given: Option<&Path>,
110    command: &str,
111) -> Result<()> {
112    let default = default_output(primary);
113    let in_default = fsutil::same_path(&default, &journal.output);
114    match given {
115        Some(o) => {
116            if !fsutil::same_path(&std::path::absolute(o)?, &journal.output) {
117                bail!(
118                    "this archive is already partially extracted to {}. Complete or restore that \
119                     extraction first",
120                    journal.output.display()
121                );
122            }
123        }
124        None if crate::chosen::chose(primary, &journal.output) => {
125            if in_default {
126                refuse_linked_default(&default)?;
127            }
128        }
129        // Releases before 0.1.6 did not record the default folder.
130        None if in_default => bail!(
131            "{} was partially extracted to {}, but this computer has no record of starting that \
132             extraction. If you started it, continue it by naming the folder again: hatchzip \
133             {command} \"{}\" -o \"{}\". Nothing was modified",
134            primary.display(),
135            journal.output.display(),
136            primary.display(),
137            journal.output.display()
138        ),
139        None => bail!(
140            "{} was partially extracted to {}, a folder not chosen on this computer. If you \
141             started that extraction, continue it by naming the folder again: hatchzip {command} \
142             \"{}\" -o \"{}\". Nothing was modified",
143            primary.display(),
144            journal.output.display(),
145            primary.display(),
146            journal.output.display()
147        ),
148    }
149    Ok(())
150}
151
152/// A link at the default output folder, next to the archive, would send the
153/// extraction wherever it points. A folder the person names is theirs to
154/// choose.
155fn refuse_linked_default(output: &Path) -> Result<()> {
156    if fs::symlink_metadata(output).is_ok_and(|m| m.is_symlink()) {
157        bail!(
158            "{} is a link, so files extracted there would land somewhere else. Remove the link, \
159             or choose the destination folder. Nothing was modified",
160            output.display()
161        );
162    }
163    Ok(())
164}
165
166/// A resume deletes and writes the files of the entries left, and its own
167/// links are only made once every entry is done. A link on the way to one of
168/// those files was put there by someone else, and following it would leave
169/// the output folder.
170pub(crate) fn check_no_links_on_the_way(job: &Job, out: &Path) -> Result<()> {
171    let mut checked = std::collections::HashSet::new();
172    for item in job.units.iter().flat_map(|u| &u.items) {
173        for parent in item
174            .path
175            .ancestors()
176            .skip(1)
177            .filter(|p| !p.as_os_str().is_empty())
178        {
179            if !checked.insert(parent.to_path_buf()) {
180                break;
181            }
182            if fs::symlink_metadata(out.join(parent)).is_ok_and(|m| m.is_symlink()) {
183                bail!(
184                    "{} is a link, and '{}' would be extracted through it. Nothing was modified",
185                    out.join(parent).display(),
186                    item.path.display()
187                );
188            }
189        }
190    }
191    Ok(())
192}
193
194/// A path the system can't create would only fail halfway through a run,
195/// after part of the archive is gone; macOS stops at 1024 bytes.
196fn check_path_lengths(job: &Job, out: &Path) -> Result<()> {
197    for item in job.units.iter().flat_map(|u| &u.items) {
198        if crate::platform::path_len(&out.join(&item.path)) > crate::platform::MAX_PATH_LEN {
199            bail!(
200                "'{}' cannot be created in {}: the full path would be longer than this system \
201                 allows. The archive was not modified. Extract to a folder with a shorter path",
202                item.path.display(),
203                out.display()
204            );
205        }
206    }
207    Ok(())
208}
209
210/// Opens an archive that may be encrypted. `ask` is called whenever a
211/// password is needed or the last one was wrong, and returns `None` to give
212/// up. Archives with a password are proven with [`Job::check_password`]
213/// before this returns, so nothing is deleted on a wrong guess. Returns the
214/// state and the password that worked.
215pub fn open_encrypted(
216    primary: &Path,
217    paths: &Paths,
218    output: Option<PathBuf>,
219    writable: bool,
220    password: Option<String>,
221    reads: &Arc<Reads>,
222    ask: impl FnMut(bool) -> Option<String>,
223) -> Result<(State, Option<String>)> {
224    open_encrypted_noting(
225        primary,
226        paths,
227        output,
228        writable,
229        password,
230        reads,
231        ask,
232        |_, _| {},
233    )
234}
235
236/// [`open_encrypted`], calling `slow` with a file and its size before a
237/// password check that decodes all of it (see [`Job::slow_password_check`]),
238/// so a front end can say it may take a while.
239#[allow(clippy::too_many_arguments)]
240pub fn open_encrypted_noting(
241    primary: &Path,
242    paths: &Paths,
243    output: Option<PathBuf>,
244    writable: bool,
245    mut password: Option<String>,
246    reads: &Arc<Reads>,
247    mut ask: impl FnMut(bool) -> Option<String>,
248    mut slow: impl FnMut(&Path, u64),
249) -> Result<(State, Option<String>)> {
250    let mut wrong = false;
251    loop {
252        let attempt = open(
253            primary,
254            paths,
255            output.clone(),
256            writable,
257            password.as_deref(),
258            reads,
259        );
260        let failure = match attempt {
261            Ok(State::Orphan(j)) => return Ok((State::Orphan(j), password)),
262            Ok(state) => {
263                let job = match &state {
264                    State::Fresh(job, _) | State::Resume(job, _) => job,
265                    State::Orphan(_) => unreachable!(),
266                };
267                if !job.encrypted() {
268                    return Ok((state, password));
269                }
270                if password.is_some()
271                    && let Some((file, size)) = job.slow_password_check()
272                {
273                    slow(file, size);
274                }
275                match job.check_password() {
276                    Ok(()) => return Ok((state, password)),
277                    Err(e) => e,
278                }
279            }
280            Err(e) => e,
281        };
282        if failure.is::<crate::archive::WrongPassword>() {
283            wrong = true;
284        } else if !failure.is::<crate::archive::PasswordNeeded>() {
285            return Err(failure);
286        }
287        // Drop the open archive before asking, so nothing stays locked while
288        // a person types.
289        match ask(wrong) {
290            Some(p) => password = Some(p),
291            None => return Err(failure),
292        }
293    }
294}
295
296/// Refuses what no extraction into `out` can get past: a folder where the
297/// archive has a file, which is never deleted or replaced, a file where it
298/// needs a folder, which would only fail halfway, and anything at the name a
299/// file is first written under. That last one would be in the way of the
300/// file, or would be deleted as the run's own by a resume.
301fn check_collisions(job: &Job, out: &Path) -> Result<()> {
302    if !out.exists() {
303        return Ok(());
304    }
305    let mut checked = std::collections::HashSet::new();
306    for item in job.units.iter().flat_map(|u| &u.items) {
307        let dest = out.join(&item.path);
308        let part = crate::engine::part_path(&dest);
309        if item.kind == crate::archive::Kind::File && fs::symlink_metadata(&part).is_ok() {
310            bail!(
311                "{} already exists. HatchZip first writes '{}' under that name and does not \
312                 replace a file it did not create. Move it or choose another destination. Nothing \
313                 was modified",
314                part.display(),
315                item.path.display()
316            );
317        }
318        if let Ok(meta) = fs::symlink_metadata(&dest) {
319            let dir = item.kind == crate::archive::Kind::Dir;
320            if dir && !meta.is_dir() {
321                bail!(
322                    "{} is a file, but the archive requires a folder at that location",
323                    dest.display()
324                );
325            }
326            if !dir && meta.is_dir() {
327                bail!(
328                    "{} is a folder, but the archive has a file at that location. Move the \
329                     folder or choose another destination",
330                    dest.display()
331                );
332            }
333        }
334        for parent in item
335            .path
336            .ancestors()
337            .skip(1)
338            .filter(|p| !p.as_os_str().is_empty())
339        {
340            if !checked.insert(parent.to_path_buf()) {
341                break;
342            }
343            if let Ok(meta) = fs::symlink_metadata(out.join(parent))
344                && !meta.is_dir()
345            {
346                bail!(
347                    "{} is a file, but the archive requires a folder at that location",
348                    out.join(parent).display()
349                );
350            }
351        }
352    }
353    Ok(())
354}
355
356/// The files and links already in `out` at paths the archive extracts to,
357/// relative to `out`. A fresh extraction may only replace them when asked
358/// to; see [`begin`]. When there are any, what would keep them from being
359/// replaced is refused here, before a front end asks.
360pub fn existing(job: &Job, out: &Path) -> Result<Vec<PathBuf>> {
361    let found = crate::replace::found(job, out);
362    if !found.is_empty() {
363        crate::replace::check(job, out, &found)?;
364    }
365    Ok(found)
366}
367
368/// Whether everything in the archive sits under one name at its top, one
369/// folder or a single file. "Extract here" puts such an archive next to
370/// itself; anything else would scatter loose files, so it gets a folder.
371pub fn single_root(job: &Job) -> bool {
372    let mut roots = job
373        .units
374        .iter()
375        .flat_map(|u| &u.items)
376        .filter_map(|i| i.path.components().next());
377    let Some(first) = roots.next() else {
378        return false;
379    };
380    roots.all(|r| r == first)
381}
382
383/// Moves a fresh extraction opened writable by [`open`] to another folder,
384/// checking it as [`open`] checks the one it was given.
385pub fn retarget(job: &Job, out: &Path) -> Result<PathBuf> {
386    let out = std::path::absolute(out)?;
387    check_path_lengths(job, &out)?;
388    check_no_links_on_the_way(job, &out)?;
389    check_collisions(job, &out)?;
390    Ok(out)
391}
392
393/// `game.zip`, `game.7z.001`, `game.tar.gz` and `game.part1.rar` all extract
394/// into `game`, next
395/// to them.
396pub fn default_output(primary: &Path) -> PathBuf {
397    let file_name = primary
398        .file_name()
399        .unwrap_or_default()
400        .to_string_lossy()
401        .into_owned();
402    let mut name = file_name.clone();
403    if let Some((stem, digits)) = name.rsplit_once('.')
404        && digits.len() >= 3
405        && digits.bytes().all(|b| b.is_ascii_digit())
406    {
407        name = stem.to_string();
408    }
409    let lower = name.to_ascii_lowercase();
410    // `game.part2.rar` and `game.part02.rar` are volumes of `game`.
411    if let Some(stem) = lower.strip_suffix(".rar")
412        && let Some((_, digits)) = stem.rsplit_once(".part")
413        && !digits.is_empty()
414        && digits.bytes().all(|b| b.is_ascii_digit())
415    {
416        name.truncate(stem.len() - digits.len() - ".part".len());
417        return primary.with_file_name(name);
418    }
419    for ext in [".zip", ".7z", ".tar", ".tar.gz", ".tgz", ".rar", ".exe"] {
420        if lower.ends_with(ext) && name.len() > ext.len() {
421            name.truncate(name.len() - ext.len());
422            break;
423        }
424    }
425    if name == file_name {
426        name.push_str("-extracted");
427    }
428    primary.with_file_name(name)
429}
430
431/// `game.zip`, or `game.7z.001 (+4 more parts)` for a split archive.
432pub fn display_name(job: &Job) -> String {
433    let parts = job.storage.parts();
434    let first = parts[0]
435        .path
436        .file_name()
437        .unwrap_or_default()
438        .to_string_lossy()
439        .into_owned();
440    match parts.len() {
441        1 => first,
442        n => format!("{first} (+{} more parts)", n - 1),
443    }
444}
445
446/// Whether the extraction of a half-extracted archive keeps it, given what
447/// the person asked for now. The journal decides: an extraction that keeps
448/// the archive goes on keeping it, and one that has already removed part of
449/// it can't start keeping it.
450pub fn keeps_archive(journal: &Journal, asked: bool) -> Result<bool> {
451    if asked && !journal.keep {
452        bail!(
453            "this archive is partially extracted in place, so part of it is already removed and \
454             it cannot be kept. Resume without --keep-archive, or run restore first"
455        );
456    }
457    Ok(journal.keep)
458}
459
460/// Whether an extraction fits, in the numbers a person needs to decide.
461pub struct SpacePlan {
462    /// Usable free space, counting files a crashed run left that will be
463    /// deleted before continuing.
464    pub free: u64,
465    /// Free space the extraction needs at its busiest moment, in the mode
466    /// asked for.
467    pub needed: u64,
468    pub keep_free: u64,
469    pub fits: bool,
470    /// Free space once finished, if it fits.
471    pub free_after: u64,
472    /// The plan is for an extraction that keeps the archive.
473    pub keep_archive: bool,
474    /// What an extraction that keeps the archive needs free: every
475    /// extracted file, as for any other extractor, plus the saved index.
476    pub normal_needs: u64,
477    /// What extracting in place needs free. Equal to `needed` unless the
478    /// archive is kept.
479    pub in_place_needs: u64,
480    /// Nothing is extracted yet, so either mode can still be chosen. A
481    /// half-extracted archive continues in the mode it started in.
482    pub either: bool,
483    /// False when the output is on another disk, so freeing the archive
484    /// doesn't help it.
485    pub reclaims: bool,
486    /// The shortfall comes from one solid block that can only be freed once
487    /// all of it is out.
488    pub solid_block_bound: bool,
489    /// The archive is one compressed stream (a `.tar.gz`) on a filesystem
490    /// that can't free space inside a file, such as FAT32 or exFAT, so it
491    /// stays whole until the extraction completes: `needed` is room for
492    /// every extracted file next to it.
493    pub archive_kept_whole: bool,
494}
495
496impl SpacePlan {
497    /// Whether an extraction that keeps the archive would fit too.
498    pub fn normal_fits(&self) -> bool {
499        self.free >= self.normal_needs + self.keep_free
500    }
501
502    pub fn in_place_fits(&self) -> bool {
503        self.free >= self.in_place_needs + self.keep_free
504    }
505}
506
507/// The space plan for extracting `job` into `out`, keeping the archive or
508/// not. For a half-extracted archive, `keep_archive` must be what its
509/// journal says; see [`keeps_archive`].
510pub fn plan(
511    job: &Job,
512    out: &Path,
513    resuming: bool,
514    keep_free: u64,
515    keep_archive: bool,
516) -> Result<SpacePlan> {
517    let reclaims = fsutil::same_filesystem(job.storage.primary(), out);
518    let stale: u64 =
519        job.uncommitted(out).iter().map(|(_, n)| n).sum::<u64>() + job.past_resume_point(out);
520    let free = fsutil::available_space(out)? + stale;
521    // Keeping the archive frees nothing, as if the output were on another
522    // disk: the replay counts every file and gives nothing back.
523    let (normal_needs, normal_end) = job.space_needed(!resuming, false);
524    let (in_place_needs, in_place_end) = if keep_archive && resuming {
525        (normal_needs, normal_end)
526    } else {
527        job.space_needed(!resuming, reclaims)
528    };
529    // The saved index is deleted at the end, when the archive is kept too.
530    let tail = job.storage.original_len().saturating_sub(job.tail_start) as i128;
531    let normal_end = normal_end - if reclaims { tail } else { 0 };
532    let (needed, end) = if keep_archive {
533        (normal_needs, normal_end)
534    } else {
535        (in_place_needs, in_place_end)
536    };
537    let fits = free >= needed + keep_free;
538    Ok(SpacePlan {
539        free,
540        needed,
541        keep_free,
542        fits,
543        free_after: (free as i128 - end).max(0) as u64,
544        keep_archive,
545        normal_needs,
546        in_place_needs,
547        either: !resuming,
548        reclaims,
549        solid_block_bound: !fits
550            && !keep_archive
551            && !job.is_stream()
552            && job
553                .units
554                .iter()
555                .any(|u| u.items.len() > 1 && u.size() > free),
556        archive_kept_whole: !keep_archive && job.kept_whole(reclaims),
557    })
558}
559
560/// Commits to a fresh extraction: saves the archive's tail and writes the
561/// journal. From here on the archive may be truncated, unless `keep_archive`
562/// is set, in which case nothing ever changes it. Files in the way (see
563/// [`existing`]) are refused unless `replace` is given; then the run moves
564/// them aside before it extracts anything, and once it is complete deletes
565/// them or puts back the ones the choices keep.
566pub fn begin(
567    job: &Job,
568    paths: &Paths,
569    output: PathBuf,
570    keep_archive: bool,
571    replace: Option<&crate::replace::Choices>,
572) -> Result<Journal> {
573    // Front ends ask earlier; the folder may have changed since.
574    let found = existing(job, &output)?;
575    if let Some(first) = found.first()
576        && replace.is_none()
577    {
578        let what = match found.len() {
579            1 => format!("{} already exists", output.join(first).display()),
580            n => format!(
581                "{} and {} other {} already exist",
582                output.join(first).display(),
583                n - 1,
584                if n == 2 { "file" } else { "files" }
585            ),
586        };
587        bail!(
588            "{what}. Existing files are only replaced when that is requested. Move the files or \
589             choose another destination. Nothing was modified"
590        );
591    }
592    if keep_archive {
593        job.storage.protect();
594    } else if let Some(why) = job.in_place_refusal() {
595        // Front ends say this earlier; this is the last line.
596        bail!("{why}. It can be extracted while keeping the archive");
597    }
598    crate::sfv::check_volumes(&job.storage)?;
599    // The default folder too: a resume trusts the journal only when this
600    // computer recorded starting the extraction (see [`check_output`]).
601    crate::chosen::remember(&paths.archive, &output);
602    // A choice for a file that has gone since it was made has nothing to
603    // keep.
604    let only_found = |paths: &[PathBuf]| -> Vec<PathBuf> {
605        paths
606            .iter()
607            .filter(|p| found.contains(p))
608            .cloned()
609            .collect()
610    };
611    let replace = replace
612        .filter(|_| !found.is_empty())
613        .map(|c| crate::journal::Replace {
614            moved: false,
615            keep: only_found(&c.keep),
616            both: only_found(&c.both),
617        });
618    let plan = Plan {
619        format: job.format_name,
620        tail_start: job.tail_start,
621        output,
622        total_size: job.remaining_size(),
623        keep: keep_archive,
624        replace,
625    };
626    Journal::create(paths, &job.storage, plan)
627}
628
629/// Checks the archive's volumes against an `.sfv` file next to it, if present.
630pub fn check_sfv(storage: &Storage, cancelled: &dyn Fn() -> bool) -> Result<Option<PathBuf>> {
631    crate::sfv::check_volumes_cancellable(storage, cancelled)
632}
633
634/// Before continuing a crashed run, deletes what it wrote for batches it
635/// never committed.
636pub fn clear_uncommitted(job: &Job, out: &Path) -> Result<()> {
637    check_no_links_on_the_way(job, out)?;
638    for (p, _) in job.uncommitted(out) {
639        fs::remove_file(&p).with_context(|| format!("removing stale {}", p.display()))?;
640    }
641    Ok(())
642}
643
644#[cfg(test)]
645mod tests {
646    use std::io::Write;
647
648    use ::zip::write::{SimpleFileOptions, ZipWriter};
649
650    use super::*;
651
652    #[test]
653    fn output_folder_drops_the_volume_and_format_suffixes() {
654        let name = |n: &str| default_output(Path::new(n));
655        assert_eq!(name("game.zip"), Path::new("game"));
656        assert_eq!(name("game.7z.001"), Path::new("game"));
657        assert_eq!(name("game.part1.rar"), Path::new("game"));
658        assert_eq!(name("game.PART02.RAR"), Path::new("game"));
659        assert_eq!(name("game.rar"), Path::new("game"));
660        assert_eq!(name("game.part.rar"), Path::new("game.part"));
661        assert_eq!(name("notes.txt"), Path::new("notes.txt-extracted"));
662    }
663
664    /// Eight stored entries, so extracting in place frees the archive entry
665    /// by entry and needs far less than keeping it.
666    fn sample_zip(dir: &Path) -> PathBuf {
667        let path = dir.join("plan.zip");
668        let mut w = ZipWriter::new(fs::File::create(&path).unwrap());
669        let opts =
670            SimpleFileOptions::default().compression_method(::zip::CompressionMethod::Stored);
671        for i in 0..8u8 {
672            w.start_file(format!("data/{i}.bin"), opts).unwrap();
673            w.write_all(&vec![i; 200_000 + usize::from(i)]).unwrap();
674        }
675        w.finish().unwrap();
676        path
677    }
678
679    #[test]
680    fn keeping_the_archive_plans_for_every_file() {
681        let dir = std::env::temp_dir().join(format!("hatchzip-plan-{}", std::process::id()));
682        fs::create_dir_all(&dir).unwrap();
683        let archive = sample_zip(&dir);
684        let out = dir.join("out");
685        let job = Job::open(&archive, false, None, Default::default()).unwrap();
686        let files: u64 = job
687            .units
688            .iter()
689            .flat_map(|u| &u.items)
690            .map(|i| i.size.next_multiple_of(4096))
691            .sum();
692        let tail = job.storage.original_len() - job.tail_start;
693
694        let keep = plan(&job, &out, false, 0, true).unwrap();
695        assert!(keep.keep_archive && keep.either);
696        // Every file, plus the copy of the index a resume would need.
697        assert_eq!(keep.needed, files + tail);
698        assert_eq!(keep.normal_needs, keep.needed);
699        assert!(!keep.solid_block_bound && !keep.archive_kept_whole);
700        // Nothing of the archive comes back; the saved index does.
701        assert_eq!(keep.free.saturating_sub(keep.free_after), files);
702
703        let in_place = plan(&job, &out, false, 0, false).unwrap();
704        assert!(!in_place.keep_archive);
705        assert_eq!(in_place.normal_needs, keep.needed);
706        assert_eq!(in_place.in_place_needs, in_place.needed);
707        assert_eq!(keep.in_place_needs, in_place.needed);
708        assert!(
709            in_place.needed < keep.needed / 2,
710            "in place {} vs kept {}",
711            in_place.needed,
712            keep.needed
713        );
714        drop(job);
715        fs::remove_dir_all(&dir).unwrap();
716    }
717
718    /// Once an extraction that keeps the archive has begun, nothing can
719    /// change it, whatever the caller does.
720    #[test]
721    fn a_kept_archive_refuses_every_change() {
722        let dir = std::env::temp_dir().join(format!("hatchzip-protect-{}", std::process::id()));
723        fs::create_dir_all(&dir).unwrap();
724        let archive = sample_zip(&dir);
725        let before = fs::read(&archive).unwrap();
726        let (primary, paths) = locate(&archive).unwrap();
727        let reads = Arc::default();
728        let State::Fresh(job, out) = open(&primary, &paths, None, true, None, &reads).unwrap()
729        else {
730            panic!("a new archive opens fresh");
731        };
732        let journal = begin(&job, &paths, out, true, None).unwrap();
733        assert!(journal.keep);
734        let len = job.storage.original_len();
735        assert!(job.storage.set_len(len / 2).is_err());
736        assert!(job.storage.punch(0, len / 2).is_err());
737        assert!(job.storage.write_at(0, b"PK").is_err());
738        assert!(job.storage.cut_to(0).is_err());
739        drop(job);
740        assert_eq!(fs::read(&archive).unwrap(), before);
741
742        // The journal says so, and a resumed job is protected as well.
743        let (journal, tail) = Journal::load(&paths).unwrap();
744        let job = Job::resume(&journal, tail, true, None, Default::default()).unwrap();
745        assert!(job.storage.set_len(0).is_err());
746        assert_eq!(job.units.len(), 8, "nothing is committed yet");
747        drop(job);
748        assert_eq!(fs::read(&archive).unwrap(), before);
749        assert!(keeps_archive(&journal, false).unwrap());
750        assert!(keeps_archive(&journal, true).unwrap());
751        fs::remove_dir_all(&dir).unwrap();
752    }
753}