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
//! Per-candidate safety promotion and pruning predicates.
//!
//! These are the trust-boundary checks the walker and `explain`
//! both share:
//!
//! - [`apply_path_safety`]: symlinks → Blocked; system/runtime
//!   directories → Blocked; candidates resolving outside the scan
//!   root → Blocked.
//! - [`is_skip_dir`] / [`is_skip_name`]: directories we never descend
//!   into (`.git`, toolchain caches, the Trash, the macOS Library).
//! - [`is_protected_user_data_path`]: user-owned records that are never
//!   cleanable, even if a rule or plan points at them.
//! - [`is_runtime_or_system_path`]: same allowlist applied as an
//!   any-component check on the candidate path.

use std::fs;
use std::fs::Metadata;
#[cfg(unix)]
use std::os::unix::fs::MetadataExt;
#[cfg(windows)]
use std::os::windows::fs::MetadataExt;
use std::path::Path;

use crate::model::{CandidateDraft, Safety};
use crate::path_util::path_file_name;
use crate::rules;

const RUNTIME_OR_SYSTEM_COMPONENTS: &[&str] = &[
    ".cargo",
    ".rustup",
    ".nvm",
    ".fnm",
    ".pyenv",
    ".sdkman",
    ".rbenv",
    ".conda",
    "Library",
    "Applications",
    ".Trash",
];

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum DangerousLink {
    Symlink,
    #[cfg(unix)]
    HardlinkedFile,
    #[cfg(windows)]
    ReparsePoint,
}

impl DangerousLink {
    pub(crate) fn description(self) -> &'static str {
        match self {
            Self::Symlink => "symlink",
            #[cfg(unix)]
            Self::HardlinkedFile => "hardlinked file",
            #[cfg(windows)]
            Self::ReparsePoint => "junction or reparse point",
        }
    }
}

pub(crate) fn dangerous_link_kind(metadata: &Metadata) -> Option<DangerousLink> {
    if metadata.file_type().is_symlink() {
        return Some(DangerousLink::Symlink);
    }

    #[cfg(unix)]
    {
        // Directories normally have nlink > 1 on Unix, so only regular
        // hardlinked files are dangerous here.
        if metadata.file_type().is_file() && metadata.nlink() > 1 {
            return Some(DangerousLink::HardlinkedFile);
        }
    }

    #[cfg(windows)]
    {
        const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x400;
        if metadata.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 {
            return Some(DangerousLink::ReparsePoint);
        }
    }

    None
}

pub(crate) fn apply_path_safety(root: &Path, draft: &mut CandidateDraft) {
    let metadata = fs::symlink_metadata(&draft.path);
    if let Ok(metadata) = metadata.as_ref()
        && let Some(kind) = dangerous_link_kind(metadata)
    {
        draft.safety = Safety::Blocked;
        draft
            .warnings
            .push(format!("candidate is a {}", kind.description()));
        return;
    }

    if is_protected_user_data_path(&draft.path)
        && !rules::allows_protected_user_data_path(&draft.rule_id)
    {
        draft.safety = Safety::Blocked;
        draft
            .warnings
            .push("candidate is inside protected user data".to_string());
        return;
    }

    if is_docker_storage_path(&draft.path) {
        draft.safety = Safety::Blocked;
        draft
            .warnings
            .push("candidate is inside Docker daemon storage".to_string());
        return;
    }

    // Global rules target paths that live inside the user's Library /
    // runtime tree by design. Their classifier already establishes that
    // the path is a rebuildable cache, so the generic runtime/system-path
    // block would otherwise hide them.
    if !rules::is_global_rule(&draft.rule_id) && is_runtime_or_system_path(&draft.path) {
        draft.safety = Safety::Blocked;
        draft
            .warnings
            .push("candidate is inside a protected runtime or system path".to_string());
        return;
    }

    if root != Path::new(".") {
        let root = root.canonicalize().ok();
        let candidate = draft.path.canonicalize().ok();
        if let (Some(root), Some(candidate)) = (root, candidate)
            && !candidate.starts_with(root)
        {
            draft.safety = Safety::Blocked;
            draft
                .warnings
                .push("candidate resolves outside the scan root".to_string());
        }
    }
}

pub(crate) fn is_skip_dir(path: &Path) -> bool {
    path_file_name(path).is_some_and(is_skip_name)
}

