use std::path::{Path, PathBuf};
use crate::config::{Mode, OnConflict, Options};
use crate::error::FatalError;
pub fn prepare(opts: &Options) -> Result<(PathBuf, PathBuf), FatalError> {
if opts.on_conflict == OnConflict::Overwrite && !opts.force {
return Err(FatalError::OverwriteWithoutForce);
}
if !opts.source.is_dir() {
return Err(FatalError::SourceUnavailable(opts.source.clone()));
}
let source = canonical(&opts.source)?;
overlap(&source, &resolved(&opts.dest))?;
if !opts.dry_run {
std::fs::create_dir_all(&opts.dest).map_err(|e| FatalError::DestinationUnavailable {
path: opts.dest.clone(),
source: e,
})?;
}
let dest = match canonical(&opts.dest) {
Ok(d) => d,
Err(e) if opts.dry_run => {
log::debug!("destination not canonicalizable yet: {e}");
resolved(&opts.dest)
}
Err(e) => return Err(e),
};
overlap(&source, &dest)?;
if !opts.dry_run {
writable(&dest)?;
}
Ok((source, dest))
}
fn overlap(source: &Path, dest: &Path) -> Result<(), FatalError> {
if source == dest || dest.starts_with(source) || source.starts_with(dest) {
return Err(FatalError::Overlap {
source_root: source.to_path_buf(),
dest_root: dest.to_path_buf(),
});
}
Ok(())
}
fn absolute(path: &Path) -> PathBuf {
use std::path::Component;
let joined = if path.is_absolute() {
path.to_path_buf()
} else {
std::env::current_dir()
.map(|cwd| cwd.join(path))
.unwrap_or_else(|_| path.to_path_buf())
};
let mut out = PathBuf::new();
for part in joined.components() {
match part {
Component::CurDir => {}
Component::ParentDir => {
out.pop();
}
other => out.push(other.as_os_str()),
}
}
plain(&out)
}
fn resolved(path: &Path) -> PathBuf {
let absolute = absolute(path);
let mut tail: Vec<&std::ffi::OsStr> = Vec::new();
let mut probe = absolute.as_path();
loop {
if let Ok(real) = probe.canonicalize() {
let mut out = plain(&real);
out.extend(tail.iter().rev());
return out;
}
let (Some(parent), Some(name)) = (probe.parent(), probe.file_name()) else {
return absolute;
};
tail.push(name);
probe = parent;
}
}
fn canonical(path: &Path) -> Result<PathBuf, FatalError> {
path.canonicalize()
.map(|p| plain(&p))
.map_err(|e| FatalError::DestinationUnavailable {
path: path.to_path_buf(),
source: e,
})
}
fn plain(path: &Path) -> PathBuf {
#[cfg(windows)]
{
let s = path.to_string_lossy();
if let Some(rest) = s.strip_prefix(r"\\?\UNC\") {
return PathBuf::from(format!(r"\\{rest}"));
}
if let Some(rest) = s.strip_prefix(r"\\?\") {
return PathBuf::from(rest);
}
}
path.to_path_buf()
}
fn writable(dir: &Path) -> Result<(), FatalError> {
let probe = dir.join(format!("{}probe", crate::scan::TMP_PREFIX));
std::fs::write(&probe, b"").map_err(|e| FatalError::DestinationUnavailable {
path: dir.to_path_buf(),
source: e,
})?;
let _ = std::fs::remove_file(&probe);
Ok(())
}
pub fn check_space(dir: &Path, needed: u64, mode: Mode) -> Result<(), FatalError> {
if mode == Mode::Move {
return Ok(());
}
match free_space(dir) {
Some(available) if available < needed => Err(FatalError::DiskFull { needed, available }),
_ => Ok(()),
}
}
#[cfg(windows)]
pub fn free_space(dir: &Path) -> Option<u64> {
use std::os::windows::ffi::OsStrExt;
#[link(name = "kernel32")]
extern "system" {
fn GetDiskFreeSpaceExW(
lpDirectoryName: *const u16,
lpFreeBytesAvailableToCaller: *mut u64,
lpTotalNumberOfBytes: *mut u64,
lpTotalNumberOfFreeBytes: *mut u64,
) -> i32;
}
let wide: Vec<u16> = dir.as_os_str().encode_wide().chain(Some(0)).collect();
let mut available = 0u64;
let ok = unsafe {
GetDiskFreeSpaceExW(
wide.as_ptr(),
&mut available,
std::ptr::null_mut(),
std::ptr::null_mut(),
)
};
(ok != 0).then_some(available)
}
#[cfg(unix)]
pub fn free_space(dir: &Path) -> Option<u64> {
use std::ffi::CString;
use std::os::unix::ffi::OsStrExt;
let path = CString::new(dir.as_os_str().as_bytes()).ok()?;
let mut stat: libc::statvfs = unsafe { std::mem::zeroed() };
if unsafe { libc::statvfs(path.as_ptr(), &mut stat) } != 0 {
return None;
}
Some(stat.f_bavail as u64 * stat.f_frsize as u64)
}
#[cfg(not(any(unix, windows)))]
pub fn free_space(_dir: &Path) -> Option<u64> {
None
}
#[cfg(test)]
mod tests {
use super::*;
use std::fs;
fn opts(source: PathBuf, dest: PathBuf) -> Options {
Options {
source,
dest,
..Default::default()
}
}
#[test]
fn accepts_disjoint_roots() {
let tmp = tempfile::tempdir().unwrap();
let s = tmp.path().join("s");
fs::create_dir_all(&s).unwrap();
let o = opts(s, tmp.path().join("d"));
assert!(prepare(&o).is_ok());
assert!(o.dest.is_dir(), "destination is created");
}
#[test]
fn rejects_destination_inside_source() {
let tmp = tempfile::tempdir().unwrap();
let s = tmp.path().join("s");
fs::create_dir_all(&s).unwrap();
let o = opts(s.clone(), s.join("out"));
assert!(matches!(prepare(&o), Err(FatalError::Overlap { .. })));
}
#[cfg(unix)]
#[test]
fn rejects_a_destination_that_only_overlaps_once_resolved() {
let tmp = tempfile::tempdir().unwrap();
let s = tmp.path().join("s");
fs::create_dir_all(&s).unwrap();
let link = tmp.path().join("link");
std::os::unix::fs::symlink(&s, &link).unwrap();
let dest = link.join("out");
assert!(matches!(
prepare(&opts(s, dest.clone())),
Err(FatalError::Overlap { .. })
));
assert!(!dest.exists(), "the refused run created the destination");
}
#[cfg(windows)]
#[test]
fn rejects_a_destination_that_only_overlaps_once_resolved() {
let tmp = tempfile::tempdir().unwrap();
let s = tmp.path().join("src");
fs::create_dir_all(&s).unwrap();
let dest = tmp.path().join("SRC").join("out");
assert!(matches!(
prepare(&opts(s, dest.clone())),
Err(FatalError::Overlap { .. })
));
assert!(!dest.exists(), "the refused run created the destination");
}
#[test]
fn rejects_source_inside_destination() {
let tmp = tempfile::tempdir().unwrap();
let d = tmp.path().join("d");
let s = d.join("inner");
fs::create_dir_all(&s).unwrap();
assert!(matches!(
prepare(&opts(s, d)),
Err(FatalError::Overlap { .. })
));
}
#[test]
fn rejects_identical_roots() {
let tmp = tempfile::tempdir().unwrap();
let s = tmp.path().join("s");
fs::create_dir_all(&s).unwrap();
assert!(matches!(
prepare(&opts(s.clone(), s)),
Err(FatalError::Overlap { .. })
));
}
#[test]
fn rejects_a_missing_source() {
let tmp = tempfile::tempdir().unwrap();
assert!(matches!(
prepare(&opts(tmp.path().join("nope"), tmp.path().join("d"))),
Err(FatalError::SourceUnavailable(_))
));
}
#[test]
fn overwrite_demands_force() {
let tmp = tempfile::tempdir().unwrap();
let s = tmp.path().join("s");
fs::create_dir_all(&s).unwrap();
let mut o = opts(s, tmp.path().join("d"));
o.on_conflict = OnConflict::Overwrite;
assert!(matches!(
prepare(&o),
Err(FatalError::OverwriteWithoutForce)
));
o.force = true;
assert!(prepare(&o).is_ok());
}
#[test]
fn reports_free_space_for_a_real_directory() {
let tmp = tempfile::tempdir().unwrap();
let free = free_space(tmp.path()).expect("a temp dir has a filesystem");
assert!(free > 0);
assert!(check_space(tmp.path(), 1, Mode::Copy).is_ok());
assert!(matches!(
check_space(tmp.path(), u64::MAX, Mode::Copy),
Err(FatalError::DiskFull { .. })
));
assert!(check_space(tmp.path(), u64::MAX, Mode::Move).is_ok());
}
}