aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/mozart/src/commands/clear_cache.rs
blob: 59baff3cff798a874b510b6395541c0fbd4e94c1 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
use crate::cache::{Cache, build_cache_config};
use clap::Args;

#[derive(Args)]
pub struct ClearCacheArgs {
    /// Only run garbage collection, not a full cache clear
    #[arg(long)]
    pub gc: bool,
}

pub fn execute(
    args: &ClearCacheArgs,
    cli: &super::Cli,
    console: &crate::console::Console,
) -> anyhow::Result<()> {
    let config = build_cache_config(cli);

    if args.gc {
        // Run GC only (probabilistic under normal circumstances, but forced here)
        let repo_cache = Cache::repo(&config);
        let files_cache = Cache::files(&config);

        repo_cache.gc(config.cache_ttl, u64::MAX)?;
        files_cache.gc(config.cache_files_ttl, config.cache_files_maxsize)?;

        console.info("Cache garbage collection complete.");
        console.info(&format!("Cache directory: {}", config.cache_dir.display()));
    } else {
        // Full clear of all cache directories
        let repo_cache = Cache::repo(&config);
        let files_cache = Cache::files(&config);
        repo_cache.clear()?;
        files_cache.clear()?;
        // Clear anything else at the root that isn't covered by sub-caches
        if config.cache_dir.exists() {
            for entry in std::fs::read_dir(&config.cache_dir)? {
                let entry = entry?;
                let path = entry.path();
                // Skip repo/files subdirs (already cleared above)
                if path == config.cache_files_dir || path == config.cache_repo_dir {
                    continue;
                }
                if path.is_file() {
                    std::fs::remove_file(&path)?;
                } else if path.is_dir() {
                    std::fs::remove_dir_all(&path)?;
                }
            }
        }

        console.info("Cache cleared.");
        console.info(&format!("Cache directory: {}", config.cache_dir.display()));
    }

    Ok(())
}