Skip to main content

mars_agents/cli/
cache.rs

1//! `mars cache` — manage the global source cache.
2
3use crate::error::MarsError;
4use crate::source::GlobalCache;
5
6use super::output;
7
8/// Arguments for `mars cache`.
9#[derive(Debug, clap::Args)]
10pub struct CacheArgs {
11    #[command(subcommand)]
12    pub command: CacheCommand,
13}
14
15#[derive(Debug, clap::Subcommand)]
16pub enum CacheCommand {
17    /// Remove all cached sources (archives + git clones).
18    Clean(CacheCleanArgs),
19
20    /// Show cache location and disk usage.
21    Info(CacheInfoArgs),
22}
23
24/// Arguments for `mars cache clean`.
25#[derive(Debug, clap::Args)]
26pub struct CacheCleanArgs {}
27
28/// Arguments for `mars cache info`.
29#[derive(Debug, clap::Args)]
30pub struct CacheInfoArgs {}
31
32/// Run `mars cache <subcommand>`.
33pub fn run(args: &CacheArgs, json: bool) -> Result<i32, MarsError> {
34    match &args.command {
35        CacheCommand::Clean(_) => run_clean(json),
36        CacheCommand::Info(_) => run_info(json),
37    }
38}
39
40fn run_clean(json: bool) -> Result<i32, MarsError> {
41    let cache = GlobalCache::new()?;
42
43    let archives = dir_size(&cache.archives_dir());
44    let git = dir_size(&cache.git_dir());
45
46    // Remove contents but keep the directory structure
47    remove_dir_contents(&cache.archives_dir())?;
48    remove_dir_contents(&cache.git_dir())?;
49
50    let total = archives + git;
51
52    if json {
53        println!("{{\"freed_bytes\":{total},\"archives_bytes\":{archives},\"git_bytes\":{git}}}");
54    } else {
55        output::print_info(&format!(
56            "cleaned {} (archives: {}, git: {})",
57            format_bytes(total),
58            format_bytes(archives),
59            format_bytes(git),
60        ));
61    }
62
63    Ok(0)
64}
65
66fn run_info(json: bool) -> Result<i32, MarsError> {
67    let cache = GlobalCache::new()?;
68
69    let archives = dir_size(&cache.archives_dir());
70    let git = dir_size(&cache.git_dir());
71    let total = archives + git;
72    let path = cache.root.display().to_string();
73
74    if json {
75        println!(
76            "{{\"path\":\"{path}\",\"total_bytes\":{total},\"archives_bytes\":{archives},\"git_bytes\":{git}}}"
77        );
78    } else {
79        println!("path:     {path}");
80        println!("total:    {}", format_bytes(total));
81        println!("archives: {}", format_bytes(archives));
82        println!("git:      {}", format_bytes(git));
83    }
84
85    Ok(0)
86}
87
88/// Calculate total size of all files in a directory tree.
89fn dir_size(path: &std::path::Path) -> u64 {
90    if !path.exists() {
91        return 0;
92    }
93    walkdir::WalkDir::new(path)
94        .into_iter()
95        .filter_map(|e| e.ok())
96        .filter(|e| e.file_type().is_file())
97        .filter_map(|e| e.metadata().ok())
98        .map(|m| m.len())
99        .sum()
100}
101
102/// Remove all contents of a directory without removing the directory itself.
103fn remove_dir_contents(path: &std::path::Path) -> Result<(), MarsError> {
104    if !path.exists() {
105        return Ok(());
106    }
107    for entry in std::fs::read_dir(path)? {
108        let entry = entry?;
109        let entry_path = entry.path();
110        if entry_path.is_dir() {
111            std::fs::remove_dir_all(&entry_path)?;
112        } else {
113            std::fs::remove_file(&entry_path)?;
114        }
115    }
116    Ok(())
117}
118
119/// Format bytes as human-readable string.
120fn format_bytes(bytes: u64) -> String {
121    if bytes < 1024 {
122        format!("{bytes} B")
123    } else if bytes < 1024 * 1024 {
124        format!("{:.1} KB", bytes as f64 / 1024.0)
125    } else if bytes < 1024 * 1024 * 1024 {
126        format!("{:.1} MB", bytes as f64 / (1024.0 * 1024.0))
127    } else {
128        format!("{:.1} GB", bytes as f64 / (1024.0 * 1024.0 * 1024.0))
129    }
130}
131
132#[cfg(test)]
133mod tests {
134    use super::*;
135
136    #[test]
137    fn format_bytes_ranges() {
138        assert_eq!(format_bytes(0), "0 B");
139        assert_eq!(format_bytes(512), "512 B");
140        assert_eq!(format_bytes(1024), "1.0 KB");
141        assert_eq!(format_bytes(1536), "1.5 KB");
142        assert_eq!(format_bytes(1024 * 1024), "1.0 MB");
143        assert_eq!(format_bytes(1024 * 1024 * 1024), "1.0 GB");
144    }
145
146    #[test]
147    fn dir_size_empty() {
148        let dir = tempfile::TempDir::new().unwrap();
149        assert_eq!(dir_size(dir.path()), 0);
150    }
151
152    #[test]
153    fn dir_size_with_files() {
154        let dir = tempfile::TempDir::new().unwrap();
155        std::fs::write(dir.path().join("a.txt"), "hello").unwrap();
156        std::fs::write(dir.path().join("b.txt"), "world!").unwrap();
157        assert_eq!(dir_size(dir.path()), 11); // 5 + 6
158    }
159
160    #[test]
161    fn dir_size_nonexistent() {
162        assert_eq!(dir_size(std::path::Path::new("/nonexistent/path")), 0);
163    }
164
165    #[test]
166    fn remove_dir_contents_clears_files() {
167        let dir = tempfile::TempDir::new().unwrap();
168        std::fs::write(dir.path().join("a.txt"), "hello").unwrap();
169        std::fs::create_dir_all(dir.path().join("sub")).unwrap();
170        std::fs::write(dir.path().join("sub").join("b.txt"), "world").unwrap();
171
172        remove_dir_contents(dir.path()).unwrap();
173
174        assert!(dir.path().exists()); // directory itself survives
175        assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0); // but empty
176    }
177
178    #[test]
179    fn remove_dir_contents_nonexistent_ok() {
180        assert!(remove_dir_contents(std::path::Path::new("/nonexistent")).is_ok());
181    }
182}