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
//! Detection of unused dependencies: parse `[dependencies]`-style tables out
//! of Cargo.toml, scan Rust sources once, and match the two. Pure analysis —
//! no subprocesses, no mutations.

use anyhow::{Context, Result};
use crate::deps::UnusedDependency;
use crate::project::Project;
use std::fs;
use std::path::Path;
use walkdir::WalkDir;

/// Extract dependency names from Cargo.toml
fn extract_dependencies(cargo_toml_path: &Path) -> Result<Vec<(String, String)>> {
    let content = fs::read_to_string(cargo_toml_path)
        .with_context(|| format!("Failed to read Cargo.toml: {:?}", cargo_toml_path))?;

    let toml: toml::Value = toml::from_str(&content)
        .with_context(|| format!("Failed to parse Cargo.toml: {:?}", cargo_toml_path))?;

    let mut deps = Vec::new();

    // Extract [dependencies]
    if let Some(deps_table) = toml.get("dependencies").and_then(|v| v.as_table()) {
        for (name, _) in deps_table {
            // Skip workspace dependencies and path dependencies for now
            // Only check crates.io dependencies
            deps.push((name.clone(), "[dependencies]".to_string()));
        }
    }

    // Extract [dev-dependencies]
    if let Some(dev_deps_table) = toml.get("dev-dependencies").and_then(|v| v.as_table()) {
        for (name, _) in dev_deps_table {
            deps.push((name.clone(), "[dev-dependencies]".to_string()));
        }
    }

    // Extract [build-dependencies]
    if let Some(build_deps_table) = toml.get("build-dependencies").and_then(|v| v.as_table()) {
        for (name, _) in build_deps_table {
            deps.push((name.clone(), "[build-dependencies]".to_string()));
        }
    }

    Ok(deps)
}

/// Normalize crate name for matching (handle dashes vs underscores)
fn normalize_crate_name(name: &str) -> String {
    name.replace('-', "_")
}

/// Build the search patterns for a single dependency name.
fn search_patterns_for(normalized_dep: &str) -> [String; 7] {
    [
        format!("use {}::", normalized_dep),
        format!("use {};", normalized_dep),
        format!("use crate::{}", normalized_dep),
        format!("{}::", normalized_dep),
        format!("extern crate {}", normalized_dep),
        format!("{}!", normalized_dep),
        format!("#[{}", normalized_dep),
    ]
}

/// Collect the text of every Rust source file relevant to usage detection,
/// reading each file exactly once.
fn collect_source_text(project_path: &Path) -> Vec<String> {
    let mut contents: Vec<String> = Vec::new();

    for sub in ["src", "examples", "tests"] {
        let dir = project_path.join(sub);
        if !dir.exists() {
            continue;
        }
        for entry in WalkDir::new(&dir).into_iter().filter_map(|e| e.ok()) {
            if entry.file_type().is_file()
                && entry.path().extension().is_some_and(|e| e == "rs")
                && let Ok(content) = fs::read_to_string(entry.path())
            {
                contents.push(content);
            }
        }
    }

    // build.rs (build dependencies)
    let build_rs = project_path.join("build.rs");
    if let Ok(content) = fs::read_to_string(&build_rs) {
        contents.push(content);
    }

    contents
}

/// Check whether a dependency is referenced anywhere in the project sources or
/// manifest. All files are already in `sources`; the manifest is checked for
/// feature/alias references.
fn is_dependency_used(
    dep_name: &str,
    sources: &[String],
    cargo_toml_content: &str,
) -> bool {
    let normalized = normalize_crate_name(dep_name);
    let patterns = search_patterns_for(&normalized);

    for content in sources {
        for pattern in &patterns {
            if content.contains(pattern.as_str()) {
                return true;
            }
        }
    }

    // Cargo.toml feature flags / crate references (e.g. "dep/", "crate-name/").
    if cargo_toml_content.contains(&format!("{}/", dep_name))
        || cargo_toml_content.contains(&format!("{}-", dep_name))
        || cargo_toml_content.contains(&format!("{}/", normalized))
        || cargo_toml_content.contains(&format!("{}-", normalized))
    {
        return true;
    }

    false
}

