Avoid error when repeatedly clearing cache (#51)

Also avoid failing to clear the cache when it contains non-directories
(e.g., I had a `.DS_Store` after looking at it in Finder).
This commit is contained in:
Charlie Marsh 2023-10-08 00:16:48 -04:00 committed by GitHub
parent 2a846e76b7
commit fd5aef2c75
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -1,6 +1,6 @@
use std::path::Path;
use anyhow::Result;
use anyhow::{Context, Result};
use tracing::info;
use crate::commands::ExitStatus;
@ -11,7 +11,32 @@ pub(crate) async fn clean(cache: Option<&Path>) -> Result<ExitStatus> {
return Err(anyhow::anyhow!("No cache found"));
};
if !cache.exists() {
return Ok(ExitStatus::Success);
}
info!("Clearing cache at {}", cache.display());
cacache::clear(cache).await?;
for entry in cache
.read_dir()
.with_context(|| {
format!(
"Failed to read directory contents while clearing {}",
cache.display()
)
})?
.flatten()
{
if entry.file_type()?.is_dir() {
tokio::fs::remove_dir_all(entry.path())
.await
.with_context(|| format!("Failed to clear cache at {}", cache.display()))?;
} else {
tokio::fs::remove_file(entry.path())
.await
.with_context(|| format!("Failed to clear cache at {}", cache.display()))?;
}
}
Ok(ExitStatus::Success)
}