cfun 0.2.11

Tidy up common functions
Documentation
use std::{io, path::Path};

/// judge whether a file is exists
pub fn file_is_exist(file: &str) -> bool {
    let file = std::fs::metadata(file);
    file.is_ok_and(|f| f.is_file())
}

/// judge whether a file is exists
pub fn dir_is_exist(file: &str) -> bool {
    let file = std::fs::metadata(file);
    file.is_ok_and(|f| f.is_dir())
}

/// get file name of a path
pub fn file_name(path: &str) -> String {
    let p = Path::new(path);
    p.file_name()
        .unwrap_or_default()
        .to_string_lossy()
        .to_string()
}

/// get extension name of a file
pub fn file_ext(path: &str) -> String {
    let p = Path::new(path);
    p.extension()
        .unwrap_or_default()
        .to_string_lossy()
        .to_string()
}

/// ensure a file exist,if not exist,create it!
/// # example
/// ```
/// assert_eq!(true,ensure_file_exist("D:\\a\\b\\test.txt"));
/// ```
pub fn ensure_file_exist(file: &str) -> Result<(), io::Error> {
    let p = std::path::Path::new(file);
    let parent = p.parent();
    if let Some(parent) = parent {
        if !parent.exists() {
            std::fs::create_dir_all(parent)?;
        }
    };

    if !p.exists() || !p.is_file() {
        std::fs::File::create(p)?;
    }
    Ok(())
}

/// copy a file to new position
/// # example
/// ```
/// copy_file("test.txt","D:\\");
/// ```
pub fn copy_file(src_file: &str, des_dir: &str) -> Result<(), io::Error> {
    let mut src = std::fs::File::open(src_file)?;
    let name = file_name(src_file);
    let p = Path::new(des_dir);
    let p = p.join(name);
    let mut des = std::fs::File::create(p)?;
    std::io::copy(&mut src, &mut des)?;
    Ok(())
}
/// copy a file to new position
/// # example
/// ```
/// move_file("test.txt","D:\\test.txt");
/// ```
pub fn move_file(src: &str, des: &str) -> Result<(), io::Error> {
    std::fs::rename(src, des)?;
    Ok(())
}

/// get file size
/// # example
/// ```
/// let size=file_size("test.txt");
/// ```
pub fn file_size(file: &str) -> Result<u64, io::Error> {
    let metadata = std::fs::metadata(file)?;
    Ok(metadata.len())
}

#[test]
fn test_file_is_exist() {
    assert_eq!(true, file_is_exist("Cargo.toml"));
    assert_eq!(false, file_is_exist("Cargo.toml1"));
}

#[test]
fn test_dir_is_exist() {
    assert_eq!(true, dir_is_exist("src"));
    assert_eq!(false, dir_is_exist("src1"));
}

#[test]
fn test_file_name() {
    assert_eq!("Cargo.toml", file_name("Cargo.toml"));
    assert_eq!("Cargo", file_name("Cargo"));
}

#[test]
fn test_file_ext() {
    assert_eq!("toml", file_ext("Cargo.toml"));
    assert_eq!("", file_ext("Cargo"));
}

#[test]
fn test_ensure_file_exist() {
    assert_eq!(true, ensure_file_exist("D:\\a\\b\\test.txt").is_ok());
}

#[test]
fn test_copy_file() {
    assert_eq!(true, copy_file("Cargo.toml", ".\\target").is_ok());
}