use std::fs::{self, DirBuilder, OpenOptions};
use std::io::{self, Write};
use std::path::Path;
use std::process;
use std::time::{SystemTime, UNIX_EPOCH};
pub fn private_mkdir(directory: &Path) -> io::Result<()> {
let mut missing = Vec::new();
let mut current = directory;
while !current.exists() {
missing.push(current);
match current.parent() {
Some(parent) => current = parent,
None => break,
}
}
let builder = private_builder();
for level in missing.into_iter().rev() {
match builder.create(level) {
Err(error) if error.kind() != io::ErrorKind::AlreadyExists => return Err(error),
_ => {}
}
}
Ok(())
}
#[cfg(unix)]
fn private_builder() -> DirBuilder {
use std::os::unix::fs::DirBuilderExt;
let mut builder = DirBuilder::new();
builder.mode(0o700);
builder
}
#[cfg(not(unix))]
fn private_builder() -> DirBuilder {
DirBuilder::new()
}
#[cfg(unix)]
pub fn private() -> OpenOptions {
use std::os::unix::fs::OpenOptionsExt;
let mut options = OpenOptions::new();
options.mode(0o600);
options
}
#[cfg(not(unix))]
pub fn private() -> OpenOptions {
OpenOptions::new()
}
pub fn atomic_write(file: &Path, text: &str, sync: bool) -> io::Result<()> {
let parent = file.parent().unwrap_or(Path::new("."));
private_mkdir(parent)?;
let mut attempt = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_or(0, |since| since.subsec_nanos());
let (temp, mut handle) = loop {
let temp = parent.join(format!(".neosian-tmp-{}-{attempt:08x}", process::id()));
match private().write(true).create_new(true).open(&temp) {
Ok(handle) => break (temp, handle),
Err(error) if error.kind() == io::ErrorKind::AlreadyExists => attempt += 1,
Err(error) => return Err(error),
}
};
let written = handle
.write_all(text.as_bytes())
.and_then(|()| if sync { handle.sync_all() } else { Ok(()) })
.and_then(|()| fs::rename(&temp, file));
if written.is_err() {
let _ = fs::remove_file(&temp);
}
written
}
pub fn append_line(file: &Path, text: &str, sync: bool) -> io::Result<()> {
if let Some(parent) = file.parent() {
private_mkdir(parent)?;
}
let mut handle = private().append(true).create(true).open(file)?;
handle.write_all(text.as_bytes())?;
if sync { handle.sync_all() } else { Ok(()) }
}