deepclean 0.1.6

Fast, parallel Rust tool to clean Cargo target/ directories, remove unused dependencies, and free disk space from global toolchain caches (npm, Bun, cargo, pip, uv, Homebrew, HuggingFace, and more)
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
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
use crate::utils::{format_bytes, get_directory_size_parallel, home_dir};
use anyhow::Result;
use colored::Colorize;
use rayon::prelude::*;
use serde::Serialize;
use std::ffi::OsString;
use std::io::{self, BufRead, Write};
use std::path::{Path, PathBuf};

/// A discoverable global toolchain cache that can be cleaned.
#[derive(Debug, Clone, Serialize)]
pub struct CacheEntry {
    pub id: String,
    pub name: String,
    pub category: String,
    /// "safe" = pure download cache (re-fetches on demand);
    /// "heavy" = re-download required (model weights, browser binaries, runtimes).
    pub risk: String,
    #[serde(skip)]
    paths: Vec<PathBuf>,
    pub size_bytes: u64,
    pub note: Option<String>,
}

impl CacheEntry {
    fn new(id: &str, name: &str, category: &str, risk: &str, paths: Vec<PathBuf>) -> Self {
        Self {
            id: id.to_string(),
            name: name.to_string(),
            category: category.to_string(),
            risk: risk.to_string(),
            paths,
            size_bytes: 0,
            note: None,
        }
    }

    fn with_note(mut self, note: &str) -> Self {
        self.note = Some(note.to_string());
        self
    }
}

#[derive(Debug, Serialize)]
pub struct CacheCleanResult {
    pub id: String,
    pub name: String,
    pub success: bool,
    pub freed_bytes: u64,
    pub error: Option<String>,
}

/// Build the full registry of known caches. Paths that do not exist are filtered
/// out later by [`discover_caches`].
pub fn build_registry() -> Vec<CacheEntry> {
    let home = match home_dir() {
        Some(h) => h,
        None => return Vec::new(),
    };
    let xdg = env_base_dir(
        std::env::var_os("XDG_CACHE_HOME"),
        home.join(".cache"),
    );
    let mac = home.join("Library/Caches");
    let win_local = env_base_dir(
        std::env::var_os("LOCALAPPDATA"),
        home.join("AppData/Local"),
    );
    let app_support = home.join("Library/Application Support");
    let config = env_base_dir(
        std::env::var_os("XDG_CONFIG_HOME"),
        home.join(".config"),
    );
    let win_roaming = env_base_dir(
        std::env::var_os("APPDATA"),
        home.join("AppData/Roaming"),
    );
    build_registry_for(&home, &xdg, &mac, &win_local, &app_support, &config, &win_roaming)
}

/// Resolve a base directory from an env var, falling back when unset **or empty**.
///
/// A set-but-empty value must not swallow the fallback (it would yield a bogus
/// relative path `""`) — same lesson as `utils::resolve_home`. Pure so it is
/// testable without mutating process environment.
fn env_base_dir(env: Option<OsString>, fallback: PathBuf) -> PathBuf {
    env.filter(|v| !v.is_empty())
        .map(PathBuf::from)
        .unwrap_or(fallback)
}

