use cstats_core::{cache::FileCache, config::Config, Result};
use tracing::info;
use crate::{CacheAction, CacheArgs};
pub async fn cache_command(args: CacheArgs, config: &Config) -> Result<()> {
let cache = FileCache::new(config.cache.clone());
match args.action {
CacheAction::Stats => {
info!("Getting cache statistics");
let stats = cache.stats().await?;
println!("\n=== Cache Statistics ===");
println!("Cache directory: {}", stats.cache_dir.display());
println!("Total entries: {}", stats.entry_count);
println!("Expired entries: {}", stats.expired_count);
println!(
"Total size: {} bytes ({:.2} MB)",
stats.total_size_bytes,
stats.total_size_bytes as f64 / 1024.0 / 1024.0
);
let active_entries = stats.entry_count - stats.expired_count;
println!("Active entries: {}", active_entries);
}
CacheAction::Clear => {
info!("Clearing cache");
cache.clear().await?;
println!("Cache cleared successfully");
}
CacheAction::List => {
info!("Listing cache entries");
let stats = cache.stats().await?;
println!("\n=== Cache Entries ===");
println!("Cache directory: {}", stats.cache_dir.display());
if stats.cache_dir.exists() {
let mut entries = tokio::fs::read_dir(&stats.cache_dir).await?;
let mut count = 0;
while let Some(entry) = entries.next_entry().await? {
if entry.file_type().await?.is_file() {
let metadata = entry.metadata().await?;
let modified = metadata.modified()?;
let size = metadata.len();
println!(
"{}: {} bytes, modified: {:?}",
entry.file_name().to_string_lossy(),
size,
modified
);
count += 1;
}
}
if count == 0 {
println!("No cache entries found");
}
} else {
println!("Cache directory does not exist");
}
}
}
Ok(())
}