1use std::{io, path::Path};
2
3pub fn file_is_exist(file: &str) -> bool {
5 let file = std::fs::metadata(file);
6 file.is_ok_and(|f| f.is_file())
7}
8
9pub fn dir_is_exist(file: &str) -> bool {
11 let file = std::fs::metadata(file);
12 file.is_ok_and(|f| f.is_dir())
13}
14
15pub fn file_name(path: &str) -> String {
17 let p = Path::new(path);
18 p.file_name()
19 .unwrap_or_default()
20 .to_string_lossy()
21 .to_string()
22}
23
24pub fn file_ext(path: &str) -> String {
26 let p = Path::new(path);
27 p.extension()
28 .unwrap_or_default()
29 .to_string_lossy()
30 .to_string()
31}
32
33pub fn ensure_file_exist(file: &str) -> Result<(), io::Error> {
39 let p = std::path::Path::new(file);
40 let parent = p.parent();
41 if let Some(parent) = parent {
42 if !parent.exists() {
43 std::fs::create_dir_all(parent)?;
44 }
45 };
46
47 if !p.exists() || !p.is_file() {
48 std::fs::File::create(p)?;
49 }
50 Ok(())
51}
52
53pub fn copy_file(src_file: &str, des_dir: &str) -> Result<(), io::Error> {
59 let mut src = std::fs::File::open(src_file)?;
60 let name = file_name(src_file);
61 let p = Path::new(des_dir);
62 let p = p.join(name);
63 let mut des = std::fs::File::create(p)?;
64 std::io::copy(&mut src, &mut des)?;
65 Ok(())
66}
67pub fn move_file(src: &str, des: &str) -> Result<(), io::Error> {
73 std::fs::rename(src, des)?;
74 Ok(())
75}
76
77pub fn file_size(file: &str) -> Result<u64, io::Error> {
83 let metadata = std::fs::metadata(file)?;
84 Ok(metadata.len())
85}
86
87#[test]
88fn test_file_is_exist() {
89 assert_eq!(true, file_is_exist("Cargo.toml"));
90 assert_eq!(false, file_is_exist("Cargo.toml1"));
91}
92
93#[test]
94fn test_dir_is_exist() {
95 assert_eq!(true, dir_is_exist("src"));
96 assert_eq!(false, dir_is_exist("src1"));
97}
98
99#[test]
100fn test_file_name() {
101 assert_eq!("Cargo.toml", file_name("Cargo.toml"));
102 assert_eq!("Cargo", file_name("Cargo"));
103}
104
105#[test]
106fn test_file_ext() {
107 assert_eq!("toml", file_ext("Cargo.toml"));
108 assert_eq!("", file_ext("Cargo"));
109}
110
111#[test]
112fn test_ensure_file_exist() {
113 assert_eq!(true, ensure_file_exist("D:\\a\\b\\test.txt").is_ok());
114}
115
116#[test]
117fn test_copy_file() {
118 assert_eq!(true, copy_file("Cargo.toml", ".\\target").is_ok());
119}