rclean-cli 0.2.0

Find and safely clean rebuildable developer artifacts across local workspaces
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
//! `rclean doctor` — diagnostic for which global-cache rules are
//! applicable on this machine.
//!
//! Each Phase 1 global-path rule has a canonical anchor directory
//! (`~/.cargo`, `~/.gradle`, `~/Library/Developer`, ...). Doctor
//! reports per-rule whether that anchor exists, so the user can
//! see at a glance what `rclean scan --home` will actually touch.
//!
//! No filesystem writes, no subprocess spawns. Pure dir-exists
//! checks. Safe to run on any machine, including CI.
//!
//! See `docs/specs/v0.2-developer-mole.md` §4.3.

mod anchors;

use std::path::PathBuf;
use std::time::Duration;

use anchors::{
    android_sdk_anchors, browser_cache_anchors, deno_cache_anchors, homebrew_download_anchors,
    ide_log_anchors, ide_system_anchors, python_cache_anchors, simple_cache_anchors,
};

#[derive(Debug)]
pub struct DoctorReport {
    pub entries: Vec<DoctorEntry>,
}

#[derive(Debug)]
pub struct DoctorEntry {
    pub rule_id: &'static str,
    pub anchor: PathBuf,
    pub status: Status,
}

#[derive(Debug, PartialEq, Eq)]
pub enum Status {
    Applicable,
    Skipped { reason: String },
}

#[derive(Debug, Default)]
pub struct DoctorOptions {
    pub include_docker: bool,
}

impl DoctorReport {
    pub fn applicable_count(&self) -> usize {
        self.entries
            .iter()
            .filter(|e| matches!(e.status, Status::Applicable))
            .count()
    }

    pub fn total_count(&self) -> usize {
        self.entries.len()
    }
}

pub fn diagnose() -> DoctorReport {
    diagnose_with_options(DoctorOptions::default())
}

