ym 0.3.67

Yummy - A modern Java build tool
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
use anyhow::{Result, bail};
use console::style;
use std::path::{Path, PathBuf};

use crate::config;

pub fn execute(yes: bool, pattern: Option<&str>) -> Result<()> {
    let project = std::env::current_dir()
        .ok()
        .and_then(|cwd| config::find_config(&cwd))
        .map(|cfg_path| config::project_dir(&cfg_path));

    let maven_cache = config::maven_cache_dir();
    let pom_cache = config::pom_cache_dir();

    match pattern {
        Some(pat) => clean_pattern(&maven_cache, &pom_cache, project.as_deref(), pat, yes),
        None => clean_all(&maven_cache, &pom_cache, project.as_deref(), yes),
    }
}

fn clean_all(
    maven_cache: &Path,
    pom_cache: &Path,
    _project: Option<&Path>,
    yes: bool,
) -> Result<()> {
    let size = config::dir_size(maven_cache) + config::dir_size(pom_cache);

    if size == 0 {
        println!("  {} No cache to clean", style("").green());
        return Ok(());
    }

    if !yes {
        let confirm = dialoguer::Confirm::new()
            .with_prompt(format!(
                "  Delete entire dependency cache ({})?",
                config::format_size(size)
            ))
            .default(false)
            .interact()?;
        if !confirm {
            println!("  {} Cancelled", style("!").yellow());
            return Ok(());
        }
    }

    if maven_cache.exists() {
        std::fs::remove_dir_all(maven_cache)?;
        println!("  {} Removed {}", style("").green(), maven_cache.display());
    }
    if pom_cache.exists() {
        std::fs::remove_dir_all(pom_cache)?;
        println!("  {} Removed {}", style("").green(), pom_cache.display());
    }

    // NOTE: Do NOT touch ym-lock.json. Lockfile is git-tracked source
    // (like Cargo.lock / package-lock.json / yarn.lock), not cache.
    // Touching it breaks `--frozen-lockfile`. See ADR-016.
    // Industry standard: `npm cache clean` / `cargo clean` / `pnpm store prune`
    // all leave the lockfile alone.

    println!(
        "  {} Cache clean complete ({} freed)",
        style("").green(),
        config::format_size(size)
    );
    Ok(())
}

#[derive(Debug)]
enum CachePattern {
    /// Match by artifactId only, across any groupId. The artifactId must
    /// equal the cache directory name exactly — no substring semantics.
    ArtifactAnyGroup(String),
    GroupWildcard(String),
    Ga { group: String, artifact: String },
    Gav { group: String, artifact: String, version: String },
}

impl CachePattern {
    fn parse(raw: &str) -> Result<Self> {
        let parts: Vec<&str> = raw.split(':').collect();
        match parts.as_slice() {
            [a] if !a.is_empty() => Ok(Self::ArtifactAnyGroup((*a).to_string())),
            [g, "*"] if !g.is_empty() => Ok(Self::GroupWildcard((*g).to_string())),
            [g, a] if !g.is_empty() && !a.is_empty() => Ok(Self::Ga {
                group: (*g).to_string(),
                artifact: (*a).to_string(),
            }),
            [g, a, v] if !g.is_empty() && !a.is_empty() && !v.is_empty() => Ok(Self::Gav {
                group: (*g).to_string(),
                artifact: (*a).to_string(),
                version: (*v).to_string(),
            }),
            _ => bail!(
                "Invalid pattern '{}'. Expected: <artifact>, <group>:*, <group>:<artifact>, or <group>:<artifact>:<version>",
                raw
            ),
        }
    }
}

/// Collect paths matching `pat` within a cache rooted at `cache`.
/// `gav_leaf` maps the `{group}/{artifact}/{version}` triple to the actual
/// filesystem entry that represents the GAV — a directory for the Maven
/// cache (`~/.ym/maven/...`) but a `{version}.json` file for the POM cache
/// (`~/.ym/pom-cache/...`). Non-existent candidates are filtered out.
fn match_cache<F>(cache: &Path, pat: &CachePattern, gav_leaf: F) -> Vec<PathBuf>
where
    F: Fn(&Path, &str, &str, &str) -> PathBuf,
{
    let mut matches = Vec::new();

    match pat {
        CachePattern::ArtifactAnyGroup(artifact) => {
            // `read_dir` on a missing cache path returns Err, handled here;
            // no separate `cache.exists()` pre-check needed.
            let Ok(groups) = std::fs::read_dir(cache) else { return matches };
            for entry in groups.flatten() {
                if !entry.file_type().map(|t| t.is_dir()).unwrap_or(false) {
                    continue;
                }
                let artifact_dir = entry.path().join(artifact);
                if artifact_dir.is_dir() {
                    matches.push(artifact_dir);
                }
            }
        }
        CachePattern::GroupWildcard(group) => {
            let p = cache.join(group);
            if p.is_dir() {
                matches.push(p);
            }
        }
        CachePattern::Ga { group, artifact } => {
            let p = cache.join(group).join(artifact);
            if p.is_dir() {
                matches.push(p);
            }
        }
        CachePattern::Gav { group, artifact, version } => {
            let p = gav_leaf(cache, group, artifact, version);
            if p.exists() {
                matches.push(p);
            }
        }
    }

    matches
}

