use std::{
fs::File,
io::{BufWriter, Write},
ops::{Deref, DerefMut},
os::unix::fs::OpenOptionsExt,
path::Path,
sync::Arc,
};
use crate::temp_path::{TempPath, TempPathOptions, TempfileError};
#[derive(Debug, Clone, Copy)]
pub enum Permissions {
Public,
Private,
Mode(u32),
}
#[derive(Debug)]
pub struct TempFile<F: Write> {
temp_path: TempPath,
file: F,
}
impl<F: Write> Deref for TempFile<F> {
type Target = F;
fn deref(&self) -> &Self::Target {
&self.file
}
}
impl<F: Write> DerefMut for TempFile<F> {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.file
}
}
impl<F: Write> TempFile<F> {
pub fn into_constituents(self) -> (TempPath, F) {
let Self { temp_path, file } = self;
(temp_path, file)
}
pub fn temp_path(&self) -> &Path {
self.temp_path.temp_path()
}
pub fn target_path(&self) -> &Path {
self.temp_path.target_path()
}
pub fn persist(self) -> Result<Arc<Path>, TempfileError> {
let TempFile {
temp_path,
mut file,
} = self;
file.flush().map_err(|e| {
TempfileError::IOError(
temp_path.temp_path().to_owned().into(),
"flushing temporary file",
e,
)
})?;
drop(file);
temp_path.persist()
}
}
impl TempPathOptions {
pub fn unbuffered_temp_file_for(
self,
target_path: impl Into<Arc<Path>>,
permissions: Option<Permissions>,
) -> Result<TempFile<File>, TempfileError> {
let temp_path = self.temp_path_for(target_path)?;
let path = &temp_path.temp_path;
let mut opts = File::options();
opts.create(true).write(true);
if let Some(permissions) = permissions {
let mode = match permissions {
Permissions::Public => 0o666,
Permissions::Private => 0o600,
Permissions::Mode(val) => val,
};
opts.mode(mode);
}
let file = opts.open(path).map_err(|e| {
TempfileError::IOError(path.clone().into(), "creating temporary file", e)
})?;
Ok(TempFile { temp_path, file })
}
pub fn temp_file_for(
self,
target_path: impl Into<Arc<Path>>,
permissions: Option<Permissions>,
) -> Result<TempFile<BufWriter<File>>, TempfileError> {
let TempFile { temp_path, file } =
self.unbuffered_temp_file_for(target_path, permissions)?;
let file = BufWriter::new(file);
Ok(TempFile { temp_path, file })
}
}
pub fn unbuffered_temp_file_for(
target_path: impl Into<Arc<Path>>,
permissions: Option<Permissions>,
) -> Result<TempFile<File>, TempfileError> {
TempPathOptions::default().unbuffered_temp_file_for(target_path, permissions)
}
pub fn temp_file_for(
target_path: impl Into<Arc<Path>>,
permissions: Option<Permissions>,
) -> Result<TempFile<BufWriter<File>>, TempfileError> {
let TempFile { temp_path, file } = unbuffered_temp_file_for(target_path, permissions)?;
let file = BufWriter::new(file);
Ok(TempFile { temp_path, file })
}