Skip to content

Rescan a single folder and move items to the Trash - #25

Merged
phalladar merged 5 commits into
phalladar:mainfrom
horus-leonardo:feat/rescan-and-trash
Nov 25, 2026
Merged

phalladar merged 5 commits into
phalladar:mainfrom
horus-leonardo:feat/rescan-and-trash

Conversation

@horus-leonardo

@horus-leonardo horus-leonardo commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

Motivation

While cleaning up a disk, every deletion meant going to Finder and then rescanning the whole drive to see the new totals. This adds the two missing pieces: rescan one folder, and move an item to the Trash from the app. Two commits.

Rescan a single folder

  • "Rescan Folder" in the sidebar's context menu scans that folder in the background with the existing FileScanner and splices the result into the tree. The row shows a spinner while it runs; the folder keeps its inode, so expanded folders stay expanded.
  • AppState.replace(_:with:) recomputes and re-sorts only the ancestors, with computeAggregates(recursing: false).
  • Folder nodes change in place, so AppState bumps a treeVersion that the sidebar rows, the inspector and the treemap layout take as a value. The sparkline now takes the values it draws instead of the node, so a row redraws when its totals change.
  • The treemap layout reads the tree off the main thread, so replace waits for it before changing the tree. Layouts now run one after another and stop early when cancelled, so there is only one to wait for.
  • One rescan or trash runs at a time (busyID), and a full scan cancels it. This keeps two changes from overlapping in the tree, e.g. a rescan of a folder bringing back a child trashed while it ran.

Move to Trash

  • "Move to Trash…" in the sidebar and treemap menus asks for confirmation, moves the item with NSWorkspace.recycle, and removes it from the tree with replace(_:with: nil), without rescanning. The menu items are disabled while a rescan or trash runs.
  • Before moving, lstat checks that the path still holds the scanned inode, so a file replaced since the scan isn't trashed by mistake. The scan root has no Move to Trash item.
  • The move is asynchronous. My first version called FileManager.trashItem on the main thread, and it froze the app for 15.8 s on a folder of 890k files, with the confirmation alert stuck on screen.

Measurements

swiftc -O, best of 20–30:

main this PR
computeAggregates, full scan (1.37M files, 137k folders) 36 ms 36 ms
update after a splice, folder at depth 6 (re-total + re-sort ancestors) 41 ms (whole tree) 0.003 ms
same, parent is a flat folder of 300k files 27 ms
freeing a 1.5M-node subtree (long names) ~45–75 ms

Limits

  • A hard link or clone whose other copy is outside the rescanned folder is counted again, since the partial scan doesn't know the inodes seen elsewhere.
  • Freeing the old subtree runs on the main thread (last row above), as a full rescan already does today.
  • If the scan includes ~/.Trash, the totals drop after a trash while the disk usage doesn't, until that folder is rescanned.
  • One item at a time; no undo inside the app (the item can be restored from the Trash).

Validation

  • swift build, swift test (new replacingASubtreeUpdatesItsAncestors, covering the selection and treemap root moving to the fresh node).
  • On macOS 27 with a local SDK 15 build: trash from the sidebar and from the treemap, cancel, rescan after adding a file, expansion and scroll kept after a change, a file replaced since the scan refused, and a real 8.5 GB folder (12.8k items) trashed in 0.4 s with the UI responsive throughout. Not yet re-run on an SDK 26 build.

🤖 Generated with Claude Code

horus-leonardo and others added 2 commits November 24, 2026 15:18
"Rescan Folder" in the sidebar's context menu scans just that folder in
the background and splices the result into the tree, so cleaning up a
folder no longer means rescanning the whole drive. The row shows a
spinner while it runs. The folder keeps its inode, so expanded folders
stay expanded.

AppState.replace(_:with:) recomputes only the ancestors, with a new
computeAggregates(recursing: false): 0.003 ms instead of 41 ms for the
whole tree on a synthetic tree of 1.37M files and 137k folders
(swiftc -O). A full scan's computeAggregates is unchanged (36 ms both).