/// Check for unused dependencies in a project
pub fn check_unused_dependencies(project: &Project) -> Result<Vec<UnusedDependency>> {
    let cargo_toml = project.path.join("Cargo.toml");
    if !cargo_toml.exists() {
        return Ok(vec![]);
    }

    let all_deps = extract_dependencies(&cargo_toml)?;

    // Common dependencies that may be used indirectly (macros, build scripts,
    // proc-macros). Skipped to avoid false positives. Allocated once.
    const SKIP_LIST: &[&str] = &[
        "proc-macro2",
        "quote",
        "syn",
        "serde",
        "serde_derive",
        "serde_json", // Often used in build scripts
    ];

    // Filter to the dependencies we actually need to check.
    let deps_to_check: Vec<(String, String)> = all_deps
        .into_iter()
        .filter(|(name, _)| {
            !SKIP_LIST.contains(&name.as_str())
                && !name.ends_with("_derive")
                && !name.contains("proc-macro")
        })
        .collect();

    if deps_to_check.is_empty() {
        return Ok(vec![]);
    }

    // Read every relevant source file exactly once.
    let sources = collect_source_text(&project.path);
    let cargo_content = fs::read_to_string(&cargo_toml).unwrap_or_default();

    let mut unused = Vec::new();
    for (dep_name, location) in deps_to_check {
        if !is_dependency_used(&dep_name, &sources, &cargo_content) {
            unused.push(UnusedDependency {
                name: dep_name,
                location,
            });
        }
    }

    Ok(unused)
}

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

    #[test]
    fn test_normalize_crate_name() {
        assert_eq!(normalize_crate_name("my-crate"), "my_crate");
        assert_eq!(normalize_crate_name("my_crate"), "my_crate");
        assert_eq!(normalize_crate_name("serde-json"), "serde_json");
    }

    #[test]
    fn test_extract_dependencies() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let cargo_toml = temp_dir.path().join("Cargo.toml");
        fs::write(
            &cargo_toml,
            r#"
[package]
name = "test"
version = "0.1.0"

[dependencies]
serde = "1.0"
tokio = "1.0"

[dev-dependencies]
tempfile = "3.0"
"#,
        ).unwrap();

        let deps = extract_dependencies(&cargo_toml).unwrap();
        assert!(deps.len() >= 2);
        let dep_names: Vec<String> = deps.iter().map(|(n, _)| n.clone()).collect();
        assert!(dep_names.contains(&"serde".to_string()));
        assert!(dep_names.contains(&"tokio".to_string()));
    }

    #[test]
    fn test_extract_dependencies_includes_build_deps() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let cargo_toml = temp_dir.path().join("Cargo.toml");
        fs::write(
            &cargo_toml,
            r#"
[package]
name = "test"
version = "0.1.0"

[dependencies]
serde = "1.0"

[build-dependencies]
cc = "1.0"
"#,
        )
        .unwrap();

        let deps = extract_dependencies(&cargo_toml).unwrap();
        let names: Vec<String> = deps.iter().map(|(n, _)| n.clone()).collect();
        assert!(names.contains(&"cc".to_string()));
        let cc_loc = deps
            .iter()
            .find(|(n, _)| n == "cc")
            .map(|(_, l)| l.as_str())
            .unwrap();
        assert_eq!(cc_loc, "[build-dependencies]");
    }

    #[test]
    fn test_is_dependency_used_with_use_statement() {
        let sources = vec!["use serde::Deserialize;".to_string()];
        assert!(is_dependency_used("serde", &sources, ""));
    }

    #[test]
    fn test_is_dependency_used_unused() {
        let sources = vec!["fn main() {}".to_string()];
        assert!(!is_dependency_used("serde", &sources, ""));
    }

    #[test]
    fn test_is_dependency_used_dash_underscore_normalization() {
        // Crate name "serde-json" should match `use serde_json::`
        let sources = vec!["use serde_json::Value;".to_string()];
        assert!(is_dependency_used("serde-json", &sources, ""));
    }

    #[test]
    fn test_is_dependency_used_macro_invocation() {
        let sources = vec!["println!(\"hi\");".to_string()];
        assert!(is_dependency_used("println", &sources, ""));
    }

    #[test]
    fn test_is_dependency_used_attribute() {
        let sources = vec!["#[derive(Debug)]".to_string()];
        assert!(is_dependency_used("derive", &sources, ""));
    }

    #[test]
    fn test_is_dependency_used_cargo_feature_reference() {
        // Dependency referenced in Cargo.toml via "crate-name/feature" pattern
        let sources = vec!["fn main() {}".to_string()];
        let cargo = r#"[features]
feat1 = ["some-crate/feature"]
"#;
        assert!(is_dependency_used("some-crate", &sources, cargo));
    }

    #[test]
    fn test_is_dependency_used_bare_use_statement() {
        let sources = vec!["use tempfile;".to_string()];
        assert!(is_dependency_used("tempfile", &sources, ""));
    }

    #[test]
    fn test_is_dependency_used_use_crate_path() {
        let sources = vec!["use crate::serde_json::Value;".to_string()];
        assert!(is_dependency_used("serde-json", &sources, ""));
    }

    #[test]
    fn test_is_dependency_used_extern_crate() {
        let sources = vec!["extern crate libc;".to_string()];
        assert!(is_dependency_used("libc", &sources, ""));
    }

    #[test]
    fn test_is_dependency_used_manifest_normalized_variants() {
        // Dependency "serde-json" referenced in the manifest with its
        // underscore-normalized name (feature refs, aliases, version pins).
        let sources = vec!["fn main() {}".to_string()];
        assert!(is_dependency_used(
            "serde-json",
            &sources,
            "[features]\nbig = [\"serde_json/fancy\"]\n"
        ));
        assert!(is_dependency_used(
            "serde-json",
            &sources,
            "[package]\nname = \"serde_json-something\"\n"
        ));
    }

    #[test]
    fn test_is_dependency_used_plain_name_no_false_positive() {
        // A bare mention without ::, !, #[, /, or - separators must NOT count.
        let sources = vec!["let serdejson = 1;".to_string()];
        assert!(!is_dependency_used("serde-json", &sources, ""));
    }

    #[test]
    fn test_check_unused_dependencies_finds_unused() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        fs::create_dir_all(temp_dir.path().join("src")).unwrap();
        fs::write(
            temp_dir.path().join("Cargo.toml"),
            r#"
[package]
name = "test"
version = "0.1.0"

[dependencies]
rayon = "1.0"
"#,
        )
        .unwrap();
        // rayon is never used in source
        fs::write(temp_dir.path().join("src/main.rs"), "fn main() {}").unwrap();

        let project = crate::project::Project {
            path: temp_dir.path().to_path_buf(),
            is_workspace: false,
        };
        let unused = check_unused_dependencies(&project).unwrap();
        let names: Vec<String> = unused.iter().map(|d| d.name.clone()).collect();
        assert!(
            names.contains(&"rayon".to_string()),
            "rayon should be detected as unused, got: {:?}",
            names
        );
    }

    #[test]
    fn test_check_unused_dependencies_no_false_positive_for_used() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        fs::create_dir_all(temp_dir.path().join("src")).unwrap();
        fs::write(
            temp_dir.path().join("Cargo.toml"),
            r#"
[package]
name = "test"
version = "0.1.0"

[dependencies]
rayon = "1.0"
"#,
        )
        .unwrap();
        fs::write(
            temp_dir.path().join("src/main.rs"),
            "use rayon::prelude::*;\nfn main() {}",
        )
        .unwrap();

        let project = crate::project::Project {
            path: temp_dir.path().to_path_buf(),
            is_workspace: false,
        };
        let unused = check_unused_dependencies(&project).unwrap();
        let names: Vec<String> = unused.iter().map(|d| d.name.clone()).collect();
        assert!(
            !names.contains(&"rayon".to_string()),
            "rayon is used and should not be flagged as unused"
        );
    }

    #[test]
    fn test_check_unused_dependencies_skips_skip_list() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        fs::create_dir_all(temp_dir.path().join("src")).unwrap();
        fs::write(
            temp_dir.path().join("Cargo.toml"),
            r#"
[package]
name = "test"
version = "0.1.0"

[dependencies]
serde = "1.0"
serde_derive = "1.0"
"#,
        )
        .unwrap();
        // Neither serde nor serde_derive is used in source, but both are in the skip list
        fs::write(temp_dir.path().join("src/main.rs"), "fn main() {}").unwrap();

        let project = crate::project::Project {
            path: temp_dir.path().to_path_buf(),
            is_workspace: false,
        };
        let unused = check_unused_dependencies(&project).unwrap();
        let names: Vec<String> = unused.iter().map(|d| d.name.clone()).collect();
        assert!(
            !names.contains(&"serde".to_string()),
            "serde is in skip list and should not be flagged"
        );
    }

    #[test]
    fn test_check_unused_dependencies_missing_manifest_is_empty() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let project = crate::project::Project {
            path: temp_dir.path().to_path_buf(),
            is_workspace: false,
        };
        let unused = check_unused_dependencies(&project).unwrap();
        assert!(unused.is_empty());
    }

    #[test]
    fn test_check_unused_dependencies_dev_and_build_locations() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        fs::create_dir_all(temp_dir.path().join("src")).unwrap();
        fs::write(
            temp_dir.path().join("Cargo.toml"),
            r#"
[package]
name = "test"
version = "0.1.0"

[dev-dependencies]
unused-dev = "1.0"

[build-dependencies]
cc = "1.0"
"#,
        )
        .unwrap();
        fs::write(temp_dir.path().join("src/main.rs"), "fn main() {}").unwrap();
        // cc is used by build.rs, so it must not be flagged.
        fs::write(
            temp_dir.path().join("build.rs"),
            "fn main() { let _ = cc::compiler(); }",
        )
        .unwrap();

        let project = crate::project::Project {
            path: temp_dir.path().to_path_buf(),
            is_workspace: false,
        };
        let unused = check_unused_dependencies(&project).unwrap();
        let names: Vec<String> = unused.iter().map(|d| d.name.clone()).collect();
        assert!(names.contains(&"unused-dev".to_string()));
        assert!(!names.contains(&"cc".to_string()), "cc is used in build.rs");
        let dev = unused.iter().find(|d| d.name == "unused-dev").unwrap();
        assert_eq!(dev.location, "[dev-dependencies]");
    }

    #[test]
    fn test_check_unused_dependencies_skips_derive_and_proc_macro_names() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        fs::create_dir_all(temp_dir.path().join("src")).unwrap();
        fs::write(
            temp_dir.path().join("Cargo.toml"),
            r#"
[package]
name = "test"
version = "0.1.0"

[dependencies]
some_derive = "1.0"
my-proc-macro-helper = "1.0"
thiserror = "1.0"
"#,
        )
        .unwrap();
        fs::write(temp_dir.path().join("src/main.rs"), "fn main() {}").unwrap();

        let project = crate::project::Project {
            path: temp_dir.path().to_path_buf(),
            is_workspace: false,
        };
        let unused = check_unused_dependencies(&project).unwrap();
        let names: Vec<String> = unused.iter().map(|d| d.name.clone()).collect();
        assert!(
            !names.contains(&"some_derive".to_string()),
            "*_derive names are skipped (likely used via re-exported macros)"
        );
        assert!(
            !names.contains(&"my-proc-macro-helper".to_string()),
            "names containing proc-macro are skipped"
        );
        assert!(
            names.contains(&"thiserror".to_string()),
            "normal deps outside the skip filters are still checked"
        );
    }

    #[test]
    fn test_collect_source_text_includes_build_rs() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        fs::create_dir_all(temp_dir.path().join("src")).unwrap();
        fs::create_dir_all(temp_dir.path().join("examples")).unwrap();
        fs::write(temp_dir.path().join("src/main.rs"), "fn main() {}").unwrap();
        fs::write(
            temp_dir.path().join("examples/demo.rs"),
            "fn main() {}",
        )
        .unwrap();
        fs::write(temp_dir.path().join("build.rs"), "fn main() {}").unwrap();

        let texts = collect_source_text(temp_dir.path());
        // src/main.rs + examples/demo.rs + build.rs = 3 files
        assert_eq!(texts.len(), 3);
    }

    #[test]
    fn test_collect_source_text_includes_tests_dir() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        fs::create_dir_all(temp_dir.path().join("tests")).unwrap();
        fs::write(
            temp_dir.path().join("tests/integration.rs"),
            "use my_crate::thing;",
        )
        .unwrap();
        let texts = collect_source_text(temp_dir.path());
        assert_eq!(texts.len(), 1);
        assert!(texts[0].contains("my_crate"));
    }

    #[test]
    fn test_collect_source_text_empty_project() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let texts = collect_source_text(temp_dir.path());
        assert!(texts.is_empty());
    }

    #[test]
    fn test_collect_source_text_skips_invalid_utf8() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        fs::create_dir_all(temp_dir.path().join("src")).unwrap();
        fs::write(temp_dir.path().join("src/binary.bin.rs"), [0xFF, 0xFE, 0x00]).unwrap();
        fs::write(temp_dir.path().join("src/main.rs"), "fn main() {}").unwrap();
        let texts = collect_source_text(temp_dir.path());
        assert_eq!(texts.len(), 1, "invalid UTF-8 file skipped without error");
    }

    #[test]
    fn test_extract_dependencies_renamed_dep_uses_manifest_key() {
        // `foo = { package = "bar" }` means the crate is imported as `foo` in
        // code, so the manifest key (not the package name) is the dep name.
        let temp_dir = tempfile::TempDir::new().unwrap();
        let cargo_toml = temp_dir.path().join("Cargo.toml");
        fs::write(
            &cargo_toml,
            r#"
[dependencies]
foo = { package = "bar", version = "1.0" }
"#,
        )
        .unwrap();

        let deps = extract_dependencies(&cargo_toml).unwrap();
        let names: Vec<String> = deps.iter().map(|(n, _)| n.clone()).collect();
        assert_eq!(names, vec!["foo".to_string()]);
    }

    #[test]
    fn test_extract_dependencies_ignores_workspace_dependencies() {
        // `[workspace.dependencies]` entries live under the `workspace` key and
        // are intentionally not extracted: inheritance is not resolved, so
        // inherited deps can never be falsely flagged as unused.
        let temp_dir = tempfile::TempDir::new().unwrap();
        let cargo_toml = temp_dir.path().join("Cargo.toml");
        fs::write(
            &cargo_toml,
            r#"
[workspace.dependencies]
serde = "1.0"
"#,
        )
        .unwrap();

        let deps = extract_dependencies(&cargo_toml).unwrap();
        assert!(deps.is_empty());
    }

    #[test]
    fn test_extract_dependencies_invalid_toml_is_err() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        let cargo_toml = temp_dir.path().join("Cargo.toml");
        fs::write(&cargo_toml, "not [ valid toml").unwrap();
        assert!(extract_dependencies(&cargo_toml).is_err());
    }

    #[test]
    fn test_extract_dependencies_missing_file_is_err() {
        let temp_dir = tempfile::TempDir::new().unwrap();
        assert!(extract_dependencies(&temp_dir.path().join("Cargo.toml")).is_err());
    }
}