fs_utils/remove.rs
1//! Functions to remove files and directories.
2use std::{fs, io, path::Path};
3
4/// Cleans up the contents (files and folders) of the given folder while keeping the folder itself.
5///
6/// It is useful if you don't want to loose the permissions set on the folder, or if you only have
7/// enough permissions to manipulate with the contents of the given folder, but not the folder
8/// itself.
9///
10/// It is a common pattern:
11///
12/// * ["How to remove only the content of directories?"](https://unix.stackexchange.com/questions/45950/how-to-remove-only-the-content-of-directories)
13/// * ["How to delete the contents of a folder in Python?"](https://stackoverflow.com/questions/185936/how-to-delete-the-contents-of-a-folder-in-python)
14pub fn cleanup_folder(folder_path: impl AsRef<Path>) -> io::Result<()> {
15 for entry in fs::read_dir(&folder_path)? {
16 let path = entry?.path();
17 if path.is_dir() {
18 fs::remove_dir_all(&path)?;
19 } else {
20 fs::remove_file(&path)?;
21 }
22 }
23 Ok(())
24}