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.

Export List of Apps builds the list off the main thread

Țugui Dragoș686d6175c1df
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/DownloadOrigins.swift b/Packages/PeelCore/Sources/PeelCore/Apps/DownloadOrigins.swift
index 8c47ce11..b325b321 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/DownloadOrigins.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/DownloadOrigins.swift
@@ -17,33 +17,36 @@ public struct DownloadOrigins: Sendable {
self.events = events
}
- func address(of bundle: URL) -> URL? {
- whereFrom(bundle) ?? quarantinedDownload(of: bundle)
+ /// A reader for one list of apps, which opens the quarantine database once for all of them.
+ func reader() -> Reader {
+ Reader(events: QuarantineEvents(at: events))
}
- /// The attribute is a binary property list of addresses: the file's own address, then the page it was on.
- private func whereFrom(_ bundle: URL) -> URL? {
- guard let data = Self.attribute("com.apple.metadata:kMDItemWhereFroms", of: bundle),
- let addresses = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String] else { return nil }
- return addresses.lazy.compactMap(Self.shareable).first
- }
+ final class Reader {
+ private let events: QuarantineEvents
- /// The quarantine attribute reads `flags;time;agent;identifier`, and the identifier names the download's row.
- private func quarantinedDownload(of bundle: URL) -> URL? {
- guard let data = Self.attribute("com.apple.quarantine", of: bundle) else { return nil }
- let fields = String(decoding: data, as: UTF8.self).split(separator: ";", omittingEmptySubsequences: false)
- guard fields.count >= 4, let identifier = UUID(uuidString: String(fields[3]))?.uuidString else { return nil }
-
- var database: OpaquePointer?
- defer { sqlite3_close(database) }
- guard sqlite3_open_v2(events.path(percentEncoded: false), &database, SQLITE_OPEN_READONLY, nil) == SQLITE_OK else { return nil }
- var statement: OpaquePointer?
- defer { sqlite3_finalize(statement) }
- let query = "SELECT LSQuarantineDataURLString, LSQuarantineOriginURLString FROM LSQuarantineEvent WHERE LSQuarantineEventIdentifier = ?"
- guard sqlite3_prepare_v2(database, query, -1, &statement, nil) == SQLITE_OK,
- sqlite3_bind_text(statement, 1, identifier, -1, unsafeBitCast(-1, to: sqlite3_destructor_type.self)) == SQLITE_OK,
- sqlite3_step(statement) == SQLITE_ROW else { return nil }
- return [Int32(0), 1].lazy.compactMap { sqlite3_column_text(statement, $0).map { String(cString: $0) } }.compactMap(Self.shareable).first
+ fileprivate init(events: QuarantineEvents) {
+ self.events = events
+ }
+
+ func address(of bundle: URL) -> URL? {
+ whereFrom(bundle) ?? quarantinedDownload(of: bundle)
+ }
+
+ /// The attribute is a binary property list of addresses: the file's own address, then the page it was on.
+ private func whereFrom(_ bundle: URL) -> URL? {
+ guard let data = DownloadOrigins.attribute("com.apple.metadata:kMDItemWhereFroms", of: bundle),
+ let addresses = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String] else { return nil }
+ return addresses.lazy.compactMap(DownloadOrigins.shareable).first
+ }
+
+ /// The quarantine attribute reads `flags;time;agent;identifier`, and the identifier names the download's row.
+ private func quarantinedDownload(of bundle: URL) -> URL? {
+ guard let data = DownloadOrigins.attribute("com.apple.quarantine", of: bundle) else { return nil }
+ let fields = String(decoding: data, as: UTF8.self).split(separator: ";", omittingEmptySubsequences: false)
+ guard fields.count >= 4, let identifier = UUID(uuidString: String(fields[3]))?.uuidString else { return nil }
+ return events.addresses(of: identifier).lazy.compactMap(DownloadOrigins.shareable).first
+ }
}
private static func shareable(_ address: String) -> URL? {
@@ -65,3 +68,38 @@ public struct DownloadOrigins: Sendable {
return read == size ? data : nil
}
}
+
+/// Launch Services' list of downloads, opened read-only at the first record looked up, and closed with this.
+private final class QuarantineEvents {
+ private let url: URL
+ private var database: OpaquePointer?
+ private var statement: OpaquePointer?
+ private var hasOpened = false
+
+ init(at url: URL) {
+ self.url = url
+ }
+
+ deinit {
+ sqlite3_finalize(statement)
+ sqlite3_close(database)
+ }
+
+ /// The download's own address and the page it was on, as recorded for the event `identifier`.
+ func addresses(of identifier: String) -> [String] {
+ guard let statement = prepared() else { return [] }
+ defer { sqlite3_reset(statement) }
+ guard sqlite3_bind_text(statement, 1, identifier, -1, unsafeBitCast(-1, to: sqlite3_destructor_type.self)) == SQLITE_OK,
+ sqlite3_step(statement) == SQLITE_ROW else { return [] }
+ return [Int32(0), 1].compactMap { sqlite3_column_text(statement, $0).map { String(cString: $0) } }
+ }
+
+ private func prepared() -> OpaquePointer? {
+ guard !hasOpened else { return statement }
+ hasOpened = true
+ let query = "SELECT LSQuarantineDataURLString, LSQuarantineOriginURLString FROM LSQuarantineEvent WHERE LSQuarantineEventIdentifier = ?"
+ guard sqlite3_open_v2(url.path(percentEncoded: false), &database, SQLITE_OPEN_READONLY, nil) == SQLITE_OK,
+ sqlite3_prepare_v2(database, query, -1, &statement, nil) == SQLITE_OK else { return nil }
+ return statement
+ }
+}
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/Inventory.swift b/Packages/PeelCore/Sources/PeelCore/Apps/Inventory.swift
index 6e444aef..8cbf3a2f 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/Inventory.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/Inventory.swift
@@ -58,13 +58,14 @@ public struct Inventory: Sendable {
origins: DownloadOrigins? = nil,
brewfile: String? = nil
) -> Inventory {
+ let reader = origins?.reader()
let entries = apps
.sorted { $0.name.localizedStandardCompare($1.name) == .orderedAscending }
- .map { app in entry(for: app, casks: casks, origins: origins) }
+ .map { app in entry(for: app, casks: casks, origins: reader) }
return Inventory(entries: entries, brewfile: brewfile)
}
- static func entry(for app: InstalledApp, casks: [HomebrewPackage], origins: DownloadOrigins?) -> InventoryEntry {
+ static func entry(for app: InstalledApp, casks: [HomebrewPackage], origins: DownloadOrigins.Reader?) -> InventoryEntry {
let cask = CaskEvidence.installedCask(for: app, in: casks)
let (source, detail) = origin(of: app, cask: cask, origins: origins)
return InventoryEntry(
@@ -83,7 +84,7 @@ public struct Inventory: Sendable {
}
/// Homebrew comes first: a cask says exactly how to install the app again.
- static func origin(of app: InstalledApp, cask: HomebrewPackage?, origins: DownloadOrigins?) -> (String, String?) {
+ static func origin(of app: InstalledApp, cask: HomebrewPackage?, origins: DownloadOrigins.Reader?) -> (String, String?) {
if let cask {
return ("Homebrew", cask.name)
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/InventoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/InventoryTests.swift
index 753848ed..3bd173f4 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/InventoryTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/InventoryTests.swift
@@ -100,6 +100,26 @@ struct InventoryTests {
#expect(entries["Plain"]?.source == "Unknown")
}
+ @Test func everyDownloadedAppGetsItsOwnAddress() throws {
+ let directory = try TemporaryDirectory()
+ let events = directory.url.appending(path: "QuarantineEventsV2")
+ let identifiers = (0..<3).map { _ in UUID().uuidString }
+ try sqlite(events, [
+ "CREATE TABLE LSQuarantineEvent (LSQuarantineEventIdentifier TEXT PRIMARY KEY NOT NULL, LSQuarantineTimeStamp REAL, LSQuarantineAgentBundleIdentifier TEXT, LSQuarantineAgentName TEXT, LSQuarantineDataURLString TEXT, LSQuarantineSenderName TEXT, LSQuarantineSenderAddress TEXT, LSQuarantineTypeNumber INTEGER, LSQuarantineOriginTitle TEXT, LSQuarantineOriginURLString TEXT, LSQuarantineOriginAlias BLOB)",
+ "INSERT INTO LSQuarantineEvent (LSQuarantineEventIdentifier, LSQuarantineDataURLString) VALUES ('\(identifiers[0])', 'https://example.org/First.zip'), ('\(identifiers[2])', 'https://example.org/Third.zip')",
+ ])
+ let names = ["First", "Second", "Third"]
+ let apps = try zip(names, identifiers).map { name, identifier in
+ let bundle = try directory.directory("Applications/\(name).app")
+ try setAttribute("com.apple.quarantine", Data("0083;66f0f0f0;Safari;\(identifier)".utf8), on: bundle)
+ return InstalledApp(url: bundle, bundleIdentifier: "org.example.\(name.lowercased())", name: name)
+ }
+
+ let entries = Inventory.build(apps: apps, origins: DownloadOrigins(events: events)).entries
+
+ #expect(entries.map(\.sourceDetail) == ["https://example.org/First.zip", nil, "https://example.org/Third.zip"])
+ }
+
private func setAttribute(_ name: String, _ value: Data, on url: URL) throws {
let status = value.withUnsafeBytes { setxattr(url.path(percentEncoded: false), name, $0.baseAddress, value.count, 0, XATTR_NOFOLLOW) }
#expect(status == 0)
diff --git a/Peel/Model/InventoryExport.swift b/Peel/Model/InventoryExport.swift
index a55408dc..15eec76d 100644
--- a/Peel/Model/InventoryExport.swift
+++ b/Peel/Model/InventoryExport.swift
@@ -37,9 +37,7 @@ enum InventoryExport {
}
}
do {
- contents = try Inventory.build(
- apps: apps, casks: homebrew.packages ?? [], origins: .onThisMac, brewfile: brewfile
- ).written(as: format)
+ contents = try await written(format, apps: apps, casks: homebrew.packages ?? [], brewfile: brewfile)
} catch is Inventory.HomebrewDidNotAnswer {
return String(localized: "Homebrew didn’t answer, so Peel has nothing to write a Brewfile from. Open Homebrew in Peel to see why.")
} catch {
@@ -65,6 +63,14 @@ enum InventoryExport {
}
}
+ /// The list as `format` writes it, worked out off the main actor, since it reads every app's download records.
+ @concurrent
+ private static func written(
+ _ format: Inventory.Format, apps: [InstalledApp], casks: [HomebrewPackage], brewfile: String?
+ ) async throws -> String {
+ try Inventory.build(apps: apps, casks: casks, origins: .onThisMac, brewfile: brewfile).written(as: format)
+ }
+
private static func contentType(for format: Inventory.Format) -> UTType? {
switch format {
case .json: .json