use std::path::Path;
use std::time::Duration;
use super::Verified;
use crate::delete::outcome::{FailureKind, RemovalFailure};
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
#[non_exhaustive]
pub struct Removal {
pub dry_run: bool,
pub force: bool,
}
impl Removal {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn dry() -> Self {
Self {
dry_run: true,
force: false,
}
}
#[must_use]
pub fn forced() -> Self {
Self {
dry_run: false,
force: true,
}
}
}
const BACKOFF: [Duration; 3] = [
Duration::from_millis(50),
Duration::from_millis(200),
Duration::from_millis(800),
];
pub(super) fn remove(verified: &Verified, removal: Removal) -> (std::io::Result<()>, Option<u64>) {
let mut repaired = false;
let mut attempt = 0;
let mut freed: Option<u64> = None;
loop {
let result = if verified.is_dir {
remove_dir(verified.canonical(), removal.force, &mut freed)
} else {
std::fs::remove_file(verified.canonical())
};
let Err(error) = result else { return (Ok(()), freed) };
if !removal.force {
return (Err(error), freed);
}
match error.kind() {
std::io::ErrorKind::DirectoryNotEmpty => {
let Some(wait) = BACKOFF.get(attempt) else {
return (Err(error), freed);
};
std::thread::sleep(*wait);
attempt += 1;
}
_ if RemovalFailure::from_io(&error).kind() == FailureKind::Exhausted => {
let Some(wait) = BACKOFF.get(attempt) else {
return (Err(error), freed);
};
std::thread::sleep(*wait);
attempt += 1;
}
std::io::ErrorKind::PermissionDenied if !repaired => {
repair(verified.canonical());
repaired = true;
}
_ => return (Err(error), freed),
}
}
}
#[cfg(unix)]
fn remove_dir(path: &Path, force: bool, freed: &mut Option<u64>) -> std::io::Result<()> {
let removed = crate::tree::remove_dir(path, force);
*freed = Some(freed.unwrap_or(0) + removed.freed);
removed.error.map_or(Ok(()), Err)
}
#[cfg(not(unix))]
fn remove_dir(path: &Path, _force: bool, _freed: &mut Option<u64>) -> std::io::Result<()> {
std::fs::remove_dir_all(path)
}
fn repair(root: &Path) {
let mut stack = vec![root.to_path_buf()];
relax(root);
while let Some(directory) = stack.pop() {
let Ok(entries) = std::fs::read_dir(&directory) else {
continue;
};
for entry in entries.flatten() {
let path = entry.path();
let Ok(metadata) = std::fs::symlink_metadata(&path) else {
continue;
};
if metadata.file_type().is_symlink() {
continue;
}
relax(&path);
if metadata.is_dir() {
stack.push(path);
}
}
}
}
#[cfg(unix)]
fn relax(path: &Path) {
use std::os::unix::fs::{MetadataExt, PermissionsExt};
let Ok(metadata) = std::fs::symlink_metadata(path) else {
return;
};
if !metadata.is_dir() && metadata.nlink() > 1 {
return;
}
let mode = metadata.permissions().mode();
let wanted = if metadata.is_dir() { 0o700 } else { 0o200 };
if mode & wanted != wanted {
let _ = std::fs::set_permissions(path, PermissionsExt::from_mode(mode | wanted));
}
clear_immutable(path, &metadata);
}
#[cfg(not(unix))]
fn relax(path: &Path) {
let Ok(metadata) = std::fs::symlink_metadata(path) else {
return;
};
let mut permissions = metadata.permissions();
if permissions.readonly() {
#[expect(clippy::permissions_set_readonly_false, reason = "clearing it is the point")]
permissions.set_readonly(false);
let _ = std::fs::set_permissions(path, permissions);
}
}
#[cfg(target_vendor = "apple")]
fn clear_immutable(path: &Path, metadata: &std::fs::Metadata) {
use std::ffi::CString;
use std::os::darwin::fs::MetadataExt;
use std::os::unix::ffi::OsStrExt;
const UF_IMMUTABLE: u32 = 0x0000_0002;
const UF_APPEND: u32 = 0x0000_0004;
let flags = metadata.st_flags();
if flags & (UF_IMMUTABLE | UF_APPEND) == 0 {
return;
}
let Ok(raw) = CString::new(path.as_os_str().as_bytes()) else {
return;
};
unsafe {
libc::chflags(raw.as_ptr(), flags & !(UF_IMMUTABLE | UF_APPEND));
}
}
#[cfg(all(unix, not(target_vendor = "apple")))]
fn clear_immutable(_path: &Path, _metadata: &std::fs::Metadata) {}
#[cfg(test)]
mod tests {
use std::path::Path;
use super::*;
use crate::delete::{Guard, Outcome, PROTECTED_PATHS};
use crate::testing::tree;
#[cfg(unix)]
use crate::testing::snapshot;
fn guard(root: &Path) -> Guard {
Guard::new(&[root.to_path_buf()], true).expect("the fixture root resolves")
}
#[test]
fn the_retry_ladder_is_bounded() {
let total: Duration = BACKOFF.iter().sum();
assert!(
total <= Duration::from_millis(1_100),
"the retries add up to {total:?} per artifact, which is no longer a short backoff"
);
assert!(
BACKOFF.windows(2).all(|pair| pair[0] < pair[1]),
"each wait must be longer than the last"
);
}
#[test]
fn a_removal_forces_nothing_unless_asked() {
assert!(!Removal::new().force);
assert!(!Removal::new().dry_run);
assert!(!Removal::dry().force, "a dry run never repairs anything");
assert!(Removal::forced().force);
assert!(!Removal::forced().dry_run);
}
#[test]
fn force_should_still_refuse_every_rail() {
let outside = tempfile::TempDir::new().unwrap();
std::fs::write(outside.path().join("precious.txt"), b"not voom's business").unwrap();
let fixture = tree(&["Cargo.toml", ".git/HEAD", "target/app"]);
let guard = guard(fixture.path());
let mut refusable: Vec<std::path::PathBuf> = vec![
fixture.path().join(".git"), outside.path().to_path_buf(), fixture.path().to_path_buf(), ];
refusable.extend(
PROTECTED_PATHS
.iter()
.map(Path::new)
.filter(|path| path.exists())
.map(Path::to_path_buf),
);
for path in refusable {
for removal in [Removal::new(), Removal::forced()] {
let outcome = guard.remove(&path, 0, removal);
assert!(
matches!(outcome, Outcome::Refused(_)),
"`{}` was not refused with force={}: {outcome:?}",
path.display(),
removal.force
);
}
}
assert!(
outside.path().join("precious.txt").exists(),
"and nothing outside the root was touched by either pass"
);
}
#[test]
#[cfg(unix)]
fn force_should_reclaim_an_artifact_a_read_only_subdirectory_was_holding() {
use std::os::unix::fs::PermissionsExt;
let fixture = tree(&["Cargo.toml", "target/locked/held.bin"]);
let locked = fixture.path().join("target/locked");
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o555)).unwrap();
let guard = guard(fixture.path());
let target = fixture.path().join("target");
let plain = guard.remove(&target, 0, Removal::new());
if matches!(plain, Outcome::Removed) {
return;
}
assert!(target.exists(), "plain mode leaves it: {plain:?}");
let forced = guard.remove(&target, 0, Removal::forced());
assert_eq!(forced, Outcome::Removed, "forced mode finishes it");
assert!(!target.exists());
}
#[test]
#[cfg(unix)]
fn should_not_repair_permissions_without_force() {
use std::os::unix::fs::PermissionsExt;
let fixture = tree(&["Cargo.toml", "target/locked/held.bin"]);
let locked = fixture.path().join("target/locked");
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o555)).unwrap();
let before = std::fs::symlink_metadata(&locked).unwrap().permissions().mode();
let outcome = guard(fixture.path()).remove(&fixture.path().join("target"), 0, Removal::new());
if matches!(outcome, Outcome::Removed) {
return;
}
assert_eq!(
std::fs::symlink_metadata(&locked).unwrap().permissions().mode(),
before,
"an unforced run changes no mode"
);
}
#[test]
#[cfg(unix)]
fn force_should_not_follow_a_symlink_when_repairing_permissions() {
use std::os::unix::fs::PermissionsExt;
let outside = tempfile::TempDir::new().unwrap();
let guarded = outside.path().join("guarded");
std::fs::create_dir_all(&guarded).unwrap();
std::fs::write(guarded.join("precious.rs"), b"fn main() {}").unwrap();
std::fs::set_permissions(&guarded, std::fs::Permissions::from_mode(0o555)).unwrap();
let before = std::fs::symlink_metadata(&guarded).unwrap().permissions().mode();
let fixture = tree(&["Cargo.toml", "target/app"]);
std::os::unix::fs::symlink(&guarded, fixture.path().join("target/link")).unwrap();
let _ = guard(fixture.path()).remove(&fixture.path().join("target"), 0, Removal::forced());
assert_eq!(
std::fs::symlink_metadata(&guarded).unwrap().permissions().mode(),
before,
"the link's target keeps its mode: the repair never followed it"
);
assert!(guarded.join("precious.rs").exists(), "and keeps its contents");
std::fs::set_permissions(&guarded, std::fs::Permissions::from_mode(0o755)).unwrap();
}
#[test]
#[cfg(unix)]
fn force_should_not_change_anything_outside_the_artifact() {
use std::os::unix::fs::PermissionsExt;
let fixture = tree(&["project/Cargo.toml", "project/target/app", "project/src/main.rs"]);
let project = fixture.path().join("project");
std::fs::set_permissions(&project, std::fs::Permissions::from_mode(0o555)).unwrap();
let parent_before = std::fs::symlink_metadata(&project).unwrap().permissions().mode();
let sibling_before = std::fs::symlink_metadata(project.join("src"))
.unwrap()
.permissions()
.mode();
let _ = guard(fixture.path()).remove(&project.join("target"), 0, Removal::forced());
assert_eq!(
std::fs::symlink_metadata(&project).unwrap().permissions().mode(),
parent_before,
"the artifact's parent is never touched"
);
assert_eq!(
std::fs::symlink_metadata(project.join("src"))
.unwrap()
.permissions()
.mode(),
sibling_before,
"nor is a sibling"
);
std::fs::set_permissions(&project, std::fs::Permissions::from_mode(0o755)).unwrap();
}
#[test]
#[cfg(unix)]
fn force_should_reclaim_an_artifact_a_search_only_directory_was_holding() {
use std::os::unix::fs::PermissionsExt;
let fixture = tree(&["Cargo.toml", "target/sealed/held.bin"]);
let sealed = fixture.path().join("target/sealed");
std::fs::set_permissions(&sealed, std::fs::Permissions::from_mode(0o111)).unwrap();
let guard = guard(fixture.path());
let target = fixture.path().join("target");
let plain = guard.remove(&target, 0, Removal::new());
if matches!(plain, Outcome::Removed) {
return;
}
assert!(target.exists(), "plain mode leaves it: {plain:?}");
assert_eq!(
guard.remove(&target, 0, Removal::forced()),
Outcome::Removed,
"forced mode grants read as well and finishes it"
);
assert!(!target.exists());
}
#[test]
#[cfg(unix)]
fn force_should_not_widen_a_file_hard_linked_from_outside_the_artifact() {
use std::os::unix::fs::PermissionsExt;
let outside = tempfile::TempDir::new().unwrap();
let precious = outside.path().join("precious.rs");
std::fs::write(&precious, b"fn main() {}").unwrap();
std::fs::set_permissions(&precious, std::fs::Permissions::from_mode(0o400)).unwrap();
let fixture = tree(&["Cargo.toml", "target/locked/app"]);
std::fs::hard_link(&precious, fixture.path().join("target/shared.rs")).unwrap();
let locked = fixture.path().join("target/locked");
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o555)).unwrap();
let _ = guard(fixture.path()).remove(&fixture.path().join("target"), 0, Removal::forced());
assert_eq!(
std::fs::symlink_metadata(&precious).unwrap().permissions().mode() & 0o777,
0o400,
"the inode's mode is unchanged where it is named outside the artifact"
);
}
#[test]
#[cfg(unix)]
fn a_dry_run_with_force_touches_nothing() {
use std::os::unix::fs::PermissionsExt;
let fixture = tree(&["Cargo.toml", "target/locked/held.bin"]);
let locked = fixture.path().join("target/locked");
std::fs::set_permissions(&locked, std::fs::Permissions::from_mode(0o555)).unwrap();
let before = snapshot(fixture.path());
let mode = std::fs::symlink_metadata(&locked).unwrap().permissions().mode();
let outcome = guard(fixture.path()).remove(
&fixture.path().join("target"),
0,
Removal {
dry_run: true,
force: true,
},
);
assert_eq!(outcome, Outcome::WouldRemove);
assert_eq!(snapshot(fixture.path()), before, "the tree is byte-identical");
assert_eq!(
std::fs::symlink_metadata(&locked).unwrap().permissions().mode(),
mode,
"and no mode was repaired"
);
}
}