/// Build the registry from explicit base directories (pure, testable).
///
/// Base-dir conventions:
/// - `home`: `$HOME` / `%USERPROFILE%` — tool dirs like `.cargo`, `.npm`, `.bun`
/// - `xdg`: `$XDG_CACHE_HOME`, defaulting to `~/.cache` (also where Windows tools
///   like puppeteer/HuggingFace/torch live, since `%USERPROFILE%\.cache` is their default)
/// - `mac`: `~/Library/Caches` (macOS per-tool cache subdirs)
/// - `win_local`: `%LOCALAPPDATA%`, defaulting to `~/AppData/Local` (Windows per-tool caches)
/// - `app_support`: `~/Library/Application Support` (macOS Electron-app cache dirs)
/// - `config`: `$XDG_CONFIG_HOME`, defaulting to `~/.config` (Linux Electron-app dirs)
/// - `win_roaming`: `%APPDATA%`, defaulting to `~/AppData/Roaming` (Windows Electron-app dirs)
fn build_registry_for(
    home: &Path,
    xdg: &Path,
    mac: &Path,
    win_local: &Path,
    app_support: &Path,
    config: &Path,
    win_roaming: &Path,
) -> Vec<CacheEntry> {
    let vscode_paths = vscode_family_paths(app_support, config, win_roaming);
    vec![
        // Rust
        CacheEntry::new(
            "cargo-cache",
            "Cargo registry cache",
            "Rust",
            "safe",
            vec![home.join(".cargo/registry/cache")],
        ),
        CacheEntry::new(
            "cargo-src",
            "Cargo registry src",
            "Rust",
            "heavy",
            vec![home.join(".cargo/registry/src")],
        )
        .with_note("Unpacked crate sources; re-extracts on next build"),
        CacheEntry::new(
            "cargo-git",
            "Cargo git checkouts",
            "Rust",
            "safe",
            vec![home.join(".cargo/git")],
        )
        .with_note("Git dep checkouts; re-clones on next build"),
        CacheEntry::new(
            "sccache",
            "sccache",
            "Rust",
            "safe",
            vec![
                mac.join("Mozilla.sccache"),
                xdg.join("sccache"),
                win_local.join("Mozilla/sccache"),
            ],
        ),
        // Python
        CacheEntry::new(
            "pip",
            "pip",
            "Python",
            "safe",
            vec![mac.join("pip"), xdg.join("pip"), win_local.join("pip")],
        ),
        CacheEntry::new(
            "uv",
            "uv",
            "Python",
            "safe",
            vec![
                xdg.join("uv"),
                mac.join("uv"),
                win_local.join("uv"),
            ],
        ),
        CacheEntry::new(
            "poetry",
            "Poetry",
            "Python",
            "safe",
            vec![
                mac.join("pypoetry"),
                xdg.join("pypoetry"),
                win_local.join("pypoetry"),
            ],
        ),
        CacheEntry::new(
            "conda",
            "Conda pkgs",
            "Python",
            "safe",
            vec![
                home.join("anaconda3/pkgs"),
                home.join("miniconda3/pkgs"),
                home.join("miniforge3/pkgs"),
                home.join(".conda/pkgs"),
            ],
        )
        .with_note("Package cache; re-downloads on env create (envs unaffected)"),
        // JS/TS
        CacheEntry::new(
            "npm",
            "npm",
            "JS/TS",
            "safe",
            vec![
                home.join(".npm/_cacache"),
                home.join(".npm/_npx"),
                win_local.join("npm-cache"),
            ],
        ),
        CacheEntry::new(
            "bun",
            "Bun install cache",
            "JS/TS",
            "safe",
            vec![home.join(".bun/install/cache"), mac.join("bun")],
        ),
        CacheEntry::new(
            "pnpm",
            "pnpm store",
            "JS/TS",
            "safe",
            vec![
                home.join(".local/share/pnpm"),
                home.join("Library/pnpm"),
                win_local.join("pnpm"),
            ],
        ),
        CacheEntry::new(
            "yarn",
            "Yarn cache",
            "JS/TS",
            "safe",
            vec![
                mac.join("Yarn"),
                home.join(".yarn"),
                win_local.join("Yarn"),
            ],
        ),
        CacheEntry::new(
            "deno",
            "Deno",
            "JS/TS",
            "safe",
            vec![mac.join("deno"), xdg.join("deno"), win_local.join("deno")],
        ),
        CacheEntry::new(
            "node-gyp",
            "node-gyp",
            "JS/TS",
            "safe",
            vec![
                mac.join("node-gyp"),
                xdg.join("node-gyp"),
                win_local.join("node-gyp"),
            ],
        ),
        CacheEntry::new("vercel", "Vercel CLI", "JS/TS", "safe", vec![mac.join("com.vercel.cli")]),
        CacheEntry::new(
            "prisma",
            "Prisma engines",
            "JS/TS",
            "heavy",
            vec![xdg.join("prisma"), mac.join("prisma")],
        )
        .with_note("Engine binaries; re-downloads on next prisma generate"),
        CacheEntry::new(
            "chrome-devtools-mcp",
            "Chrome DevTools MCP",
            "JS/TS",
            "heavy",
            vec![xdg.join("chrome-devtools-mcp")],
        )
        .with_note("Chrome-for-testing binaries; re-downloads on next run"),
        CacheEntry::new(
            "selenium",
            "Selenium Manager",
            "JS/TS",
            "heavy",
            vec![xdg.join("selenium")],
        )
        .with_note("Browser/driver binaries; re-downloads on next run"),
        // .NET
        CacheEntry::new(
            "nuget",
            "NuGet packages",
            ".NET",
            "safe",
            vec![home.join(".nuget/packages")],
        )
        .with_note("Global package cache; re-downloads on next restore"),
        // Other
        CacheEntry::new(
            "homebrew",
            "Homebrew",
            "Other",
            "safe",
            vec![mac.join("Homebrew")],
        ),
        CacheEntry::new(
            "puppeteer",
            "Puppeteer (Chrome)",
            "Other",
            "heavy",
            vec![xdg.join("puppeteer")],
        )
        .with_note("Browser binaries; re-downloads on next run"),
        CacheEntry::new(
            "playwright",
            "Playwright browsers",
            "Other",
            "heavy",
            vec![
                mac.join("ms-playwright"),
                mac.join("ms-playwright-mcp"),
                xdg.join("ms-playwright"),
                xdg.join("ms-playwright-mcp"),
                win_local.join("ms-playwright"),
                win_local.join("ms-playwright-mcp"),
            ],
        )
        .with_note("Browser binaries; re-downloads on next run"),
        CacheEntry::new(
            "huggingface",
            "HuggingFace",
            "Other",
            "heavy",
            vec![xdg.join("huggingface")],
        )
        .with_note("Model weights; re-downloads on demand"),
        CacheEntry::new(
            "torch",
            "PyTorch models",
            "Other",
            "heavy",
            vec![xdg.join("torch")],
        )
        .with_note("Model weights; re-downloads on demand"),
        CacheEntry::new(
            "go-build",
            "Go build cache",
            "Other",
            "safe",
            vec![
                mac.join("go-build"),
                xdg.join("go-build"),
                win_local.join("go-build"),
            ],
        ),
        CacheEntry::new(
            "go-mod",
            "Go module cache",
            "Other",
            "safe",
            vec![home.join("go/pkg/mod")],
        )
        .with_note("Re-downloads modules on next build"),
        // JVM
        CacheEntry::new(
            "gradle",
            "Gradle",
            "Java",
            "safe",
            vec![home.join(".gradle/caches")],
        )
        .with_note("Build + dependency caches; regenerates on next build"),
        CacheEntry::new(
            "maven",
            "Maven",
            "Java",
            "safe",
            vec![home.join(".m2/repository")],
        )
        .with_note("Re-downloads artifacts on next build"),
        CacheEntry::new(
            "javasharedresources",
            "JVM shared class cache",
            "Java",
            "safe",
            vec![xdg.join("javasharedresources"), mac.join("javasharedresources")],
        )
        .with_note("IBM/Semeru shared class cache; rebuilt on next run"),
        // Apple
        CacheEntry::new(
            "xcode-deriveddata",
            "Xcode DerivedData",
            "Apple",
            "safe",
            vec![home.join("Library/Developer/Xcode/DerivedData")],
        )
        .with_note("Build artifacts; recompiles on next build"),
        CacheEntry::new(
            "xcode-devicesupport",
            "Xcode DeviceSupport",
            "Apple",
            "safe",
            vec![
                home.join("Library/Developer/Xcode/iOS DeviceSupport"),
                home.join("Library/Developer/Xcode/macOS DeviceSupport"),
                home.join("Library/Developer/Xcode/tvOS DeviceSupport"),
                home.join("Library/Developer/Xcode/watchOS DeviceSupport"),
                home.join("Library/Developer/Xcode/visionOS DeviceSupport"),
            ],
        )
        .with_note("Device symbol caches; regenerated on next device connect"),
        CacheEntry::new(
            "coresimulator",
            "iOS Simulator",
            "Apple",
            "heavy",
            vec![home.join("Library/Developer/CoreSimulator")],
        )
        .with_note("Simulator runtimes + devices; recreates via Xcode"),
        CacheEntry::new(
            "swiftpm",
            "SwiftPM",
            "Apple",
            "safe",
            vec![
                mac.join("org.swift.swiftpm"),
                home.join("Library/org.swift.swiftpm"),
                xdg.join("org.swift.swiftpm"),
            ],
        )
        .with_note("Dependency clones + module cache; re-fetches on resolve"),
        CacheEntry::new(
            "cocoapods",
            "CocoaPods",
            "Apple",
            "safe",
            vec![home.join(".cocoapods"), mac.join("CocoaPods")],
        )
        .with_note("Specs repo + cache; re-fetches on next pod install"),
        // JS/TS binaries
        CacheEntry::new(
            "cypress",
            "Cypress",
            "JS/TS",
            "heavy",
            vec![
                mac.join("Cypress"),
                xdg.join("Cypress"),
                win_local.join("Cypress/Cache"),
            ],
        )
        .with_note("Browser binaries; re-downloads on next run"),
        CacheEntry::new(
            "electron",
            "Electron",
            "JS/TS",
            "heavy",
            vec![
                mac.join("electron"),
                xdg.join("electron"),
                win_local.join("electron/Cache"),
            ],
        )
        .with_note("Electron binaries; re-downloads on next install"),
        CacheEntry::new(
            "codex-runtimes",
            "Codex runtimes",
            "Other",
            "heavy",
            vec![xdg.join("codex-runtimes")],
        )
        .with_note("Agent runtimes; re-fetches on next session"),
        // IDE
        CacheEntry::new(
            "jetbrains",
            "JetBrains IDEs",
            "IDE",
            "safe",
            vec![
                mac.join("JetBrains"),
                xdg.join("JetBrains"),
                win_local.join("JetBrains"),
            ],
        )
        .with_note("Index + log caches; IDEs reindex on next launch"),
        CacheEntry::new(
            "vscode-family",
            "VS Code-family editor caches",
            "IDE",
            "safe",
            vscode_paths,
        )
        .with_note("Chromium caches, logs, extension installers; editors regenerate"),
        // Other build/tooling
        CacheEntry::new("bazel", "Bazel", "Other", "safe", vec![xdg.join("bazel"), mac.join("bazel")])
            .with_note("output_user_root; next build starts cold"),
        CacheEntry::new("zig", "Zig", "Other", "safe", vec![xdg.join("zig"), mac.join("zig")]),
        CacheEntry::new("gh", "GitHub CLI", "Other", "safe", vec![xdg.join("gh"), mac.join("gh")]),
        CacheEntry::new(
            "chroma",
            "ChromaDB models",
            "Other",
            "heavy",
            vec![xdg.join("chroma")],
        )
        .with_note("Embedding models; re-downloads on demand"),
        CacheEntry::new(
            "opencode",
            "opencode",
            "Other",
            "heavy",
            vec![xdg.join("opencode"), mac.join("opencode")],
        )
        .with_note("Agent caches; re-fetches on next session"),
    ]
}

