baichun-framework-core 0.1.0

Core module for Baichun-Rust framework
Documentation
use std::path::Path;

use crate::error::{Error, Result};

/// 文件工具
pub struct FileUtils;

impl FileUtils {
    /// 获取文件扩展名
    pub fn get_extension(path: impl AsRef<Path>) -> Option<String> {
        path.as_ref()
            .extension()
            .and_then(|ext| ext.to_str())
            .map(|s| s.to_lowercase())
    }

    /// 获取文件名(不含扩展名)
    pub fn get_stem(path: impl AsRef<Path>) -> Option<String> {
        path.as_ref()
            .file_stem()
            .and_then(|stem| stem.to_str())
            .map(|s| s.to_string())
    }

    /// 获取文件名(含扩展名)
    pub fn get_filename(path: impl AsRef<Path>) -> Option<String> {
        path.as_ref()
            .file_name()
            .and_then(|name| name.to_str())
            .map(|s| s.to_string())
    }

    /// 检查文件是否存在
    pub fn exists(path: impl AsRef<Path>) -> bool {
        path.as_ref().exists()
    }

    /// 检查是否为文件
    pub fn is_file(path: impl AsRef<Path>) -> bool {
        path.as_ref().is_file()
    }

    /// 检查是否为目录
    pub fn is_dir(path: impl AsRef<Path>) -> bool {
        path.as_ref().is_dir()
    }

    /// 创建目录(递归)
    pub fn create_dir_all(path: impl AsRef<Path>) -> Result<()> {
        std::fs::create_dir_all(path.as_ref()).map_err(Error::from)
    }

    /// 删除文件
    pub fn remove_file(path: impl AsRef<Path>) -> Result<()> {
        std::fs::remove_file(path.as_ref()).map_err(Error::from)
    }

    /// 删除目录(递归)
    pub fn remove_dir_all(path: impl AsRef<Path>) -> Result<()> {
        std::fs::remove_dir_all(path.as_ref()).map_err(Error::from)
    }

    /// 获取文件大小
    pub fn get_size(path: impl AsRef<Path>) -> Result<u64> {
        std::fs::metadata(path.as_ref())
            .map(|meta| meta.len())
            .map_err(Error::from)
    }

    /// 获取文件修改时间
    pub fn get_modified_time(path: impl AsRef<Path>) -> Result<std::time::SystemTime> {
        std::fs::metadata(path.as_ref())
            .map(|meta| meta.modified().unwrap())
            .map_err(Error::from)
    }
}