Folder nodes change in place, so AppState bumps a treeVersion that the
sidebar rows, the inspector and the treemap layout depend on. The
sparkline now takes the values it draws instead of the node, so a row
redraws when its totals change.

The treemap layout reads the tree off the main thread, so replace()
waits for it before changing the tree. Layouts now run one after
another and stop early when cancelled, so there is only one to wait
for. Only one rescan runs at a time, and a full scan cancels it.

Limits: a hard link or clone whose other copy is outside the rescanned
folder is counted again, since the partial scan doesn't know the inodes
seen elsewhere. Freeing the old subtree runs on the main thread, about
45 ms per million nodes, as a full rescan already does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
"Move to Trash…" in the sidebar and treemap menus asks for confirmation,
moves the item with NSWorkspace.recycle and removes it from the tree
without rescanning. A folder's row shows a spinner until the move
finishes.

Before moving, lstat checks that the path still holds the inode that was
scanned, so a file replaced since the scan isn't trashed by mistake. The
scan root has no Move to Trash item. Trashing shares the one-at-a-time
rule with rescans, checked before the confirmation, and the menu items
are disabled while either runs.

The move runs asynchronously: FileManager.trashItem on the main thread
froze the app for 15.8 s on a folder of 890k files, and the confirmation
alert stayed on screen the whole time.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

@phalladar phalladar left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thank you for putting this together! Rescanning a single folder and trashing from inside the app are the two things I've wanted most while cleaning up a disk. The write-up made this a pleasure to review: the measurements, the limits section, and the care taken so the wrong item never gets trashed (the inode check, the confirmation, no trash on the scan root) all really show.

I'd love to merge this. A few changes first:

1. Don't allow Move to Trash for iCloud items
I'd rather the app never trash cloud-only content. Could you disable Move to Trash in both the sidebar and treemap menus for nodes where isDataless is true or cloudOnlyFileCount > 0? The second check covers a local folder that contains cloud-only files. Please also have FileActions.moveToTrash refuse those nodes, so the guard doesn't rely on the menu alone. While you're in there, it would be nice to wrap that lstat in withoutDatalessMaterialization, the way the scanner does.

2. Two windows share one layout task
layoutTask moved from the view's @State into AppState, but MacDirStatApp hands the same AppState to every window in the WindowGroup. With two windows open, each treemap's recomputeLayout cancels the other window's layout, so one window can be left empty after a scan finishes. I found this by reading the code and haven't reproduced it. Keeping one task per view, for example a dictionary in AppState keyed by a per-view id with replace awaiting all of them, would keep the wait without the cross-cancelling.

3. Detach the old subtree in replace
replace doesn't clear old.parent, so nodes from the replaced subtree still pass the isInSubtree(of: root) guard. busyID clears before the relayout lands, so for a moment the treemap still shows rects for the old nodes. If one of those is trashed in that window, the file goes to the Trash, but the removal is applied to the orphaned subtree and the fresh one keeps counting the file. Adding old.parent = nil after the splice, in both branches, fixes it. Here's the test I used. It fails on this branch and passes with that change:

@MainActor @Test func replacedSubtreeIsDetached() async {
    let root = FileNode(inode: 1, name: "/", isDirectory: true)
    let a = FileNode(inode: 2, name: "a", isDirectory: true)
    let video = FileNode(inode: 4, name: "x.mp4", isDirectory: false, allocatedSize: 8192, category: .video)
    root.addChild(a)
    a.addChild(video)
    root.computeAggregates()
    let state = AppState()
    state.setScanCompleted(root: root)

    let fresh = FileNode(inode: 2, name: "/a", isDirectory: true)
    fresh.addChild(FileNode(inode: 4, name: "x.mp4", isDirectory: false, allocatedSize: 8192, category: .video))
    fresh.computeAggregates()
    await state.replace(a, with: fresh)

    // A treemap rect laid out before the replace still points at the old node.
    #expect(!video.isInSubtree(of: root))
}

