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    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
58/// Refuses, before anything is touched, what would keep the files `found`
59/// from being moved aside.
60pub(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
101/// Moves every file at the path of an entry of `job` into the folder, then
102/// flushes the moves. A resume runs it again until the journal says it is
103/// done; a file already moved is no longer at its path, so it moves once.
104pub(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        // The open checked the way to every entry; this is the way into
121        // the folder, which a crashed run left for anyone to change.
122        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        // A rename moves a link itself, never what it points to.
140        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
154/// Moves the files set aside back to their paths, for a restore. A file
155/// whose path is taken stays in the folder, unless `over`: in place, what
156/// was extracted there may be the only copy of that entry. Returns how many
157/// stay; the folder is deleted when none do.
158pub(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
197/// Once every entry is extracted, puts back the existing files the person
198/// chose to keep: over what was extracted at their paths, or beside it with
199/// the extracted copy renamed. Each step is a rename a rerun finds done or
200/// not, so after a crash this runs again until it completes. Nothing is
201/// deleted here; whatever can't go back stays in the folder with an error,
202/// before [`remove`] could take it.
203pub(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            // Put back by an earlier run that stopped before finishing.
211            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        // A rename over the extracted file replaces it in one step.
232        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
240/// `report (2).pdf`, or the first such name not taken, beside `path`.
241fn 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
257/// Deletes the files set aside, once the extraction is complete.
258pub(crate) fn remove(out: &Path) -> Result<()> {
259    let aside = folder(out);
260    // Never follows a link: one in the folder is removed, not its target.
261    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
269/// The files and links under `dir`, relative to `root`.
270fn 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
282/// Makes the renames of `rels` between the output and the folder durable.
283/// The journal is about to say they happened, and a resume that believed it
284/// while a power cut had undone one would delete a file of the person's.
285fn 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}