Skip to content

armgit / peel

Public Imported from GitHub
0

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

Keep an update for the app that runs, and ask that app to quit before it moves

Țugui Dragoș3f9aea05bf32
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift b/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift
index 0935062b..00f92c54 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/OpenFiles.swift
@@ -80,6 +80,15 @@ struct OpenFiles {
Set(holding(url, lettingItsProgramsRun: lettingItsProgramsRun).map(\.process)).sorted()
}
+ /// The app bundles programs run from, the outermost of each, wherever they are.
+ func runningApps() -> Set<URL> {
+ Set(programs.values.compactMap { program in
+ let names = PathComponents.of(program)
+ guard let app = names.firstIndex(where: { $0.hasSuffix(".app") }) else { return nil }
+ return URL(filePath: "/" + names[...app].joined(separator: "/"), directoryHint: .isDirectory)
+ })
+ }
+
func isAttachedDiskImage(_ url: URL) -> Bool {
attachedImages.contains(PathComponents.of(PathPattern.canonical(url).path(percentEncoded: false)))
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift b/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift
index 2bd0b2cd..ded8c248 100644
--- a/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift
@@ -37,6 +37,18 @@ public struct InstallerItem: Sendable, Hashable, Identifiable {
public var heldBack: HoldBack?
/// What keeps it in step with the other devices, when it is held back as `inTheCloud`.
public var syncedBy: SyncKeeper? = nil
+ /// The app a downloaded update is for, which has to quit before the update moves from under it.
+ public var updatesApp: UpdatedApp? = nil
+
+ public struct UpdatedApp: Sendable, Hashable {
+ public let identifier: String
+ public let name: String
+
+ public init(identifier: String, name: String) {
+ self.identifier = identifier
+ self.name = name
+ }
+ }
public var id: URL { url }
@@ -81,6 +93,12 @@ extension Collection where Element == InstallerItem {
return SizeTotal(filter { selectable.contains($0.url) }.map(\.size))
}
+ /// What a kind's row and page show: what moving could free, or what is there for a device backup, which Peel only
+ /// shows.
+ public func shownTotal(of kind: InstallerItem.Kind, canUseHelper: Bool) -> SizeTotal {
+ kind == .deviceBackup ? SizeTotal(map(\.size)) : movable(canUseHelper: canUseHelper)
+ }
+
public func selectableRows(canUseHelper: Bool) -> SelectableRows<URL> {
let selectable = filter { $0.canBeMoved && !$0.isLocked(canUseHelper: canUseHelper) }
return SelectableRows(
@@ -597,6 +615,7 @@ public enum Installers {
addIfElectronUpdaters(url)
}
let place = Folder(url: caches, isSharedWithEveryone: false)
+ let elsewhere = found.contains { $0.identifier == nil } ? electronAppsRunning(openFiles) : [:]
var items: [InstallerItem] = []
for (url, identifier, app) in found {
guard !Task.isCancelled else { return items }
@@ -607,9 +626,9 @@ public enum Installers {
guard isAnExcludedApps != true else { continue }
let (size, seen, _) = await measured(url, by: measure)
guard isWorthARow(size, minimumSize) else { continue }
- let isRunning = identifier.map {
- !NSRunningApplication.runningApplications(withBundleIdentifier: $0).isEmpty
- } ?? false
+ let fromElsewhere = identifier == nil ? elsewhere[url.lastPathComponent.lowercased()] : nil
+ let running = identifier.map(NSRunningApplication.runningApplications(withBundleIdentifier:)) ?? []
+ let name = app?.name ?? fromElsewhere?.name ?? running.first?.localizedName
items.append(InstallerItem(
url: url,
kind: .updateDownload,
@@ -618,17 +637,36 @@ public enum Installers {
date: (try? url.resourceValues(forKeys: [.contentModificationDateKey]))?.contentModificationDate,
installedApp: nil,
isReadOnly: false,
- notes: app.map { [.downloadedBy($0.name)] } ?? [],
+ notes: (app?.name ?? fromElsewhere?.name).map { [.downloadedBy($0)] } ?? [],
requiresPrivileges: FileAccess.requiresPrivilegesToRemove(url),
heldBack: heldBack(
url, seen: seen, in: place, syncKeeper: syncKeeper, openFiles: openFiles
)
- ?? (isRunning ? .appIsRunning : nil)
+ ?? (!running.isEmpty || fromElsewhere != nil ? .appIsRunning : nil),
+ updatesApp: (identifier ?? fromElsewhere?.identifier).flatMap { identifier in
+ name.map { InstallerItem.UpdatedApp(identifier: identifier, name: $0) }
+ }
))
}
return items
}
+ /// The Electron apps running now, listed or not, by the folder each names for its updates in `app-update.yml`.
+ private static func electronAppsRunning(
+ _ openFiles: OpenFiles
+ ) -> [String: (identifier: String?, name: String)] {
+ var apps: [String: (identifier: String?, name: String)] = [:]
+ for app in openFiles.runningApps() {
+ let contents = app.appending(path: "Contents", directoryHint: .isDirectory)
+ guard let folder = ElectronUpdater.configuration(in: contents)
+ .flatMap(ElectronUpdater.downloadsFolder(fromConfiguration:))
+ else { continue }
+ let identifier = AppInspector.stated(AppInspector.infoDictionary(in: contents)?["CFBundleIdentifier"])
+ apps[folder.lowercased()] = (identifier, app.deletingPathExtension().lastPathComponent)
+ }
+ return apps
+ }
+
/// Installer packages in `~/Library/Application Support`, up to three levels down, never inside a package or in
/// what macOS keeps there for its own services, the device backups and Contacts among them. Each is matched by its
/// name to an installed app, or else by the folder it sits in.
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swift
index 00f1e744..3abec2dc 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/InstallersTests.swift
@@ -632,6 +632,49 @@ struct InstallersTests {
#expect(scan.items(in: .updateDownload).map(\.name) == ["org.example.other.ShipIt"])
}
+ @Test func anElectronAppRunningFromElsewhereKeepsItsUpdate() async throws {
+ let directory = try TemporaryDirectory()
+ try directory.file("Library/Caches/chat-updater/update.zip", bytes: 400_000)
+ try directory.file("Library/Caches/other-updater/update.zip", bytes: 400_000)
+ try directory.file(
+ "Elsewhere/Chat.app/Contents/Resources/app-update.yml",
+ contents: Data("provider: generic\nupdaterCacheDirName: chat-updater\n".utf8)
+ )
+ try directory.file(
+ "Elsewhere/Chat.app/Contents/Info.plist",
+ contents: try PropertyListSerialization.data(
+ fromPropertyList: ["CFBundleIdentifier": "org.example.chat"], format: .xml, options: 0
+ )
+ )
+ let process = try directory.runningProgram("Elsewhere/Chat.app/Contents/MacOS/Chat")
+ defer { process.terminate() }
+ try directory.directory("Applications")
+
+ let scan = await Installers.scan(
+ installedApps: [], home: directory.url, root: directory.url, exclusions: .none, minimumSize: 100_000,
+ measure: LeftoverScanner.walk, openFiles: OpenFiles(excluding: nil)
+ )
+
+ let updates = Dictionary(uniqueKeysWithValues: scan.items(in: .updateDownload).map { ($0.name, $0) })
+ #expect(updates["chat-updater"]?.heldBack == .appIsRunning)
+ #expect(updates["chat-updater"]?.notes == [.downloadedBy("Chat")])
+ #expect(updates["chat-updater"]?.updatesApp?.identifier == "org.example.chat")
+ #expect(updates["other-updater"]?.heldBack == nil)
+ #expect(updates["other-updater"]?.updatesApp == nil)
+ }
+
+ @Test func aKindShowsWhatCanMoveAndABackupWhatIsThere() {
+ let download = { (heldBack: HoldBack?) in
+ InstallerItem(
+ url: URL(filePath: "/Users/me/Downloads/\(UUID().uuidString).dmg"), kind: .appInstaller, name: "Tool.dmg",
+ size: 100, date: nil, installedApp: nil, isReadOnly: false, notes: [], heldBack: heldBack
+ )
+ }
+ let items = [download(nil), download(.inTheCloud)]
+ #expect(items.shownTotal(of: .appInstaller, canUseHelper: true).known == 100)
+ #expect(items.shownTotal(of: .deviceBackup, canUseHelper: true).known == 200)
+ }
+
@Test func findsWhatElectronUpdaterDownloadedInEitherPlace() async throws {
let directory = try TemporaryDirectory()
let old = "Library/Application Support/Caches"
diff --git a/Peel/Model/InstallerLibrary.swift b/Peel/Model/InstallerLibrary.swift
index d75e8207..9f80d076 100644
--- a/Peel/Model/InstallerLibrary.swift
+++ b/Peel/Model/InstallerLibrary.swift
@@ -1,3 +1,4 @@
+import AppKit
import Foundation
import Observation
import PeelCore
@@ -74,8 +75,18 @@ extension InstallerLibrary: CarriesSelection {
}
}
+ /// An app a selected update is for, while it runs: it may install the update when it quits, and would download it
+ /// again.
+ func appToQuit(for part: CarriedSelection.Part) -> String? {
+ guard let kind = InstallerItem.Kind(rawValue: part.page.scope) else { return nil }
+ return selected(in: kind).filter { part.sizes.keys.contains($0.url) }.compactMap(\.updatesApp).first { app in
+ !NSRunningApplication.runningApplications(withBundleIdentifier: app.identifier).isEmpty
+ }?.name
+ }
+
func move(_ part: CarriedSelection.Part, apps: AppLibrary) async -> TrashResult? {
guard let kind = InstallerItem.Kind(rawValue: part.page.scope) else { return TrashResult() }
+ guard appToQuit(for: part) == nil else { return nil }
isRemoving = true
defer { isRemoving = false }
let selected = selected(in: kind).filter { part.sizes.keys.contains($0.url) }