use std::{
fs::File,
io::{BufWriter, Write},
os::unix::fs::{MetadataExt, PermissionsExt},
path::{Path, PathBuf},
};
use log::info;
use nix::{
errno::Errno,
unistd::{chown, getpid, Gid, Uid},
};
use crate::path_util::AppendToPath;
#[derive(Debug, thiserror::Error)]
pub enum TempfileError {
#[error("path is missing parent directory part")]
MissingParent,
#[error("path is missing file name part")]
MissingFileName,
#[error("IO error while {1} {0:?}: {2:#}")]
IOError(PathBuf, &'static str, std::io::Error),
#[error("IO error while {1} {0:?}: {2:#}")]
IOErrno(PathBuf, &'static str, Errno),
}
pub fn temp_path(target_path: impl AsRef<Path>) -> Result<PathBuf, TempfileError> {
let target_path = target_path.as_ref();
let dir = target_path.parent().ok_or(TempfileError::MissingParent)?;
let file_name = target_path
.file_name()
.ok_or(TempfileError::MissingFileName)?;
let mut file_name: Vec<u8> = file_name.to_string_lossy().to_string().into();
let pid = getpid();
let tid = std::thread::current().id();
write!(&mut file_name, ".tmp~{pid}-{tid:?}").expect("nofail: no IO");
let file_name =
String::from_utf8(file_name).expect("nofail: was a string, with strings appended");
Ok(dir.append(file_name))
}
#[derive(Debug, Clone)]
pub struct TempfileOptions {
pub target_path: PathBuf,
pub retain_tempfile: bool,
pub migrate_access: bool,
}
impl TempfileOptions {
pub fn tempfile(self) -> Result<Tempfile, TempfileError> {
Tempfile::try_from(self)
}
}
#[derive(Debug)]
pub struct Tempfile {
opts: TempfileOptions,
temp_path: PathBuf,
}
impl TryFrom<TempfileOptions> for Tempfile {
type Error = TempfileError;
fn try_from(opts: TempfileOptions) -> Result<Self, TempfileError> {
let temp_path = temp_path(&opts.target_path)?;
Ok(Tempfile { opts, temp_path })
}
}
impl Tempfile {
pub fn temp_path(&self) -> &Path {
&self.temp_path
}
pub fn target_path(&self) -> &Path {
&self.opts.target_path
}
pub fn finish(mut self) -> Result<(), TempfileError> {
self.opts.retain_tempfile = true; let Self {
opts:
TempfileOptions {
ref target_path,
retain_tempfile: _,
migrate_access,
},
ref temp_path,
} = self;
let meta = if migrate_access {
match target_path.metadata() {
Ok(m) => Some(m),
Err(e) => match e.kind() {
std::io::ErrorKind::NotFound => None,
_ => {
return Err(TempfileError::IOError(
target_path.clone(),
"getting metadata on target file",
e,
));
}
},
}
} else {
None
};
if let Some(meta) = meta {
let uid = meta.uid();
let gid = meta.gid();
chown(
temp_path,
Some(Uid::from_raw(uid)),
Some(Gid::from_raw(gid)),
)
.map_err(|e| {
TempfileError::IOErrno(temp_path.clone(), "copying owner/group to new file", e)
})?;
let perms = meta.permissions();
let mode = perms.mode();
std::fs::set_permissions(temp_path, std::fs::Permissions::from_mode(mode)).map_err(
|e| TempfileError::IOError(temp_path.clone(), "copying permissions to new file", e),
)?;
}
std::fs::rename(temp_path, target_path).map_err(|e| {
TempfileError::IOError(
target_path.clone(),
"renaming to target",
e,
)
})?;
Ok(())
}
}
impl Drop for Tempfile {
fn drop(&mut self) {
let Self {
opts:
TempfileOptions {
target_path: _,
retain_tempfile,
migrate_access: _,
},
temp_path,
} = self;
if !*retain_tempfile {
match std::fs::remove_file(&*temp_path) {
Ok(()) => (),
Err(e) => match e.kind() {
std::io::ErrorKind::NotFound => (),
_ => info!("error deleting temporary file {:?}: {e:#}", temp_path),
},
}
}
}
}
pub fn tempfile_unbuffered(
target_path: PathBuf,
migrate_access: bool,
) -> Result<(Tempfile, File), TempfileError> {
let tmp_file = TempfileOptions {
target_path,
retain_tempfile: false,
migrate_access,
}
.tempfile()?;
let temp_path = &tmp_file.temp_path;
let out = File::create(temp_path)
.map_err(|e| TempfileError::IOError(temp_path.clone(), "creating temporary file", e))?;
Ok((tmp_file, out))
}
pub fn tempfile_buffered(
target_path: PathBuf,
migrate_access: bool,
) -> Result<(Tempfile, BufWriter<File>), TempfileError> {
let (temp, file) = tempfile_unbuffered(target_path, migrate_access)?;
Ok((temp, BufWriter::new(file)))
}