pub fn diagnose_with_options(options: DoctorOptions) -> DoctorReport {
    let Some(home) = std::env::var_os("HOME").map(PathBuf::from) else {
        return DoctorReport {
            entries: Vec::new(),
        };
    };

    // Cross-platform rules. Each anchor is the directory the rule's
    // classifier checks via parent_ends_with — its existence is a
    // necessary (not sufficient) condition for the rule to fire.
    let mut entries = vec![
        check_anchor(
            "cargo.registry_cache",
            home.join(".cargo").join("registry"),
            "no Cargo install detected",
        ),
        check_anchor(
            "cargo.git_db",
            home.join(".cargo").join("git"),
            "no Cargo git deps detected",
        ),
        check_any_anchor(
            "homebrew.downloads",
            homebrew_download_anchors(&home),
            "no Homebrew download cache detected",
        ),
        check_any_anchor(
            "android_sdk.download_intermediates",
            android_sdk_anchors(&home),
            "no Android SDK root detected",
        ),
        check_anchor(
            "android_sdk.legacy_build_cache",
            home.join(".android").join("build-cache"),
            "no legacy Android build cache detected",
        ),
        check_anchor(
            "dart.pub_hosted_cache",
            home.join(".pub-cache").join("hosted"),
            "no Dart pub hosted cache detected",
        ),
        check_anchor(
            "dart.pub_git_cache",
            home.join(".pub-cache").join("git"),
            "no Dart pub git cache detected",
        ),
        check_anchor(
            "go.module_download_cache",
            home.join("go").join("pkg").join("mod").join("cache"),
            "no Go module cache detected",
        ),
        check_anchor(
            "go.module_cache",
            home.join("go").join("pkg").join("mod"),
            "no Go module cache detected",
        ),
        check_anchor(
            "gradle.caches",
            home.join(".gradle"),
            "no Gradle install detected",
        ),
        check_anchor(
            "maven.local_repo",
            home.join(".m2"),
            "no Maven install detected",
        ),
        check_anchor(
            "node.npm_cacache",
            home.join(".npm"),
            "no npm install detected",
        ),
        check_anchor(
            "node.npm_transient",
            home.join(".npm"),
            "no npm install detected",
        ),
        check_anchor(
            "bun.cache",
            home.join(".bun").join("install"),
            "no bun install cache detected",
        ),
        check_anchor(
            "pre_commit.cache",
            home.join(".cache"),
            "no XDG cache directory",
        ),
        check_anchor(
            "ruby.bundle_compact_index",
            home.join(".bundle").join("cache").join("compact_index"),
            "no Bundler compact index detected",
        ),
        check_anchor(
            "cloud.kube_cache",
            home.join(".kube").join("cache"),
            "no Kubernetes cache detected",
        ),
        check_anchor(
            "cloud.gcloud_logs",
            home.join(".config").join("gcloud").join("logs"),
            "no gcloud logs detected",
        ),
        check_anchor(
            "editor.vscode_obsolete_extension",
            home.join(".vscode").join("extensions"),
            "no VS Code extensions detected",
        ),
        check_anchor(
            "editor.cursor_obsolete_extension",
            home.join(".cursor").join("extensions"),
            "no Cursor extensions detected",
        ),
        check_anchor(
            "claude.old_version",
            home.join(".local")
                .join("share")
                .join("claude")
                .join("versions"),
            "no Claude Code versions detected",
        ),
    ];

    let mut pnpm_anchors = vec![home.join(".pnpm-store")];
    #[cfg(target_os = "macos")]
    {
        pnpm_anchors.push(home.join("Library").join("pnpm").join("store"));
        pnpm_anchors.push(
            home.join("Library")
                .join("Caches")
                .join("pnpm")
                .join("store"),
        );
    }
    #[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
    {
        pnpm_anchors.push(home.join(".local").join("share").join("pnpm").join("store"));
    }
    #[cfg(target_os = "windows")]
    {
        pnpm_anchors.push(
            home.join("AppData")
                .join("Local")
                .join("pnpm")
                .join("store"),
        );
    }
    entries.push(check_any_anchor(
        "node.pnpm_store",
        pnpm_anchors,
        "no pnpm store detected",
    ));

    // pip uses different anchors per platform.
    #[cfg(target_os = "macos")]
    {
        entries.push(check_anchor(
            "pip.cache",
            home.join("Library").join("Caches"),
            "no Library/Caches directory",
        ));
        entries.push(check_anchor(
            "go.build_cache",
            home.join("Library").join("Caches").join("go-build"),
            "no Go build cache detected",
        ));
    }
    #[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
    {
        entries.push(check_anchor(
            "pip.cache",
            home.join(".cache"),
            "no XDG cache directory",
        ));
        entries.push(check_anchor(
            "go.build_cache",
            home.join(".cache").join("go-build"),
            "no Go build cache detected",
        ));
    }
    #[cfg(target_os = "windows")]
    {
        entries.push(check_anchor(
            "pip.cache",
            home.join(".cache"),
            "no XDG cache directory",
        ));
        entries.push(check_anchor(
            "go.build_cache",
            home.join("AppData").join("Local").join("go-build"),
            "no Go build cache detected",
        ));
    }

    // AI / ML model caches (#102). All three rules anchor under
    // `~/.cache/...` and `~/.ollama/...` on every platform.
    entries.push(check_anchor(
        "ai.huggingface_hub",
        home.join(".cache").join("huggingface").join("hub"),
        "no HuggingFace cache detected",
    ));
    entries.push(check_anchor(
        "ai.torch_hub",
        home.join(".cache").join("torch").join("hub"),
        "no PyTorch hub cache detected",
    ));
    entries.push(check_anchor(
        "ai.vllm_compile_cache",
        home.join(".cache").join("vllm").join("torch_compile_cache"),
        "no vLLM compile cache detected",
    ));
    entries.push(check_anchor(
        "ai.whisper_models",
        home.join(".cache").join("whisper"),
        "no Whisper model cache detected",
    ));
    entries.push(check_any_anchor(
        "ai.llama_cpp_cache",
        simple_cache_anchors(&home, "llama.cpp"),
        "no llama.cpp model cache detected",
    ));
    entries.push(check_anchor(
        "ai.ollama_models",
        home.join(".ollama").join("models"),
        "no Ollama install detected",
    ));

    // Python global tooling caches (#101). uv, Poetry, and pipx each
    // resolve to either the native macOS path or the XDG override —
    // real users hit both, so doctor accepts either anchor.
    entries.push(check_any_anchor(
        "python.uv_cache",
        python_cache_anchors(&home, "uv"),
        "no uv install detected",
    ));
    entries.push(check_any_anchor(
        "python.poetry_cache",
        python_cache_anchors(&home, "pypoetry"),
        "no Poetry install detected",
    ));
    entries.push(check_any_anchor(
        "python.pipx_cache",
        python_cache_anchors(&home, "pipx"),
        "no pipx install detected",
    ));

    // Deno's cache can be native macOS or XDG-style, depending on
    // platform and user environment.
    entries.push(check_any_anchor(
        "js.deno_cache",
        deno_cache_anchors(&home),
        "no Deno install detected",
    ));

    // Puppeteer keeps Chrome for Testing downloads in a global cache.
    entries.push(check_any_anchor(
        "browser.puppeteer",
        browser_cache_anchors(&home, "puppeteer"),
        "no Puppeteer install detected",
    ));
    entries.push(check_any_anchor(
        "jetbrains.system_caches",
        ide_system_anchors(&home, "JetBrains"),
        "no JetBrains IDE system cache detected",
    ));
    entries.push(check_any_anchor(
        "jetbrains.logs",
        ide_log_anchors(&home, "JetBrains"),
        "no JetBrains IDE logs detected",
    ));
    entries.push(check_any_anchor(
        "android_studio.system_caches",
        ide_system_anchors(&home, "Google"),
        "no Android Studio system cache detected",
    ));
    entries.push(check_any_anchor(
        "android_studio.logs",
        ide_log_anchors(&home, "Google"),
        "no Android Studio logs detected",
    ));

    // macOS-only rules. On non-macOS the anchor never exists, so the
    // entry is reported as Skipped with a platform reason — gives
    // Linux users an accurate "this rule doesn't apply here" instead
    // of hiding it.
    #[cfg(target_os = "macos")]
    {
        entries.push(check_anchor(
            "node.yarn_cache",
            home.join("Library").join("Caches"),
            "no Library/Caches directory",
        ));
        entries.push(check_anchor(
            "xcode.derived_data",
            home.join("Library").join("Developer").join("Xcode"),
            "no Xcode install detected",
        ));
        entries.push(check_anchor(
            "xcode.simulators",
            home.join("Library").join("Developer"),
            "no Xcode install detected",
        ));
    }
    #[cfg(not(target_os = "macos"))]
    {
        entries.push(DoctorEntry {
            rule_id: "node.yarn_cache",
            anchor: PathBuf::from("(macOS only)"),
            status: Status::Skipped {
                reason: "rule only applies on macOS".to_string(),
            },
        });
        entries.push(DoctorEntry {
            rule_id: "xcode.derived_data",
            anchor: PathBuf::from("(macOS only)"),
            status: Status::Skipped {
                reason: "rule only applies on macOS".to_string(),
            },
        });
        entries.push(DoctorEntry {
            rule_id: "xcode.simulators",
            anchor: PathBuf::from("(macOS only)"),
            status: Status::Skipped {
                reason: "rule only applies on macOS".to_string(),
            },
        });
    }

    // Playwright lives in `~/Library/Caches/ms-playwright` on macOS
    // and `~/.cache/ms-playwright` on Linux. On Windows the layout is
    // different and v0.3 doesn't support it — report Skipped.
    #[cfg(target_os = "macos")]
    {
        entries.push(check_anchor(
            "playwright.browsers",
            home.join("Library").join("Caches").join("ms-playwright"),
            "no Playwright browsers detected",
        ));
    }
    #[cfg(all(not(target_os = "macos"), not(target_os = "windows")))]
    {
        entries.push(check_anchor(
            "playwright.browsers",
            home.join(".cache").join("ms-playwright"),
            "no Playwright browsers detected",
        ));
    }
    #[cfg(target_os = "windows")]
    {
        entries.push(DoctorEntry {
            rule_id: "playwright.browsers",
            anchor: PathBuf::from("(macOS / Linux only)"),
            status: Status::Skipped {
                reason: "rule only applies on macOS and Linux".to_string(),
            },
        });
    }

    // v0.3 Phase 2: GUI app caches under ~/Library/* (macOS only).
    // Each rule anchors on the candidate's parent directory, so
    // doctor checks whether that parent exists at all.
    #[cfg(target_os = "macos")]
    {
        entries.push(check_anchor(
            "app.shipit_caches",
            home.join("Library").join("Caches"),
            "no Library/Caches directory",
        ));
        entries.push(check_anchor(
            "chrome.cache",
            home.join("Library").join("Caches").join("Google"),
            "no Chrome cache detected",
        ));
        entries.push(check_anchor(
            "chrome.google_updater",
            home.join("Library")
                .join("Application Support")
                .join("Google"),
            "no Google app data detected",
        ));
        entries.push(check_anchor(
            "app.lark_cache",
            home.join("Library")
                .join("Caches")
                .join("LarkInternational"),
            "no Lark/Feishu cache detected",
        ));
        entries.push(skipped_anchor(
            "macos.chrome_code_sign_clone",
            PathBuf::from("/private/var/folders/*/*/X/com.google.Chrome.code_sign_clone"),
            "exact macOS temp candidate not checked by doctor",
        ));
        entries.push(skipped_anchor(
            "macos.remem_dry_run_tmp",
            PathBuf::from("/private/var/folders/*/*/T/remem-dry-run-*"),
            "exact macOS temp candidate not checked by doctor",
        ));
        entries.push(check_anchor(
            "apple.wallpaper_aerial_videos",
            home.join("Library")
                .join("Application Support")
                .join("com.apple.wallpaper")
                .join("aerials"),
            "no macOS aerial wallpaper cache detected",
        ));
        entries.push(skipped_anchor(
            "apple.idleassetsd",
            PathBuf::from("/Library")
                .join("Application Support")
                .join("com.apple.idleassetsd"),
            "system-scope candidate checked by scan --system",
        ));
        entries.push(check_anchor(
            "chrome.opt_guide_model",
            home.join("Library")
                .join("Application Support")
                .join("Google")
                .join("Chrome"),
            "no Chrome app support detected",
        ));
        entries.push(check_anchor(
            "app.lark_update",
            home.join("Library")
                .join("Application Support")
                .join("LarkInternational"),
            "no Lark/Feishu app support detected",
        ));
        entries.push(check_anchor(
            "macos.geod_map_tiles",
            home.join("Library")
                .join("Containers")
                .join("com.apple.geod")
                .join("Data")
                .join("Library")
                .join("Caches")
                .join("com.apple.geod"),
            "no geod map cache detected",
        ));
        entries.push(check_anchor(
            "macos.mediaanalysisd_cache",
            home.join("Library")
                .join("Containers")
                .join("com.apple.mediaanalysisd")
                .join("Data")
                .join("Library")
                .join("Caches"),
            "no mediaanalysisd cache detected",
        ));
        entries.push(check_anchor(
            "macos.mediaanalysisd_tmp",
            home.join("Library")
                .join("Containers")
                .join("com.apple.mediaanalysisd")
                .join("Data")
                .join("tmp"),
            "no mediaanalysisd tmp cache detected",
        ));
        entries.push(check_anchor(
            "editor.vscode_cache",
            home.join("Library")
                .join("Application Support")
                .join("Code"),
            "no VS Code app support detected",
        ));
        entries.push(check_anchor(
            "editor.cursor_cache",
            home.join("Library")
                .join("Application Support")
                .join("Cursor"),
            "no Cursor app support detected",
        ));
        entries.push(check_any_anchor(
            "app.electron_cache",
            ["Notion", "Slack", "LarkInternational"]
                .into_iter()
                .map(|app| home.join("Library").join("Application Support").join(app))
                .collect(),
            "no known Electron app support detected",
        ));
    }
    #[cfg(not(target_os = "macos"))]
    {
        for rule_id in [
            "app.shipit_caches",
            "chrome.cache",
            "chrome.google_updater",
            "app.lark_cache",
            "macos.chrome_code_sign_clone",
            "macos.remem_dry_run_tmp",
            "apple.wallpaper_aerial_videos",
            "apple.idleassetsd",
            "chrome.opt_guide_model",
            "app.lark_update",
            "macos.geod_map_tiles",
            "macos.mediaanalysisd_cache",
            "macos.mediaanalysisd_tmp",
            "editor.vscode_cache",
            "editor.cursor_cache",
            "app.electron_cache",
        ] {
            entries.push(DoctorEntry {
                rule_id,
                anchor: PathBuf::from("(macOS only)"),
                status: Status::Skipped {
                    reason: "rule only applies on macOS".to_string(),
                },
            });
        }
    }

    if options.include_docker {
        entries.push(check_docker_daemon(Duration::from_secs(5)));
    }

    DoctorReport { entries }
}