fn match_maven_cache(cache: &Path, pat: &CachePattern) -> Vec<PathBuf> {
    // Maven cache GAV leaf: `{group}/{artifact}/{version}/` (directory)
    match_cache(cache, pat, |root, g, a, v| root.join(g).join(a).join(v))
}

fn match_pom_cache(cache: &Path, pat: &CachePattern) -> Vec<PathBuf> {
    // POM cache GAV leaf: `{group}/{artifact}/{version}.json` (file)
    match_cache(cache, pat, |root, g, a, v| {
        root.join(g).join(a).join(format!("{}.json", v))
    })
}

fn clean_pattern(
    maven_cache: &Path,
    pom_cache: &Path,
    _project: Option<&Path>,
    pattern: &str,
    yes: bool,
) -> Result<()> {
    let pat = CachePattern::parse(pattern)?;
    let mut matches = match_maven_cache(maven_cache, &pat);
    matches.extend(match_pom_cache(pom_cache, &pat));

    if matches.is_empty() {
        println!(
            "  {} No cache entries matched '{}'",
            style("!").yellow(),
            pattern
        );
        return Ok(());
    }

    let total_size: u64 = matches.iter().map(|p| path_size(p)).sum();

    if !yes {
        println!(
            "  {} Matched {} entr{} for '{}':",
            style("").cyan(),
            matches.len(),
            if matches.len() == 1 { "y" } else { "ies" },
            pattern
        );
        for p in &matches {
            println!("    {}", p.display());
        }
        let confirm = dialoguer::Confirm::new()
            .with_prompt(format!(
                "  Delete matched entries ({})?",
                config::format_size(total_size)
            ))
            .default(false)
            .interact()?;
        if !confirm {
            println!("  {} Cancelled", style("!").yellow());
            return Ok(());
        }
    }

    for p in &matches {
        remove_path(p)?;
        println!("  {} Removed {}", style("").green(), p.display());
    }

    // NOTE: Do NOT touch ym-lock.json here. Lockfile is git-tracked source
    // (like Cargo.lock / package-lock.json / yarn.lock), not cache. Touching
    // it breaks `--frozen-lockfile` builds. See ADR-016.
    // Industry standard: `npm cache clean` / `cargo clean` / `pnpm store prune`
    // all leave the lockfile alone.

    println!(
        "  {} Cache clean complete ({} freed)",
        style("").green(),
        config::format_size(total_size)
    );
    Ok(())
}

fn remove_path(p: &Path) -> Result<()> {
    match std::fs::metadata(p) {
        Ok(m) if m.is_dir() => std::fs::remove_dir_all(p)?,
        Ok(_) => std::fs::remove_file(p)?,
        // Already gone between match and remove — idempotent, fine.
        Err(e) if e.kind() == std::io::ErrorKind::NotFound => {}
        Err(e) => return Err(e.into()),
    }
    Ok(())
}

