cap_primitives/rustix/fs/
remove_dir_all_impl.rs

1use crate::fs::{
2    read_dir_nofollow, read_dir_unchecked, remove_dir, remove_file, remove_open_dir, stat,
3    FollowSymlinks, ReadDir,
4};
5use std::path::{Component, Path};
6use std::{fs, io};
7
8pub(crate) fn remove_dir_all_impl(start: &fs::File, path: &Path) -> io::Result<()> {
9    // Code adapted from `remove_dir_all` in Rust's
10    // library/std/src/sys_common/fs.rs at revision
11    // 108e90ca78f052c0c1c49c42a22c85620be19712.
12    let filetype = stat(start, path, FollowSymlinks::No)?.file_type();
13    if filetype.is_symlink() {
14        remove_file(start, path)
15    } else {
16        remove_dir_all_recursive(read_dir_nofollow(start, path)?)?;
17        remove_dir(start, path)
18    }
19}
20
21pub(crate) fn remove_open_dir_all_impl(dir: fs::File) -> io::Result<()> {
22    remove_dir_all_recursive(read_dir_unchecked(
23        &dir,
24        Component::CurDir.as_ref(),
25        FollowSymlinks::No,
26    )?)?;
27    remove_open_dir(dir)
28}
29
30fn remove_dir_all_recursive(children: ReadDir) -> io::Result<()> {
31    for child in children {
32        let child = child?;
33        if child.file_type()?.is_dir() {
34            remove_dir_all_recursive(child.inner.read_dir(FollowSymlinks::No)?)?;
35            child.remove_dir()?;
36        } else {
37            child.remove_file()?;
38        }
39    }
40    Ok(())
41}