maclean 1.0.0

Find and reclaim disk space on macOS
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
use std::collections::HashSet;
use std::fs;
use std::path::{Path, PathBuf};

use anyhow::Result;
use cargo_toml::Manifest;
use walkdir::WalkDir;

use crate::core::{
    Item, Module, ModuleInfo, ModuleScan, ReclaimContext, ReclaimError, ReclaimResult, Relevance,
    Safety, ScanContext, ScheduleTarget, delete_contents, delete_tree, dir_size_in,
    exists_named_within, format_bytes, run_command, skip_walk_dir,
};

/// Minimum `target/` size to report. Tiny incremental leftovers aren't worth listing.
const MIN_TARGET_BYTES: u64 = 10 * 1000 * 1000;

/// Shared caches under ~/.cargo. All of them are re-fetched on demand.
const REGISTRY_DIRS: &[(&str, &str, &str)] = &[
    ("crates", "registry/cache", "Downloaded .crate archives"),
    (
        "sources",
        "registry/src",
        "Unpacked crate sources used while building",
    ),
    ("git-db", "git/db", "Bare clones of git dependencies"),
    (
        "git-checkouts",
        "git/checkouts",
        "Working copies of git dependencies",
    ),
];

pub struct CargoModule;

impl CargoModule {
    fn roots(ctx: &ScanContext) -> Vec<PathBuf> {
        ctx.roots_for("cargo")
    }

    fn cargo_home(ctx: &ScanContext) -> PathBuf {
        std::env::var_os("CARGO_HOME")
            .map(PathBuf::from)
            .unwrap_or_else(|| ctx.path("cargo", "home", ".cargo"))
    }
}

