rusty_files/
lib.rs

1#![allow(unused_variables)]
2
3use std::{fs, path::Path};
4
5/// Recursively deletes all files and directories within a directory.
6///
7/// # Arguments
8///
9/// * `dir_path` - A `Path` reference to the directory to delete the contents of.
10///
11pub fn delete_dir_contents(dir_path: &Path) {
12    if dir_path.exists() && dir_path.is_dir() {
13        let inner_paths = fs::read_dir(dir_path).unwrap();
14        for inner_path in inner_paths {
15            let inner_path = inner_path.unwrap();
16            if inner_path.file_type().unwrap().is_dir() {
17                let inner_dir_name = inner_path.file_name();
18                let inner_dir_path = dir_path.join(inner_dir_name);
19                delete_dir_contents(&inner_dir_path);
20            } else {
21                let file_name = inner_path.file_name();
22                let file_path = dir_path.join(file_name);
23                if file_path.exists() && file_path.is_file() {
24                    fs::remove_file(file_path).unwrap();
25                }
26            }
27        }
28    }
29}
30
31/// Checks if a file or directory exists at the given path.
32///
33/// # Arguments
34///
35/// * `path` - A `Path` reference to the file or directory to check for existence.
36///
37/// # Returns
38///
39/// A `Result` containing a `bool` indicating whether the file or directory exists (`true`) or not (`false`), or an `std::io::Error` if an I/O error occurred.
40///
41pub fn check_if_path_exists(path: &Path) -> Result<bool, std::io::Error> {
42    match fs::metadata(path) {
43        Ok(metadata) => Ok(true),
44        Err(e) => match e.kind() {
45            std::io::ErrorKind::NotFound => Ok(false),
46            _ => Err(e),
47        },
48    }
49}
50
51#[cfg(test)]
52mod tests {
53    use super::*;
54    use std::path::PathBuf;
55
56    #[test]
57    fn test_check_if_path_exists() {
58        let path = PathBuf::from("src/lib.rs");
59        let result = check_if_path_exists(&path);
60        assert!(
61            result.is_ok(),
62            "Expected Ok result, but got an error: {:?}",
63            result
64        );
65        assert_eq!(result.unwrap(), true, "Expected true, but got false");
66
67        let path = PathBuf::from("src/lib1.rs");
68        let result = check_if_path_exists(&path);
69        assert!(
70            result.is_ok(),
71            "Expected Ok result, but got an error: {:?}",
72            result
73        );
74        assert_eq!(result.unwrap(), false, "Expected false, but got true");
75    }
76}