Skip to content

armgit / peel

Public Imported from GitHub
0

Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.

A size is what moving the item would free

Țugui Dragoș693728a90b88
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index d966fecf..9e142f60 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -69,8 +69,10 @@ Take the most common case, uninstalling an app. Every other page follows the sam
claim the file too (with the apps of the same maker that macOS knows outside the Applications folders), the
other copies of the app that use it (any macOS knows, wherever they are, named by their place), and, when Peel
holds it back, why (`HoldBack`).
-3. **Measure.** `FileSize` walks each folder on a thread of its own, with a time budget. A folder that doesn't
- answer in time, or that macOS won't open, has an unknown size, never zero, and every list shows it that way.
+3. **Measure.** `FileSize` walks each folder on a thread of its own, with a time budget. A size is what moving
+ the item would free: a file that shares its blocks with an APFS clone counts only what it holds alone, and one
+ with another name outside the folder counts nothing. A folder that doesn't answer in time, or that macOS won't
+ open, even a folder inside it, has an unknown size, never zero, and every list shows it that way.
4. **Plan.** The page shows every match with its reason. Only `certain` and `likely` matches that nothing else
claims are selected for the user (`Uninstallation.suggestedSelection`), and nothing is selected for an app
that would stay. The user can change the selection freely, and what they choose stays through the page's
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/FileSize.swift b/Packages/PeelCore/Sources/PeelCore/Support/FileSize.swift
index c622e50e..a6387f09 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/FileSize.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/FileSize.swift
@@ -4,6 +4,8 @@ import Synchronization
/// What one walk of a folder found.
public struct FolderContents: Sendable, Hashable {
+ /// The space removing the folder would free, which is less than it takes on disk when a file shares its blocks
+ /// with an APFS clone, or keeps another name outside it.
public let size: Int64
/// True when a version control repository was seen inside (`repositoryMarkers`). Work that is not
/// committed, or not pushed, exists nowhere else.
@@ -36,18 +38,18 @@ public enum FileSize {
/// How a scanner asks for a size. Tests hand in their own, to stand in for a folder that does not answer.
typealias Measure = @Sendable (URL) async -> Int64?
- static let measure: Measure = { await allocatedSize(of: $0) }
+ static let measure: Measure = { await reclaimableSize(of: $0) }
- /// The space a file, or everything inside a folder, takes on disk. Nil for a folder that does not answer
- /// within `budget` or that macOS will not let Peel open. No variant answers zero instead: unknown is not
+ /// The space removing a file, or a folder with everything inside it, would free. Nil for a folder that does not
+ /// answer within `budget` or that macOS will not let Peel open. No variant answers zero instead: unknown is not
/// empty, and every caller has to decide how to handle it.
@concurrent
- public static func allocatedSize(of url: URL, within budget: TimeInterval = FileSize.budget) async -> Int64? {
+ public static func reclaimableSize(of url: URL, within budget: TimeInterval = FileSize.budget) async -> Int64? {
guard let contents = await contents(of: url, within: budget), !contents.couldNotBeRead else { return nil }
return contents.size
}
- /// The walk behind `allocatedSize(of:within:)`, which also reports what it saw on the way. Nil when the
+ /// The walk behind `reclaimableSize(of:within:)`, which also reports what it saw on the way. Nil when the
/// folder does not answer within `budget`, or when the task is canceled.
///
/// A folder a file provider owns (a cloud drive, or a container such as Podcasts') can hold a directory
@@ -103,9 +105,9 @@ public enum FileSize {
private static func immediateContents(of url: URL) -> FolderContents {
ScanCount.current?.add(1)
do {
- let values = try url.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .contentModificationDateKey])
+ let values = try url.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .contentModificationDateKey, .linkCountKey, .mayShareFileContentKey])
return FolderContents(
- size: Int64(values.totalFileAllocatedSize ?? 0),
+ size: (values.linkCount ?? 1) > 1 ? 0 : freed(by: url, values),
holdsRepository: repositoryMarkers.contains(url.lastPathComponent),
holdsWallet: isWallet(url.lastPathComponent),
newestChange: values.contentModificationDate
@@ -132,6 +134,7 @@ public enum FileSize {
static func walk(_ url: URL, countingFor scan: ScanCount? = nil, unless isStopped: () -> Bool) -> FolderContents? {
let fileKeys: Set<URLResourceKey> = [
.isRegularFileKey, .totalFileAllocatedSizeKey, .linkCountKey, .fileIdentifierKey, .contentModificationDateKey,
+ .mayShareFileContentKey,
]
// Notes whether the folder, or a folder inside it, failed to open. The enumerator reports that only to the
// error handler and goes on without it, which would read as a folder holding less than it does. A folder
@@ -152,9 +155,9 @@ public enum FileSize {
var holdsRepository = repositoryMarkers.contains(url.lastPathComponent)
var holdsWallet = isWallet(url.lastPathComponent)
var newestChange: Date?
- // A file with several hard links takes its space once. Counting it once per name would overstate what
- // emptying the folder frees.
- var counted: Set<UInt64> = []
+ // A file with several names goes only once every name has gone, so it counts once, and only when all of
+ // its names are inside.
+ var severalNames: [UInt64: (seen: Int, count: Int, size: Int64)] = [:]
// Each entry gets its own autorelease pool, or what reading every name leaves behind would pile up in
// memory until the walk ends.
walking: while true {
@@ -173,9 +176,10 @@ public enum FileSize {
return .next
}
if let links = values.linkCount, links > 1, let identifier = values.fileIdentifier {
- guard counted.insert(identifier).inserted else { return .next }
+ severalNames[identifier, default: (0, links, Int64(values.totalFileAllocatedSize ?? 0))].seen += 1
+ return .next
}
- total += Int64(values.totalFileAllocatedSize ?? 0)
+ total += freed(by: file, values)
return .next
}
switch step {
@@ -184,6 +188,7 @@ public enum FileSize {
case .stopped: return nil
}
}
+ total += severalNames.values.reduce(0) { $0 + ($1.seen >= $1.count ? $1.size : 0) }
return FolderContents(
size: total,
holdsRepository: holdsRepository,
@@ -197,6 +202,12 @@ public enum FileSize {
case next, finished, stopped
}
+ /// What removing a file with one name frees: what it holds alone when it may share blocks with an APFS clone
+ /// (`ReclaimableSpace`), and every block it takes otherwise.
+ private static func freed(by file: URL, _ values: URLResourceValues) -> Int64 {
+ values.mayShareFileContent == true ? ReclaimableSpace.of(file) : Int64(values.totalFileAllocatedSize ?? 0)
+ }
+
/// Whether a folder of the walk refused to open. Set by the enumerator's error handler on the walking thread,
/// and read once the walk ends.
private final class Refused: Sendable {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/FileSizeTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/FileSizeTests.swift
index 68382ee8..f2973795 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/FileSizeTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/FileSizeTests.swift
@@ -32,13 +32,38 @@ struct FileSizeTests {
try FileManager.default.linkItem(at: original, to: folder.appending(path: name))
}
- let size = try #require(await FileSize.allocatedSize(of: folder))
- let one = try #require(await FileSize.allocatedSize(of: original))
+ let size = try #require(await FileSize.reclaimableSize(of: folder))
+ let one = ReclaimableSpace.allocated(original)
#expect(one > 0)
#expect(size == one, "four names for one file measured \(size) instead of \(one)")
}
+ /// A size is what removing the item would free. An APFS clone of a file kept elsewhere frees only what it holds
+ /// alone, and a file with another name outside the folder frees nothing, since that name keeps it. A file whose
+ /// names are all inside frees its blocks once.
+ @Test func aFolderFreesOnlyWhatGoesWithIt() async throws {
+ let directory = try TemporaryDirectory()
+ let random = { (count: Int) in Data((0..<count).map { _ in UInt8.random(in: 0...255) }) }
+ let stored = try directory.file("store/package.bin", contents: random(1_048_576))
+ let shared = try directory.file("store/shared.bin", contents: random(524_288))
+ let own = try directory.file("project/own.bin", contents: random(262_144))
+ for url in [stored, shared, own] {
+ let handle = try FileHandle(forWritingTo: url)
+ try handle.synchronize()
+ try handle.close()
+ }
+ let project = directory.url.appending(path: "project", directoryHint: .isDirectory)
+ #expect(clonefile(stored.path(percentEncoded: false), project.appending(path: "clone.bin").path(percentEncoded: false), 0) == 0)
+ try FileManager.default.linkItem(at: shared, to: project.appending(path: "linked.bin"))
+ try FileManager.default.linkItem(at: own, to: project.appending(path: "own again.bin"))
+
+ let size = try #require(await FileSize.reclaimableSize(of: project))
+
+ #expect(size >= 262_144 && size < 262_144 + 131_072, "the project frees \(size), not what only its own file holds")
+ #expect(try #require(await FileSize.reclaimableSize(of: project.appending(path: "linked.bin"))) == 0)
+ }
+
/// A walk releases what it reads as it goes, rather than holding every name until it ends. The check runs in
/// a process of its own: the footprint covers the whole process, and suites running in parallel would add
/// their own allocations to it.
@@ -86,7 +111,7 @@ struct FileSizeTests {
try directory.file("tree/a.bin", bytes: 100_000)
try directory.file("tree/b.bin", bytes: 100_000)
- #expect(try #require(await FileSize.allocatedSize(of: folder)) >= 200_000)
+ #expect(try #require(await FileSize.reclaimableSize(of: folder)) >= 200_000)
}
/// A folder macOS will not open has no known size. Read as zero, it would fall under Space's size floor and
@@ -99,7 +124,7 @@ struct FileSizeTests {
defer { try? directory.setPermissions(0o755, of: "closed") }
#expect(await FileSize.contents(of: folder)?.couldNotBeRead == true)
- #expect(await FileSize.allocatedSize(of: folder) == nil)
+ #expect(await FileSize.reclaimableSize(of: folder) == nil)
}
/// A folder inside that macOS will not open leaves the walk short: its size, and whatever wallet or repository
@@ -113,7 +138,7 @@ struct FileSizeTests {
defer { try? directory.setPermissions(0o755, of: "Vendor/Private") }
#expect(await FileSize.contents(of: folder)?.couldNotBeRead == true)
- #expect(await FileSize.allocatedSize(of: folder) == nil)
+ #expect(await FileSize.reclaimableSize(of: folder) == nil)
}
/// A folder that goes away while the walk goes on holds nothing any more, which is no reason to doubt the rest:
@@ -146,19 +171,19 @@ struct FileSizeTests {
try directory.setPermissions(0, of: "closed")
defer { try? directory.setPermissions(0o755, of: "closed") }
- #expect(await FileSize.allocatedSize(of: file) == nil)
- #expect(await FileSize.allocatedSize(of: folder) == nil)
+ #expect(await FileSize.reclaimableSize(of: file) == nil)
+ #expect(await FileSize.reclaimableSize(of: folder) == nil)
#expect(await FileSize.contents(of: file)?.couldNotBeRead == true)
- #expect(await FileSize.allocatedSize(of: directory.url.appending(path: "not there")) == 0)
+ #expect(await FileSize.reclaimableSize(of: directory.url.appending(path: "not there")) == 0)
}
- /// `allocatedSize(of:)` makes the same walk as `contents(of:)`, so both report the same size.
+ /// `reclaimableSize(of:)` makes the same walk as `contents(of:)`, so both report the same size.
@Test func measuresAFolderThatAnswers() async throws {
let directory = try TemporaryDirectory()
let folder = try directory.directory("tree")
try directory.file("tree/a.bin", bytes: 100_000)
- let measured = try #require(await FileSize.allocatedSize(of: folder))
+ let measured = try #require(await FileSize.reclaimableSize(of: folder))
#expect(measured >= 100_000)
#expect(await FileSize.contents(of: folder)?.size == measured)
}
@@ -172,7 +197,7 @@ struct FileSizeTests {
try directory.file("wide/folder\(index)/file.bin", bytes: 4_096)
}
- let measured = await FileSize.allocatedSize(of: folder, within: 0.001)
+ let measured = await FileSize.reclaimableSize(of: folder, within: 0.001)
// Either it finished, or it ran out of budget. Never a hang, and never a wrong number.
if let measured { #expect(measured >= 4_096) }
@@ -188,11 +213,11 @@ struct FileSizeTests {
try directory.file("big/folder\(index)/file.bin", bytes: 16)
}
- #expect(await FileSize.allocatedSize(of: folder, within: 0) == nil, "no budget at all, so nothing can be known yet")
+ #expect(await FileSize.reclaimableSize(of: folder, within: 0) == nil, "no budget at all, so nothing can be known yet")
var later: Int64?
for _ in 0..<200 where later == nil {
try await Task.sleep(for: .milliseconds(20))
- later = await FileSize.allocatedSize(of: folder, within: 0)
+ later = await FileSize.reclaimableSize(of: folder, within: 0)
}
#expect(await FileSize.contents(of: folder)?.size == later)
#expect(try #require(later) >= 8_192)
@@ -229,7 +254,7 @@ struct FileSizeTests {
var later: Int64?
for _ in 0..<200 where later == nil {
try await Task.sleep(for: .milliseconds(20))
- later = await FileSize.allocatedSize(of: folder, within: 0)
+ later = await FileSize.reclaimableSize(of: folder, within: 0)
}
#expect(later != nil, "the folder stayed unknown once the walk was taken")
}
@@ -245,12 +270,12 @@ struct FileSizeTests {
let task = Task { () -> Int64? in
while !Task.isCancelled { await Task.yield() }
- return await FileSize.allocatedSize(of: folder, within: 3_600)
+ return await FileSize.reclaimableSize(of: folder, within: 3_600)
}
task.cancel()
#expect(await task.value == nil, "nobody wanted it, so nothing was walked for it")
- #expect(try #require(await FileSize.allocatedSize(of: folder)) >= 100_000)
+ #expect(try #require(await FileSize.reclaimableSize(of: folder)) >= 100_000)
}
/// A walk nobody wants anymore stops at the next entry instead of reading the folder to its end.
@@ -272,8 +297,8 @@ struct FileSizeTests {
let folder = try directory.directory("tree")
try directory.file("tree/a.bin", bytes: 100_000)
- async let first = FileSize.allocatedSize(of: folder)
- async let second = FileSize.allocatedSize(of: folder)
+ async let first = FileSize.reclaimableSize(of: folder)
+ async let second = FileSize.reclaimableSize(of: folder)
let (one, two) = (await first, await second)
#expect(try #require(one) >= 100_000)
@@ -289,14 +314,14 @@ struct FileSizeTests {
try directory.file("tree/folder\(index)/file.bin", bytes: 16)
}
- #expect(await FileSize.allocatedSize(of: folder, within: 0) == nil, "no budget at all, so nothing can be known yet")
+ #expect(await FileSize.reclaimableSize(of: folder, within: 0) == nil, "no budget at all, so nothing can be known yet")
// Asked again, with a real budget: the answer comes from what is known about the folder, not from a
// second walk waited out. The same folder written with a trailing slash is the same key.
let withSlash = URL(filePath: folder.path(percentEncoded: false) + "/", directoryHint: .isDirectory)
let start = ContinuousClock.now
- _ = await FileSize.allocatedSize(of: folder, within: FileSize.budget)
- _ = await FileSize.allocatedSize(of: withSlash, within: FileSize.budget)
+ _ = await FileSize.reclaimableSize(of: folder, within: FileSize.budget)
+ _ = await FileSize.reclaimableSize(of: withSlash, within: FileSize.budget)
#expect(ContinuousClock.now - start < .seconds(2), "a question about a folder already being walked paid a budget of its own")
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PluginsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PluginsTests.swift
index d2bcc054..bcf5e0ae 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/PluginsTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/PluginsTests.swift
@@ -98,7 +98,7 @@ struct PluginsTests {
)
let plugins = await Plugins.scan(environment: environment, exclusions: .none) { url in
- url.lastPathComponent == "Slow.vst3" ? nil : await FileSize.allocatedSize(of: url, within: FileSize.budget)
+ url.lastPathComponent == "Slow.vst3" ? nil : await FileSize.reclaimableSize(of: url, within: FileSize.budget)
}
#expect(plugins.map(\.name) == ["Quick", "Slow"])
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swift
index aac45c8a..0272112b 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swift
@@ -41,7 +41,7 @@ struct SpaceInventoryTests {
try directory.file("Library/Caches/com.example.app/blob", bytes: 400_000)
let report = await SpaceInventory.scan(home: directory.url, root: directory.url, minimumSize: 100_000) { url in
- url.lastPathComponent == "Caches" ? nil : await FileSize.allocatedSize(of: url, within: FileSize.budget)
+ url.lastPathComponent == "Caches" ? nil : await FileSize.reclaimableSize(of: url, within: FileSize.budget)
}
#expect(report.items.map(\.id) == ["caches", "logs"])
diff --git a/Peel/Model/AppLibrary.swift b/Peel/Model/AppLibrary.swift
index 02a1ced6..7f523f5a 100644
--- a/Peel/Model/AppLibrary.swift
+++ b/Peel/Model/AppLibrary.swift
@@ -264,7 +264,7 @@ final class AppLibrary {
var pending = missing.makeIterator()
for _ in 0..<Self.concurrentSizeReads {
guard let app = pending.next() else { break }
- _ = group.addTaskUnlessCancelled { (app.id, await FileSize.allocatedSize(of: app.url)) }
+ _ = group.addTaskUnlessCancelled { (app.id, await FileSize.reclaimableSize(of: app.url)) }
}
while let (id, size) = await group.next() {
// A bundle that did not answer in time stays unknown (blank in the list) and is tried
@@ -274,7 +274,7 @@ final class AppLibrary {
sizes[id] = size
}
if !Task.isCancelled, let app = pending.next() {
- _ = group.addTaskUnlessCancelled { (app.id, await FileSize.allocatedSize(of: app.url)) }
+ _ = group.addTaskUnlessCancelled { (app.id, await FileSize.reclaimableSize(of: app.url)) }
}
}
}
diff --git a/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift b/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift
index e1585edf..90940c8b 100644
--- a/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift
+++ b/Peel/Views/BackgroundItems/BackgroundItemDetailView.swift
@@ -145,7 +145,7 @@ struct BackgroundItemDetailView: View {
// Read before the move: afterwards nothing is at that path to measure.
var sizes: [URL: Int64] = [:]
if let plist = item.plistURL {
- sizes[plist] = await FileSize.allocatedSize(of: plist)
+ sizes[plist] = await FileSize.reclaimableSize(of: plist)
}
await backgroundItems.perform(.moveToTrash, on: item) { result in
await history.record(result, tool: .backgroundItems, source: item.label, sizes: sizes)
diff --git a/Peel/Views/Packages/ForgetReceiptDialog.swift b/Peel/Views/Packages/ForgetReceiptDialog.swift
index 4b4c73d0..d9af68d3 100644
--- a/Peel/Views/Packages/ForgetReceiptDialog.swift
+++ b/Peel/Views/Packages/ForgetReceiptDialog.swift
@@ -20,7 +20,7 @@ struct ForgetReceiptDialog: ViewModifier {
let result = await forget(receipt) { result in
var sizes: [URL: Int64] = [:]
for item in result.trashed {
- sizes[item.originalURL] = await FileSize.allocatedSize(of: item.trashedURL)
+ sizes[item.originalURL] = await FileSize.reclaimableSize(of: item.trashedURL)
}
await history.record(result, tool: .packages, source: receipt.identifier, sizes: sizes)
}
diff --git a/Peel/Views/Settings/SavedSettingsSection.swift b/Peel/Views/Settings/SavedSettingsSection.swift
index 3ac59a0b..218f4edf 100644
--- a/Peel/Views/Settings/SavedSettingsSection.swift
+++ b/Peel/Views/Settings/SavedSettingsSection.swift
@@ -139,7 +139,7 @@ struct SavedSettingsSection: View {
workingOn = copy.id
defer { workingOn = nil }
// Measured before the move, since nothing is left at that path after it.
- let size = await FileSize.allocatedSize(of: copy.folder)
+ let size = await FileSize.reclaimableSize(of: copy.folder)
await QuitGuard.shared.run {
let result = await TrashService(exclusions: ExclusionsStore.shared.exclusions).trash([copy.folder])
if let reason = result.failures.first?.reason {
diff --git a/README.md b/README.md
index f83e8b3b..06c78f2c 100644
--- a/README.md
+++ b/README.md
@@ -289,6 +289,17 @@ your keychains, Mail, Messages, and photo libraries.
</details>
+<details>
+<summary><strong>Why does Peel show a smaller size than Finder?</strong></summary>
+
+<br>
+
+Peel shows what moving an item to the Trash would free, and Finder shows the space it takes. The two differ when
+files share their space: a copy Finder makes on an APFS disk shares its blocks with the original until one of them
+changes, and a file can have a second name somewhere else, which keeps it. Peel counts only what would really go.
+
+</details>
+
<details>
<summary><strong>Why does Peel ask for Full Disk Access?</strong></summary>