baichun_framework_core/utils/
file.rs1use std::path::Path;
2
3use crate::error::{Error, Result};
4
5pub struct FileUtils;
7
8impl FileUtils {
9 pub fn get_extension(path: impl AsRef<Path>) -> Option<String> {
11 path.as_ref()
12 .extension()
13 .and_then(|ext| ext.to_str())
14 .map(|s| s.to_lowercase())
15 }
16
17 pub fn get_stem(path: impl AsRef<Path>) -> Option<String> {
19 path.as_ref()
20 .file_stem()
21 .and_then(|stem| stem.to_str())
22 .map(|s| s.to_string())
23 }
24
25 pub fn get_filename(path: impl AsRef<Path>) -> Option<String> {
27 path.as_ref()
28 .file_name()
29 .and_then(|name| name.to_str())
30 .map(|s| s.to_string())
31 }
32
33 pub fn exists(path: impl AsRef<Path>) -> bool {
35 path.as_ref().exists()
36 }
37
38 pub fn is_file(path: impl AsRef<Path>) -> bool {
40 path.as_ref().is_file()
41 }
42
43 pub fn is_dir(path: impl AsRef<Path>) -> bool {
45 path.as_ref().is_dir()
46 }
47
48 pub fn create_dir_all(path: impl AsRef<Path>) -> Result<()> {
50 std::fs::create_dir_all(path.as_ref()).map_err(Error::from)
51 }
52
53 pub fn remove_file(path: impl AsRef<Path>) -> Result<()> {
55 std::fs::remove_file(path.as_ref()).map_err(Error::from)
56 }
57
58 pub fn remove_dir_all(path: impl AsRef<Path>) -> Result<()> {
60 std::fs::remove_dir_all(path.as_ref()).map_err(Error::from)
61 }
62
63 pub fn get_size(path: impl AsRef<Path>) -> Result<u64> {
65 std::fs::metadata(path.as_ref())
66 .map(|meta| meta.len())
67 .map_err(Error::from)
68 }
69
70 pub fn get_modified_time(path: impl AsRef<Path>) -> Result<std::time::SystemTime> {
72 std::fs::metadata(path.as_ref())
73 .map(|meta| meta.modified().unwrap())
74 .map_err(Error::from)
75 }
76}