How to remove directories I don't have permission to access in Rust?

Viewed 925

How to remove a directory recursively in Rust, deleting empty directories with Unix permissions of 000 as well? These permissions are read as "no reading, writing or executing is allowed by any user".

I've previously created the directory like this:

mkdir -p dir/trap
chmod 000 dir/trap

I've tried this method:

std::fs::remove_dir_all("dir").unwrap();

It fails with "Permission denied" however. Are there any other solutions that still remove such directory, like rm -rf would?

2 Answers

The problem is that remove_dir_all() first walks the contents of the directory to delete any file or subdirectory that may be there. And you do not have permissions to read the directory, thus the error.

You can call instead:

std::fs::remove_dir("dir").unwrap();

It does not try to walk the directory, instead assumes that it is already empty, and fails if it is not.

If you want to delete a non-empty, 000 moded directory you will have to change the permissions first back to a sensible value and then you can call remove_dir_all() safely.

No easy answer was found yet, so I've written my own implementation: https://crates.io/crates/rm_rf

Usage:

rm_rf::force_remove_all("target").expect("Failed to remove target");

This will remove read-only files on Windows and empty directories lacking read access on Linux.

Related