teo_parser/utils/
path.rs

1use std::fs;
2use std::path::{Path, PathBuf};
3use path_clean::PathClean;
4
5pub struct FileUtility {
6    pub read_file: fn(file_path: &str) -> Option<String>,
7    pub file_exists: fn(file_path: &str) -> bool,
8    pub file_is_directory: fn(file_path: &str) -> bool,
9    pub path_join: fn(base: &str, path: &str) -> String,
10    pub parent_directory: fn(file_path: &str) -> String,
11    pub path_is_absolute: fn(file_path: &str) -> bool,
12}
13
14impl FileUtility {
15
16    pub fn import_path(&self, source_path: &str, string: &str) -> String {
17        (self.path_join)(&(self.parent_directory)(source_path), string)
18    }
19}
20
21impl Default for FileUtility {
22
23    fn default() -> Self {
24        Self {
25            read_file,
26            file_exists,
27            file_is_directory,
28            path_join,
29            parent_directory,
30            path_is_absolute,
31        }
32    }
33}
34
35fn read_file(file_path: &str) -> Option<String> {
36    match fs::read_to_string(Path::new(file_path)) {
37        Ok(s) => Some(s),
38        Err(_) => None,
39    }
40}
41
42fn file_exists(file_path: &str) -> bool {
43    Path::new(file_path).exists()
44}
45
46fn parent_directory(path: &str) -> String {
47    let mut path = PathBuf::from(path);
48    path.pop();
49    path.to_str().unwrap().to_string()
50}
51
52fn path_is_absolute(path: &str) -> bool {
53    Path::new(path).is_absolute()
54}
55
56fn path_join(base: &str, path: &str) -> String {
57    Path::new(base).join(Path::new(path)).clean().to_str().unwrap().to_string()
58}
59
60fn file_is_directory(file_path: &str) -> bool {
61    Path::new(file_path).is_dir()
62}