use std::{io, path::Path};
pub fn file_is_exist(file: &str) -> bool {
let file = std::fs::metadata(file);
file.is_ok_and(|f| f.is_file())
}
pub fn dir_is_exist(file: &str) -> bool {
let file = std::fs::metadata(file);
file.is_ok_and(|f| f.is_dir())
}
pub fn file_name(path: &str) -> String {
let p = Path::new(path);
p.file_name()
.unwrap_or_default()
.to_string_lossy()
.to_string()
}
pub fn file_ext(path: &str) -> String {
let p = Path::new(path);
p.extension()
.unwrap_or_default()
.to_string_lossy()
.to_string()
}
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(())
}
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(())
}
pub fn move_file(src: &str, des: &str) -> Result<(), io::Error> {
std::fs::rename(src, des)?;
Ok(())
}
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());
}