use std::path::Path;
use tokio;
pub async fn empty_dir<P: AsRef<Path>>(path: P) -> anyhow::Result<()> {
let mut entries = tokio::fs::read_dir(path).await?;
while let Some(entry) = entries.next_entry().await? {
if entry.file_type().await?.is_dir() {
tokio::fs::remove_dir_all(entry.path()).await?
} else {
tokio::fs::remove_file(entry.path()).await?;
}
}
Ok(())
}
#[cfg(test)]
mod tests {
use tempfile;
use super::*;
#[tokio::test]
async fn test_empty_dir() -> anyhow::Result<()> {
let tempdir = tempfile::tempdir()?;
let file_path = tempdir.path().join("file");
tokio::fs::File::create(file_path).await?;
let subdir = tempdir.path().join("subdir");
tokio::fs::create_dir(&subdir).await?;
let subfile_path = subdir.join("subfile");
tokio::fs::File::create(subfile_path).await?;
empty_dir(tempdir.path()).await?;
assert!(tokio::fs::read_dir(tempdir.path())
.await?
.next_entry()
.await?
.is_none());
Ok(())
}
}