/// VS Code-family Electron editors all keep the same Chromium-style cache
/// subdirs under their per-app data dir. Nonexistent paths are filtered out
/// during discovery, so enumerating the full apps × subdirs × bases
/// cross-product is cheap.
fn vscode_family_paths(app_support: &Path, config: &Path, win_roaming: &Path) -> Vec<PathBuf> {
    const APPS: &[&str] = &[
        "Code",
        "Code - Insiders",
        "VSCodium",
        "Cursor",
        "Windsurf",
        "Trae",
        "Qoder",
        "Positron",
        "Kiro",
        "Void",
    ];
    const SUBDIRS: &[&str] = &[
        "Cache",
        "CachedData",
        "Code Cache",
        "GPUCache",
        "CachedExtensionVSIXs",
        "logs",
    ];
    [app_support, config, win_roaming]
        .iter()
        .flat_map(|base| {
            APPS.iter().flat_map(move |app| {
                SUBDIRS.iter().map(move |sub| base.join(app).join(sub))
            })
        })
        .collect()
}

/// Resolve the registry to caches that currently exist on disk, with sizes
/// computed in parallel. Entries with no existing paths are dropped.
pub fn discover_caches() -> Vec<CacheEntry> {
    let mut entries = build_registry();
    entries.par_iter_mut().for_each(|e| {
        e.size_bytes = e
            .paths
            .iter()
            .filter(|p| p.exists())
            .map(|p| get_directory_size_parallel(p))
            .sum();
    });
    entries.into_iter().filter(|e| e.size_bytes > 0).collect()
}

