1use 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
15pub 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 Fresh(Job, PathBuf),
28 Resume(Job, Journal),
29 Orphan(Journal),
31}
32
33pub(crate) fn check_recorded_case(journal: &Journal) -> Result<()> {
36 crate::engine::check_case_record(
37 &journal.output,
38 &journal.case_folders,
39 journal.case_beyond_ascii,
40 )
41}
42
43pub fn case_sensitive(dir: &Path) -> bool {
46 crate::platform::case_sensitive(dir)
47}
48
49pub fn open(
58 primary: &Path,
59 paths: &Paths,
60 output: Option<PathBuf>,
61 writable: bool,
62 password: Option<&str>,
63 reads: &Arc<Reads>,
64) -> Result<State> {
65 if paths.exists() {
66 let (mut journal, tail) = Journal::load(paths)?;
67 if writable && !journal.done && journal.parts[0].0.exists() {
71 journal.check_folders(paths)?;
72 }
73 if writable || output.is_some() {
75 check_output(&journal, primary, output.as_deref(), "extract")?;
76 }
77 if writable {
78 check_recorded_case(&journal)?;
79 }
80 if journal.restoring.is_some() {
81 if !writable {
82 bail!(
83 "a restore of this archive was interrupted. Run restore again to complete \
84 it, or run extract to resume the extraction"
85 );
86 }
87 crate::restore::recover(&mut journal, paths)?;
88 }
89 if !journal.parts[0].0.exists() {
90 if journal.keep {
91 bail!(
94 "{} was moved or deleted during an extraction that keeps it. Put it back \
95 to resume, or delete {} to discard the progress",
96 journal.parts[0].0.display(),
97 paths.journal.display()
98 );
99 }
100 return Ok(State::Orphan(journal));
101 }
102 if journal.done {
106 return Ok(State::Orphan(journal));
107 }
108 let job = Job::resume(&journal, tail, writable, password, reads.clone())?;
109 check_no_links_on_the_way(&job, &journal.output)?;
110 return Ok(State::Resume(job, journal));
111 }
112 let job = Job::open(primary, writable, password, reads.clone())?;
113 let output = match output {
114 Some(o) => std::path::absolute(o)?,
115 None => {
116 let output = default_output(primary);
117 refuse_linked_default(&output)?;
118 output
119 }
120 };
121 check_path_lengths(&job, &output)?;
122 if writable {
123 check_no_links_on_the_way(&job, &output)?;
124 check_collisions(&job, &output)?;
125 job.check_case(&output)?;
126 }
127 Ok(State::Fresh(job, output))
128}
129
130pub fn check_output(
139 journal: &Journal,
140 primary: &Path,
141 given: Option<&Path>,
142 command: &str,
143) -> Result<()> {
144 let default = default_output(primary);
145 let in_default = fsutil::same_path(&default, &journal.output);
146 match given {
147 Some(o) => {
148 if !fsutil::same_path(&std::path::absolute(o)?, &journal.output) {
149 bail!(
150 "this archive is already partially extracted to {}. Complete or restore that \
151 extraction first",
152 journal.output.display()
153 );
154 }
155 }
156 None if crate::chosen::chose(primary, &journal.output) => {
157 if in_default {
158 refuse_linked_default(&default)?;
159 }
160 }
161 None if in_default => bail!(
163 "{} was partially extracted to {}, but this computer has no record of starting that \
164 extraction. If you started it, continue it by naming the folder again: hatchzip \
165 {command} \"{}\" -o \"{}\". Nothing was modified",
166 primary.display(),
167 journal.output.display(),
168 primary.display(),
169 journal.output.display()
170 ),
171 None => bail!(
172 "{} was partially extracted to {}, a folder not chosen on this computer. If you \
173 started that extraction, continue it by naming the folder again: hatchzip {command} \
174 \"{}\" -o \"{}\". Nothing was modified",
175 primary.display(),
176 journal.output.display(),
177 primary.display(),
178 journal.output.display()
179 ),
180 }
181 Ok(())
182}
183
184fn refuse_linked_default(output: &Path) -> Result<()> {
188 if fs::symlink_metadata(output).is_ok_and(|m| m.is_symlink()) {
189 bail!(
190 "{} is a link, so files extracted there would land somewhere else. Remove the link, \
191 or choose the destination folder. Nothing was modified",
192 output.display()
193 );
194 }
195 Ok(())
196}
197
198pub(crate) fn check_no_links_on_the_way(job: &Job, out: &Path) -> Result<()> {
203 let mut checked = std::collections::HashSet::new();
204 for item in job.units.iter().flat_map(|u| &u.items) {
205 for parent in item
206 .path
207 .ancestors()
208 .skip(1)
209 .filter(|p| !p.as_os_str().is_empty())
210 {
211 if !checked.insert(parent.to_path_buf()) {
212 break;
213 }
214 if fs::symlink_metadata(out.join(parent)).is_ok_and(|m| m.is_symlink()) {
215 bail!(
216 "{} is a link, and '{}' would be extracted through it. Nothing was modified",
217 out.join(parent).display(),
218 item.path.display()
219 );
220 }
221 }
222 }
223 Ok(())
224}
225
226fn check_path_lengths(job: &Job, out: &Path) -> Result<()> {
229 for item in job.units.iter().flat_map(|u| &u.items) {
230 if crate::platform::path_len(&out.join(&item.path)) > crate::platform::MAX_PATH_LEN {
231 bail!(
232 "'{}' cannot be created in {}: the full path would be longer than this system \
233 allows. The archive was not modified. Extract to a folder with a shorter path",
234 item.path.display(),
235 out.display()
236 );
237 }
238 }
239 Ok(())
240}
241
242pub fn open_encrypted(
248 primary: &Path,
249 paths: &Paths,
250 output: Option<PathBuf>,
251 writable: bool,
252 password: Option<String>,
253 reads: &Arc<Reads>,
254 ask: impl FnMut(bool) -> Option<String>,
255) -> Result<(State, Option<String>)> {
256 open_encrypted_noting(
257 primary,
258 paths,
259 output,
260 writable,
261 password,
262 reads,
263 ask,
264 |_, _| {},
265 )
266}
267
268#[allow(clippy::too_many_arguments)]
272pub fn open_encrypted_noting(
273 primary: &Path,
274 paths: &Paths,
275 output: Option<PathBuf>,
276 writable: bool,
277 mut password: Option<String>,
278 reads: &Arc<Reads>,
279 mut ask: impl FnMut(bool) -> Option<String>,
280 mut slow: impl FnMut(&Path, u64),
281) -> Result<(State, Option<String>)> {
282 let mut wrong = false;
283 loop {
284 let attempt = open(
285 primary,
286 paths,
287 output.clone(),
288 writable,
289 password.as_deref(),
290 reads,
291 );
292 let failure = match attempt {
293 Ok(State::Orphan(j)) => return Ok((State::Orphan(j), password)),
294 Ok(state) => {
295 let job = match &state {
296 State::Fresh(job, _) | State::Resume(job, _) => job,
297 State::Orphan(_) => unreachable!(),
298 };
299 if !job.encrypted() {
300 return Ok((state, password));
301 }
302 if password.is_some()
303 && let Some((file, size)) = job.slow_password_check()
304 {
305 slow(file, size);
306 }
307 match job.check_password() {
308 Ok(()) => return Ok((state, password)),
309 Err(e) => e,
310 }
311 }
312 Err(e) => e,
313 };
314 if failure.is::<crate::archive::WrongPassword>() {
315 wrong = true;
316 } else if !failure.is::<crate::archive::PasswordNeeded>() {
317 return Err(failure);
318 }
319 match ask(wrong) {
322 Some(p) => password = Some(p),
323 None => return Err(failure),
324 }
325 }
326}
327
328fn check_collisions(job: &Job, out: &Path) -> Result<()> {
334 if !out.exists() {
335 return Ok(());
336 }
337 check_own_files(job, out)?;
338 let mut checked = std::collections::HashSet::new();
339 for item in job.units.iter().flat_map(|u| &u.items) {
340 let dest = out.join(&item.path);
341 let part = crate::engine::part_path(&dest);
342 if item.kind == crate::archive::Kind::File && fs::symlink_metadata(&part).is_ok() {
343 bail!(
344 "{} already exists. HatchZip first writes '{}' under that name and does not \
345 replace a file it did not create. Move it or choose another destination. Nothing \
346 was modified",
347 part.display(),
348 item.path.display()
349 );
350 }
351 if let Ok(meta) = fs::symlink_metadata(&dest) {
352 let dir = item.kind == crate::archive::Kind::Dir;
353 if dir && !meta.is_dir() {
354 bail!(
355 "{} is a file, but the archive requires a folder at that location",
356 dest.display()
357 );
358 }
359 if !dir && meta.is_dir() {
360 bail!(
361 "{} is a folder, but the archive has a file at that location. Move the \
362 folder or choose another destination",
363 dest.display()
364 );
365 }
366 }
367 for parent in item
368 .path
369 .ancestors()
370 .skip(1)
371 .filter(|p| !p.as_os_str().is_empty())
372 {
373 if !checked.insert(parent.to_path_buf()) {
374 break;
375 }
376 if let Ok(meta) = fs::symlink_metadata(out.join(parent))
377 && !meta.is_dir()
378 {
379 bail!(
380 "{} is a file, but the archive requires a folder at that location",
381 out.join(parent).display()
382 );
383 }
384 }
385 }
386 Ok(())
387}
388
389fn check_own_files(job: &Job, out: &Path) -> Result<()> {
397 let text = |p: &Path| p.to_string_lossy().to_lowercase();
398 let folder = |p: &Path| {
399 let dir = p.parent().filter(|d| !d.as_os_str().is_empty());
400 fs::canonicalize(dir.unwrap_or(Path::new(".")))
401 .ok()
402 .map(|d| text(&d))
403 };
404 let lower = |p: &Path| p.file_name().map(|n| text(Path::new(n)));
405 let Ok(out) = fs::canonicalize(out) else {
406 return Ok(());
407 };
408 let primary = job.storage.primary();
409 let own_folder = folder(primary);
410 let side = lower(primary).map(|n| format!("{n}.hatchzip"));
411 let volumes: Vec<_> = job
412 .storage
413 .parts()
414 .iter()
415 .map(|p| (folder(&p.path), lower(&p.path)))
416 .collect();
417 for item in job.units.iter().flat_map(|u| &u.items) {
418 let dest = out.join(&item.path);
419 let dir = dest.parent().map(text);
420 let name = lower(&dest);
421 let (Some(dir), Some(name)) = (dir, name) else {
422 continue;
423 };
424 let volume = volumes
425 .iter()
426 .any(|(d, n)| d.as_ref() == Some(&dir) && n.as_ref() == Some(&name));
427 let progress = own_folder.as_ref() == Some(&dir)
428 && side.as_ref().is_some_and(|s| name.starts_with(s.as_str()));
429 if volume || progress {
430 bail!(
431 "'{}' would be extracted onto {}, one of the archive's own files. Choose another \
432 destination. Nothing was modified",
433 item.path.display(),
434 dest.display()
435 );
436 }
437 }
438 Ok(())
439}
440
441pub fn existing(job: &Job, out: &Path) -> Result<Vec<PathBuf>> {
446 let found = crate::replace::found(job, out);
447 if !found.is_empty() {
448 crate::replace::check(job, out, &found)?;
449 }
450 Ok(found)
451}
452
453pub fn single_root(job: &Job) -> bool {
457 let mut roots = job
458 .units
459 .iter()
460 .flat_map(|u| &u.items)
461 .filter_map(|i| i.path.components().next());
462 let Some(first) = roots.next() else {
463 return false;
464 };
465 roots.all(|r| r == first)
466}
467
468pub fn retarget(job: &Job, out: &Path) -> Result<PathBuf> {
471 let out = std::path::absolute(out)?;
472 check_path_lengths(job, &out)?;
473 check_no_links_on_the_way(job, &out)?;
474 check_collisions(job, &out)?;
475 job.check_case(&out)?;
476 Ok(out)
477}
478
479pub fn default_output(primary: &Path) -> PathBuf {
483 let file_name = primary
484 .file_name()
485 .unwrap_or_default()
486 .to_string_lossy()
487 .into_owned();
488 let mut name = file_name.clone();
489 if let Some((stem, digits)) = name.rsplit_once('.')
490 && digits.len() >= 3
491 && digits.bytes().all(|b| b.is_ascii_digit())
492 {
493 name = stem.to_string();
494 }
495 let lower = name.to_ascii_lowercase();
496 if let Some(stem) = lower.strip_suffix(".rar")
498 && let Some((_, digits)) = stem.rsplit_once(".part")
499 && !digits.is_empty()
500 && digits.bytes().all(|b| b.is_ascii_digit())
501 {
502 name.truncate(stem.len() - digits.len() - ".part".len());
503 } else {
504 for ext in [
505 ".zip", ".7z", ".tar.xz", ".txz", ".tar", ".tar.gz", ".tgz", ".rar", ".exe",
506 ] {
507 if lower.ends_with(ext) && name.len() > ext.len() {
508 name.truncate(name.len() - ext.len());
509 break;
510 }
511 }
512 }
513 if name == file_name || name.chars().all(|c| c == '.' || c == ' ') {
519 name = file_name;
520 name.push_str("-extracted");
521 }
522 primary.with_file_name(name)
523}
524
525pub fn display_name(job: &Job) -> String {
527 let parts = job.storage.parts();
528 let first = parts[0]
529 .path
530 .file_name()
531 .unwrap_or_default()
532 .to_string_lossy()
533 .into_owned();
534 match parts.len() {
535 1 => first,
536 n => format!("{first} (+{} more parts)", n - 1),
537 }
538}
539
540pub fn keeps_archive(journal: &Journal, asked: bool) -> Result<bool> {
545 if asked && !journal.keep {
546 bail!(
547 "this archive is partially extracted in place, so part of it is already removed and \
548 it cannot be kept. Resume without --keep-archive, or run restore first"
549 );
550 }
551 Ok(journal.keep)
552}
553
554pub struct SpacePlan {
556 pub free: u64,
559 pub needed: u64,
562 pub keep_free: u64,
563 pub fits: bool,
564 pub free_after: u64,
566 pub keep_archive: bool,
568 pub normal_needs: u64,
571 pub in_place_needs: u64,
574 pub either: bool,
577 pub reclaims: bool,
580 pub solid_block_bound: bool,
583 pub archive_kept_whole: bool,
588}
589
590impl SpacePlan {
591 pub fn normal_fits(&self) -> bool {
593 self.free >= self.normal_needs + self.keep_free
594 }
595
596 pub fn in_place_fits(&self) -> bool {
597 self.free >= self.in_place_needs + self.keep_free
598 }
599}
600
601pub fn plan(
605 job: &Job,
606 out: &Path,
607 resuming: bool,
608 keep_free: u64,
609 keep_archive: bool,
610) -> Result<SpacePlan> {
611 job.check_case(out)?;
612 let reclaims = fsutil::same_filesystem(job.storage.primary(), out);
613 let stale: u64 =
614 job.uncommitted(out).iter().map(|(_, n)| n).sum::<u64>() + job.past_resume_point(out);
615 let free = fsutil::available_space(out)? + stale;
616 let (normal_needs, normal_end) = job.space_needed(!resuming, false);
619 let (in_place_needs, in_place_end) = if keep_archive && resuming {
620 (normal_needs, normal_end)
621 } else {
622 job.space_needed(!resuming, reclaims)
623 };
624 let tail = job.storage.original_len().saturating_sub(job.tail_start) as i128;
626 let normal_end = normal_end - if reclaims { tail } else { 0 };
627 let (needed, end) = if keep_archive {
628 (normal_needs, normal_end)
629 } else {
630 (in_place_needs, in_place_end)
631 };
632 let fits = free >= needed + keep_free;
633 Ok(SpacePlan {
634 free,
635 needed,
636 keep_free,
637 fits,
638 free_after: (free as i128 - end).max(0) as u64,
639 keep_archive,
640 normal_needs,
641 in_place_needs,
642 either: !resuming,
643 reclaims,
644 solid_block_bound: !fits
645 && !keep_archive
646 && !job.is_stream()
647 && job
648 .units
649 .iter()
650 .any(|u| u.items.len() > 1 && u.size() > free),
651 archive_kept_whole: !keep_archive && job.kept_whole(reclaims),
652 })
653}
654
655pub fn begin(
662 job: &Job,
663 paths: &Paths,
664 output: PathBuf,
665 keep_archive: bool,
666 replace: Option<&crate::replace::Choices>,
667) -> Result<Journal> {
668 job.check_case(&output)?;
670 let found = existing(job, &output)?;
671 if let Some(first) = found.first()
672 && replace.is_none()
673 {
674 let what = match found.len() {
675 1 => format!("{} already exists", output.join(first).display()),
676 n => format!(
677 "{} and {} other {} already exist",
678 output.join(first).display(),
679 n - 1,
680 if n == 2 { "file" } else { "files" }
681 ),
682 };
683 bail!(
684 "{what}. Existing files are only replaced when that is requested. Move the files or \
685 choose another destination. Nothing was modified"
686 );
687 }
688 if keep_archive {
689 job.storage.protect();
690 } else if let Some(why) = job.in_place_refusal() {
691 bail!("{why}. It can be extracted while keeping the archive");
693 }
694 crate::sfv::check_volumes(&job.storage)?;
695 crate::chosen::remember(&paths.archive, &output);
698 let only_found = |paths: &[PathBuf]| -> Vec<PathBuf> {
701 paths
702 .iter()
703 .filter(|p| found.contains(p))
704 .cloned()
705 .collect()
706 };
707 let replace = replace
708 .filter(|_| !found.is_empty())
709 .map(|c| crate::journal::Replace {
710 moved: false,
711 keep: only_found(&c.keep),
712 both: only_found(&c.both),
713 });
714 let folders = crate::folders::of(&job.units, &output);
715 let plan = Plan {
716 format: job.format_name,
717 tail_start: job.tail_start,
718 output,
719 total_size: job.remaining_size(),
720 keep: keep_archive,
721 replace,
722 case_folders: job.case_folders(),
723 case_beyond_ascii: job.case_beyond_ascii(),
724 folders,
725 };
726 Journal::create(paths, &job.storage, plan)
727}
728
729pub fn check_sfv(storage: &Storage, cancelled: &dyn Fn() -> bool) -> Result<Option<PathBuf>> {
731 crate::sfv::check_volumes_cancellable(storage, cancelled)
732}
733
734pub fn clear_uncommitted(job: &Job, out: &Path) -> Result<()> {
737 check_no_links_on_the_way(job, out)?;
738 let found = job.uncommitted(out);
739 let mut listed = std::collections::HashMap::new();
740 for (p, _) in &found {
741 check_spelling(out, p, &mut listed)?;
742 }
743 for (p, _) in found {
744 fs::remove_file(&p).with_context(|| format!("removing stale {}", p.display()))?;
745 }
746 Ok(())
747}
748
749fn check_spelling(
756 out: &Path,
757 path: &Path,
758 listed: &mut std::collections::HashMap<PathBuf, std::collections::HashSet<String>>,
759) -> Result<()> {
760 use unicode_normalization::UnicodeNormalization;
761 let spelling = |n: &std::ffi::OsStr| n.to_string_lossy().nfd().collect::<String>();
762 let Ok(rel) = path.strip_prefix(out) else {
763 return Ok(());
764 };
765 let mut dir = out.to_path_buf();
766 for name in rel.iter() {
767 let names = match listed.entry(dir.clone()) {
768 std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
769 std::collections::hash_map::Entry::Vacant(e) => e.insert(
770 fs::read_dir(&dir)
771 .with_context(|| format!("listing {}", dir.display()))?
772 .map(|e| e.map(|e| spelling(&e.file_name())))
773 .collect::<std::io::Result<_>>()
774 .with_context(|| format!("listing {}", dir.display()))?,
775 ),
776 };
777 if !names.contains(&spelling(name)) {
778 bail!(
779 "{} is spelled differently on disk than in the archive, so it was not made by \
780 this extraction and is left alone. Move it out of the way, then run the command \
781 again",
782 dir.join(name).display()
783 );
784 }
785 dir.push(name);
786 }
787 Ok(())
788}
789
790#[cfg(test)]
791mod tests {
792 use std::io::Write;
793
794 use ::zip::write::{SimpleFileOptions, ZipWriter};
795
796 use super::*;
797
798 #[test]
801 fn a_resume_leaves_names_spelled_differently_alone() {
802 let dir = tempfile::tempdir().unwrap();
803 let out = dir.path();
804 fs::create_dir(out.join("Src")).unwrap();
805 fs::write(out.join("Src/Makefile"), b"theirs").unwrap();
806 fs::write(out.join("Src/caf\u{e9}.txt"), b"ours").unwrap();
807 let mut listed = std::collections::HashMap::new();
808 assert!(check_spelling(out, &out.join("Src/makefile"), &mut listed).is_err());
809 assert!(check_spelling(out, &out.join("src/Makefile"), &mut listed).is_err());
810 assert!(check_spelling(out, &out.join("Src/Makefile"), &mut listed).is_ok());
811 assert!(check_spelling(out, &out.join("Src/cafe\u{301}.txt"), &mut listed).is_ok());
813 }
814
815 #[test]
816 fn output_folder_drops_the_volume_and_format_suffixes() {
817 let name = |n: &str| default_output(Path::new(n));
818 assert_eq!(name("game.zip"), Path::new("game"));
819 assert_eq!(name("game.7z.001"), Path::new("game"));
820 assert_eq!(name("game.part1.rar"), Path::new("game"));
821 assert_eq!(name("game.PART02.RAR"), Path::new("game"));
822 assert_eq!(name("game.rar"), Path::new("game"));
823 assert_eq!(name("game.tar.xz"), Path::new("game"));
824 assert_eq!(name("game.txz"), Path::new("game"));
825 assert_eq!(name("game.part.rar"), Path::new("game.part"));
826 assert_eq!(name("notes.txt"), Path::new("notes.txt-extracted"));
827 }
828
829 #[test]
832 fn output_folder_is_never_the_folder_above_or_the_archives_own() {
833 let name = |n: &str| default_output(&Path::new("dl").join(n));
834 for n in [
835 "...zip",
836 "..zip",
837 ".zip",
838 ". .zip",
839 "...tar.gz",
840 "...7z.001",
841 "...part1.rar",
842 "..part2.rar",
843 ] {
844 assert_eq!(
845 name(n),
846 Path::new("dl").join(format!("{n}-extracted")),
847 "{n}"
848 );
849 }
850 assert_eq!(name("...game.zip"), Path::new("dl/...game"));
851 }
852
853 fn sample_zip(dir: &Path) -> PathBuf {
856 let path = dir.join("plan.zip");
857 let mut w = ZipWriter::new(fs::File::create(&path).unwrap());
858 let opts =
859 SimpleFileOptions::default().compression_method(::zip::CompressionMethod::Stored);
860 for i in 0..8u8 {
861 w.start_file(format!("data/{i}.bin"), opts).unwrap();
862 w.write_all(&vec![i; 200_000 + usize::from(i)]).unwrap();
863 }
864 w.finish().unwrap();
865 path
866 }
867
868 #[test]
869 fn keeping_the_archive_plans_for_every_file() {
870 let dir = std::env::temp_dir().join(format!("hatchzip-plan-{}", std::process::id()));
871 fs::create_dir_all(&dir).unwrap();
872 let archive = sample_zip(&dir);
873 let out = dir.join("out");
874 let job = Job::open(&archive, false, None, Default::default()).unwrap();
875 let files: u64 = job
876 .units
877 .iter()
878 .flat_map(|u| &u.items)
879 .map(|i| i.size.next_multiple_of(4096))
880 .sum();
881 let tail = job.storage.original_len() - job.tail_start;
882
883 let keep = plan(&job, &out, false, 0, true).unwrap();
884 assert!(keep.keep_archive && keep.either);
885 assert_eq!(keep.needed, files + tail);
887 assert_eq!(keep.normal_needs, keep.needed);
888 assert!(!keep.solid_block_bound && !keep.archive_kept_whole);
889 assert_eq!(keep.free.saturating_sub(keep.free_after), files);
891
892 let in_place = plan(&job, &out, false, 0, false).unwrap();
893 assert!(!in_place.keep_archive);
894 assert_eq!(in_place.normal_needs, keep.needed);
895 assert_eq!(in_place.in_place_needs, in_place.needed);
896 assert_eq!(keep.in_place_needs, in_place.needed);
897 assert!(
898 in_place.needed < keep.needed / 2,
899 "in place {} vs kept {}",
900 in_place.needed,
901 keep.needed
902 );
903 drop(job);
904 fs::remove_dir_all(&dir).unwrap();
905 }
906
907 #[test]
910 fn a_kept_archive_refuses_every_change() {
911 let dir = std::env::temp_dir().join(format!("hatchzip-protect-{}", std::process::id()));
912 fs::create_dir_all(&dir).unwrap();
913 let archive = sample_zip(&dir);
914 let before = fs::read(&archive).unwrap();
915 let (primary, paths) = locate(&archive).unwrap();
916 let reads = Arc::default();
917 let State::Fresh(job, out) = open(&primary, &paths, None, true, None, &reads).unwrap()
918 else {
919 panic!("a new archive opens fresh");
920 };
921 let journal = begin(&job, &paths, out, true, None).unwrap();
922 assert!(journal.keep);
923 let len = job.storage.original_len();
924 assert!(job.storage.set_len(len / 2).is_err());
925 assert!(job.storage.punch(0, len / 2).is_err());
926 assert!(job.storage.write_at(0, b"PK").is_err());
927 assert!(job.storage.cut_to(0).is_err());
928 drop(job);
929 assert_eq!(fs::read(&archive).unwrap(), before);
930
931 let (journal, tail) = Journal::load(&paths).unwrap();
933 let job = Job::resume(&journal, tail, true, None, Default::default()).unwrap();
934 assert!(job.storage.set_len(0).is_err());
935 assert_eq!(job.units.len(), 8, "nothing is committed yet");
936 drop(job);
937 assert_eq!(fs::read(&archive).unwrap(), before);
938 assert!(keeps_archive(&journal, false).unwrap());
939 assert!(keeps_archive(&journal, true).unwrap());
940 fs::remove_dir_all(&dir).unwrap();
941 }
942}