use std::{
io::{self, Write},
path::Path,
thread,
time::Duration,
};
use tempfile::NamedTempFile;
pub(crate) fn create(path: &Path, content: &str) -> io::Result<()> {
persist(path, content, false)
}
pub(crate) fn replace(path: &Path, content: &str) -> io::Result<()> {
persist(path, content, true)
}
fn persist(path: &Path, content: &str, overwrite: bool) -> io::Result<()> {
let parent = path.parent().ok_or_else(|| {
io::Error::new(
io::ErrorKind::InvalidInput,
"task path has no parent directory",
)
})?;
let mut temporary = NamedTempFile::new_in(parent)?;
temporary.write_all(content.as_bytes())?;
temporary.as_file_mut().sync_all()?;
if overwrite {
persist_replace(temporary, path)
} else {
temporary
.persist_noclobber(path)
.map(|_| ())
.map_err(|error| error.error)
}
}
fn persist_replace(mut temporary: NamedTempFile, path: &Path) -> io::Result<()> {
let mut attempts = 0;
loop {
match temporary.persist(path) {
Ok(_) => return Ok(()),
Err(error)
if error.error.kind() == io::ErrorKind::PermissionDenied && attempts < 49 =>
{
temporary = error.file;
attempts += 1;
thread::sleep(Duration::from_millis(1));
}
Err(error) => return Err(error.error),
}
}
}