fn remove_path(p: &Path) -> std::io::Result<()> {
    if p.is_dir() {
        std::fs::remove_dir_all(p)
    } else if p.is_file() {
        std::fs::remove_file(p)
    } else {
        Ok(())
    }
}

/// Clean the given caches. Reports the pre-computed size as freed bytes.
pub fn clean_caches(entries: &[CacheEntry], dry_run: bool) -> Vec<CacheCleanResult> {
    entries
        .par_iter()
        .map(|e| {
            let freed = e.size_bytes;
            if dry_run {
                return CacheCleanResult {
                    id: e.id.clone(),
                    name: e.name.clone(),
                    success: true,
                    freed_bytes: freed,
                    error: None,
                };
            }
            let mut error = None;
            let mut success = true;
            for p in &e.paths {
                if p.exists()
                    && let Err(err) = remove_path(p)
                {
                    success = false;
                    error = Some(format!("{}: {}", p.display(), err));
                }
            }
            CacheCleanResult {
                id: e.id.clone(),
                name: e.name.clone(),
                success,
                freed_bytes: freed,
                error,
            }
        })
        .collect()
}

/// Parse a 1-based, comma/space separated selection into 0-based indices,
/// deduplicated and bounded by `count`. Out-of-range and non-numeric tokens are
/// silently ignored.
pub fn parse_selection(input: &str, count: usize) -> Vec<usize> {
    let mut seen = std::collections::HashSet::new();
    let mut out = Vec::new();
    for token in input.split(|c: char| c == ',' || c.is_whitespace()) {
        if let Ok(n) = token.trim().parse::<usize>()
            && n >= 1
            && n <= count
            && seen.insert(n - 1)
        {
            out.push(n - 1);
        }
    }
    out
}

fn print_cache_list(caches: &[CacheEntry]) {
    println!("{} Available caches to clean:", "[INFO]".blue().bold());
    println!();
    println!(
        "  {:>3}  {:<26} {:<10} {:<6} {:>10}",
        "#", "Cache", "Category", "Risk", "Size"
    );
    for (i, c) in caches.iter().enumerate() {
        println!(
            "  {:>3}  {:<26} {:<10} {:<6} {:>10}",
            i + 1,
            c.name,
            c.category,
            c.risk,
            format_bytes(c.size_bytes)
        );
        if let Some(ref note) = c.note {
            println!("        {}", note.dimmed());
        }
    }
}

fn print_cache_results(results: &[CacheCleanResult]) {
    println!();
    println!("{} === CACHE CLEAN SUMMARY ===", "[INFO]".blue().bold());
    let total_freed: u64 = results.iter().map(|r| r.freed_bytes).sum();
    let ok = results.iter().filter(|r| r.success).count();
    let failed = results.len() - ok;
    for r in results {
        if r.success {
            println!(
                "  {} {} (freed: {})",
                "✓".green(),
                r.name,
                format_bytes(r.freed_bytes)
            );
        } else {
            println!(
                "  {} {} - {}",
                "✗".red(),
                r.name,
                r.error.as_deref().unwrap_or("failed")
            );
        }
    }
    println!();
    if failed == 0 {
        println!(
            "{} Cleaned {} cache(s), freed {}",
            "[SUCCESS]".green().bold(),
            ok,
            format_bytes(total_freed)
        );
    } else {
        println!(
            "{} Cleaned {}, failed {}, freed {}",
            "[INFO]".blue().bold(),
            ok,
            failed,
            format_bytes(total_freed)
        );
    }
}

fn prompt_selection(count: usize) -> Result<Vec<usize>> {
    print!("Select caches to clean (comma-separated numbers, 'all', or 'q' to quit): ");
    io::stdout().flush()?;
    let mut line = String::new();
    io::stdin().lock().read_line(&mut line)?;
    let trimmed = line.trim().to_ascii_lowercase();
    match trimmed.as_str() {
        "q" | "quit" | "exit" | "n" | "" => Ok(Vec::new()),
        "all" | "a" | "y" | "yes" => Ok((0..count).collect()),
        other => Ok(parse_selection(other, count)),
    }
}

