use std::fs;
use std::io;
use std::path::Path;
use std::io::Write;
#[cfg(target_family = "unix")]
use std::os::unix::fs::PermissionsExt;
pub fn ensure_exists<T>(raw: T) -> io::Result<()>
where
T: AsRef<Path>,
{
let path = raw.as_ref();
if path.exists() {
Ok(())
} else {
Err(io::Error::new(
io::ErrorKind::NotFound,
format!("Path [{}] does not exist", path.display()),
))
}
}
pub fn make_executable<T>(p: T) -> io::Result<()>
where
T: AsRef<Path>,
{
if cfg!(unix) {
let mut perms = fs::metadata(p.as_ref())?.permissions();
perms.set_mode(0o755);
fs::set_permissions(p, perms)?;
}
Ok(())
}
pub fn is_executable<T: AsRef<Path>>(path: T) -> io::Result<bool> {
if cfg!(unix) {
let perms = fs::metadata(path.as_ref())?.permissions();
Ok(perms.mode() & 0o111 != 0)
} else {
Ok(true)
}
}
pub fn replace_all<T>(p: T, pattern: &str, to: &str) -> io::Result<()>
where
T: AsRef<Path>,
{
let data = fs::read_to_string(p.as_ref())?;
fs::File::create(p.as_ref())?.write_all(data.replace(pattern, to).as_bytes())?;
Ok(())
}