cargo-target-gc 0.1.3

Cargo target-artifact garbage collector: analyze and reclaim target/ build artifacts
Documentation
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
//! End-to-end CLI behavior tests driving the real `cargo-target-gc` binary.

use std::fs::{self, File};
use std::path::{Path, PathBuf};
use std::time::{Duration, SystemTime};

use assert_cmd::Command;
use predicates::prelude::*;
use predicates::str::contains;

const FIXTURE: &str = "tests/fixtures/single-package";
const TEST_SECONDS_PER_DAY: u64 = 86_400;

fn target_gc() -> Command {
    Command::cargo_bin("cargo-target-gc").expect("cargo-target-gc binary builds")
}

/// Create a unique temp project with a populated `target/` tree.
///
/// `target/` contains a fresh (retained) debug profile, an old incremental subtree,
/// and an old (stale) release profile, with deterministic mtimes. Returns the
/// project root; the caller removes it.
fn temp_project(tag: &str) -> PathBuf {
    let nanos = SystemTime::now()
        .duration_since(SystemTime::UNIX_EPOCH)
        .map(|d| d.as_nanos())
        .unwrap_or(0);
    let root = std::env::temp_dir().join(format!(
        "target-gc-cli-{tag}-{}-{nanos}",
        std::process::id()
    ));
    fs::create_dir_all(&root).expect("create project");
    fs::write(root.join("Cargo.toml"), "[package]\nname = \"x\"\n").expect("manifest");
    let target = root.join("target");
    fs::create_dir_all(&target).expect("target");
    fs::write(target.join("CACHEDIR.TAG"), "Signature").expect("tag");
    write_aged(&target.join("debug/deps/lib.rlib"), 1000, 0);
    write_aged(&target.join("debug/incremental/seg/x.o"), 500, 2);
    write_aged(&target.join("release/deps/lib.rlib"), 2000, 100);
    root
}

/// Write a file of `len` bytes with an mtime `age_days` in the past.
fn write_aged(path: &Path, len: usize, age_days: u64) {
    if let Some(parent) = path.parent() {
        fs::create_dir_all(parent).expect("parents");
    }
    fs::write(path, vec![b'x'; len]).expect("write");
    let when = SystemTime::now()
        .checked_sub(Duration::from_secs(age_days * TEST_SECONDS_PER_DAY))
        .expect("aged");
    File::options()
        .write(true)
        .open(path)
        .expect("open")
        .set_modified(when)
        .expect("mtime");
}

/// Total bytes and entry count under a directory tree (for unchanged checks).
fn tree_fingerprint(dir: &Path) -> (u64, usize) {
    let mut bytes = 0u64;
    let mut count = 0usize;
    let entries = match fs::read_dir(dir) {
        Ok(e) => e,
        Err(_) => return (bytes, count),
    };
    for entry in entries.flatten() {
        let path = entry.path();
        count += 1;
        let meta = entry.metadata().expect("metadata");
        if meta.is_dir() {
            let (b, c) = tree_fingerprint(&path);
            bytes += b;
            count += c;
        } else {
            bytes += meta.len();
        }
    }
    (bytes, count)
}

#[test]
fn help_lists_subcommands() {
    target_gc()
        .arg("--help")
        .assert()
        .success()
        .stdout(contains("scan"))
        .stdout(contains("clean"))
        .stdout(contains("config"))
        .stdout(contains("install-agent-skills"))
        .stdout(contains("same directory where you would run `cargo build`"));
}

#[test]
fn scan_help_lists_flags() {
    target_gc()
        .args(["scan", "--help"])
        .assert()
        .success()
        .stdout(contains("--json"))
        .stdout(contains("--path"))
        .stdout(contains("same directory where `cargo build`"));
}

