cj-path-util 0.4.0

Utilities to make working with Path/PathBuf more productive
Documentation
//! More composable/controllable utilities for handling temporary
//! files: temporary paths bundled with an open file handle
//!
//! Currently requires the 'unix' feature. Todo: make portable.

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};

/// The file permissions for creating new files
///
/// The default, `None`, leads to doing whatever `File::create` does
/// by default.
///
/// Note that the current permissions of the target files have no
/// effect on the permissions used for the creation of the temporary
/// file (see `TempPathOptions.migrate_access`). Be sure to set
/// `permissions` if there is a chance that the user need the file to
/// be private (they can always open up, but not close down,
/// permissions).
#[derive(Debug, Clone, Copy)]
pub enum Permissions {
    /// Make the file public (note that, like mentioned below, on unix
    /// the permissions are modified by the umask, hence a restrictive
    /// umask might make a file private anyway)
    Public,
    /// Make the file private
    Private,
    /// The unix mode bits value, like 0o666 for normal public
    /// writable files, or 0o600 for private normal writable files,
    /// 0o777 for public executable files, etc.; this number is
    /// modified by the current umask by the OS at the time of
    /// creating the file (`mode & ~umask`).
    Mode(u32),
}

/// A temporary file
///
/// This is a wrapper around a file writer that also bundles a
/// `TempPath` associated with the writer, and makes both work
/// together. Returned by the `temp_file_*` functions.
#[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> {
    /// Split up into the `TempPath` and writer parts, for situations
    /// that require to keep their life times independent.
    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()
    }

    /// Returns the `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();
        // Note: do *not* use `create_new` since stale files *may*
        // linger! The assumption is that overwriting is fine because
        // the thread id is part of the file name, and it wouldn't
        // make sense to hold two TempPath instances that overwrite
        // the same target path in the same thread.
        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 })
    }
}

/// Create a temporary file for `target_path` without buffering.
///
/// If you need more options, create a `TempPathOptions` instance and
/// call `unbuffered_temp_file_for` instead.
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)
}

/// Create a temporary file for `target_path` with buffering
///
/// If you need more options, create a `TempPathOptions` instance and
/// call `temp_file_for` instead.
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 })
}