file_io/
delete.rs

1use std::path::Path;
2
3/// Deletes a folder at the specified path if it exists.
4///
5/// # Arguments
6///
7/// * `path` - The path to the folder to delete (can be a `&str`, [`String`], [`Path`], or
8///   [`std::path::PathBuf`]).
9///
10/// # Panics
11///
12/// If some error is encountered while deleting the folder at `path`.
13///
14/// # Examples
15///
16/// ## Using a string literal
17///
18/// ```
19/// use file_io::{create_folder, delete_folder};
20/// use std::path::Path;
21///
22/// // Create a folder to delete later.
23/// let path: &str = "folder/subfolder_5";
24/// create_folder(path);
25///
26/// // Verify that the folder exists.
27/// assert!(Path::new(path).exists());
28///
29/// // Now delete the folder.
30/// delete_folder(path);
31///
32/// // Verify that the folder no longer exists.
33/// assert!(!Path::new(path).exists());
34/// ```
35///
36/// ## Using a `Path` reference
37///
38/// ```
39/// use file_io::{create_folder, delete_folder};
40/// use std::path::Path;
41///
42/// // Create a folder to delete later.
43/// let path: &Path = Path::new("folder/subfolder_5");
44/// create_folder(path);
45///
46/// // Verify that the folder exists.
47/// assert!(path.exists());
48///
49/// // Now delete the folder.
50/// delete_folder(path);
51///
52/// // Verify that the folder no longer exists.
53/// assert!(!path.exists());
54/// ```
55pub fn delete_folder<P: AsRef<Path>>(path: P) {
56    let path = path.as_ref();
57    if path.exists() {
58        std::fs::remove_dir_all(path)
59            .unwrap_or_else(|_| panic!("Failed to delete folder at '{path:?}'."));
60    }
61}
62
63/// Deletes a file at the specified path if it exists.
64///
65/// # Arguments
66///
67/// * `path` - The path to the file to delete (can be a `&str`, [`String`], [`Path`], or
68///   [`std::path::PathBuf`]).
69///
70/// # Panics
71///
72/// If some error is encountered while deleting the file at `path`.
73///
74/// # Examples
75///
76/// ## Using a string literal
77///
78/// ```
79/// use file_io::{delete_file, save_string_to_file};
80/// use std::path::Path;
81///
82/// // Create a file to delete later.
83/// let path: &str = "file_to_delete_1.txt";
84/// save_string_to_file("Hello, world!", path);
85///
86/// // Verify that the file exists.
87/// assert!(Path::new(path).exists());
88///
89/// // Now delete the file.
90/// delete_file(path);
91///
92/// // Verify that the file no longer exists.
93/// assert!(!Path::new(path).exists());
94/// ```
95///
96/// ## Using a `Path` reference
97///
98/// ```
99/// use file_io::{delete_file, save_string_to_file};
100/// use std::path::Path;
101///
102/// // Create a file to delete later.
103/// let path: &Path = Path::new("file_to_delete_2.txt");
104/// save_string_to_file("Hello, world!", path);
105///
106/// // Verify that the file exists.
107/// assert!(path.exists());
108///
109/// // Now delete the file.
110/// delete_file(path);
111///
112/// // Verify that the file no longer exists.
113/// assert!(!path.exists());
114/// ```
115pub fn delete_file<P: AsRef<Path>>(path: P) {
116    let path = path.as_ref();
117    if path.exists() {
118        std::fs::remove_file(path)
119            .unwrap_or_else(|_| panic!("Failed to delete file at '{path:?}'."));
120    }
121}
122
123#[cfg(test)]
124mod tests {
125    use super::*;
126    use crate::save::save_string_to_file;
127    use crate::test_utils::get_temp_dir_path;
128    use crate::to_path_buf;
129    use tempfile::tempdir;
130
131    #[test]
132    fn test_delete_file() {
133        // Create a temporary directory.
134        let temp_dir = tempdir().unwrap();
135
136        // Get the path to the temporary directory.
137        let temp_dir_path = get_temp_dir_path(&temp_dir);
138
139        // Path to the file to copy.
140        let file_path = temp_dir_path.join("file_to_copy.txt");
141
142        // File path in different formats.
143        let file_paths: Vec<Box<dyn AsRef<Path>>> = vec![
144            Box::new(file_path.to_str().unwrap()),             // &str
145            Box::new(file_path.to_str().unwrap().to_string()), // String
146            Box::new(file_path.as_path()),                     // Path
147            Box::new(file_path.clone()),                       // PathBuf
148        ];
149
150        // Test with all different path formats.
151        for file_path in file_paths {
152            // Get a reference to this path representation (i.e. "unbox").
153            let file_path = file_path.as_ref();
154
155            // File path as a pathbuf.
156            let file_path_buf = to_path_buf(file_path);
157
158            // Check that the file does not exist before creating it.
159            assert!(!file_path_buf.exists());
160
161            // Create a file at the specified path.
162            save_string_to_file("Hello, world!", file_path);
163
164            // Verify that the file exists.
165            assert!(file_path_buf.exists());
166
167            // Now delete the file.
168            delete_file(file_path);
169
170            // Verify that the file no longer exists.
171            assert!(!file_path_buf.exists());
172        }
173    }
174}