use std::{
io::Write,
mem::swap,
os::unix::fs::{MetadataExt, PermissionsExt},
path::{Path, PathBuf},
sync::Arc,
};
use lazy_static::lazy_static;
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(Arc<Path>, &'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, Copy)]
pub struct TempPathOptions {
pub retain_tempfile: bool,
pub migrate_access: bool,
}
impl Default for TempPathOptions {
fn default() -> Self {
Self {
retain_tempfile: false,
migrate_access: true,
}
}
}
impl TempPathOptions {
pub fn temp_path_for(
self,
target_path: impl Into<Arc<Path>>,
) -> Result<TempPath, TempfileError> {
let target_path = target_path.into();
let temp_path = temp_path(&target_path)?;
Ok(TempPath {
target_path,
options: self,
temp_path,
})
}
}
#[derive(Debug)]
pub struct TempPath {
pub target_path: Arc<Path>,
pub options: TempPathOptions,
pub temp_path: PathBuf,
}
lazy_static! {
static ref EMPTY_PATH: Arc<Path> = PathBuf::from("").into();
}
impl TempPath {
pub fn temp_path(&self) -> &Path {
&self.temp_path
}
pub fn target_path(&self) -> &Arc<Path> {
&self.target_path
}
pub fn persist(mut self) -> Result<Arc<Path>, TempfileError> {
let Self {
target_path: _,
options:
TempPathOptions {
retain_tempfile: _,
migrate_access,
},
ref temp_path,
} = self;
self.options.retain_tempfile = true;
let target_path = {
let mut target_path = EMPTY_PATH.clone();
swap(&mut target_path, &mut self.target_path);
target_path
};
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().into(),
"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(target_path)
}
}
impl Drop for TempPath {
fn drop(&mut self) {
let Self {
target_path: _,
options:
TempPathOptions {
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),
},
}
}
}
}