iron_ingot/functions/
fs.rs

1use std::{
2  fs::{create_dir, read_dir, remove_dir_all, remove_file},
3  io,
4};
5
6// It removes all files and subdirectories in the directory where its path is received from its parameter.
7//
8// `dir_path`: The path where the directory is to be emptied.
9pub fn empty_dir(dir_path: &str) -> io::Result<()> {
10  if let Err(err) = remove_dir_all(dir_path) {
11    if err.kind() != io::ErrorKind::NotFound {
12      return Err(err);
13    }
14  }
15  create_dir(dir_path)?;
16  Ok(())
17}
18
19/// It removes all files in the directory where its path is received from its parameter with matching `ext_name`
20/// received.
21///
22/// `ext_name`: Files where its file name contains the extension name will be removed. The name must not starts with .
23///
24/// `dir_path`: The path where the directory is to be focused on.
25pub fn remove_files(ext_name: &str, dir_path: &str) -> io::Result<()> {
26  for entry in read_dir(dir_path)? {
27    let entry = entry?;
28    if entry.file_type()?.is_dir() {
29      remove_files(ext_name, &entry.path().to_string_lossy())?;
30    } else if entry
31      .file_name()
32      .to_string_lossy()
33      .ends_with(&format!(".{ext_name}"))
34    {
35      remove_file(entry.path())?;
36    }
37  }
38  Ok(())
39}
40
41/// It checks whether the directory path given has at least one file with an `ext_name` that is received from the
42/// parameter.
43///
44/// `ext_name`: The extension name used during checking. The name must not start with .
45///
46/// `dir_path`: The path where the directory is to be focused on.
47///
48/// It returns true if there is at least one file with an `ext_name` that is coming from the parameter, false
49///   otherwise.
50pub fn has_file_with_ext(ext_name: &str, dir_path: &str) -> io::Result<bool> {
51  for entry in read_dir(dir_path)? {
52    if entry?
53      .file_name()
54      .to_string_lossy()
55      .ends_with(&format!(".{ext_name}"))
56    {
57      return Ok(true);
58    }
59  }
60  Ok(false)
61}