impl Module for CargoModule {
    fn id(&self) -> &'static str {
        "cargo"
    }

    fn name(&self) -> &'static str {
        "Cargo"
    }

    fn description(&self) -> &'static str {
        "Cargo registry cache and project build output (`target/`)"
    }

    fn programs(&self) -> &'static [&'static str] {
        &["cargo"]
    }

    fn paths(&self) -> Vec<(&'static str, &'static str)> {
        vec![("home", ".cargo")]
    }

    fn searches(&self) -> bool {
        true
    }

    fn schedule_targets(&self) -> Vec<ScheduleTarget> {
        vec![
            ScheduleTarget::new(
                "cargo:projects",
                "Project build output",
                "cargo clean in every project found when the job runs",
            ),
            ScheduleTarget::new(
                "cargo:registry",
                "Registry and git cache",
                "Shared crates and git deps under ~/.cargo",
            ),
        ]
    }

    fn info(&self, ctx: &ScanContext) -> ModuleInfo {
        let mut info = ModuleInfo::new(self.id(), self.name(), self.description())
            .finds("The shared registry and git caches under ~/.cargo")
            .finds("`target/` directories next to every Cargo.toml under your home directory (and any extra search folders)")
            .finds("Workspaces (one shared target) and leftover targets inside members")
            .finds("Custom target directories set by .cargo/config.toml")
            .effect("Cleaning a project runs `cargo clean`, which empties target/ only")
            .effect("Your source, Cargo.toml and Cargo.lock are never touched")
            .effect("Cargo re-downloads registry files and rebuilds target/ on the next build")
            .location(Self::cargo_home(ctx));
        for root in Self::roots(ctx) {
            info = info.location(root);
        }
        info
    }

    fn relevance(&self, ctx: &ScanContext) -> Relevance {
        let cargo_home = Self::cargo_home(ctx);
        if cargo_home.join("registry").is_dir() {
            return Relevance::yes(format!("registry cache exists at {}", cargo_home.display()));
        }
        let roots = Self::roots(ctx);
        if exists_named_within(&roots, "Cargo.toml", 8) {
            Relevance::yes(
                "found at least one Cargo.toml under the search folders (toolchain not required)",
            )
        } else {
            Relevance::no("no Cargo.toml under the search folders (default is your home directory)")
        }
    }

    fn scan(&self, ctx: &ScanContext, relevance: Relevance) -> ModuleScan {
        let mut scan = ModuleScan::new(self.id(), self.name(), relevance);
        if let Some(registry) = registry_item(self.id(), &Self::cargo_home(ctx), ctx) {
            scan.items.push(registry);
        }
        let manifests = find_manifests(&Self::roots(ctx));
        if manifests.is_empty() {
            return scan;
        }

        let parsed: Vec<ParsedManifest> = manifests
            .iter()
            .filter_map(|path| parse_manifest(path).ok())
            .collect();

        let member_dirs = workspace_member_dirs(&parsed);
        let mut seen_targets = HashSet::new();
        let mut items = Vec::new();

        for manifest in &parsed {
            if ctx.cancelled() {
                break;
            }
            let is_member = member_dirs.contains(&manifest.dir);
            let owns_workspace_target = manifest.is_workspace || !is_member;
            let target = resolve_target_dir(&manifest.dir);

            if owns_workspace_target {
                push_target_item(
                    &mut items,
                    &mut seen_targets,
                    self.id(),
                    &manifest.dir,
                    &target,
                    manifest.is_workspace,
                    false,
                    ctx,
                );
            } else if target.is_dir() {
                push_target_item(
                    &mut items,
                    &mut seen_targets,
                    self.id(),
                    &manifest.dir,
                    &target,
                    false,
                    true,
                    ctx,
                );
            }
        }

        if !items.is_empty() {
            items.sort_by(|a, b| b.bytes.cmp(&a.bytes));
            let bytes: u64 = items.iter().map(|i| i.bytes).sum();
            let count = items.len();
            scan.items.push(
                Item::new(self.id(), "cargo:projects", "Project build output")
                    .with_summary(format!(
                        "cargo clean in {} — source, Cargo.toml and Cargo.lock stay",
                        crate::core::plural(count, "project")
                    ))
                    .with_bytes(bytes)
                    .with_safety(Safety::Safe)
                    .with_note("Each row runs `cargo clean` in that project. The project directory is not removed.")
                    .with_children(items),
            );
        }
        scan.items.sort_by(|a, b| b.bytes.cmp(&a.bytes));
        scan
    }

    fn reclaim(&self, item: &Item, ctx: &ReclaimContext) -> Result<ReclaimResult, ReclaimError> {
        let Some(target) = item.paths.first() else {
            return Err(ReclaimError::new(
                &item.id,
                crate::core::IssueKind::Warning,
                "cargo item has no path",
            ));
        };
        if !target.is_dir() {
            return Err(ReclaimError::new(
                &item.id,
                crate::core::IssueKind::Warning,
                format!("refusing to delete {} (not a directory)", target.display()),
            ));
        }

        if item.id.starts_with("cargo:registry:") {
            let freed = delete_contents(item, target, ctx)?;
            return Ok(ReclaimResult::ok(
                &item.id,
                freed,
                format!("emptied {} ({})", target.display(), format_bytes(freed)),
                ctx.dry_run,
            ));
        }

        if ctx.dry_run {
            return Ok(ReclaimResult::ok(
                &item.id,
                item.bytes,
                format!(
                    "would run cargo clean in {} ({})",
                    target.parent().unwrap_or(target).display(),
                    format_bytes(item.bytes)
                ),
                true,
            ));
        }

        let project = item
            .id
            .strip_prefix("cargo:")
            .map(PathBuf::from)
            .unwrap_or_else(|| target.parent().unwrap_or(target).to_path_buf());
        let manifest = project.join("Cargo.toml");
        let manifest_s = manifest.to_string_lossy();
        if run_command(
            item,
            "cargo",
            &["clean", "--manifest-path", manifest_s.as_ref()],
            ctx,
        )
        .is_ok()
            && !target.exists()
        {
            return Ok(ReclaimResult::ok(
                &item.id,
                item.bytes,
                format!(
                    "cargo clean in {} ({})",
                    project.display(),
                    format_bytes(item.bytes)
                ),
                false,
            ));
        }

        let freed = delete_tree(item, target, ctx)?;
        Ok(ReclaimResult::ok(
            &item.id,
            freed,
            format!("emptied {} ({})", target.display(), format_bytes(freed)),
            false,
        ))
    }
}

struct ParsedManifest {
    dir: PathBuf,
    is_workspace: bool,
    member_patterns: Vec<String>,
    exclude_patterns: Vec<String>,
    workspace_ptr: Option<PathBuf>,
}