fn check_anchor(
    rule_id: &'static str,
    anchor: PathBuf,
    missing_reason: &'static str,
) -> DoctorEntry {
    let exists = anchor.is_dir();
    let status = if exists {
        Status::Applicable
    } else {
        Status::Skipped {
            reason: missing_reason.to_string(),
        }
    };
    DoctorEntry {
        rule_id,
        anchor,
        status,
    }
}

#[cfg(target_os = "macos")]
fn skipped_anchor(rule_id: &'static str, anchor: PathBuf, reason: &'static str) -> DoctorEntry {
    DoctorEntry {
        rule_id,
        anchor,
        status: Status::Skipped {
            reason: reason.to_string(),
        },
    }
}

fn check_any_anchor(
    rule_id: &'static str,
    anchors: Vec<PathBuf>,
    missing_reason: &'static str,
) -> DoctorEntry {
    if let Some(anchor) = anchors.iter().find(|anchor| anchor.is_dir()) {
        return DoctorEntry {
            rule_id,
            anchor: anchor.clone(),
            status: Status::Applicable,
        };
    }

    DoctorEntry {
        rule_id,
        anchor: anchors
            .into_iter()
            .next()
            .unwrap_or_else(|| PathBuf::from("(unknown)")),
        status: Status::Skipped {
            reason: missing_reason.to_string(),
        },
    }
}

