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.

Say when an app shares most of its storage with another copy

Țugui Dragoș1651790d7fdc
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index b1e03f22..98b06e2a 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -70285,6 +70285,112 @@
}
}
},
+ "Most of this app’s files share their space on disk with another copy of it, such as one in the Trash, so moving it frees much less than its size." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Většina souborů této aplikace sdílí místo na disku s jinou její kopií, například s tou v koši, takže jejím přesunutím se uvolní mnohem méně, než kolik činí její velikost."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Die meisten Dateien dieser App teilen sich Speicherplatz mit einer anderen Kopie von ihr, etwa einer im Papierkorb, daher gibt ihr Verschieben viel weniger frei, als ihre Größe angibt."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "La mayoría de los archivos de esta app comparten almacenamiento con otra copia suya, como una que está en la papelera, así que trasladarla libera mucho menos de lo que ocupa."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "La plupart des fichiers de cette app partagent leur stockage avec une autre copie, comme celle de la corbeille, si bien que la déplacer libère bien moins d’espace que sa taille."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "La maggior parte dei file di questa app condivide lo spazio su disco con un’altra sua copia, come una nel Cestino, quindi spostarla libera molto meno della sua dimensione."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "このアプリのファイルの大部分は、ゴミ箱にあるコピーなど別のコピーとストレージを共有しているため、移動しても解放される領域はサイズよりはるかに小さくなります。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "이 앱의 파일 대부분이 휴지통에 있는 사본 등 다른 사본과 저장 공간을 공유하므로, 이동해도 확보되는 공간은 크기보다 훨씬 적습니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "De meeste bestanden van deze app delen opslag met een andere kopie ervan, zoals een in de prullenmand, dus als je hem verplaatst, komt er veel minder ruimte vrij dan zijn grootte."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Większość plików tej aplikacji współdzieli miejsce na dysku z inną jej kopią, na przykład tą w Koszu, więc przeniesienie jej zwolni znacznie mniej miejsca, niż wynosi jej wielkość."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "A maioria dos arquivos deste app compartilha armazenamento com outra cópia dele, como uma no Lixo, então movê-lo libera muito menos do que o tamanho dele."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Majoritatea fișierelor acestei aplicații partajează spațiul de stocare cu o altă copie a ei, de exemplu una din Coș, așa că mutarea ei eliberează mult mai puțin decât dimensiunea sa."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Большинство файлов этого приложения использует общее пространство на диске с другой его копией, например в Корзине, поэтому его перемещение освободит гораздо меньше места, чем указывает его размер."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "De flesta av appens filer delar lagringsutrymme med en annan kopia av den, till exempel en i papperskorgen, så om du flyttar den frigörs mycket mindre än dess storlek."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Bu uygulamanın dosyalarının çoğu, Çöp Sepeti’ndeki gibi başka bir kopyasıyla aynı saklama alanını paylaşıyor, bu yüzden onu taşımak büyüklüğünden çok daha az yer boşaltır."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Більшість файлів цієї програми спільно використовують сховище з іншою її копією, наприклад у Смітнику, тож її переміщення звільнить набагато менше місця, ніж її розмір."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "此App的大部分文件与它的另一个副本(例如废纸篓中的副本)共享储存空间,因此移动它所释放的空间远小于它的大小。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "此App的大部分檔案與它的另一個副本(例如垃圾桶中的副本)共用儲存空間,因此移動它所釋放的空間會遠少於其大小。"
+ }
+ }
+ }
+ },
"Move %@ (%@) to the Trash?" : {
"localizations" : {
"cs" : {
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift
index c7b4629d..5df37357 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift
@@ -11,6 +11,9 @@ public struct Uninstallation: Sendable {
public var isExcluded = false
/// False when the bundle did not answer in time, so `appSize` is not known rather than zero.
public var isAppMeasured = true
+ /// True when moving the bundle would free less than half the space it takes, because most of its files share
+ /// their blocks with another copy, such as one in the Trash: `appSize` is then far below the app's size.
+ public var appSharesStorage = false
/// True when the app needs administrator rights and the helper may not move it. The app is then never
/// selected: its leftovers would move first, and the app would stay without them.
public var isAppBeyondTheHelper = false
@@ -38,7 +41,8 @@ public struct Uninstallation: Sendable {
appRequiresPrivileges: FileAccess.requiresPrivilegesToRemove(app.url),
scan: LeftoverScan(leftovers: [], unreadableLocations: []),
isExcluded: true,
- isAppMeasured: await bundle.map { !$0.couldNotBeRead } ?? false
+ isAppMeasured: await bundle.map { !$0.couldNotBeRead } ?? false,
+ appSharesStorage: await bundle?.sharesMostOfItsStorage ?? false
)
}
let scanner = LeftoverScanner(environment: environment, exclusions: exclusions)
@@ -67,6 +71,7 @@ public struct Uninstallation: Sendable {
appRequiresPrivileges: appRequiresPrivileges,
scan: scan,
isAppMeasured: await bundle.map { !$0.couldNotBeRead } ?? false,
+ appSharesStorage: await bundle?.sharesMostOfItsStorage ?? false,
isAppBeyondTheHelper: appRequiresPrivileges && !app.isSystemProtected && reach.isBeyond(app.url),
isAppInTheTrash: TrashService(environment: environment).isInsideATrash(app.url)
)
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/FileSize.swift b/Packages/PeelCore/Sources/PeelCore/Support/FileSize.swift
index 9f315348..23bdd0da 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/FileSize.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/FileSize.swift
@@ -22,6 +22,13 @@ public struct FolderContents: Sendable, Hashable {
/// then counts only what was, which must never be read as the folder's size. From macOS 27, another team's
/// container is refused outright.
public let couldNotBeRead: Bool
+ /// The space the folder takes on disk, each file once whatever its names: more than `size` when files share
+ /// their blocks with APFS clones elsewhere.
+ public let taken: Int64
+
+ /// True when moving the folder would free less than half the space it takes, because most of its files share
+ /// their blocks with a copy elsewhere: what it frees is then no measure of how big it is.
+ public var sharesMostOfItsStorage: Bool { size * 2 < taken }
init(
size: Int64,
@@ -29,9 +36,11 @@ public struct FolderContents: Sendable, Hashable {
holdsWallet: Bool = false,
holdsPasswordDatabase: Bool = false,
newestChange: Date? = nil,
- couldNotBeRead: Bool = false
+ couldNotBeRead: Bool = false,
+ taken: Int64? = nil
) {
self.size = size
+ self.taken = taken ?? size
self.holdsRepository = holdsRepository
self.holdsWallet = holdsWallet
self.holdsPasswordDatabase = holdsPasswordDatabase
@@ -147,7 +156,8 @@ public enum FileSize {
holdsRepository: repositoryMarkers.contains(url.lastPathComponent),
holdsWallet: isWallet(url.lastPathComponent),
holdsPasswordDatabase: isPasswordDatabase(url.lastPathComponent),
- newestChange: values.contentModificationDate
+ newestChange: values.contentModificationDate,
+ taken: Int64(values.totalFileAllocatedSize ?? 0)
)
} catch CocoaError.fileReadNoSuchFile {
// Nothing is there, which holds nothing.
@@ -189,6 +199,7 @@ public enum FileSize {
) else { return FolderContents(size: 0, holdsRepository: false, couldNotBeRead: true) }
var total: Int64 = 0
+ var taken: Int64 = 0
// The folder's own name counts as its entries' do: a `keystore` or a `.git` measured on its own.
var holdsRepository = repositoryMarkers.contains(url.lastPathComponent)
var holdsWallet = isWallet(url.lastPathComponent)
@@ -221,6 +232,7 @@ public enum FileSize {
severalNames[identifier, default: (0, links, Int64(values.totalFileAllocatedSize ?? 0))].seen += 1
return .next
}
+ taken += Int64(values.totalFileAllocatedSize ?? 0)
total += freed(by: file, values)
return .next
}
@@ -231,13 +243,15 @@ public enum FileSize {
}
}
total += severalNames.values.reduce(0) { $0 + ($1.seen >= $1.count ? $1.size : 0) }
+ taken += severalNames.values.reduce(0) { $0 + $1.size }
return FolderContents(
size: total,
holdsRepository: holdsRepository,
holdsWallet: holdsWallet,
holdsPasswordDatabase: holdsPasswordDatabase,
newestChange: newestChange,
- couldNotBeRead: refused.happened
+ couldNotBeRead: refused.happened,
+ taken: taken
)
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/FileSizeTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/FileSizeTests.swift
index ccab75a0..3d0d3de8 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/FileSizeTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/FileSizeTests.swift
@@ -70,6 +70,30 @@ struct FileSizeTests {
#expect(try #require(await FileSize.reclaimableSize(of: project.appending(path: "linked.bin"))) == 0)
}
+ /// A folder whose files are mostly APFS clones of a copy kept elsewhere takes its full size on disk and frees
+ /// little, which is what tells a copy that shares its storage from one that is all its own.
+ @Test func saysWhenAFolderSharesMostOfItsStorage() 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("original/Example.app/payload.bin", contents: random(1_048_576))
+ let own = try directory.file("copy/Example.app/own.bin", contents: random(65_536))
+ for url in [stored, own] {
+ let handle = try FileHandle(forWritingTo: url)
+ try handle.synchronize()
+ try handle.close()
+ }
+ let copy = directory.url.appending(path: "copy/Example.app", directoryHint: .isDirectory)
+ let clone = copy.appending(path: "payload.bin").path(percentEncoded: false)
+ #expect(clonefile(stored.path(percentEncoded: false), clone, 0) == 0)
+
+ let shared = try #require(await FileSize.contents(of: copy))
+ #expect(shared.taken >= 1_048_576 + 65_536)
+ #expect(shared.sharesMostOfItsStorage)
+ let alone = try directory.file("alone/Example.app/payload.bin", contents: random(1_048_576))
+ let ownCopy = try #require(await FileSize.contents(of: alone.deletingLastPathComponent()))
+ #expect(!ownCopy.sharesMostOfItsStorage)
+ }
+
/// 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.
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift
index d5554372..7108d8bb 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift
@@ -269,6 +269,31 @@ struct UninstallationTests {
#expect(!plan.isAppMeasured, "an app that could not be read counted as measured, at zero bytes")
}
+ /// A copy of an app made as an APFS clone of another, as the Finder copies on one disk, frees almost nothing while
+ /// the other is there, though it takes its full size: the page says so rather than leave a small figure
+ /// unexplained.
+ @Test func anAppThatSharesItsStorageWithAnotherCopySaysSo() async throws {
+ let directory = try TemporaryDirectory()
+ let home = try directory.directory("home")
+ let payload = try directory.file(
+ "home/.Trash/Example.app/Contents/payload.bin",
+ contents: Data((0..<1_048_576).map { _ in UInt8.random(in: 0...255) })
+ )
+ let handle = try FileHandle(forWritingTo: payload)
+ try handle.synchronize()
+ try handle.close()
+ let bundle = try directory.directory("home/Applications/Example.app/Contents")
+ .deletingLastPathComponent()
+ let clone = bundle.appending(path: "Contents/payload.bin").path(percentEncoded: false)
+ #expect(clonefile(payload.path(percentEncoded: false), clone, 0) == 0)
+ let installed = InstalledApp(url: bundle, bundleIdentifier: "org.example.app", name: "Example")
+ let environment = SearchEnvironment(homeDirectory: home, rootDirectory: directory.url.appending(path: "root"))
+
+ let plan = await Uninstallation.prepare(installed, installedApps: [installed], environment: environment)
+
+ #expect(plan.appSharesStorage)
+ }
+
/// Watch the Trash leads to the page of an app already in the Trash, so what it left behind can go too. Its bundle
/// can't move again, so it is neither selected nor counted, on its own page or among several apps, and the app
/// does not count as one that stays, which would hold its leftovers back.
diff --git a/Peel/Model/AppLibrary.swift b/Peel/Model/AppLibrary.swift
index 2acb16f4..8e2373c5 100644
--- a/Peel/Model/AppLibrary.swift
+++ b/Peel/Model/AppLibrary.swift
@@ -105,6 +105,10 @@ final class AppLibrary {
didSet { sizesRevision += 1 }
}
+ /// The apps whose bundle shares most of its storage with another copy (`FolderContents.sharesMostOfItsStorage`),
+ /// so its size is far below the space it takes.
+ private(set) var sharingStorage: Set<InstalledApp.ID> = []
+
/// Incremented when a size arrives. Only the size sort depends on it, so other sorts keep their cached list.
private(set) var sizesRevision = 0
private(set) var lastUpdateChecks: [InstalledApp.ID: Date] = [:]
@@ -296,6 +300,7 @@ final class AppLibrary {
let keeps = { (id: InstalledApp.ID) in present.contains(id) && !stale.contains(id) }
sizes = sizes.filter { keeps($0.key) }
unmeasured = unmeasured.filter(keeps)
+ sharingStorage = sharingStorage.filter(keeps)
updateStatuses = updateStatuses.filter { keeps($0.key) }
lastUpdateChecks = lastUpdateChecks.filter { keeps($0.key) }
selection.formIntersection(present)
@@ -342,27 +347,33 @@ final class AppLibrary {
private func measure(_ missing: [InstalledApp]) async {
guard !missing.isEmpty else { return }
- let measured = Dictionary(missing.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
- await withTaskGroup(of: (InstalledApp.ID, Int64?).self) { group in
+ let asked = Dictionary(missing.map { ($0.id, $0) }, uniquingKeysWith: { first, _ in first })
+ await withTaskGroup(of: (InstalledApp.ID, FolderContents?).self) { group in
var pending = missing.makeIterator()
for _ in 0..<Self.concurrentSizeReads {
guard let app = pending.next() else { break }
- _ = group.addTaskUnlessCancelled { (app.id, await FileSize.reclaimableSize(of: app.url)) }
+ _ = group.addTaskUnlessCancelled { (app.id, await FileSize.contents(of: app.url)) }
}
- while let (id, size) = await group.next() {
+ while let (id, contents) = await group.next() {
+ let measured = contents.flatMap { $0.couldNotBeRead ? nil : $0 }
// A walk given up because the list changed says nothing about the bundle, and a bundle replaced
// while it was walked is another build, so neither answer is kept.
- if !Task.isCancelled, let app = measured[id],
+ if !Task.isCancelled, let app = asked[id],
apps.contains(where: { $0.id == id && $0.isTheSameBuild(as: app) }) {
- if let size {
- sizes[id] = size
+ if let measured {
+ sizes[id] = measured.size
unmeasured.remove(id)
+ if measured.sharesMostOfItsStorage {
+ sharingStorage.insert(id)
+ } else {
+ sharingStorage.remove(id)
+ }
} else {
unmeasured.insert(id)
}
}
if !Task.isCancelled, let app = pending.next() {
- _ = group.addTaskUnlessCancelled { (app.id, await FileSize.reclaimableSize(of: app.url)) }
+ _ = group.addTaskUnlessCancelled { (app.id, await FileSize.contents(of: app.url)) }
}
}
}
diff --git a/Peel/Model/RemovalPlan.swift b/Peel/Model/RemovalPlan.swift
index 8a61c929..2caa26c8 100644
--- a/Peel/Model/RemovalPlan.swift
+++ b/Peel/Model/RemovalPlan.swift
@@ -51,6 +51,10 @@ final class RemovalPlan {
uninstallation?.isAppMeasured ?? true
}
+ var appSharesStorage: Bool {
+ uninstallation?.appSharesStorage ?? false
+ }
+
var appRequiresPrivileges: Bool {
uninstallation?.appRequiresPrivileges ?? false
}
diff --git a/Peel/Views/AppHeader.swift b/Peel/Views/AppHeader.swift
index 78fd9cb8..8f402101 100644
--- a/Peel/Views/AppHeader.swift
+++ b/Peel/Views/AppHeader.swift
@@ -13,6 +13,8 @@ struct AppHeader<Actions: View>: View {
var waitingVersion: String?
var lastCheck: Date?
var total: SizeTotal?
+ /// True when the app frees much less than its size, because most of it is shared with another copy.
+ var sharesStorage = false
@ViewBuilder var actions: Actions
var body: some View {
@@ -71,6 +73,13 @@ struct AppHeader<Actions: View>: View {
detail: Text("Built for Intel processors only. On Apple silicon it needs Rosetta.")
)
}
+ if sharesStorage {
+ NoteBadge(
+ title: Text("Shares storage"), systemImage: "link", tint: .secondary,
+ name: String(localized: "Shares storage"),
+ detail: Text("Most of this app’s files share their space on disk with another copy of it, such as one in the Trash, so moving it frees much less than its size.")
+ )
+ }
if app.isSystemProtected {
NoteBadge(
title: Text("Protected by macOS"), systemImage: "lock", tint: .secondary,
diff --git a/Peel/Views/AppList.swift b/Peel/Views/AppList.swift
index db8572fd..0b7eeb60 100644
--- a/Peel/Views/AppList.swift
+++ b/Peel/Views/AppList.swift
@@ -99,6 +99,7 @@ struct AppList: View {
updateStatus: library.updateStatuses[app.id],
size: library.sizes[app.id],
isUnmeasured: library.unmeasured.contains(app.id),
+ sharesStorage: library.sharingStorage.contains(app.id),
teamChange: library.teamChanges[app.bundleIdentifier],
sort: library.sort,
hasUpdate: library.hasUpdate(app),
@@ -230,6 +231,8 @@ private struct AppRow: View {
/// True when the bundle could not be measured, so the size reads "Unknown" rather than staying blank as it does
/// while it is measured.
let isUnmeasured: Bool
+ /// True when the size is far below the space the app takes, because most of it is shared with another copy.
+ let sharesStorage: Bool
let teamChange: TeamRegistry.Change?
let sort: AppSort
let hasUpdate: Bool
@@ -265,6 +268,13 @@ private struct AppRow: View {
.help(Text(.excludedApp))
.accessibilityLabel(Text(.excludedApp))
}
+ if sharesStorage {
+ let words = Text("Most of this app’s files share their space on disk with another copy of it, such as one in the Trash, so moving it frees much less than its size.")
+ Image(systemName: "link")
+ .foregroundStyle(.secondary)
+ .help(words)
+ .accessibilityLabel(Text("Shares storage"))
+ }
// Always drawn, even before the sizes arrive, so nothing shifts when they do.
Text(size?.byteCount ?? (isUnmeasured ? String(localized: "Unknown") : ""))
.font(.subheadline)
diff --git a/Peel/Views/AppPageHeader.swift b/Peel/Views/AppPageHeader.swift
index 3b0c0743..891327b9 100644
--- a/Peel/Views/AppPageHeader.swift
+++ b/Peel/Views/AppPageHeader.swift
@@ -21,7 +21,8 @@ struct AppPageHeader: View {
isCheckingForUpdates: library.appsCheckingForUpdates.contains(plan.app.id),
waitingVersion: waitingVersion == nil ? nil : library.updateStatuses[plan.app.id]?.displayVersion,
lastCheck: library.lastUpdateChecks[plan.app.id],
- total: plan.total
+ total: plan.total,
+ sharesStorage: plan.appSharesStorage
) {
appActions
}