fn find_manifests(roots: &[PathBuf]) -> Vec<PathBuf> {
    let mut found = Vec::new();
    for root in roots {
        if !root.is_dir() {
            continue;
        }
        for entry in WalkDir::new(root)
            .follow_links(false)
            .max_depth(8)
            .into_iter()
            .filter_entry(|e| {
                if !e.file_type().is_dir() {
                    return true;
                }
                !skip_walk_dir(&e.file_name().to_string_lossy())
            })
            .filter_map(|e| e.ok())
        {
            if entry.file_type().is_file() && entry.file_name() == "Cargo.toml" {
                found.push(entry.path().to_path_buf());
            }
        }
    }
    found.sort();
    found.dedup();
    found
}

fn parse_manifest(cargo_toml: &Path) -> Result<ParsedManifest> {
    let bytes = fs::read(cargo_toml)?;
    let manifest = Manifest::from_slice(&bytes)?;
    let dir = cargo_toml
        .parent()
        .map(Path::to_path_buf)
        .unwrap_or_default();
    let (is_workspace, member_patterns, exclude_patterns) = match &manifest.workspace {
        Some(ws) => (true, ws.members.clone(), ws.exclude.clone()),
        None => (false, Vec::new(), Vec::new()),
    };
    let workspace_ptr = manifest
        .package
        .as_ref()
        .and_then(|p| p.workspace.as_ref())
        .map(|rel| dir.join(rel));
    Ok(ParsedManifest {
        dir,
        is_workspace,
        member_patterns,
        exclude_patterns,
        workspace_ptr,
    })
}

fn workspace_member_dirs(parsed: &[ParsedManifest]) -> HashSet<PathBuf> {
    let mut members = HashSet::new();
    for manifest in parsed {
        if let Some(ptr) = &manifest.workspace_ptr {
            members.insert(normalize(ptr));
        }
        if !manifest.is_workspace {
            continue;
        }
        let expanded = expand_globs(&manifest.dir, &manifest.member_patterns);
        let excluded = expand_globs(&manifest.dir, &manifest.exclude_patterns);
        for path in expanded {
            if excluded.contains(&path) {
                continue;
            }
            members.insert(path);
        }
    }
    members
}

fn expand_globs(root: &Path, patterns: &[String]) -> HashSet<PathBuf> {
    let mut out = HashSet::new();
    for pattern in patterns {
        let joined = root.join(pattern);
        let glob_pat = joined.to_string_lossy();
        if let Ok(entries) = glob::glob(&glob_pat) {
            for entry in entries.flatten() {
                let dir = if entry.is_dir() {
                    entry
                } else {
                    continue;
                };
                if dir.join("Cargo.toml").is_file() {
                    out.insert(normalize(&dir));
                }
            }
        }
        // Non-glob exact member path.
        let exact = root.join(pattern);
        if exact.join("Cargo.toml").is_file() {
            out.insert(normalize(&exact));
        }
    }
    out
}

fn normalize(path: &Path) -> PathBuf {
    fs::canonicalize(path).unwrap_or_else(|_| path.to_path_buf())
}

#[derive(serde::Deserialize)]
struct CargoConfig {
    build: Option<CargoBuild>,
}

#[derive(serde::Deserialize)]
struct CargoBuild {
    #[serde(rename = "target-dir")]
    target_dir: Option<String>,
}

fn resolve_target_dir(project: &Path) -> PathBuf {
    for name in [".cargo/config.toml", ".cargo/config"] {
        let cfg = project.join(name);
        let Ok(text) = fs::read_to_string(&cfg) else {
            continue;
        };
        let Ok(parsed) = toml::from_str::<CargoConfig>(&text) else {
            continue;
        };
        if let Some(dir) = parsed.build.and_then(|b| b.target_dir) {
            let path = PathBuf::from(dir);
            return if path.is_absolute() {
                path
            } else {
                project.join(path)
            };
        }
    }
    project.join("target")
}

