1use std::fs;
5use std::path::{Path, PathBuf};
6
7use anyhow::{Context, Result, bail};
8
9use crate::archive::storage;
10use crate::engine::Job;
11use crate::fsutil;
12use crate::journal::{Journal, Paths, Plan};
13
14pub fn locate(archive: &Path) -> Result<(PathBuf, Paths)> {
17 let primary = std::path::absolute(storage::first_volume(archive))
18 .with_context(|| format!("resolving {}", archive.display()))?;
19 let paths = Paths::for_archive(&primary);
20 Ok((primary, paths))
21}
22
23pub enum State {
24 Fresh(Job, PathBuf),
27 Resume(Job, Journal),
28 Orphan(Journal),
30}
31
32pub fn open(
38 primary: &Path,
39 paths: &Paths,
40 output: Option<PathBuf>,
41 writable: bool,
42 password: Option<&str>,
43) -> Result<State> {
44 if paths.exists() {
45 let (mut journal, tail) = Journal::load(paths)?;
46 if let Some(o) = &output
47 && std::path::absolute(o)? != journal.output
48 {
49 bail!(
50 "this archive is already partially extracted to {}. Complete or restore that extraction first",
51 journal.output.display()
52 );
53 }
54 if journal.restoring.is_some() {
55 if !writable {
56 bail!(
57 "a restore of this archive was interrupted. Run restore again to complete \
58 it, or run extract to resume the extraction"
59 );
60 }
61 crate::restore::recover(&mut journal, paths)?;
62 }
63 if !journal.parts[0].0.exists() {
64 return Ok(State::Orphan(journal));
65 }
66 let job = Job::resume(&journal, tail, writable, password)?;
67 return Ok(State::Resume(job, journal));
68 }
69 let job = Job::open(primary, writable, password)?;
70 let output = match output {
71 Some(o) => std::path::absolute(o)?,
72 None => default_output(primary),
73 };
74 if writable {
75 check_collisions(&job, &output)?;
76 }
77 Ok(State::Fresh(job, output))
78}
79
80pub fn open_encrypted(
86 primary: &Path,
87 paths: &Paths,
88 output: Option<PathBuf>,
89 writable: bool,
90 mut password: Option<String>,
91 mut ask: impl FnMut(bool) -> Option<String>,
92) -> Result<(State, Option<String>)> {
93 let mut wrong = false;
94 loop {
95 let attempt = open(
96 primary,
97 paths,
98 output.clone(),
99 writable,
100 password.as_deref(),
101 );
102 let failure = match attempt {
103 Ok(State::Orphan(j)) => return Ok((State::Orphan(j), password)),
104 Ok(state) => {
105 let job = match &state {
106 State::Fresh(job, _) | State::Resume(job, _) => job,
107 State::Orphan(_) => unreachable!(),
108 };
109 if !job.encrypted() {
110 return Ok((state, password));
111 }
112 match job.check_password() {
113 Ok(()) => return Ok((state, password)),
114 Err(e) => e,
115 }
116 }
117 Err(e) => e,
118 };
119 if failure.is::<crate::archive::WrongPassword>() {
120 wrong = true;
121 } else if !failure.is::<crate::archive::PasswordNeeded>() {
122 return Err(failure);
123 }
124 match ask(wrong) {
127 Some(p) => password = Some(p),
128 None => return Err(failure),
129 }
130 }
131}
132
133fn check_collisions(job: &Job, out: &Path) -> Result<()> {
137 if !out.exists() {
138 return Ok(());
139 }
140 let mut checked = std::collections::HashSet::new();
141 for item in job.units.iter().flat_map(|u| &u.items) {
142 let dest = out.join(&item.path);
143 if let Ok(meta) = fs::symlink_metadata(&dest)
144 && !(meta.is_dir() && item.kind == crate::archive::Kind::Dir)
145 {
146 bail!(
147 "{} already exists. HatchZip does not overwrite existing files. \
148 Move the file or choose another destination",
149 dest.display()
150 );
151 }
152 for parent in item
154 .path
155 .ancestors()
156 .skip(1)
157 .filter(|p| !p.as_os_str().is_empty())
158 {
159 if !checked.insert(parent.to_path_buf()) {
160 break;
161 }
162 if let Ok(meta) = fs::symlink_metadata(out.join(parent))
163 && !meta.is_dir()
164 {
165 bail!(
166 "{} is a file, but the archive requires a folder at that location",
167 out.join(parent).display()
168 );
169 }
170 }
171 }
172 Ok(())
173}
174
175pub fn default_output(primary: &Path) -> PathBuf {
178 let file_name = primary
179 .file_name()
180 .unwrap_or_default()
181 .to_string_lossy()
182 .into_owned();
183 let mut name = file_name.clone();
184 if let Some((stem, digits)) = name.rsplit_once('.')
185 && digits.len() >= 3
186 && digits.bytes().all(|b| b.is_ascii_digit())
187 {
188 name = stem.to_string();
189 }
190 let lower = name.to_ascii_lowercase();
191 for ext in [".zip", ".7z", ".tar", ".tar.gz", ".tgz", ".exe"] {
192 if lower.ends_with(ext) && name.len() > ext.len() {
193 name.truncate(name.len() - ext.len());
194 break;
195 }
196 }
197 if name == file_name {
198 name.push_str("-extracted");
199 }
200 primary.with_file_name(name)
201}
202
203pub fn display_name(job: &Job) -> String {
205 let parts = job.storage.parts();
206 let first = parts[0]
207 .path
208 .file_name()
209 .unwrap_or_default()
210 .to_string_lossy()
211 .into_owned();
212 match parts.len() {
213 1 => first,
214 n => format!("{first} (+{} more parts)", n - 1),
215 }
216}
217
218pub struct SpacePlan {
220 pub free: u64,
223 pub needed: u64,
225 pub keep_free: u64,
226 pub fits: bool,
227 pub free_after: u64,
229 pub normal_needs: u64,
231 pub reclaims: bool,
234 pub solid_block_bound: bool,
237 pub archive_kept_whole: bool,
242}
243
244pub fn plan(job: &Job, out: &Path, resuming: bool, keep_free: u64) -> Result<SpacePlan> {
245 let reclaims = fsutil::same_filesystem(job.storage.primary(), out);
246 let stale: u64 =
247 job.uncommitted(out).iter().map(|(_, n)| n).sum::<u64>() + job.past_resume_point(out);
248 let free = fsutil::available_space(out)? + stale;
249 let (needed, end) = job.space_needed(!resuming, reclaims);
250 let fits = free >= needed + keep_free;
251 Ok(SpacePlan {
252 free,
253 needed,
254 keep_free,
255 fits,
256 free_after: (free as i128 - end).max(0) as u64,
257 normal_needs: job.remaining_size(),
258 reclaims,
259 solid_block_bound: !fits
260 && !job.is_stream()
261 && job
262 .units
263 .iter()
264 .any(|u| u.items.len() > 1 && u.size() > free),
265 archive_kept_whole: job.kept_whole(reclaims),
266 })
267}
268
269pub fn begin(job: &Job, paths: &Paths, output: PathBuf) -> Result<Journal> {
272 let plan = Plan {
273 format: job.format_name,
274 tail_start: job.tail_start,
275 output,
276 total_size: job.remaining_size(),
277 };
278 Journal::create(paths, &job.storage, plan)
279}
280
281pub fn clear_uncommitted(job: &Job, out: &Path) -> Result<()> {
284 for (p, _) in job.uncommitted(out) {
285 fs::remove_file(&p).with_context(|| format!("removing stale {}", p.display()))?;
286 }
287 Ok(())
288}