mod report;
use std::path::{Path, PathBuf};
use std::time::{Duration, Instant};
pub use report::{document, render_human, render_json};
use crate::delete::{Guard, Outcome, Removal};
use crate::error::Result;
use crate::size::measure_fully;
pub const SCHEMA_VERSION: u32 = 1;
const OWNER_MARKER: &str = "DO_NOT_BUILD_HERE";
#[derive(Debug, Clone)]
pub struct BazelPruneOptions {
pub roots: Vec<PathBuf>,
pub dry_run: bool,
pub force: bool,
pub one_file_system: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum OutputBaseState {
Unproven,
Owned {
owner: PathBuf,
},
Orphaned {
owner: PathBuf,
},
}
#[derive(Debug, Clone)]
pub struct OutputBase {
pub path: PathBuf,
pub state: OutputBaseState,
pub bytes: Option<u64>,
pub outcome: Option<Outcome>,
}
impl OutputBase {
#[must_use]
pub fn is_orphaned(&self) -> bool {
matches!(self.state, OutputBaseState::Orphaned { .. })
}
}
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub struct Totals {
pub found: usize,
pub removed: usize,
pub refused: usize,
pub kept: usize,
pub bytes: u64,
}
#[derive(Debug)]
pub struct BazelPruneResult {
pub roots: Vec<PathBuf>,
pub output_bases: Vec<OutputBase>,
pub dry_run: bool,
pub elapsed: Duration,
}
impl BazelPruneResult {
#[must_use]
pub fn totals(&self) -> Totals {
let mut totals = Totals {
found: self.output_bases.len(),
..Totals::default()
};
for base in &self.output_bases {
match (&base.state, &base.outcome) {
(OutputBaseState::Orphaned { .. }, Some(Outcome::Removed | Outcome::WouldRemove)) => {
totals.removed += 1;
totals.bytes += base.bytes.unwrap_or(0);
}
(OutputBaseState::Orphaned { .. }, Some(Outcome::Refused(_))) => totals.refused += 1,
(OutputBaseState::Orphaned { .. } | OutputBaseState::Owned { .. } | OutputBaseState::Unproven, _) => {
totals.kept += 1;
}
}
}
totals
}
#[must_use]
pub fn exit_code(&self) -> i32 {
let failed = self.output_bases.iter().any(|base| {
matches!(
base.outcome,
Some(Outcome::Failed(_) | Outcome::PartiallyRemoved { .. })
)
});
if failed {
crate::report::exit::REMOVAL_FAILED
} else {
crate::report::exit::SUCCESS
}
}
}
#[must_use]
pub fn conventional_roots() -> Vec<PathBuf> {
let Some(user) = current_user() else {
return Vec::new();
};
let name = format!("_bazel_{user}");
let mut roots = vec![PathBuf::from("/tmp").join(&name), PathBuf::from("/var/tmp").join(&name)];
if let Some(home) = dirs::home_dir() {
roots.push(home.join(".cache/bazel").join(&name));
}
roots
}
fn current_user() -> Option<String> {
std::env::var("USER").or_else(|_| std::env::var("USERNAME")).ok()
}
pub fn prune(options: &BazelPruneOptions) -> Result<BazelPruneResult> {
let started = Instant::now();
let mut roots = Vec::new();
let mut candidates = Vec::new();
for root in &options.roots {
let Ok(canonical) = root.canonicalize() else {
continue;
};
candidates.extend(immediate_subdirectories(&canonical));
roots.push(canonical);
}
let guard = Guard::new(&roots, options.one_file_system)?;
let removal = Removal {
dry_run: options.dry_run,
force: options.force,
};
let mut output_bases: Vec<OutputBase> = candidates
.into_iter()
.map(|path| {
let state = state_of(&path);
let (bytes, outcome) = if matches!(state, OutputBaseState::Orphaned { .. }) {
let measured = measure_fully(&path);
(Some(measured.bytes), Some(guard.remove(&path, measured.bytes, removal)))
} else {
(None, None)
};
OutputBase {
path,
state,
bytes,
outcome,
}
})
.collect();
output_bases.sort_by(|left, right| left.path.cmp(&right.path));
Ok(BazelPruneResult {
roots,
output_bases,
dry_run: options.dry_run,
elapsed: started.elapsed(),
})
}
fn immediate_subdirectories(root: &Path) -> Vec<PathBuf> {
let Ok(entries) = std::fs::read_dir(root) else {
return Vec::new();
};
entries
.flatten()
.filter(|entry| entry.file_type().is_ok_and(|file_type| file_type.is_dir()))
.map(|entry| entry.path())
.collect()
}
fn state_of(output_base: &Path) -> OutputBaseState {
let Some(owner) = read_owner(output_base) else {
return OutputBaseState::Unproven;
};
if owner.exists() {
OutputBaseState::Owned { owner }
} else {
OutputBaseState::Orphaned { owner }
}
}
fn read_owner(output_base: &Path) -> Option<PathBuf> {
for candidate in [
output_base.join(OWNER_MARKER),
output_base.join("execroot").join(OWNER_MARKER),
] {
if let Ok(contents) = std::fs::read_to_string(&candidate) {
let trimmed = contents.trim();
if !trimmed.is_empty() {
return Some(PathBuf::from(trimmed));
}
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use crate::testing::tree;
fn options(root: &Path) -> BazelPruneOptions {
BazelPruneOptions {
roots: vec![root.to_path_buf()],
dry_run: false,
force: false,
one_file_system: true,
}
}
#[test]
fn should_remove_an_output_base_whose_owner_no_longer_exists() {
let fixture = tree(&[
"_bazel_dev/abc123/execroot/armis/BUILD",
"_bazel_dev/abc123/DO_NOT_BUILD_HERE",
]);
let root = fixture.path().join("_bazel_dev");
std::fs::write(root.join("abc123/DO_NOT_BUILD_HERE"), "/nonexistent/workspace").unwrap();
let result = prune(&options(&root)).expect("the root resolves");
assert_eq!(result.output_bases.len(), 1);
let base = &result.output_bases[0];
assert!(
matches!(&base.state, OutputBaseState::Orphaned { owner } if owner == Path::new("/nonexistent/workspace"))
);
assert_eq!(base.outcome, Some(Outcome::Removed));
assert!(!base.path.exists(), "the orphan is actually gone");
}
#[test]
fn should_leave_an_owned_output_base_alone() {
let fixture = tree(&["_bazel_dev/abc123/DO_NOT_BUILD_HERE", "workspace/WORKSPACE"]);
let root = fixture.path().join("_bazel_dev");
let owner = fixture.path().join("workspace");
std::fs::write(root.join("abc123/DO_NOT_BUILD_HERE"), owner.display().to_string()).unwrap();
let result = prune(&options(&root)).expect("the root resolves");
let base = &result.output_bases[0];
assert!(matches!(&base.state, OutputBaseState::Owned { .. }));
assert!(
base.outcome.is_none(),
"nothing is even attempted against an owned base"
);
assert!(base.path.exists(), "an owned output base survives");
}
#[test]
fn should_leave_an_unmarked_directory_unproven() {
let fixture = tree(&["_bazel_dev/abc123/execroot/armis/BUILD"]);
let root = fixture.path().join("_bazel_dev");
let result = prune(&options(&root)).expect("the root resolves");
assert_eq!(result.output_bases[0].state, OutputBaseState::Unproven);
}
#[test]
fn should_read_the_execroot_marker_only_when_no_root_marker_exists() {
let fixture = tree(&["_bazel_dev/shared/execroot/DO_NOT_BUILD_HERE"]);
let root = fixture.path().join("_bazel_dev");
std::fs::write(
root.join("shared/execroot/DO_NOT_BUILD_HERE"),
"/nonexistent/last-builder",
)
.unwrap();
let result = prune(&options(&root)).expect("the root resolves");
assert!(matches!(
&result.output_bases[0].state,
OutputBaseState::Orphaned { owner } if owner == Path::new("/nonexistent/last-builder")
));
}
#[test]
fn should_leave_a_missing_root_silently_absent() {
let fixture = tree(&["keep.txt"]);
let missing = fixture.path().join("does-not-exist");
let result = prune(&options(&missing)).expect("a missing root is not an error");
assert!(result.roots.is_empty());
assert!(result.output_bases.is_empty());
}
#[test]
fn should_respect_dry_run_and_leave_the_orphan_on_disk() {
let fixture = tree(&["_bazel_dev/abc123/DO_NOT_BUILD_HERE"]);
let root = fixture.path().join("_bazel_dev");
std::fs::write(root.join("abc123/DO_NOT_BUILD_HERE"), "/nonexistent/workspace").unwrap();
let mut dry = options(&root);
dry.dry_run = true;
let result = prune(&dry).expect("the root resolves");
assert_eq!(result.output_bases[0].outcome, Some(Outcome::WouldRemove));
assert!(root.join("abc123").exists(), "a dry run removes nothing");
}
}