use std::{fs, io, path::Path};
pub fn copy_and_replace<P, Q>(from: P, to: Q) -> io::Result<()>
where
P: AsRef<Path>,
Q: AsRef<Path>,
{
copy_and_delete(from, to, true)
}
pub fn copy_without_replace<P, Q>(from: P, to: Q) -> io::Result<()>
where
P: AsRef<Path>,
Q: AsRef<Path>,
{
copy_and_delete(from, to, false)
}
fn copy_and_delete<P, Q>(from: P, to: Q, replace: bool) -> io::Result<()>
where
P: AsRef<Path>,
Q: AsRef<Path>,
{
let from = from.as_ref();
if from.is_dir() {
return copy_dir(from, to, replace).and(remove_dir_all::remove_dir_all(from));
} else if replace || !to.as_ref().exists() {
fs::copy(from, to)?;
}
if replace {
fs::remove_file(from)?;
}
Ok(())
}
fn copy_dir<P, Q>(from: P, to: Q, replace: bool) -> io::Result<()>
where
P: AsRef<Path>,
Q: AsRef<Path>,
{
fs::create_dir_all(&to)?;
for entry in from.as_ref().read_dir()? {
let entry = entry?;
let kind = entry.file_type()?;
let from = entry.path();
let to = to.as_ref().join(entry.file_name());
if kind.is_dir() {
copy_dir(&from, &to, replace)?;
} else if replace || !to.exists() {
fs::copy(&from, &to)?;
}
}
Ok(())
}