Skip to main content

hatchzip_core/
replace.rs

1//! Extracting over files that are already in the output folder.
2//!
3//! A resumed run deletes whatever sits at the paths of its uncommitted
4//! entries, which is only safe because the run put it there. So before an
5//! extraction that replaces files extracts anything, it moves every file at
6//! the path of an entry into [`FOLDER`] inside the output, keeping its path.
7//! A rename on the same filesystem takes no space and leaves the file whole,
8//! so a restore can put it back. Only a completed extraction deletes them.
9//!
10//! The journal records `replace` before the first rename, and `moved` only
11//! once every rename is flushed. Until then nothing is extracted, so a
12//! resume deletes nothing at those paths and finishes the moves first.
13
14use 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
26/// Where replaced files wait inside the output folder until the extraction
27/// completes. An archive with an entry of this name at its root can't
28/// replace files, or that entry would be extracted among them.
29pub const FOLDER: &str = ".hatchzip-replaced";
30
31/// What happens to each existing file an extraction finds at the path of
32/// an entry. Every one not listed is replaced.
33#[derive(Clone, Debug, Default, PartialEq, Eq)]
34pub struct Choices {
35    /// Stay as they are. The archive's copy is extracted, then dropped.
36    pub keep: Vec<PathBuf>,
37    /// Stay as they are, with the archive's copy beside them under a new
38    /// name, such as `report (2).pdf`.
39    pub both: Vec<PathBuf>,
40}
41
42pub fn folder(out: &Path) -> PathBuf {
43    out.join(FOLDER)
44}
45
46/// Files and links at the paths entries of `job` are extracted to, relative
47/// to `out`. A folder at one of them is refused when the archive is opened.
48pub(crate) fn found(job: &Job, out: &Path) -> Vec<PathBuf> {
49    // Nothing can be under a folder that isn't there, and looking for every
50    // entry below it costs a failing stat each on Windows.
51    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
63/// Refuses, before anything is touched, what would keep the files `found`
64/// from being moved aside.
65pub(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    // The folder isn't there yet, so it will take after the output, which can
104    // ignore case where a folder inside doesn't. The second of a pair would
105    // fail to move, after the journal is written and the first has moved.
106    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
121/// Two of `paths`, or of the folders they are in, that differ only in case.
122/// Folders count here: merged in the folder of replaced files, what a restore
123/// puts back would land in the wrong one.
124fn 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| (p.to_string_lossy().to_lowercase(), 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
139/// Moves every file at the path of an entry of `job` into the folder, then
140/// flushes the moves. A resume runs it again until the journal says it is
141/// done; a file already moved is no longer at its path, so it moves once.
142pub(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        // The open checked the way to every entry; this is the way into
159        // the folder, which a crashed run left for anyone to change.
160        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        // A rename moves a link itself, never what it points to.
178        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
192/// Moves the files set aside back to their paths, for a restore. A file
193/// whose path is taken stays in the folder, unless `over`: in place, what
194/// was extracted there may be the only copy of that entry. Returns how many
195/// stay; the folder is deleted when none do.
196pub(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
235/// Once every entry is extracted, puts back the existing files the person
236/// chose to keep: over what was extracted at their paths, or beside it with
237/// the extracted copy renamed. Each step is a rename a rerun finds done or
238/// not, so after a crash this runs again until it completes. Nothing is
239/// deleted here; whatever can't go back stays in the folder with an error,
240/// before [`remove`] could take it.
241pub(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            // Put back by an earlier run that stopped before finishing.
249            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        // A rename over the extracted file replaces it in one step.
270        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
278/// `report (2).pdf`, or the first such name not taken, beside `path`.
279fn 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
295/// Deletes the files set aside, once the extraction is complete.
296pub(crate) fn remove(out: &Path) -> Result<()> {
297    let aside = folder(out);
298    // Never follows a link: one in the folder is removed, not its target.
299    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
307/// The files and links under `dir`, relative to `root`.
308fn 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
320/// Makes the renames of `rels` between the output and the folder durable.
321/// The journal is about to say they happened, and a resume that believed it
322/// while a power cut had undone one would delete a file of the person's.
323fn 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}