Building a Windows disk cleaner in Rust that never deletes blindly

2026-12-02来源 dev.toEnglish
Building a Windows disk cleaner in Rust that never deletes blindly

Every Windows cleaner I tried worked the same way: click Clean, watch a number go up, and hope. I never knew what had actually been deleted, or why.

So I built FreeMyDisk, a free, open-source (GPL-3.0) disk cleaner for Windows 10 and 11, around one idea: it has to explain everything before it touches anything, and a bug or a crash must never cost you a file.

This post is about how that works under the hood: the rule format, the deletion pipeline, the duplicate finder, and one bug I shipped that taught me the most.

(The Large Files and Duplicates parts of the video use sample data.)

The stack

  • Engine: a Rust workspace with four crates: freemydisk-core (rules, scanning, disposal, journal), freemydisk-platform (Win32: Recycle Bin, Restart Manager, USN scan), freemydisk-cli, and a small elevated helper.
  • App: Tauri 2 with React 19, TypeScript and Zustand.
  • Storage: SQLite (rusqlite, WAL mode) for the journal.
  • Hashing: BLAKE3.

Deep Cleanup view: each rule shows its owner app, risk level, size, and whether a running app is locking it

1. Rules are data, not code

Every cleanup target is a plain TOML file, and there are 122 of them for Windows, browsers, apps, developer tools and AI caches. This is the real rule for Spotify:

[rule] id = "windows_application_spotify_cache" name = "Spotify Media & Storage Cache" category = "application" risk = "safe" verified_rebuildable = true description = "Cached streamed audio chunks and offline artwork stored by Spotify" platform = "windows" locking_processes = ["spotify.exe"] # skipped while Spotify is running [applicability] conditions = [{ type = "path_exists", path = "${local_app_data}/Spotify/Data" }] [targets] paths = [{ path = "${local_app_data}/Spotify/Data/*", matcher = "glob" }] [disposal] default_action = "permanent" protect_subpaths = ["*/Users/*"] 

This gives three things I wanted:

  1. Anyone can audit it. You don't have to trust me about what "Spotify cache" means; the paths are right there.
  2. The UI can explain itself. Risk level, owner app and locking processes come straight from the rule, so the app can say "close Spotify to clean" instead of failing silently.
  3. Contributions are easy. A new app's cache is about 20 lines of TOML, with no engine change.

A build script validates every rule (including duplicate IDs), and integration tests check them too, so a broken rule fails the build or CI rather than a user's cleanup.

2. The deletion pipeline

This is the part I spent the most time on. Each item goes through the same steps:

Step What happens
Intent Write the deletion to the SQLite journal before anything is touched on disk
Check Re-check the path against a protected-path registry (Windows, Program Files, user hives, FreeMyDisk itself)
Check Skip files a running app holds open
Check Keep anything modified in the last 24 hours, so temp cleaning never races a running installer
Dispose Move to the Recycle Bin, or delete through a staging rename (below)
Commit Mark the journal row done

The journal row is inserted with the status in_flight:

"INSERT INTO disposal_journal (session_id, target_path, staging_path, planned_action, timestamp, status) VALUES (?1, ?2, ?3, ?4, ?5, 'in_flight');" 

If the app crashes or the PC loses power mid-cleanup, the next start finds rows still in_flight and recovers them.

Recycle Bin by default

By default, everything goes to the Recycle Bin, so any cleanup can be undone. If a move to the Recycle Bin fails, the file is kept and flagged, never silently deleted instead.

You can turn that setting off. Then rules marked as rebuildable caches are deleted permanently, but still not in a single step: the item is first renamed to a staging path that the journal records, then deleted. If the delete only partly succeeds, the rest is renamed back to where it was:

/// Renames `path` to its staging name before deleting it, so a crash leaves a /// restorable copy that the journal can put back. Whatever cannot be deleted is /// restored to the original location. fn delete_through_staging(/* ... */) -> (u64, Option<String>) { // ... } 

A permanent delete that leaves files behind (because something had them open) is reported as partial, not as success.

3. The bug I'm least proud of

Version 1.0.0 had a real data-safety bug: when moving a folder to the Recycle Bin, a symlink or junction inside it was followed. The folder the link pointed to could end up in the Recycle Bin instead of the link itself.

The cause was one innocent-looking line. Before handing a path to the Recycle Bin, the code normalized it:

let clean = dunce::canonicalize(path) .unwrap_or_else(|_| dunce::simplified(path).to_path_buf()); 

