Skip to content

armgit / peel

Public Imported from GitHub
0

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

Say why Put Back stays when an item or its folder is locked

Țugui Dragoș661756d5f18a
diff --git a/Localization/Peel/Localizable.xcstrings b/Localization/Peel/Localizable.xcstrings
index db19408d..7db95d80 100644
--- a/Localization/Peel/Localizable.xcstrings
+++ b/Localization/Peel/Localizable.xcstrings
@@ -170452,6 +170452,112 @@
}
}
},
+ "The folder it goes back to is locked. In Finder, choose File > Get Info for that folder and deselect Locked, then try again." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Složka, do které se to má vrátit, je zamčená. Ve Finderu pro tuto složku zvolte Soubor > Informace, zrušte zaškrtnutí políčka Zamčeno a zkuste to znovu."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Der Ordner, in den es zurückgelegt wird, ist geschützt. Wähle im Finder für diesen Ordner „Ablage“ > „Informationen“, deaktiviere „Geschützt“ und versuche es dann erneut."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "La carpeta a la que vuelve está bloqueada. En el Finder, elige Archivo > Obtener información para esa carpeta, anula la selección de “Bloquear” y vuelve a intentarlo."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Le dossier où il doit retourner est verrouillé. Dans le Finder, choisissez Fichier > Lire les informations pour ce dossier, désélectionnez « Verrouillé », puis réessayez."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "La cartella in cui deve tornare è bloccata. Nel Finder, scegli File > Ottieni informazioni per quella cartella, deseleziona Bloccato e riprova."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "戻し先のフォルダがロックされています。Finderで、そのフォルダに対して“ファイル”>“情報を見る”と選択し、“ロック”を選択解除してから、やり直してください。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "되돌아갈 폴더가 잠겨 있습니다. Finder에서 해당 폴더에 대해 파일 > 정보 가져오기를 선택하고, ‘잠김’을 선택 해제한 다음 다시 시도하십시오."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "De map waarin het wordt teruggezet, is beveiligd. Kies in Finder Archief > Toon info voor die map, deselecteer 'Beveiligd' en probeer het opnieuw."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Folder, do którego ta rzecz ma wrócić, jest zablokowany. W Finderze wybierz dla tego folderu polecenie Plik > Informacje, usuń zaznaczenie pola Zablokowany i spróbuj ponownie."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "A pasta para onde ele volta está bloqueada. No Finder, selecione essa pasta, escolha Arquivo > Obter Informações, desmarque a opção “Bloqueado” e tente novamente."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Dosarul în care trebuie să revină este blocat. În Finder, alegeți Fișier > Obțineți informații pentru acel dosar și deselectați „Blocat”, apoi încercați din nou."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Папка, в которую возвращается объект, защищена. В Finder выберите «Файл» > «Свойства» для этой папки, снимите флажок «Защита», а затем повторите попытку."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Mappen som det ska tillbaka till är låst. Välj Arkiv > Visa info för den mappen i Finder, avmarkera Låst och försök sedan igen."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Geri döneceği klasör kilitli. Finder’da o klasör için Dosya > Bilgi Ver komutunu seçin, Kilitli onay kutusunun seçimini kaldırın ve yeniden deneyin."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Папку, куди його треба повернути, замкнено. У Finder виберіть Файл > Досьє для цієї папки, зніміть прапорець «Замкнено» і спробуйте ще раз."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "它要放回的文件夹已被锁定。请在“访达”中为该文件夹选取“文件”>“显示简介”,取消选择“已锁定”,然后重试。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "它要還原到的檔案夾已鎖定。請在Finder中選取該檔案夾並選擇「檔案」>「取得資訊」,取消勾選「已鎖定」,然後再試一次。"
+ }
+ }
+ }
+ },
"The folder it’s in couldn’t be found." : {
"localizations" : {
"cs" : {
@@ -220060,6 +220166,112 @@
}
}
},
+ "macOS lets Peel put back another developer’s app only with App Management. Allow Peel in System Settings > Privacy & Security > App Management, then try again." : {
+ "localizations" : {
+ "cs" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "Systém macOS dovolí Peelu vrátit zpět aplikaci jiného vývojáře jen s oprávněním Správa aplikací. Povolte Peel v Nastavení systému > Soukromí a zabezpečení > Správa aplikací a zkuste to znovu."
+ }
+ },
+ "de" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS lässt Peel die App eines anderen Entwicklers nur zurücklegen, wenn Peel unter „App-Verwaltung“ erlaubt ist. Erlaube Peel unter „Systemeinstellungen“ > „Datenschutz & Sicherheit“ > „App-Verwaltung“ und versuche es dann erneut."
+ }
+ },
+ "es" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS solo permite que Peel restaure la app de otro desarrollador con Gestión de las apps. Da permiso a Peel en Ajustes del Sistema > Privacidad y seguridad > Gestión de las apps y vuelve a intentarlo."
+ }
+ },
+ "fr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS ne laisse Peel remettre en place l’app d’un autre développeur qu’avec l’autorisation Gestion des apps. Autorisez Peel dans Réglages Système > Confidentialité et sécurité > Gestion des apps, puis réessayez."
+ }
+ },
+ "it" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS permette a Peel di ripristinare l’app di un’altra azienda di sviluppo solo se Peel è autorizzato in “Gestione app”. Autorizza Peel in Impostazioni di Sistema > Privacy e sicurezza > Gestione app, poi riprova."
+ }
+ },
+ "ja" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOSでは、Peelが“アプリ管理”で許可されている場合にのみ、ほかの開発元のアプリを戻すことができます。“システム設定”>“プライバシーとセキュリティ”>“アプリ管理”でPeelを許可してから、やり直してください。"
+ }
+ },
+ "ko" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS는 앱 관리에서 Peel이 허용된 경우에만 Peel이 다른 개발자의 앱을 되돌려 놓을 수 있게 합니다. 시스템 설정 > 개인정보 보호 및 보안 > 앱 관리에서 Peel을 허용한 다음 다시 시도하십시오."
+ }
+ },
+ "nl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS laat Peel de app van een andere ontwikkelaar alleen terugzetten met toestemming voor 'Appbeheer'. Sta Peel toe in Systeeminstellingen > Privacy en beveiliging > Appbeheer en probeer het opnieuw."
+ }
+ },
+ "pl" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS pozwala aplikacji Peel przywrócić aplikację innego dewelopera tylko wtedy, gdy Peel ma pozwolenie w sekcji Zarządzanie aplikacjami. Pozwól na to aplikacji Peel w Ustawieniach systemowych > Prywatność i ochrona > Zarządzanie aplikacjami, a następnie spróbuj ponownie."
+ }
+ },
+ "pt" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "O macOS só deixa o Peel colocar de volta o app de outro desenvolvedor se ele tiver permissão em Gerenciamento de Apps. Permita o Peel em Ajustes do Sistema > Privacidade e Segurança > Gerenciamento de Apps e tente novamente."
+ }
+ },
+ "ro" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS lasă Peel să pună înapoi aplicația altui dezvoltator doar cu permisiunea Gestionare aplicații. Permiteți Peel în Configurări sistem > Intimitate și securitate > Gestionare aplicații, apoi încercați din nou."
+ }
+ },
+ "ru" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS позволяет Peel восстанавливать приложения других разработчиков, только если Peel разрешен в разделе «Управление приложениями». Разрешите Peel доступ в разделе «Системные настройки» > «Конфиденциальность и безопасность» > «Управление приложениями», а затем повторите попытку."
+ }
+ },
+ "sv" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS låter Peel lägga tillbaka en annan utvecklares app bara om Peel är tillåten under Apphantering. Tillåt Peel i Systeminställningar > Integritet och säkerhet > Apphantering och försök sedan igen."
+ }
+ },
+ "tr" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS, Peel’in başka bir geliştiricinin uygulamasını yerine koymasına yalnızca Uygulama Yönetimi izniyle izin verir. Sistem Ayarları > Gizlilik ve Güvenlik > Uygulama Yönetimi bölümünde Peel’e izin verin, ardından yeniden deneyin."
+ }
+ },
+ "uk" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS дає Peel повертати програму іншого розробника, лише якщо Peel дозволено в розділі «Керування програмами». Дозвольте Peel у розділі Системні параметри > Приватність і безпека > Керування програмами та спробуйте ще раз."
+ }
+ },
+ "zh-Hans" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "只有获得“App管理”权限,macOS才允许Peel放回另一开发者的App。请在“系统设置”>“隐私与安全性”>“App管理”中允许Peel,然后重试。"
+ }
+ },
+ "zh-Hant" : {
+ "stringUnit" : {
+ "state" : "translated",
+ "value" : "macOS只有在Peel獲得「App管理」權限時,才允許它還原其他開發者的App。請在「系統設定」>「隱私權與安全性」>「App管理」中允許Peel,然後再試一次。"
+ }
+ }
+ }
+ },
"macOS makes a snapshot before it updates, so the update can be undone. It goes away by itself." : {
"localizations" : {
"cs" : {
diff --git a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift
index 3c68ecf7..b4cfe9b1 100644
--- a/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift
+++ b/Packages/PeelCore/Sources/PeelCommandLine/Support/Output.swift
@@ -239,6 +239,11 @@ extension RestoreFailure {
"your exclusions keep Peel from putting anything there; take it off the list, or drag it out of the Trash in Finder"
case .notAllowed(let refusal): "Peel protects that place now (\(refusal.summary)); drag it out of the Trash in Finder"
case .notInATrash: "it isn't in the Trash where Peel put it"
+ case .locked: "it is locked; unlock it in Finder's Get Info"
+ case .folderLocked: "the folder it goes back to is locked; unlock it in Finder's Get Info"
+ case .needsAppManagement:
+ "macOS lets your terminal app put back another developer's app only with App Management; allow it in System Settings > Privacy & Security > App Management, or put it back with the Peel app"
+ case .notPermitted: "macOS didn't allow it"
case .failed(let message): Output.plain(message)
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
index dfadd9dd..4162dec0 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
@@ -204,13 +204,20 @@ public enum RestoreFailure: Sendable, Hashable {
case notAllowed(GuardRefusal)
/// The record names something that isn't in a Trash where Peel put it.
case notInATrash
+ /// It is locked in the Trash, as Finder's Get Info locks it.
+ case locked
+ case folderLocked
+ /// Another developer's app, which macOS lets Peel change only with App Management.
+ case needsAppManagement
+ /// macOS's privacy protection refused it.
+ case notPermitted
case failed(String)
/// True when asking again can't help: the item left the Trash, or Peel puts nothing back from or to there.
public var isFinal: Bool {
switch self {
case .missingFromTrash, .notAllowed, .notInATrash: true
- case .alreadyThere, .needsHelper, .failed: false
+ case .alreadyThere, .needsHelper, .locked, .folderLocked, .needsAppManagement, .notPermitted, .failed: false
}
}
}
@@ -759,6 +766,8 @@ public struct TrashService: Sendable {
}
guard item.isInTheTrash else { return .missingFromTrash }
guard !item.originalURL.isThere else { return .alreadyThere }
+ if FileAccess.isLockedInFinder(item.trashedURL) { return .locked }
+ if FileAccess.isLockedInFinder(URL(filePath: Self.folder(puttingBack: item))) { return .folderLocked }
if Self.needsTheHelper(toPutBack: item) {
let reach = HelperReach(environment: environment)
if let rejection = reach.refusal(ofPuttingBack: item.trashedURL, at: item.originalURL) {
@@ -769,14 +778,19 @@ public struct TrashService: Sendable {
return nil
}
- /// Whether putting `item` back is the helper's to do: the nearest folder on its way that exists is one the person
- /// can't write to. Missing folders are made again, so that is the folder that decides.
- static func needsTheHelper(toPutBack item: TrashedItem) -> Bool {
+ /// The nearest folder on `item`'s way back that exists, which its Put Back writes into: missing folders are made
+ /// again.
+ static func folder(puttingBack item: TrashedItem) -> String {
var ancestor = item.originalURL.deletingLastPathComponent().path(percentEncoded: false)
while !FileManager.default.fileExists(atPath: ancestor), ancestor != "/" {
ancestor = (ancestor as NSString).deletingLastPathComponent
}
- return !FileManager.default.isWritableFile(atPath: ancestor)
+ return ancestor
+ }
+
+ /// Whether putting `item` back is the helper's to do: the person can't write to the folder it goes back into.
+ static func needsTheHelper(toPutBack item: TrashedItem) -> Bool {
+ !FileManager.default.isWritableFile(atPath: folder(puttingBack: item))
}
private func moveBack(_ item: TrashedItem, canUseHelper: Bool) async -> RestoreFailure? {
@@ -794,6 +808,11 @@ public struct TrashService: Sendable {
return .alreadyThere
} catch {
guard Self.reason(for: error) == .notPermitted else { return .failed(error.localizedDescription) }
+ // Refused by macOS rather than by the permissions, the helper couldn't do it either.
+ if FileAccess.isProtectedByPrivacy(item.trashedURL) {
+ let isAnApp = item.trashedURL.pathExtension.caseInsensitiveCompare("app") == .orderedSame
+ return isAnApp ? .needsAppManagement : .notPermitted
+ }
}
}
guard canUseHelper, PrivilegedHelper.status == .enabled else { return .needsHelper }
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
index 6afd70c9..056a0b7a 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
@@ -597,6 +597,36 @@ struct TrashServiceTests {
#expect(throughTheHelper == .failed(PrivilegedPathPolicy.Rejection.loadsCode.explanation))
}
+ @Test func anItemLockedInTheTrashOrAFolderLockedOnItsWayBackIsSaidSo() async throws {
+ let directory = try TemporaryDirectory()
+ let documents = try directory.directory("home/Documents")
+ let trashed = try directory.file("home/.Trash/notes.txt", bytes: 1)
+ let otherTrashed = try directory.file("home/.Trash/letter.txt", bytes: 1)
+ let service = TrashService(
+ environment: SearchEnvironment(
+ homeDirectory: directory.url.appending(path: "home"),
+ rootDirectory: directory.url.appending(path: "root")
+ )
+ ) { $0 }
+ let locked = TrashedItem(originalURL: documents.appending(path: "notes.txt"), trashedURL: trashed, date: .now)
+ let intoALockedFolder = TrashedItem(
+ originalURL: documents.appending(path: "letter.txt"), trashedURL: otherTrashed, date: .now
+ )
+ func lock(_ url: URL, _ isLocked: Bool) throws {
+ try FileManager.default.setAttributes([.immutable: isLocked], ofItemAtPath: url.path(percentEncoded: false))
+ }
+
+ try lock(trashed, true)
+ let lockedItem = await service.restore(locked)
+ try lock(trashed, false)
+ try lock(documents, true)
+ let lockedFolder = await service.restore(intoALockedFolder)
+ try lock(documents, false)
+
+ #expect(lockedItem == .locked)
+ #expect(lockedFolder == .folderLocked)
+ }
+
@Test(.permissionsHold) func saysWhatTheHelperWouldOfAPlaceItDoesNotServe() throws {
let directory = try TemporaryDirectory()
let locked = try directory.directory("home/Locked")
diff --git a/Peel/Views/History/HistoryDetailView.swift b/Peel/Views/History/HistoryDetailView.swift
index 3cd7d2d9..093ea1c4 100644
--- a/Peel/Views/History/HistoryDetailView.swift
+++ b/Peel/Views/History/HistoryDetailView.swift
@@ -71,6 +71,9 @@ struct HistoryDetailView: View {
isShowingFailures = !failures.isEmpty
}
.alert("Some items couldn’t be put back.", isPresented: $isShowingFailures) {
+ if failures.contains(where: { $0.failure == .needsAppManagement }) {
+ Button("Open System Settings") { NSWorkspace.shared.open(AppManagement.settingsURL) }
+ }
if failures.contains(where: { $0.failure == .needsHelper }) {
Button("Open Peel Settings") { SettingsPane.helper.open(with: openSettings) }
}
diff --git a/Peel/Views/Presentation.swift b/Peel/Views/Presentation.swift
index 46de302a..4283c5d6 100644
--- a/Peel/Views/Presentation.swift
+++ b/Peel/Views/Presentation.swift
@@ -253,6 +253,12 @@ extension RestoreFailure {
String(localized: "Your exclusions in Settings keep Peel from putting anything back there. Take it off the list to put this back, or drag it out of the Trash in Finder.")
case .notAllowed: String(localized: "Peel protects that place now, so it puts nothing back there. You can drag it out of the Trash in Finder.")
case .notInATrash: String(localized: "It isn’t in the Trash where Peel put it, so Peel leaves it where it is.")
+ case .locked: String(localized: "It is locked. In Finder, choose File > Get Info and deselect Locked, then try again.")
+ case .folderLocked:
+ String(localized: "The folder it goes back to is locked. In Finder, choose File > Get Info for that folder and deselect Locked, then try again.")
+ case .needsAppManagement:
+ String(localized: "macOS lets Peel put back another developer’s app only with App Management. Allow Peel in System Settings > Privacy & Security > App Management, then try again.")
+ case .notPermitted: String(localized: "macOS didn’t allow it.")
case .failed(let message): FixedSentence.translated(message)
}
}
diff --git a/Peel/Views/RemovalFailureAlert.swift b/Peel/Views/RemovalFailureAlert.swift
index 563dfbb2..06f40ac9 100644
--- a/Peel/Views/RemovalFailureAlert.swift
+++ b/Peel/Views/RemovalFailureAlert.swift
@@ -172,7 +172,7 @@ struct RemovalFailureAlert: ViewModifier {
}
private static func appManagementLines(_ outcome: RemovalOutcome) -> [String] {
- guard needsAppManagement(outcome) else { return [] }
+ guard movesNeedAppManagement(outcome) else { return [] }
return [String(localized: "If Peel isn’t allowed under App Management, macOS won’t let it move another developer’s app to the Trash.")]
}
@@ -224,6 +224,10 @@ struct RemovalFailureAlert: ViewModifier {
/// True when macOS refused to move an app although the user can write to its folder and nothing locks it.
/// That refusal comes from App Management, which the user can allow in System Settings.
private static func needsAppManagement(_ outcome: RemovalOutcome) -> Bool {
+ movesNeedAppManagement(outcome) || outcome.putBackFailures.contains { $0.failure == .needsAppManagement }
+ }
+
+ private static func movesNeedAppManagement(_ outcome: RemovalOutcome) -> Bool {
outcome.failures.contains { failure in
failure.reason == .notPermitted && failure.url.pathExtension.lowercased() == "app"
&& AppManagement.isRefusedForWantOfPermission(failure.url)
diff --git a/PeelTests/RemovalFailureAlertTests.swift b/PeelTests/RemovalFailureAlertTests.swift
index 0035f108..b887ce74 100644
--- a/PeelTests/RemovalFailureAlertTests.swift
+++ b/PeelTests/RemovalFailureAlertTests.swift
@@ -26,6 +26,18 @@ struct RemovalFailureAlertTests {
#expect(details.filter { $0.contains("Example 30") }.count == 3)
}
+ @Test func anUndoThatMacOSRefusedNamesAppManagementAndNotTheMove() {
+ let outcome = RemovalOutcome()
+ outcome.reportPutBack([
+ .init(url: URL(filePath: "/Applications/Example.app"), failure: .needsAppManagement),
+ ])
+
+ let message = RemovalFailureAlert.message(for: outcome)
+
+ #expect(message.contains(RestoreFailure.needsAppManagement.explanation))
+ #expect(!message.contains("to the Trash."), "\(message)")
+ }
+
@Test func namesTheFirstFoldersAnAlertRefusesAndCountsTheOthers() {
let most = RemovalFailureAlert.mostListed
let paths = (1...30).map { "/Users/someone/Folder \($0)" }