pub(crate) fn is_skip_name(name: &str) -> bool {
    matches!(
        name,
        ".git"
            | ".hg"
            | ".svn"
            | ".Trash"
            | "Library"
            | "Applications"
            | ".cargo"
            | ".rustup"
            | ".nvm"
            | ".fnm"
            | ".pyenv"
            | ".sdkman"
            | ".rbenv"
            | ".conda"
            | ".terraform"
    )
}

pub(crate) fn is_runtime_or_system_path(path: &Path) -> bool {
    path.components()
        .filter_map(component_name)
        .any(|name| RUNTIME_OR_SYSTEM_COMPONENTS.contains(&name))
}

pub(crate) fn is_protected_user_data_path(path: &Path) -> bool {
    let mut previous = None;
    for name in path.components().filter_map(component_name) {
        match (previous, name) {
            (Some(".codex"), "sessions" | "memories") => return true,
            (
                Some(".claude"),
                "projects" | "sessions" | "history.jsonl" | "shell-snapshots" | "file-history"
                | "todos",
            ) => return true,
            (Some("Library"), "Containers") => return true,
            (Some("Chrome"), "Default") => return true,
            (Some("Code") | Some("Cursor"), "User" | "globalStorage" | "workspaceStorage") => {
                return true;
            }
            (Some("Notion"), "Partitions") => return true,
            _ => {}
        }
        previous = Some(name);
    }
    false
}

pub(crate) fn is_docker_storage_path(path: &Path) -> bool {
    let components: Vec<&str> = path.components().filter_map(component_name).collect();
    has_component_sequence(&components, &["var", "lib", "docker"])
        || has_component_sequence(&components, &[".local", "share", "docker"])
        || has_component_sequence(&components, &["Library", "Containers", "com.docker.docker"])
        || has_component_sequence_ignore_ascii_case(&components, &["AppData", "Local", "Docker"])
        || has_component_sequence_ignore_ascii_case(
            &components,
            &["AppData", "Local", "Docker Desktop"],
        )
}

fn has_component_sequence(components: &[&str], sequence: &[&str]) -> bool {
    components
        .windows(sequence.len())
        .any(|window| window == sequence)
}

fn has_component_sequence_ignore_ascii_case(components: &[&str], sequence: &[&str]) -> bool {
    components.windows(sequence.len()).any(|window| {
        window
            .iter()
            .zip(sequence)
            .all(|(component, expected)| component.eq_ignore_ascii_case(expected))
    })
}

fn component_name(component: std::path::Component<'_>) -> Option<&str> {
    component.as_os_str().to_str()
}

#[cfg(test)]
mod tests {
    use super::{
        DangerousLink, dangerous_link_kind, is_docker_storage_path, is_protected_user_data_path,
        is_runtime_or_system_path,
    };
    use std::fs;
    use std::path::PathBuf;
    use tempfile::TempDir;

    #[test]
    fn regular_directory_is_not_a_dangerous_link() {
        let temp = TempDir::new().unwrap();
        let metadata = fs::symlink_metadata(temp.path()).unwrap();

        assert_eq!(dangerous_link_kind(&metadata), None);
    }

    #[test]
    #[cfg(unix)]
    fn detects_hardlinked_regular_file() {
        let temp = TempDir::new().unwrap();
        let original = temp.path().join("original");
        let hardlink = temp.path().join("hardlink");
        fs::write(&original, "content").unwrap();
        fs::hard_link(&original, &hardlink).unwrap();

        let metadata = fs::symlink_metadata(&hardlink).unwrap();

        assert_eq!(
            dangerous_link_kind(&metadata),
            Some(DangerousLink::HardlinkedFile)
        );
    }

    #[test]
    #[cfg(windows)]
    fn detects_junction_as_dangerous_link() {
        let temp = TempDir::new().unwrap();
        let target = temp.path().join("target");
        let junction = temp.path().join("junction");
        fs::create_dir(&target).unwrap();
        let output = std::process::Command::new("cmd")
            .args(["/C", "mklink", "/J"])
            .arg(&junction)
            .arg(&target)
            .output()
            .unwrap();
        assert!(
            output.status.success(),
            "mklink failed: {}",
            String::from_utf8_lossy(&output.stderr)
        );

        let metadata = fs::symlink_metadata(&junction).unwrap();

        let kind = dangerous_link_kind(&metadata).expect("junction must be dangerous");
        assert!(
            matches!(kind, DangerousLink::Symlink | DangerousLink::ReparsePoint),
            "unexpected dangerous link kind: {kind:?}"
        );
    }