fn push_target_item(
    items: &mut Vec<Item>,
    seen: &mut HashSet<PathBuf>,
    module: &str,
    project: &Path,
    target: &Path,
    workspace: bool,
    leftover_member: bool,
    ctx: &ScanContext,
) {
    let key = normalize(target);
    if !seen.insert(key) {
        return;
    }
    if !target.is_dir() {
        return;
    }
    let bytes = dir_size_in(target, ctx).bytes;
    if bytes < MIN_TARGET_BYTES {
        return;
    }
    let name = project
        .file_name()
        .and_then(|s| s.to_str())
        .unwrap_or("project");
    let title = if workspace {
        format!("{name} — build output (workspace)")
    } else {
        format!("{name} — build output")
    };
    let summary = if leftover_member {
        format!(
            "Stale target/ inside a workspace member — the shared one lives at the workspace root ({})",
            target.display()
        )
    } else {
        format!("cargo clean in {}", project.display())
    };
    let mut profiles = Vec::new();
    if let Ok(entries) = fs::read_dir(target) {
        for entry in entries.flatten() {
            if !entry.path().is_dir() || ctx.cancelled() {
                continue;
            }
            let sub = entry.path();
            let sub_bytes = dir_size_in(&sub, ctx).bytes;
            if sub_bytes == 0 {
                continue;
            }
            let profile = entry.file_name().to_string_lossy().into_owned();
            profiles.push(
                Item::new(
                    module,
                    format!("cargo:{}:{profile}", project.display()),
                    profile,
                )
                .with_summary(sub.display().to_string())
                .with_bytes(sub_bytes)
                .with_safety(Safety::Safe),
            );
        }
    }

    items.push(
        Item::new(module, format!("cargo:{}", project.display()), title)
            .with_summary(summary)
            .with_bytes(bytes)
            .with_path(target.to_path_buf())
            .with_safety(Safety::Safe)
            .with_reclaimable(true)
            .clean_whole()
            .with_detail("Project", project.display().to_string())
            .with_detail("Runs", "cargo clean")
            .with_detail("Empties", target.display().to_string())
            .with_detail(
                "Kind",
                if workspace {
                    "workspace root"
                } else if leftover_member {
                    "workspace member (stale target)"
                } else {
                    "standalone crate"
                },
            )
            .with_note(
                "The project is not removed. Only target/ is emptied — source, Cargo.toml and Cargo.lock stay.",
            )
            .with_note("The next `cargo build` compiles from scratch.")
            .with_children(profiles)
            .prune_children(1_000_000, 8),
    );
}

/// The shared caches under ~/.cargo, one row per kind so you can pick.
fn registry_item(module: &str, cargo_home: &Path, ctx: &ScanContext) -> Option<Item> {
    let mut children = Vec::new();
    for (key, rel, what) in REGISTRY_DIRS {
        let path = cargo_home.join(rel);
        if !path.is_dir() {
            continue;
        }
        let bytes = dir_size_in(&path, ctx).bytes;
        if bytes == 0 {
            continue;
        }
        children.push(
            Item::new(module, format!("cargo:registry:{key}"), rel.to_string())
                .with_summary(what.to_string())
                .with_bytes(bytes)
                .with_path(path.clone())
                .with_safety(Safety::Safe)
                .with_reclaimable(true)
                .clean_whole()
                .with_detail("Path", path.display().to_string())
                .with_note("Cargo fetches this again the next time a build needs it."),
        );
    }
    if children.is_empty() {
        return None;
    }
    let bytes = children.iter().map(|c| c.bytes).sum();
    Some(
        Item::new(module, "cargo:registry", "Registry and git cache")
            .with_summary(format!("Shared download cache in {}", cargo_home.display()))
            .with_bytes(bytes)
            .with_safety(Safety::Safe)
            .with_note("Shared by every Rust project on this Mac. No project is modified.")
            .with_children(children),
    )
}

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

    #[test]
    fn exact_member_paths_expand() {
        let tmp = std::env::temp_dir().join(format!("maclean-cargo-test-{}", std::process::id()));
        let member = tmp.join("crates/foo");
        fs::create_dir_all(&member).unwrap();
        fs::write(
            member.join("Cargo.toml"),
            "[package]\nname=\"foo\"\nversion=\"0.1.0\"\n",
        )
        .unwrap();
        let expanded = expand_globs(&tmp, &["crates/foo".into()]);
        assert!(expanded.contains(&normalize(&member)));
        let _ = fs::remove_dir_all(&tmp);
    }
}