fn check_docker_daemon(timeout: Duration) -> DoctorEntry {
    match crate::docker::probe_for_doctor(timeout) {
        crate::docker::DockerDoctorStatus::Available { server_version } => DoctorEntry {
            rule_id: "docker.daemon",
            anchor: server_version
                .map(|version| PathBuf::from(format!("Docker Server {version}")))
                .unwrap_or_else(|| PathBuf::from("Docker daemon")),
            status: Status::Applicable,
        },
        crate::docker::DockerDoctorStatus::Skipped { reason } => DoctorEntry {
            rule_id: "docker.daemon",
            anchor: PathBuf::from("docker"),
            status: Status::Skipped { reason },
        },
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::fs;
    use std::path::Path;
    use std::sync::{Mutex, MutexGuard};

    static HOME_LOCK: Mutex<()> = Mutex::new(());

    #[test]
    fn diagnose_returns_one_entry_per_phase1_global_rule() {
        // Run with a synthetic HOME to make the result deterministic.
        let temp = tempfile::TempDir::new().unwrap();
        // SAFETY: tests in a single binary share process env. The
        // assertion only relies on the total entry count, which is
        // the same regardless of which anchors exist.
        let _restore = with_home(temp.path());

        let report = diagnose();
        // v0.3 Phase 2 + Python + Deno + Puppeteer + AI/ML had 26 entries;
        // #116 conservative user/app cache coverage adds 10 more;
        // #117 macOS whole-machine/app cache coverage adds 7 more anchors
        // plus the Go modcache root cleanup rule. #160/#162 add 10 more
        // exact-anchor global cache rules. #158 adds one system-scope
        // report-only rule.
        assert_eq!(report.total_count(), 59);
    }

    #[test]
    fn diagnose_marks_existing_anchor_applicable() {
        let temp = tempfile::TempDir::new().unwrap();
        // Synthesize ~/.cargo/registry so cargo.registry_cache becomes
        // applicable.
        fs::create_dir_all(temp.path().join(".cargo").join("registry")).unwrap();
        let _restore = with_home(temp.path());

        let report = diagnose();
        let cargo_reg = report
            .entries
            .iter()
            .find(|e| e.rule_id == "cargo.registry_cache")
            .expect("cargo.registry_cache entry should exist");
        assert_eq!(cargo_reg.status, Status::Applicable);
    }

    #[test]
    fn diagnose_marks_missing_anchor_skipped() {
        let temp = tempfile::TempDir::new().unwrap();
        let _restore = with_home(temp.path());

        let report = diagnose();
        let cargo_reg = report
            .entries
            .iter()
            .find(|e| e.rule_id == "cargo.registry_cache")
            .expect("cargo.registry_cache entry should exist");
        assert!(matches!(cargo_reg.status, Status::Skipped { .. }));
    }

    /// Test helper that swaps HOME for the duration of the test and
    /// restores it on drop. Avoids leaking the override into other
    /// tests in the same binary.
    fn with_home(path: &Path) -> HomeGuard {
        let lock = HOME_LOCK.lock().expect("HOME test mutex poisoned");
        let previous = std::env::var_os("HOME");
        // SAFETY: HOME_LOCK serializes every test in this module that
        // mutates the process environment, and Drop restores HOME.
        unsafe {
            std::env::set_var("HOME", path);
        }
        HomeGuard {
            previous,
            _lock: lock,
        }
    }

    struct HomeGuard {
        previous: Option<std::ffi::OsString>,
        _lock: MutexGuard<'static, ()>,
    }

    impl Drop for HomeGuard {
        fn drop(&mut self) {
            // SAFETY: see with_home above.
            unsafe {
                match &self.previous {
                    Some(v) => std::env::set_var("HOME", v),
                    None => std::env::remove_var("HOME"),
                }
            }
        }
    }
}