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
//!
//! Currently requires the 'unix' feature. Todo: make portable.

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),
}

/// Append a suffix `.tmp~..-..` where the numbers are pid and
/// tid. Non-unicode file names are converted to unicode lossily for
/// the temporary path.
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))
}

/// The parameters for creating a temporary file
#[derive(Debug, Clone, Copy)]
pub struct TempPathOptions {
    /// Whether to leave the temporary file at its temporary path in
    /// case of errors; if false, Tempfile::drop deletes it. Default:
    /// false.
    pub retain_tempfile: bool,
    /// Whether to copy the access permissions from a pre-existing
    /// file at `target_path`, if any. If there is no file, or this is
    /// `false`, currently the default permissions on File creation
    /// are retained. (Note: the current permissions of the
    /// `target_path` are only used in `persist`; they have no effect
    /// on the permissions used for creating at temporary file via
    /// `TempFile`. The temporary file might thus be more open than
    /// the target file!)  Defailt: true.
    pub migrate_access: bool,
}

impl Default for TempPathOptions {
    fn default() -> Self {
        Self {
            retain_tempfile: false,
            migrate_access: true,
        }
    }
}

impl TempPathOptions {
    /// `target_path`: the path where the file should end up once it is finalized.
    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
    }

    /// Returns the `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;
        // tell Drop that it should do nothing
        self.options.retain_tempfile = true;
        // Take the target_path away from self efficiently
        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 {
            // XX iirc when one sets setuid/setgid, user needs to be
            // set first? Also, accessibility race, OK?
            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();
            // Is the way via mode really necessary, or pass perms directly??
            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(
                // XX well, we have two paths here; assume the problem
                // is not because of temp_path because it worked so
                // far?
                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),
                },
            }
        }
    }
}