use crate::utils::paths::{artifacts_dir, test_target_dir};
use std::fs;
use std::io;
use std::path::Path;
use walkdir::WalkDir;
fn is_effectively_empty(path: &Path) -> bool {
if !path.is_dir() {
return false;
}
for entry in WalkDir::new(path).min_depth(1) {
match entry {
Ok(entry) => {
if !entry.file_type().is_dir() {
return false;
}
}
Err(_) => {
return false;
}
}
}
true
}
fn remove_empty_directories(path: &Path) -> bool {
if !path.is_dir() || !is_effectively_empty(path) {
return false;
}
if let Ok(entries) = fs::read_dir(path) {
for entry in entries.filter_map(Result::ok) {
let path = entry.path();
if path.is_dir() {
remove_empty_directories(&path);
}
}
}
match fs::remove_dir(path) {
Ok(_) => {
println!("Removed empty directory: {}", path.display());
true
}
Err(e) => {
println!(
"Warning: Failed to clean up empty directory '{}': {}",
path.display(),
e
);
false
}
}
}
pub fn cleanup_single_test_dir(output_dir: &Path, test_name: &str) -> io::Result<()> {
let target_dir = test_target_dir(output_dir, test_name);
if target_dir.exists() {
println!("Cleaning up target directory for test: {}", test_name);
fs::remove_dir_all(&target_dir)?;
}
if let Some(parent) = target_dir.parent() {
if parent.exists() && is_effectively_empty(parent) {
let _ = remove_empty_directories(parent);
}
}
Ok(())
}
pub fn cleanup_target_dirs(output_dir: &Path, test_names: &[String]) {
println!("Cleaning up temporary target directories...");
let artifacts_directory = artifacts_dir(output_dir);
for test_name in test_names {
if let Err(e) = cleanup_single_test_dir(output_dir, test_name) {
println!(
"Warning: Failed to clean up directory for test '{}': {}",
test_name, e
);
}
}
if artifacts_directory.exists() {
remove_empty_directories(&artifacts_directory);
}
}