use std::env;
use std::error;
use std::ffi::OsStr;
use std::fmt;
use std::fs::{self, File, OpenOptions};
use std::io::{self, Read, Seek, SeekFrom, Write};
use std::mem;
use std::ops::Deref;
use std::path::{Path, PathBuf};
use crate::error::IoResultExt;
use crate::Builder;
mod imp;
pub fn tempfile() -> io::Result<File> {
tempfile_in(&env::temp_dir())
}
pub fn tempfile_in<P: AsRef<Path>>(dir: P) -> io::Result<File> {
imp::create(dir.as_ref())
}
#[derive(Debug)]
pub struct PathPersistError {
pub error: io::Error,
pub path: TempPath,
}
impl From<PathPersistError> for io::Error {
#[inline]
fn from(error: PathPersistError) -> io::Error {
error.error
}
}
impl From<PathPersistError> for TempPath {
#[inline]
fn from(error: PathPersistError) -> TempPath {
error.path
}
}
impl fmt::Display for PathPersistError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "failed to persist temporary file path: {}", self.error)
}
}
impl error::Error for PathPersistError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
Some(&self.error)
}
}
pub struct TempPath {
path: PathBuf,
}
impl TempPath {
pub fn close(mut self) -> io::Result<()> {
let result = fs::remove_file(&self.path).with_err_path(|| &self.path);
self.path = PathBuf::new();
mem::forget(self);
result
}
pub fn persist<P: AsRef<Path>>(mut self, new_path: P) -> Result<(), PathPersistError> {
match imp::persist(&self.path, new_path.as_ref(), true) {
Ok(_) => {
self.path = PathBuf::new();
mem::forget(self);
Ok(())
}
Err(e) => Err(PathPersistError {
error: e,
path: self,
}),
}
}
pub fn persist_noclobber<P: AsRef<Path>>(
mut self,
new_path: P,
) -> Result<(), PathPersistError> {
match imp::persist(&self.path, new_path.as_ref(), false) {
Ok(_) => {
self.path = PathBuf::new();
mem::forget(self);
Ok(())
}
Err(e) => Err(PathPersistError {
error: e,
path: self,
}),
}
}
pub fn keep(mut self) -> Result<PathBuf, PathPersistError> {
match imp::keep(&self.path) {
Ok(_) => {
let path = mem::replace(&mut self.path, PathBuf::new());
mem::forget(self);
Ok(path)
}
Err(e) => Err(PathPersistError {
error: e,
path: self,
}),
}
}
}
impl fmt::Debug for TempPath {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.path.fmt(f)
}
}
impl Drop for TempPath {
fn drop(&mut self) {
let _ = fs::remove_file(&self.path);
}
}
impl Deref for TempPath {
type Target = Path;
fn deref(&self) -> &Path {
&self.path
}
}
impl AsRef<Path> for TempPath {
fn as_ref(&self) -> &Path {
&self.path
}
}
impl AsRef<OsStr> for TempPath {
fn as_ref(&self) -> &OsStr {
self.path.as_os_str()
}
}
pub struct NamedTempFile {
path: TempPath,
file: File,
}
impl fmt::Debug for NamedTempFile {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "NamedTempFile({:?})", self.path)
}
}
impl AsRef<Path> for NamedTempFile {
#[inline]
fn as_ref(&self) -> &Path {
self.path()
}
}
#[derive(Debug)]
pub struct PersistError {
pub error: io::Error,
pub file: NamedTempFile,
}
impl From<PersistError> for io::Error {
#[inline]
fn from(error: PersistError) -> io::Error {
error.error
}
}
impl From<PersistError> for NamedTempFile {
#[inline]
fn from(error: PersistError) -> NamedTempFile {
error.file
}
}
impl fmt::Display for PersistError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "failed to persist temporary file: {}", self.error)
}
}
impl error::Error for PersistError {
fn source(&self) -> Option<&(dyn error::Error + 'static)> {
Some(&self.error)
}
}
impl NamedTempFile {
pub fn new() -> io::Result<NamedTempFile> {
Builder::new().tempfile()
}
pub fn new_in<P: AsRef<Path>>(dir: P) -> io::Result<NamedTempFile> {
Builder::new().tempfile_in(dir)
}
#[inline]
pub fn path(&self) -> &Path {
&self.path
}
pub fn close(self) -> io::Result<()> {
let NamedTempFile { path, .. } = self;
path.close()
}
pub fn persist<P: AsRef<Path>>(self, new_path: P) -> Result<File, PersistError> {
let NamedTempFile { path, file } = self;
match path.persist(new_path) {
Ok(_) => Ok(file),
Err(err) => {
let PathPersistError { error, path } = err;
Err(PersistError {
file: NamedTempFile { path, file },
error,
})
}
}
}
pub fn persist_noclobber<P: AsRef<Path>>(self, new_path: P) -> Result<File, PersistError> {
let NamedTempFile { path, file } = self;
match path.persist_noclobber(new_path) {
Ok(_) => Ok(file),
Err(err) => {
let PathPersistError { error, path } = err;
Err(PersistError {
file: NamedTempFile { path, file },
error,
})
}
}
}
pub fn keep(self) -> Result<(File, PathBuf), PersistError> {
let (file, path) = (self.file, self.path);
match path.keep() {
Ok(path) => Ok((file, path)),
Err(PathPersistError { error, path }) => Err(PersistError {
file: NamedTempFile { path, file },
error,
}),
}
}
pub fn reopen(&self) -> io::Result<File> {
imp::reopen(self.as_file(), NamedTempFile::path(self))
.with_err_path(|| NamedTempFile::path(self))
}
pub fn as_file(&self) -> &File {
&self.file
}
pub fn as_file_mut(&mut self) -> &mut File {
&mut self.file
}
pub fn into_file(self) -> File {
self.file
}
pub fn into_temp_path(self) -> TempPath {
self.path
}
pub fn into_parts(self) -> (File, TempPath) {
(self.file, self.path)
}
}
impl Read for NamedTempFile {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.as_file_mut().read(buf).with_err_path(|| self.path())
}
}
impl<'a> Read for &'a NamedTempFile {
fn read(&mut self, buf: &mut [u8]) -> io::Result<usize> {
self.as_file().read(buf).with_err_path(|| self.path())
}
}
impl Write for NamedTempFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.as_file_mut().write(buf).with_err_path(|| self.path())
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.as_file_mut().flush().with_err_path(|| self.path())
}
}
impl<'a> Write for &'a NamedTempFile {
fn write(&mut self, buf: &[u8]) -> io::Result<usize> {
self.as_file().write(buf).with_err_path(|| self.path())
}
#[inline]
fn flush(&mut self) -> io::Result<()> {
self.as_file().flush().with_err_path(|| self.path())
}
}
impl Seek for NamedTempFile {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
self.as_file_mut().seek(pos).with_err_path(|| self.path())
}
}
impl<'a> Seek for &'a NamedTempFile {
fn seek(&mut self, pos: SeekFrom) -> io::Result<u64> {
self.as_file().seek(pos).with_err_path(|| self.path())
}
}
#[cfg(unix)]
impl std::os::unix::io::AsRawFd for NamedTempFile {
#[inline]
fn as_raw_fd(&self) -> std::os::unix::io::RawFd {
self.as_file().as_raw_fd()
}
}
#[cfg(windows)]
impl std::os::windows::io::AsRawHandle for NamedTempFile {
#[inline]
fn as_raw_handle(&self) -> std::os::windows::io::RawHandle {
self.as_file().as_raw_handle()
}
}
pub(crate) fn create_named(
mut path: PathBuf,
open_options: &mut OpenOptions,
) -> io::Result<NamedTempFile> {
if !path.is_absolute() {
path = env::current_dir()?.join(path)
}
imp::create_named(&path, open_options)
.with_err_path(|| path.clone())
.map(|file| NamedTempFile {
path: TempPath { path },
file,
})
}