1use std::collections::HashSet;
15use std::fs;
16use std::io;
17use std::path::{Path, PathBuf};
18
19use anyhow::{Context, Result, bail};
20
21use crate::archive::Kind;
22use crate::engine::{self, Job};
23use crate::journal::Replace;
24use crate::{fsutil, platform};
25
26pub const FOLDER: &str = ".hatchzip-replaced";
30
31#[derive(Clone, Debug, Default, PartialEq, Eq)]
34pub struct Choices {
35 pub keep: Vec<PathBuf>,
37 pub both: Vec<PathBuf>,
40}
41
42pub fn folder(out: &Path) -> PathBuf {
43 out.join(FOLDER)
44}
45
46pub(crate) fn found(job: &Job, out: &Path) -> Vec<PathBuf> {
49 if !out.exists() {
52 return Vec::new();
53 }
54 job.units
55 .iter()
56 .flat_map(|u| &u.items)
57 .filter(|i| i.kind != Kind::Dir)
58 .filter(|i| fs::symlink_metadata(out.join(&i.path)).is_ok_and(|m| !m.is_dir()))
59 .map(|i| i.path.clone())
60 .collect()
61}
62
63pub(crate) fn check(job: &Job, out: &Path, found: &[PathBuf]) -> Result<()> {
66 let named = |p: &Path| {
67 p.components()
68 .next()
69 .is_some_and(|c| c.as_os_str().to_string_lossy().eq_ignore_ascii_case(FOLDER))
70 };
71 if let Some(item) = job
72 .units
73 .iter()
74 .flat_map(|u| &u.items)
75 .find(|i| named(&i.path))
76 {
77 bail!(
78 "the archive contains '{}', but HatchZip uses the name {FOLDER} for the files it \
79 replaces, so existing files cannot be replaced in this extraction. Extract to an \
80 empty folder instead. Nothing was modified",
81 item.path.display()
82 );
83 }
84 let aside = folder(out);
85 if fs::symlink_metadata(&aside).is_ok() {
86 bail!(
87 "{} already exists, so existing files cannot be moved there. It may hold files \
88 replaced by an earlier extraction; move its contents elsewhere, delete it, then try \
89 again. Nothing was modified",
90 aside.display()
91 );
92 }
93 for rel in found {
94 if platform::path_len(&aside.join(rel)) > platform::MAX_PATH_LEN {
95 bail!(
96 "{} cannot be replaced: moving it into {} would make its path longer than this \
97 system allows. Nothing was modified. Extract to a folder with a shorter path",
98 out.join(rel).display(),
99 aside.display()
100 );
101 }
102 }
103 if let Some((a, b)) = case_pair(found)
107 && !engine::keeps_case_apart(out)
108 {
109 bail!(
110 "'{}' and '{}' differ only in case, and {} is not known to keep such names apart, so \
111 they cannot be moved aside to be replaced. Nothing was modified. Extract to an empty \
112 folder or move them first",
113 a.display(),
114 b.display(),
115 out.display()
116 );
117 }
118 Ok(())
119}
120
121fn case_pair(paths: &[PathBuf]) -> Option<(&Path, &Path)> {
125 let mut names: Vec<(String, &Path)> = paths
126 .iter()
127 .flat_map(|p| p.ancestors())
128 .filter(|p| !p.as_os_str().is_empty())
129 .map(|p| (crate::fsutil::fold_name(&p.to_string_lossy()), p))
130 .collect();
131 names.sort_unstable();
132 names.dedup();
133 names
134 .windows(2)
135 .find(|w| w[0].0 == w[1].0)
136 .map(|w| (w[0].1, w[1].1))
137}
138
139pub(crate) fn set_aside(job: &Job, out: &Path) -> Result<()> {
143 let aside = folder(out);
144 if let Err(e) = fs::create_dir(&aside)
145 && e.kind() != io::ErrorKind::AlreadyExists
146 {
147 return Err(e).with_context(|| format!("creating {}", aside.display()));
148 }
149 if !fs::symlink_metadata(&aside).is_ok_and(|m| m.is_dir()) {
150 bail!(
151 "{} is not a folder, so existing files cannot be moved there. Nothing was extracted",
152 aside.display()
153 );
154 }
155 for rel in found(job, out) {
156 let from = out.join(&rel);
157 let to = aside.join(&rel);
158 if let Some(via) = engine::link_on_the_way(&aside, &rel) {
161 bail!(
162 "{} is a link, and {} would be moved through it. Nothing was extracted",
163 aside.join(via).display(),
164 from.display()
165 );
166 }
167 if let Some(parent) = to.parent() {
168 fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
169 }
170 if fs::symlink_metadata(&to).is_ok() {
171 bail!(
172 "{} cannot be moved aside: {} already exists. Nothing was extracted",
173 from.display(),
174 to.display()
175 );
176 }
177 fs::rename(&from, &to)
179 .with_context(|| format!("moving {} to {}", from.display(), to.display()))?;
180 engine::crash_point("set-aside");
181 }
182 let rels: Vec<&Path> = job
183 .units
184 .iter()
185 .flat_map(|u| &u.items)
186 .filter(|i| i.kind != Kind::Dir)
187 .map(|i| i.path.as_path())
188 .collect();
189 flush(out, &rels)
190}
191
192pub(crate) fn put_back(out: &Path, over: bool) -> Result<usize> {
197 let aside = folder(out);
198 if !fs::symlink_metadata(&aside).is_ok_and(|m| m.is_dir()) {
199 return Ok(0);
200 }
201 let mut files = Vec::new();
202 walk(&aside, &aside, &mut files)?;
203 let mut stay = 0;
204 for rel in &files {
205 let from = aside.join(rel);
206 let to = out.join(rel);
207 if engine::link_on_the_way(out, rel).is_some() {
208 stay += 1;
209 continue;
210 }
211 match fs::symlink_metadata(&to) {
212 Err(e) if e.kind() == io::ErrorKind::NotFound => {
213 if let Some(parent) = to.parent() {
214 fs::create_dir_all(parent)
215 .with_context(|| format!("creating {}", parent.display()))?;
216 }
217 }
218 Ok(m) if over && !m.is_dir() => {}
219 _ => {
220 stay += 1;
221 continue;
222 }
223 }
224 fs::rename(&from, &to)
225 .with_context(|| format!("moving {} back to {}", from.display(), to.display()))?;
226 }
227 let rels: Vec<&Path> = files.iter().map(PathBuf::as_path).collect();
228 flush(out, &rels)?;
229 if stay == 0 {
230 remove(out)?;
231 }
232 Ok(stay)
233}
234
235pub(crate) fn settle(out: &Path, r: &Replace) -> Result<()> {
242 let aside = folder(out);
243 let chosen = r.keep.iter().map(|p| (p, false));
244 let mut done: Vec<&Path> = Vec::new();
245 for (rel, both) in chosen.chain(r.both.iter().map(|p| (p, true))) {
246 let from = aside.join(rel);
247 if fs::symlink_metadata(&from).is_err() {
248 continue;
250 }
251 let to = out.join(rel);
252 if let Some(via) = engine::link_on_the_way(out, rel) {
253 bail!(
254 "{} could not be put back: {} is a link. It is kept in {}. Remove the link, then \
255 resume the extraction to finish",
256 to.display(),
257 out.join(via).display(),
258 aside.display()
259 );
260 }
261 if let Some(parent) = to.parent() {
262 fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
263 }
264 if both && fs::symlink_metadata(&to).is_ok() {
265 let beside = free_name(&to);
266 fs::rename(&to, &beside)
267 .with_context(|| format!("moving {} to {}", to.display(), beside.display()))?;
268 }
269 fs::rename(&from, &to)
271 .with_context(|| format!("moving {} back to {}", from.display(), to.display()))?;
272 engine::crash_point("settle");
273 done.push(rel);
274 }
275 flush(out, &done)
276}
277
278fn free_name(path: &Path) -> PathBuf {
280 let stem = path.file_stem().unwrap_or_default();
281 (2u32..)
282 .map(|n| {
283 let mut name = stem.to_os_string();
284 name.push(format!(" ({n})"));
285 if let Some(ext) = path.extension() {
286 name.push(".");
287 name.push(ext);
288 }
289 path.with_file_name(name)
290 })
291 .find(|p| fs::symlink_metadata(p).is_err())
292 .unwrap_or_else(|| path.to_path_buf())
293}
294
295pub(crate) fn remove(out: &Path) -> Result<()> {
297 let aside = folder(out);
298 match fs::remove_dir_all(&aside) {
300 Err(e) if e.kind() != io::ErrorKind::NotFound => {
301 Err(e).with_context(|| format!("removing {}", aside.display()))
302 }
303 _ => Ok(()),
304 }
305}
306
307fn walk(root: &Path, dir: &Path, files: &mut Vec<PathBuf>) -> Result<()> {
309 for entry in fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
310 let path = entry?.path();
311 if fs::symlink_metadata(&path)?.is_dir() {
312 walk(root, &path, files)?;
313 } else if let Ok(rel) = path.strip_prefix(root) {
314 files.push(rel.to_path_buf());
315 }
316 }
317 Ok(())
318}
319
320fn flush(out: &Path, rels: &[&Path]) -> Result<()> {
324 platform::sync_batch(out).context("flushing moved files to disk")?;
325 if !platform::SYNC_EACH_FILE {
326 return Ok(());
327 }
328 let aside = folder(out);
329 let mut dirs: HashSet<PathBuf> = HashSet::from([out.to_path_buf(), aside.clone()]);
330 for rel in rels {
331 for parent in rel.ancestors().skip(1) {
332 dirs.insert(out.join(parent));
333 dirs.insert(aside.join(parent));
334 }
335 }
336 for d in dirs {
337 if fs::symlink_metadata(&d).is_ok_and(|m| m.is_dir()) {
338 fsutil::sync_dir(&d)?;
339 }
340 }
341 Ok(())
342}