nmd_core/utility/
file_utility.rs

1use std::fs::{self, File};
2use std::io::{self, Read, Write};
3use std::path::{Path, PathBuf};
4
5
6/// Return entirely file content 
7pub fn read_file_content(file_path_buf: &PathBuf) -> Result<String, io::Error> {
8
9    let mut file = File::open(file_path_buf)?;
10
11    let mut content = String::new();
12    file.read_to_string(&mut content)?;
13
14    Ok(content)
15}
16
17
18/// Return true if &str passed is a valid file path
19pub fn is_file_path(s: &str) -> bool {
20    
21    Path::new(s).is_absolute() || Path::new(s).is_relative()
22}
23
24pub fn create_directory(path: &PathBuf) -> Result<(), io::Error> {
25   fs::create_dir(path)
26}
27
28pub fn create_empty_file(file_path: &PathBuf) -> Result<(), io::Error> {
29
30    create_file_with_content(file_path, "")
31}
32
33pub fn create_file_with_content(file_path: &PathBuf, content: &str) -> Result<(), io::Error> {
34
35    let mut file = File::create(&file_path)?;
36
37    file.write_all(content.as_bytes())
38}
39
40/// Generate a new file name String using passed base and extension arguments
41pub fn build_output_file_name(base: &str, ext: Option<&str>) -> String {
42
43    let base: Vec<char> = base.chars()
44                                .filter(|c| c.is_alphanumeric() || c.eq(&'_') || c.eq(&'-') || c.eq(&' ') || c.eq(&'.'))
45                                .map(|c| c.to_ascii_lowercase())
46                                .collect();
47
48    let base = String::from_iter(base);
49
50    let base: Vec<char> = base.trim().chars().map(|c| {
51                                    if c.eq(&' ') {
52                                        return '-';
53                                    }
54
55                                    c
56                                })
57                                .collect();
58
59    let base = String::from_iter(base);
60
61    if let Some(ext) = ext {
62
63        return format!("{}.{}", base, ext);
64
65    } else {
66
67        return base;
68    }
69}
70
71pub fn all_files_in_dir(dir_path: &PathBuf, exts: &Vec<String>) -> Result<Vec<PathBuf>, io::Error> {
72    if !dir_path.is_dir() {
73
74        let e = format!("{:?} must be a directory", dir_path);
75
76        return Err(io::Error::new(io::ErrorKind::NotFound, e));
77    }
78
79    let mut files: Vec<PathBuf> = Vec::new();
80
81    for entry in fs::read_dir(dir_path)? {
82        if let Ok(entry) = entry {
83            let path = entry.path();
84            
85            if let Some(extension) = path.extension() {
86
87                for ext in exts {
88                    if extension.to_string_lossy().eq(ext) {
89                        if let Some(_) = path.file_name() {
90                            files.push(path);
91                            break;
92                        }
93                    }
94                }
95            }
96        }
97    }   
98
99    Ok(files)
100}