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 job.units
50 .iter()
51 .flat_map(|u| &u.items)
52 .filter(|i| i.kind != Kind::Dir)
53 .filter(|i| fs::symlink_metadata(out.join(&i.path)).is_ok_and(|m| !m.is_dir()))
54 .map(|i| i.path.clone())
55 .collect()
56}
57
58pub(crate) fn check(job: &Job, out: &Path, found: &[PathBuf]) -> Result<()> {
61 let named = |p: &Path| {
62 p.components()
63 .next()
64 .is_some_and(|c| c.as_os_str().to_string_lossy().eq_ignore_ascii_case(FOLDER))
65 };
66 if let Some(item) = job
67 .units
68 .iter()
69 .flat_map(|u| &u.items)
70 .find(|i| named(&i.path))
71 {
72 bail!(
73 "the archive contains '{}', but HatchZip uses the name {FOLDER} for the files it \
74 replaces, so existing files cannot be replaced in this extraction. Extract to an \
75 empty folder instead. Nothing was modified",
76 item.path.display()
77 );
78 }
79 let aside = folder(out);
80 if fs::symlink_metadata(&aside).is_ok() {
81 bail!(
82 "{} already exists, so existing files cannot be moved there. It may hold files \
83 replaced by an earlier extraction; move its contents elsewhere, delete it, then try \
84 again. Nothing was modified",
85 aside.display()
86 );
87 }
88 for rel in found {
89 if platform::path_len(&aside.join(rel)) > platform::MAX_PATH_LEN {
90 bail!(
91 "{} cannot be replaced: moving it into {} would make its path longer than this \
92 system allows. Nothing was modified. Extract to a folder with a shorter path",
93 out.join(rel).display(),
94 aside.display()
95 );
96 }
97 }
98 Ok(())
99}
100
101pub(crate) fn set_aside(job: &Job, out: &Path) -> Result<()> {
105 let aside = folder(out);
106 if let Err(e) = fs::create_dir(&aside)
107 && e.kind() != io::ErrorKind::AlreadyExists
108 {
109 return Err(e).with_context(|| format!("creating {}", aside.display()));
110 }
111 if !fs::symlink_metadata(&aside).is_ok_and(|m| m.is_dir()) {
112 bail!(
113 "{} is not a folder, so existing files cannot be moved there. Nothing was extracted",
114 aside.display()
115 );
116 }
117 for rel in found(job, out) {
118 let from = out.join(&rel);
119 let to = aside.join(&rel);
120 if let Some(via) = engine::link_on_the_way(&aside, &rel) {
123 bail!(
124 "{} is a link, and {} would be moved through it. Nothing was extracted",
125 aside.join(via).display(),
126 from.display()
127 );
128 }
129 if let Some(parent) = to.parent() {
130 fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
131 }
132 if fs::symlink_metadata(&to).is_ok() {
133 bail!(
134 "{} cannot be moved aside: {} already exists. Nothing was extracted",
135 from.display(),
136 to.display()
137 );
138 }
139 fs::rename(&from, &to)
141 .with_context(|| format!("moving {} to {}", from.display(), to.display()))?;
142 engine::crash_point("set-aside");
143 }
144 let rels: Vec<&Path> = job
145 .units
146 .iter()
147 .flat_map(|u| &u.items)
148 .filter(|i| i.kind != Kind::Dir)
149 .map(|i| i.path.as_path())
150 .collect();
151 flush(out, &rels)
152}
153
154pub(crate) fn put_back(out: &Path, over: bool) -> Result<usize> {
159 let aside = folder(out);
160 if !fs::symlink_metadata(&aside).is_ok_and(|m| m.is_dir()) {
161 return Ok(0);
162 }
163 let mut files = Vec::new();
164 walk(&aside, &aside, &mut files)?;
165 let mut stay = 0;
166 for rel in &files {
167 let from = aside.join(rel);
168 let to = out.join(rel);
169 if engine::link_on_the_way(out, rel).is_some() {
170 stay += 1;
171 continue;
172 }
173 match fs::symlink_metadata(&to) {
174 Err(e) if e.kind() == io::ErrorKind::NotFound => {
175 if let Some(parent) = to.parent() {
176 fs::create_dir_all(parent)
177 .with_context(|| format!("creating {}", parent.display()))?;
178 }
179 }
180 Ok(m) if over && !m.is_dir() => {}
181 _ => {
182 stay += 1;
183 continue;
184 }
185 }
186 fs::rename(&from, &to)
187 .with_context(|| format!("moving {} back to {}", from.display(), to.display()))?;
188 }
189 let rels: Vec<&Path> = files.iter().map(PathBuf::as_path).collect();
190 flush(out, &rels)?;
191 if stay == 0 {
192 remove(out)?;
193 }
194 Ok(stay)
195}
196
197pub(crate) fn settle(out: &Path, r: &Replace) -> Result<()> {
204 let aside = folder(out);
205 let chosen = r.keep.iter().map(|p| (p, false));
206 let mut done: Vec<&Path> = Vec::new();
207 for (rel, both) in chosen.chain(r.both.iter().map(|p| (p, true))) {
208 let from = aside.join(rel);
209 if fs::symlink_metadata(&from).is_err() {
210 continue;
212 }
213 let to = out.join(rel);
214 if let Some(via) = engine::link_on_the_way(out, rel) {
215 bail!(
216 "{} could not be put back: {} is a link. It is kept in {}. Remove the link, then \
217 resume the extraction to finish",
218 to.display(),
219 out.join(via).display(),
220 aside.display()
221 );
222 }
223 if let Some(parent) = to.parent() {
224 fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
225 }
226 if both && fs::symlink_metadata(&to).is_ok() {
227 let beside = free_name(&to);
228 fs::rename(&to, &beside)
229 .with_context(|| format!("moving {} to {}", to.display(), beside.display()))?;
230 }
231 fs::rename(&from, &to)
233 .with_context(|| format!("moving {} back to {}", from.display(), to.display()))?;
234 engine::crash_point("settle");
235 done.push(rel);
236 }
237 flush(out, &done)
238}
239
240fn free_name(path: &Path) -> PathBuf {
242 let stem = path.file_stem().unwrap_or_default();
243 (2u32..)
244 .map(|n| {
245 let mut name = stem.to_os_string();
246 name.push(format!(" ({n})"));
247 if let Some(ext) = path.extension() {
248 name.push(".");
249 name.push(ext);
250 }
251 path.with_file_name(name)
252 })
253 .find(|p| fs::symlink_metadata(p).is_err())
254 .unwrap_or_else(|| path.to_path_buf())
255}
256
257pub(crate) fn remove(out: &Path) -> Result<()> {
259 let aside = folder(out);
260 match fs::remove_dir_all(&aside) {
262 Err(e) if e.kind() != io::ErrorKind::NotFound => {
263 Err(e).with_context(|| format!("removing {}", aside.display()))
264 }
265 _ => Ok(()),
266 }
267}
268
269fn walk(root: &Path, dir: &Path, files: &mut Vec<PathBuf>) -> Result<()> {
271 for entry in fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
272 let path = entry?.path();
273 if fs::symlink_metadata(&path)?.is_dir() {
274 walk(root, &path, files)?;
275 } else if let Ok(rel) = path.strip_prefix(root) {
276 files.push(rel.to_path_buf());
277 }
278 }
279 Ok(())
280}
281
282fn flush(out: &Path, rels: &[&Path]) -> Result<()> {
286 platform::sync_batch(out).context("flushing moved files to disk")?;
287 if !platform::SYNC_EACH_FILE {
288 return Ok(());
289 }
290 let aside = folder(out);
291 let mut dirs: HashSet<PathBuf> = HashSet::from([out.to_path_buf(), aside.clone()]);
292 for rel in rels {
293 for parent in rel.ancestors().skip(1) {
294 dirs.insert(out.join(parent));
295 dirs.insert(aside.join(parent));
296 }
297 }
298 for d in dirs {
299 if fs::symlink_metadata(&d).is_ok_and(|m| m.is_dir()) {
300 fsutil::sync_dir(&d)?;
301 }
302 }
303 Ok(())
304}