fn confirm() -> Result<bool> {
    print!("Proceed? [y/N]: ");
    io::stdout().flush()?;
    let mut line = String::new();
    io::stdin().lock().read_line(&mut line)?;
    Ok(matches!(
        line.trim().to_ascii_lowercase().as_str(),
        "y" | "yes"
    ))
}

/// Filter a discovered cache list down to entries tagged `"safe"`.
///
/// Pure so the `--all` selection rule (heavy caches are never cleaned without
/// an explicit interactive pick) is unit-testable.
fn select_safe_caches(caches: &[CacheEntry]) -> Vec<CacheEntry> {
    caches
        .iter()
        .filter(|c| c.risk == "safe")
        .cloned()
        .collect()
}

/// Entry point for `--caches` mode: discover caches, list them, let the user
/// select, then clean. In JSON mode the discovered caches are printed as JSON
/// and no prompt is shown (useful for automation/inspection).
///
/// With `all` (`--caches --all`) the run is non-interactive: only `"safe"`
/// caches are cleaned — no selection or confirmation prompt. With `--json`,
/// cleaning is reported as a JSON array of [`CacheCleanResult`] instead of the
/// discovered-cache listing.
pub fn run_cache_mode(dry_run: bool, json: bool, all: bool) -> Result<()> {
    let caches = discover_caches();

    if caches.is_empty() {
        if json {
            println!("[]");
        } else {
            println!("{} No caches found to clean", "[INFO]".blue().bold());
        }
        return Ok(());
    }

    if all {
        return run_cache_all_mode(&caches, dry_run, json);
    }

    if json {
        println!("{}", serde_json::to_string_pretty(&caches)?);
        return Ok(());
    }

    print_cache_list(&caches);
    let total: u64 = caches.iter().map(|c| c.size_bytes).sum();
    println!();
    println!("  Total reclaimable: {}", format_bytes(total).bold());
    println!();

    let selection = prompt_selection(caches.len())?;
    if selection.is_empty() {
        println!("{} Cancelled", "[INFO]".blue().bold());
        return Ok(());
    }

    let selected: Vec<CacheEntry> = selection
        .iter()
        .filter_map(|&i| caches.get(i).cloned())
        .collect();
    let sel_total: u64 = selected.iter().map(|c| c.size_bytes).sum();

    println!();
    println!(
        "{} About to clean {} cache(s), freeing ~{}",
        "[INFO]".cyan().bold(),
        selected.len(),
        format_bytes(sel_total)
    );
    if dry_run {
        println!(
            "{} DRY RUN MODE - no changes will be made",
            "[INFO]".yellow().bold()
        );
    } else if !confirm()? {
        println!("{} Cancelled by user", "[INFO]".blue().bold());
        return Ok(());
    }

    let results = clean_caches(&selected, dry_run);
    print_cache_results(&results);

    if results.iter().any(|r| !r.success) {
        std::process::exit(1);
    }
    Ok(())
}

