util-easy 0.1.0

Small utility helpers for common tasks.
Documentation
//! Contains functions for working with the filesystem.

use std::path::Path;

/// Ensures that the directory at the given path exists, creating it if necessary.
///
/// # Arguments
/// * `path` - The directory path to ensure exists.
///
/// # Returns
/// * `Ok(())` if the directory exists or was successfully created.
/// * `Err(std::io::Error)` if there was an error creating the directory.
pub fn ensure_dir_exists(path: impl AsRef<Path>) -> std::io::Result<()> {
    let path = path.as_ref();

    std::fs::create_dir_all(path).map_err(|err| {
        std::io::Error::new(
            err.kind(),
            format!("failed to create directory '{}': {err}", path.display()),
        )
    })
}

/// Ensures that the parent directory of the given path exists, creating it if necessary.
///
/// # Arguments
/// * `path` - The file path whose parent directory should exist.
///
/// # Returns
/// * `Ok(())` if the parent directory exists or was successfully created.
/// * `Err(std::io::Error)` if there was an error creating the parent directory.
pub fn ensure_parent_dir_exists(path: impl AsRef<Path>) -> std::io::Result<()> {
    if let Some(parent) = path.as_ref().parent()
        && !parent.as_os_str().is_empty()
    {
        ensure_dir_exists(parent)?;
    }

    Ok(())
}

/// Removes the file at the given path if it exists.
///
/// # Arguments
/// * `path` - The file path to remove if it exists.
///
/// # Returns
/// * `Ok(())` if the file was successfully removed or did not exist.
/// * `Err(std::io::Error)` if there was an error removing the file.
pub fn remove_file_if_exists(path: impl AsRef<Path>) -> std::io::Result<()> {
    let path = path.as_ref();
    match std::fs::remove_file(path) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(err) => Err(std::io::Error::new(
            err.kind(),
            format!("failed to remove file '{}': {err}", path.display()),
        )),
    }
}

/// Removes the directory and its contents at the given path if it exists.
///
/// # Arguments
/// * `path` - The directory path to remove if it exists.
///
/// # Returns
/// * `Ok(())` if the directory was successfully removed or did not exist.
/// * `Err(std::io::Error)` if there was an error removing the directory.
pub fn remove_dir_all_if_exists(path: impl AsRef<Path>) -> std::io::Result<()> {
    let path = path.as_ref();
    match std::fs::remove_dir_all(path) {
        Ok(()) => Ok(()),
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(()),
        Err(err) => Err(std::io::Error::new(
            err.kind(),
            format!("failed to remove directory '{}': {err}", path.display()),
        )),
    }
}

#[cfg(test)]
mod tests;