canonicalize resolves every component, including the last one. When the last component was a symlink or junction, clean became the path of the target, and the target went to the Recycle Bin.

I shipped the fix in 1.0.1 three days after release and put it at the top of the changelog. It resolves only the parent folder and keeps the last component as given, so the path still names the link itself:

/// Absolute form of `path` that still names the same directory entry. /// When `path` is a symlink or junction, the result is the link itself, /// never the folder or file it points to. pub fn link_preserving_path(path: &Path) -> PathBuf { let fallback = || dunce::simplified(path).to_path_buf(); match (path.parent(), path.file_name()) { (Some(parent), Some(name)) if !parent.as_os_str().is_empty() => { match dunce::canonicalize(parent) { Ok(parent) => parent.join(name), Err(_) => fallback(), } } _ => fallback(), } } 

There was a second, quieter case. Clearing the read-only flag with set_permissions also follows links, so it could change the target. Now it's skipped for anything that is a link or reparse point, checked with symlink_metadata (which doesn't follow links) and the FILE_ATTRIBUTE_REPARSE_POINT attribute:

/// True when `path` itself is a symlink, junction or other reparse point. /// The link is not followed. pub fn is_link_or_reparse_point(path: &Path) -> bool { let Ok(meta) = std::fs::symlink_metadata(path) else { return false; }; #[cfg(windows)] { use std::os::windows::fs::MetadataExt; const FILE_ATTRIBUTE_REPARSE_POINT: u32 = 0x0000_0400; if meta.file_attributes() & FILE_ATTRIBUTE_REPARSE_POINT != 0 { return true; } } meta.file_type().is_symlink() } 

The fix came with a regression test (link_safety_test.rs) that builds links and asserts their targets survive.

Lesson: in code that deletes things, treat every "normalize the path" helper as suspicious. canonicalize, metadata() and set_permissions all follow links.

4. Finding duplicates without reading every file

Hashing every file on five drives would take forever. The duplicate finder narrows the field in phases, so most files are never opened:

  1. Size grouping. Only files that share their exact size with another file can be duplicates.
  2. Physical identity. Hard links and the same file reached twice (overlapping folders, a subst or mapped drive) share a volume and file index. They're merged, count as 0 bytes saved, and are never offered as a duplicate of themselves.
  3. Partial hash. A sample from the start and end of each file.
  4. Full BLAKE3 hash, streamed, only for files that are still candidates.

Step 2 came from another 1.0.0 bug: when two scan roots overlapped, the only copy of a file could be listed as its own duplicate. Now each physical file is listed once.

Duplicates view (sample data)

5. Making it fast

The first build was slow. Measured on a real PC with five drives:

Task First build 1.0.1
Scan all 122 cleanup rules 27 s 9 s
Large files, 5 drives 269 s 47 s
Duplicates, 5 drives 390 s 177 s

The engine runs on a rayon pool capped at 1–4 threads to keep the PC responsive during a scan, and hashing runs on its own small pool so it keeps SSDs busy without flooding slower drives.

6. Least privilege

The app runs as a normal user. Tasks that really need admin rights go through a separate small Rust binary behind the Windows UAC prompt, and that helper only accepts an allow-list of commands. One fix in 1.0.1: the helper no longer runs a diskpart script from the user's Temp folder (another program could have changed it there). The script is now passed through stdin.

7. A CLI with the same engine

The installer ships freemydisk-cli.exe, which uses the same core crate:

freemydisk-cli scan --category browser freemydisk-cli clean --dry-run freemydisk-cli duplicates --roots "D:\Photos" --min-size 5 freemydisk-cli vitals --format json 

--dry-run shows exactly what would happen, and --format json/csv makes it scriptable.

What's next

  • winget install FreeMyDisk
  • Scheduled background cleaning
  • macOS and Linux (the platform layer is already its own crate)

It's Windows-only for now, has no ads, no accounts and no telemetry. The only network request is the update check, which you can turn off, and updates are signed.

If you want to read the code, the most interesting parts are cleanup/disposal.rs, filesystem/journal.rs and storage/duplicates.rs in freemydisk-core.

I'd really like feedback on the deletion and journal code. If you've written software that deletes user data, how do you test it so you can sleep at night?

原文:https://www.a8q9.cn/en/article/building-a-windows-disk-cleaner-in-rust-that-never-deletes-blindly-d2eb26.html

相关文章