aboutsummaryrefslogtreecommitdiffhomepage
path: root/crates/mozart/src/commands/clear_cache.rs
blob: b6ab2f17c68215de75f09e791307a708ccca8731 (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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
use std::{borrow::Cow, path::Path};

use clap::Args;
use mozart_core::{composer::Composer, factory::create_config};
use mozart_registry::cache::Cache;

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

pub async fn execute(
    args: &ClearCacheArgs,
    cli: &super::Cli,
    console: &mozart_core::console::Console,
) -> anyhow::Result<()> {
    let composer = Composer::try_load(cli.working_dir()?)?;
    let config = if let Some(composer) = &composer {
        Cow::Borrowed(composer.config())
    } else {
        Cow::Owned(create_config()?)
    };

    let cache_paths = [
        ("cache-vcs-dir", &config.cache_vcs_dir),
        ("cache-repo-dir", &config.cache_repo_dir),
        ("cache-files-dir", &config.cache_files_dir),
        ("cache-dir", &config.cache_dir),
    ];

    for (key, path) in cache_paths {
        // only individual dirs get garbage collected
        if key == "cache-dir" && args.gc {
            continue;
        }

        let path = Path::new(path);

        if !path.exists() {
            console.info(&format!(
                "Cache directory does not exist ({key}): {}",
                path.display()
            ));
            continue;
        }

        let cache = Cache::new(path.to_owned(), config.cache_read_only);
        if !cache.is_enabled() {
            console.info(&format!("Cache is not enabled ({key}): {}", path.display()));
            continue;
        }

        if args.gc {
            console.info(&format!(
                "Garbage-collecting cache ({key}): {}",
                path.display()
            ));
            match key {
                "cache-files-dir" => cache.gc(config.cache_files_ttl, config.cache_files_maxsize)?,
                "cache-repo-dir" => cache.gc(config.cache_files_ttl, 1024 * 1024 * 1024 /* 1GB, this should almost never clear anything that is not outdated */)?,
                "cache-vcs-dir" => cache.gc_vcs(config.cache_files_ttl)?,
                _ => unreachable!(),
            };
        } else {
            console.info(&format!("Clearing cache ({key}): {}", path.display()));
            cache.clear()?;
        }
    }

    if args.gc {
        console.info("All caches garbage-collected.");
    } else {
        console.info("All caches cleared.");
    }

    Ok(())
}