    #[test]
    fn runtime_or_system_path_matches_any_protected_component() {
        for path in [
            "/Users/me/.cargo/registry/cache",
            "/Users/me/Library/Caches/example",
            "/Users/me/project/.Trash/old-file",
        ] {
            assert!(
                is_runtime_or_system_path(&PathBuf::from(path)),
                "expected {path} to be protected"
            );
        }
    }

    #[test]
    fn runtime_or_system_path_requires_exact_component_match() {
        for path in [
            "/Users/me/cargo/registry/cache",
            "/Users/me/MyLibrary/Caches/example",
            "/Users/me/project/Trash/old-file",
        ] {
            assert!(
                !is_runtime_or_system_path(&PathBuf::from(path)),
                "did not expect {path} to be protected"
            );
        }
    }

    #[test]
    fn protects_codex_user_records() {
        assert!(is_protected_user_data_path(&PathBuf::from(
            "/Users/me/.codex/sessions"
        )));
        assert!(is_protected_user_data_path(&PathBuf::from(
            "/Users/me/.codex/memories/note.md"
        )));
    }

    #[test]
    fn protects_claude_code_user_records() {
        for path in [
            "/Users/me/.claude/projects/-some-encoded-path/abc.jsonl",
            "/Users/me/.claude/sessions/2026-05-24",
            "/Users/me/.claude/history.jsonl",
            "/Users/me/.claude/shell-snapshots/snap-1.json",
            "/Users/me/.claude/file-history/foo.diff",
            "/Users/me/.claude/todos/today.md",
        ] {
            assert!(
                is_protected_user_data_path(&PathBuf::from(path)),
                "expected {path} to be protected"
            );
        }
    }

    #[test]
    fn protects_macos_app_container_and_profile_state() {
        for path in [
            "/Users/me/Library/Containers/com.tencent.xinWeChat",
            "/Users/me/Library/Application Support/Google/Chrome/Default",
            "/Users/me/Library/Application Support/Code/User",
            "/Users/me/Library/Application Support/Code/globalStorage",
            "/Users/me/Library/Application Support/Cursor/workspaceStorage",
            "/Users/me/Library/Application Support/Notion/Partitions",
        ] {
            assert!(
                is_protected_user_data_path(&PathBuf::from(path)),
                "expected {path} to be protected"
            );
        }
    }

    #[test]
    fn protects_docker_daemon_storage_paths() {
        for path in [
            "/var/lib/docker/overlay2/layer/target",
            "/Users/me/.local/share/docker/buildx/cache",
            "/Users/me/Library/Containers/com.docker.docker/Data/vms/0",
            "C:/Users/me/AppData/Local/Docker/wsl/data/ext4.vhdx",
            "C:/Users/me/AppData/Local/Docker Desktop/cache",
            "C:/Users/me/AppData/Local/docker/wsl/data/ext4.vhdx",
            "C:/Users/me/appdata/local/docker desktop/cache",
        ] {
            assert!(
                is_docker_storage_path(&PathBuf::from(path)),
                "expected {path} to be protected Docker daemon storage"
            );
        }
    }

    #[test]
    fn docker_storage_path_requires_exact_component_sequence() {
        for path in [
            "/Users/me/project/docker/cache",
            "/Users/me/.local/share/docker-tools/cache",
            "/var/lib/docker-compose/cache",
            "C:/Users/me/AppData/Local/Dockerfile/cache",
        ] {
            assert!(
                !is_docker_storage_path(&PathBuf::from(path)),
                "did not expect {path} to be Docker daemon storage"
            );
        }
    }

    #[test]
    fn does_not_protect_rebuildable_claude_subdirs() {
        for path in [
            "/Users/me/.claude/cache/x",
            "/Users/me/.claude/paste-cache/y",
            "/Users/me/.claude/downloads/z",
        ] {
            assert!(
                !is_protected_user_data_path(&PathBuf::from(path)),
                "did not expect {path} to be protected"
            );
        }
    }

    #[test]
    fn does_not_protect_unrelated_paths() {
        assert!(!is_protected_user_data_path(&PathBuf::from(
            "/Users/me/work/projects/foo"
        )));
        assert!(!is_protected_user_data_path(&PathBuf::from(
            "/Users/me/.config/sessions/foo"
        )));
    }
}