#[test]
fn scan_reports_target_roots_and_reclaimable() {
    let root = temp_project("scan");
    target_gc()
        .args(["scan", "--path"])
        .arg(&root)
        .assert()
        .success()
        .stdout(contains("target:"))
        .stdout(contains("old incremental:"))
        .stdout(contains("fresh incremental:"))
        .stdout(contains("reclaimable:"))
        .stdout(contains("summary:"));
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn cargo_subcommand_invocation_shape_works() {
    let root = temp_project("cargo-subcommand");
    target_gc()
        .args(["target-gc", "scan", "--path"])
        .arg(&root)
        .assert()
        .success()
        .stdout(contains("cargo target-gc scan:"))
        .stdout(contains("reclaimable:"));
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn scan_json_has_roots_and_reclaimable_keys() {
    let root = temp_project("scanjson");
    let output = target_gc()
        .args(["scan", "--json", "--path"])
        .arg(&root)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(output).expect("utf8 stdout");
    let value: serde_json::Value = serde_json::from_str(&text).expect("stdout is valid JSON");
    let roots = value["roots"].as_array().expect("roots is an array");
    assert_eq!(roots.len(), 1);
    assert!(roots[0]["reclaimable_bytes"].is_u64());
    assert!(roots[0]["fresh_incremental_bytes"].is_u64());
    assert!(value["summary"]["reclaimable_bytes"].is_u64());
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn scan_never_runs_cargo_and_leaves_target_unchanged() {
    let root = temp_project("readonly");
    let target = root.join("target");
    let before = tree_fingerprint(&target);

    target_gc()
        .args(["scan", "--path"])
        .arg(&root)
        .assert()
        .success();

    // scan must not invoke cargo: no Cargo.lock and no extra target dir appear,
    // and the existing target tree is byte-identical.
    assert!(
        !root.join("Cargo.lock").exists(),
        "scan created a Cargo.lock"
    );
    assert_eq!(tree_fingerprint(&target), before, "scan mutated target/");
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn scan_on_project_without_target_succeeds() {
    target_gc()
        .args(["scan", "--path", FIXTURE])
        .assert()
        .success()
        .stdout(contains("cargo target-gc scan:"))
        .stdout(contains("same directory where you run `cargo build`"));
    // The read-only fixture must gain no Cargo.lock or target/.
    assert!(!Path::new(FIXTURE).join("Cargo.lock").exists());
    assert!(!Path::new(FIXTURE).join("target").exists());
}

#[test]
fn clean_help_lists_flags() {
    target_gc()
        .args(["clean", "--help"])
        .assert()
        .success()
        .stdout(contains("--dry-run"))
        .stdout(contains("--confirm"))
        .stdout(contains("--force-active"))
        .stdout(contains("--max-reclaim"))
        .stdout(contains("--stale"))
        .stdout(contains("--profile-cache"));
}

#[test]
fn install_agent_skills_help_lists_host_flags() {
    target_gc()
        .args(["install-agent-skills", "--help"])
        .assert()
        .success()
        .stdout(contains("--claude-skills-dir"))
        .stdout(contains("--codex-skills-dir"))
        .stdout(contains("--only"))
        .stdout(contains("--all"))
        .stdout(contains("--dry-run"))
        .stdout(contains("--yes"));
}

#[test]
fn install_agent_skills_dry_run_writes_nothing() {
    let root = temp_project("skill-dry-run");
    let claude = root.join("claude-skills");

    target_gc()
        .args([
            "install-agent-skills",
            "--only",
            "claude",
            "--dry-run",
            "--claude-skills-dir",
        ])
        .arg(&claude)
        .assert()
        .success()
        .stdout(contains("Would install Claude Code skill"));

    assert!(!claude.join("cargo-target-gc/SKILL.md").exists());
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn install_agent_skills_writes_selected_hosts() {
    let root = temp_project("skill-install");
    let claude = root.join("claude-skills");
    let codex = root.join("codex-skills");

    target_gc()
        .args([
            "install-agent-skills",
            "--only",
            "claude,codex",
            "--claude-skills-dir",
        ])
        .arg(&claude)
        .args(["--codex-skills-dir"])
        .arg(&codex)
        .assert()
        .success()
        .stdout(contains("Installed Claude Code skill"))
        .stdout(contains("Installed Codex skill"));

    let claude_skill =
        fs::read_to_string(claude.join("cargo-target-gc/SKILL.md")).expect("claude skill");
    let codex_skill =
        fs::read_to_string(codex.join("cargo-target-gc/SKILL.md")).expect("codex skill");
    assert!(claude_skill.contains("name: cargo-target-gc"));
    assert!(claude_skill.contains("cargo target-gc scan"));
    assert!(claude_skill.contains("Do not run `cargo target-gc clean --confirm`"));
    assert_eq!(claude_skill, codex_skill);
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn install_agent_skills_skip_existing_preserves_file() {
    let root = temp_project("skill-skip-existing");
    let claude = root.join("claude-skills");
    let skill = claude.join("cargo-target-gc/SKILL.md");
    fs::create_dir_all(skill.parent().expect("skill parent")).expect("parent");
    fs::write(&skill, "custom skill").expect("write existing skill");

    target_gc()
        .args([
            "install-agent-skills",
            "--only",
            "claude",
            "--skip-existing",
            "--claude-skills-dir",
        ])
        .arg(&claude)
        .assert()
        .success()
        .stdout(contains("Keeping existing Claude Code skill"));

    assert_eq!(fs::read_to_string(skill).expect("skill"), "custom skill");
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn cargo_subcommand_can_install_agent_skills() {
    let root = temp_project("skill-cargo-subcommand");
    let codex = root.join("codex-skills");

    target_gc()
        .args([
            "target-gc",
            "install-agent-skills",
            "--only",
            "codex",
            "--codex-skills-dir",
        ])
        .arg(&codex)
        .assert()
        .success()
        .stdout(contains("Installed Codex skill"));

    assert!(codex.join("cargo-target-gc/SKILL.md").exists());
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn clean_without_mode_refuses() {
    let root = temp_project("refuse");
    target_gc()
        .args(["clean", "--path"])
        .arg(&root)
        .assert()
        .failure()
        .stderr(contains("--dry-run").or(contains("--confirm")));
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn clean_rejects_both_dry_run_and_confirm() {
    let root = temp_project("conflict");
    let target = root.join("target");
    let before = tree_fingerprint(&target);

    target_gc()
        .args(["clean", "--dry-run", "--confirm", "--path"])
        .arg(&root)
        .assert()
        .failure()
        .stderr(contains("cannot be used with"));

    // A rejected invocation must never touch the target tree.
    assert_eq!(
        tree_fingerprint(&target),
        before,
        "conflicting flags mutated target/"
    );
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn clean_dry_run_leaves_target_unchanged() {
    let root = temp_project("dryrun");
    let target = root.join("target");
    let before = tree_fingerprint(&target);

    target_gc()
        .args(["clean", "--dry-run", "--stale", "--path"])
        .arg(&root)
        .assert()
        .success()
        .stdout(contains("would remove"))
        .stdout(contains("reclaimable:"));

    assert_eq!(tree_fingerprint(&target), before, "dry-run mutated target/");
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn clean_profile_cache_dry_run_includes_fresh_deps() {
    let root = temp_project("profile-cache");
    let target = root.join("target");
    let before = tree_fingerprint(&target);

    target_gc()
        .args(["clean", "--dry-run", "--profile-cache", "--path"])
        .arg(&root)
        .assert()
        .success()
        .stdout(contains("profile-cache mode: enabled"))
        .stdout(contains("profile_cache"))
        .stdout(contains("debug/deps"));

    assert_eq!(
        tree_fingerprint(&target),
        before,
        "profile-cache dry-run mutated target/"
    );
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn clean_profile_cache_json_marks_mode() {
    let root = temp_project("profile-cache-json");
    let output = target_gc()
        .args(["clean", "--dry-run", "--profile-cache", "--json", "--path"])
        .arg(&root)
        .assert()
        .success()
        .get_output()
        .stdout
        .clone();
    let text = String::from_utf8(output).expect("utf8 stdout");
    let value: serde_json::Value = serde_json::from_str(&text).expect("stdout is valid JSON");
    assert_eq!(value["include_profile_cache"], true);
    assert!(value["reclaimable_bytes"].as_u64().expect("bytes") >= 1000);
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn clean_confirm_removes_reclaimable_preserves_retained() {
    let root = temp_project("confirm");
    let target = root.join("target");

    target_gc()
        .args(["clean", "--confirm", "--stale", "--path"])
        .arg(&root)
        .assert()
        .success()
        .stdout(contains("removed"))
        .stdout(contains("reclaimed:"));

    // Reclaimable artifacts are gone; retained + tag survive.
    assert!(!target.join("debug/incremental").exists());
    assert!(!target.join("release/deps/lib.rlib").exists());
    assert!(target.join("debug/deps/lib.rlib").exists());
    assert!(target.join("CACHEDIR.TAG").exists());
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn clean_confirm_refuses_over_max_reclaim() {
    let root = temp_project("maxreclaim");
    let target = root.join("target");
    let before = tree_fingerprint(&target);

    target_gc()
        .args([
            "clean",
            "--confirm",
            "--stale",
            "--max-reclaim",
            "100B",
            "--path",
        ])
        .arg(&root)
        .assert()
        .failure()
        .stderr(contains("exceeds the limit"));

    assert_eq!(
        tree_fingerprint(&target),
        before,
        "max-reclaim refusal mutated target/"
    );
    let _ = fs::remove_dir_all(&root);
}

#[test]
fn config_prints_retention_days() {
    target_gc()
        .args(["config", "--path", FIXTURE])
        .assert()
        .success()
        .stdout(contains("retention_days:").and(contains("30")))
        .stdout(contains("incremental_retention_hours:").and(contains("12")))
        .stdout(contains("max_reclaim_bytes:").and(contains("1048576")));
}

#[test]
fn nonexistent_path_exits_nonzero_with_error() {
    target_gc()
        .args(["scan", "--path", "/cargo-target-gc/definitely/not/here"])
        .assert()
        .failure()
        .stderr(contains("no Cargo.toml found"));
}