Skip to main content

chub_cli/commands/
cache.rs

1use clap::{Args, Subcommand};
2use owo_colors::OwoColorize;
3
4use chub_core::cache::{clear_cache, get_cache_stats, SourceStat};
5
6#[derive(Args)]
7pub struct CacheArgs {
8    #[command(subcommand)]
9    command: CacheCommand,
10}
11
12#[derive(Subcommand)]
13enum CacheCommand {
14    /// Show cache information
15    Status,
16    /// Clear cached data
17    Clear,
18}
19
20pub fn run(args: CacheArgs, json: bool) {
21    match args.command {
22        CacheCommand::Status => run_status(json),
23        CacheCommand::Clear => run_clear(json),
24    }
25}
26
27fn run_status(json: bool) {
28    let stats = get_cache_stats();
29
30    if json {
31        println!(
32            "{}",
33            serde_json::to_string_pretty(&stats).unwrap_or_default()
34        );
35        return;
36    }
37
38    if !stats.exists || stats.sources.is_empty() {
39        eprintln!(
40            "{}",
41            "No cache found. Run `chub update` to initialize.".yellow()
42        );
43        return;
44    }
45
46    eprintln!("{}", "Cache Status\n".bold());
47    for src in &stats.sources {
48        match src {
49            SourceStat::Local { name, path } => {
50                eprintln!("  {} {}", name.bold(), "(local)".dimmed());
51                eprintln!("    Path: {}", path);
52            }
53            SourceStat::Remote {
54                name,
55                has_registry,
56                last_updated,
57                full_bundle,
58                file_count,
59                data_size,
60            } => {
61                eprintln!("  {} {}", name.bold(), "(remote)".dimmed());
62                let reg = if *has_registry {
63                    "yes".green().to_string()
64                } else {
65                    "no".red().to_string()
66                };
67                eprintln!("    Registry: {}", reg);
68                eprintln!(
69                    "    Last updated: {}",
70                    last_updated.as_deref().unwrap_or("never")
71                );
72                eprintln!(
73                    "    Full bundle: {}",
74                    if *full_bundle { "yes" } else { "no" }
75                );
76                eprintln!("    Cached files: {}", file_count);
77                eprintln!("    Size: {:.1} KB", *data_size as f64 / 1024.0);
78            }
79        }
80    }
81}
82
83fn run_clear(json: bool) {
84    clear_cache();
85
86    if json {
87        println!("{}", serde_json::json!({ "status": "cleared" }));
88    } else {
89        eprintln!("{}", "Cache cleared.".green());
90    }
91}