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 Ok(())
104}
105
106pub(crate) fn set_aside(job: &Job, out: &Path) -> Result<()> {
110 let aside = folder(out);
111 if let Err(e) = fs::create_dir(&aside)
112 && e.kind() != io::ErrorKind::AlreadyExists
113 {
114 return Err(e).with_context(|| format!("creating {}", aside.display()));
115 }
116 if !fs::symlink_metadata(&aside).is_ok_and(|m| m.is_dir()) {
117 bail!(
118 "{} is not a folder, so existing files cannot be moved there. Nothing was extracted",
119 aside.display()
120 );
121 }
122 for rel in found(job, out) {
123 let from = out.join(&rel);
124 let to = aside.join(&rel);
125 if let Some(via) = engine::link_on_the_way(&aside, &rel) {
128 bail!(
129 "{} is a link, and {} would be moved through it. Nothing was extracted",
130 aside.join(via).display(),
131 from.display()
132 );
133 }
134 if let Some(parent) = to.parent() {
135 fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
136 }
137 if fs::symlink_metadata(&to).is_ok() {
138 bail!(
139 "{} cannot be moved aside: {} already exists. Nothing was extracted",
140 from.display(),
141 to.display()
142 );
143 }
144 fs::rename(&from, &to)
146 .with_context(|| format!("moving {} to {}", from.display(), to.display()))?;
147 engine::crash_point("set-aside");
148 }
149 let rels: Vec<&Path> = job
150 .units
151 .iter()
152 .flat_map(|u| &u.items)
153 .filter(|i| i.kind != Kind::Dir)
154 .map(|i| i.path.as_path())
155 .collect();
156 flush(out, &rels)
157}
158
159pub(crate) fn put_back(out: &Path, over: bool) -> Result<usize> {
164 let aside = folder(out);
165 if !fs::symlink_metadata(&aside).is_ok_and(|m| m.is_dir()) {
166 return Ok(0);
167 }
168 let mut files = Vec::new();
169 walk(&aside, &aside, &mut files)?;
170 let mut stay = 0;
171 for rel in &files {
172 let from = aside.join(rel);
173 let to = out.join(rel);
174 if engine::link_on_the_way(out, rel).is_some() {
175 stay += 1;
176 continue;
177 }
178 match fs::symlink_metadata(&to) {
179 Err(e) if e.kind() == io::ErrorKind::NotFound => {
180 if let Some(parent) = to.parent() {
181 fs::create_dir_all(parent)
182 .with_context(|| format!("creating {}", parent.display()))?;
183 }
184 }
185 Ok(m) if over && !m.is_dir() => {}
186 _ => {
187 stay += 1;
188 continue;
189 }
190 }
191 fs::rename(&from, &to)
192 .with_context(|| format!("moving {} back to {}", from.display(), to.display()))?;
193 }
194 let rels: Vec<&Path> = files.iter().map(PathBuf::as_path).collect();
195 flush(out, &rels)?;
196 if stay == 0 {
197 remove(out)?;
198 }
199 Ok(stay)
200}
201
202pub(crate) fn settle(out: &Path, r: &Replace) -> Result<()> {
209 let aside = folder(out);
210 let chosen = r.keep.iter().map(|p| (p, false));
211 let mut done: Vec<&Path> = Vec::new();
212 for (rel, both) in chosen.chain(r.both.iter().map(|p| (p, true))) {
213 let from = aside.join(rel);
214 if fs::symlink_metadata(&from).is_err() {
215 continue;
217 }
218 let to = out.join(rel);
219 if let Some(via) = engine::link_on_the_way(out, rel) {
220 bail!(
221 "{} could not be put back: {} is a link. It is kept in {}. Remove the link, then \
222 resume the extraction to finish",
223 to.display(),
224 out.join(via).display(),
225 aside.display()
226 );
227 }
228 if let Some(parent) = to.parent() {
229 fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
230 }
231 if both && fs::symlink_metadata(&to).is_ok() {
232 let beside = free_name(&to);
233 fs::rename(&to, &beside)
234 .with_context(|| format!("moving {} to {}", to.display(), beside.display()))?;
235 }
236 fs::rename(&from, &to)
238 .with_context(|| format!("moving {} back to {}", from.display(), to.display()))?;
239 engine::crash_point("settle");
240 done.push(rel);
241 }
242 flush(out, &done)
243}
244
245fn free_name(path: &Path) -> PathBuf {
247 let stem = path.file_stem().unwrap_or_default();
248 (2u32..)
249 .map(|n| {
250 let mut name = stem.to_os_string();
251 name.push(format!(" ({n})"));
252 if let Some(ext) = path.extension() {
253 name.push(".");
254 name.push(ext);
255 }
256 path.with_file_name(name)
257 })
258 .find(|p| fs::symlink_metadata(p).is_err())
259 .unwrap_or_else(|| path.to_path_buf())
260}
261
262pub(crate) fn remove(out: &Path) -> Result<()> {
264 let aside = folder(out);
265 match fs::remove_dir_all(&aside) {
267 Err(e) if e.kind() != io::ErrorKind::NotFound => {
268 Err(e).with_context(|| format!("removing {}", aside.display()))
269 }
270 _ => Ok(()),
271 }
272}
273
274fn walk(root: &Path, dir: &Path, files: &mut Vec<PathBuf>) -> Result<()> {
276 for entry in fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
277 let path = entry?.path();
278 if fs::symlink_metadata(&path)?.is_dir() {
279 walk(root, &path, files)?;
280 } else if let Ok(rel) = path.strip_prefix(root) {
281 files.push(rel.to_path_buf());
282 }
283 }
284 Ok(())
285}
286
287fn flush(out: &Path, rels: &[&Path]) -> Result<()> {
291 platform::sync_batch(out).context("flushing moved files to disk")?;
292 if !platform::SYNC_EACH_FILE {
293 return Ok(());
294 }
295 let aside = folder(out);
296 let mut dirs: HashSet<PathBuf> = HashSet::from([out.to_path_buf(), aside.clone()]);
297 for rel in rels {
298 for parent in rel.ancestors().skip(1) {
299 dirs.insert(out.join(parent));
300 dirs.insert(aside.join(parent));
301 }
302 }
303 for d in dirs {
304 if fs::symlink_metadata(&d).is_ok_and(|m| m.is_dir()) {
305 fsutil::sync_dir(&d)?;
306 }
307 }
308 Ok(())
309}