use std::ffi::OsStr;
use std::path::{Path, PathBuf};
mod force;
mod outcome;
mod pool;
mod trash;
pub use force::Removal;
pub use outcome::{FailureKind, Outcome, Refusal, RemovalFailure};
pub use pool::{freed_so_far, limit_removal_workers};
pub(crate) use pool::{install_removal, note_freed, remove_in_pool};
pub use trash::{
Reaped, TRASH_ENV, Trash, collect_ledger, detach_removals, detached_count, reap, spawn_reaper,
spawn_reaper_for_pending, trash_location, yield_to_foreground,
};
use crate::error::{Error, Result};
pub(crate) const PROTECTED_PATHS: &[&str] = &[
"/",
"/Applications",
"/bin",
"/boot",
"/dev",
"/etc",
"/home",
"/Library",
"/opt",
"/private",
"/proc",
"/root",
"/sbin",
"/srv",
"/sys",
"/System",
"/tmp",
"/usr",
"/var",
"/Users",
"/Volumes",
"C:\\",
"C:\\Program Files",
"C:\\Program Files (x86)",
"C:\\Users",
"C:\\Windows",
];
const VCS_DIRS: &[&str] = &[".git", ".hg", ".svn"];
#[cfg(not(windows))]
fn names_equal(left: &OsStr, right: &OsStr) -> bool {
left == right
}
#[cfg(windows)]
fn names_equal(left: &OsStr, right: &OsStr) -> bool {
if left.eq_ignore_ascii_case(right) {
return true;
}
left.to_string_lossy().to_lowercase() == right.to_string_lossy().to_lowercase()
}
pub(crate) fn paths_equal(left: &Path, right: &Path) -> bool {
#[cfg(not(windows))]
{
left == right
}
#[cfg(windows)]
{
let mut left = left.components();
let mut right = right.components();
loop {
match (left.next(), right.next()) {
(None, None) => return true,
(Some(left), Some(right)) if names_equal(left.as_os_str(), right.as_os_str()) => {}
_ => return false,
}
}
}
}
fn path_starts_with(child: &Path, ancestor: &Path) -> bool {
#[cfg(not(windows))]
{
child.starts_with(ancestor)
}
#[cfg(windows)]
{
let mut child = child.components();
for component in ancestor.components() {
match child.next() {
Some(seen) if names_equal(seen.as_os_str(), component.as_os_str()) => {}
_ => return false,
}
}
true
}
}
pub(crate) fn resolved_protected_paths() -> Vec<PathBuf> {
#[cfg(windows)]
const SYSTEM_VARIABLES: &[&str] = &[
"SystemRoot",
"ProgramFiles",
"ProgramFiles(x86)",
"ProgramW6432",
"ProgramData",
"USERPROFILE",
];
let mut resolved: Vec<PathBuf> = Vec::new();
let mut push = |path: &Path| {
if let Ok(canonical) = path.canonicalize()
&& !resolved.iter().any(|seen| paths_equal(seen, &canonical))
{
resolved.push(canonical);
}
};
for protected in PROTECTED_PATHS {
push(Path::new(protected));
}
#[cfg(windows)]
for variable in SYSTEM_VARIABLES {
if let Some(value) = std::env::var_os(variable) {
push(Path::new(&value));
}
}
#[cfg(windows)]
if let Some(drive) = std::env::var_os("SystemDrive") {
let mut root = drive;
root.push(std::path::MAIN_SEPARATOR_STR);
push(Path::new(&root));
}
#[cfg(windows)]
if let Some(profile) = std::env::var_os("USERPROFILE") {
if let Some(parent) = Path::new(&profile).parent() {
push(parent);
}
}
resolved
}
#[cfg(windows)]
const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400;
#[cfg(windows)]
fn is_reparse_point(metadata: &std::fs::Metadata) -> bool {
use std::os::windows::fs::MetadataExt;
metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0
}
#[cfg(windows)]
fn volume_prefix(path: &Path) -> Option<&OsStr> {
match path.components().next() {
Some(std::path::Component::Prefix(prefix)) => Some(prefix.as_os_str()),
_ => None,
}
}
#[cfg(windows)]
fn same_volume(left: &Path, right: &Path) -> bool {
match (volume_prefix(left), volume_prefix(right)) {
(Some(left), Some(right)) => names_equal(left, right),
_ => false,
}
}
#[derive(Debug)]
pub struct Verified {
canonical: PathBuf,
is_dir: bool,
}
impl Verified {
#[must_use]
pub fn canonical(&self) -> &Path {
&self.canonical
}
}
#[derive(Debug)]
pub struct Guard {
roots: Vec<PathBuf>,
#[cfg(unix)]
root_devices: Vec<u64>,
resolved_protected: Vec<PathBuf>,
home: Option<PathBuf>,
one_file_system: bool,
}
impl Guard {
pub fn new(roots: &[PathBuf], one_file_system: bool) -> Result<Self> {
let mut resolved = Vec::with_capacity(roots.len());
#[cfg(unix)]
let mut devices = Vec::with_capacity(roots.len());
for root in roots {
let canonical = root.canonicalize().map_err(|source| Error::ReadDir {
path: root.clone(),
source,
})?;
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt;
let metadata = canonical.metadata().map_err(|source| Error::ReadDir {
path: canonical.clone(),
source,
})?;
devices.push(metadata.dev());
}
resolved.push(canonical);
}
Ok(Self {
roots: resolved,
#[cfg(unix)]
root_devices: devices,
resolved_protected: resolved_protected_paths(),
home: dirs::home_dir().and_then(|home| home.canonicalize().ok()),
one_file_system,
})
}
#[must_use]
pub fn roots(&self) -> &[PathBuf] {
&self.roots
}
pub fn check(&self, path: &Path) -> std::result::Result<Verified, Refusal> {
let metadata = std::fs::symlink_metadata(path).map_err(|_| Refusal::Vanished)?;
if metadata.file_type().is_symlink() {
return Err(Refusal::Symlink);
}
#[cfg(windows)]
if is_reparse_point(&metadata) {
return Err(Refusal::ReparsePoint);
}
let canonical = path.canonicalize().map_err(|_| Refusal::Vanished)?;
if self.is_protected(&canonical) {
return Err(Refusal::Protected);
}
let Some(index) = self.containing_root(&canonical) else {
return Err(Refusal::EscapesRoot);
};
#[cfg(unix)]
if self.one_file_system {
use std::os::unix::fs::MetadataExt;
if self
.root_devices
.get(index)
.is_some_and(|device| *device != metadata.dev())
{
return Err(Refusal::FilesystemBoundary);
}
}
#[cfg(windows)]
if self.one_file_system {
if self.roots.get(index).is_some_and(|root| !same_volume(root, &canonical)) {
return Err(Refusal::FilesystemBoundary);
}
}
#[cfg(not(any(unix, windows)))]
let _ = index;
Ok(Verified {
canonical,
is_dir: metadata.file_type().is_dir(),
})
}
fn is_protected(&self, canonical: &Path) -> bool {
if canonical.parent().is_none() {
return true;
}
if PROTECTED_PATHS
.iter()
.any(|protected| paths_equal(canonical, Path::new(protected)))
{
return true;
}
if self
.resolved_protected
.iter()
.any(|protected| paths_equal(canonical, protected))
{
return true;
}
if self.home.as_deref().is_some_and(|home| paths_equal(canonical, home)) {
return true;
}
canonical
.file_name()
.is_some_and(|name| VCS_DIRS.iter().any(|vcs| names_equal(name, OsStr::new(vcs))))
}
fn containing_root(&self, canonical: &Path) -> Option<usize> {
self.roots
.iter()
.position(|root| !paths_equal(canonical, root) && path_starts_with(canonical, root))
}
#[must_use]
pub fn remove(&self, path: &Path, bytes: u64, removal: Removal) -> Outcome {
let verified = match self.check(path) {
Ok(verified) => verified,
Err(refusal) => return Outcome::Refused(refusal),
};
if removal.dry_run {
return Outcome::WouldRemove;
}
if let Some(outcome) = trash::try_detach(&verified, removal) {
return outcome;
}
let (result, counted) = remove_in_pool(&verified, removal);
if result.is_ok() && counted.is_none() {
note_freed(bytes);
}
match result {
Ok(()) => Outcome::Removed,
Err(error) if error.kind() == std::io::ErrorKind::NotFound => Outcome::Refused(Refusal::Vanished),
Err(error) => Self::failed(&verified, bytes, &error),
}
}
#[must_use]
pub fn reclaim(&self, path: &Path, removal: Removal) -> (Outcome, u64) {
let (outcome, measured) = self.reclaim_fully(path, removal);
(outcome, measured.bytes)
}
pub(crate) fn reclaim_fully(&self, path: &Path, removal: Removal) -> (Outcome, crate::size::Measured) {
use crate::size::Measured;
let verified = match self.check(path) {
Ok(verified) => verified,
Err(refusal) => return (Outcome::Refused(refusal), Measured::default()),
};
if removal.dry_run {
return (Outcome::WouldRemove, crate::size::measure_fully(&verified.canonical));
}
if let Some(outcome) = trash::try_detach(&verified, removal) {
return (outcome, Measured::default());
}
let before = (!cfg!(unix) || !verified.is_dir).then(|| crate::size::measure(&verified.canonical));
let (result, counted) = remove_in_pool(&verified, removal);
let Some(freed) = counted.or(before) else {
return (Outcome::Removed, Measured::default());
};
if counted.is_none() && result.is_ok() {
note_freed(freed);
}
match result {
Ok(()) => (
Outcome::Removed,
Measured {
bytes: freed,
unreadable: 0,
},
),
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
(Outcome::Refused(Refusal::Vanished), Measured::default())
}
Err(error) => {
let failure = RemovalFailure::from_io(&error);
let remaining = if verified.is_dir {
crate::size::measure_fully(&verified.canonical)
} else {
Measured {
bytes: freed,
unreadable: 0,
}
};
if counted.is_none() || freed == 0 {
return (Outcome::Failed(failure), remaining);
}
(
Outcome::PartiallyRemoved {
freed,
remaining: remaining.bytes,
failure,
},
Measured {
bytes: freed + remaining.bytes,
..remaining
},
)
}
}
}
fn failed(verified: &Verified, bytes: u64, error: &std::io::Error) -> Outcome {
let failure = RemovalFailure::from_io(error);
if !verified.is_dir {
return Outcome::Failed(failure);
}
let remaining = crate::size::measure(&verified.canonical);
let freed = bytes.saturating_sub(remaining);
if freed == 0 {
return Outcome::Failed(failure);
}
Outcome::PartiallyRemoved {
freed,
remaining,
failure,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::{snapshot, tree};
fn guard(root: &Path) -> Guard {
Guard::new(&[root.to_path_buf()], true).expect("the root resolves")
}
#[test]
fn should_remove_a_verified_directory() {
let fixture = tree(&["Cargo.toml", "target/debug/build.o"]);
let guard = guard(fixture.path());
assert_eq!(
guard.remove(&fixture.path().join("target"), 0, Removal::new()),
Outcome::Removed
);
assert_eq!(snapshot(fixture.path()), vec!["Cargo.toml".to_owned()]);
}
#[test]
fn should_remove_a_file_artifact() {
let fixture = tree(&["package.json", "app.tsbuildinfo"]);
let guard = guard(fixture.path());
assert_eq!(
guard.remove(&fixture.path().join("app.tsbuildinfo"), 0, Removal::new()),
Outcome::Removed
);
assert_eq!(snapshot(fixture.path()), vec!["package.json".to_owned()]);
}
#[test]
#[cfg(unix)]
fn should_refuse_a_symlink_and_leave_its_target_intact() {
let fixture = tree(&["Cargo.toml", "source/precious.rs"]);
std::os::unix::fs::symlink(fixture.path().join("source"), fixture.path().join("target")).expect("a symlink");
let guard = guard(fixture.path());
assert_eq!(
guard.remove(&fixture.path().join("target"), 0, Removal::new()),
Outcome::Refused(Refusal::Symlink)
);
assert!(
fixture.path().join("source/precious.rs").exists(),
"the target survives"
);
}
#[test]
fn should_refuse_a_path_outside_every_scan_root() {
let scanned = tree(&["Cargo.toml", "target/"]);
let elsewhere = tree(&["Cargo.toml", "target/"]);
let guard = guard(scanned.path());
assert_eq!(
guard.remove(&elsewhere.path().join("target"), 0, Removal::new()),
Outcome::Refused(Refusal::EscapesRoot)
);
assert!(elsewhere.path().join("target").exists());
}
#[test]
fn should_refuse_the_scan_root_itself() {
let fixture = tree(&["Cargo.toml"]);
let guard = guard(fixture.path());
assert_eq!(
guard.remove(fixture.path(), 0, Removal::new()),
Outcome::Refused(Refusal::EscapesRoot)
);
assert!(fixture.path().exists());
}
#[test]
fn should_refuse_every_protected_path() {
let fixture = tree(&["Cargo.toml"]);
let guard = guard(fixture.path());
for protected in PROTECTED_PATHS {
let path = Path::new(protected);
if !path.exists() {
continue;
}
match guard.check(path) {
Err(Refusal::Protected | Refusal::Symlink) => {}
other => panic!("`{protected}` was not refused: {other:?}"),
}
}
}
#[test]
#[cfg(not(windows))]
fn should_compare_paths_case_sensitively_off_windows() {
assert!(!names_equal(OsStr::new(".GIT"), OsStr::new(".git")));
assert!(!paths_equal(Path::new("/Users"), Path::new("/users")));
assert!(!path_starts_with(Path::new("/a/B/c"), Path::new("/a/b")));
assert!(paths_equal(Path::new("/a/b"), Path::new("/a/b")));
assert!(path_starts_with(Path::new("/a/b/c"), Path::new("/a/b")));
}
#[test]
#[cfg(windows)]
fn should_compare_paths_case_insensitively_on_windows() {
assert!(names_equal(OsStr::new(".GIT"), OsStr::new(".git")));
assert!(paths_equal(Path::new(r"C:\Windows"), Path::new(r"c:\windows")));
assert!(path_starts_with(
Path::new(r"C:\Users\X\Target"),
Path::new(r"c:\users\x")
));
assert!(!path_starts_with(Path::new(r"C:\a\bc"), Path::new(r"C:\a\b")));
assert!(!paths_equal(
Path::new(r"C:\Windows"),
Path::new(r"C:\Windows\System32")
));
}
#[test]
#[cfg(windows)]
fn should_refuse_a_differently_cased_vcs_directory_on_windows() {
let fixture = tree(&["Cargo.toml", ".GIT/HEAD"]);
let guard = guard(fixture.path());
assert_eq!(
guard.remove(&fixture.path().join(".GIT"), 0, Removal::new()),
Outcome::Refused(Refusal::Protected)
);
assert!(fixture.path().join(".GIT/HEAD").exists());
}
#[test]
#[cfg(windows)]
fn should_refuse_a_junction_and_leave_its_target_intact() {
let fixture = tree(&["Cargo.toml", "source/precious.rs"]);
let status = std::process::Command::new("cmd")
.arg("/C")
.arg("mklink")
.arg("/J")
.arg(fixture.path().join("target"))
.arg(fixture.path().join("source"))
.status()
.expect("mklink runs");
assert!(status.success(), "the fixture junction must be created");
let guard = guard(fixture.path());
assert_eq!(
guard.remove(&fixture.path().join("target"), 0, Removal::new()),
Outcome::Refused(Refusal::Symlink)
);
assert!(
fixture.path().join("source/precious.rs").exists(),
"the junction's target survives"
);
}
#[test]
#[cfg(windows)]
fn should_resolve_the_windows_system_locations_from_the_environment() {
let resolved = resolved_protected_paths();
let system_root = std::env::var_os("SystemRoot").expect("Windows sets SystemRoot");
let canonical = Path::new(&system_root).canonicalize().expect("SystemRoot resolves");
assert!(
resolved.iter().any(|path| paths_equal(path, &canonical)),
"the real Windows directory must be protected: {resolved:?}"
);
}
#[test]
fn should_refuse_every_resolved_protected_path() {
let fixture = tree(&["Cargo.toml"]);
let guard = guard(fixture.path());
for protected in &guard.resolved_protected {
match guard.check(protected) {
Err(Refusal::Protected | Refusal::Symlink) => {}
other => panic!("`{}` was not refused: {other:?}", protected.display()),
}
}
}
#[test]
#[cfg(windows)]
fn should_read_the_volume_from_a_windows_path() {
assert!(same_volume(Path::new(r"\\?\C:\a"), Path::new(r"\\?\c:\a\b")));
assert!(!same_volume(Path::new(r"\\?\C:\a"), Path::new(r"\\?\D:\a\b")));
assert!(!same_volume(
Path::new(r"\\?\UNC\server\one"),
Path::new(r"\\?\UNC\server\two")
));
assert!(!same_volume(Path::new("relative"), Path::new(r"\\?\C:\a")));
}
#[test]
fn should_remove_an_artifact_on_the_same_filesystem_as_its_root() {
let fixture = tree(&["Cargo.toml", "target/debug/build.o"]);
let guard = Guard::new(&[fixture.path().to_path_buf()], true).expect("the root resolves");
assert_eq!(
guard.remove(&fixture.path().join("target"), 0, Removal::new()),
Outcome::Removed
);
}
#[test]
fn the_protected_denylist_is_append_only() {
const REQUIRED: &[&str] = &[
"/",
"/Applications",
"/bin",
"/boot",
"/dev",
"/etc",
"/home",
"/Library",
"/opt",
"/private",
"/proc",
"/root",
"/sbin",
"/srv",
"/sys",
"/System",
"/tmp",
"/usr",
"/var",
"/Users",
"/Volumes",
"C:\\",
"C:\\Program Files",
"C:\\Program Files (x86)",
"C:\\Users",
"C:\\Windows",
];
for required in REQUIRED {
assert!(
PROTECTED_PATHS.contains(required),
"`{required}` was removed from PROTECTED_PATHS. The list is append-only: \
removing or narrowing an entry needs an ADR 0006 amendment saying why it was \
safe, never a drive-by edit."
);
}
for vcs in [".git", ".hg", ".svn"] {
assert!(VCS_DIRS.contains(&vcs), "`{vcs}` was removed from VCS_DIRS");
}
}
#[test]
fn should_refuse_a_vcs_directory_wherever_it_appears() {
let fixture = tree(&["Cargo.toml", ".git/HEAD", "nested/.git/HEAD"]);
let guard = guard(fixture.path());
for vcs in [".git", "nested/.git"] {
assert_eq!(
guard.remove(&fixture.path().join(vcs), 0, Removal::new()),
Outcome::Refused(Refusal::Protected),
"`{vcs}` must be refused"
);
}
assert!(fixture.path().join(".git/HEAD").exists());
}
#[test]
fn should_refuse_the_home_directory_itself() {
let Some(home) = dirs::home_dir() else { return };
let fixture = tree(&["Cargo.toml"]);
let guard = guard(fixture.path());
assert_eq!(guard.check(&home).unwrap_err(), Refusal::Protected);
}
#[test]
fn should_refuse_a_path_that_vanished_between_the_walk_and_the_removal() {
let fixture = tree(&["Cargo.toml"]);
let guard = guard(fixture.path());
assert_eq!(
guard.remove(&fixture.path().join("target"), 0, Removal::new()),
Outcome::Refused(Refusal::Vanished)
);
}
#[test]
fn should_leave_the_tree_untouched_and_agree_with_a_real_run() {
let fixture = tree(&["Cargo.toml", "target/debug/build.o", "src/main.rs"]);
let guard = guard(fixture.path());
let before = snapshot(fixture.path());
let target = fixture.path().join("target");
assert_eq!(guard.remove(&target, 0, Removal::dry()), Outcome::WouldRemove);
assert_eq!(snapshot(fixture.path()), before, "a dry run must not touch the tree");
assert_eq!(guard.remove(&target, 0, Removal::new()), Outcome::Removed);
assert_eq!(
snapshot(fixture.path()),
vec!["Cargo.toml".to_owned(), "src/".to_owned(), "src/main.rs".to_owned()]
);
}
#[test]
#[cfg(unix)]
fn should_apply_every_rail_during_a_dry_run() {
let fixture = tree(&["Cargo.toml", "source/precious.rs"]);
std::os::unix::fs::symlink(fixture.path().join("source"), fixture.path().join("target")).expect("a symlink");
let guard = guard(fixture.path());
assert_eq!(
guard.remove(&fixture.path().join("target"), 0, Removal::dry()),
Outcome::Refused(Refusal::Symlink)
);
}
#[test]
fn should_reject_a_root_that_does_not_exist() {
let error = Guard::new(&[PathBuf::from("/no/such/root")], true).unwrap_err();
assert!(matches!(error, Error::ReadDir { .. }));
}
}