cj-path-util 0.3.0

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

use std::{
    fs::File,
    io::{BufWriter, Write},
    os::unix::fs::{MetadataExt, PermissionsExt},
    path::{Path, PathBuf},
};

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(PathBuf, &'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)]
pub struct TempfileOptions {
    /// The path where the file should end up once it is finalized.
    pub target_path: PathBuf,
    /// Whether to leave the temporary file at its temporary path in
    /// case of errors; if false, Tempfile::drop deletes it.
    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.
    pub migrate_access: bool,
}

impl TempfileOptions {
    pub fn tempfile(self) -> Result<Tempfile, TempfileError> {
        Tempfile::try_from(self)
    }
}

#[derive(Debug)]
pub struct Tempfile {
    opts: TempfileOptions,
    temp_path: PathBuf,
}

impl TryFrom<TempfileOptions> for Tempfile {
    type Error = TempfileError;

    fn try_from(opts: TempfileOptions) -> Result<Self, TempfileError> {
        let temp_path = temp_path(&opts.target_path)?;
        Ok(Tempfile { opts, temp_path })
    }
}

impl Tempfile {
    pub fn temp_path(&self) -> &Path {
        &self.temp_path
    }

    pub fn target_path(&self) -> &Path {
        &self.opts.target_path
    }

    pub fn finish(mut self) -> Result<(), TempfileError> {
        self.opts.retain_tempfile = true; // tell Drop that it should do nothing
        let Self {
            opts:
                TempfileOptions {
                    ref target_path,
                    retain_tempfile: _,
                    migrate_access,
                },
            ref temp_path,
        } = self;
        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(), "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(())
    }
}

impl Drop for Tempfile {
    fn drop(&mut self) {
        let Self {
            opts:
                TempfileOptions {
                    target_path: _,
                    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),
                },
            }
        }
    }
}

/// Usage of Tempfile made easier: opens a file handle to the
/// temporary file and hands it back, too
pub fn tempfile_unbuffered(
    target_path: PathBuf,
    migrate_access: bool,
) -> Result<(Tempfile, File), TempfileError> {
    let tmp_file = TempfileOptions {
        target_path,
        retain_tempfile: false,
        migrate_access,
    }
    .tempfile()?;
    let temp_path = &tmp_file.temp_path;
    let out = File::create(temp_path)
        .map_err(|e| TempfileError::IOError(temp_path.clone(), "creating temporary file", e))?;
    Ok((tmp_file, out))
}

pub fn tempfile_buffered(
    target_path: PathBuf,
    migrate_access: bool,
) -> Result<(Tempfile, BufWriter<File>), TempfileError> {
    let (temp, file) = tempfile_unbuffered(target_path, migrate_access)?;
    Ok((temp, BufWriter::new(file)))
}

// XX todo?
// pub struct TempfileWithFlush {
//     pub tempfile: Tempfile,
//     pub file: File,
// }