/// Non-interactive `--all` path: clean every discovered `"safe"` cache without
/// prompting. Heavy caches are skipped (they need an explicit interactive pick
/// via plain `--caches`). JSON mode reports [`CacheCleanResult`]s.
fn run_cache_all_mode(caches: &[CacheEntry], dry_run: bool, json: bool) -> Result<()> {
    let safe = select_safe_caches(caches);

    if json {
        let results = clean_caches(&safe, dry_run);
        println!("{}", serde_json::to_string_pretty(&results)?);
        if results.iter().any(|r| !r.success) {
            std::process::exit(1);
        }
        return Ok(());
    }

    if safe.is_empty() {
        println!(
            "{} No safe caches found to clean (heavy caches require interactive --caches)",
            "[INFO]".blue().bold()
        );
        return Ok(());
    }

    print_cache_list(&safe);
    let total: u64 = safe.iter().map(|c| c.size_bytes).sum();
    println!();
    println!(
        "{} Cleaning all {} safe cache(s), freeing ~{}",
        "[INFO]".cyan().bold(),
        safe.len(),
        format_bytes(total)
    );
    if dry_run {
        println!(
            "{} DRY RUN MODE - no changes will be made",
            "[INFO]".yellow().bold()
        );
    }
    println!(
        "{} Heavy caches skipped — clean them interactively with --caches",
        "[INFO]".blue().bold()
    );

    let results = clean_caches(&safe, dry_run);
    print_cache_results(&results);

    if results.iter().any(|r| !r.success) {
        std::process::exit(1);
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::utils::get_directory_size;
    use std::fs;
    use tempfile::TempDir;

    #[test]
    fn test_build_registry_has_known_caches() {
        let reg = build_registry();
        assert!(!reg.is_empty());
        let ids: Vec<_> = reg.iter().map(|e| e.id.as_str()).collect();
        assert!(ids.contains(&"npm"));
        assert!(ids.contains(&"cargo-cache"));
        assert!(ids.contains(&"huggingface"));
    }

    #[test]
    fn test_parse_selection_basic() {
        assert_eq!(parse_selection("1,3", 5), vec![0, 2]);
        assert_eq!(parse_selection("1 3", 5), vec![0, 2]);
    }

    #[test]
    fn test_parse_selection_out_of_range() {
        assert!(parse_selection("0", 5).is_empty());
        assert!(parse_selection("6", 5).is_empty());
    }

    #[test]
    fn test_parse_selection_dedup() {
        assert_eq!(parse_selection("1,1,2", 5), vec![0, 1]);
    }

    #[test]
    fn test_parse_selection_invalid_ignored() {
        assert_eq!(parse_selection("1,foo,3", 5), vec![0, 2]);
    }

    #[test]
    fn test_clean_caches_removes_dirs() {
        let temp = TempDir::new().unwrap();
        let dir = temp.path().join("npm_cache");
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join("a"), "hello world").unwrap();
        let size = get_directory_size(&dir).unwrap();

        let entry = CacheEntry {
            id: "test".into(),
            name: "test".into(),
            category: "Test".into(),
            risk: "safe".into(),
            paths: vec![dir.clone()],
            size_bytes: size,
            note: None,
        };
        let results = clean_caches(&[entry], false);
        assert_eq!(results.len(), 1);
        assert!(results[0].success);
        assert_eq!(results[0].freed_bytes, size);
        assert!(!dir.exists());
    }

    #[test]
    fn test_clean_caches_dry_run_keeps_dirs() {
        let temp = TempDir::new().unwrap();
        let dir = temp.path().join("cache");
        fs::create_dir_all(&dir).unwrap();
        fs::write(dir.join("a"), "data").unwrap();
        let size = get_directory_size(&dir).unwrap();
        let entry = CacheEntry {
            id: "test".into(),
            name: "test".into(),
            category: "Test".into(),
            risk: "safe".into(),
            paths: vec![dir.clone()],
            size_bytes: size,
            note: None,
        };
        let results = clean_caches(&[entry], true);
        assert!(results[0].success);
        assert!(dir.exists(), "dry run should not delete");
    }

    #[test]
    fn test_clean_caches_multiple_paths() {
        let temp = TempDir::new().unwrap();
        let dir1 = temp.path().join("cache1");
        let dir2 = temp.path().join("cache2");
        fs::create_dir_all(&dir1).unwrap();
        fs::create_dir_all(&dir2).unwrap();
        fs::write(dir1.join("a"), "aaa").unwrap();
        fs::write(dir2.join("b"), "bbbbbb").unwrap();
        let size = get_directory_size(&dir1).unwrap() + get_directory_size(&dir2).unwrap();

        let entry = CacheEntry {
            id: "multi".into(),
            name: "multi".into(),
            category: "Test".into(),
            risk: "safe".into(),
            paths: vec![dir1.clone(), dir2.clone()],
            size_bytes: size,
            note: None,
        };
        let results = clean_caches(&[entry], false);
        assert!(results[0].success);
        assert_eq!(results[0].freed_bytes, size);
        assert!(!dir1.exists());
        assert!(!dir2.exists());
    }

    #[test]
    fn test_clean_caches_nonexistent_paths_succeeds() {
        let entry = CacheEntry {
            id: "ghost".into(),
            name: "ghost".into(),
            category: "Test".into(),
            risk: "safe".into(),
            paths: vec![PathBuf::from("/nonexistent/path/that/does/not/exist")],
            size_bytes: 100,
            note: None,
        };
        let results = clean_caches(&[entry], false);
        assert!(results[0].success, "non-existent paths should not cause failure");
    }

    #[test]
    fn test_clean_caches_empty_entries() {
        let results = clean_caches(&[], false);
        assert!(results.is_empty());
    }

    #[test]
    fn test_registry_risk_values_valid() {
        let reg = build_registry();
        for entry in &reg {
            assert!(
                entry.risk == "safe" || entry.risk == "heavy",
                "entry {} has invalid risk: {}",
                entry.id,
                entry.risk
            );
        }
    }

    #[test]
    fn test_registry_unique_ids() {
        let reg = build_registry();
        let mut ids: Vec<&str> = reg.iter().map(|e| e.id.as_str()).collect();
        ids.sort();
        let len_before = ids.len();
        ids.dedup();
        assert_eq!(
            ids.len(),
            len_before,
            "registry has duplicate cache IDs"
        );
    }

    #[test]
    fn test_registry_all_categories_nonempty() {
        let reg = build_registry();
        for entry in &reg {
            assert!(!entry.category.is_empty(), "entry {} has empty category", entry.id);
            assert!(!entry.name.is_empty(), "entry {} has empty name", entry.id);
        }
    }

    #[test]
    fn test_remove_path_on_file() {
        let temp = TempDir::new().unwrap();
        let file = temp.path().join("single_file");
        fs::write(&file, "data").unwrap();
        assert!(file.is_file());
        remove_path(&file).unwrap();
        assert!(!file.exists());
    }

    #[test]
    fn test_remove_path_nonexistent_is_ok() {
        let result = remove_path(Path::new("/nonexistent/path"));
        assert!(result.is_ok());
    }

    #[test]
    fn test_parse_selection_all_tokens() {
        assert_eq!(parse_selection("1,2,3,4,5", 5), vec![0, 1, 2, 3, 4]);
    }

    #[test]
    fn test_parse_selection_mixed_separators() {
        assert_eq!(parse_selection("1, 2 3", 5), vec![0, 1, 2]);
    }

    #[test]
    fn test_parse_selection_empty() {
        assert!(parse_selection("", 5).is_empty());
    }

    #[test]
    fn test_env_base_dir_treats_empty_as_unset() {
        let fallback = PathBuf::from("/fallback");
        assert_eq!(env_base_dir(None, fallback.clone()), fallback);
        assert_eq!(env_base_dir(Some("".into()), fallback.clone()), fallback);
        assert_eq!(
            env_base_dir(Some("/custom".into()), fallback),
            PathBuf::from("/custom")
        );
    }

    /// Registry with all platform base dirs derived from a fake home, so tests
    /// assert on resulting paths without repeating seven arguments.
    fn reg(home: &Path) -> Vec<CacheEntry> {
        build_registry_for(
            home,
            &home.join(".cache"),
            &home.join("Library/Caches"),
            &home.join("AppData/Local"),
            &home.join("Library/Application Support"),
            &home.join(".config"),
            &home.join("AppData/Roaming"),
        )
    }

    #[test]
    fn test_registry_windows_localappdata_paths() {
        let home = PathBuf::from("/home/t");
        let win_local = home.join("AppData/Local");
        let reg = reg(&home);
        let find = |id: &str| {
            reg.iter()
                .find(|e| e.id == id)
                .unwrap_or_else(|| panic!("missing entry {}", id))
        };
        assert!(find("npm").paths.contains(&win_local.join("npm-cache")));
        assert!(find("pip").paths.contains(&win_local.join("pip")));
        assert!(find("uv").paths.contains(&win_local.join("uv")));
        assert!(find("poetry").paths.contains(&win_local.join("pypoetry")));
        assert!(find("pnpm").paths.contains(&win_local.join("pnpm")));
        assert!(find("yarn").paths.contains(&win_local.join("Yarn")));
        assert!(find("playwright").paths.contains(&win_local.join("ms-playwright")));
        assert!(find("go-build").paths.contains(&win_local.join("go-build")));
    }

    #[test]
    fn test_registry_xdg_default_covers_windows_dotcache() {
        // On Windows XDG_CACHE_HOME is unset and xdg defaults to ~/.cache, which is
        // also where puppeteer/HuggingFace/torch/codex store data on Windows.
        let home = PathBuf::from("/home/t");
        let reg = reg(&home);
        let find = |id: &str| {
            reg.iter()
                .find(|e| e.id == id)
                .unwrap_or_else(|| panic!("missing entry {}", id))
        };
        assert!(find("puppeteer").paths.contains(&home.join(".cache/puppeteer")));
        assert!(find("huggingface").paths.contains(&home.join(".cache/huggingface")));
        assert!(find("torch").paths.contains(&home.join(".cache/torch")));
    }

    #[test]
    fn test_registry_cargo_and_bun_are_home_based_on_all_platforms() {
        let home = PathBuf::from("/home/t");
        let reg = reg(&home);
        let find = |id: &str| {
            reg.iter()
                .find(|e| e.id == id)
                .unwrap_or_else(|| panic!("missing entry {}", id))
        };
        assert!(find("cargo-cache").paths.contains(&home.join(".cargo/registry/cache")));
        assert!(find("bun").paths.contains(&home.join(".bun/install/cache")));
    }

    #[test]
    fn test_registry_tier1_paths() {
        let home = PathBuf::from("/home/t");
        let mac = home.join("Library/Caches");
        let xdg = home.join(".cache");
        let win_local = home.join("AppData/Local");
        let reg = reg(&home);
        let find = |id: &str| {
            reg.iter()
                .find(|e| e.id == id)
                .unwrap_or_else(|| panic!("missing entry {}", id))
        };
        // Xcode DerivedData lives under ~/Library/Developer, not ~/Library/Caches
        assert!(find("xcode-deriveddata")
            .paths
            .contains(&home.join("Library/Developer/Xcode/DerivedData")));
        assert!(find("gradle").paths.contains(&home.join(".gradle/caches")));
        assert!(find("maven").paths.contains(&home.join(".m2/repository")));
        assert!(find("go-mod").paths.contains(&home.join("go/pkg/mod")));
        let cypress = find("cypress");
        assert!(cypress.paths.contains(&mac.join("Cypress")));
        assert!(cypress.paths.contains(&xdg.join("Cypress")));
        assert!(cypress.paths.contains(&win_local.join("Cypress/Cache")));
        let electron = find("electron");
        assert!(electron.paths.contains(&mac.join("electron")));
        assert!(electron.paths.contains(&xdg.join("electron")));
        assert!(electron.paths.contains(&win_local.join("electron/Cache")));
    }

    #[test]
    fn test_registry_tier1_risk_and_category() {
        let reg = build_registry();
        let find = |id: &str| {
            reg.iter()
                .find(|e| e.id == id)
                .unwrap_or_else(|| panic!("missing entry {}", id))
        };
        for id in ["gradle", "maven", "go-mod", "xcode-deriveddata"] {
            assert_eq!(find(id).risk, "safe", "{} should be safe", id);
        }
        // Browser/runtime binaries follow the playwright/puppeteer convention
        for id in ["cypress", "electron"] {
            assert_eq!(find(id).risk, "heavy", "{} should be heavy", id);
        }
        assert_eq!(find("xcode-deriveddata").category, "Apple");
        assert_eq!(find("gradle").category, "Java");
        assert_eq!(find("maven").category, "Java");
    }

    #[test]
    fn test_select_safe_caches_filters_heavy() {
        let mk = |id: &str, risk: &str| CacheEntry {
            id: id.into(),
            name: id.into(),
            category: "T".into(),
            risk: risk.into(),
            paths: vec![],
            size_bytes: 10,
            note: None,
        };
        let caches = vec![mk("a", "safe"), mk("b", "heavy"), mk("c", "safe")];
        let safe = select_safe_caches(&caches);
        let ids: Vec<_> = safe.iter().map(|c| c.id.as_str()).collect();
        assert_eq!(ids, vec!["a", "c"]);
        assert!(select_safe_caches(&[]).is_empty());
        let heavy_only = vec![mk("h", "heavy")];
        assert!(select_safe_caches(&heavy_only).is_empty());
    }

    #[test]
    fn test_registry_tier2_paths() {
        let home = PathBuf::from("/home/t");
        let mac = home.join("Library/Caches");
        let xdg = home.join(".cache");
        let win_local = home.join("AppData/Local");
        let app_support = home.join("Library/Application Support");
        let config = home.join(".config");
        let win_roaming = home.join("AppData/Roaming");
        let reg = reg(&home);
        let find = |id: &str| {
            reg.iter()
                .find(|e| e.id == id)
                .unwrap_or_else(|| panic!("missing entry {}", id))
        };
        assert!(find("cargo-git").paths.contains(&home.join(".cargo/git")));
        assert!(find("sccache").paths.contains(&mac.join("Mozilla.sccache")));
        assert!(find("sccache").paths.contains(&win_local.join("Mozilla/sccache")));
        assert!(find("nuget").paths.contains(&home.join(".nuget/packages")));
        assert!(find("conda").paths.contains(&home.join("miniconda3/pkgs")));
        assert!(find("deno").paths.contains(&xdg.join("deno")));
        assert!(find("playwright").paths.contains(&mac.join("ms-playwright-mcp")));
        assert!(find("playwright").paths.contains(&win_local.join("ms-playwright-mcp")));
        assert!(find("coresimulator")
            .paths
            .contains(&home.join("Library/Developer/CoreSimulator")));
        assert!(find("xcode-devicesupport")
            .paths
            .contains(&home.join("Library/Developer/Xcode/iOS DeviceSupport")));
        assert!(find("xcode-devicesupport")
            .paths
            .contains(&home.join("Library/Developer/Xcode/visionOS DeviceSupport")));
        assert!(find("swiftpm").paths.contains(&mac.join("org.swift.swiftpm")));
        assert!(find("swiftpm").paths.contains(&home.join("Library/org.swift.swiftpm")));
        assert!(find("cocoapods").paths.contains(&home.join(".cocoapods")));
        assert!(find("jetbrains").paths.contains(&mac.join("JetBrains")));
        // VS Code-family: same cache subdirs under macOS/Linux/Windows app dirs
        let vscode = find("vscode-family");
        assert!(vscode.paths.contains(&app_support.join("Code/Cache")));
        assert!(vscode.paths.contains(&app_support.join("Cursor/CachedData")));
        assert!(vscode.paths.contains(&config.join("Code/Code Cache")));
        assert!(vscode.paths.contains(&config.join("Windsurf/logs")));
        assert!(vscode.paths.contains(&win_roaming.join("Code/CachedExtensionVSIXs")));
        assert!(vscode.paths.contains(&win_roaming.join("Trae/GPUCache")));
    }

    #[test]
    fn test_registry_tier2_risk_and_category() {
        let reg = build_registry();
        let find = |id: &str| {
            reg.iter()
                .find(|e| e.id == id)
                .unwrap_or_else(|| panic!("missing entry {}", id))
        };
        // Browser/engine binaries and simulator runtimes are heavy (re-download)
        for id in [
            "prisma",
            "chrome-devtools-mcp",
            "selenium",
            "coresimulator",
            "chroma",
            "opencode",
        ] {
            assert_eq!(find(id).risk, "heavy", "{} should be heavy", id);
        }
        // Regenerable caches are safe
        for id in [
            "cargo-git",
            "sccache",
            "conda",
            "deno",
            "node-gyp",
            "vercel",
            "nuget",
            "javasharedresources",
            "xcode-devicesupport",
            "swiftpm",
            "cocoapods",
            "jetbrains",
            "vscode-family",
            "bazel",
            "zig",
            "gh",
        ] {
            assert_eq!(find(id).risk, "safe", "{} should be safe", id);
        }
        assert_eq!(find("nuget").category, ".NET");
        assert_eq!(find("jetbrains").category, "IDE");
        assert_eq!(find("vscode-family").category, "IDE");
        assert_eq!(find("coresimulator").category, "Apple");
    }
}