use std::fs;
use std::io::Write;
use std::path::{Path, PathBuf};
use walkdir::WalkDir;
use crate::error::{Error, Result};
pub fn supports_reflink(src: &Path, at: &Path) -> Result<bool> {
let probe = at.join(".cargo-shared-target-probe");
fs::create_dir_all(&probe).map_err(Error::io("creating a probe directory at", &probe))?;
let answer = probe_inside(src, &probe);
let _ = fs::remove_file(probe.join("a"));
let _ = fs::remove_file(probe.join("b"));
let _ = fs::remove_dir(&probe);
answer
}
fn probe_inside(src: &Path, probe: &Path) -> Result<bool> {
let destination = probe.join("b");
let _ = fs::remove_file(&destination);
let subject = match first_file(src) {
Some(existing) => existing,
None => {
let written = probe.join("a");
let mut file = fs::File::create(&written)
.map_err(Error::io("writing the probe file", &written))?;
file.write_all(&[0u8; 8192])
.map_err(Error::io("writing the probe file", &written))?;
file.sync_all()
.map_err(Error::io("writing the probe file", &written))?;
written
}
};
Ok(reflink_copy::reflink(&subject, &destination).is_ok())
}
fn first_file(src: &Path) -> Option<PathBuf> {
WalkDir::new(src)
.min_depth(1)
.into_iter()
.filter_map(std::result::Result::ok)
.find(|entry| entry.file_type().is_file())
.map(|entry| entry.path().to_path_buf())
}