fn path_size(p: &Path) -> u64 {
    // Single stat for both file-or-dir dispatch + size readout.
    match std::fs::metadata(p) {
        Ok(m) if m.is_file() => m.len(),
        Ok(_) => config::dir_size(p),
        Err(_) => 0,
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn parse_artifact_any_group() {
        match CachePattern::parse("theme-service").unwrap() {
            CachePattern::ArtifactAnyGroup(a) => assert_eq!(a, "theme-service"),
            other => panic!("expected ArtifactAnyGroup, got {:?}", other),
        }
    }

    #[test]
    fn parse_group_wildcard() {
        match CachePattern::parse("com.summer.jarvis:*").unwrap() {
            CachePattern::GroupWildcard(g) => assert_eq!(g, "com.summer.jarvis"),
            other => panic!("expected GroupWildcard, got {:?}", other),
        }
    }

    #[test]
    fn parse_ga_exact() {
        match CachePattern::parse("com.summer.jarvis:theme-service").unwrap() {
            CachePattern::Ga { group, artifact } => {
                assert_eq!(group, "com.summer.jarvis");
                assert_eq!(artifact, "theme-service");
            }
            other => panic!("expected Ga, got {:?}", other),
        }
    }

    #[test]
    fn parse_gav_exact() {
        match CachePattern::parse("com.summer.jarvis:theme-service:4.0.12").unwrap() {
            CachePattern::Gav { group, artifact, version } => {
                assert_eq!(group, "com.summer.jarvis");
                assert_eq!(artifact, "theme-service");
                assert_eq!(version, "4.0.12");
            }
            other => panic!("expected Gav, got {:?}", other),
        }
    }

    #[test]
    fn parse_invalid_empty() {
        assert!(CachePattern::parse("").is_err());
        assert!(CachePattern::parse(":").is_err());
        assert!(CachePattern::parse("a:").is_err());
        assert!(CachePattern::parse(":b").is_err());
    }

    #[test]
    fn parse_invalid_too_many_parts() {
        assert!(CachePattern::parse("a:b:c:d").is_err());
    }

    #[test]
    fn match_maven_artifact_fuzzy() {
        let tmp = tempfile::tempdir().unwrap();
        let cache = tmp.path();
        std::fs::create_dir_all(cache.join("com.example").join("foo").join("1.0")).unwrap();
        std::fs::create_dir_all(cache.join("org.other").join("foo").join("2.0")).unwrap();
        std::fs::create_dir_all(cache.join("com.example").join("bar").join("1.0")).unwrap();

        let matches = match_maven_cache(cache, &CachePattern::ArtifactAnyGroup("foo".to_string()));
        assert_eq!(matches.len(), 2);
    }

    #[test]
    fn match_maven_gav_exact() {
        let tmp = tempfile::tempdir().unwrap();
        let cache = tmp.path();
        std::fs::create_dir_all(cache.join("com.example").join("foo").join("1.0")).unwrap();
        std::fs::create_dir_all(cache.join("com.example").join("foo").join("2.0")).unwrap();

        let matches = match_maven_cache(
            cache,
            &CachePattern::Gav {
                group: "com.example".to_string(),
                artifact: "foo".to_string(),
                version: "1.0".to_string(),
            },
        );
        assert_eq!(matches.len(), 1);
        assert!(matches[0].ends_with("1.0"));
    }

    // --- Regression tests: cache clean must NOT touch ym-lock.json (ADR-016) ---
    // Lockfile is git-tracked source (like Cargo.lock / package-lock.json),
    // not cache. Touching it breaks `--frozen-lockfile`.

    #[test]
    fn clean_all_preserves_lockfile() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path();
        std::fs::write(project.join("ym.json"), r#"{"name":"test"}"#).unwrap();
        let lock_path = project.join("ym-lock.json");
        std::fs::write(&lock_path, r#"{"lockfile_version":1,"dependencies":{}}"#).unwrap();

        let maven_cache = tmp.path().join("maven");
        std::fs::create_dir_all(&maven_cache).unwrap();
        std::fs::write(maven_cache.join("dummy"), "x").unwrap();
        let pom_cache = tmp.path().join("pom-cache");
        std::fs::create_dir_all(&pom_cache).unwrap();

        clean_all(&maven_cache, &pom_cache, Some(project), true).unwrap();

        assert!(
            lock_path.exists(),
            "clean_all must NOT delete ym-lock.json (lockfile is git-tracked source, not cache)"
        );
    }

    #[test]
    fn clean_pattern_preserves_lockfile() {
        let tmp = tempfile::tempdir().unwrap();
        let project = tmp.path();
        std::fs::write(project.join("ym.json"), r#"{"name":"test"}"#).unwrap();
        let lock_path = project.join("ym-lock.json");
        std::fs::write(&lock_path, r#"{"lockfile_version":1,"dependencies":{}}"#).unwrap();

        let maven_cache = tmp.path().join("maven");
        std::fs::create_dir_all(maven_cache.join("com.example").join("foo").join("1.0")).unwrap();
        let pom_cache = tmp.path().join("pom-cache");
        std::fs::create_dir_all(&pom_cache).unwrap();

        clean_pattern(
            &maven_cache,
            &pom_cache,
            Some(project),
            "com.example:foo:1.0",
            true,
        )
        .unwrap();

        assert!(
            lock_path.exists(),
            "clean_pattern must NOT delete ym-lock.json (lockfile is git-tracked source, not cache)"
        );
    }

    #[test]
    fn match_pom_gav_is_file() {
        let tmp = tempfile::tempdir().unwrap();
        let cache = tmp.path();
        let group_dir = cache.join("com.example").join("foo");
        std::fs::create_dir_all(&group_dir).unwrap();
        std::fs::write(group_dir.join("1.0.json"), "[]").unwrap();

        let matches = match_pom_cache(
            cache,
            &CachePattern::Gav {
                group: "com.example".to_string(),
                artifact: "foo".to_string(),
                version: "1.0".to_string(),
            },
        );
        assert_eq!(matches.len(), 1);
        assert!(matches[0].is_file());
    }
}