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    Ok(())
104}
105
106/// Moves every file at the path of an entry of `job` into the folder, then
107/// flushes the moves. A resume runs it again until the journal says it is
108/// done; a file already moved is no longer at its path, so it moves once.
109pub(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        // The open checked the way to every entry; this is the way into
126        // the folder, which a crashed run left for anyone to change.
127        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        // A rename moves a link itself, never what it points to.
145        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
159/// Moves the files set aside back to their paths, for a restore. A file
160/// whose path is taken stays in the folder, unless `over`: in place, what
161/// was extracted there may be the only copy of that entry. Returns how many
162/// stay; the folder is deleted when none do.
163pub(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
202/// Once every entry is extracted, puts back the existing files the person
203/// chose to keep: over what was extracted at their paths, or beside it with
204/// the extracted copy renamed. Each step is a rename a rerun finds done or
205/// not, so after a crash this runs again until it completes. Nothing is
206/// deleted here; whatever can't go back stays in the folder with an error,
207/// before [`remove`] could take it.
208pub(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            // Put back by an earlier run that stopped before finishing.
216            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        // A rename over the extracted file replaces it in one step.
237        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
245/// `report (2).pdf`, or the first such name not taken, beside `path`.
246fn 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
262/// Deletes the files set aside, once the extraction is complete.
263pub(crate) fn remove(out: &Path) -> Result<()> {
264    let aside = folder(out);
265    // Never follows a link: one in the folder is removed, not its target.
266    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
274/// The files and links under `dir`, relative to `root`.
275fn 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
287/// Makes the renames of `rels` between the output and the folder durable.
288/// The journal is about to say they happened, and a resume that believed it
289/// while a power cut had undone one would delete a file of the person's.
290fn 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}