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.

Remember what an uninstall left for an administrator

Țugui Dragoșb284a1f58774
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md
index a9a40125..1b4a9761 100644
--- a/ARCHITECTURE.md
+++ b/ARCHITECTURE.md
@@ -286,6 +286,7 @@ where a Homebrew install takes them from.
| `~/Library/Application Support/Peel/digests.bin` | What Duplicates already read, so an unchanged file isn't read again. |
| `~/Library/Application Support/Peel/apps.json`, `teams.json` | What Peel remembers about apps and their signing teams between launches. |
| `~/Library/Application Support/Peel/orphan-owners.json` | The orphaned files the user said belong to an installed app. |
+| `~/Library/Application Support/Peel/left-for-an-administrator.json` | What an uninstall left that only an administrator can move, so Orphaned Files lists it once the app is gone. |
| `~/Library/Application Support/Peel/dock-tiles.json` | The Dock icons an uninstall took out, and where each was, so History puts them back with their app. |
| `~/Library/Application Support/Peel/app-folders.json` | The folders the user chose for Peel to look for apps in, beside the Applications folders. |
| `~/Library/Application Support/Peel/homebrew.json` | The `brew` the user chose for a Homebrew in a folder of its own, which the app and `peel` run. |
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a8e0de93..ea5b753c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,7 +27,8 @@ its changes the way [Keep a Changelog](https://keepachangelog.com/) suggests.
- Shows iCloud Drive's downloads in the folders Finder shows them in, and on macOS 27 how far Remove Downloads got,
with a way to stop it.
- Lists in Orphaned Files what a gone app's own product file named, and browser helpers that start nothing.
-- Lists apart in Orphaned Files what only an administrator can remove, with how to remove it in Finder.
+- Lists apart in Orphaned Files what only an administrator can remove, with how to remove it in Finder, and says
+ after an uninstall when something stayed for an administrator.
- On macOS 27, says in History when an audio driver you put back needs a restart, and when an app shared its storage
with a copy.
- On macOS 27, says how to delete a network extension in System Settings, even once its app is gone.
diff --git a/GUIDE.md b/GUIDE.md
index f2c905a0..b457375d 100644
--- a/GUIDE.md
+++ b/GUIDE.md
@@ -25,6 +25,9 @@ and how to get it, [SAFETY.md](SAFETY.md) what it protects, [PRIVACY.md](PRIVACY
folder holding another installed app's own data, such as Xcode's in `~/Library/Developer`, can't be selected at
all. What Peel only guesses at, from the start of a name or an identifier the app's maker or signing team also
uses, waits under Review Before Removing.
+- **What only an administrator can move** stays where it is when Peel's helper isn't allowed to move it from there.
+ Once the app is gone, Peel says how many items stayed, and Orphaned Files lists them under Needs an Administrator,
+ with how to remove them in Finder.
- **The Select menu** has Select Recommended, Select All, and Deselect All. Select All selects everything you can
select, what Peel holds back included, and asks first when that takes anything Peel doesn't recommend.
- **Several ways in.** Choose an app in the list, drop one on Peel's Dock icon, select several apps at once, or
@@ -61,7 +64,8 @@ Space shows what fills your disk, area by area, and what each area is.
named only for a maker, such as `Google` in Application Support, a data folder only the app's documentation names,
such as Tor Browser's `TorBrowser-Data`, and a hidden folder in your home named like an app, since one such as
`~/.local` is shared by many command-line tools. What only an administrator can move, from a place Peel's helper
- isn't allowed to move it from, is listed apart under Needs an Administrator, with how to remove it in Finder.
+ isn't allowed to move it from, is listed apart under Needs an Administrator, with how to remove it in Finder, and
+ so is what an uninstall left there, which nothing else would tie to the app once it is gone.
- **Developer:** caches of developer tools, editors, browsers, and AI models. Nothing is selected for you, and Select
Recommended passes by what you may want again; toolchains or anything holding an account are never listed.
- **Build Artifacts:** what builds left in your projects, like `node_modules`, `DerivedData`, or `target`, each only
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index a8ccba82..aee57708 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -98321,6 +98321,112 @@
}
}
},
+ "One item stayed because only an administrator can move it, and Peel’s helper isn’t allowed to. Orphaned Files lists it under Needs an Administrator, with how to remove it." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Jedna položka zůstala na místě, protože ji může přesunout jen správce a pomocník Peelu ji přesunout nesmí. Stránka Osiřelé soubory ji zobrazuje v části Vyžaduje správce, kde najdete i postup, jak ji odstranit."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ein Objekt ist geblieben, weil nur ein Administrator es verschieben kann und das Hilfsprogramm von Peel es nicht verschieben darf. Die Seite „Verwaiste Dateien“ zeigt es unter „Benötigt einen Administrator“ an und erklärt, wie du es entfernst."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Un ítem se ha quedado porque solo un administrador puede trasladarlo, y el asistente de Peel no tiene permiso para hacerlo. La página Archivos huérfanos lo muestra en “Necesita un administrador”, donde se explica cómo eliminarlo."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Un élément est resté en place : seul un administrateur peut le déplacer, et l’utilitaire de Peel n’y est pas autorisé. La page Fichiers orphelins le liste sous « Nécessite un administrateur » et indique comment le supprimer."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Un elemento è rimasto perché solo un amministratore può spostarlo, e all’assistente di Peel non è consentito farlo. “File orfani” lo elenca in “Richiede un amministratore”, con le istruzioni per rimuoverlo."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "移動できるのは管理者だけで、Peelのヘルパーは移動を許可されていないため、1項目が残りました。この項目は“孤立ファイル”の“管理者が必要”に、取り除く方法とともに表示されます。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "항목 1개는 관리자만 이동할 수 있으며, Peel 보조 프로그램이 이동하는 것은 허용되지 않으므로 그대로 남았습니다. 주인 없는 파일 페이지의 ‘관리자 필요’에 이 항목이 제거 방법과 함께 나열됩니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Eén onderdeel is blijven staan omdat alleen een beheerder het kan verplaatsen, en het hulpprogramma van Peel dat niet mag. De pagina 'Verweesde bestanden' toont het onder 'Beheerder vereist', met uitleg over hoe je het verwijdert."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Jedna rzecz została na miejscu, ponieważ przenieść ją może tylko administrator, a pomocnikowi Peel nie wolno jej przenosić. Strona Osierocone pliki wyświetla ją w grupie „Wymaga administratora” wraz z instrukcją, jak się jej pozbyć."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Um item ficou porque só um administrador pode movê-lo, e o auxiliar do Peel não tem permissão para isso. A página Arquivos Órfãos lista esse item em “Requer um Administrador”, com instruções para removê-lo."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Un articol a rămas pe loc deoarece doar un administrator îl poate muta, iar instrumentul de ajutor Peel nu are voie să îl mute. Pagina Fișiere orfane îl listează la „Necesită un administrator” și explică cum îl puteți elimina."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Один объект остался на месте, потому что переместить его может только администратор, а помощнику Peel это не разрешено. Он есть в разделе «Осиротевшие файлы» > «Нужен администратор», где сказано, как его удалить."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ett objekt blev kvar eftersom bara en administratör kan flytta det och Peels hjälpprogram inte får göra det. Sidan Övergivna filer listar det under ”Kräver en administratör” och förklarar hur du tar bort det."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Bir öğe olduğu yerde kaldı, çünkü onu yalnızca bir yönetici taşıyabilir ve Peel’in yardımcısının onu taşımasına izin verilmiyor. Sahipsiz Dosyalar, onu Yönetici Gerektirenler altında listeler ve nasıl kaldıracağınızı açıklar."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Один елемент лишився на місці, бо перемістити його може лише адміністратор, а помічнику Peel цього не дозволено. Розділ «Покинуті файли» показує його в групі «Потрібен адміністратор» і пояснює, як його вилучити."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "有一个项目仍留在原处,因为只有管理员才能移动它,而Peel的帮助程序不能移动它。“孤立文件”会在“需要管理员”中列出它,并说明如何将其移除。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "有一個項目仍留在原處,因為只有管理者能移動它,而Peel的輔助程式不能移動它。「孤立檔案」會在「需要管理者」中列出它,並說明如何移除。"
+ }
+ }
+ }
+ },
"One of these takes effect the next time you log out and back in." : {
"localizations" : {
"cs" : {
@@ -100123,6 +100229,112 @@
}
}
},
+ "Open Orphaned Files" : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Otevřít Osiřelé soubory"
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "„Verwaiste Dateien“ öffnen"
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Abrir Archivos huérfanos"
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Ouvrir la page Fichiers orphelins"
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Apri “File orfani”"
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "孤立ファイルを開く"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "주인 없는 파일 열기"
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Open 'Verweesde bestanden'"
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Otwórz Osierocone pliki"
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Abrir Arquivos Órfãos"
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Deschideți pagina Fișiere orfane"
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Открыть раздел «Осиротевшие файлы»"
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Öppna Övergivna filer"
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Sahipsiz Dosyalar’ı Aç"
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Відкрити Покинуті файли"
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "打开孤立文件"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "打開孤立檔案"
+ }
+ }
+ }
+ },
"Open Peel" : {
"localizations" : {
"cs" : {
@@ -111014,6 +111226,112 @@
}
}
},
+ "Peel isn’t sure only %@ used this. Check it before you remove it." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel si není jistý, že tuto položku nepoužívala žádná jiná aplikace než %@. Před odstraněním ji zkontrolujte."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel ist sich nicht sicher, ob dies nur von %@ verwendet wurde. Prüfe es, bevor du es entfernst."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel no está seguro de que esto fuera usado solo por %@. Revísalo antes de eliminarlo."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel n’est pas sûr que cet élément ait été utilisé uniquement par %@. Examinez-le avant de le supprimer."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel non è sicuro che fosse usato solo da %@. Controllalo prima di rimuoverlo."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peelは、これを使用していたのが%@だけかどうか確信を持てません。取り除く前に確認してください。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel은 이 항목이 %@에서만 사용되었는지 확신하지 못합니다. 제거하기 전에 확인하십시오."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel weet niet zeker of dit alleen door %@ werd gebruikt. Controleer het voordat je het verwijdert."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel nie jest pewien, czy było to używane tylko przez: %@. Sprawdź to, zanim się tego pozbędziesz."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "O Peel não tem certeza de que isto fosse usado só por %@. Verifique-o antes de removê-lo."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel nu este sigur că acest articol a fost folosit doar de %@. Verificați‑l înainte să îl eliminați."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel не уверен, что этот объект принадлежал только %@. Проверьте его, прежде чем удалять."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel är inte säker på att bara %@ använde det här. Kontrollera det innan du tar bort det."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel, bunun yalnızca %@ tarafından kullanıldığından emin değil. Onu kaldırmadan önce gözden geçirin."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel не впевнена, що це належало лише %@. Перевірте це, перш ніж його вилучати."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel不确定是否只有“%@”使用过此项。请在移除前检查它。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Peel無法確定是否只有%@使用過此項目。移除前請先檢查。"
+ }
+ }
+ }
+ },
"Peel isn’t watching the Trash right now. It tries again each time you come back to Peel." : {
"localizations" : {
"cs" : {
@@ -146881,6 +147199,112 @@
}
}
},
+ "Some items stayed for an administrator." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Některé položky zůstaly pro správce."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Einige Objekte sind geblieben und benötigen einen Administrator."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Algunos ítems se han quedado para un administrador."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Certains éléments sont restés en place pour un administrateur."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Alcuni elementi sono rimasti in attesa di un amministratore."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "一部の項目は管理者が必要なため残りました。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "일부 항목은 관리자가 필요하여 그대로 남았습니다."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Sommige onderdelen zijn blijven staan voor een beheerder."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Niektóre rzeczy zostały na miejscu i czekają na administratora."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Alguns itens ficaram para um administrador."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Unele articole au rămas în seama unui administrator."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Некоторые объекты остались на месте: нужен администратор."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Vissa objekt blev kvar åt en administratör."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Bazı öğeler yönetici gerektirdiği için olduğu yerde kaldı."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Деякі елементи лишилися для адміністратора."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "部分项目仍留在原处,需由管理员移动。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "部分項目仍留在原處,需由管理者移動。"
+ }
+ }
+ }
+ },
"Some leftovers sit in folders only an administrator can change. The helper moves those for Peel. macOS asks you to approve it once, in Login Items & Extensions. It belongs to the copy of Peel that installed it: a second copy, in another folder, has to install its own." : {
"localizations" : {
"cs" : {
@@ -195878,6 +196302,346 @@
}
}
},
+ "^[%lld item](inflect: true) stayed because only an administrator can move them, and Peel’s helper isn’t allowed to. Orphaned Files lists them under Needs an Administrator, with how to remove them." : {
+ "localizations" : {
+ "cs" : {
+ "variations" : {
+ "plural" : {
+ "few" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld položky zůstaly na místě, protože je může přesunout jen správce a pomocník Peelu je přesunout nesmí. Stránka Osiřelé soubory je zobrazuje v části Vyžaduje správce, kde najdete i postup, jak je odstranit."
+ }
+ },
+ "many" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld položky zůstalo na místě, protože je může přesunout jen správce a pomocník Peelu je přesunout nesmí. Stránka Osiřelé soubory je zobrazuje v části Vyžaduje správce, kde najdete i postup, jak je odstranit."
+ }
+ },
+ "one" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld položka zůstala na místě, protože ji může přesunout jen správce a pomocník Peelu ji přesunout nesmí. Stránka Osiřelé soubory ji zobrazuje v části Vyžaduje správce, kde najdete i postup, jak ji odstranit."
+ }
+ },
+ "other" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld položek zůstalo na místě, protože je může přesunout jen správce a pomocník Peelu je přesunout nesmí. Stránka Osiřelé soubory je zobrazuje v části Vyžaduje správce, kde najdete i postup, jak je odstranit."
+ }
+ }
+ }
+ }
+ },
+ "de" : {
+ "variations" : {
+ "plural" : {
+ "one" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld Objekt ist geblieben, weil nur ein Administrator es verschieben kann und das Hilfsprogramm von Peel es nicht verschieben darf. Die Seite „Verwaiste Dateien“ zeigt es unter „Benötigt einen Administrator“ an und erklärt, wie du es entfernst."
+ }
+ },
+ "other" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld Objekte sind geblieben, weil nur ein Administrator sie verschieben kann und das Hilfsprogramm von Peel sie nicht verschieben darf. Die Seite „Verwaiste Dateien“ zeigt sie unter „Benötigt einen Administrator“ an und erklärt, wie du sie entfernst."
+ }
+ }
+ }
+ }
+ },
+ "es" : {
+ "variations" : {
+ "plural" : {
+ "many" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld de ítems se han quedado porque solo un administrador puede trasladarlos, y el asistente de Peel no tiene permiso para hacerlo. La página Archivos huérfanos los muestra en “Necesita un administrador”, donde se explica cómo eliminarlos."
+ }
+ },
+ "one" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld ítem se ha quedado porque solo un administrador puede trasladarlo, y el asistente de Peel no tiene permiso para hacerlo. La página Archivos huérfanos lo muestra en “Necesita un administrador”, donde se explica cómo eliminarlo."
+ }
+ },
+ "other" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld ítems se han quedado porque solo un administrador puede trasladarlos, y el asistente de Peel no tiene permiso para hacerlo. La página Archivos huérfanos los muestra en “Necesita un administrador”, donde se explica cómo eliminarlos."
+ }
+ }
+ }
+ }
+ },
+ "fr" : {
+ "variations" : {
+ "plural" : {
+ "many" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld d’éléments sont restés en place : seul un administrateur peut les déplacer, et l’utilitaire de Peel n’y est pas autorisé. La page Fichiers orphelins les liste sous « Nécessite un administrateur » et indique comment les supprimer."
+ }
+ },
+ "one" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld élément est resté en place : seul un administrateur peut le déplacer, et l’utilitaire de Peel n’y est pas autorisé. La page Fichiers orphelins le liste sous « Nécessite un administrateur » et indique comment le supprimer."
+ }
+ },
+ "other" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld éléments sont restés en place : seul un administrateur peut les déplacer, et l’utilitaire de Peel n’y est pas autorisé. La page Fichiers orphelins les liste sous « Nécessite un administrateur » et indique comment les supprimer."
+ }
+ }
+ }
+ }
+ },
+ "it" : {
+ "variations" : {
+ "plural" : {
+ "many" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld di elementi sono rimasti perché solo un amministratore può spostarli, e all’assistente di Peel non è consentito farlo. “File orfani” li elenca in “Richiede un amministratore”, con le istruzioni per rimuoverli."
+ }
+ },
+ "one" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld elemento è rimasto perché solo un amministratore può spostarlo, e all’assistente di Peel non è consentito farlo. “File orfani” lo elenca in “Richiede un amministratore”, con le istruzioni per rimuoverlo."
+ }
+ },
+ "other" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld elementi sono rimasti perché solo un amministratore può spostarli, e all’assistente di Peel non è consentito farlo. “File orfani” li elenca in “Richiede un amministratore”, con le istruzioni per rimuoverli."
+ }
+ }
+ }
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "移動できるのは管理者だけで、Peelのヘルパーは移動を許可されていないため、%lld項目が残りました。これらの項目は“孤立ファイル”の“管理者が必要”に、取り除く方法とともに表示されます。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "항목 %lld개는 관리자만 이동할 수 있으며, Peel 보조 프로그램이 이동하는 것은 허용되지 않으므로 그대로 남았습니다. 주인 없는 파일 페이지의 ‘관리자 필요’에 이 항목들이 제거 방법과 함께 나열됩니다."
+ }
+ },
+ "nl" : {
+ "variations" : {
+ "plural" : {
+ "one" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld onderdeel is blijven staan omdat alleen een beheerder het kan verplaatsen, en het hulpprogramma van Peel dat niet mag. De pagina 'Verweesde bestanden' toont het onder 'Beheerder vereist', met uitleg over hoe je het verwijdert."
+ }
+ },
+ "other" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld onderdelen zijn blijven staan omdat alleen een beheerder ze kan verplaatsen, en het hulpprogramma van Peel dat niet mag. De pagina 'Verweesde bestanden' toont ze onder 'Beheerder vereist', met uitleg over hoe je ze verwijdert."
+ }
+ }
+ }
+ }
+ },
+ "pl" : {
+ "variations" : {
+ "plural" : {
+ "few" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld rzeczy zostały na miejscu, ponieważ przenieść je może tylko administrator, a pomocnikowi Peel nie wolno ich przenosić. Strona Osierocone pliki wyświetla je w grupie „Wymaga administratora” wraz z instrukcją, jak się ich pozbyć."
+ }
+ },
+ "many" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld rzeczy zostało na miejscu, ponieważ przenieść je może tylko administrator, a pomocnikowi Peel nie wolno ich przenosić. Strona Osierocone pliki wyświetla je w grupie „Wymaga administratora” wraz z instrukcją, jak się ich pozbyć."
+ }
+ },
+ "one" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld rzecz została na miejscu, ponieważ przenieść ją może tylko administrator, a pomocnikowi Peel nie wolno jej przenosić. Strona Osierocone pliki wyświetla ją w grupie „Wymaga administratora” wraz z instrukcją, jak się jej pozbyć."
+ }
+ },
+ "other" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld rzeczy zostało na miejscu, ponieważ przenieść je może tylko administrator, a pomocnikowi Peel nie wolno ich przenosić. Strona Osierocone pliki wyświetla je w grupie „Wymaga administratora” wraz z instrukcją, jak się ich pozbyć."
+ }
+ }
+ }
+ }
+ },
+ "pt" : {
+ "variations" : {
+ "plural" : {
+ "many" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld de itens ficaram porque só um administrador pode movê-los, e o auxiliar do Peel não tem permissão para isso. A página Arquivos Órfãos lista esses itens em “Requer um Administrador”, com instruções para removê-los."
+ }
+ },
+ "one" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld item ficou porque só um administrador pode movê-lo, e o auxiliar do Peel não tem permissão para isso. A página Arquivos Órfãos lista esse item em “Requer um Administrador”, com instruções para removê-lo."
+ }
+ },
+ "other" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld itens ficaram porque só um administrador pode movê-los, e o auxiliar do Peel não tem permissão para isso. A página Arquivos Órfãos lista esses itens em “Requer um Administrador”, com instruções para removê-los."
+ }
+ }
+ }
+ }
+ },
+ "ro" : {
+ "variations" : {
+ "plural" : {
+ "few" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld articole au rămas pe loc deoarece doar un administrator le poate muta, iar instrumentul de ajutor Peel nu are voie să le mute. Pagina Fișiere orfane le listează la „Necesită un administrator” și explică cum le puteți elimina."
+ }
+ },
+ "one" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld articol a rămas pe loc deoarece doar un administrator îl poate muta, iar instrumentul de ajutor Peel nu are voie să îl mute. Pagina Fișiere orfane îl listează la „Necesită un administrator” și explică cum îl puteți elimina."
+ }
+ },
+ "other" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld de articole au rămas pe loc deoarece doar un administrator le poate muta, iar instrumentul de ajutor Peel nu are voie să le mute. Pagina Fișiere orfane le listează la „Necesită un administrator” și explică cum le puteți elimina."
+ }
+ }
+ }
+ }
+ },
+ "ru" : {
+ "variations" : {
+ "plural" : {
+ "few" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld объекта остались на месте, потому что переместить их может только администратор, а помощнику Peel это не разрешено. Они есть в разделе «Осиротевшие файлы» > «Нужен администратор», где сказано, как их удалить."
+ }
+ },
+ "many" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld объектов остались на месте, потому что переместить их может только администратор, а помощнику Peel это не разрешено. Они есть в разделе «Осиротевшие файлы» > «Нужен администратор», где сказано, как их удалить."
+ }
+ },
+ "one" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld объект остался на месте, потому что переместить их может только администратор, а помощнику Peel это не разрешено. Они есть в разделе «Осиротевшие файлы» > «Нужен администратор», где сказано, как их удалить."
+ }
+ },
+ "other" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld объекта остались на месте, потому что переместить их может только администратор, а помощнику Peel это не разрешено. Они есть в разделе «Осиротевшие файлы» > «Нужен администратор», где сказано, как их удалить."
+ }
+ }
+ }
+ }
+ },
+ "sv" : {
+ "variations" : {
+ "plural" : {
+ "one" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld objekt blev kvar eftersom bara en administratör kan flytta det och Peels hjälpprogram inte får göra det. Sidan Övergivna filer listar det under ”Kräver en administratör” och förklarar hur du tar bort det."
+ }
+ },
+ "other" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld objekt blev kvar eftersom bara en administratör kan flytta dem och Peels hjälpprogram inte får göra det. Sidan Övergivna filer listar dem under ”Kräver en administratör” och förklarar hur du tar bort dem."
+ }
+ }
+ }
+ }
+ },
+ "tr" : {
+ "variations" : {
+ "plural" : {
+ "one" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld öğe olduğu yerde kaldı, çünkü onu yalnızca bir yönetici taşıyabilir ve Peel’in yardımcısının onu taşımasına izin verilmiyor. Sahipsiz Dosyalar, onu Yönetici Gerektirenler altında listeler ve nasıl kaldıracağınızı açıklar."
+ }
+ },
+ "other" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld öğe olduğu yerde kaldı, çünkü onları yalnızca bir yönetici taşıyabilir ve Peel’in yardımcısının onları taşımasına izin verilmiyor. Sahipsiz Dosyalar, onları Yönetici Gerektirenler altında listeler ve nasıl kaldıracağınızı açıklar."
+ }
+ }
+ }
+ }
+ },
+ "uk" : {
+ "variations" : {
+ "plural" : {
+ "few" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld елементи лишилися на місці, бо перемістити їх може лише адміністратор, а помічнику Peel цього не дозволено. Розділ «Покинуті файли» показує їх у групі «Потрібен адміністратор» і пояснює, як їх вилучити."
+ }
+ },
+ "many" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld елементів лишилися на місці, бо перемістити їх може лише адміністратор, а помічнику Peel цього не дозволено. Розділ «Покинуті файли» показує їх у групі «Потрібен адміністратор» і пояснює, як їх вилучити."
+ }
+ },
+ "one" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld елемент лишився на місці, бо перемістити їх може лише адміністратор, а помічнику Peel цього не дозволено. Розділ «Покинуті файли» показує їх у групі «Потрібен адміністратор» і пояснює, як їх вилучити."
+ }
+ },
+ "other" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "%lld елемента лишилося на місці, бо перемістити їх може лише адміністратор, а помічнику Peel цього не дозволено. Розділ «Покинуті файли» показує їх у групі «Потрібен адміністратор» і пояснює, як їх вилучити."
+ }
+ }
+ }
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "有%lld个项目仍留在原处,因为只有管理员才能移动它们,而Peel的帮助程序不能移动它们。“孤立文件”会在“需要管理员”中列出它们,并说明如何将其移除。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "有%lld個項目仍留在原處,因為只有管理者能移動它們,而Peel的輔助程式不能移動它們。「孤立檔案」會在「需要管理者」中列出它們,並說明如何移除。"
+ }
+ }
+ }
+ },
"^[%lld item](inflect: true) · %@" : {
"localizations" : {
"cs" : {
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift
index 26948879..c7c8203b 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/AppCommands.swift
@@ -304,6 +304,7 @@ struct UninstallCommand: AsyncParsableCommand {
let appMoved: Bool?
let needsAdministrator: Int
let needsReview: Int
+ let leftForAnAdministrator: Int
let unreadableLocations: [String]
private enum CodingKeys: String, CodingKey {
@@ -316,6 +317,7 @@ struct UninstallCommand: AsyncParsableCommand {
case appMoved
case needsAdministrator
case needsReview
+ case leftForAnAdministrator
case unreadableLocations
}
@@ -331,6 +333,7 @@ struct UninstallCommand: AsyncParsableCommand {
try container.encode(appMoved, forKey: .appMoved)
try container.encode(needsAdministrator, forKey: .needsAdministrator)
try container.encode(needsReview, forKey: .needsReview)
+ try container.encode(leftForAnAdministrator, forKey: .leftForAnAdministrator)
try container.encode(unreadableLocations, forKey: .unreadableLocations)
}
}
@@ -357,6 +360,7 @@ struct UninstallCommand: AsyncParsableCommand {
appMoved: result.map { result in result.trashed.contains { $0.originalURL == plan.app } },
needsAdministrator: plan.needsAdministrator,
needsReview: plan.needsReview,
+ leftForAnAdministrator: plan.leftForAnAdministrator,
unreadableLocations: unreadable.map { Output.path($0.url) }
)
}
@@ -607,7 +611,9 @@ struct UninstallCommand: AsyncParsableCommand {
// The privacy reset comes before the move, because `tccutil` only finds an app that is still in place.
let reset = resetPrivacy ? await PrivacyReset.reset([target], beforeMovingWith: service).first?.result : nil
let result = await plan.move(using: service)
- return (reset, result, await plan.record(result, from: target.name))
+ let recorded = await plan.record(result, from: target.name)
+ await LeftForAnAdministrator().record(uninstallation.leftForAnAdministrator(after: result))
+ return (reset, result, recorded)
}
let privacy = reset.map { Self.privacyOutcome($0, app: target, after: result) }
if isInTheDock, Self.takesOutDockIcon(of: target, after: result, keeping: keepInDock) {
@@ -661,6 +667,10 @@ struct UninstallCommand: AsyncParsableCommand {
let them = plan.needsAdministrator == 1 ? "it" : "them"
notes.append("\(Output.count(plan.needsAdministrator, "item needs", "items need")) administrator access and will stay. Remove \(them) with the Peel app.")
}
+ if plan.leftForAnAdministrator > 0 {
+ let them = plan.leftForAnAdministrator == 1 ? "it" : "them"
+ notes.append("\(Output.count(plan.leftForAnAdministrator, "item needs", "items need")) an administrator, and Peel's helper isn't allowed to move \(them). Once \(Output.plain(app.name)) is in the Trash, Orphaned Files in the Peel app lists \(them) under Needs an Administrator, with how to remove \(them).")
+ }
if plan.needsReview > 0 {
let them = plan.needsReview == 1 ? "it" : "them"
notes.append("\(Output.count(plan.needsReview, "file needs", "files need")) review and will stay. See \(them) with `peel leftovers \(Output.quoted(app.name)) --all`.")
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift b/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift
index b27822d2..44b7e572 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Commands/FileCommands.swift
@@ -29,6 +29,28 @@ struct OrphansCommand: AsyncParsableCommand {
let path: String
let size: MeasuredSize
let apps: [String]
+ /// How the uninstall that left it found it, in `peel leftovers --json`'s words, or `null` for what the
+ /// scan found itself.
+ let reason: String?
+ let confidence: String?
+
+ private enum CodingKeys: String, CodingKey {
+ case path
+ case size
+ case apps
+ case reason
+ case confidence
+ }
+
+ /// Encodes a missing claim as `null`, for the reason `AppRecord` gives.
+ func encode(to encoder: any Encoder) throws {
+ var container = encoder.container(keyedBy: CodingKeys.self)
+ try container.encode(path, forKey: .path)
+ try container.encode(size, forKey: .size)
+ try container.encode(apps, forKey: .apps)
+ try container.encode(reason, forKey: .reason)
+ try container.encode(confidence, forKey: .confidence)
+ }
}
struct Group: Encodable {
@@ -74,8 +96,8 @@ struct OrphansCommand: AsyncParsableCommand {
let catalog = await AppCatalog.scan()
if let refusal = Self.refusal(for: catalog) { throw refusal }
let apps = catalog.apps
- // The same signals the app uses (the apps Peel remembers and the apps running), so both judge these
- // files alike. The memory of apps is only read here, never written.
+ // The same signals the app uses (the apps Peel remembers, the apps running, and what uninstalls left for an
+ // administrator), so both judge these files alike. What Peel remembers is only read here, never written.
let remembered = await AppMemory().load()
let running = Set(await RunningCopies.current.compactMap(\.bundleIdentifier))
let exclusions = await UnreadableExclusions.load()
@@ -85,7 +107,8 @@ struct OrphansCommand: AsyncParsableCommand {
installedApps: apps,
remembered: remembered,
running: running,
- owners: OrphanOwners().load()
+ owners: OrphanOwners().load(),
+ leftForAnAdministrator: await LeftForAnAdministrator().load()
)
}
if let group {
@@ -156,7 +179,11 @@ struct OrphansCommand: AsyncParsableCommand {
},
forAnAdministrator: scan.forAnAdministrator.map { entry in
Report.ForAnAdministrator(
- path: Output.path(entry.item.url), size: MeasuredSize(entry.item.size), apps: entry.apps
+ path: Output.path(entry.item.url),
+ size: MeasuredSize(entry.item.size),
+ apps: entry.apps,
+ reason: entry.claim?.reason.rawValue,
+ confidence: entry.claim?.confidence.summary
)
},
unreadableLocations: scan.unreadableLocations.map { Output.path($0.url) }
@@ -172,8 +199,14 @@ struct OrphansCommand: AsyncParsableCommand {
static func administratorRows(for scan: OrphanScan) -> [[String]] {
scan.forAnAdministrator.map { entry in
- let apps = Output.list(entry.apps.map(Output.plain))
- return [Output.size(entry.item.size), Output.path(entry.item.url), "found for \(apps)"]
+ var found = "found for \(Output.list(entry.apps.map(Output.plain)))"
+ if let claim = entry.claim {
+ found += ", \(claim.reason.summary)"
+ if claim.confidence == .possible {
+ found += ", review: \(claim.confidence.summary) match"
+ }
+ }
+ return [Output.size(entry.item.size), Output.path(entry.item.url), found]
}
}
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swift
index 6f1aff66..04b4c8ee 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/UninstallPlan.swift
@@ -18,8 +18,10 @@ struct UninstallPlan {
/// How many recommended leftovers need administrator access. The command line never asks for it, so they stay.
let needsAdministrator: Int
/// How many leftovers are listed but not recommended: shared with another app, only possible, or held back for
- /// a reason other than the app's own uninstaller, which removes what it holds back.
+ /// a reason other than the app's own uninstaller, which removes what it holds back, or than an administrator.
let needsReview: Int
+ /// How many leftovers stay for an administrator (`Uninstallation.leftForAnAdministrator`).
+ var leftForAnAdministrator = 0
var uninstallsItself = false
var makersFolderNames: Set<String> = []
var appSharesStorage = false
@@ -58,11 +60,16 @@ struct UninstallPlan {
return Item(url: url, size: size, refusal: refusal(url))
}
let rest = keepLeftovers ? [] : uninstallation.scan.leftovers
+ let forAnAdministrator = Set(uninstallation.leftForAnAdministrator.map(\.url))
return UninstallPlan(
app: app,
items: items,
needsAdministrator: rest.count(where: { $0.match.isRecommended && $0.requiresPrivileges }),
- needsReview: rest.count(where: { !$0.match.isRecommended && $0.match.heldBack != .leftToItsUninstaller }),
+ needsReview: rest.count(where: {
+ !$0.match.isRecommended && $0.match.heldBack != .leftToItsUninstaller
+ && !forAnAdministrator.contains($0.url)
+ }),
+ leftForAnAdministrator: forAnAdministrator.count,
uninstallsItself: uninstallation.uninstallsItself != nil,
makersFolderNames: uninstallation.makersFolderNames,
appSharesStorage: uninstallation.appSharesStorage
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift
index 6c567d0a..52a75bcb 100644
--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift
@@ -265,13 +265,17 @@ public struct Leftover: Sendable, Hashable, Identifiable {
public let requiresPrivileges: Bool
/// True for a preference file that is no property list (`PreferenceFile.isDamaged`).
public var holdsDamagedSettings = false
+ /// True when only an administrator can move it, from a place the helper may not move it from, and nothing else
+ /// holds it back.
+ public var isLeftForAnAdministrator = false
public var id: URL { url }
func sharing(with apps: [String]) -> Leftover {
Leftover(
url: url, kind: kind, match: match.sharing(with: apps), size: size, isMeasured: isMeasured,
- requiresPrivileges: requiresPrivileges, holdsDamagedSettings: holdsDamagedSettings
+ requiresPrivileges: requiresPrivileges, holdsDamagedSettings: holdsDamagedSettings,
+ isLeftForAnAdministrator: isLeftForAnAdministrator
)
}
@@ -281,7 +285,8 @@ public struct Leftover: Sendable, Hashable, Identifiable {
guard match.heldBack?.cannotBeMoved != true else { return self }
return Leftover(
url: url, kind: kind, match: match.forReview(reason), size: size, isMeasured: isMeasured,
- requiresPrivileges: requiresPrivileges, holdsDamagedSettings: holdsDamagedSettings
+ requiresPrivileges: requiresPrivileges, holdsDamagedSettings: holdsDamagedSettings,
+ isLeftForAnAdministrator: isLeftForAnAdministrator
)
}
}
@@ -306,12 +311,15 @@ public struct LeftoverScan: Sendable {
public var needsFullDiskAccess = false
/// Holds back, as `beyondTheHelper`, each item that needs an administrator and that the helper would refuse
- /// once `app` has moved. An item already held back by a reason that blocks the move keeps its reason.
+ /// once `app` has moved. An item already held back by a reason that blocks the move keeps its reason, and one
+ /// held back for nothing else is left for an administrator.
func holdingBack(beyond reach: HelperReach, leaving app: URL) -> LeftoverScan {
LeftoverScan(
leftovers: leftovers.map { leftover in
guard leftover.requiresPrivileges, reach.isBeyond(leftover.url, leaving: app) else { return leftover }
- return leftover.heldBack(.beyondTheHelper)
+ var held = leftover.heldBack(.beyondTheHelper)
+ held.isLeftForAnAdministrator = leftover.match.heldBack == nil
+ return held
},
unreadableLocations: unreadableLocations,
cutShortLocations: cutShortLocations,
diff --git a/Packages/PeelCore/Sources/PeelCore/Orphans/AdministratorItem.swift b/Packages/PeelCore/Sources/PeelCore/Orphans/AdministratorItem.swift
index 3647a0b6..08f990af 100644
--- a/Packages/PeelCore/Sources/PeelCore/Orphans/AdministratorItem.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Orphans/AdministratorItem.swift
@@ -6,6 +6,12 @@ public struct AdministratorItem: Sendable, Hashable, Identifiable {
public let item: OrphanItem
/// The apps it was found for, by name.
public let apps: [String]
+ public var claim: Claim?
public var id: URL { item.url }
+
+ public struct Claim: Sendable, Hashable {
+ public let reason: MatchReason
+ public let confidence: MatchConfidence
+ }
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Orphans/LeftForAnAdministrator.swift b/Packages/PeelCore/Sources/PeelCore/Orphans/LeftForAnAdministrator.swift
new file mode 100644
index 00000000..bb31a0ab
--- /dev/null
+++ b/Packages/PeelCore/Sources/PeelCore/Orphans/LeftForAnAdministrator.swift
@@ -0,0 +1,107 @@
+public import Foundation
+internal import PeelPrivileged
+
+/// What uninstalls left for an administrator: items only an administrator can move, from places the helper may not
+/// move them from. Once their app is gone nothing else names them, so they are kept here for Orphaned Files.
+public struct LeftForAnAdministrator: Sendable {
+ /// One item an uninstall left, with the apps it was found for and the claim that found it.
+ public struct Record: Sendable, Hashable, Codable {
+ public struct App: Sendable, Hashable, Codable {
+ /// The app's `InstalledApp.reference`.
+ public let reference: String
+ public let name: String
+ }
+
+ public let path: String
+ public let kind: SearchLocation.Kind
+ public let apps: [App]
+ public let reason: MatchReason
+ public let confidence: MatchConfidence
+
+ /// The record of one item with a later one: the surer claim, or the later claim with both records' apps
+ /// when they are as sure.
+ func followed(by later: Record) -> Record {
+ guard later.confidence == confidence else { return later.confidence > confidence ? later : self }
+ let apps = apps + later.apps.filter { app in
+ !apps.contains { $0.reference.lowercased() == app.reference.lowercased() }
+ }
+ return Record(path: later.path, kind: later.kind, apps: apps, reason: later.reason, confidence: confidence)
+ }
+
+ /// One record per item however its path is spelled, each from all of its records in their order.
+ static func merged(_ records: [Record]) -> [ItemKey: Record] {
+ Dictionary(records.map { (ItemKey(URL(filePath: $0.path)), $0) }, uniquingKeysWith: { $0.followed(by: $1) })
+ }
+ }
+
+ public let url: URL
+
+ public init(url: URL = LeftForAnAdministrator.defaultURL) {
+ self.url = url
+ }
+
+ public static var defaultURL: URL { url(inHome: .homeDirectory) }
+
+ static func url(inHome home: URL) -> URL {
+ PeelFolder.url(inHome: home).appending(path: "left-for-an-administrator.json")
+ }
+
+ @concurrent
+ public func load() async -> [Record] {
+ // Taking the lock makes its file and folder, and a read must leave a home as it found it.
+ guard !url.isMissing else { return [] }
+ return FileLock.whileHeld(beside: url) { read() } ?? []
+ }
+
+ /// Adds `records`, each joined with the older ones of its item however its path is spelled, and forgets those
+ /// whose item is gone. A file that can't be read is never written over.
+ @concurrent
+ public func record(_ records: [Record]) async {
+ guard !records.isEmpty else { return }
+ FileLock.whileHeld(beside: url) {
+ guard let known = read() else { return }
+ let all = known + records
+ let merged = Record.merged(all)
+ var written: Set<ItemKey> = []
+ write(all.compactMap { record in
+ let item = ItemKey(URL(filePath: record.path))
+ guard written.insert(item).inserted, let record = merged[item] else { return nil }
+ return URL(filePath: record.path).isMissing ? nil : record
+ })
+ }
+ }
+
+ /// Returns nil when the file can't be read or reached. A damaged file is first kept under another name, and only
+ /// the records that can be read are kept, or nil when it can't be set aside.
+ private func read() -> [Record]? {
+ guard !url.isMissing else { return [] }
+ guard let data = BoundedRead.data(at: url) else { return nil }
+ let decoder = JSONDecoder()
+ if let records = try? decoder.decode([Record].self, from: data) { return records }
+ let readable = (try? decoder.decode([Row].self, from: data))?.compactMap(\.record) ?? []
+ guard DamagedFile.setAside(url) != nil else { return nil }
+ write(readable)
+ return readable
+ }
+
+ /// One record of the file, decoded on its own. `record` is nil when the row is not a valid record.
+ private struct Row: Decodable {
+ let record: Record?
+
+ init(from decoder: any Decoder) {
+ record = try? Record(from: decoder)
+ }
+ }
+
+ private func write(_ records: [Record]) {
+ let encoder = JSONEncoder()
+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
+ guard let data = try? encoder.encode(records) else { return }
+ try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try? data.write(to: url, options: .atomic)
+ }
+}
+
+extension SearchLocation.Kind: Codable {}
+extension MatchReason: Codable {}
+extension MatchConfidence: Codable {}
diff --git a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift
index aa0591b0..33802ab0 100644
--- a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift
@@ -16,6 +16,7 @@ public struct OrphanScanner: Sendable {
/// The most folders listed per location while looking inside folders no orphan is named after.
private let nestedFolderLimit: Int
private let systemExtensions: AppExtensions.SystemExtensionsAnswer
+ private let installedByApple: LeftoverScanner.InstalledByApple
public init(environment: SearchEnvironment = .current, exclusions: Exclusions = .none) {
self.init(
@@ -32,7 +33,8 @@ public struct OrphanScanner: Sendable {
systemApps: [InstalledApp]? = nil,
walk: @escaping LeftoverScanner.Measure = LeftoverScanner.walk,
nestedFolderLimit: Int = NestedSearch.folderLimit,
- systemExtensions: @escaping AppExtensions.SystemExtensionsAnswer = AppExtensions.askingMacOS
+ systemExtensions: @escaping AppExtensions.SystemExtensionsAnswer = AppExtensions.askingMacOS,
+ installedByApple: @escaping LeftoverScanner.InstalledByApple = { await PackageReceipts.isInstalledByApple($0) }
) {
self.environment = environment
self.exclusions = exclusions
@@ -41,6 +43,7 @@ public struct OrphanScanner: Sendable {
self.walk = walk
self.nestedFolderLimit = nestedFolderLimit
self.systemExtensions = systemExtensions
+ self.installedByApple = installedByApple
}
private var launchdFolders: [URL] {
@@ -59,7 +62,8 @@ public struct OrphanScanner: Sendable {
installedApps: [InstalledApp],
remembered: [RememberedApp] = [],
running: Set<String> = [],
- owners: [String: String] = [:]
+ owners: [String: String] = [:],
+ leftForAnAdministrator records: [LeftForAnAdministrator.Record] = []
) async -> OrphanScan {
let systemApps = if let systemApps { systemApps } else { await AppCatalog.systemApps.value }
let (installedApps, gone) = Self.split(remembered, installedApps: installedApps)
@@ -161,10 +165,7 @@ public struct OrphanScanner: Sendable {
item.heldBack = .signInPlugIn
return (entry.identifier, item)
}
- guard item.requiresPrivileges, item.leftAlone == nil, reach.isBeyond(item.url) else { return entry }
- item.isLeftForAnAdministrator = item.heldBack == nil
- item.heldBack = .beyondTheHelper
- return (entry.identifier, item)
+ return (entry.identifier, Self.holdingBack(item, beyond: reach))
}
let teams = Set(installedApps.compactMap(\.teamIdentifier))
let byPath: (SearchLocation, SearchLocation) -> Bool = {
@@ -173,15 +174,117 @@ public struct OrphanScanner: Sendable {
let (groups, apart) = Self.settingApart(
Self.group(kept, remembered: gone, installedTeams: teams, running: running)
)
+ let recorded = await recorded(
+ records,
+ listed: Set(kept.map { ItemKey($0.1.url) }),
+ installedApps: installedApps,
+ ownership: ownership,
+ reach: reach
+ )
return OrphanScan(
groups: groups,
unreadableLocations: unreadableLocations.sorted(by: byPath),
needsFullDiskAccess: unreadableLocations.contains { FullDiskAccess.canList($0.url) == .missing },
cutShortLocations: cutShortLocations.sorted(by: byPath),
- forAnAdministrator: apart
+ forAnAdministrator: (Self.claiming(apart, by: records) + recorded)
+ .sorted { Self.comesBefore($0.item, $1.item) }
)
}
+ /// What the scan set apart, each item an uninstall recorded with that uninstall's apps and claim, unless the claim
+ /// was only a hint, which says less than what the scan found itself.
+ static func claiming(
+ _ apart: [AdministratorItem],
+ by records: [LeftForAnAdministrator.Record]
+ ) -> [AdministratorItem] {
+ let byItem = LeftForAnAdministrator.Record.merged(records)
+ return apart.map { entry in
+ guard let record = byItem[ItemKey(entry.item.url)], record.confidence >= .likely else { return entry }
+ return AdministratorItem(
+ item: entry.item,
+ apps: record.apps.map(\.name),
+ claim: AdministratorItem.Claim(reason: record.reason, confidence: record.confidence)
+ )
+ }
+ }
+
+ /// What uninstalls left for an administrator that the scan didn't list, judged as the scan judges what it finds.
+ /// A record is a file any process can write, so only a place an uninstall searches counts, the guard every move
+ /// asks judges it too, and what one of Apple's packages installed is never listed.
+ private func recorded(
+ _ records: [LeftForAnAdministrator.Record],
+ listed: Set<ItemKey>,
+ installedApps: [InstalledApp],
+ ownership: AppOwnership,
+ reach: HelperReach
+ ) async -> [AdministratorItem] {
+ let home = environment.homeDirectory.path(percentEncoded: false)
+ let installed = Set(installedApps.map { $0.reference.lowercased() })
+ let merged = LeftForAnAdministrator.Record.merged(records)
+ var seen: Set<ItemKey> = []
+ let unlisted = records.compactMap { record -> LeftForAnAdministrator.Record? in
+ let item = ItemKey(URL(filePath: record.path))
+ guard !listed.contains(item), seen.insert(item).inserted else { return nil }
+ return merged[item]
+ }
+ let places = environment.locations.map { PathPattern.comparablePath(of: $0.url) }
+ let searched = unlisted.filter { record in
+ let path = PathPattern.comparablePath(of: URL(filePath: record.path))
+ return places.contains { PathComponents.isPath(path, inside: $0) }
+ }
+ let removalGuard = searched.isEmpty ? nil : RemovalGuard(environment: environment, exclusions: exclusions)
+ let homePath = PathPattern.comparablePath(of: environment.homeDirectory)
+ var candidates: [LeftForAnAdministrator.Record] = []
+ for record in searched where !Task.isCancelled {
+ let url = URL(filePath: record.path)
+ let name = url.lastPathComponent
+ let judged = !record.apps.contains { installed.contains($0.reference.lowercased()) }
+ && !record.apps.contains { exclusions.excludes(bundleIdentifier: $0.reference) }
+ && Self.isAFileAFolderOrALink(url) && !FileAccess.cannotBeRemoved(url)
+ && !ProtectedData.refuses(url.path(percentEncoded: false), home: home)
+ && !exclusions.excludes(url) && !exclusions.holds(url)
+ && !record.apps.contains { app in
+ let identifier = Identifier.isValid(app.reference)
+ ? app.reference : LeftoverMatcher.key(from: name, kind: record.kind)
+ return ownership.isClaimed(fileName: name, kind: record.kind, identifier: identifier)
+ }
+ && removalGuard?.refusal(of: url) == nil
+ guard judged else { continue }
+ let isInTheHome = PathComponents.isPath(PathPattern.comparablePath(of: url), atOrInside: homePath)
+ if !isInTheHome, await installedByApple(url) { continue }
+ candidates.append(record)
+ }
+ let walked = await candidates.concurrentMap(width: LeftoverScanner.concurrentMeasurements) { [walk] record in
+ await walk(URL(filePath: record.path))
+ }
+ return zip(candidates, walked).compactMap { record, contents in
+ let url = URL(filePath: record.path)
+ let item = Self.holdingBack(
+ Self.item(
+ at: url, kind: record.kind, contents: contents,
+ parent: ParentAccess(url.deletingLastPathComponent()), home: home
+ ),
+ beyond: reach
+ )
+ guard item.isLeftForAnAdministrator else { return nil }
+ return AdministratorItem(
+ item: item,
+ apps: record.apps.map(\.name),
+ claim: AdministratorItem.Claim(reason: record.reason, confidence: record.confidence)
+ )
+ }
+ }
+
+ /// The item held back as `beyondTheHelper` when it needs an administrator where the helper may not move it, and
+ /// left for an administrator when nothing else held it back.
+ static func holdingBack(_ item: OrphanItem, beyond reach: HelperReach) -> OrphanItem {
+ guard item.requiresPrivileges, item.leftAlone == nil, reach.isBeyond(item.url) else { return item }
+ var item = item
+ item.isLeftForAnAdministrator = item.heldBack == nil
+ item.heldBack = .beyondTheHelper
+ return item
+ }
+
/// Takes out of `groups` what only an administrator can move, each with the app it was found for. A group Peel is
/// unsure of keeps its own, since something may still use them, and a group left empty goes.
static func settingApart(_ groups: [OrphanGroup]) -> (groups: [OrphanGroup], apart: [AdministratorItem]) {
@@ -201,7 +304,7 @@ public struct OrphanScanner: Sendable {
confidence: group.confidence
)
}
- return (kept, apart.sorted { comesBefore($0.item, $1.item) })
+ return (kept, apart)
}
/// The order a list of orphaned items keeps: the largest first, what could not be measured before all, then by
@@ -618,44 +721,14 @@ public struct OrphanScanner: Sendable {
let walked = await candidates.map(\.url).concurrentMap(width: LeftoverScanner.concurrentMeasurements) {
await walk($0)
}
- var found: [(identifier: String, item: OrphanItem)] = []
- for (candidate, contents) in zip(candidates, walked) {
- let url = candidate.url
- // The item's own date changes when something is taken out of it, but not when a file inside is
- // rewritten in place, so the newest date inside comes from the walk.
- let own = try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
- let path = url.path(percentEncoded: false)
- let heldBack: HoldBack? = if location.kind == .containers, ProtectedData.holdsAContainersDocuments(path) {
- .holdsDocuments
- } else if ProtectedData.holds(path, home: home) || ProtectedData.holdsABrowserWallet(path) {
- .holdsKeys
- } else if ProtectedData.holdsALibrary(path) {
- .holdsALibrary
- } else if ProtectedData.holdsWorkKeptInACache(path) {
- .holdsWorkKeptInACache
- } else if let keptOnlyHere = KeptOnlyHere.reason(for: path, home: home) {
- keptOnlyHere
- } else if candidate.folder?.holdsWork(at: url) == true {
- .holdsWorkMadeWithTheApp
- } else if location.kind == .logs, CrashReport.isOne(url) {
- .crashReport
- } else {
- // `/Users/Shared` belongs to every account on the Mac, and the other accounts' apps are not known here.
- HoldBack.seen(in: contents) ?? (location.kind == .sharedFolder ? .sharedWithEveryone : nil)
- ?? (candidate.namedAfter != nil ? .namedLikeTheApp : nil)
- }
- let item = OrphanItem(
- url: url,
- kind: location.kind,
- size: contents.flatMap { $0.couldNotBeRead ? nil : $0.size },
- modificationDate: [own, contents?.newestChange].compactMap(\.self).max(),
- requiresPrivileges: candidate.parent.requiresPrivileges(toRemove: url),
- heldBack: heldBack,
- namedAfter: candidate.namedAfter,
- holdsDamagedSettings: location.kind == .preferences && PreferenceFile.isDamaged(url),
- productFolder: candidate.folder
+ let found = zip(candidates, walked).map { candidate, contents in
+ (
+ identifier: candidate.identifier,
+ item: item(
+ at: candidate.url, kind: location.kind, contents: contents, parent: candidate.parent, home: home,
+ namedAfter: candidate.namedAfter, folder: candidate.folder
+ )
)
- found.append((candidate.identifier, item))
}
return .found(
found,
@@ -663,6 +736,53 @@ public struct OrphanScanner: Sendable {
unreadable: inside.unreadable.map { SearchLocation(kind: location.kind, url: $0) }
)
}
+
+ /// The orphaned item at `url`, with its size and newest write from its walk, held back for what it holds, where
+ /// it is, and what its walk saw.
+ private static func item(
+ at url: URL,
+ kind: SearchLocation.Kind,
+ contents: FolderContents?,
+ parent: ParentAccess,
+ home: String,
+ namedAfter: String? = nil,
+ folder: ProductFolder? = nil
+ ) -> OrphanItem {
+ // The item's own date changes when something is taken out of it, but not when a file inside is
+ // rewritten in place, so the newest date inside comes from the walk.
+ let own = try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
+ let path = url.path(percentEncoded: false)
+ let heldBack: HoldBack? = if kind == .containers, ProtectedData.holdsAContainersDocuments(path) {
+ .holdsDocuments
+ } else if ProtectedData.holds(path, home: home) || ProtectedData.holdsABrowserWallet(path) {
+ .holdsKeys
+ } else if ProtectedData.holdsALibrary(path) {
+ .holdsALibrary
+ } else if ProtectedData.holdsWorkKeptInACache(path) {
+ .holdsWorkKeptInACache
+ } else if let keptOnlyHere = KeptOnlyHere.reason(for: path, home: home) {
+ keptOnlyHere
+ } else if folder?.holdsWork(at: url) == true {
+ .holdsWorkMadeWithTheApp
+ } else if kind == .logs, CrashReport.isOne(url) {
+ .crashReport
+ } else {
+ // `/Users/Shared` belongs to every account on the Mac, and the other accounts' apps are not known here.
+ HoldBack.seen(in: contents) ?? (kind == .sharedFolder ? .sharedWithEveryone : nil)
+ ?? (namedAfter != nil ? .namedLikeTheApp : nil)
+ }
+ return OrphanItem(
+ url: url,
+ kind: kind,
+ size: contents.flatMap { $0.couldNotBeRead ? nil : $0.size },
+ modificationDate: [own, contents?.newestChange].compactMap(\.self).max(),
+ requiresPrivileges: parent.requiresPrivileges(toRemove: url),
+ heldBack: heldBack,
+ namedAfter: namedAfter,
+ holdsDamagedSettings: kind == .preferences && PreferenceFile.isDamaged(url),
+ productFolder: folder
+ )
+ }
}
/// The folders the product files of apps Peel saw go named for their data, by where they are. A folder an installed
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift b/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift
index efb93eab..0923dab5 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift
@@ -23,6 +23,8 @@ public struct BulkUninstallation: Sendable {
public var isMeasured = true
/// Needs administrator rights, and the helper may not move it. Shown, never selected, never moved.
public var isBeyondTheHelper = false
+ /// Only an administrator can move it, and nothing else holds it back, for every chosen app it belongs to.
+ public var isLeftForAnAdministrator = false
/// How an app removed elsewhere is removed instead, for it and its files: Peel by Remove Peel, an agent by its
/// maker's uninstaller. Shown, never selected, never moved.
public var removedElsewhere: RemovedElsewhere?
@@ -186,6 +188,31 @@ public struct BulkUninstallation: Sendable {
)
}
+ /// What stays for an administrator once the apps are gone, by one app's rule (`Uninstallation`), used by no app
+ /// outside the selection, and only once every chosen copy of each app it belongs to is gone.
+ public func leftForAnAdministrator(after result: TrashResult) -> [LeftForAnAdministrator.Record] {
+ let moved = Set(result.trashed.map(\.originalURL))
+ let staying = Set(
+ uninstallations.filter { !$0.isAppInTheTrash && !moved.contains($0.app.url) }.map(\.app.reference)
+ )
+ let names = Dictionary(
+ uninstallations.map { ($0.app.reference, $0.app.name) },
+ uniquingKeysWith: { first, _ in first }
+ )
+ return items.compactMap { item in
+ guard item.isLeftForAnAdministrator, let kind = item.kind, kind != .elsewhere, let match = item.match,
+ item.sharedWithOthers.isEmpty, item.otherCopies.isEmpty, !item.apps.contains(where: staying.contains)
+ else { return nil }
+ return LeftForAnAdministrator.Record(
+ path: PathPattern.comparablePath(of: item.url),
+ kind: kind,
+ apps: item.apps.map { .init(reference: $0, name: names[$0] ?? $0) },
+ reason: match.reason,
+ confidence: match.confidence
+ )
+ }
+ }
+
/// The chosen apps that stayed while files of their own were selected, which then stayed with them.
public func appsThatKeptTheirFiles(after result: TrashResult, selection: Set<URL>) -> [InstalledApp] {
let failed = Set(result.failures.map(\.url))
@@ -229,6 +256,7 @@ public struct BulkUninstallation: Sendable {
isKeptByMacOS: existing.isKeptByMacOS || item.isKeptByMacOS,
isMeasured: existing.isMeasured || item.isMeasured,
isBeyondTheHelper: existing.isBeyondTheHelper || item.isBeyondTheHelper,
+ isLeftForAnAdministrator: existing.isLeftForAnAdministrator && item.isLeftForAnAdministrator,
removedElsewhere: existing.removedElsewhere ?? item.removedElsewhere,
isInTheTrash: existing.isInTheTrash || item.isInTheTrash,
enclosingPackage: existing.enclosingPackage ?? item.enclosingPackage,
@@ -260,6 +288,7 @@ public struct BulkUninstallation: Sendable {
isKeptByMacOS: uninstallation.app.isSystemProtected,
isMeasured: leftover.isMeasured,
isBeyondTheHelper: leftover.match.heldBack == .beyondTheHelper,
+ isLeftForAnAdministrator: leftover.isLeftForAnAdministrator,
removedElsewhere: uninstallation.removedElsewhere,
holdsDamagedSettings: leftover.holdsDamagedSettings
))
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift
index 6ac3d626..8034ec16 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift
@@ -431,6 +431,26 @@ public struct Uninstallation: Sendable {
MakersFolders.names(of: [app])
}
+ /// The leftovers that stay for an administrator once the app is gone: nothing else holds them back or uses them,
+ /// and each sits where an uninstall searches, the only places Orphaned Files believes a record of.
+ public var leftForAnAdministrator: [Leftover] {
+ scan.leftovers.filter { $0.isLeftForAnAdministrator && !$0.match.isShared && $0.kind != .elsewhere }
+ }
+
+ /// What to remember of `leftForAnAdministrator` once the app is gone, moved by `result` or already in the Trash.
+ public func leftForAnAdministrator(after result: TrashResult) -> [LeftForAnAdministrator.Record] {
+ guard isAppInTheTrash || result.trashed.contains(where: { $0.originalURL == app.url }) else { return [] }
+ return leftForAnAdministrator.map { leftover in
+ LeftForAnAdministrator.Record(
+ path: PathPattern.comparablePath(of: leftover.url),
+ kind: leftover.kind,
+ apps: [.init(reference: app.reference, name: app.name)],
+ reason: leftover.match.reason,
+ confidence: leftover.match.confidence
+ )
+ }
+ }
+
/// Whether the app stayed while files of its own were selected, which then stayed with it.
public func keptItsFiles(after result: TrashResult, selection: Set<URL>) -> Bool {
selection.contains(app.url) && result.failures.contains { $0.url == app.url }
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/BulkUninstallationTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/BulkUninstallationTests.swift
index 3e8292f9..7fba6b5d 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/BulkUninstallationTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/BulkUninstallationTests.swift
@@ -32,6 +32,37 @@ struct BulkUninstallationTests {
)
}
+ @Test func leavesForAnAdministratorWhatOnlyAppsThatWentUsed() {
+ let synth = app("org.example.synth", "Synth")
+ let effects = app("org.example.synth-fx", "Synth Effects")
+ let other = app("org.example.other", "Other")
+ func beyond(_ path: String, sharedWith: [String] = []) -> Leftover {
+ var leftover = leftover(path, size: 10, sharedWith: sharedWith).heldBack(.beyondTheHelper)
+ leftover.isLeftForAnAdministrator = true
+ return leftover
+ }
+ let shared = "/Library/Example Audio/Shared"
+ let own = "/Library/Example Audio/Synth"
+ let used = "/Library/Example Audio/Used"
+ let bulk = BulkUninstallation(uninstallations: [
+ uninstallation(synth, [
+ beyond(shared, sharedWith: [effects.reference]),
+ beyond(own),
+ beyond(used, sharedWith: [other.reference]),
+ ]),
+ uninstallation(effects, [beyond(shared, sharedWith: [synth.reference])]),
+ ])
+ let moved = { (apps: [InstalledApp]) in
+ TrashResult(trashed: apps.map { TrashedItem(originalURL: $0.url, trashedURL: $0.url, date: .now) })
+ }
+
+ let both = bulk.leftForAnAdministrator(after: moved([synth, effects]))
+ #expect(Set(both.map(\.path)) == [shared, own])
+ #expect(both.first { $0.path == shared }?.apps.map(\.name) == ["Synth", "Synth Effects"])
+ #expect(bulk.leftForAnAdministrator(after: moved([synth])).map(\.path) == [own])
+ #expect(bulk.leftForAnAdministrator(after: TrashResult()).isEmpty)
+ }
+
@Test func anAppsBundleSaysItSharesItsStorage() {
let clone = app("org.example.clone", "Clone")
let own = app("org.example.own", "Own")
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift
index e17a9f4c..dcf9b3d3 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/CommandLineTests.swift
@@ -622,6 +622,35 @@ struct CommandLineTests {
#expect(notes[4] == "1 file needs review and will stay. See it with `peel leftovers Editor --all`.")
}
+ @Test func saysWhereWhatOnlyAnAdministratorCanMoveIsListed() throws {
+ let app = InstalledApp(url: URL(filePath: "/Applications/Editor.app", directoryHint: .isDirectory), bundleIdentifier: "com.example.editor", name: "Editor")
+ func beyond(_ path: String, sharedWith: [String] = []) -> Leftover {
+ var item = leftover(
+ URL(filePath: path), sharedWith: sharedWith, heldBack: .beyondTheHelper, requiresPrivileges: true
+ )
+ item.isLeftForAnAdministrator = true
+ return item
+ }
+ let editor = uninstallation(app: app, leftovers: [beyond("/Library/Editor"), beyond("/Library/Acme", sharedWith: ["com.acme.other"])])
+ let plan = UninstallPlan.make(editor, keepLeftovers: false, refusal: { _ in nil })
+
+ #expect(plan.leftForAnAdministrator == 1)
+ #expect(plan.needsReview == 1)
+ let notes = UninstallCommand.whatStays(
+ plan, app: app, homebrew: CaskLookup.Answer(), scan: LeftoverScan(leftovers: [], unreadableLocations: [])
+ )
+ #expect(notes == [
+ "1 item needs an administrator, and Peel's helper isn't allowed to move it. Once Editor is in the Trash, Orphaned Files in the Peel app lists it under Needs an Administrator, with how to remove it.",
+ "1 file needs review and will stay. See it with `peel leftovers Editor --all`.",
+ ])
+ #expect(UninstallPlan.make(editor, keepLeftovers: true, refusal: { _ in nil }).leftForAnAdministrator == 1)
+ let json = try Output.jsonText(
+ UninstallCommand.report(app: app, plan: plan, result: nil, privacy: nil, unreadable: [])
+ )
+ let report = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])
+ #expect(report["leftForAnAdministrator"] as? Int == 1)
+ }
+
@Test func saysNothingWhenNothingWillStay() {
let app = InstalledApp(url: URL(filePath: "/Applications/Editor.app", directoryHint: .isDirectory), bundleIdentifier: "com.example.editor", name: "Editor")
let plan = UninstallPlan.make(
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift
index 33b5d9ca..24263cc9 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/FileCommandTests.swift
@@ -535,12 +535,24 @@ struct FileCommandTests {
@Test func listsApartWhatOnlyAnAdministratorCanMove() throws {
let directory = try TemporaryDirectory()
let item = try orphan("com.example.gone", in: directory, heldBack: .beyondTheHelper, requiresPrivileges: true)
+ let left = try orphan("com.example.left", in: directory, heldBack: .beyondTheHelper, requiresPrivileges: true)
+ let hinted = try orphan("com.example.hint", in: directory, heldBack: .beyondTheHelper, requiresPrivileges: true)
let scan = OrphanScan(
- groups: [], unreadableLocations: [], forAnAdministrator: [AdministratorItem(item: item, apps: ["Gone"])]
+ groups: [],
+ unreadableLocations: [],
+ forAnAdministrator: [
+ AdministratorItem(item: item, apps: ["Gone"]),
+ AdministratorItem(item: left, apps: ["Left"], claim: .init(reason: .bundleIdentifier, confidence: .certain)),
+ AdministratorItem(item: hinted, apps: ["Synth"], claim: .init(reason: .vendorPrefix, confidence: .possible)),
+ ]
)
- #expect(OrphansCommand.administratorHeading(for: scan) == "Needs an administrator 10 bytes")
- #expect(OrphansCommand.administratorRows(for: scan) == [["10 bytes", Output.path(item.url), "found for Gone"]])
+ #expect(OrphansCommand.administratorHeading(for: scan) == "Needs an administrator 30 bytes")
+ #expect(OrphansCommand.administratorRows(for: scan) == [
+ ["10 bytes", Output.path(item.url), "found for Gone"],
+ ["10 bytes", Output.path(left.url), "found for Left, bundle identifier"],
+ ["10 bytes", Output.path(hinted.url), "found for Synth, developer, review: possible match"],
+ ])
#expect(OrphansCommand.notes(for: scan) == [OrphansCommand.byHand])
let json = try Output.jsonText(OrphansCommand.report(for: scan))
let report = try #require(JSONSerialization.jsonObject(with: Data(json.utf8)) as? [String: Any])
@@ -548,6 +560,10 @@ struct FileCommandTests {
#expect(listed.first?["path"] as? String == Output.path(item.url))
#expect(listed.first?["size"] as? Int == 10)
#expect(listed.first?["apps"] as? [String] == ["Gone"])
+ #expect(listed.first?["reason"] is NSNull)
+ #expect(listed.first?["confidence"] is NSNull)
+ #expect(listed.last?["reason"] as? String == "vendorPrefix")
+ #expect(listed.last?["confidence"] as? String == "possible")
}
@Test func theOrphansListSaysWhereItStoppedLookingInsideFolders() {
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/InflectionMarkupTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/InflectionMarkupTests.swift
new file mode 100644
index 00000000..4a6e053b
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/InflectionMarkupTests.swift
@@ -0,0 +1,22 @@
+import Foundation
+import Testing
+
+struct InflectionMarkupTests {
+ @Test func noPlainLocalizedStringCarriesInflection() throws {
+ let call = "String(localized:"
+ let markup = "](inflect: true)"
+ let root = LineLengthTests.repository.path(percentEncoded: false)
+ var found: [String] = []
+ for file in try LineLengthTests.swiftFiles() {
+ let lines = try String(contentsOf: file, encoding: .utf8)
+ .split(separator: "\n", omittingEmptySubsequences: false)
+ for (index, line) in lines.enumerated() where !line.trimmingCharacters(in: .whitespaces).hasPrefix("//") {
+ let plain = line.replacingOccurrences(of: "Attributed" + call, with: "")
+ if plain.contains(call), plain.contains(markup) {
+ found.append("\(file.path(percentEncoded: false).dropFirst(root.count)):\(index + 1)")
+ }
+ }
+ }
+ #expect(found.isEmpty, "String(localized:) shows inflection markup as written; use String(inflecting:): \(found)")
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/LeftForAnAdministratorTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/LeftForAnAdministratorTests.swift
new file mode 100644
index 00000000..a0d37d6a
--- /dev/null
+++ b/Packages/PeelCore/Tests/PeelCoreTests/LeftForAnAdministratorTests.swift
@@ -0,0 +1,94 @@
+import Foundation
+@testable import PeelCore
+import Testing
+
+struct LeftForAnAdministratorTests {
+ private func record(
+ _ url: URL, app: String = "Scribbler", confidence: MatchConfidence = .certain
+ ) -> LeftForAnAdministrator.Record {
+ LeftForAnAdministrator.Record(
+ path: PathPattern.comparablePath(of: url),
+ kind: .library,
+ apps: [.init(reference: "org.example.\(app.lowercased())", name: app)],
+ reason: confidence == .possible ? .vendorPrefix : .bundleIdentifier,
+ confidence: confidence
+ )
+ }
+
+ @Test func keepsWhatItIsGivenAndForgetsWhatIsGone() async throws {
+ let directory = try TemporaryDirectory()
+ let memory = LeftForAnAdministrator(url: directory.url.appending(path: "left.json"))
+ let kept = try directory.directory("root/Library/org.example.kept")
+ let removed = try directory.directory("root/Library/org.example.removed")
+
+ await memory.record([record(kept), record(removed)])
+ #expect(await memory.load() == [record(kept), record(removed)])
+
+ try FileManager.default.removeItem(at: removed)
+ let later = try directory.directory("root/Library/org.example.later")
+ await memory.record([record(later)])
+
+ #expect(await memory.load() == [record(kept), record(later)])
+ }
+
+ @Test func theRecordsOfOneItemBecomeOneKeepingTheSurerClaim() async throws {
+ let directory = try TemporaryDirectory()
+ let memory = LeftForAnAdministrator(url: directory.url.appending(path: "left.json"))
+ let shared = try directory.directory("root/Library/org.example.shared")
+ let first = record(shared, app: "First")
+ let spelledElsewhere = LeftForAnAdministrator.Record(
+ path: "/private" + first.path, kind: first.kind, apps: first.apps, reason: first.reason,
+ confidence: first.confidence
+ )
+ #expect(first.path.hasPrefix("/var/"), "the temporary folder is not under /var, so /private names it no other way")
+ let sure = try directory.directory("root/Library/org.example.sure")
+ let hinted = try directory.directory("root/Library/org.example.hinted")
+
+ await memory.record([spelledElsewhere, record(sure, app: "Sure"), record(hinted, app: "Hint", confidence: .possible)])
+ await memory.record([
+ record(shared, app: "Second"), record(sure, app: "Hint", confidence: .possible), record(hinted, app: "Sure"),
+ ])
+
+ let loaded = await memory.load()
+ #expect(loaded.count == 3)
+ #expect(loaded.first { $0.path.hasSuffix("org.example.shared") }?.apps.map(\.name) == ["First", "Second"])
+ #expect(loaded.first { $0.path.hasSuffix("org.example.sure") } == record(sure, app: "Sure"))
+ #expect(loaded.first { $0.path.hasSuffix("org.example.hinted") } == record(hinted, app: "Sure"))
+ }
+
+ @Test func readingLeavesAHomeAsItFoundIt() async throws {
+ let directory = try TemporaryDirectory()
+ let url = directory.url.appending(path: "Peel/left.json")
+
+ #expect(await LeftForAnAdministrator(url: url).load().isEmpty)
+ #expect(url.deletingLastPathComponent().isMissing)
+ }
+
+ @Test(.permissionsHold) func leavesAFileItCannotReadAlone() async throws {
+ let directory = try TemporaryDirectory()
+ let url = directory.url.appending(path: "left.json")
+ let memory = LeftForAnAdministrator(url: url)
+ await memory.record([record(try directory.directory("root/Library/org.example.one"))])
+ let before = try Data(contentsOf: url)
+ try directory.setPermissions(0o000, of: "left.json")
+ defer { try? directory.setPermissions(0o644, of: "left.json") }
+
+ await memory.record([record(try directory.directory("root/Library/org.example.two"))])
+
+ try directory.setPermissions(0o644, of: "left.json")
+ #expect(try Data(contentsOf: url) == before, "a file that could not be read was written over")
+ }
+
+ @Test func aDamagedFileIsSetAsideAndWhatCanBeReadOfItKept() async throws {
+ let directory = try TemporaryDirectory()
+ let url = directory.url.appending(path: "left.json")
+ let folder = try directory.directory("root/Library/org.example.one")
+ let encoder = JSONEncoder()
+ let good = try #require(String(data: try encoder.encode(record(folder)), encoding: .utf8))
+ try Data("[\(good), {\"path\": 7}]".utf8).write(to: url)
+
+ #expect(await LeftForAnAdministrator(url: url).load() == [record(folder)])
+ let set = try FileManager.default.contentsOfDirectory(atPath: directory.url.path(percentEncoded: false))
+ #expect(set.contains { $0.contains("damaged") }, "the file as it was is not kept: \(set)")
+ }
+}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift
index f67a6f30..4f9d667d 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/OrphanScannerTests.swift
@@ -32,6 +32,37 @@ struct OrphanScannerTests {
#expect(stop.askedAfter == 0)
}
+ @Test func aScanStoppedWhileMeasuringWhatAnUninstallLeftStops() async throws {
+ let directory = try TemporaryDirectory()
+ let left = try directory.directory("root/Library/Example Audio/Gone")
+ let environment = SearchEnvironment(
+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),
+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory),
+ userCacheDirectory: directory.url.appending(path: "var/C", directoryHint: .isDirectory),
+ userTemporaryDirectory: directory.url.appending(path: "var/T", directoryHint: .isDirectory)
+ )
+ let unanswered = Unanswered()
+ let scanner = OrphanScanner(
+ environment: environment,
+ isRegisteredApp: { _ in false },
+ systemApps: [],
+ walk: unanswered.walk,
+ installedByApple: { _ in false }
+ )
+ let record = LeftForAnAdministrator.Record(
+ path: PathPattern.comparablePath(of: left), kind: .library,
+ apps: [.init(reference: "org.example.gone", name: "Gone")], reason: .bundleIdentifier, confidence: .certain
+ )
+
+ let stop = try await unanswered.stop {
+ _ = await scanner.scan(installedApps: [], leftForAnAdministrator: [record])
+ }
+
+ #expect(stop.took < .seconds(1))
+ #expect(stop.askedBefore == 1)
+ #expect(stop.askedAfter == 0)
+ }
+
/// Launch Services is asked about apps outside the scanned folders. It knows an app by its bundle identifier,
/// never by a group container's name, which has a team or `group.` in front.
@@ -363,6 +394,93 @@ struct OrphanScannerTests {
#expect(try item(beyond).leftAlone == .beyondTheHelper)
}
+ @Test(.permissionsHold) func listsWhatAnUninstallLeftForAnAdministrator() async throws {
+ let directory = try TemporaryDirectory()
+ let left = try directory.directory("root/Library/Example Audio/Hexachord")
+ let hinted = try directory.directory("root/Library/Example Audio/Updater")
+ let found = try directory.directory("root/Library/org.example.hexachord")
+ let tritone = try directory.directory("root/Library/org.example.tritone")
+ let back = try directory.directory("root/Library/Example Audio/Reinstalled")
+ let claimed = try directory.directory("root/Library/Example Audio/Installed")
+ let excluded = try directory.directory("root/Library/Example Audio/Excluded")
+ let apples = try directory.directory("root/Library/Example Audio/Apples")
+ let outside = try directory.directory("root/opt/org.example.hexachord")
+ let missing = directory.url.appending(path: "root/Library/Example Audio/Missing")
+ let locked = [left, hinted, found, tritone, back, claimed, excluded, apples, outside]
+ for folder in locked {
+ try directory.setPermissions(0o555, of: folder)
+ }
+ defer {
+ for folder in locked {
+ try? FileManager.default.setAttributes(
+ [.posixPermissions: 0o755],
+ ofItemAtPath: folder.path(percentEncoded: false)
+ )
+ }
+ }
+ let path = { (url: URL) in PathPattern.comparablePath(of: url) }
+ func record(
+ _ url: URL, app: String = "org.example.hexachord", name: String = "Hexachord",
+ confidence: MatchConfidence = .likely
+ ) -> LeftForAnAdministrator.Record {
+ LeftForAnAdministrator.Record(
+ path: path(url), kind: .library, apps: [.init(reference: app, name: name)], reason: .homebrewCask,
+ confidence: confidence
+ )
+ }
+ let hexachord = RememberedApp(
+ bundleIdentifier: "org.example.hexachord", name: "Hexachord", teamIdentifier: nil, lastSeen: .now,
+ lastPath: "/Applications/Hexachord.app"
+ )
+ let tritoneApp = RememberedApp(
+ bundleIdentifier: "org.example.tritone", name: "Tritone", teamIdentifier: nil, lastSeen: .now,
+ lastPath: "/Applications/Tritone.app"
+ )
+ let scanner = OrphanScanner(
+ environment: SearchEnvironment(
+ homeDirectory: directory.url.appending(path: "home", directoryHint: .isDirectory),
+ rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)
+ ),
+ exclusions: Exclusions(paths: [excluded]),
+ isRegisteredApp: { _ in false },
+ systemApps: [],
+ installedByApple: { [applesPath = path(apples)] in PathPattern.comparablePath(of: $0) == applesPath }
+ )
+
+ var spelledElsewhere = record(found)
+ spelledElsewhere = LeftForAnAdministrator.Record(
+ path: "/private" + path(found), kind: spelledElsewhere.kind, apps: spelledElsewhere.apps,
+ reason: spelledElsewhere.reason, confidence: spelledElsewhere.confidence
+ )
+ #expect(path(found).hasPrefix("/var/"), "the temporary folder is not under /var, so /private names it no other way")
+
+ let scan = await scanner.scan(
+ installedApps: installed,
+ remembered: [hexachord, tritoneApp],
+ leftForAnAdministrator: [
+ record(left), record(hinted, confidence: .possible), spelledElsewhere,
+ record(back, app: "com.installed.app", name: "Installed"), record(claimed), record(excluded),
+ record(missing), record(left), record(apples), record(outside), record(URL(filePath: "/private/etc/hosts")),
+ record(left, app: "org.example.other", name: "Other", confidence: .possible),
+ record(tritone, app: "org.example.other", name: "Other", confidence: .possible),
+ ]
+ )
+ let listed = Dictionary(
+ scan.forAnAdministrator.map { (path($0.item.url), $0) }, uniquingKeysWith: { first, _ in first }
+ )
+
+ #expect(scan.forAnAdministrator.count == 4)
+ #expect(Set(listed.keys) == [path(left), path(hinted), path(found), path(tritone)])
+ #expect(listed[path(left)]?.apps == ["Hexachord"])
+ #expect(listed[path(left)]?.claim == AdministratorItem.Claim(reason: .homebrewCask, confidence: .likely))
+ #expect(listed[path(hinted)]?.claim?.confidence == .possible)
+ #expect(listed[path(found)]?.claim != nil)
+ #expect(listed[path(tritone)]?.apps == ["Tritone"])
+ #expect(listed[path(tritone)]?.claim == nil)
+ #expect(listed.values.allSatisfy { $0.item.leftAlone == .beyondTheHelper })
+ #expect(!scan.groups.contains { $0.items.contains { path($0.url) == path(found) } })
+ }
+
@Test(.permissionsHold) func whatOnlyAnAdministratorCanMoveIsListedApart() async throws {
let directory = try TemporaryDirectory()
let beyond = try directory.directory("root/Library/com.gone.app")
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift
index 928c12de..2777d71a 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/UninstallationTests.swift
@@ -733,6 +733,73 @@ struct UninstallationTests {
}
}
+ @Test func leavesForAnAdministratorOnlyWhatSitsWhereAnUninstallSearches() {
+ var searched = leftover("com.example.app", requiresPrivileges: true).heldBack(.beyondTheHelper)
+ searched.isLeftForAnAdministrator = true
+ var elsewhere = Leftover(
+ url: URL(filePath: "/opt/example"),
+ kind: .elsewhere,
+ match: LeftoverMatch(reason: .homebrewCask, confidence: .likely, sharedWith: []),
+ size: 1,
+ isMeasured: true,
+ requiresPrivileges: true
+ ).heldBack(.beyondTheHelper)
+ elsewhere.isLeftForAnAdministrator = true
+
+ let plan = uninstallation(leftovers: [searched, elsewhere])
+
+ #expect(plan.leftForAnAdministrator.map(\.url) == [searched.url])
+ }
+
+ @Test(.permissionsHold) func whatOnlyAnAdministratorKeepsHereIsLeftForOneOnceTheAppIsGone() async throws {
+ let directory = try TemporaryDirectory()
+ let app = InstalledApp(url: directory.url.appending(path: "root/Applications/Scribbler.app"), bundleIdentifier: "com.example.scribbler", name: "Scribbler")
+ let served = try directory.directory("root/Library/Application Support/com.example.scribbler")
+ let named = try directory.directory("root/Library/Scribbler")
+ let identified = try directory.directory("root/Library/com.example.scribbler")
+ let coin = try directory.directory("root/Library/com.example.scribbler.coin")
+ try directory.file("root/Library/com.example.scribbler.coin/wallet.dat")
+ let locked = [served, named, identified, coin]
+ for folder in locked {
+ try directory.setPermissions(0o555, of: folder)
+ }
+ defer {
+ for folder in locked {
+ try? FileManager.default.setAttributes(
+ [.posixPermissions: 0o755],
+ ofItemAtPath: folder.path(percentEncoded: false)
+ )
+ }
+ }
+ let environment = SearchEnvironment(
+ homeDirectory: directory.url.appending(path: "home"),
+ rootDirectory: directory.url.appending(path: "root")
+ )
+
+ let plan = await Uninstallation.prepare(app, installedApps: [app], environment: environment)
+ func leftover(_ url: URL) throws -> Leftover {
+ try #require(
+ plan.scan.leftovers.first {
+ PathPattern.comparablePath(of: $0.url) == PathPattern.comparablePath(of: url)
+ }
+ )
+ }
+ let moved = TrashResult(trashed: [
+ TrashedItem(originalURL: app.url, trashedURL: directory.url.appending(path: "Trash/Scribbler.app"), date: .now),
+ ])
+
+ #expect(try leftover(identified).isLeftForAnAdministrator)
+ for url in [served, named, coin] {
+ #expect(try !leftover(url).isLeftForAnAdministrator, "\(url.lastPathComponent)")
+ }
+ #expect(plan.leftForAnAdministrator(after: TrashResult()).isEmpty)
+ let records = plan.leftForAnAdministrator(after: moved)
+ #expect(records.map(\.path) == [PathPattern.comparablePath(of: identified)])
+ #expect(records.first?.apps == [.init(reference: "com.example.scribbler", name: "Scribbler")])
+ #expect(records.first?.kind == .library)
+ #expect(records.first?.confidence == .certain)
+ }
+
/// Many casks name `/Applications/<Name>.app` among what they delete. The app's URL ends in a slash and the
/// cask's path does not, so they are compared as paths, and the app is never listed as its own leftover.
@Test func doesNotListTheAppAsItsOwnLeftover() async throws {
diff --git a/Peel/Model/OrphanLibrary.swift b/Peel/Model/OrphanLibrary.swift
index 85c6051c..fbc5b5eb 100644
--- a/Peel/Model/OrphanLibrary.swift
+++ b/Peel/Model/OrphanLibrary.swift
@@ -61,8 +61,13 @@ final class OrphanLibrary {
// What is currently running is better evidence than anything worked out from what is installed: a
// helper or an agent can keep a folder that no app bundle claims.
let running = Set(NSWorkspace.shared.runningApplications.compactMap(\.bundleIdentifier))
- return await OrphanScanner(exclusions: ExclusionsStore.shared.exclusions)
- .scan(installedApps: installedApps, remembered: remembered, running: running, owners: owners)
+ return await OrphanScanner(exclusions: ExclusionsStore.shared.exclusions).scan(
+ installedApps: installedApps,
+ remembered: remembered,
+ running: running,
+ owners: owners,
+ leftForAnAdministrator: await LeftForAnAdministrator().load()
+ )
}), library.unreadable.isEmpty else { return }
let remainingURLs = Set(result.groups.flatMap(\.items).filter { $0.leftAlone == nil }.map(\.url))
scan = result
diff --git a/Peel/Model/RemovalOutcome.swift b/Peel/Model/RemovalOutcome.swift
index e3fab8d5..6bd76bd6 100644
--- a/Peel/Model/RemovalOutcome.swift
+++ b/Peel/Model/RemovalOutcome.swift
@@ -23,22 +23,25 @@ final class RemovalOutcome {
private(set) var driversAwaitingARestart: [String] = []
/// The apps that moved whose background items macOS still starts at login from the Trash (`TrashResult`).
private(set) var appsStartingFromTheTrash: [String] = []
+ /// How many of the items the removal left stay for an administrator, which Orphaned Files lists.
+ private(set) var leftForAnAdministrator = 0
private(set) var movedCount = 0
var isEmpty: Bool {
failures.isEmpty && privacy.isEmpty && appsToQuit.isEmpty && driversAwaitingARestart.isEmpty
- && appsStartingFromTheTrash.isEmpty
+ && appsStartingFromTheTrash.isEmpty && leftForAnAdministrator == 0
}
- /// Keeps what the removal could not do, and what a restart or an emptied Trash finishes, for the alert.
- /// `privacy` is every reset the removal ran, and `PrivacyReset.worthTelling` picks which of them to tell. A
- /// removal with nothing to tell changes nothing.
+ /// Keeps what the removal could not do, what a restart or an emptied Trash finishes, and what stays for an
+ /// administrator, for the alert. `privacy` is every reset the removal ran, and `PrivacyReset.worthTelling` picks
+ /// which of them to tell. A removal with nothing to tell changes nothing.
func report(
_ result: TrashResult,
privacy resets: [(app: InstalledApp, result: PrivacyReset.Result)] = [],
appsToQuit: [String] = [],
keptTheirFiles: [String] = [],
- startingFromTheTrash: [String] = []
+ startingFromTheTrash: [String] = [],
+ leftForAnAdministrator: Int = 0
) {
let privacy = PrivacyReset.worthTelling(resets, after: result).map {
Privacy(app: $0.app.name, result: $0.result)
@@ -46,7 +49,7 @@ final class RemovalOutcome {
let drivers = AudioDrivers.awaitingARestart(after: result)
guard
!result.failures.isEmpty || !privacy.isEmpty || !appsToQuit.isEmpty || !drivers.isEmpty
- || !startingFromTheTrash.isEmpty
+ || !startingFromTheTrash.isEmpty || leftForAnAdministrator > 0
else { return }
failures = result.failures
movedCount = result.trashed.count
@@ -54,6 +57,7 @@ final class RemovalOutcome {
self.appsToQuit = appsToQuit
self.keptTheirFiles = keptTheirFiles
driversAwaitingARestart = drivers
+ self.leftForAnAdministrator = leftForAnAdministrator
// Two copies of an app share its name and its background items.
var named: Set<String> = []
appsStartingFromTheTrash = startingFromTheTrash.filter { named.insert($0).inserted }
@@ -67,5 +71,6 @@ final class RemovalOutcome {
keptTheirFiles = []
driversAwaitingARestart = []
appsStartingFromTheTrash = []
+ leftForAnAdministrator = 0
}
}
diff --git a/Peel/Views/AppDetailView.swift b/Peel/Views/AppDetailView.swift
index ca99a742..43e867a2 100644
--- a/Peel/Views/AppDetailView.swift
+++ b/Peel/Views/AppDetailView.swift
@@ -482,11 +482,14 @@ struct AppDetailView: View {
let privacy = await PrivacyReset.reset(resetting(request.urls), beforeMovingWith: service)
let result = await plan.move(request)
let keptItsFiles = plan.uninstallation?.keptItsFiles(after: result, selection: request.urls) == true
+ let left = plan.uninstallation?.leftForAnAdministrator(after: result) ?? []
+ await LeftForAnAdministrator().record(left)
outcome.report(
result,
privacy: privacy,
keptTheirFiles: keptItsFiles ? [plan.app.name] : [],
- startingFromTheTrash: result.startsFromTheTrash.contains(plan.app.url) ? [plan.app.name] : []
+ startingFromTheTrash: result.startsFromTheTrash.contains(plan.app.url) ? [plan.app.name] : [],
+ leftForAnAdministrator: left.count
)
if plan.removesDockTile, result.trashed.contains(where: { $0.originalURL == plan.app.url }) {
_ = await DockTiles().takeOut([plan.app.url])
diff --git a/Peel/Views/MultipleAppsView.swift b/Peel/Views/MultipleAppsView.swift
index d375060f..2960a53d 100644
--- a/Peel/Views/MultipleAppsView.swift
+++ b/Peel/Views/MultipleAppsView.swift
@@ -358,11 +358,14 @@ struct MultipleAppsView: View {
let privacy = await PrivacyReset.reset(resetting(request.urls), beforeMovingWith: service)
let result = await plan.move(request)
let kept = plan.bulk?.appsThatKeptTheirFiles(after: result, selection: request.urls) ?? []
+ let left = plan.bulk?.leftForAnAdministrator(after: result) ?? []
+ await LeftForAnAdministrator().record(left)
outcome.report(
result,
privacy: privacy,
keptTheirFiles: kept.map(\.name),
- startingFromTheTrash: plan.apps.filter { result.startsFromTheTrash.contains($0.url) }.map(\.name)
+ startingFromTheTrash: plan.apps.filter { result.startsFromTheTrash.contains($0.url) }.map(\.name),
+ leftForAnAdministrator: left.count
)
if plan.removesDockTiles {
let moved = Set(result.trashed.map(\.originalURL))
diff --git a/Peel/Views/Orphans/AdministratorItemsView.swift b/Peel/Views/Orphans/AdministratorItemsView.swift
index ab0f4352..b1171778 100644
--- a/Peel/Views/Orphans/AdministratorItemsView.swift
+++ b/Peel/Views/Orphans/AdministratorItemsView.swift
@@ -24,9 +24,9 @@ struct AdministratorItemsView: View {
RemovalRow(
url: entry.item.url,
icon: .symbol(entry.item.kind.symbolName),
- detail: nil,
+ detail: entry.claim?.reason.title,
kind: entry.item.kind.title,
- warning: String(localized: HoldBack.beyondTheHelper.explanation),
+ warning: warning(for: entry),
lastWritten: entry.item.modificationDate,
foundFor: entry.apps.formatted(.list(type: .and)),
size: entry.item.size ?? 0,
@@ -52,6 +52,13 @@ struct AdministratorItemsView: View {
.toolbar(removing: .title)
}
+ private func warning(for entry: AdministratorItem) -> String {
+ let why = String(localized: HoldBack.beyondTheHelper.explanation)
+ guard entry.claim?.confidence == .possible else { return why }
+ let apps = entry.apps.formatted(.list(type: .and))
+ return why + "\n\n" + String(localized: "Peel isn’t sure only \(apps) used this. Check it before you remove it.")
+ }
+
private var header: some View {
PageHeader(systemImage: "lock.shield") {
Text("Needs an Administrator")
diff --git a/Peel/Views/RemovalFailureAlert.swift b/Peel/Views/RemovalFailureAlert.swift
index 96743934..ed96495c 100644
--- a/Peel/Views/RemovalFailureAlert.swift
+++ b/Peel/Views/RemovalFailureAlert.swift
@@ -5,13 +5,14 @@ import SwiftUI
/// The alert every tool shows when a removal fails for some items: which ones, and why, with a button that
/// fixes the cause when there is one. It also reports the privacy resets worth telling about, the audio drivers that
-/// wait for a restart, and on macOS 27 the background items macOS still starts from the Trash, since two alerts cannot
-/// be up at once.
+/// wait for a restart, what stays for an administrator, and on macOS 27 the background items macOS still starts from
+/// the Trash, since two alerts cannot be up at once.
struct RemovalFailureAlert: ViewModifier {
/// How many items the alert lists by path. The rest are only counted, to keep the alert short.
static let mostListed = 4
@Environment(RemovalOutcome.self) private var outcome
+ @Environment(OrphanLibrary.self) private var orphans
@Environment(\.openSettings) private var openSettings
func body(content: Content) -> some View {
@@ -25,6 +26,12 @@ struct RemovalFailureAlert: ViewModifier {
if #available(macOS 27, *), !outcome.appsStartingFromTheTrash.isEmpty {
Button("Open Login Items & Extensions") { SMAppService.openSystemSettingsLoginItems() }
}
+ if outcome.leftForAnAdministrator > 0 {
+ Button("Open Orphaned Files") {
+ orphans.selection = .forAnAdministrator
+ Navigator.shared.requestedTool = .orphans
+ }
+ }
if !outcome.failures.isEmpty {
Button("Copy Details") { copyDetails() }
}
@@ -51,6 +58,10 @@ struct RemovalFailureAlert: ViewModifier {
? Text("Empty the Trash to finish.")
: Text("Restart your Mac and empty the Trash to finish.")
}
+ if outcome.failures.isEmpty, outcome.appsToQuit.isEmpty, outcome.privacy.isEmpty,
+ outcome.driversAwaitingARestart.isEmpty, outcome.leftForAnAdministrator > 0 {
+ return Text("Some items stayed for an administrator.")
+ }
if outcome.failures.isEmpty, outcome.appsToQuit.isEmpty, outcome.privacy.isEmpty {
return Text("Restart your Mac to finish.")
}
@@ -67,13 +78,21 @@ struct RemovalFailureAlert: ViewModifier {
if rest > 0 {
lines.append(String(inflecting: "And ^[\(rest) more item](inflect: true)."))
}
- lines += keptLines + driverLines + extraLines
+ lines += keptLines + driverLines + administratorLines + extraLines
if #available(macOS 27, *) {
lines += trashLines
}
return lines.joined(separator: "\n\n")
}
+ private var administratorLines: [String] {
+ let count = outcome.leftForAnAdministrator
+ guard count > 0 else { return [] }
+ return count == 1
+ ? [String(localized: "One item stayed because only an administrator can move it, and Peel’s helper isn’t allowed to. Orphaned Files lists it under Needs an Administrator, with how to remove it.")]
+ : [String(inflecting: "^[\(count) item](inflect: true) stayed because only an administrator can move them, and Peel’s helper isn’t allowed to. Orphaned Files lists them under Needs an Administrator, with how to remove them.")]
+ }
+
private var driverLines: [String] {
let drivers = outcome.driversAwaitingARestart
guard !drivers.isEmpty else { return [] }
@@ -109,7 +128,7 @@ struct RemovalFailureAlert: ViewModifier {
/// selected.
private func copyDetails() {
var lines = quitLines + outcome.failures.map { "\($0.url.path(percentEncoded: false))\n\($0.reason.explanation)" }
- + keptLines + driverLines + extraLines
+ + keptLines + driverLines + administratorLines + extraLines
if #available(macOS 27, *) {
lines += trashLines
}
diff --git a/SAFETY.md b/SAFETY.md
index 158c5925..d4d5c2ed 100644
--- a/SAFETY.md
+++ b/SAFETY.md
@@ -576,4 +576,6 @@ and it fails closed.
takes back only what is still owned by root and writable by nobody else.
If you never install the helper, Peel still works; it just cannot touch what needs administrator rights.
-Home lists the helper as required for that reason, and keeps a reminder there until it is installed.
+Home lists the helper as required for that reason, and keeps a reminder there until it is installed. What needs an
+administrator outside the folders the helper serves, Peel leaves where it is: Orphaned Files lists it under Needs an
+Administrator, what an uninstall left there included, with how to remove it yourself in Finder.