use std::collections::HashSet;
use std::fs;
use std::io;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use crate::archive::Kind;
use crate::engine::{self, Job};
use crate::journal::Replace;
use crate::{fsutil, platform};
pub const FOLDER: &str = ".hatchzip-replaced";
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Choices {
pub keep: Vec<PathBuf>,
pub both: Vec<PathBuf>,
}
pub fn folder(out: &Path) -> PathBuf {
out.join(FOLDER)
}
pub(crate) fn found(job: &Job, out: &Path) -> Vec<PathBuf> {
if !out.exists() {
return Vec::new();
}
job.units
.iter()
.flat_map(|u| &u.items)
.filter(|i| i.kind != Kind::Dir)
.filter(|i| fs::symlink_metadata(out.join(&i.path)).is_ok_and(|m| !m.is_dir()))
.map(|i| i.path.clone())
.collect()
}
pub(crate) fn check(job: &Job, out: &Path, found: &[PathBuf]) -> Result<()> {
let named = |p: &Path| {
p.components()
.next()
.is_some_and(|c| c.as_os_str().to_string_lossy().eq_ignore_ascii_case(FOLDER))
};
if let Some(item) = job
.units
.iter()
.flat_map(|u| &u.items)
.find(|i| named(&i.path))
{
bail!(
"the archive contains '{}', but HatchZip uses the name {FOLDER} for the files it \
replaces, so existing files cannot be replaced in this extraction. Extract to an \
empty folder instead. Nothing was modified",
item.path.display()
);
}
let aside = folder(out);
if fs::symlink_metadata(&aside).is_ok() {
bail!(
"{} already exists, so existing files cannot be moved there. It may hold files \
replaced by an earlier extraction; move its contents elsewhere, delete it, then try \
again. Nothing was modified",
aside.display()
);
}
for rel in found {
if platform::path_len(&aside.join(rel)) > platform::MAX_PATH_LEN {
bail!(
"{} cannot be replaced: moving it into {} would make its path longer than this \
system allows. Nothing was modified. Extract to a folder with a shorter path",
out.join(rel).display(),
aside.display()
);
}
}
if let Some((a, b)) = case_pair(found)
&& !engine::keeps_case_apart(out)
{
bail!(
"'{}' and '{}' differ only in case, and {} is not known to keep such names apart, so \
they cannot be moved aside to be replaced. Nothing was modified. Extract to an empty \
folder or move them first",
a.display(),
b.display(),
out.display()
);
}
Ok(())
}
fn case_pair(paths: &[PathBuf]) -> Option<(&Path, &Path)> {
let mut names: Vec<(String, &Path)> = paths
.iter()
.flat_map(|p| p.ancestors())
.filter(|p| !p.as_os_str().is_empty())
.map(|p| (p.to_string_lossy().to_lowercase(), p))
.collect();
names.sort_unstable();
names.dedup();
names
.windows(2)
.find(|w| w[0].0 == w[1].0)
.map(|w| (w[0].1, w[1].1))
}
pub(crate) fn set_aside(job: &Job, out: &Path) -> Result<()> {
let aside = folder(out);
if let Err(e) = fs::create_dir(&aside)
&& e.kind() != io::ErrorKind::AlreadyExists
{
return Err(e).with_context(|| format!("creating {}", aside.display()));
}
if !fs::symlink_metadata(&aside).is_ok_and(|m| m.is_dir()) {
bail!(
"{} is not a folder, so existing files cannot be moved there. Nothing was extracted",
aside.display()
);
}
for rel in found(job, out) {
let from = out.join(&rel);
let to = aside.join(&rel);
if let Some(via) = engine::link_on_the_way(&aside, &rel) {
bail!(
"{} is a link, and {} would be moved through it. Nothing was extracted",
aside.join(via).display(),
from.display()
);
}
if let Some(parent) = to.parent() {
fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
}
if fs::symlink_metadata(&to).is_ok() {
bail!(
"{} cannot be moved aside: {} already exists. Nothing was extracted",
from.display(),
to.display()
);
}
fs::rename(&from, &to)
.with_context(|| format!("moving {} to {}", from.display(), to.display()))?;
engine::crash_point("set-aside");
}
let rels: Vec<&Path> = job
.units
.iter()
.flat_map(|u| &u.items)
.filter(|i| i.kind != Kind::Dir)
.map(|i| i.path.as_path())
.collect();
flush(out, &rels)
}
pub(crate) fn put_back(out: &Path, over: bool) -> Result<usize> {
let aside = folder(out);
if !fs::symlink_metadata(&aside).is_ok_and(|m| m.is_dir()) {
return Ok(0);
}
let mut files = Vec::new();
walk(&aside, &aside, &mut files)?;
let mut stay = 0;
for rel in &files {
let from = aside.join(rel);
let to = out.join(rel);
if engine::link_on_the_way(out, rel).is_some() {
stay += 1;
continue;
}
match fs::symlink_metadata(&to) {
Err(e) if e.kind() == io::ErrorKind::NotFound => {
if let Some(parent) = to.parent() {
fs::create_dir_all(parent)
.with_context(|| format!("creating {}", parent.display()))?;
}
}
Ok(m) if over && !m.is_dir() => {}
_ => {
stay += 1;
continue;
}
}
fs::rename(&from, &to)
.with_context(|| format!("moving {} back to {}", from.display(), to.display()))?;
}
let rels: Vec<&Path> = files.iter().map(PathBuf::as_path).collect();
flush(out, &rels)?;
if stay == 0 {
remove(out)?;
}
Ok(stay)
}
pub(crate) fn settle(out: &Path, r: &Replace) -> Result<()> {
let aside = folder(out);
let chosen = r.keep.iter().map(|p| (p, false));
let mut done: Vec<&Path> = Vec::new();
for (rel, both) in chosen.chain(r.both.iter().map(|p| (p, true))) {
let from = aside.join(rel);
if fs::symlink_metadata(&from).is_err() {
continue;
}
let to = out.join(rel);
if let Some(via) = engine::link_on_the_way(out, rel) {
bail!(
"{} could not be put back: {} is a link. It is kept in {}. Remove the link, then \
resume the extraction to finish",
to.display(),
out.join(via).display(),
aside.display()
);
}
if let Some(parent) = to.parent() {
fs::create_dir_all(parent).with_context(|| format!("creating {}", parent.display()))?;
}
if both && fs::symlink_metadata(&to).is_ok() {
let beside = free_name(&to);
fs::rename(&to, &beside)
.with_context(|| format!("moving {} to {}", to.display(), beside.display()))?;
}
fs::rename(&from, &to)
.with_context(|| format!("moving {} back to {}", from.display(), to.display()))?;
engine::crash_point("settle");
done.push(rel);
}
flush(out, &done)
}
fn free_name(path: &Path) -> PathBuf {
let stem = path.file_stem().unwrap_or_default();
(2u32..)
.map(|n| {
let mut name = stem.to_os_string();
name.push(format!(" ({n})"));
if let Some(ext) = path.extension() {
name.push(".");
name.push(ext);
}
path.with_file_name(name)
})
.find(|p| fs::symlink_metadata(p).is_err())
.unwrap_or_else(|| path.to_path_buf())
}
pub(crate) fn remove(out: &Path) -> Result<()> {
let aside = folder(out);
match fs::remove_dir_all(&aside) {
Err(e) if e.kind() != io::ErrorKind::NotFound => {
Err(e).with_context(|| format!("removing {}", aside.display()))
}
_ => Ok(()),
}
}
fn walk(root: &Path, dir: &Path, files: &mut Vec<PathBuf>) -> Result<()> {
for entry in fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))? {
let path = entry?.path();
if fs::symlink_metadata(&path)?.is_dir() {
walk(root, &path, files)?;
} else if let Ok(rel) = path.strip_prefix(root) {
files.push(rel.to_path_buf());
}
}
Ok(())
}
fn flush(out: &Path, rels: &[&Path]) -> Result<()> {
platform::sync_batch(out).context("flushing moved files to disk")?;
if !platform::SYNC_EACH_FILE {
return Ok(());
}
let aside = folder(out);
let mut dirs: HashSet<PathBuf> = HashSet::from([out.to_path_buf(), aside.clone()]);
for rel in rels {
for parent in rel.ancestors().skip(1) {
dirs.insert(out.join(parent));
dirs.insert(aside.join(parent));
}
}
for d in dirs {
if fs::symlink_metadata(&d).is_ok_and(|m| m.is_dir()) {
fsutil::sync_dir(&d)?;
}
}
Ok(())
}