Skip to main content

cortex_runtime/cli/
cache_cmd.rs

1//! `cortex cache` — manage cached maps.
2
3use crate::cli::doctor::cortex_home;
4use crate::cli::output::{self, Styled};
5use anyhow::Result;
6use std::path::PathBuf;
7
8/// Clear cached maps.
9pub async fn run_clear(domain: Option<&str>) -> Result<()> {
10    let s = Styled::new();
11    let maps_dir = cortex_home().join("maps");
12
13    match domain {
14        Some(d) => {
15            // Clear specific domain
16            let map_path = maps_dir.join(format!("{d}.ctx"));
17            if map_path.exists() {
18                std::fs::remove_file(&map_path)?;
19                if output::is_json() {
20                    output::print_json(&serde_json::json!({
21                        "cleared": d,
22                    }));
23                } else if !output::is_quiet() {
24                    eprintln!("  {} Cleared cached map for '{d}'.", s.ok_sym());
25                }
26            } else if output::is_json() {
27                output::print_json(&serde_json::json!({
28                    "error": "not_found",
29                    "message": format!("No cached map for '{d}'"),
30                }));
31            } else if !output::is_quiet() {
32                eprintln!("  No cached map for '{d}'.");
33            }
34        }
35        None => {
36            // Clear all
37            let mut count = 0;
38            let mut size = 0u64;
39            if let Ok(entries) = std::fs::read_dir(&maps_dir) {
40                for entry in entries.flatten() {
41                    let path = entry.path();
42                    if path.extension().is_some_and(|e| e == "ctx") {
43                        if let Ok(meta) = path.metadata() {
44                            size += meta.len();
45                        }
46                        std::fs::remove_file(&path)?;
47                        count += 1;
48                    }
49                }
50            }
51
52            if output::is_json() {
53                output::print_json(&serde_json::json!({
54                    "cleared_count": count,
55                    "cleared_bytes": size,
56                }));
57            } else if !output::is_quiet() {
58                if count > 0 {
59                    eprintln!(
60                        "  {} Cleared {count} cached map(s) ({}).",
61                        s.ok_sym(),
62                        output::format_size(size)
63                    );
64                } else {
65                    eprintln!("  No cached maps to clear.");
66                }
67            }
68        }
69    }
70
71    Ok(())
72}