Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: use remove_dir_all in cargo clean to resolve race condition #11442

Merged
merged 5 commits into from
May 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions crates/cargo-util/src/paths.rs
Original file line number Diff line number Diff line change
Expand Up @@ -413,11 +413,22 @@ fn _create_dir_all(p: &Path) -> Result<()> {
Ok(())
}

/// Recursively remove all files and directories at the given directory.
/// Equivalent to [`std::fs::remove_dir_all`] with better error messages.
///
/// This does *not* follow symlinks.
pub fn remove_dir_all<P: AsRef<Path>>(p: P) -> Result<()> {
_remove_dir_all(p.as_ref())
_remove_dir_all(p.as_ref()).or_else(|prev_err| {
// `std::fs::remove_dir_all` is highly specialized for different platforms
// and may be more reliable than a simple walk. We try the walk first in
// order to report more detailed errors.
fs::remove_dir_all(p.as_ref()).with_context(|| {
format!(
"{:?}\n\nError: failed to remove directory `{}`",
prev_err,
p.as_ref().display(),
)
})
})
}

fn _remove_dir_all(p: &Path) -> Result<()> {
Expand Down
7 changes: 6 additions & 1 deletion src/cargo/ops/cargo_clean.rs
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,12 @@ fn rm_rf(path: &Path, config: &Config, progress: &mut dyn CleaningProgressBar) -
let entry = entry?;
progress.on_clean()?;
if entry.file_type().is_dir() {
paths::remove_dir(entry.path()).with_context(|| "could not remove build directory")?;
// The contents should have been removed by now, but sometimes a race condition is hit
// where other files have been added by the OS. `paths::remove_dir_all` also falls back
// to `std::fs::remove_dir_all`, which may be more reliable than a simple walk in
// platform-specific edge cases.
paths::remove_dir_all(entry.path())
.with_context(|| "could not remove build directory")?;
epage marked this conversation as resolved.
Show resolved Hide resolved
} else {
paths::remove_file(entry.path()).with_context(|| "failed to remove build artifact")?;
}
Expand Down