Smaller things, not blocking

  • If a folder is deleted in Finder before you rescan it, the rescan shows an error and the folder stays in the tree. Removing it in that case would be a nice touch.
  • The README's FAQ still describes MacDirStat as read-only. Would you mind updating those lines to mention Move to Trash?
  • You mentioned this hasn't been run on an SDK 26 build yet. When you get a chance, a quick rescan and trash pass on a CI-built binary would be great, since that's what releases ship.

Thanks again, I'm looking forward to having this in!

- Disable Move to Trash for cloud-only items and for folders holding them or
  other unscanned folders, with the reason as a menu subtitle; FileActions
  refuses them too and rechecks SF_DATALESS without materializing.
- Warn that trashing an item synced with iCloud also deletes it there.
- Keep one layout task per treemap view, so windows don't cancel each other.
- Detach the replaced subtree and ignore stale treemap rects in trash and
  drill-down.
- Drop a rescanned folder from the tree when it no longer exists.
- Give context menu items icons; update the README FAQ.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@horus-leonardo

Copy link
Copy Markdown
Contributor Author

Thanks for the careful review and the feedback. MacDirStat is exactly what I needed to manage my disk space, so congratulations on what you've built.

All three changes are in, plus the smaller ones.

1. iCloud items

  • Move to Trash is disabled in both menus for nodes with isDataless or cloudOnlyFileCount > 0, and FileActions.moveToTrash refuses them too. The lstat now runs inside withoutDatalessMaterialization and also checks SF_DATALESS, so a file evicted to iCloud after the scan is refused as well.
  • One gap showed up while testing: a cloud-only folder is counted in unscannedDirectoryCount, not in cloudOnlyFileCount, so a local folder holding one still passed. Folders with unscanned subfolders are now blocked too, since the app can't know what's inside them. This also covers unreadable folders, such as ~/Library without Full Disk Access. There's a test for it.
  • A greyed-out item with no reason looked like a bug, so the menu item now shows the reason as a subtitle: "Stored in iCloud", "Contains items stored in iCloud" or "Contains folders that weren't scanned".
  • Items that are downloaded but synced with iCloud can still be trashed, as in Finder, but show "Also deletes it from iCloud", because trashing them removes them on every device.
  • While there, I gave the context menu items SF Symbols, reusing the ones from the inspector and the toolbar. macOS menus only show them with .labelStyle(.titleAndIcon). Happy to drop this if you'd rather keep the PR narrower.

2. Two windows
layoutTasks is now a dictionary keyed by a per-view id, and replace waits until none of them changes.

3. Detaching the old subtree
old.parent = nil is in, with your test. On its own it didn't stop the scenario, though: the file went to the Trash before replace ran, so the guard there only skipped removing it from the tree. moveToTrash now checks isInSubtree(of: root) before asking for confirmation, and drillDown does the same for stale rects.

Smaller things

  • Rescanning a folder that was deleted in Finder removes it from the tree. This happens only on ENOENT, so a permission error still shows the error.
  • The README no longer says the app is read-only.
  • The menus were checked on a local build stamped as SDK 26 (vtool -set-build-version macos 15.0 26.0). I haven't run a rescan and trash pass on a CI binary yet.

Unrelated bug found while testing
On macOS 27, clicking the Inspector button after a scan hangs the app, and sometimes AppKit throws and the app aborts. It happens on main too, back to at least early November. The cause is animating the inspector while the treemap has a .contextMenu. The fix is in #27.

phalladar and others added 2 commits November 25, 2026 12:17
Conflicts in AppState (new state properties on both sides) and the tests
(new tests on both sides); kept both. The cloud-only folder test now sets
scanIssue to .cloudOnly, since main turned scanIssue into a ScanIssue enum.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
replace(_:with:) left AppState.skippedFolders holding nodes from the
replaced subtree, so the incomplete-scan banner kept counting and listing
folders that a rescan had read, or that were trashed. Rebuild the list from
the updated tree; the walk only visits branches that still have issues.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@phalladar
phalladar merged commit e6bef79 into phalladar:main Nov 25, 2026
1 check passed
@phalladar

Copy link
Copy Markdown
Owner

Merged, thank you @horus-leonardo

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants