1use std::collections::HashSet;
5use std::fs;
6use std::path::{Path, PathBuf};
7use std::sync::Arc;
8
9use anyhow::{Context, Result, bail};
10
11use crate::archive::storage::{self, Reads, Storage};
12use crate::engine::Job;
13use crate::fsutil;
14use crate::journal::{Journal, Paths, Plan};
15
16pub fn locate(archive: &Path) -> Result<(PathBuf, Paths)> {
19 let primary = std::path::absolute(storage::first_volume(archive))
20 .with_context(|| format!("resolving {}", archive.display()))?;
21 let paths = Paths::for_archive(&primary);
22 Ok((primary, paths))
23}
24
25pub fn nested_offer(path: &Path, written: &HashSet<PathBuf>) -> Option<PathBuf> {
38 crate::archive::nested_kind(path)?;
39 let (primary, paths) = locate(path).ok()?;
40 let kind = crate::archive::nested_kind(&primary)?;
43 let side_files = [&paths.journal, &paths.tail, &paths.folders]
44 .into_iter()
45 .chain(&paths.stub)
46 .any(|p| fs::symlink_metadata(p).is_ok());
47 if side_files || !volumes_written(&primary, written) {
48 return None;
49 }
50 if kind == crate::archive::SPLIT_ZIP {
54 Job::open(&primary, false, None, Arc::default()).ok()?;
55 }
56 Some(primary)
57}
58
59pub fn volumes_written(primary: &Path, written: &HashSet<PathBuf>) -> bool {
72 let mut volumes = Vec::new();
73 if storage::is_split_zip(primary) {
74 for disk in 0.. {
75 let Some(segment) = storage::split_zip_segment(primary, disk) else {
76 break;
77 };
78 if !segment.exists() {
79 break;
80 }
81 volumes.push(segment);
82 }
83 match storage::split_zip_last(primary) {
84 Some(last) if last.exists() => volumes.push(last),
85 _ => return false,
86 }
87 let beyond_a_gap = written.iter().any(|w| {
88 w.parent() == primary.parent()
89 && !volumes.contains(w)
90 && storage::first_volume(w) == primary
91 });
92 if beyond_a_gap {
93 return false;
94 }
95 } else {
96 for index in 0.. {
97 let Some(volume) = storage::volume_path(primary, index) else {
98 break;
99 };
100 if index > 0 && !volume.exists() {
101 break;
102 }
103 volumes.push(volume);
104 }
105 }
106 volumes
107 .iter()
108 .filter(|v| v.exists())
109 .all(|v| written.contains(v))
110 && written.contains(primary)
111}
112
113#[derive(Clone, Debug, PartialEq, Eq)]
118pub enum Output {
119 Default,
122 Computed(PathBuf),
126 Named(PathBuf),
128}
129
130impl Output {
131 pub fn path(&self) -> Option<&Path> {
132 match self {
133 Self::Default => None,
134 Self::Computed(p) | Self::Named(p) => Some(p),
135 }
136 }
137}
138
139#[allow(clippy::large_enum_variant)]
142pub enum State {
143 Fresh(Job, PathBuf),
146 Resume(Job, Journal),
147 Orphan(Journal),
149}
150
151pub(crate) fn check_recorded_case(journal: &Journal) -> Result<()> {
154 crate::engine::check_case_record(
155 &journal.output,
156 &journal.case_folders,
157 journal.case_beyond_ascii,
158 )
159}
160
161pub fn case_sensitive(dir: &Path) -> bool {
164 crate::platform::case_sensitive(dir)
165}
166
167pub fn open(
181 primary: &Path,
182 paths: &Paths,
183 output: Output,
184 only: Option<&[PathBuf]>,
185 writable: bool,
186 password: Option<&str>,
187 reads: &Arc<Reads>,
188) -> Result<State> {
189 if paths.exists() {
190 let (mut journal, tail) = Journal::load(paths)?;
191 if writable && !journal.done && journal.parts[0].0.exists() {
195 journal.check_folders(paths)?;
196 }
197 if writable || output != Output::Default {
199 check_output(&journal, primary, &output)?;
200 }
201 if writable {
202 check_recorded_case(&journal)?;
203 }
204 if journal.restoring.is_some() {
205 if !writable {
206 bail!(
207 "a restore of this archive was interrupted. Run restore again to complete \
208 it, or run extract to resume the extraction"
209 );
210 }
211 crate::restore::recover(&mut journal, paths)?;
212 }
213 if !journal.parts[0].0.exists() {
214 check_first_part_gone(&journal)?;
215 if journal.keep {
216 bail!(
219 "{} was moved or deleted during an extraction that keeps it. Put it back \
220 to resume, or delete {} to discard the progress",
221 journal.parts[0].0.display(),
222 paths.journal.display()
223 );
224 }
225 return Ok(State::Orphan(journal));
226 }
227 if journal.done {
231 return Ok(State::Orphan(journal));
232 }
233 if let Some(given) = only {
234 check_same_selection(&journal, given)?;
235 }
236 let job = Job::resume(&journal, tail, writable, password, reads.clone())?;
237 check_no_links_on_the_way(&job, &journal.output)?;
238 return Ok(State::Resume(job, journal));
239 }
240 let mut job = Job::open(primary, writable, password, reads.clone())?;
241 if writable && job.format_name == crate::archive::SPLIT_ZIP {
242 paths.check_stub()?;
243 }
244 if let Some(given) = only {
245 job.select(given)?;
246 }
247 let output = match output {
248 Output::Named(o) => std::path::absolute(o)?,
249 Output::Computed(o) => {
252 let output = std::path::absolute(o)?;
253 refuse_linked_default(&output)?;
254 output
255 }
256 Output::Default => {
257 let output = default_output(primary);
258 refuse_linked_default(&output)?;
259 output
260 }
261 };
262 check_path_lengths(&job, &output)?;
263 if writable {
264 check_no_links_on_the_way(&job, &output)?;
265 check_collisions(&job, &output)?;
266 job.check_case(&output)?;
267 }
268 Ok(State::Fresh(job, output))
269}
270
271pub(crate) fn check_first_part_gone(journal: &Journal) -> Result<()> {
278 if journal.done || journal.keep {
279 return Ok(());
280 }
281 let mut start = 0u64;
282 for (i, (part, len)) in journal.parts.iter().enumerate() {
283 if i > 0 && start < journal.committed_len && part.exists() {
284 bail!(
285 "{} was moved or deleted during the extraction, but {} and the rest of the \
286 archive still need it. Put it back to resume. Nothing was modified",
287 journal.parts[0].0.display(),
288 part.display()
289 );
290 }
291 start = start.saturating_add(*len);
292 }
293 Ok(())
294}
295
296fn check_same_selection(journal: &Journal, given: &[PathBuf]) -> Result<()> {
300 let Some(recorded) = &journal.only else {
301 bail!(
302 "this archive is partially extracted with every entry selected. Resume it without \
303 choosing entries, or run restore first. Nothing was modified"
304 );
305 };
306 for g in given {
307 let p = crate::engine::selection_path(g)?;
308 if !crate::engine::picks(recorded, &p) {
310 bail!(
311 "this archive is partially extracted with other entries selected, and '{}' is \
312 not one of them. Resume it without choosing entries to finish those, or run \
313 restore first. Nothing was modified",
314 p.display()
315 );
316 }
317 }
318 Ok(())
319}
320
321pub fn check_output(journal: &Journal, primary: &Path, given: &Output) -> Result<()> {
333 let default = default_output(primary);
334 let in_default = fsutil::same_path(&default, &journal.output);
335 if let Some(o) = given.path()
336 && !fsutil::same_path(&std::path::absolute(o)?, &journal.output)
337 {
338 bail!(
339 "this archive is already partially extracted to {}. Complete or restore that \
340 extraction first",
341 journal.output.display()
342 );
343 }
344 let named = matches!(given, Output::Named(_));
345 if crate::chosen::chose(primary, &journal.output) {
346 if in_default && !named {
348 refuse_linked_default(&default)?;
349 }
350 return Ok(());
351 }
352 let paths = Paths::for_archive(primary);
353 bail!(
354 "{} has progress files next to it for an extraction to {}, but HatchZip on this computer \
355 has no record of starting it, so they were not used. If you did not start this \
356 extraction, delete {}. Nothing was modified",
357 primary.display(),
358 journal.output.display(),
359 journal.side_files(&paths)
360 )
361}
362
363fn refuse_linked_default(output: &Path) -> Result<()> {
367 if fs::symlink_metadata(output).is_ok_and(|m| m.is_symlink()) {
368 bail!(
369 "{} is a link, so files extracted there would land somewhere else. Remove the link, \
370 or choose the destination folder. Nothing was modified",
371 output.display()
372 );
373 }
374 Ok(())
375}
376
377pub(crate) fn check_no_links_on_the_way(job: &Job, out: &Path) -> Result<()> {
382 let mut checked = std::collections::HashSet::new();
383 for item in job.units.iter().flat_map(|u| &u.items) {
384 for parent in item
385 .path
386 .ancestors()
387 .skip(1)
388 .filter(|p| !p.as_os_str().is_empty())
389 {
390 if !checked.insert(parent.to_path_buf()) {
391 break;
392 }
393 if fs::symlink_metadata(out.join(parent)).is_ok_and(|m| m.is_symlink()) {
394 bail!(
395 "{} is a link, and '{}' would be extracted through it. Nothing was modified",
396 out.join(parent).display(),
397 item.path.display()
398 );
399 }
400 }
401 }
402 Ok(())
403}
404
405fn check_path_lengths(job: &Job, out: &Path) -> Result<()> {
408 for item in job.units.iter().flat_map(|u| &u.items) {
409 if crate::platform::path_len(&out.join(&item.path)) > crate::platform::MAX_PATH_LEN {
410 bail!(
411 "'{}' cannot be created in {}: the full path would be longer than this system \
412 allows. The archive was not modified. Extract to a folder with a shorter path",
413 item.path.display(),
414 out.display()
415 );
416 }
417 }
418 Ok(())
419}
420
421#[allow(clippy::too_many_arguments)]
427pub fn open_encrypted(
428 primary: &Path,
429 paths: &Paths,
430 output: Output,
431 only: Option<&[PathBuf]>,
432 writable: bool,
433 password: Option<String>,
434 reads: &Arc<Reads>,
435 ask: impl FnMut(bool) -> Option<String>,
436) -> Result<(State, Option<String>)> {
437 open_encrypted_noting(
438 primary,
439 paths,
440 output,
441 only,
442 writable,
443 password,
444 reads,
445 ask,
446 |_, _| {},
447 )
448}
449
450#[allow(clippy::too_many_arguments)]
454pub fn open_encrypted_noting(
455 primary: &Path,
456 paths: &Paths,
457 output: Output,
458 only: Option<&[PathBuf]>,
459 writable: bool,
460 mut password: Option<String>,
461 reads: &Arc<Reads>,
462 mut ask: impl FnMut(bool) -> Option<String>,
463 mut slow: impl FnMut(&Path, u64),
464) -> Result<(State, Option<String>)> {
465 let mut wrong = false;
466 loop {
467 let attempt = open(
468 primary,
469 paths,
470 output.clone(),
471 only,
472 writable,
473 password.as_deref(),
474 reads,
475 );
476 let failure = match attempt {
477 Ok(State::Orphan(j)) => return Ok((State::Orphan(j), password)),
478 Ok(state) => {
479 let job = match &state {
480 State::Fresh(job, _) | State::Resume(job, _) => job,
481 State::Orphan(_) => unreachable!(),
482 };
483 if !job.encrypted() {
484 return Ok((state, password));
485 }
486 if password.is_some()
487 && let Some((file, size)) = job.slow_password_check()
488 {
489 slow(file, size);
490 }
491 match job.check_password() {
492 Ok(()) => return Ok((state, password)),
493 Err(e) => e,
494 }
495 }
496 Err(e) => e,
497 };
498 if failure.is::<crate::archive::WrongPassword>() {
499 wrong = true;
500 } else if !failure.is::<crate::archive::PasswordNeeded>() {
501 return Err(failure);
502 }
503 match ask(wrong) {
506 Some(p) => password = Some(p),
507 None => return Err(failure),
508 }
509 }
510}
511
512fn check_collisions(job: &Job, out: &Path) -> Result<()> {
518 if !out.exists() {
519 return Ok(());
520 }
521 check_own_files(job, out)?;
522 let mut checked = std::collections::HashSet::new();
523 for item in job.units.iter().flat_map(|u| &u.items) {
524 let dest = out.join(&item.path);
525 let part = crate::engine::part_path(&dest);
526 if item.kind == crate::archive::Kind::File && fs::symlink_metadata(&part).is_ok() {
527 bail!(
528 "{} already exists. HatchZip first writes '{}' under that name and does not \
529 replace a file it did not create. Move it or choose another destination. Nothing \
530 was modified",
531 part.display(),
532 item.path.display()
533 );
534 }
535 if let Ok(meta) = fs::symlink_metadata(&dest) {
536 let dir = item.kind == crate::archive::Kind::Dir;
537 if dir && !meta.is_dir() {
538 bail!(
539 "{} is a file, but the archive requires a folder at that location",
540 dest.display()
541 );
542 }
543 if !dir && meta.is_dir() {
544 bail!(
545 "{} is a folder, but the archive has a file at that location. Move the \
546 folder or choose another destination",
547 dest.display()
548 );
549 }
550 }
551 for parent in item
552 .path
553 .ancestors()
554 .skip(1)
555 .filter(|p| !p.as_os_str().is_empty())
556 {
557 if !checked.insert(parent.to_path_buf()) {
558 break;
559 }
560 if let Ok(meta) = fs::symlink_metadata(out.join(parent))
561 && !meta.is_dir()
562 {
563 bail!(
564 "{} is a file, but the archive requires a folder at that location",
565 out.join(parent).display()
566 );
567 }
568 }
569 }
570 Ok(())
571}
572
573fn check_own_files(job: &Job, out: &Path) -> Result<()> {
581 let text = |p: &Path| p.to_string_lossy().to_lowercase();
582 let folder = |p: &Path| {
583 let dir = p.parent().filter(|d| !d.as_os_str().is_empty());
584 fs::canonicalize(dir.unwrap_or(Path::new(".")))
585 .ok()
586 .map(|d| text(&d))
587 };
588 let lower = |p: &Path| p.file_name().map(|n| text(Path::new(n)));
589 let Ok(out) = fs::canonicalize(out) else {
590 return Ok(());
591 };
592 let primary = job.storage.primary();
593 let own_folder = folder(primary);
594 let side = lower(primary).map(|n| format!("{n}.hatchzip"));
595 let volumes: Vec<_> = job
596 .storage
597 .parts()
598 .iter()
599 .map(|p| (folder(&p.path), lower(&p.path)))
600 .collect();
601 for item in job.units.iter().flat_map(|u| &u.items) {
602 let dest = out.join(&item.path);
603 let dir = dest.parent().map(text);
604 let name = lower(&dest);
605 let (Some(dir), Some(name)) = (dir, name) else {
606 continue;
607 };
608 let volume = volumes
609 .iter()
610 .any(|(d, n)| d.as_ref() == Some(&dir) && n.as_ref() == Some(&name));
611 let progress = own_folder.as_ref() == Some(&dir)
612 && side.as_ref().is_some_and(|s| name.starts_with(s.as_str()));
613 if volume || progress {
614 bail!(
615 "'{}' would be extracted onto {}, one of the archive's own files. Choose another \
616 destination. Nothing was modified",
617 item.path.display(),
618 dest.display()
619 );
620 }
621 }
622 Ok(())
623}
624
625pub fn existing(job: &Job, out: &Path) -> Result<Vec<PathBuf>> {
630 let found = crate::replace::found(job, out);
631 if !found.is_empty() {
632 crate::replace::check(job, out, &found)?;
633 }
634 Ok(found)
635}
636
637pub fn single_root(job: &Job) -> bool {
641 let mut roots = job
642 .units
643 .iter()
644 .flat_map(|u| &u.items)
645 .filter_map(|i| i.path.components().next());
646 let Some(first) = roots.next() else {
647 return false;
648 };
649 roots.all(|r| r == first)
650}
651
652pub fn retarget(job: &Job, out: &Path) -> Result<PathBuf> {
655 let out = std::path::absolute(out)?;
656 check_path_lengths(job, &out)?;
657 check_no_links_on_the_way(job, &out)?;
658 check_collisions(job, &out)?;
659 job.check_case(&out)?;
660 Ok(out)
661}
662
663pub fn default_output(primary: &Path) -> PathBuf {
666 let file_name = primary
667 .file_name()
668 .unwrap_or_default()
669 .to_string_lossy()
670 .into_owned();
671 let mut name = file_name.clone();
672 if let Some((stem, digits)) = name.rsplit_once('.')
673 && digits.len() >= 3
674 && digits.bytes().all(|b| b.is_ascii_digit())
675 {
676 name = stem.to_string();
677 }
678 if let Some((stem, ext)) = name.rsplit_once('.')
680 && ext.len() >= 3
681 && ext.as_bytes()[0].eq_ignore_ascii_case(&b'z')
682 && ext.bytes().skip(1).all(|b| b.is_ascii_digit())
683 {
684 name = stem.to_string();
685 }
686 let lower = name.to_ascii_lowercase();
687 if let Some(stem) = lower.strip_suffix(".rar")
689 && let Some((_, digits)) = stem.rsplit_once(".part")
690 && !digits.is_empty()
691 && digits.bytes().all(|b| b.is_ascii_digit())
692 {
693 name.truncate(stem.len() - digits.len() - ".part".len());
694 } else {
695 for ext in [
696 ".zip", ".7z", ".tar.xz", ".txz", ".tar.bz2", ".tbz2", ".tbz", ".tar.zst", ".tzst",
697 ".tar", ".tar.gz", ".tgz", ".rar", ".exe",
698 ] {
699 if lower.ends_with(ext) && name.len() > ext.len() {
700 name.truncate(name.len() - ext.len());
701 break;
702 }
703 }
704 }
705 if name == file_name || name.chars().all(|c| c == '.' || c == ' ') {
711 name = file_name;
712 name.push_str("-extracted");
713 }
714 primary.with_file_name(name)
715}
716
717pub fn display_name(job: &Job) -> String {
719 let parts = job.storage.parts();
720 let first = parts[0]
721 .path
722 .file_name()
723 .unwrap_or_default()
724 .to_string_lossy()
725 .into_owned();
726 match parts.len() {
727 1 => first,
728 n => format!("{first} (+{} more parts)", n - 1),
729 }
730}
731
732pub fn keeps_archive(journal: &Journal, asked: bool) -> Result<bool> {
737 if asked && !journal.keep {
738 bail!(
739 "this archive is partially extracted in place, so part of it is already removed and \
740 it cannot be kept. Resume without --keep-archive, or run restore first"
741 );
742 }
743 Ok(journal.keep)
744}
745
746pub struct SpacePlan {
748 pub free: u64,
751 pub needed: u64,
754 pub keep_free: u64,
755 pub fits: bool,
756 pub free_after: u64,
758 pub keep_archive: bool,
760 pub normal_needs: u64,
763 pub in_place_needs: u64,
766 pub either: bool,
769 pub reclaims: bool,
772 pub solid_block_bound: bool,
775 pub archive_kept_whole: bool,
780}
781
782impl SpacePlan {
783 pub fn normal_fits(&self) -> bool {
785 self.free >= self.normal_needs + self.keep_free
786 }
787
788 pub fn in_place_fits(&self) -> bool {
789 self.free >= self.in_place_needs + self.keep_free
790 }
791}
792
793fn check_destination(out: &Path, resuming: bool) -> Result<()> {
798 let untouched = if resuming {
799 ""
800 } else {
801 ". Nothing was modified"
802 };
803 let mut path = out.to_path_buf();
807 loop {
808 match path.symlink_metadata() {
809 Ok(meta) => {
810 if path.is_dir() {
811 return Ok(());
812 }
813 let what = if meta.is_file() {
814 "is a file, not a folder"
815 } else {
816 "is not a folder"
817 };
818 if path == out {
819 bail!("the destination {} {what}{untouched}", out.display());
820 }
821 bail!(
822 "the destination {} cannot be created: {} {what}{untouched}",
823 out.display(),
824 path.display()
825 );
826 }
827 Err(_) => {
828 if !path.pop() {
829 return Ok(());
830 }
831 }
832 }
833 }
834}
835
836pub fn plan(
840 job: &Job,
841 out: &Path,
842 resuming: bool,
843 keep_free: u64,
844 keep_archive: bool,
845) -> Result<SpacePlan> {
846 job.check_case(out)?;
847 check_destination(out, resuming)?;
848 let reclaims = fsutil::same_filesystem(job.storage.primary(), out);
849 let stale: u64 =
850 job.uncommitted(out).iter().map(|(_, n)| n).sum::<u64>() + job.past_resume_point(out);
851 let free = fsutil::available_space(out)? + stale;
852 let (normal_needs, normal_end) = job.space_needed(!resuming, false);
855 let (in_place_needs, in_place_end) = if keep_archive && resuming {
856 (normal_needs, normal_end)
857 } else {
858 job.space_needed(!resuming, reclaims)
859 };
860 let tail = job.storage.original_len().saturating_sub(job.tail_start) as i128;
862 let normal_end = normal_end - if reclaims { tail } else { 0 };
863 let (needed, end) = if keep_archive {
864 (normal_needs, normal_end)
865 } else {
866 (in_place_needs, in_place_end)
867 };
868 let fits = free >= needed + keep_free;
869 Ok(SpacePlan {
870 free,
871 needed,
872 keep_free,
873 fits,
874 free_after: (free as i128 - end).max(0) as u64,
875 keep_archive,
876 normal_needs,
877 in_place_needs,
878 either: !resuming,
879 reclaims,
880 solid_block_bound: !fits
881 && !keep_archive
882 && !job.is_stream()
883 && job
884 .units
885 .iter()
886 .any(|u| u.items.len() > 1 && u.size() > free),
887 archive_kept_whole: !keep_archive && job.kept_whole(reclaims),
888 })
889}
890
891pub fn begin(
898 job: &Job,
899 paths: &Paths,
900 output: PathBuf,
901 keep_archive: bool,
902 replace: Option<&crate::replace::Choices>,
903) -> Result<Journal> {
904 job.check_case(&output)?;
906 check_destination(&output, false)?;
907 let found = existing(job, &output)?;
908 if let Some(first) = found.first()
909 && replace.is_none()
910 {
911 let what = match found.len() {
912 1 => format!("{} already exists", output.join(first).display()),
913 n => format!(
914 "{} and {} other {} already exist",
915 output.join(first).display(),
916 n - 1,
917 if n == 2 { "file" } else { "files" }
918 ),
919 };
920 bail!(
921 "{what}. Existing files are only replaced when that is requested. Move the files or \
922 choose another destination. Nothing was modified"
923 );
924 }
925 if job.selection().is_some() && !keep_archive {
926 bail!(
928 "only some entries are selected, and those are extracted only while the archive is \
929 kept. Nothing was modified"
930 );
931 }
932 if keep_archive {
933 job.storage.protect();
934 } else if let Some(why) = job.in_place_refusal() {
935 bail!("{why}. It can be extracted while keeping the archive");
937 }
938 crate::sfv::check_volumes(&job.storage)?;
939 crate::chosen::remember(&paths.archive, &output)?;
943 let only_found = |paths: &[PathBuf]| -> Vec<PathBuf> {
946 paths
947 .iter()
948 .filter(|p| found.contains(p))
949 .cloned()
950 .collect()
951 };
952 let replace = replace
953 .filter(|_| !found.is_empty())
954 .map(|c| crate::journal::Replace {
955 moved: false,
956 keep: only_found(&c.keep),
957 both: only_found(&c.both),
958 });
959 let folders = crate::folders::of(&job.units, &output);
960 let plan = Plan {
961 format: job.format_name,
962 tail_start: job.tail_start,
963 output,
964 total_size: job.remaining_size(),
965 keep: keep_archive,
966 replace,
967 case_folders: job.case_folders(),
968 case_beyond_ascii: job.case_beyond_ascii(),
969 folders,
970 only: job.selection().map(<[PathBuf]>::to_vec),
971 };
972 Journal::create(paths, &job.storage, plan)
973}
974
975pub fn check_sfv(storage: &Storage, cancelled: &dyn Fn() -> bool) -> Result<Option<PathBuf>> {
977 crate::sfv::check_volumes_cancellable(storage, cancelled)
978}
979
980pub fn clear_uncommitted(job: &Job, out: &Path) -> Result<()> {
983 clear_output(job, out, false)
984}
985
986pub(crate) fn clear_discarded(job: &Job, out: &Path) -> Result<()> {
989 clear_output(job, out, true)
990}
991
992fn clear_output(job: &Job, out: &Path, discard: bool) -> Result<()> {
993 check_no_links_on_the_way(job, out)?;
994 let found = if discard {
995 job.discarded_output(out)
996 } else {
997 job.uncommitted(out)
998 };
999 let mut listed = std::collections::HashMap::new();
1000 for (p, _) in &found {
1001 check_spelling(out, p, &mut listed)?;
1002 }
1003 for (p, _) in found {
1004 fs::remove_file(&p).with_context(|| format!("removing stale {}", p.display()))?;
1005 }
1006 Ok(())
1007}
1008
1009fn check_spelling(
1016 out: &Path,
1017 path: &Path,
1018 listed: &mut std::collections::HashMap<PathBuf, std::collections::HashSet<String>>,
1019) -> Result<()> {
1020 use unicode_normalization::UnicodeNormalization;
1021 let spelling = |n: &std::ffi::OsStr| n.to_string_lossy().nfd().collect::<String>();
1022 let Ok(rel) = path.strip_prefix(out) else {
1023 return Ok(());
1024 };
1025 let mut dir = out.to_path_buf();
1026 for name in rel.iter() {
1027 let names = match listed.entry(dir.clone()) {
1028 std::collections::hash_map::Entry::Occupied(e) => e.into_mut(),
1029 std::collections::hash_map::Entry::Vacant(e) => e.insert(
1030 fs::read_dir(&dir)
1031 .with_context(|| format!("listing {}", dir.display()))?
1032 .map(|e| e.map(|e| spelling(&e.file_name())))
1033 .collect::<std::io::Result<_>>()
1034 .with_context(|| format!("listing {}", dir.display()))?,
1035 ),
1036 };
1037 if !names.contains(&spelling(name)) {
1038 bail!(
1039 "{} is spelled differently on disk than in the archive, so it was not made by \
1040 this extraction and is left alone. Move it out of the way, then run the command \
1041 again",
1042 dir.join(name).display()
1043 );
1044 }
1045 dir.push(name);
1046 }
1047 Ok(())
1048}
1049
1050#[cfg(test)]
1051mod tests {
1052 use std::io::Write;
1053
1054 use ::zip::write::{SimpleFileOptions, ZipWriter};
1055
1056 use super::*;
1057
1058 #[test]
1061 fn a_resume_leaves_names_spelled_differently_alone() {
1062 let dir = tempfile::tempdir().unwrap();
1063 let out = dir.path();
1064 fs::create_dir(out.join("Src")).unwrap();
1065 fs::write(out.join("Src/Makefile"), b"theirs").unwrap();
1066 fs::write(out.join("Src/caf\u{e9}.txt"), b"ours").unwrap();
1067 let mut listed = std::collections::HashMap::new();
1068 assert!(check_spelling(out, &out.join("Src/makefile"), &mut listed).is_err());
1069 assert!(check_spelling(out, &out.join("src/Makefile"), &mut listed).is_err());
1070 assert!(check_spelling(out, &out.join("Src/Makefile"), &mut listed).is_ok());
1071 assert!(check_spelling(out, &out.join("Src/cafe\u{301}.txt"), &mut listed).is_ok());
1073 }
1074
1075 #[test]
1076 fn output_folder_drops_the_volume_and_format_suffixes() {
1077 let name = |n: &str| default_output(Path::new(n));
1078 assert_eq!(name("game.zip"), Path::new("game"));
1079 assert_eq!(name("game.7z.001"), Path::new("game"));
1080 assert_eq!(name("game.part1.rar"), Path::new("game"));
1081 assert_eq!(name("game.PART02.RAR"), Path::new("game"));
1082 assert_eq!(name("game.rar"), Path::new("game"));
1083 assert_eq!(name("game.tar.xz"), Path::new("game"));
1084 assert_eq!(name("game.txz"), Path::new("game"));
1085 assert_eq!(name("game.tar.zst"), Path::new("game"));
1086 assert_eq!(name("game.tzst"), Path::new("game"));
1087 assert_eq!(name("game.part.rar"), Path::new("game.part"));
1088 assert_eq!(name("notes.txt"), Path::new("notes.txt-extracted"));
1089 }
1090
1091 #[test]
1094 fn output_folder_is_never_the_folder_above_or_the_archives_own() {
1095 let name = |n: &str| default_output(&Path::new("dl").join(n));
1096 for n in [
1097 "...zip",
1098 "..zip",
1099 ".zip",
1100 ". .zip",
1101 "...tar.gz",
1102 "...7z.001",
1103 "...part1.rar",
1104 "..part2.rar",
1105 ] {
1106 assert_eq!(
1107 name(n),
1108 Path::new("dl").join(format!("{n}-extracted")),
1109 "{n}"
1110 );
1111 }
1112 assert_eq!(name("...game.zip"), Path::new("dl/...game"));
1113 }
1114
1115 fn sample_zip(dir: &Path) -> PathBuf {
1118 let path = dir.join("plan.zip");
1119 let mut w = ZipWriter::new(fs::File::create(&path).unwrap());
1120 let opts =
1121 SimpleFileOptions::default().compression_method(::zip::CompressionMethod::Stored);
1122 for i in 0..8u8 {
1123 w.start_file(format!("data/{i}.bin"), opts).unwrap();
1124 w.write_all(&vec![i; 200_000 + usize::from(i)]).unwrap();
1125 }
1126 w.finish().unwrap();
1127 path
1128 }
1129
1130 #[test]
1131 fn keeping_the_archive_plans_for_every_file() {
1132 let dir = std::env::temp_dir().join(format!("hatchzip-plan-{}", std::process::id()));
1133 fs::create_dir_all(&dir).unwrap();
1134 let archive = sample_zip(&dir);
1135 let out = dir.join("out");
1136 let job = Job::open(&archive, false, None, Default::default()).unwrap();
1137 let files: u64 = job
1138 .units
1139 .iter()
1140 .flat_map(|u| &u.items)
1141 .map(|i| i.size.next_multiple_of(4096))
1142 .sum();
1143 let tail = job.storage.original_len() - job.tail_start;
1144
1145 let keep = plan(&job, &out, false, 0, true).unwrap();
1146 assert!(keep.keep_archive && keep.either);
1147 assert_eq!(keep.needed, files + tail);
1149 assert_eq!(keep.normal_needs, keep.needed);
1150 assert!(!keep.solid_block_bound && !keep.archive_kept_whole);
1151 assert_eq!(keep.free.saturating_sub(keep.free_after), files);
1153
1154 let in_place = plan(&job, &out, false, 0, false).unwrap();
1155 assert!(!in_place.keep_archive);
1156 assert_eq!(in_place.normal_needs, keep.needed);
1157 assert_eq!(in_place.in_place_needs, in_place.needed);
1158 assert_eq!(keep.in_place_needs, in_place.needed);
1159 assert!(
1160 in_place.needed < keep.needed / 2,
1161 "in place {} vs kept {}",
1162 in_place.needed,
1163 keep.needed
1164 );
1165 drop(job);
1166 fs::remove_dir_all(&dir).unwrap();
1167 }
1168
1169 #[test]
1172 fn a_kept_archive_refuses_every_change() {
1173 let dir = std::env::temp_dir().join(format!("hatchzip-protect-{}", std::process::id()));
1174 fs::create_dir_all(&dir).unwrap();
1175 let archive = sample_zip(&dir);
1176 let before = fs::read(&archive).unwrap();
1177 let (primary, paths) = locate(&archive).unwrap();
1178 let reads = Arc::default();
1179 let State::Fresh(job, out) =
1180 open(&primary, &paths, Output::Default, None, true, None, &reads).unwrap()
1181 else {
1182 panic!("a new archive opens fresh");
1183 };
1184 let journal = begin(&job, &paths, out, true, None).unwrap();
1185 assert!(journal.keep);
1186 let len = job.storage.original_len();
1187 assert!(job.storage.set_len(len / 2).is_err());
1188 assert!(job.storage.punch(0, len / 2).is_err());
1189 assert!(job.storage.write_at(0, b"PK").is_err());
1190 assert!(job.storage.cut_to(0).is_err());
1191 drop(job);
1192 assert_eq!(fs::read(&archive).unwrap(), before);
1193
1194 let (journal, tail) = Journal::load(&paths).unwrap();
1196 let job = Job::resume(&journal, tail, true, None, Default::default()).unwrap();
1197 assert!(job.storage.set_len(0).is_err());
1198 assert_eq!(job.units.len(), 8, "nothing is committed yet");
1199 drop(job);
1200 assert_eq!(fs::read(&archive).unwrap(), before);
1201 assert!(keeps_archive(&journal, false).unwrap());
1202 assert!(keeps_archive(&journal, true).unwrap());
1203 fs::remove_dir_all(&dir).unwrap();
1204 }
1205}