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.

Keep an excluded app's own folders out of every page

Țugui Dragoș590a8cef9cd5
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 6d4f1aab..5693563c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -41,7 +41,7 @@ macOS 26 supports.
- Selects what Peel recommends, all it may, or nothing, on one list or on every page of a tool at once, leaves
to your own click what it holds back for what it may hold, and asks first before it selects anything else Peel
doesn't recommend.
-- Leaves alone the files, folders, and apps you exclude.
+- Leaves alone the files, folders, and apps you exclude, and the folders named with an excluded app's identifier.
- Starts the sidebar with the tools most people use, and keeps each tool you turn on or off in Settings.
- Opens on Home: this Mac's chip, memory, and macOS version, how much of its disk is free, what Peel has moved to
the Trash so far, and which permissions are on.
diff --git a/GUIDE.md b/GUIDE.md
index 30b12896..4a2afe48 100644
--- a/GUIDE.md
+++ b/GUIDE.md
@@ -179,8 +179,8 @@ lines to add. [TERMINAL.md](TERMINAL.md) shows every theme and every setting, wi
- **History:** everything Peel moved to the Trash, ready to put back, from the app and from Terminal alike, and
what it was asked to move and wouldn't, with the reason for each item.
- **Exclusions:** files, folders, and apps Peel must never touch. An excluded app still appears in Applications, but
- Peel won't offer to remove or reset it; the Storage pages, Plug-ins, and Package Receipts go by files and folders, so
- to keep an app's files there, exclude its folders too.
+ Peel won't offer to remove or reset it, and leaves out of every page the folders named with its identifier, such as
+ its caches; to keep its other files, such as plug-ins or a folder named after it, exclude them too.
## Work your way
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index 8f2dda86..378ed8b7 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -37025,108 +37025,108 @@
}
}
},
- "Excluded apps still appear in Applications, but Peel won’t offer to remove or reset them. The Storage pages, Plug-ins, and Package Receipts go by files and folders only, so to protect an app’s files there, exclude its folders above as well." : {
+ "Excluded apps still appear in Applications, but Peel won’t offer to remove or reset them. A folder named with an excluded app’s identifier, such as its caches or its container, is left out of every page and never moved. The app’s other files, such as plug-ins or a folder named after it, go by files and folders only, so to protect them, exclude them above as well." : {
"localizations" : {
"cs" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Vyloučené aplikace se dál zobrazují na stránce Všechny aplikace, ale Peel nenabídne jejich odstranění ani resetování. Stránky ve skupině Úložiště i stránky Plug-iny a Záznamy o instalaci se řídí jen soubory a složkami, takže chcete-li tam chránit soubory aplikace, vylučte výše také její složky."
+ "value" : "Vyloučené aplikace se dál zobrazují na stránce Všechny aplikace, ale Peel nenabídne jejich odstranění ani resetování. Složka pojmenovaná podle identifikátoru vyloučené aplikace, například její mezipaměti nebo kontejner, se nezobrazí na žádné stránce a Peel ji nikdy nepřesune. U ostatních souborů aplikace, například plug-inů nebo složky pojmenované podle jejího názvu, se Peel řídí jen soubory a složkami, takže chcete-li je chránit, vylučte je výše také."
}
},
"de" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Ausgeschlossene Apps erscheinen weiterhin in „Programme“, aber Peel bietet nicht an, sie zu entfernen oder zurückzusetzen. Die Seiten der Gruppe „Speicher“ sowie die Seiten „Plug-ins“ und „Paketquittungen“ richten sich nur nach Dateien und Ordnern. Um die Dateien einer App dort zu schützen, schließe also auch ihre Ordner oben aus."
+ "value" : "Ausgeschlossene Apps erscheinen weiterhin in „Programme“, aber Peel bietet nicht an, sie zu entfernen oder zurückzusetzen. Ein Ordner, der nach der ID einer ausgeschlossenen App benannt ist, etwa ihre Caches oder ihr Container, erscheint auf keiner Seite und wird nie verschoben. Bei den übrigen Dateien der App, etwa Plug-ins oder einem nach ihr benannten Ordner, richtet sich Peel nur nach Dateien und Ordnern. Um sie zu schützen, schließe also auch sie oben aus."
}
},
"es" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Las apps excluidas siguen apareciendo en Aplicaciones, pero Peel no ofrecerá eliminarlas ni restablecerlas. Las páginas del grupo Almacenamiento, además de Módulos y Recibos de paquetes, solo se fijan en archivos y carpetas, así que, para proteger ahí los archivos de una app, excluye también sus carpetas más arriba."
+ "value" : "Las apps excluidas siguen apareciendo en Aplicaciones, pero Peel no ofrecerá eliminarlas ni restablecerlas. Una carpeta que lleva en su nombre el identificador de una app excluida, como sus cachés o su contenedor, queda fuera de todas las páginas y nunca va a la papelera. Los demás archivos de la app, como los módulos o una carpeta con su nombre, solo se rigen por archivos y carpetas, así que, para protegerlos, exclúyelos también más arriba."
}
},
"fr" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Les apps exclues apparaissent toujours dans Applications, mais Peel ne propose pas de les supprimer ni de les réinitialiser. Les pages du groupe Stockage, ainsi que Modules et Reçus de paquets, ne tiennent compte que des fichiers et des dossiers : pour y protéger les fichiers d’une app, excluez aussi ses dossiers ci-dessus."
+ "value" : "Les apps exclues apparaissent toujours dans Applications, mais Peel ne propose pas de les supprimer ni de les réinitialiser. Un dossier nommé d’après l’identifiant d’une app exclue, comme ses caches ou son conteneur, n’apparaît sur aucune page et n’est jamais déplacé. Pour les autres fichiers de l’app, comme ses modules ou un dossier qui porte son nom, seuls comptent les fichiers et les dossiers exclus : pour les protéger, excluez-les aussi ci-dessus."
}
},
"it" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Le app escluse compaiono ancora in Applicazioni, ma Peel non propone di rimuoverle o di reimpostarle. Plugin, “Ricevute dei pacchetti” e le pagine del gruppo Archiviazione si basano solo su file e cartelle, quindi per proteggere lì i file di un’app escludi anche le sue cartelle qui sopra."
+ "value" : "Le app escluse compaiono ancora in Applicazioni, ma Peel non propone di rimuoverle o di reimpostarle. Una cartella che porta nel nome l’identificatore di un’app esclusa, come le sue cache o il suo contenitore, non compare in nessuna pagina e non viene mai spostata. Gli altri file dell’app, come i plugin o una cartella con il suo nome, contano solo come file e cartelle, quindi per proteggerli escludili anche qui sopra."
}
},
"ja" : {
"stringUnit" : {
"state" : "translated",
- "value" : "除外したアプリも“アプリケーション”には表示されますが、Peelがそれらのゴミ箱への移動やリセットを提案することはありません。“ストレージ”のページ、“プラグイン”、“パッケージレシート”はファイルとフォルダだけを基準にするため、そこでアプリのファイルを保護するには、上でそのアプリのフォルダも除外してください。"
+ "value" : "除外したアプリも“アプリケーション”には表示されますが、Peelがそれらのゴミ箱への移動やリセットを提案することはありません。キャッシュやコンテナなど、除外したアプリの識別子が名前に含まれるフォルダは、どのページにも表示されず、Peelがゴミ箱に入れることも決してありません。プラグインやアプリの名前が付いたフォルダなど、アプリのその他のファイルは、ファイルとフォルダの除外だけが基準になるため、それらを保護するには、上でそれらも除外してください。"
}
},
"ko" : {
"stringUnit" : {
"state" : "translated",
- "value" : "제외된 앱도 응용 프로그램에는 계속 표시되지만, Peel은 해당 앱의 제거나 재설정을 제안하지 않습니다. 저장 공간 페이지, 플러그인, 패키지 수신 정보는 파일과 폴더만을 기준으로 하므로, 그곳에서 앱의 파일을 보호하려면 위에서 해당 앱의 폴더도 제외하십시오."
+ "value" : "제외된 앱도 응용 프로그램에는 계속 표시되지만, Peel은 해당 앱의 제거나 재설정을 제안하지 않습니다. 캐시나 컨테이너처럼 제외된 앱의 식별자로 이름이 지정된 폴더는 어떤 페이지에도 표시되지 않으며 절대 이동되지 않습니다. 플러그인이나 앱 이름을 딴 폴더 등 앱의 다른 파일은 파일과 폴더만을 기준으로 판단되므로, 이를 보호하려면 위에서 해당 항목도 제외하십시오."
}
},
"nl" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Uitgesloten apps verschijnen nog steeds in 'Alle apps', maar Peel biedt niet aan om ze te verwijderen of opnieuw in te stellen. Op de pagina's onder 'Opslag', op 'Plug-ins' en op 'Installatiebewijzen' kijkt Peel alleen naar bestanden en mappen, dus om de bestanden van een app daar te beschermen, sluit je hierboven ook de mappen van die app uit."
+ "value" : "Uitgesloten apps verschijnen nog steeds in 'Alle apps', maar Peel biedt niet aan om ze te verwijderen of opnieuw in te stellen. Een map met de ID van een uitgesloten app in de naam, zoals de caches of de container van die app, wordt op geen enkele pagina getoond en nooit verplaatst. Bij de andere bestanden van de app, zoals plug-ins of een map met de naam van de app, kijkt Peel alleen naar bestanden en mappen, dus om die te beschermen, sluit je ze hierboven ook uit."
}
},
"pl" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Wykluczone aplikacje nadal są widoczne na stronie Wszystkie aplikacje, ale Peel nie zaproponuje ich odinstalowania ani wyzerowania. Strony z grupy Pamięć masowa, a także strony Wtyczki i Potwierdzenia instalacji, uwzględniają tylko pliki i foldery, więc aby chronić tam pliki aplikacji, wyklucz powyżej także jej foldery."
+ "value" : "Wykluczone aplikacje nadal są widoczne na stronie Wszystkie aplikacje, ale Peel nie zaproponuje ich odinstalowania ani wyzerowania. Folder nazwany identyfikatorem wykluczonej aplikacji, taki jak folder jej pamięci podręcznej lub jej kontener, jest pomijany na każdej stronie i nigdy nie jest przenoszony. Pozostałe pliki aplikacji, takie jak wtyczki czy folder o jej nazwie, są traktowane tylko jako pliki i foldery, więc aby je chronić, wyklucz je także powyżej."
}
},
"pt" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Os apps excluídos continuam aparecendo em Aplicativos, mas o Peel não oferece removê-los nem redefini-los. As páginas do grupo Armazenamento, além de Plug-ins e Recibos de Pacotes, consideram apenas arquivos e pastas, então, para proteger os arquivos de um app nessas páginas, adicione também as pastas dele à lista acima."
+ "value" : "Os apps excluídos continuam aparecendo em Aplicativos, mas o Peel não oferece removê-los nem redefini-los. Uma pasta cujo nome é o identificador de um app excluído, como a pasta de caches ou o contêiner dele, fica de fora de todas as páginas e nunca é movida. Os demais arquivos do app, como plug-ins ou uma pasta com o nome dele, contam apenas como arquivos e pastas, então, para protegê-los, adicione-os também à lista acima."
}
},
"ro" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Aplicațiile excluse apar în continuare în pagina Toate aplicațiile, dar Peel nu va propune să le elimine sau să le reseteze. Paginile din grupul Stocare, precum și paginile Plug-inuri și Recipise de pachete, țin cont doar de fișiere și dosare, așa că, pentru a proteja acolo fișierele unei aplicații, excludeți mai sus și dosarele acesteia."
+ "value" : "Aplicațiile excluse apar în continuare în pagina Toate aplicațiile, dar Peel nu va propune să le elimine sau să le reseteze. Un dosar denumit după identificatorul unei aplicații excluse, cum ar fi memoriile tampon sau containerul acesteia, nu apare în nicio pagină și nu este mutat niciodată. Celelalte fișiere ale aplicației, cum ar fi plug-inurile sau un dosar care îi poartă numele, se exclud doar ca fișiere și dosare, așa că, pentru a le proteja, excludeți‑le și pe ele mai sus."
}
},
"ru" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Исключенные приложения по-прежнему отображаются в разделе «Программы», но Peel не предложит их удалить или сбросить. Страницы группы «Хранилище», а также «Плагины» и «Квитанции пакетов» учитывают только файлы и папки, поэтому, чтобы защитить там файлы приложения, исключите выше и его папки."
+ "value" : "Исключенные приложения по-прежнему отображаются в разделе «Программы», но Peel не предложит их удалить или сбросить. Папка, названная по идентификатору исключенного приложения, например папка с его кэшами или его контейнер, не показывается ни на одной странице и никогда не перемещается. Остальные файлы приложения, например плагины или папка, названная его именем, учитываются только как файлы и папки, поэтому, чтобы защитить и их, исключите их выше."
}
},
"sv" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Undantagna appar visas fortfarande på sidan Alla appar, men Peel erbjuder sig inte att ta bort eller nollställa dem. Sidorna under Lagring, liksom Insticksfiler och Paketkvitton, utgår bara från filer och mappar, så om du vill skydda en apps filer där måste du också undanta dess mappar ovan."
+ "value" : "Undantagna appar visas fortfarande på sidan Alla appar, men Peel erbjuder sig inte att ta bort eller nollställa dem. En mapp som har namn efter en undantagen apps identifierare, till exempel dess cachar eller dess behållare, visas inte på någon sida och flyttas aldrig. Appens övriga filer, till exempel insticksfiler eller en mapp som har appens namn, behandlas bara som filer och mappar, så om du vill skydda dem måste du också undanta dem ovan."
}
},
"tr" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Hariç tutulan uygulamalar Tüm Uygulamalar’da görünmeye devam eder, ancak Peel onları kaldırmayı veya sıfırlamayı önermez. Saklama Alanı sayfaları, Yazılım Ekleri ve Paket Makbuzları yalnızca dosya ve klasörlere bakar; bu yüzden bir uygulamanın dosyalarını orada da korumak için onun klasörlerini yukarıda ayrıca hariç tutun."
+ "value" : "Hariç tutulan uygulamalar Tüm Uygulamalar’da görünmeye devam eder, ancak Peel onları kaldırmayı veya sıfırlamayı önermez. Hariç tutulan bir uygulamanın tanıtıcısıyla adlandırılmış bir klasör, örneğin önbellekleri veya kapsayıcısı, hiçbir sayfada yer almaz ve asla taşınmaz. Uygulamanın yazılım ekleri veya adını taşıyan bir klasör gibi diğer dosyaları yalnızca dosya ve klasör olarak ele alınır; bu yüzden onları korumak için yukarıda ayrıca hariç tutun."
}
},
"uk" : {
"stringUnit" : {
"state" : "translated",
- "value" : "Програми з винятків і далі показуються в розділі «Усі програми», але Peel не пропонуватиме їх вилучати чи скидати. Сторінки групи «Сховище», а також «Плагіни» і «Квитанції пакетів» зважають лише на файли й папки, тож, щоб захистити там файли програми, додайте до винятків вище також її папки."
+ "value" : "Програми з винятків і далі показуються в розділі «Усі програми», але Peel не пропонуватиме їх вилучати чи скидати. Папка з ідентифікатором такої програми в назві, як-от її кеші чи контейнер, не показується на жодній сторінці й ніколи не переміщується. На інші файли програми, як-от плагіни чи папку з її назвою, поширюються лише винятки файлів і папок, тож, щоб захистити їх, додайте до винятків вище також їх."
}
},
"zh-Hans" : {
"stringUnit" : {
"state" : "translated",
- "value" : "已排除的App仍会显示在“应用程序”中,但Peel不会提供移除或重置它们的选项。“储存空间”下的各个页面、“插件”和“软件包回执”只按文件和文件夹判断,因此若要在那些页面中保护某个App的文件,请同时在上方排除它的文件夹。"
+ "value" : "已排除的App仍会显示在“应用程序”中,但Peel不会提供移除或重置它们的选项。以已排除App的标识符命名的文件夹(例如它的缓存或容器)不会出现在任何页面中,也绝不会被移走。该App的其他文件(例如插件或以它的名称命名的文件夹)只按文件和文件夹判断,因此若要保护它们,请同时在上方排除它们。"
}
},
"zh-Hant" : {
"stringUnit" : {
"state" : "translated",
- "value" : "已排除的App仍會出現在「應用程式」中,但Peel不會提供移除或重置它們的選項。「儲存空間」中的頁面、「外掛模組」和「套件收據」只依據檔案和檔案夾判斷,因此若要在那裡保護App的檔案,也請在上方排除它的檔案夾。"
+ "value" : "已排除的App仍會出現在「應用程式」中,但Peel不會提供移除或重置它們的選項。以已排除App的識別碼命名的檔案夾(例如它的快取或容器),任何頁面都不會列出,Peel也絕不會移動。App的其他檔案(例如外掛模組,或以App名稱命名的檔案夾)只依據檔案和檔案夾來排除,因此若要保護它們,也請在上方將它們排除。"
}
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Duplicates/Duplicates.swift b/Packages/PeelCore/Sources/PeelCore/Duplicates/Duplicates.swift
index cc159974..2529013c 100644
--- a/Packages/PeelCore/Sources/PeelCore/Duplicates/Duplicates.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Duplicates/Duplicates.swift
@@ -138,7 +138,7 @@ public struct DuplicateScan: Sendable {
/// since each check resolves links on disk and a scan can list a hundred thousand copies.
@concurrent
public func excluded(by exclusions: Exclusions) async -> Set<URL> {
- guard !exclusions.paths.isEmpty else { return [] }
+ guard !exclusions.isEmpty else { return [] }
let files = groups.flatMap(\.files).map(\.url).filter(exclusions.excludes)
let folders = folderGroups.flatMap(\.folders).map(\.url).filter {
exclusions.excludes($0) || exclusions.holds($0)
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGuard.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGuard.swift
index 50bea59f..53a0648b 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGuard.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGuard.swift
@@ -179,6 +179,9 @@ struct RemovalGuard: Sendable {
// Last, since each reads what is a level or two inside the folder, and a name refused above needs none of it.
for name in names {
+ guard exclusions.appFolders(inside: URL(filePath: name, directoryHint: .isDirectory)).isEmpty else {
+ return .excluded
+ }
// An uninstall lists a whole container, and the documents inside would go with it. Space lists a
// vendor's whole cache folder, and work kept only there (an IDE's local history) would go with it.
guard !ProtectedData.holdsAContainersDocuments(name) else { return .holdsDocuments }
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swift b/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swift
index ab9d58fb..1306287a 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swift
@@ -7,11 +7,15 @@ public struct Exclusions: Sendable, Codable, Hashable {
didSet { spellings = Self.spellings(of: paths) }
}
- public var bundleIdentifiers: Set<String>
+ public var bundleIdentifiers: Set<String> {
+ didSet { appFolderNames = Self.folderNames(of: bundleIdentifiers) }
+ }
/// Every way each excluded path can be written, worked out whenever `paths` changes. A scan asks about
/// every file it meets, and working the spellings out again for each one would cost several `lstat` calls.
/// Each is kept as its names, since paths are compared name by name.
private var spellings: [[String]] = []
+ /// The excluded apps' identifiers, lowercase: what sits in a folder of that name is excluded with the app.
+ private var appFolderNames: Set<String> = []
/// True when the saved list exists but could not be read, so what the user excluded is unknown. Nothing is
/// moved while this is true.
public private(set) var isUnreadable = false
@@ -39,7 +43,7 @@ public struct Exclusions: Sendable, Codable, Hashable {
case bundleIdentifiers
}
- /// Compares what is excluded. `spellings` is left out, since it is worked out from `paths`.
+ /// Compares what is excluded. `spellings` and `appFolderNames` are left out, since they are worked out.
public static func == (one: Exclusions, other: Exclusions) -> Bool {
one.paths == other.paths && one.bundleIdentifiers == other.bundleIdentifiers
&& one.isUnreadable == other.isUnreadable
@@ -71,6 +75,7 @@ public struct Exclusions: Sendable, Codable, Hashable {
)
self.bundleIdentifiers = bundleIdentifiers
spellings = Self.spellings(of: self.paths)
+ appFolderNames = Self.folderNames(of: bundleIdentifiers)
}
public init(from decoder: any Decoder) throws {
@@ -109,7 +114,7 @@ public struct Exclusions: Sendable, Codable, Hashable {
/// combining mark after it are one `Character`, so a name beginning with the mark would never read as
/// inside its folder to a comparison of characters.
public func excludes(_ url: URL) -> Bool {
- guard !spellings.isEmpty else { return false }
+ guard !spellings.isEmpty || !appFolderNames.isEmpty else { return false }
return excludes(spellings: Self.spellings(of: url))
}
@@ -117,14 +122,14 @@ public struct Exclusions: Sendable, Codable, Hashable {
func excludes(spellings asked: Set<String>) -> Bool {
asked.contains { path in
let names = PathComponents.of(path)
- return spellings.contains { names.starts(with: $0) }
+ return spellings.contains { names.starts(with: $0) } || names.contains(where: appFolderNames.contains)
}
}
/// True when something excluded sits inside `url`, so moving `url` would take it along.
public func holds(_ url: URL) -> Bool {
- guard !spellings.isEmpty else { return false }
- return holds(spellings: Self.spellings(of: url))
+ guard !spellings.isEmpty || !appFolderNames.isEmpty else { return false }
+ return holds(spellings: Self.spellings(of: url)) || !appFolders(inside: url).isEmpty
}
/// `holds(_:)` for a path whose spellings are already worked out.
@@ -135,6 +140,19 @@ public struct Exclusions: Sendable, Codable, Hashable {
}
}
+ /// The excluded apps' folders a level or two inside `folder`. It reads the disk.
+ func appFolders(inside folder: URL) -> [URL] {
+ guard !appFolderNames.isEmpty else { return [] }
+ let list = { (folder: URL) in
+ (try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)) ?? []
+ }
+ return list(folder).flatMap { child in
+ if appFolderNames.contains(child.lastPathComponent.lowercased()) { return [child] }
+ guard child.isRealFolder else { return [] }
+ return list(child).filter { appFolderNames.contains($0.lastPathComponent.lowercased()) }
+ }
+ }
+
/// The excluded places inside `url`, leaving out one inside another, so what they hold is counted once.
public func places(inside url: URL) -> [URL] {
let asked = Self.spellings(of: url).map(PathComponents.of)
@@ -142,7 +160,7 @@ public struct Exclusions: Sendable, Codable, Hashable {
Self.spellings(of: path).map(PathComponents.of).contains { names in
asked.contains { names.count > $0.count && names.starts(with: $0) }
}
- }
+ } + appFolders(inside: url)
return inside.filter { place in !inside.contains { $0 != place && Exclusions(paths: [$0]).excludes(place) } }
}
@@ -158,14 +176,20 @@ public struct Exclusions: Sendable, Codable, Hashable {
paths.flatMap { spellings(of: $0) }.map(PathComponents.of).filter { !$0.isEmpty }
}
+ /// Lowercase, as the disk compares names. A single word is too common to say whose a folder is.
+ private static func folderNames(of identifiers: Set<String>) -> Set<String> {
+ Set(identifiers.filter(Identifier.isValid).map { $0.lowercased() })
+ }
+
/// What on the list excludes an item: the app's identifier and the entries for the item itself, which taking off
- /// the list includes it again, and the excluded folders around it, which hold other things too.
+ /// the list includes it again, and the excluded folders and apps' folders around it, which hold other things too.
public struct Reasons: Sendable, Hashable {
public let identifier: String?
public let paths: [URL]
public let folders: [URL]
+ public let apps: [String]
- public var isEmpty: Bool { identifier == nil && paths.isEmpty && folders.isEmpty }
+ public var isEmpty: Bool { identifier == nil && paths.isEmpty && folders.isEmpty && apps.isEmpty }
}
/// `app` is the identifier of the app the item is, when it is one.
@@ -179,6 +203,10 @@ public struct Exclusions: Sendable, Codable, Hashable {
Self.spellings(of: entry).map(PathComponents.of).contains { folder in
asked.contains { $0.count > folder.count && $0.starts(with: folder) }
}
+ },
+ apps: bundleIdentifiers.sorted().filter { identifier in
+ let name = identifier.lowercased()
+ return appFolderNames.contains(name) && asked.contains { $0.contains(name) }
}
)
}
@@ -223,7 +251,7 @@ public struct Exclusions: Sendable, Codable, Hashable {
}
public func keeping<T>(_ items: [T], url: (T) -> URL) -> [T] {
- guard !paths.isEmpty else { return items }
+ guard !isEmpty else { return items }
return items.filter { !excludes(url($0)) }
}
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift
index d3e05f48..a1fe6998 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift
@@ -167,6 +167,19 @@ struct DuplicateFinderTests {
#expect(await result.excluded(by: .none).isEmpty)
}
+ @Test func whatAnAppExcludedAfterTheScanKeepsInItsOwnFolderLeavesIt() async throws {
+ let directory = try TemporaryDirectory()
+ let photo = randomData(count: 4_000)
+ try directory.file("home/Pictures/photo.jpg", contents: photo)
+ try directory.file("home/Documents/org.example.Notes/photo.jpg", contents: photo)
+ let result = try await scan(directory)
+ let kept = try #require(
+ result.groups.flatMap(\.files).first { $0.url.path(percentEncoded: false).contains("org.example.Notes") }
+ ).url
+
+ #expect(await result.excluded(by: Exclusions(bundleIdentifiers: ["org.example.Notes"])) == [kept])
+ }
+
/// A folder locked by ordinary file permissions is not one Full Disk Access would open, so the scan does not
/// ask for it. Only macOS's privacy refusal does, and a test cannot stage that.
@Test(.permissionsHold) func aFolderLockedByPermissionsDoesNotAskForFullDiskAccess() async throws {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swift
index 4d987a7b..877e8129 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/ExclusionsTests.swift
@@ -9,13 +9,13 @@ struct ExclusionsTests {
let project = folder.appending(path: "Site", directoryHint: .isDirectory)
let byIdentifier = Exclusions(bundleIdentifiers: ["org.example.app"]).reasons(excluding: app, app: "org.example.app")
- #expect(byIdentifier == Exclusions.Reasons(identifier: "org.example.app", paths: [], folders: []))
+ #expect(byIdentifier == Exclusions.Reasons(identifier: "org.example.app", paths: [], folders: [], apps: []))
let byPath = Exclusions(paths: [URL(filePath: "/Applications/Example.app/")]).reasons(excluding: app, app: nil)
#expect(byPath.paths.count == 1 && byPath.folders.isEmpty && byPath.identifier == nil)
let byFolder = Exclusions(paths: [folder]).reasons(excluding: project, app: nil)
- #expect(byFolder == Exclusions.Reasons(identifier: nil, paths: [], folders: [folder]))
+ #expect(byFolder == Exclusions.Reasons(identifier: nil, paths: [], folders: [folder], apps: []))
let both = Exclusions(paths: [folder, project], bundleIdentifiers: ["org.example.other"])
.reasons(excluding: project, app: nil)
@@ -24,6 +24,17 @@ struct ExclusionsTests {
#expect(Exclusions(paths: [project]).reasons(excluding: folder, app: nil).isEmpty)
}
+ @Test func saysWhichExcludedAppsFolderAnItemIsIn() {
+ let caches = URL(filePath: "/Users/me/Library/Caches", directoryHint: .isDirectory)
+ let exclusions = Exclusions(bundleIdentifiers: ["org.example.Notes"])
+
+ let inside = exclusions.reasons(excluding: caches.appending(path: "org.example.notes/data.db"), app: nil)
+ #expect(inside == Exclusions.Reasons(identifier: nil, paths: [], folders: [], apps: ["org.example.Notes"]))
+ let own = exclusions.reasons(excluding: caches.appending(path: "org.example.Notes"), app: nil)
+ #expect(own.apps == ["org.example.Notes"])
+ #expect(exclusions.reasons(excluding: caches.appending(path: "org.example.Other"), app: nil).isEmpty)
+ }
+
@Test func findsTheExcludedPlacesInsideAFolderOnce() {
let caches = URL(filePath: "/Users/x/Library/Caches", directoryHint: .isDirectory)
let exclusions = Exclusions(paths: [
@@ -129,6 +140,56 @@ struct ExclusionsTests {
#expect(!Exclusions.none.holds(URL(filePath: "/var")))
}
+ @Test func anExcludedAppsOwnFolderIsExcludedWithAllItHolds() {
+ let caches = URL(filePath: "/Users/x/Library/Caches", directoryHint: .isDirectory)
+ let exclusions = Exclusions(bundleIdentifiers: ["org.example.Notes"])
+
+ #expect(exclusions.excludes(caches.appending(path: "org.example.Notes")))
+ #expect(exclusions.excludes(caches.appending(path: "ORG.EXAMPLE.NOTES/data.db")))
+ #expect(exclusions.excludes(URL(filePath: "/Users/x/Library/Containers/org.example.Notes/Data/Library/Caches")))
+ #expect(!exclusions.excludes(caches.appending(path: "org.example.Notes.savedState")))
+ #expect(!exclusions.excludes(caches.appending(path: "org.example.NotesHelper")))
+ #expect(!exclusions.excludes(caches))
+ #expect(!Exclusions(bundleIdentifiers: ["Example"]).excludes(caches.appending(path: "Example")))
+ }
+
+ @Test func aFolderWithAnExcludedAppsOwnFolderALevelOrTwoInsideHoldsIt() throws {
+ let directory = try TemporaryDirectory()
+ try directory.file("Maker/org.example.Notes/data.db")
+ try directory.file("Vendor/Products/org.example.Notes/data.db")
+ try directory.file("Other/org.example.Other/data.db")
+ let exclusions = Exclusions(bundleIdentifiers: ["org.example.Notes"])
+
+ #expect(exclusions.holds(directory.url.appending(path: "Maker")))
+ #expect(exclusions.holds(directory.url.appending(path: "Vendor")))
+ #expect(!exclusions.holds(directory.url.appending(path: "Other")))
+ #expect(!exclusions.holds(directory.url.appending(path: "Maker/org.example.Notes")))
+ }
+
+ @Test func refusesToRemoveAnExcludedAppsOwnFolderOrAFolderHoldingIt() async throws {
+ let directory = try TemporaryDirectory()
+ let own = try directory.file("home/Library/Caches/org.example.Notes/cache.db").deletingLastPathComponent()
+ let maker = try directory.file("home/Library/Application Support/Maker/org.example.Notes/data.db")
+ .deletingLastPathComponent().deletingLastPathComponent()
+ let other = try directory.file("home/Library/Caches/org.example.Other/cache.db").deletingLastPathComponent()
+ let environment = SearchEnvironment(
+ homeDirectory: directory.url.appending(path: "home"),
+ rootDirectory: directory.url.appending(path: "root")
+ )
+ let trash = try directory.directory("Trash")
+ let exclusions = Exclusions(bundleIdentifiers: ["org.example.Notes"])
+ let service = TrashService(environment: environment, exclusions: exclusions) { url in
+ let destination = trash.appending(path: url.lastPathComponent)
+ try FileManager.default.moveItem(at: url, to: destination)
+ return destination
+ }
+
+ let result = await service.trash([own, maker, other])
+ #expect(result.trashed.map(\.originalURL) == [other])
+ #expect(result.failures.map(\.reason) == [.guarded(.excluded), .guarded(.excluded)])
+ #expect(own.isThere && maker.isThere)
+ }
+
@Test func refusesToRemoveAFolderThatHoldsSomethingExcluded() async throws {
let directory = try TemporaryDirectory()
let kept = try directory.file("home/Library/Application Support/Example/keep.db")
@@ -157,6 +218,12 @@ struct ExclusionsTests {
#expect(kept == [URL(filePath: "/b/three")])
}
+ @Test func keepsAnExcludedAppsOwnFolderOutOfResults() {
+ let urls = [URL(filePath: "/a/org.example.Notes/one"), URL(filePath: "/a/two")]
+ let kept = Exclusions(bundleIdentifiers: ["org.example.Notes"]).keeping(urls) { $0 }
+ #expect(kept == [URL(filePath: "/a/two")])
+ }
+
@Test func survivesBeingWrittenAndReadBack() async throws {
let directory = try TemporaryDirectory()
let store = ExclusionStore(url: directory.url.appending(path: "exclusions.json"))
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swift
index 581d1d2b..32fca8e9 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swift
@@ -120,6 +120,23 @@ struct SpaceInventoryTests {
#expect(caches.size == kept)
}
+ @Test func leavesOutWhatAnExcludedAppKeepsInItsOwnFolders() async throws {
+ let directory = try TemporaryDirectory()
+ try directory.file("Library/Caches/org.example.kept/blob", bytes: 300_000)
+ try directory.file("Library/Caches/org.example.Notes/blob", bytes: 500_000)
+ try directory.file("Library/Containers/org.example.Notes/Data/Library/Caches/blob", bytes: 500_000)
+
+ let report = await SpaceInventory.scan(
+ home: directory.url, root: directory.url, minimumSize: 1,
+ exclusions: Exclusions(bundleIdentifiers: ["org.example.Notes"]), measure: FileSize.measure
+ )
+
+ let caches = try #require(report.items.first { $0.id == "caches" })
+ let kept = await FileSize.reclaimableSize(of: directory.url.appending(path: "Library/Caches/org.example.kept"))
+ #expect(caches.size == kept)
+ #expect(!report.items.flatMap(\.urls).contains { $0.path(percentEncoded: false).contains("org.example.Notes") })
+ }
+
@Test func anExcludedPlaceThatCannotBeMeasuredLeavesTheAreaUnknown() async throws {
let directory = try TemporaryDirectory()
try directory.file("Library/Caches/org.example.kept/blob", bytes: 300_000)
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/SpaceRemovalTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/SpaceRemovalTests.swift
index 15aa8801..f478cc1f 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/SpaceRemovalTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/SpaceRemovalTests.swift
@@ -489,6 +489,21 @@ struct SpaceRemovalTests {
#expect(plan.removable.map(\.lastPathComponent) == ["com.gone.app"])
}
+ @Test func leavesAnExcludedAppsOwnFolderAlone() async throws {
+ let directory = try TemporaryDirectory()
+ try directory.file("home/Library/Caches/org.example.Notes/keep.db")
+ try directory.file("home/Library/Caches/com.gone.app/old.db")
+
+ let plan = await SpaceRemoval.plan(
+ for: item(directory),
+ environment: environment(directory),
+ exclusions: Exclusions(bundleIdentifiers: ["org.example.Notes"]),
+ running: [:]
+ )
+
+ #expect(plan.removable.map(\.lastPathComponent) == ["com.gone.app"])
+ }
+
/// The figure on the screen is what emptying will free, not what the folder holds.
@Test func sizeCountsOnlyWhatWillActuallyGo() async throws {
let directory = try TemporaryDirectory()
diff --git a/Peel/Views/ItemMenu.swift b/Peel/Views/ItemMenu.swift
index 16aa5531..be744ad9 100644
--- a/Peel/Views/ItemMenu.swift
+++ b/Peel/Views/ItemMenu.swift
@@ -38,12 +38,12 @@ struct ItemMenu: View {
}
}
- /// Takes off the list exactly what excludes the item. An excluded folder around it holds other things too, so
- /// that one is named and left to Settings.
+ /// Takes off the list exactly what excludes the item. An excluded folder or app around it holds other things too,
+ /// so that one is named and left to Settings.
@ViewBuilder private var wayBack: some View {
let reasons = ExclusionsStore.shared.exclusions.reasons(excluding: url, app: appIdentifier)
- if let folder = reasons.folders.first {
- Text("Excluded with “\(folder.lastPathComponent)”")
+ if let around = reasons.folders.first?.lastPathComponent ?? reasons.apps.first {
+ Text("Excluded with “\(around)”")
Button("Open Exclusions in Settings…", systemImage: "gearshape") {
SettingsPane.exclusions.open(with: openSettings)
}
diff --git a/Peel/Views/Settings/ExclusionsSettingsView.swift b/Peel/Views/Settings/ExclusionsSettingsView.swift
index 99ed4180..b2d852ab 100644
--- a/Peel/Views/Settings/ExclusionsSettingsView.swift
+++ b/Peel/Views/Settings/ExclusionsSettingsView.swift
@@ -144,7 +144,7 @@ struct ExclusionsSettingsView: View {
}
.editingControls()
} header: {
- heading("Apps", "Excluded apps still appear in Applications, but Peel won’t offer to remove or reset them. The Storage pages, Plug-ins, and Package Receipts go by files and folders only, so to protect an app’s files there, exclude its folders above as well.")
+ heading("Apps", "Excluded apps still appear in Applications, but Peel won’t offer to remove or reset them. A folder named with an excluded app’s identifier, such as its caches or its container, is left out of every page and never moved. The app’s other files, such as plug-ins or a folder named after it, go by files and folders only, so to protect them, exclude them above as well.")
}
Section {
diff --git a/SAFETY.md b/SAFETY.md
index a4c4271b..ef96645f 100644
--- a/SAFETY.md
+++ b/SAFETY.md
@@ -328,8 +328,10 @@ exclusion cannot be side-stepped by spelling the path differently.
It holds in both directions. A folder with something excluded inside it is never moved either, because the
excluded file would go with it: an app's leftover like that is shown, unselected, with the reason, and the
other tools leave it out. An excluded app still appears in Applications, so you can see it, but gets no
-removal plan and no reset, in the app and in `peel`; the Storage pages, Plug-ins, and Package Receipts go
-by files and folders only, so to keep an app's files there, exclude its folders too.
+removal plan and no reset, in the app and in `peel`. A folder named with its identifier, such as its caches or
+its container, is left out of every page and never moved, nor is a folder holding one a level or two down. Its
+other files, such as plug-ins, receipts, or a folder named after the app, go by files and folders only, so to
+keep them, exclude them too.
If the saved list is there and cannot be read, Peel does not treat it as empty. It moves nothing until you
start over in Settings, `peel` refuses, and the file it could not read is kept beside the new one.