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.

Wrap PeelCore's long lines at 120 columns

Țugui Dragoșbdb756d529a7
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swift b/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swift
index 08c95524..d97892ab 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/AppInspector.swift
@@ -44,7 +44,10 @@ public enum AppInspector {
else { return [] }
return Set((0..<MDQueryGetResultCount(query)).compactMap { index in
guard let result = MDQueryGetResultAtIndex(query, index) else { return nil }
- return MDItemCopyAttribute(Unmanaged<MDItem>.fromOpaque(result).takeUnretainedValue(), kMDItemCFBundleIdentifier) as? String
+ return MDItemCopyAttribute(
+ Unmanaged<MDItem>.fromOpaque(result).takeUnretainedValue(),
+ kMDItemCFBundleIdentifier
+ ) as? String
})
}
return found ?? []
@@ -91,7 +94,12 @@ public enum AppInspector {
lastUsedDate: use.lastUsedDate,
isUseRecorded: use.isRecorded,
dateAdded: dateAdded(of: url),
- updateFeed: UpdateFeed.detect(info: info, contents: contents, isFromAppStore: isFromAppStore, isSystemProtected: isSystemProtected)
+ updateFeed: UpdateFeed.detect(
+ info: info,
+ contents: contents,
+ isFromAppStore: isFromAppStore,
+ isSystemProtected: isSystemProtected
+ )
)
}
@@ -118,13 +126,17 @@ public enum AppInspector {
return name.hasSuffix(".app") ? String(name.dropLast(4)) : name
}
- private static func signingInformation(for url: URL) -> (teamIdentifier: String?, developer: String?, applicationGroups: [String]) {
+ private static func signingInformation(
+ for url: URL
+ ) -> (teamIdentifier: String?, developer: String?, applicationGroups: [String]) {
guard let information = CodeSignature.information(at: url) else { return (nil, nil, []) }
let team = information[kSecCodeInfoTeamIdentifier as String] as? String
let leaf = (information[kSecCodeInfoCertificates as String] as? [SecCertificate])?.first
return (
team,
- leaf.flatMap { SecCertificateCopySubjectSummary($0) as String? }.flatMap { CodeSignature.developer(fromLeaf: $0, team: team) },
+ leaf.flatMap { SecCertificateCopySubjectSummary($0) as String? }.flatMap {
+ CodeSignature.developer(fromLeaf: $0, team: team)
+ },
applicationGroups(in: information)
)
}
@@ -145,7 +157,8 @@ public enum AppInspector {
for directory in embeddedBundleDirectories {
let folder = contents.appending(path: directory, directoryHint: .isDirectory)
- guard let children = try? fileManager.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil) else {
+ guard let children = try? fileManager.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)
+ else {
continue
}
for child in children where embeddedBundleExtensions.contains(child.pathExtension.lowercased()) {
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/AppMemory.swift b/Packages/PeelCore/Sources/PeelCore/Apps/AppMemory.swift
index a7b573bb..12e7eb9e 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/AppMemory.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/AppMemory.swift
@@ -58,7 +58,10 @@ public struct AppMemory: Sendable {
/// `known` is nil when the file cannot be read or reached. Its contents are then unknown, so it is never
/// written over, and the apps currently installed are still returned for this run.
private func remember(_ apps: [InstalledApp], now: Date, onTopOf known: [RememberedApp]?) -> [RememberedApp] {
- var byIdentifier = Dictionary((known ?? []).map { ($0.bundleIdentifier, $0) }, uniquingKeysWith: { first, _ in first })
+ var byIdentifier = Dictionary(
+ (known ?? []).map { ($0.bundleIdentifier, $0) },
+ uniquingKeysWith: { first, _ in first }
+ )
for app in apps where !app.bundleIdentifier.isEmpty && !app.isSystemProtected {
byIdentifier[app.bundleIdentifier] = RememberedApp(
bundleIdentifier: app.bundleIdentifier,
@@ -70,7 +73,9 @@ public struct AppMemory: Sendable {
}
let kept = byIdentifier.values
- .sorted { $0.lastSeen != $1.lastSeen ? $0.lastSeen > $1.lastSeen : $0.bundleIdentifier < $1.bundleIdentifier }
+ .sorted {
+ $0.lastSeen != $1.lastSeen ? $0.lastSeen > $1.lastSeen : $0.bundleIdentifier < $1.bundleIdentifier
+ }
.prefix(Self.maximumApps)
.map { $0 }
if known != nil { write(kept) }
@@ -111,7 +116,10 @@ public struct AppMemory: Sendable {
return exact
}
return remembered
- .filter { Identifier.componentCount(of: $0.bundleIdentifier) >= 3 && lowercased.hasPrefix($0.bundleIdentifier.lowercased() + ".") }
+ .filter {
+ Identifier.componentCount(of: $0.bundleIdentifier) >= 3
+ && lowercased.hasPrefix($0.bundleIdentifier.lowercased() + ".")
+ }
.max { $0.bundleIdentifier.count < $1.bundleIdentifier.count }
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/AppOrder.swift b/Packages/PeelCore/Sources/PeelCore/Apps/AppOrder.swift
index 68d60d69..2d39f223 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/AppOrder.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/AppOrder.swift
@@ -4,7 +4,10 @@ public import Foundation
public enum AppOrder {
/// Sorts `apps` by `key`, largest first. Apps that tie are sorted by name, A to Z, so the list keeps a
/// steady order while sizes are still loading.
- public static func sorted<Key: Comparable>(_ apps: [InstalledApp], descendingBy key: (InstalledApp) -> Key) -> [InstalledApp] {
+ public static func sorted<Key: Comparable>(
+ _ apps: [InstalledApp],
+ descendingBy key: (InstalledApp) -> Key
+ ) -> [InstalledApp] {
apps.sorted { lhs, rhs in
let (left, right) = (key(lhs), key(rhs))
if left != right { return left > right }
@@ -14,14 +17,23 @@ public enum AppOrder {
/// Sorts `apps` by size, largest first. An app whose size could not be measured comes first, since it is most
/// likely the biggest, and one still being measured comes last, after every size already known.
- public static func sortedBySize(_ apps: [InstalledApp], sizes: [URL: Int64], unmeasured: Set<URL>) -> [InstalledApp] {
+ public static func sortedBySize(
+ _ apps: [InstalledApp],
+ sizes: [URL: Int64],
+ unmeasured: Set<URL>
+ ) -> [InstalledApp] {
sorted(apps) { sizes[$0.id] ?? (unmeasured.contains($0.id) ? .max : -1) }
}
/// Whether `app` has not been opened in the last `months` months. An app with no record of being opened
/// counts from the day it was added, since it is exactly the kind of app this filter is meant to find. An app
/// whose openings nothing records, or one with neither date, does not count as unused.
- public static func isUnused(_ app: InstalledApp, forMonths months: Int, now: Date = .now, calendar: Calendar = .current) -> Bool {
+ public static func isUnused(
+ _ app: InstalledApp,
+ forMonths months: Int,
+ now: Date = .now,
+ calendar: Calendar = .current
+ ) -> Bool {
guard
app.isUseRecorded,
let last = app.lastUsedDate ?? app.dateAdded,
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/CodeSignature.swift b/Packages/PeelCore/Sources/PeelCore/Apps/CodeSignature.swift
index 64ddf947..ede6144a 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/CodeSignature.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/CodeSignature.swift
@@ -19,10 +19,14 @@ enum CodeSignature {
/// are covered without them, and hashing them costs seconds per app.
static func information(at url: URL) -> [String: Any]? {
var staticCode: SecStaticCode?
- guard SecStaticCodeCreateWithPath(url as CFURL, [], &staticCode) == errSecSuccess, let staticCode else { return nil }
+ guard SecStaticCodeCreateWithPath(url as CFURL, [], &staticCode) == errSecSuccess, let staticCode else {
+ return nil
+ }
var copied: CFDictionary?
let flags = SecCSFlags(rawValue: UInt32(kSecCSSigningInformation))
- guard SecCodeCopySigningInformation(staticCode, flags, &copied) == errSecSuccess, let information = copied as? [String: Any] else {
+ guard SecCodeCopySigningInformation(staticCode, flags, &copied) == errSecSuccess,
+ let information = copied as? [String: Any]
+ else {
return nil
}
@@ -35,7 +39,8 @@ enum CodeSignature {
var requirement: SecRequirement?
guard
SecRequirementCreateWithString(text as CFString, [], &requirement) == errSecSuccess, let requirement,
- SecStaticCodeCheckValidity(staticCode, SecCSFlags(rawValue: UInt32(kSecCSBasicValidateOnly)), requirement) == errSecSuccess
+ SecStaticCodeCheckValidity(staticCode, SecCSFlags(rawValue: UInt32(kSecCSBasicValidateOnly)), requirement)
+ == errSecSuccess
else { return nil }
return information
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/DownloadOrigins.swift b/Packages/PeelCore/Sources/PeelCore/Apps/DownloadOrigins.swift
index b325b321..c5e563ff 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/DownloadOrigins.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/DownloadOrigins.swift
@@ -36,7 +36,8 @@ public struct DownloadOrigins: Sendable {
/// 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 }
+ let addresses = try? PropertyListSerialization.propertyList(from: data, format: nil) as? [String]
+ else { return nil }
return addresses.lazy.compactMap(DownloadOrigins.shareable).first
}
@@ -44,7 +45,9 @@ public struct DownloadOrigins: Sendable {
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 }
+ 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
}
}
@@ -89,7 +92,9 @@ private final class QuarantineEvents {
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,
+ 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) } }
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/IntelInspector.swift b/Packages/PeelCore/Sources/PeelCore/Apps/IntelInspector.swift
index b9a4fe57..dc285194 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/IntelInspector.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/IntelInspector.swift
@@ -120,7 +120,8 @@ public enum IntelInspector {
))
continue
}
- for url in intelOnlyBundles(inside: app.url) where !Task.isCancelled && !exclusions.excludes(url) && isNew(url) {
+ for url in intelOnlyBundles(inside: app.url)
+ where !Task.isCancelled && !exclusions.excludes(url) && isNew(url) {
findings.append(IntelFinding(
url: url,
kind: .insideApp,
@@ -131,7 +132,9 @@ public enum IntelInspector {
}
}
- for plugin in plugins where !Task.isCancelled && !exclusions.excludes(plugin.url) && isIntelOnly(bundle: plugin.url) && isNew(plugin.url) {
+ for plugin in plugins
+ where !Task.isCancelled && !exclusions.excludes(plugin.url) && isIntelOnly(bundle: plugin.url)
+ && isNew(plugin.url) {
findings.append(IntelFinding(
url: plugin.url,
kind: .plugin,
@@ -141,7 +144,8 @@ public enum IntelInspector {
))
}
- for url in bundles(in: driverDirectories(environment)) where !Task.isCancelled && !exclusions.excludes(url) && isIntelOnly(bundle: url) && isNew(url) {
+ for url in bundles(in: driverDirectories(environment))
+ where !Task.isCancelled && !exclusions.excludes(url) && isIntelOnly(bundle: url) && isNew(url) {
findings.append(IntelFinding(
url: url,
kind: .driver,
@@ -152,7 +156,8 @@ public enum IntelInspector {
}
let printerDirectories = driverDirectories(environment, folders: [printers])
- for url in programs(in: printerDirectories) where !Task.isCancelled && !exclusions.excludes(url) && isIntelOnly(executable: url) && isNew(url) {
+ for url in programs(in: printerDirectories)
+ where !Task.isCancelled && !exclusions.excludes(url) && isIntelOnly(executable: url) && isNew(url) {
findings.append(IntelFinding(
url: url,
kind: .driver,
@@ -189,25 +194,31 @@ public enum IntelInspector {
))
}
- return IntelScan(findings: findings.sorted { $0.size != $1.size ? SizeTotal([$0.size]) > SizeTotal([$1.size]) : $0.name < $1.name })
+ return IntelScan(
+ findings: findings.sorted {
+ $0.size != $1.size ? SizeTotal([$0.size]) > SizeTotal([$1.size]) : $0.name < $1.name
+ }
+ )
}
/// Helpers, plug-ins, and plain binaries inside an app that only have Intel code.
static func intelOnlyBundles(inside bundle: URL) -> [URL] {
- frameworkProcesses(inside: bundle).filter(isIntelOnly(bundle:)) + embeddedDirectories.flatMap { directory -> [URL] in
- let folder = bundle.appending(path: directory, directoryHint: .isDirectory)
- let names = (try? FileManager.default.contentsOfDirectory(atPath: folder.path(percentEncoded: false))) ?? []
- return names.map { folder.appending(path: $0) }.filter { url in
- var info = stat()
- guard lstat(url.path(percentEncoded: false), &info) == 0 else { return false }
- if info.st_mode & S_IFMT == S_IFDIR {
- return !url.pathExtension.isEmpty && isIntelOnly(bundle: url)
+ frameworkProcesses(inside: bundle).filter(isIntelOnly(bundle:))
+ + embeddedDirectories.flatMap { directory -> [URL] in
+ let folder = bundle.appending(path: directory, directoryHint: .isDirectory)
+ let names =
+ (try? FileManager.default.contentsOfDirectory(atPath: folder.path(percentEncoded: false))) ?? []
+ return names.map { folder.appending(path: $0) }.filter { url in
+ var info = stat()
+ guard lstat(url.path(percentEncoded: false), &info) == 0 else { return false }
+ if info.st_mode & S_IFMT == S_IFDIR {
+ return !url.pathExtension.isEmpty && isIntelOnly(bundle: url)
+ }
+ // A library or a bundle kept beside the programs runs in the process that loads it.
+ return info.st_mode & S_IFMT == S_IFREG && isIntelOnly(executable: url)
+ && MachOHeader.isProgram(at: url)
}
- // A library or a bundle kept beside the programs runs in the process that loads it.
- return info.st_mode & S_IFMT == S_IFREG && isIntelOnly(executable: url)
- && MachOHeader.isProgram(at: url)
}
- }
}
/// Returns the processes under `Contents/Frameworks`: apps and XPC services kept there directly, as every
diff --git a/Packages/PeelCore/Sources/PeelCore/Apps/Inventory.swift b/Packages/PeelCore/Sources/PeelCore/Apps/Inventory.swift
index 8cbf3a2f..73a1476f 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/Inventory.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/Inventory.swift
@@ -65,7 +65,11 @@ public struct Inventory: Sendable {
return Inventory(entries: entries, brewfile: brewfile)
}
- static func entry(for app: InstalledApp, casks: [HomebrewPackage], origins: DownloadOrigins.Reader?) -> 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(
@@ -84,7 +88,11 @@ 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.Reader?) -> (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/Sources/PeelCore/Apps/RunningCopies.swift b/Packages/PeelCore/Sources/PeelCore/Apps/RunningCopies.swift
index 54918c65..afbb4fa3 100644
--- a/Packages/PeelCore/Sources/PeelCore/Apps/RunningCopies.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Apps/RunningCopies.swift
@@ -19,7 +19,9 @@ public enum RunningCopies {
@MainActor
public static var current: [Process] {
NSWorkspace.shared.runningApplications.compactMap { running in
- running.bundleIdentifier.map { Process(identifier: running.processIdentifier, bundleIdentifier: $0, bundleURL: running.bundleURL) }
+ running.bundleIdentifier.map {
+ Process(identifier: running.processIdentifier, bundleIdentifier: $0, bundleURL: running.bundleURL)
+ }
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swift
index ca67c3db..72bf935e 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemActions.swift
@@ -41,7 +41,10 @@ public enum BackgroundItemActions {
case blockedByQuarantine
}
- static func plan(toStart item: BackgroundItem, isRefusedByLaunchd: (URL) -> Bool = Quarantine.stopsLaunchd) -> Start {
+ static func plan(
+ toStart item: BackgroundItem,
+ isRefusedByLaunchd: (URL) -> Bool = Quarantine.stopsLaunchd
+ ) -> Start {
guard item.state == .notLoaded, let plist = item.plistURL else { return .kickstart }
return isRefusedByLaunchd(plist) ? .blockedByQuarantine : .bootstrap(plist)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemOwnership.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemOwnership.swift
index 2f0f309a..42ec91b4 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemOwnership.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItemOwnership.swift
@@ -29,7 +29,10 @@ public struct BackgroundItemOwnership: Sendable {
init(installedApps: [InstalledApp], teamOfProgram: @escaping @Sendable (String) -> String?) {
self.teamOfProgram = teamOfProgram
apps = installedApps
- byIdentifier = Dictionary(installedApps.map { ($0.bundleIdentifier.lowercased(), $0) }, uniquingKeysWith: { first, _ in first })
+ byIdentifier = Dictionary(
+ installedApps.map { ($0.bundleIdentifier.lowercased(), $0) },
+ uniquingKeysWith: { first, _ in first }
+ )
byTeam = Dictionary(grouping: installedApps.compactMap { app in app.teamIdentifier.map { ($0, app) } }, by: \.0)
.mapValues { $0.map(\.1) }
}
@@ -49,7 +52,9 @@ public struct BackgroundItemOwnership: Sendable {
return owner(forIdentifier: registeredBy)
}
let team = program.flatMap(teamOfProgram)
- if let team, let app = associated.lazy.compactMap({ byIdentifier[$0.lowercased()] }).first(where: { $0.teamIdentifier == team }) {
+ if let team,
+ let app = associated.lazy.compactMap({ byIdentifier[$0.lowercased()] })
+ .first(where: { $0.teamIdentifier == team }) {
return Owner(bundleIdentifier: app.bundleIdentifier, name: app.name, url: app.url)
}
if let identifier = Self.bundleIdentifier(inProgramPath: program) {
@@ -58,14 +63,25 @@ public struct BackgroundItemOwnership: Sendable {
return owner
}
if let app = appMatching(label: label) {
- return Owner(bundleIdentifier: app.bundleIdentifier, name: app.name, url: app.url, isConfirmed: proves(program, app, team: team))
+ return Owner(
+ bundleIdentifier: app.bundleIdentifier,
+ name: app.name,
+ url: app.url,
+ isConfirmed: proves(program, app, team: team)
+ )
}
if let team, let candidates = byTeam[team], candidates.count == 1 {
- return Owner(bundleIdentifier: candidates[0].bundleIdentifier, name: candidates[0].name, url: candidates[0].url)
+ return Owner(
+ bundleIdentifier: candidates[0].bundleIdentifier,
+ name: candidates[0].name,
+ url: candidates[0].url
+ )
}
// No installed app claims the job. An app the plist names that is gone is still returned, so the user
// can see which app it was. That app is not installed, so it keeps nothing from being called orphaned.
- let gone = associated.first { byIdentifier[$0.lowercased()] == nil && AppInspector.applicationURL(forBundleIdentifier: $0) == nil }
+ let gone = associated.first {
+ byIdentifier[$0.lowercased()] == nil && AppInspector.applicationURL(forBundleIdentifier: $0) == nil
+ }
return gone.map { Owner(bundleIdentifier: $0, name: nil, url: nil, isConfirmed: false) }
}
@@ -100,14 +116,21 @@ public struct BackgroundItemOwnership: Sendable {
return Owner(bundleIdentifier: app.bundleIdentifier, name: app.name, url: app.url)
}
let elsewhere = AppInspector.applicationURL(forBundleIdentifier: identifier)
- return Owner(bundleIdentifier: identifier, name: elsewhere?.deletingPathExtension().lastPathComponent, url: elsewhere)
+ return Owner(
+ bundleIdentifier: identifier,
+ name: elsewhere?.deletingPathExtension().lastPathComponent,
+ url: elsewhere
+ )
}
/// Whether `program` is `app`'s own: signed by its team, or inside its bundle.
private func proves(_ program: String?, _ app: InstalledApp, team: String?) -> Bool {
if let team, team == app.teamIdentifier { return true }
guard let program else { return false }
- return PathComponents.isPath(PathPattern.comparablePath(of: URL(filePath: program)), inside: PathPattern.comparablePath(of: app.url))
+ return PathComponents.isPath(
+ PathPattern.comparablePath(of: URL(filePath: program)),
+ inside: PathPattern.comparablePath(of: app.url)
+ )
}
/// Returns the installed app whose bundle identifier is the label, or else the longest one the label
diff --git a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
index 12aceeca..d41b03d7 100644
--- a/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
+++ b/Packages/PeelCore/Sources/PeelCore/BackgroundItems/BackgroundItems.swift
@@ -35,12 +35,16 @@ public enum BackgroundItems {
var results: [BackgroundItem] = []
for _ in 0..<concurrentDetailQueries {
guard let next = pending.next() else { break }
- group.addTask { await appSubmittedItem(next, ownership: ownership, loaded: loaded, exclusions: exclusions) }
+ group.addTask {
+ await appSubmittedItem(next, ownership: ownership, loaded: loaded, exclusions: exclusions)
+ }
}
while let result = await group.next() {
if let result { results.append(result) }
if !Task.isCancelled, let next = pending.next() {
- group.addTask { await appSubmittedItem(next, ownership: ownership, loaded: loaded, exclusions: exclusions) }
+ group.addTask {
+ await appSubmittedItem(next, ownership: ownership, loaded: loaded, exclusions: exclusions)
+ }
}
}
return results
@@ -72,7 +76,11 @@ public enum BackgroundItems {
/// The jobs launchd keeps disabled that no row lists, because they are not loaded and no file here declares
/// them, when they belong to an installed app. A job an app registered is seen only while it is loaded, so without
/// this row, one disabled here would leave the list after a restart, with no way to Enable it again.
- static func disabledJobs(in loaded: Loaded, listed: [BackgroundItem], ownership: BackgroundItemOwnership) -> [BackgroundItem] {
+ static func disabledJobs(
+ in loaded: Loaded,
+ listed: [BackgroundItem],
+ ownership: BackgroundItemOwnership
+ ) -> [BackgroundItem] {
let known = Set(listed.map { "\($0.kind.rawValue)/\($0.label)" })
let overrides = (loaded.userDisabled ?? [:]).map { ($0.key, $0.value, BackgroundItem.Kind.agent) }
+ (loaded.systemDisabled ?? [:]).map { ($0.key, $0.value, BackgroundItem.Kind.daemon) }
diff --git a/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift b/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift
index a1ef9d1e..eae9a7e7 100644
--- a/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift
@@ -97,7 +97,8 @@ public struct DeveloperEnvironment: Sendable, Hashable, Identifiable {
/// folders. Asked each time, since an app can be opened at any moment.
public var runningApp: String? {
appBundleIdentifiers.lazy.compactMap { identifier in
- NSRunningApplication.runningApplications(withBundleIdentifier: identifier).lazy.compactMap(\.localizedName).first
+ NSRunningApplication.runningApplications(withBundleIdentifier: identifier)
+ .lazy.compactMap(\.localizedName).first
}.first
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Developer/ProjectArtifacts.swift b/Packages/PeelCore/Sources/PeelCore/Developer/ProjectArtifacts.swift
index 8841c40c..5aac03a5 100644
--- a/Packages/PeelCore/Sources/PeelCore/Developer/ProjectArtifacts.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Developer/ProjectArtifacts.swift
@@ -404,7 +404,9 @@ public enum ProjectArtifacts {
private static let exactMarkers = Set(
definitions.flatMap(\.markers).filter { !$0.hasPrefix("*") }.compactMap { PathComponents.of($0).first }
)
- private static let markerSuffixes = Set(definitions.flatMap(\.markers).filter { $0.hasPrefix("*") }.map { String($0.dropFirst()) })
+ private static let markerSuffixes = Set(
+ definitions.flatMap(\.markers).filter { $0.hasPrefix("*") }.map { String($0.dropFirst()) }
+ )
static let maximumDepth = 8
static let maximumFolders = 40_000
@@ -493,7 +495,9 @@ public enum ProjectArtifacts {
}
var isDirectory: ObjCBool = false
- let isThere = FileManager.default.fileExists(atPath: PathPattern.comparablePath(of: root), isDirectory: &isDirectory) && isDirectory.boolValue
+ let isThere =
+ FileManager.default.fileExists(atPath: PathPattern.comparablePath(of: root), isDirectory: &isDirectory)
+ && isDirectory.boolValue
guard isThere else { return .notAFolder }
return root.isOrIsInsideAPackage ? .inAPackage : nil
}
@@ -564,7 +568,9 @@ public enum ProjectArtifacts {
guard depth < maximumDepth else { continue }
for entry in look.entries where !reached.contains(Self.key(of: entry)) {
- guard isRealFolder(entry), !exclusions.excludes(entry), !isSkipped(entry.lastPathComponent) else { continue }
+ guard isRealFolder(entry), !exclusions.excludes(entry), !isSkipped(entry.lastPathComponent) else {
+ continue
+ }
queue.append((entry, depth + 1))
}
}
@@ -632,7 +638,8 @@ public enum ProjectArtifacts {
var newest: Date?
for mark in gitMarks {
let url = project.appending(path: mark)
- guard let date = try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate else { continue }
+ guard let date = try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
+ else { continue }
if newest == nil || date > newest! { newest = date }
if date > cutoff { return (date, true) }
}
@@ -656,7 +663,8 @@ public enum ProjectArtifacts {
}
samples += 1
guard samples <= maximumActivitySamples else { return (newest, false) }
- guard let date = try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate else { continue }
+ guard let date = try? url.resourceValues(forKeys: [.contentModificationDateKey]).contentModificationDate
+ else { continue }
if newest == nil || date > newest! { newest = date }
if date > cutoff { return (date, true) }
}
@@ -680,8 +688,12 @@ public enum ProjectArtifacts {
/// Not a link, a cloud placeholder, or a package: an Electron app ships `package.json` beside `node_modules`
/// inside its bundle.
static func isRealFolder(_ url: URL) -> Bool {
- let values = try? url.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey, .isUbiquitousItemKey, .isPackageKey])
- guard values?.isDirectory == true, values?.isSymbolicLink != true, values?.isPackage != true else { return false }
+ let values = try? url.resourceValues(forKeys: [
+ .isDirectoryKey, .isSymbolicLinkKey, .isUbiquitousItemKey, .isPackageKey,
+ ])
+ guard values?.isDirectory == true, values?.isSymbolicLink != true, values?.isPackage != true else {
+ return false
+ }
return values?.isUbiquitousItem != true
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Duplicates/DigestMemory.swift b/Packages/PeelCore/Sources/PeelCore/Duplicates/DigestMemory.swift
index d94ed139..a7136ef8 100644
--- a/Packages/PeelCore/Sources/PeelCore/Duplicates/DigestMemory.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Duplicates/DigestMemory.swift
@@ -80,7 +80,9 @@ public struct DigestMemory: Sendable {
while offset < body {
let key = KnownDigests.Key(
device: next(Int64.self), inode: next(UInt64.self), size: next(Int64.self),
- modificationTime: next(Int64.self), statusChangeTime: next(Int64.self), creationTime: next(Int64.self)
+ modificationTime: next(Int64.self),
+ statusChangeTime: next(Int64.self),
+ creationTime: next(Int64.self)
)
let lastUsed = next(UInt32.self)
let parts = next(UInt32.self)
@@ -107,7 +109,10 @@ public struct DigestMemory: Sendable {
}
let none = [UInt8](repeating: 0, count: ContentDigest.byteCount)
for (key, entry) in kept {
- for number in [key.device, Int64(bitPattern: key.inode), key.size, key.modificationTime, key.statusChangeTime, key.creationTime] {
+ for number in [
+ key.device, Int64(bitPattern: key.inode), key.size, key.modificationTime, key.statusChangeTime,
+ key.creationTime,
+ ] {
append(number)
}
append(entry.lastUsed)
@@ -131,7 +136,14 @@ final class KnownDigests: Sendable {
let statusChangeTime: Int64
let creationTime: Int64
- init(device: Int64, inode: UInt64, size: Int64, modificationTime: Int64, statusChangeTime: Int64, creationTime: Int64) {
+ init(
+ device: Int64,
+ inode: UInt64,
+ size: Int64,
+ modificationTime: Int64,
+ statusChangeTime: Int64,
+ creationTime: Int64
+ ) {
self.device = device
self.inode = inode
self.size = size
diff --git a/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateFinder.swift b/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateFinder.swift
index 4abb6073..6334ddbc 100644
--- a/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateFinder.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateFinder.swift
@@ -16,7 +16,11 @@ public struct DuplicateFinder: Sendable {
/// Without a `digestMemory`, every file is read and no digest is saved, so tests never touch the user's
/// saved digests.
- public init(homeDirectory: URL = .homeDirectory, exclusions: Exclusions = .none, digestMemory: DigestMemory? = nil) {
+ public init(
+ homeDirectory: URL = .homeDirectory,
+ exclusions: Exclusions = .none,
+ digestMemory: DigestMemory? = nil
+ ) {
self.exclusions = exclusions
self.homeDirectory = homeDirectory.resolvingSymlinksInPath()
self.digestMemory = digestMemory
@@ -71,7 +75,11 @@ public struct DuplicateFinder: Sendable {
// Folders are compared only when no file kind is chosen: a kind, such as images, applies to files alone.
let folderGroups = options.kind == .any
- ? try await FolderDuplicates(managed: Self.managedPaths(home: homeDirectory), exclusions: exclusions, neverProjects: neverProjects).groups(
+ ? try await FolderDuplicates(
+ managed: Self.managedPaths(home: homeDirectory),
+ exclusions: exclusions,
+ neverProjects: neverProjects
+ ).groups(
in: scannable,
minimumSize: options.minimumSize,
downloads: Self.path(of: homeDirectory.appending(path: "Downloads")),
@@ -82,7 +90,13 @@ public struct DuplicateFinder: Sendable {
: []
let spokenFor = Set(folderGroups.flatMap { $0.folders.map { Self.path(of: $0.url) } })
- let collected = try collect(options, in: scannable, spokenFor: spokenFor, neverProjects: neverProjects, progress: progress)
+ let collected = try collect(
+ options,
+ in: scannable,
+ spokenFor: spokenFor,
+ neverProjects: neverProjects,
+ progress: progress
+ )
// Each file is read once, under the first of its names, and an excluded name is never read.
var names: [FileIdentity.Link: [Candidate]] = [:]
var files: [Candidate] = []
@@ -93,17 +107,26 @@ public struct DuplicateFinder: Sendable {
let sameSize = Dictionary(grouping: files, by: \.identity.size).values.filter { $0.count > 1 }.flatMap { $0 }
let comparing = ReportThrottle()
- let sampled = await FileDigest.many(sameSize, digest: { FileDigest.sample(of: $0.url, identity: $0.identity, known: known) }) { completed in
+ let sampled = await FileDigest.many(
+ sameSize,
+ digest: { FileDigest.sample(of: $0.url, identity: $0.identity, known: known) }
+ ) { completed in
if comparing.allows(isLast: completed == sameSize.count) {
progress(.comparing(filesCompared: completed, filesToCompare: sameSize.count))
}
}
guard !Task.isCancelled else { throw CancellationError() }
- let sampledGroups = try Self.movable(Self.grouped(sampled), names: names) { removalGuard.allowsRemoval(of: $0) && !$0.isInTheCloud }
+ let sampledGroups = try Self.movable(Self.grouped(sampled), names: names) {
+ removalGuard.allowsRemoval(of: $0) && !$0.isInTheCloud
+ }
let finalGroups = sampledGroups.filter { !FileDigest.isSampled(size: $0[0].item.identity.size) }
- let toVerify = sampledGroups.filter { FileDigest.isSampled(size: $0[0].item.identity.size) }.flatMap { $0.map(\.item) }
- let reading = ReadProgress(bytesToRead: FileDigest.bytesToRead(toVerify.map(\.identity), known: known), report: progress)
+ let toVerify = sampledGroups.filter { FileDigest.isSampled(size: $0[0].item.identity.size) }
+ .flatMap { $0.map(\.item) }
+ let reading = ReadProgress(
+ bytesToRead: FileDigest.bytesToRead(toVerify.map(\.identity), known: known),
+ report: progress
+ )
let verified = await FileDigest.many(toVerify) { candidate in
FileDigest.full(of: candidate.url, identity: candidate.identity, known: known, onRead: reading.add)
}
@@ -265,7 +288,12 @@ public struct DuplicateFinder: Sendable {
private func makeGroup(_ members: [HashedCandidate]) -> DuplicateGroup {
let downloads = Self.path(of: homeDirectory.appending(path: "Downloads"))
let files = members
- .map { ($0.item, Self.keepRank(of: $0.item.url, creationTime: $0.item.identity.creationTime, downloads: downloads)) }
+ .map {
+ (
+ $0.item,
+ Self.keepRank(of: $0.item.url, creationTime: $0.item.identity.creationTime, downloads: downloads)
+ )
+ }
.sorted { $0.1 < $1.1 }
.map { candidate, _ in
DuplicateFile(
@@ -299,7 +327,10 @@ public struct DuplicateFinder: Sendable {
/// out of the scan.
static func neverProjects(chosen: [URL], home: URL) -> Set<String> {
let home = path(of: home.resolvingSymlinksInPath())
- return Set(chosen.map { path(of: $0.resolvingSymlinksInPath()) } + [home] + ProtectedData.accountFolders.map { home + "/" + $0 })
+ return Set(
+ chosen.map { path(of: $0.resolvingSymlinksInPath()) } + [home]
+ + ProtectedData.accountFolders.map { home + "/" + $0 }
+ )
}
static func managedPaths(home: URL) -> Set<String> {
diff --git a/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateRemoval.swift b/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateRemoval.swift
index 5e83c39f..a2655c75 100644
--- a/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateRemoval.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateRemoval.swift
@@ -21,7 +21,8 @@ public enum DuplicateRemoval {
let kept = group.files.filter { !selection.contains($0.url) }
for file in selected {
- guard kept.contains(where: { FileIdentity.of($0.url)?.holdsTheSameContents(as: $0.identity) == true }) else {
+ guard kept.contains(where: { FileIdentity.of($0.url)?.holdsTheSameContents(as: $0.identity) == true })
+ else {
result.failures.append(TrashFailure(url: file.url, reason: .lastCopy))
continue
}
@@ -40,7 +41,11 @@ public enum DuplicateRemoval {
/// Moves the selected folders to the Trash. A folder moves only while it and at least one unselected folder
/// of its group still hold exactly what was compared: the same entries, each the same file with the same size
/// and times, with nothing added or removed.
- private static func trash(folders: Set<URL>, from scan: DuplicateScan, using trashService: TrashService) async -> TrashResult {
+ private static func trash(
+ folders: Set<URL>,
+ from scan: DuplicateScan,
+ using trashService: TrashService
+ ) async -> TrashResult {
var result = TrashResult()
for group in scan.folderGroups {
diff --git a/Packages/PeelCore/Sources/PeelCore/Duplicates/Duplicates.swift b/Packages/PeelCore/Sources/PeelCore/Duplicates/Duplicates.swift
index fb9566b4..ebe46407 100644
--- a/Packages/PeelCore/Sources/PeelCore/Duplicates/Duplicates.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Duplicates/Duplicates.swift
@@ -133,7 +133,9 @@ public struct DuplicateScan: Sendable {
public func excluded(by exclusions: Exclusions) async -> Set<URL> {
guard !exclusions.paths.isEmpty else { return [] }
let files = groups.flatMap(\.files).map(\.url).filter(exclusions.excludes)
- let folders = folderGroups.flatMap(\.folders).map(\.url).filter { exclusions.excludes($0) || exclusions.holds($0) }
+ let folders = folderGroups.flatMap(\.folders).map(\.url).filter {
+ exclusions.excludes($0) || exclusions.holds($0)
+ }
return Set(files + folders)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Duplicates/FileDigest.swift b/Packages/PeelCore/Sources/PeelCore/Duplicates/FileDigest.swift
index fbd2f268..2c78749b 100644
--- a/Packages/PeelCore/Sources/PeelCore/Duplicates/FileDigest.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Duplicates/FileDigest.swift
@@ -53,14 +53,25 @@ enum FileDigest {
let digest = isSampled(size: identity.size)
? read(url, bufferLength: sampleLength, identity: identity) { descriptor, buffer, hasher in
readFully(descriptor, count: sampleLength, offset: 0, buffer: buffer, into: &hasher)
- && readFully(descriptor, count: sampleLength, offset: identity.size - Int64(sampleLength), buffer: buffer, into: &hasher)
+ && readFully(
+ descriptor,
+ count: sampleLength,
+ offset: identity.size - Int64(sampleLength),
+ buffer: buffer,
+ into: &hasher
+ )
}
: whole(url, identity: identity)
if let digest { known?.keep(sample: digest, of: identity) }
return digest
}
- static func full(of url: URL, identity: FileIdentity, known: KnownDigests? = nil, onRead: (Int) -> Void = { _ in }) -> ContentDigest? {
+ static func full(
+ of url: URL,
+ identity: FileIdentity,
+ known: KnownDigests? = nil,
+ onRead: (Int) -> Void = { _ in }
+ ) -> ContentDigest? {
if let digest = known?.full(of: identity) { return digest }
let digest = whole(url, identity: identity, onRead: onRead)
if let digest { known?.keep(full: digest, of: identity) }
@@ -68,12 +79,18 @@ enum FileDigest {
}
private static func whole(_ url: URL, identity: FileIdentity, onRead: (Int) -> Void = { _ in }) -> ContentDigest? {
- read(url, bufferLength: Int(min(Int64(chunkLength), max(identity.size, 1))), identity: identity) { descriptor, buffer, hasher in
+ read(
+ url,
+ bufferLength: Int(min(Int64(chunkLength), max(identity.size, 1))),
+ identity: identity
+ ) { descriptor, buffer, hasher in
var offset: Int64 = 0
while offset < identity.size {
guard !Task.isCancelled else { return false }
let count = Int(min(Int64(buffer.count), identity.size - offset))
- guard readFully(descriptor, count: count, offset: offset, buffer: buffer, into: &hasher) else { return false }
+ guard readFully(descriptor, count: count, offset: offset, buffer: buffer, into: &hasher) else {
+ return false
+ }
offset += Int64(count)
onRead(count)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Duplicates/FolderDuplicates.swift b/Packages/PeelCore/Sources/PeelCore/Duplicates/FolderDuplicates.swift
index 014a799f..b3e35ddd 100644
--- a/Packages/PeelCore/Sources/PeelCore/Duplicates/FolderDuplicates.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Duplicates/FolderDuplicates.swift
@@ -64,7 +64,9 @@ struct FolderDuplicates: Sendable {
for root in roots.map({ $0.resolvingSymlinksInPath() })
where visited.insert(DuplicateFinder.path(of: root)).inserted {
var info = stat()
- guard lstat(root.path(percentEncoded: false), &info) == 0, info.st_mode & S_IFMT == S_IFDIR else { continue }
+ guard lstat(root.path(percentEncoded: false), &info) == 0, info.st_mode & S_IFMT == S_IFDIR else {
+ continue
+ }
let folder = try list(root, identity: FileIdentity(info), depth: 0, isNeverOffered: false) {
found += 1
if listing.allows(isLast: false) { progress(.listing(foldersFound: found)) }
@@ -80,7 +82,10 @@ struct FolderDuplicates: Sendable {
let files = Self.files(in: candidates)
let comparing = ReportThrottle()
- let sampled = await FileDigest.many(files, digest: { FileDigest.sample(of: $0.url, identity: $0.identity, known: known) }) { completed in
+ let sampled = await FileDigest.many(
+ files,
+ digest: { FileDigest.sample(of: $0.url, identity: $0.identity, known: known) }
+ ) { completed in
if comparing.allows(isLast: completed == files.count) {
progress(.comparing(filesCompared: completed, filesToCompare: files.count))
}
@@ -90,7 +95,10 @@ struct FolderDuplicates: Sendable {
let alike = grouped(candidates, by: samples).flatMap(\.folders)
let toRead = Self.files(in: alike).filter { FileDigest.isSampled(size: $0.identity.size) }
- let reading = ReadProgress(bytesToRead: FileDigest.bytesToRead(toRead.map(\.identity), known: known), report: progress)
+ let reading = ReadProgress(
+ bytesToRead: FileDigest.bytesToRead(toRead.map(\.identity), known: known),
+ report: progress
+ )
let read = await FileDigest.many(toRead) { file in
FileDigest.full(of: file.url, identity: file.identity, known: known, onRead: reading.add)
}
@@ -104,13 +112,15 @@ struct FolderDuplicates: Sendable {
/// Whether `folder` still holds exactly what the scan compared, listed again the same way. The exclusions and
/// managed folders are not needed: a folder that held an excluded or managed item was never offered.
static func holdsTheSameContents(_ folder: DuplicateFolder) -> Bool {
- FolderDuplicates(neverProjects: folder.neverProjects).contents(of: folder.url).map { $0 == folder.contents } ?? false
+ FolderDuplicates(neverProjects: folder.neverProjects).contents(of: folder.url).map { $0 == folder.contents }
+ ?? false
}
private func contents(of url: URL) -> String? {
var info = stat()
guard lstat(url.path(percentEncoded: false), &info) == 0, info.st_mode & S_IFMT == S_IFDIR else { return nil }
- guard let folder = try? list(url, identity: FileIdentity(info), depth: 0, isNeverOffered: false, onListing: {}) else { return nil }
+ guard let folder = try? list(url, identity: FileIdentity(info), depth: 0, isNeverOffered: false, onListing: {})
+ else { return nil }
return identity(of: folder).map(Self.hexadecimal)
}
@@ -139,7 +149,8 @@ struct FolderDuplicates: Sendable {
onListing()
// The listing and each entry get an autorelease pool of their own, or what Foundation reads for every entry
// would pile up in memory until the walk ends.
- guard depth < Self.depthLimit, let contents = autoreleasepool(invoking: { entries(of: url, depth: depth) }) else {
+ guard depth < Self.depthLimit, let contents = autoreleasepool(invoking: { entries(of: url, depth: depth) })
+ else {
folder.isWhole = false
return folder
}
@@ -151,7 +162,13 @@ struct FolderDuplicates: Sendable {
for entry in contents.entries {
switch autoreleasepool(invoking: { look(at: entry, isNeverOffered: isNeverOffered) }) {
case .folder(let name, let identity, let isNeverOffered):
- let child = try list(entry, identity: identity, depth: depth + 1, isNeverOffered: isNeverOffered, onListing: onListing)
+ let child = try list(
+ entry,
+ identity: identity,
+ depth: depth + 1,
+ isNeverOffered: isNeverOffered,
+ onListing: onListing
+ )
guard !child.isProject else {
folder.isWhole = false
continue
@@ -169,7 +186,8 @@ struct FolderDuplicates: Sendable {
}
private func entries(of url: URL, depth: Int) -> (entries: [URL], isProject: Bool)? {
- guard let entries = try? FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil) else {
+ guard let entries = try? FileManager.default.contentsOfDirectory(at: url, includingPropertiesForKeys: nil)
+ else {
return nil
}
let isProject = depth > 0 && !neverProjects.contains(DuplicateFinder.path(of: url))
diff --git a/Packages/PeelCore/Sources/PeelCore/Duplicates/ReclaimableSpace.swift b/Packages/PeelCore/Sources/PeelCore/Duplicates/ReclaimableSpace.swift
index 94719a5d..c7e9454e 100644
--- a/Packages/PeelCore/Sources/PeelCore/Duplicates/ReclaimableSpace.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Duplicates/ReclaimableSpace.swift
@@ -41,7 +41,10 @@ enum ReclaimableSpace {
request.bitmapcount = u_short(ATTR_BIT_MAP_COUNT)
request.volattr = attrgroup_t(ATTR_VOL_INFO) | attrgroup_t(ATTR_VOL_CAPABILITIES)
// Layout: UInt32 length, then the capabilities, whose interfaces word holds cloning and snapshots.
- var buffer = [UInt8](repeating: 0, count: MemoryLayout<UInt32>.size + MemoryLayout<vol_capabilities_attr_t>.size)
+ var buffer = [UInt8](
+ repeating: 0,
+ count: MemoryLayout<UInt32>.size + MemoryLayout<vol_capabilities_attr_t>.size
+ )
let status = buffer.withUnsafeMutableBytes { bytes in
getattrlist(path, &request, bytes.baseAddress, bytes.count, 0)
}
@@ -67,15 +70,25 @@ enum ReclaimableSpace {
let flagsOffset = sizeOffset + MemoryLayout<Int64>.size
var buffer = [UInt8](repeating: 0, count: 64)
let status = buffer.withUnsafeMutableBytes { bytes in
- getattrlist(path, &request, bytes.baseAddress, bytes.count, UInt32(FSOPT_ATTR_CMN_EXTENDED | FSOPT_NOFOLLOW | FSOPT_PACK_INVAL_ATTRS))
+ getattrlist(
+ path,
+ &request,
+ bytes.baseAddress,
+ bytes.count,
+ UInt32(FSOPT_ATTR_CMN_EXTENDED | FSOPT_NOFOLLOW | FSOPT_PACK_INVAL_ATTRS)
+ )
}
guard status == 0 else { return nil }
return buffer.withUnsafeBytes { bytes in
let returned = bytes.loadUnaligned(fromByteOffset: returnedExtendedOffset, as: UInt32.self)
return (
- returned & UInt32(ATTR_CMNEXT_PRIVATESIZE) != 0 ? bytes.loadUnaligned(fromByteOffset: sizeOffset, as: Int64.self) : nil,
+ returned & UInt32(ATTR_CMNEXT_PRIVATESIZE) != 0
+ ? bytes.loadUnaligned(fromByteOffset: sizeOffset, as: Int64.self)
+ : nil,
returned & UInt32(ATTR_CMNEXT_EXT_FLAGS) != 0
- ? bytes.loadUnaligned(fromByteOffset: flagsOffset, as: UInt64.self) & UInt64(EF_MAY_SHARE_BLOCKS) != 0 : nil
+ ? bytes.loadUnaligned(fromByteOffset: flagsOffset, as: UInt64.self)
+ & UInt64(EF_MAY_SHARE_BLOCKS) != 0
+ : nil
)
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Extensions/AppExtensions.swift b/Packages/PeelCore/Sources/PeelCore/Extensions/AppExtensions.swift
index 41bbfc5a..7ae43373 100644
--- a/Packages/PeelCore/Sources/PeelCore/Extensions/AppExtensions.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Extensions/AppExtensions.swift
@@ -121,7 +121,9 @@ public enum AppExtensions {
guard one == other else { return one.localizedStandardCompare(other) == .orderedAscending }
return $0.name.localizedStandardCompare($1.name) == .orderedAscending
},
- unanswered: Set([apps == nil ? .appExtension : nil, system == nil ? .systemExtension : nil].compactMap(\.self))
+ unanswered: Set(
+ [apps == nil ? .appExtension : nil, system == nil ? .systemExtension : nil].compactMap(\.self)
+ )
)
}
@@ -166,7 +168,9 @@ public enum AppExtensions {
.compactMap { parse(String($0)) }
.first { $0.identifier == identifier && $0.election == .on }
guard let chosen else { return false }
- let theirs = FileIdentity.Link.of(URL(filePath: chosen.path, directoryHint: .isDirectory).resolvingSymlinksInPath())
+ let theirs = FileIdentity.Link.of(
+ URL(filePath: chosen.path, directoryHint: .isDirectory).resolvingSymlinksInPath()
+ )
return theirs != FileIdentity.Link.of(own.resolvingSymlinksInPath())
}
@@ -233,7 +237,10 @@ public enum AppExtensions {
/// The name of the app the extension came with. This is the outermost app, so an extension inside
/// Instruments inside Xcode belongs to Xcode.
static func owner(ofExtensionAt path: String) -> String? {
- guard let end = path.range(of: ".app/") ?? (path.hasSuffix(".app") ? path.range(of: ".app", options: .backwards) : nil) else { return nil }
+ guard
+ let end = path.range(of: ".app/")
+ ?? (path.hasSuffix(".app") ? path.range(of: ".app", options: .backwards) : nil)
+ else { return nil }
return AppInspector.displayName(of: URL(filePath: String(path[..<end.lowerBound]) + ".app"))
}
@@ -274,8 +281,12 @@ public enum AppExtensions {
static func parseSystemExtension(
_ line: String
) -> (identifier: String, version: String?, name: String, teamIdentifier: String?, state: String)? {
- let fields = line.split(separator: "\t", omittingEmptySubsequences: false).map { String($0).trimmingCharacters(in: .whitespaces) }
- guard fields.count >= 6, let bracketed = fields.last, bracketed.hasPrefix("["), bracketed.hasSuffix("]") else { return nil }
+ let fields = line.split(separator: "\t", omittingEmptySubsequences: false).map {
+ String($0).trimmingCharacters(in: .whitespaces)
+ }
+ guard fields.count >= 6, let bracketed = fields.last, bracketed.hasPrefix("["), bracketed.hasSuffix("]") else {
+ return nil
+ }
let identifier = String(fields[3].prefix { $0 != " " })
guard identifier.contains(".") else { return nil }
let version = fields[3].dropFirst(identifier.count).trimmingCharacters(in: .whitespaces)
@@ -318,7 +329,11 @@ public enum AppExtensions {
/// The record of the extension `systemextensionsctl` listed: the one of its version, or the only one of its
/// identifier. During an update an identifier has a record per version, and the other version's copy is not
/// this one: no path is better than a wrong one.
- static func record(for identifier: String, version: String?, among records: [SystemExtensionRecord]) -> SystemExtensionRecord? {
+ static func record(
+ for identifier: String,
+ version: String?,
+ among records: [SystemExtensionRecord]
+ ) -> SystemExtensionRecord? {
let named = records.filter { $0.identifier == identifier }
return named.first { $0.version == version } ?? (named.count == 1 ? named.first : nil)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Home/Access.swift b/Packages/PeelCore/Sources/PeelCore/Home/Access.swift
index 84724b99..bc517b39 100644
--- a/Packages/PeelCore/Sources/PeelCore/Home/Access.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Home/Access.swift
@@ -105,7 +105,8 @@ public enum CommandLineTool {
// A file that is not a link: something else named `peel`, not Peel's tool.
return .somethingElse
}
- let target = URL(filePath: destination, relativeTo: URL(filePath: path).deletingLastPathComponent()).standardizedFileURL
+ let target = URL(filePath: destination, relativeTo: URL(filePath: path).deletingLastPathComponent())
+ .standardizedFileURL
guard target.path(percentEncoded: false) == embedded.standardizedFileURL.path(percentEncoded: false) else {
return isAPeelsTool(target) ? .otherPeel : .somethingElse
}
@@ -136,7 +137,11 @@ public enum AppManagement {
/// What a removal shows about App Management, or nil when it shows nothing. An app bundle Peel moved means
/// granted. A bundle macOS refused to move from a folder the user can write to, when nothing locks it, means
/// missing. Bundles the root helper moved don't count, since the helper doesn't need Peel's permission.
- public static func state(after result: TrashResult, appBundles: Set<URL>, movedByTheHelper: Set<URL> = []) -> AccessState? {
+ public static func state(
+ after result: TrashResult,
+ appBundles: Set<URL>,
+ movedByTheHelper: Set<URL> = []
+ ) -> AccessState? {
let asked = appBundles.subtracting(movedByTheHelper)
if result.trashed.contains(where: { asked.contains($0.originalURL) }) {
return .granted
diff --git a/Packages/PeelCore/Sources/PeelCore/Home/DeviceInfo.swift b/Packages/PeelCore/Sources/PeelCore/Home/DeviceInfo.swift
index b551bd48..e1766b8c 100644
--- a/Packages/PeelCore/Sources/PeelCore/Home/DeviceInfo.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Home/DeviceInfo.swift
@@ -25,7 +25,14 @@ public struct DeviceInfo: Sendable, Hashable {
public let memory: Int64
public let storage: Storage
- public init(model: String, modelIdentifier: String, chip: String, systemVersion: String, memory: Int64, storage: Storage) {
+ public init(
+ model: String,
+ modelIdentifier: String,
+ chip: String,
+ systemVersion: String,
+ memory: Int64,
+ storage: Storage
+ ) {
self.model = model
self.modelIdentifier = modelIdentifier
self.chip = chip
@@ -96,7 +103,9 @@ public struct DeviceInfo: Sendable, Hashable {
}
public static func storage(of url: URL) -> Storage {
- let values = try? url.resourceValues(forKeys: [.volumeTotalCapacityKey, .volumeAvailableCapacityKey, .volumeAvailableCapacityForImportantUsageKey])
+ let values = try? url.resourceValues(forKeys: [
+ .volumeTotalCapacityKey, .volumeAvailableCapacityKey, .volumeAvailableCapacityForImportantUsageKey,
+ ])
return storage(
total: values?.volumeTotalCapacity,
available: values?.volumeAvailableCapacity,
diff --git a/Packages/PeelCore/Sources/PeelCore/Home/FoundLastTime.swift b/Packages/PeelCore/Sources/PeelCore/Home/FoundLastTime.swift
index f8b1975f..37ec016c 100644
--- a/Packages/PeelCore/Sources/PeelCore/Home/FoundLastTime.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Home/FoundLastTime.swift
@@ -31,7 +31,9 @@ public struct FoundLastTime: Sendable, Equatable {
}
public var data: Data {
- let entries = findings.mapValues { Stored(count: $0.count, bytes: $0.size?.known, complete: $0.size?.isComplete, date: $0.date) }
+ let entries = findings.mapValues {
+ Stored(count: $0.count, bytes: $0.size?.known, complete: $0.size?.isComplete, date: $0.date)
+ }
return (try? JSONEncoder().encode(entries)) ?? Data()
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Home/Greeting.swift b/Packages/PeelCore/Sources/PeelCore/Home/Greeting.swift
index 7795e4c5..96b06209 100644
--- a/Packages/PeelCore/Sources/PeelCore/Home/Greeting.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Home/Greeting.swift
@@ -18,7 +18,12 @@ public enum Greeting: String, Sendable, Hashable, CaseIterable {
/// When the greeting changes next, so a view can schedule its update.
public static func change(after date: Date, calendar: Calendar = .autoupdatingCurrent) -> Date {
let changes = startHours.compactMap {
- calendar.nextDate(after: date, matching: DateComponents(hour: $0), matchingPolicy: .nextTime, direction: .forward)
+ calendar.nextDate(
+ after: date,
+ matching: DateComponents(hour: $0),
+ matchingPolicy: .nextTime,
+ direction: .forward
+ )
}
return changes.min() ?? date.addingTimeInterval(3600)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Home/LookAround.swift b/Packages/PeelCore/Sources/PeelCore/Home/LookAround.swift
index 9d9b7196..faa9d481 100644
--- a/Packages/PeelCore/Sources/PeelCore/Home/LookAround.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Home/LookAround.swift
@@ -50,7 +50,8 @@ public struct LookAround: Sendable {
]
private static let cycle = places.indices.reduce(0) { total, index in
- total + places[index].seconds + travel(from: places[index].moment, to: places[(index + 1) % places.count].moment)
+ total + places[index].seconds
+ + travel(from: places[index].moment, to: places[(index + 1) % places.count].moment)
}
private let start: Moment
diff --git a/Packages/PeelCore/Sources/PeelCore/Homebrew/CaskEvidence.swift b/Packages/PeelCore/Sources/PeelCore/Homebrew/CaskEvidence.swift
index da91e717..68e42eff 100644
--- a/Packages/PeelCore/Sources/PeelCore/Homebrew/CaskEvidence.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Homebrew/CaskEvidence.swift
@@ -13,7 +13,11 @@ public struct CaskEvidence: Sendable, Hashable {
public let items: [Item]
- public static func evidence(for app: InstalledApp, casks: [HomebrewPackage], home: URL = .homeDirectory) -> CaskEvidence? {
+ public static func evidence(
+ for app: InstalledApp,
+ casks: [HomebrewPackage],
+ home: URL = .homeDirectory
+ ) -> CaskEvidence? {
guard let cask = cask(for: app, in: casks) else { return nil }
var seen: Set<ItemKey> = []
let named = cask.leftoverPatterns.flatMap { expand($0, home: home) }
@@ -34,7 +38,8 @@ public struct CaskEvidence: Sendable, Hashable {
let path = PathPattern.comparablePath(of: app.url)
return casks.first { cask in
guard cask.installedVersion != nil, proves(cask, isThe: app) else { return false }
- return cask.appTargets.isEmpty || cask.appTargets.contains { $0.caseInsensitiveCompare(path) == .orderedSame }
+ return cask.appTargets.isEmpty
+ || cask.appTargets.contains { $0.caseInsensitiveCompare(path) == .orderedSame }
}
}
@@ -52,7 +57,10 @@ public struct CaskEvidence: Sendable, Hashable {
var tokens: [String] = []
for name in app.names {
let plain = tokenize(name)
- let candidates = [plain, tokenize(separatingWords(in: name)), plain.replacingOccurrences(of: "-", with: ""), plain + "-app"]
+ let candidates = [
+ plain, tokenize(separatingWords(in: name)), plain.replacingOccurrences(of: "-", with: ""),
+ plain + "-app",
+ ]
for candidate in candidates where candidate.count >= 2 && !tokens.contains(candidate) {
tokens.append(candidate)
}
@@ -103,7 +111,9 @@ public struct CaskEvidence: Sendable, Hashable {
let bundleName = app.url.lastPathComponent
if cask.appNames.contains(where: { $0.caseInsensitiveCompare(bundleName) == .orderedSame }) {
let maker = Identifier.vendor(of: identifier)
- if quits.isEmpty || quits.contains(where: { maker != nil && Identifier.vendor(of: $0) == maker }) { return true }
+ if quits.isEmpty || quits.contains(where: { maker != nil && Identifier.vendor(of: $0) == maker }) {
+ return true
+ }
}
guard !identifier.isEmpty else { return false }
@@ -137,8 +147,15 @@ public struct CaskEvidence: Sendable, Hashable {
/// Merges installed packages with the casks Homebrew only knows of, keeping the installed one when both
/// share an ID. `receipts`, the installer receipts on the Mac, are noted on each installed package, since
/// a receipt is what proves a cask that installs its app from a `.pkg`.
- public static func combined(installed: [HomebrewPackage], known: [HomebrewPackage], receipts: Set<String>) -> [HomebrewPackage] {
- var byID = Dictionary(installed.map { ($0.id, $0.noting(receipts: receipts)) }, uniquingKeysWith: { first, _ in first })
+ public static func combined(
+ installed: [HomebrewPackage],
+ known: [HomebrewPackage],
+ receipts: Set<String>
+ ) -> [HomebrewPackage] {
+ var byID = Dictionary(
+ installed.map { ($0.id, $0.noting(receipts: receipts)) },
+ uniquingKeysWith: { first, _ in first }
+ )
for cask in known where byID[cask.id] == nil {
byID[cask.id] = cask
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift
index f6ffaec5..38b32bb3 100644
--- a/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Homebrew/Homebrew.swift
@@ -449,14 +449,22 @@ public enum Homebrew {
@concurrent
public static func caskTokens() async -> Set<String> {
guard let output = try? await answer(["casks"]) else { return [] }
- return Set(output.split(whereSeparator: \.isNewline).map { String($0).trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty })
+ return Set(
+ output.split(whereSeparator: \.isNewline)
+ .map { String($0).trimmingCharacters(in: .whitespaces) }
+ .filter { !$0.isEmpty }
+ )
}
/// Returns the name of every formula Homebrew knows of, read from its local copy of the definitions.
@concurrent
public static func formulaNames() async -> Set<String> {
guard let output = try? await answer(["formulae"]) else { return [] }
- return Set(output.split(whereSeparator: \.isNewline).map { String($0).trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty })
+ return Set(
+ output.split(whereSeparator: \.isNewline)
+ .map { String($0).trimmingCharacters(in: .whitespaces) }
+ .filter { !$0.isEmpty }
+ )
}
/// Asks about several formulae in one call. A single unknown name makes the whole call fail, so only names from
@@ -481,14 +489,20 @@ public enum Homebrew {
/// hours: `onOutput` is handed what Homebrew writes as it writes it, so the person can follow it, and the
/// upgrade stops when its task is canceled.
@concurrent
- public static func upgrade(_ package: HomebrewPackage, onOutput: @escaping @Sendable (Data) -> Void) async throws(CommandFailure) -> String {
+ public static func upgrade(
+ _ package: HomebrewPackage,
+ onOutput: @escaping @Sendable (Data) -> Void
+ ) async throws(CommandFailure) -> String {
let arguments = ["upgrade", package.kind == .cask ? "--cask" : "--formula", package.name]
return try await execute(arguments, autoUpdate: true, timeout: nil, onOutput: onOutput).transcript()
}
/// Upgrades `packages` the same way.
@concurrent
- public static func upgrade(_ packages: [HomebrewPackage], onOutput: @escaping @Sendable (Data) -> Void) async throws(CommandFailure) -> String {
+ public static func upgrade(
+ _ packages: [HomebrewPackage],
+ onOutput: @escaping @Sendable (Data) -> Void
+ ) async throws(CommandFailure) -> String {
// Said once: both calls below would fail the same way.
guard executableURL != nil else { throw CommandFailure(output: notInstalled) }
return try await upgrade(packages) { arguments throws(CommandFailure) in
@@ -621,7 +635,9 @@ public enum Homebrew {
@concurrent
public static func vulnerabilities() async throws(CommandFailure) -> HomebrewVulnerabilityReport {
let attempt = try await execute(["vulns", "--json"], autoUpdate: false, timeout: longestCommand)
- guard var report = (try? JSONDecoder().decode(VulnsReport.self, from: Data(attempt.standardOutput.utf8)))?.report else {
+ guard
+ var report = (try? JSONDecoder().decode(VulnsReport.self, from: Data(attempt.standardOutput.utf8)))?.report
+ else {
throw CommandFailure(output: attempt.output)
}
report.caveats = attempt.standardError.trimmingCharacters(in: .whitespacesAndNewlines)
@@ -715,7 +731,9 @@ public enum Homebrew {
quitIdentifiers: cask.artifacts?.flatMap(\.quitIdentifiers) ?? [],
packageIdentifiers: cask.artifacts?.flatMap(\.packageIdentifiers) ?? [],
retirement: cask.retirement.value,
- upgradeNeedsAnAdministrator: cask.artifacts?.contains { $0.installNeedsAnAdministrator || $0.uninstallNeedsAnAdministrator } ?? false,
+ upgradeNeedsAnAdministrator: cask.artifacts?.contains {
+ $0.installNeedsAnAdministrator || $0.uninstallNeedsAnAdministrator
+ } ?? false,
uninstallNeedsAnAdministrator: cask.artifacts?.contains(where: \.uninstallNeedsAnAdministrator) ?? false
)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift
index aa5b8fe9..581b5cb8 100644
--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/Leftover.swift
@@ -136,7 +136,14 @@ public struct LeftoverMatch: Sendable, Hashable {
/// Returns the same match, held back for `heldBack`: shown, but never selected.
public func forReview(_ heldBack: HoldBack) -> LeftoverMatch {
- LeftoverMatch(reason: reason, confidence: confidence, sharedWith: sharedWith, otherCopies: otherCopies, heldBack: heldBack, isAWord: isAWord)
+ LeftoverMatch(
+ reason: reason,
+ confidence: confidence,
+ sharedWith: sharedWith,
+ otherCopies: otherCopies,
+ heldBack: heldBack,
+ isAWord: isAWord
+ )
}
/// Returns the same match, no surer than `ceiling`.
@@ -151,7 +158,9 @@ public struct LeftoverMatch: Sendable, Hashable {
/// and if either one is held back, so is the result.
func combined(with other: LeftoverMatch) -> LeftoverMatch {
let weaker = [self, other].min { lhs, rhs in
- lhs.confidence != rhs.confidence ? lhs.confidence < rhs.confidence : lhs.reason.rawValue < rhs.reason.rawValue
+ lhs.confidence != rhs.confidence
+ ? lhs.confidence < rhs.confidence
+ : lhs.reason.rawValue < rhs.reason.rawValue
} ?? self
// A reason that blocks the move outranks one that only leaves the item unselected.
let heldBack = [heldBack, other.heldBack].compactMap(\.self).min { lhs, rhs in
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverMatcher.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverMatcher.swift
index b9c85be7..581add90 100644
--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverMatcher.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverMatcher.swift
@@ -189,7 +189,9 @@ extension LeftoverMatcher {
isAWord = false
rank = Self.tier(of: reason) * 10_000 + specificity
family = switch reason {
- case .bundleIdentifier, .embeddedBundleIdentifier, .applicationGroup, .bundleIdentifierPrefix, .launchdJob, .linksToTheApp, .installerReceipt: .identifier
+ case .bundleIdentifier, .embeddedBundleIdentifier, .applicationGroup, .bundleIdentifierPrefix,
+ .launchdJob, .linksToTheApp, .installerReceipt:
+ .identifier
case .name, .namePrefix, .homebrewCask: .name
case .teamIdentifier, .vendorPrefix: .maker
}
@@ -251,7 +253,10 @@ extension LeftoverMatcher {
identifier = app.bundleIdentifier.lowercased()
let vendor = Identifier.vendor(of: identifier)
embeddedIdentifiers = app.embeddedBundleIdentifiers.map {
- EmbeddedIdentifier(value: $0.lowercased(), sharesVendor: vendor != nil && Identifier.vendor(of: $0) == vendor)
+ EmbeddedIdentifier(
+ value: $0.lowercased(),
+ sharesVendor: vendor != nil && Identifier.vendor(of: $0) == vendor
+ )
}
prefixes = ([identifier] + embeddedIdentifiers.map(\.value))
.filter { Identifier.componentCount(of: $0) >= 3 }
@@ -295,7 +300,11 @@ extension LeftoverMatcher {
}
if let embedded = embeddedIdentifiers.first(where: { $0.value == key }) {
guard Identifier.isValid(key) else { return unproven(.embeddedBundleIdentifier, candidate) }
- return Evidence(.embeddedBundleIdentifier, embedded.sharesVendor ? .certain : .likely, specificity: key.count)
+ return Evidence(
+ .embeddedBundleIdentifier,
+ embedded.sharesVendor ? .certain : .likely,
+ specificity: key.count
+ )
}
if applicationGroups.contains(key) {
guard Identifier.isGroup(key) else { return unproven(.applicationGroup, candidate) }
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift
index ebf7d050..0a13a209 100644
--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/LeftoverScanner.swift
@@ -60,7 +60,10 @@ public struct LeftoverScanner: Sendable {
let identifiers = [app.bundleIdentifier] + makers.filter { $0.lowercased() != own }.sorted()
let wanted = Set(identifiers.map { $0.lowercased() })
let bundle = PathPattern.comparablePath(of: PathPattern.canonical(app.url))
- let listed = Set(known.filter { wanted.contains($0.bundleIdentifier.lowercased()) }.map { PathPattern.comparablePath(of: PathPattern.canonical($0.url)) })
+ let listed = Set(
+ known.filter { wanted.contains($0.bundleIdentifier.lowercased()) }
+ .map { PathPattern.comparablePath(of: PathPattern.canonical($0.url)) }
+ )
return identifiers.flatMap(AppInspector.applicationURLs).filter { url in
let path = PathPattern.comparablePath(of: PathPattern.canonical(url))
return !listed.contains(path) && !PathComponents.isPath(path, atOrInside: bundle)
@@ -86,7 +89,12 @@ public struct LeftoverScanner: Sendable {
let bundle = PathPattern.comparablePath(of: app.url)
_ = group.addTaskUnlessCancelled { [exclusions, measure, refuses, nestedFolderLimit] in
(location, await Self.scan(
- location, matcher: matcher, home: home, bundle: bundle, exclusions: exclusions, measure: measure,
+ location,
+ matcher: matcher,
+ home: home,
+ bundle: bundle,
+ exclusions: exclusions,
+ measure: measure,
refuses: refuses, nestedFolderLimit: nestedFolderLimit
))
}
@@ -131,7 +139,9 @@ public struct LeftoverScanner: Sendable {
PathComponents.of(location.url.path(percentEncoded: false)).count
}
let nearestFirst = found.sorted { one, other in
- guard depth(one.location) == depth(other.location) else { return depth(one.location) > depth(other.location) }
+ guard depth(one.location) == depth(other.location) else {
+ return depth(one.location) > depth(other.location)
+ }
// Two locations as deep never reach the same file; any fixed order will do.
return (one.location.url.path(percentEncoded: false), one.location.kind.rawValue)
< (other.location.url.path(percentEncoded: false), other.location.kind.rawValue)
@@ -181,7 +191,8 @@ public struct LeftoverScanner: Sendable {
do {
// Sorted, because Apple documents the order of a listing as undefined, and with a limit on how many
// folders are looked into, the order decides which ones.
- entries = try FileManager.default.contentsOfDirectory(atPath: location.url.path(percentEncoded: false)).sorted()
+ entries = try FileManager.default.contentsOfDirectory(atPath: location.url.path(percentEncoded: false))
+ .sorted()
ScanCount.current?.add(entries.count)
} catch CocoaError.fileReadNoSuchFile {
return .found([], cutShort: nil, unreadable: [])
@@ -200,10 +211,12 @@ public struct LeftoverScanner: Sendable {
guard !Task.isCancelled else { break }
let url = location.url.appending(path: name)
let path = url.path(percentEncoded: false)
- if let match = claim(name, at: url, kind: location.kind, matcher: matcher, bundle: bundle), !isSharedWithTheWholeMac(url, home: home) {
+ if let match = claim(name, at: url, kind: location.kind, matcher: matcher, bundle: bundle),
+ !isSharedWithTheWholeMac(url, home: home) {
guard !refuses(path, home), !exclusions.excludes(url) else { continue }
toMeasure.append(Found(url: url, match: match, parent: parent, isInsideAnotherAppsFolder: false))
- } else if nestedKinds.contains(location.kind), url.isRealFolder, !refuses(path, home), !exclusions.excludes(url) {
+ } else if nestedKinds.contains(location.kind), url.isRealFolder, !refuses(path, home),
+ !exclusions.excludes(url) {
// Not this app's. Whether it is somebody else's decides what a name inside it is worth.
nobodysFolders.append((url, isSomebodyElses(name, kind: location.kind, matcher: matcher)))
}
@@ -240,8 +253,12 @@ public struct LeftoverScanner: Sendable {
for depth in 0..<nestedDepth {
var deeper: [(url: URL, isAnotherApps: Bool)] = []
for (folder, isAnotherApps) in pending {
- guard !Task.isCancelled else { return (await measured(found, kind: kind, home: home, measure: measure), false, unreadable) }
- guard visited < limit else { return (await measured(found, kind: kind, home: home, measure: measure), true, unreadable) }
+ guard !Task.isCancelled else {
+ return (await measured(found, kind: kind, home: home, measure: measure), false, unreadable)
+ }
+ guard visited < limit else {
+ return (await measured(found, kind: kind, home: home, measure: measure), true, unreadable)
+ }
visited += 1
let names: [String]
do {
@@ -266,8 +283,11 @@ public struct LeftoverScanner: Sendable {
if let match = Self.match(name, at: url, kind: kind, matcher: matcher), match.confidence >= .likely,
!isSharedWithTheWholeMac(url, home: home) {
guard !refuses(path, home), !exclusions.excludes(url) else { continue }
- found.append(Found(url: url, match: match, parent: parent, isInsideAnotherAppsFolder: isAnotherApps))
- } else if depth + 1 < nestedDepth, url.isRealFolder, !refuses(path, home), !exclusions.excludes(url) {
+ found.append(
+ Found(url: url, match: match, parent: parent, isInsideAnotherAppsFolder: isAnotherApps)
+ )
+ } else if depth + 1 < nestedDepth, url.isRealFolder, !refuses(path, home),
+ !exclusions.excludes(url) {
deeper.append((url, isAnotherApps || isSomebodyElses(name, kind: kind, matcher: matcher)))
}
}
@@ -393,13 +413,20 @@ public struct LeftoverScanner: Sendable {
/// This app's claim on an item from its name and from the identifier it declares, which is read for a plug-in, a
/// crash report, and an item whose name answers nothing. The identifier says whose such an item is: a claim
/// through it replaces a weaker one on the name, and a name it does not back makes the item only possible.
- private static func match(_ name: String, at url: URL, kind: SearchLocation.Kind, matcher: LeftoverMatcher) -> LeftoverMatch? {
+ private static func match(
+ _ name: String,
+ at url: URL,
+ kind: SearchLocation.Kind,
+ matcher: LeftoverMatcher
+ ) -> LeftoverMatch? {
// A system extension macOS activated is its own to remove: it uninstalls one with the app it came in.
guard url.pathExtension.lowercased() != "systemextension" else { return nil }
let byName = matcher.match(fileName: name, kind: kind, at: url)
guard byName == nil || DeclaredIdentifier.outranksTheName(of: url, kind: kind) else { return byName }
// `.elsewhere`, so no extension is taken off the identifier as if it were a file name.
- let declared = DeclaredIdentifier.of(url, kind: kind).flatMap { matcher.match(fileName: $0, kind: .elsewhere, at: url) }
+ let declared = DeclaredIdentifier.of(url, kind: kind).flatMap {
+ matcher.match(fileName: $0, kind: .elsewhere, at: url)
+ }
guard let byName else { return declared }
guard let declared else { return byName.restsOnAName ? byName.atMost(.possible) : byName }
return declared.confidence >= byName.confidence ? declared : byName
@@ -415,7 +442,11 @@ public struct LeftoverScanner: Sendable {
/// A job that runs a program inside the app is that app's, whatever it is called: `com.maker.updater.plist`
/// carries no name of the app it keeps up to date. No rival is named, because a path inside one bundle
/// cannot be inside another.
- private static func runsSomethingInside(_ bundle: String, job url: URL, kind: SearchLocation.Kind) -> LeftoverMatch? {
+ private static func runsSomethingInside(
+ _ bundle: String,
+ job url: URL,
+ kind: SearchLocation.Kind
+ ) -> LeftoverMatch? {
guard kind == .launchAgents || kind == .launchDaemons, url.pathExtension == "plist" else { return nil }
guard let program = JobDefinition(contentsOf: url)?.program, program.hasPrefix("/") else { return nil }
let path = PathPattern.comparablePath(of: URL(filePath: program))
@@ -426,7 +457,11 @@ public struct LeftoverScanner: Sendable {
/// A link that leads inside the app is that app's, whatever the tool is called. A link that leads anywhere
/// else is not claimed. The link is read without following it, and a relative one is taken from its folder.
private static func leadsInside(_ bundle: String, link url: URL) -> LeftoverMatch? {
- guard let destination = try? FileManager.default.destinationOfSymbolicLink(atPath: url.path(percentEncoded: false)) else { return nil }
+ guard
+ let destination = try? FileManager.default.destinationOfSymbolicLink(
+ atPath: url.path(percentEncoded: false)
+ )
+ else { return nil }
let target = URL(filePath: destination, relativeTo: url.deletingLastPathComponent()).standardizedFileURL
let path = PathPattern.comparablePath(of: target)
guard PathComponents.isPath(path, inside: bundle) else { return nil }
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/Naming.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/Naming.swift
index 1144baee..0854213a 100644
--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/Naming.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/Naming.swift
@@ -24,7 +24,8 @@ enum Naming {
static func withoutTrailingVersion(_ name: String) -> String? {
guard let space = name.lastIndex(of: " ") else { return nil }
let version = name[name.index(after: space)...]
- guard !version.isEmpty, version.allSatisfy({ $0.isNumber || $0 == "." }), version.contains(where: \.isNumber) else { return nil }
+ guard !version.isEmpty, version.allSatisfy({ $0.isNumber || $0 == "." }), version.contains(where: \.isNumber)
+ else { return nil }
var base = String(name[..<space])
while base.hasSuffix(" ") { base.removeLast() }
return isSignificant(base) ? base : nil
@@ -62,7 +63,8 @@ enum Identifier {
let components = identifier.split(separator: ".", omittingEmptySubsequences: false)
guard components.count >= 2, !identifier.hasPrefix("-") else { return false }
return components.allSatisfy { component in
- !component.isEmpty && component.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == "_") }
+ !component.isEmpty
+ && component.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == "_") }
}
}
@@ -78,14 +80,16 @@ enum Identifier {
domain.allSatisfy({ $0.isASCII && $0.isLowercase })
else { return false }
return components.allSatisfy { component in
- !component.isEmpty && component.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == "_") }
+ !component.isEmpty
+ && component.allSatisfy { $0.isASCII && ($0.isLetter || $0.isNumber || $0 == "-" || $0 == "_") }
}
}
/// True for a group name in one of the forms macOS uses: a team identifier and a dot in front, or `group.`
/// and then a reverse DNS name. Expects the name lowercased, as the matcher keeps its keys.
static func isGroup(_ name: String) -> Bool {
- if let dot = name.firstIndex(of: "."), name[..<dot].count == 10, name[..<dot].allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber) }) {
+ if let dot = name.firstIndex(of: "."), name[..<dot].count == 10,
+ name[..<dot].allSatisfy({ $0.isASCII && ($0.isLetter || $0.isNumber) }) {
return name.index(after: dot) < name.endIndex
}
return name.hasPrefix("group.") && isReverseDNS(String(name.dropFirst("group.".count)))
@@ -96,7 +100,8 @@ enum Identifier {
guard let dot = name.firstIndex(of: ".") else { return nil }
let team = name[..<dot]
let remainder = name[name.index(after: dot)...]
- guard team.count == 10, team.allSatisfy({ $0.isASCII && ($0.isUppercase || $0.isNumber) }), !remainder.isEmpty else { return nil }
+ guard team.count == 10, team.allSatisfy({ $0.isASCII && ($0.isUppercase || $0.isNumber) }), !remainder.isEmpty
+ else { return nil }
return (String(team), String(remainder))
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swift b/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swift
index 6f3b320e..d0ecd8e6 100644
--- a/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Leftovers/SearchLocation.swift
@@ -75,7 +75,8 @@ extension SearchLocation.Kind {
case .privilegedHelperTools: self = .privilegedHelperTools
case .startupItems: self = .startupItems
case .frameworks: self = .frameworks
- case .audioUnits, .audioDrivers, .vst, .vst3, .clap, .midiDrivers, .internetPlugIns, .preferencePanes, .quickLook,
+ case .audioUnits, .audioDrivers, .vst, .vst3, .clap, .midiDrivers, .internetPlugIns, .preferencePanes,
+ .quickLook,
.screenSavers, .spotlight, .services, .inputMethods, .colorPickers, .contextualMenuItems, .mailBundles,
.aax, .mas, .imageUnits, .dictionaries, .automatorActions, .contactsPlugIns:
self = .plugIns
@@ -160,11 +161,17 @@ public struct SearchEnvironment: Sendable {
let userLibrary = homeDirectory.appending(path: "Library", directoryHint: .isDirectory)
let localLibrary = rootDirectory.appending(path: "Library", directoryHint: .isDirectory)
- var locations = Self.userEntries.map { SearchLocation(kind: $0.0, url: userLibrary.appending(path: $0.1, directoryHint: .isDirectory)) }
- locations += Self.localEntries.map { SearchLocation(kind: $0.0, url: localLibrary.appending(path: $0.1, directoryHint: .isDirectory)) }
+ var locations = Self.userEntries.map {
+ SearchLocation(kind: $0.0, url: userLibrary.appending(path: $0.1, directoryHint: .isDirectory))
+ }
+ locations += Self.localEntries.map {
+ SearchLocation(kind: $0.0, url: localLibrary.appending(path: $0.1, directoryHint: .isDirectory))
+ }
// The Plug-ins tool's own table, so the two cannot diverge.
locations += [userLibrary, localLibrary].flatMap { library in
- Plugins.folders.map { SearchLocation(kind: .plugIns, url: library.appending(path: $0.0, directoryHint: .isDirectory)) }
+ Plugins.folders.map {
+ SearchLocation(kind: .plugIns, url: library.appending(path: $0.0, directoryHint: .isDirectory))
+ }
}
locations += Self.systemCodeFolders.map {
SearchLocation(kind: .plugIns, url: localLibrary.appending(path: $0, directoryHint: .isDirectory))
diff --git a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanConfidence.swift b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanConfidence.swift
index 84228fd7..161ccd1e 100644
--- a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanConfidence.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanConfidence.swift
@@ -75,7 +75,8 @@ public struct OrphanConfidence: Sendable, Hashable {
// A folder's own date changes when files are taken out of it, so the last write on a leftover is often
// the uninstall itself. If nothing was written later than `settling` after Peel last saw the app, a
// recent date is the removal, not a sign that something still uses the folder.
- if !makerIsStillHere, let app = group.rememberedApp, let written = lastWrite(in: group), written <= app.lastSeen.addingTimeInterval(settling) {
+ if !makerIsStillHere, let app = group.rememberedApp, let written = lastWrite(in: group),
+ written <= app.lastSeen.addingTimeInterval(settling) {
return OrphanConfidence(level: .certain, reasons: [.appLeft(name: app.name, lastSeen: app.lastSeen)])
}
if let written = group.lastModified, now.timeIntervalSince(written) < recentlyWritten, written <= now {
@@ -115,7 +116,9 @@ public struct OrphanConfidence: Sendable, Hashable {
/// loads keeps its date, so a group of plug-ins alone says nothing this way.
static func monthsUntouched(_ group: OrphanGroup, now: Date) -> Int? {
let used = group.items.filter { !$0.kind.isLoadedCode }
- guard group.total.isComplete, let written = used.compactMap(\.modificationDate).max(), written <= now else { return nil }
+ guard group.total.isComplete, let written = used.compactMap(\.modificationDate).max(), written <= now else {
+ return nil
+ }
// Counts Gregorian months, whatever calendar the user has set. In a lunar calendar, the default in Saudi
// Arabia, six months end several days sooner.
var calendar = Calendar(identifier: .gregorian)
diff --git a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanOwners.swift b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanOwners.swift
index b9fb2e3e..feb775ee 100644
--- a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanOwners.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanOwners.swift
@@ -37,7 +37,10 @@ public struct OrphanOwners: Sendable {
guard var owners = read() ?? (url.isMissing ? [:] : nil) else { return false }
edit(&owners)
guard let data = try? JSONEncoder().encode(owners) else { return false }
- try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try? FileManager.default.createDirectory(
+ at: url.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
return (try? data.write(to: url, options: .atomic)) != nil
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanRemoval.swift b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanRemoval.swift
index 5879b2b6..04cfe758 100644
--- a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanRemoval.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanRemoval.swift
@@ -18,9 +18,13 @@ public enum OrphanRemoval {
let moving = mayUseHelper ? orphaned.map(\.url) : orphaned.map(\.url).filter { !privileged.contains($0) }
var result = await trashService.trash(moving, usingHelperFor: mayUseHelper ? privileged : [])
if !mayUseHelper {
- result.failures += orphaned.filter(\.requiresPrivileges).map { TrashFailure(url: $0.url, reason: .needsHelper) }
+ result.failures += orphaned.filter(\.requiresPrivileges).map {
+ TrashFailure(url: $0.url, reason: .needsHelper)
+ }
+ }
+ result.failures += items.filter { !kept.contains($0.url) }.map {
+ TrashFailure(url: $0.url, reason: .claimedSinceScan)
}
- result.failures += items.filter { !kept.contains($0.url) }.map { TrashFailure(url: $0.url, reason: .claimedSinceScan) }
return result
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift
index 960dfbdd..57d513bc 100644
--- a/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Orphans/OrphanScanner.swift
@@ -15,7 +15,11 @@ public struct OrphanScanner: Sendable {
private let walk: LeftoverScanner.Measure
public init(environment: SearchEnvironment = .current, exclusions: Exclusions = .none) {
- self.init(environment: environment, exclusions: exclusions, isRegisteredApp: AppOwnership.launchServicesKnowsApp(withBundleIdentifier:))
+ self.init(
+ environment: environment,
+ exclusions: exclusions,
+ isRegisteredApp: AppOwnership.launchServicesKnowsApp(withBundleIdentifier:)
+ )
}
init(
@@ -57,12 +61,20 @@ public struct OrphanScanner: Sendable {
let ownership = AppOwnership(installedApps: installedApps + systemApps, isRegisteredApp: isRegisteredApp)
let jobs = BackgroundItemOwnership(installedApps: installedApps + systemApps)
let goneBundles = Dictionary(
- gone.map { (PathPattern.comparablePath(of: URL(filePath: $0.lastPath, directoryHint: .isDirectory)), $0.bundleIdentifier) },
+ gone.map {
+ (
+ PathPattern.comparablePath(of: URL(filePath: $0.lastPath, directoryHint: .isDirectory)),
+ $0.bundleIdentifier
+ )
+ },
uniquingKeysWith: { first, _ in first }
)
let goneApps = gone.map { $0.bundleIdentifier.lowercased() }
- let goneNames = Dictionary(gone.map { ($0.name.lowercased(), $0.bundleIdentifier) }, uniquingKeysWith: { first, _ in first })
+ let goneNames = Dictionary(
+ gone.map { ($0.name.lowercased(), $0.bundleIdentifier) },
+ uniquingKeysWith: { first, _ in first }
+ )
let results = await withTaskGroup(of: LocationResult.self) { group in
let home = environment.homeDirectory.path(percentEncoded: false)
@@ -88,11 +100,14 @@ public struct OrphanScanner: Sendable {
let reach = HelperReach(environment: environment)
let kept = found.filter {
- !exclusions.excludes($0.item.url) && !exclusions.holds($0.item.url) && !exclusions.excludes(bundleIdentifier: $0.identifier)
+ !exclusions.excludes($0.item.url) && !exclusions.holds($0.item.url)
+ && !exclusions.excludes(bundleIdentifier: $0.identifier)
&& !(owners[$0.identifier.lowercased()].map { here.contains($0.lowercased()) } ?? false)
}
.map { entry in
- guard entry.item.requiresPrivileges, entry.item.leftAlone == nil, reach.isBeyond(entry.item.url) else { return entry }
+ guard entry.item.requiresPrivileges, entry.item.leftAlone == nil, reach.isBeyond(entry.item.url) else {
+ return entry
+ }
var item = entry.item
item.heldBack = .beyondTheHelper
return (entry.identifier, item)
@@ -116,7 +131,12 @@ public struct OrphanScanner: Sendable {
var kept: [OrphanItem] = []
for item in items {
let isStillOrphaned = if let app = item.namedAfter {
- await Self.goneApp(named: item.url, kind: item.kind, goneNames: [item.url.lastPathComponent.lowercased(): app], ownership: ownership) != nil
+ await Self.goneApp(
+ named: item.url,
+ kind: item.kind,
+ goneNames: [item.url.lastPathComponent.lowercased(): app],
+ ownership: ownership
+ ) != nil
} else {
await Self.orphanIdentifier(of: item.url, kind: item.kind, ownership: ownership, jobs: jobs) != nil
}
@@ -165,7 +185,9 @@ public struct OrphanScanner: Sendable {
return grouped.map { root, entries in
let identifier = entries.map { groupingKey(for: $0.identifier) }.first { $0.lowercased() == root } ?? root
let items = entries.map(\.item).sorted {
- $0.size != $1.size ? SizeTotal([$0.size]) > SizeTotal([$1.size]) : $0.url.path(percentEncoded: false) < $1.url.path(percentEncoded: false)
+ $0.size != $1.size
+ ? SizeTotal([$0.size]) > SizeTotal([$1.size])
+ : $0.url.path(percentEncoded: false) < $1.url.path(percentEncoded: false)
}
var group = OrphanGroup(
identifier: identifier,
@@ -198,7 +220,11 @@ public struct OrphanScanner: Sendable {
/// keep one folder per app inside their own, so a folder named after nobody can still hold an app's files.
/// A folder that did not answer in time, or that macOS will not list, counts as holding one, so it is never
/// reported as nobody's.
- static func holdsFilesOfAnInstalledApp(_ url: URL, kind: SearchLocation.Kind, ownership: AppOwnership) async -> Bool {
+ static func holdsFilesOfAnInstalledApp(
+ _ url: URL,
+ kind: SearchLocation.Kind,
+ ownership: AppOwnership
+ ) async -> Bool {
guard let names = await SlowRead.names(in: url) else { return true }
return names.contains { name in
let key = LeftoverMatcher.key(from: name, kind: kind)
@@ -228,10 +254,18 @@ public struct OrphanScanner: Sendable {
/// The app bundle a link leads into, when that bundle is gone. Nil for a link into an app that is still
/// there, or into no app at all.
static func goneApp(behind link: URL) -> URL? {
- guard let destination = try? FileManager.default.destinationOfSymbolicLink(atPath: link.path(percentEncoded: false)) else { return nil }
- let components = URL(filePath: destination, relativeTo: link.deletingLastPathComponent()).standardizedFileURL.pathComponents
+ guard
+ let destination = try? FileManager.default.destinationOfSymbolicLink(
+ atPath: link.path(percentEncoded: false)
+ )
+ else { return nil }
+ let components = URL(filePath: destination, relativeTo: link.deletingLastPathComponent())
+ .standardizedFileURL.pathComponents
guard let app = components.firstIndex(where: { $0.hasSuffix(".app") }) else { return nil }
- let bundle = URL(filePath: NSString.path(withComponents: Array(components[...app])), directoryHint: .isDirectory)
+ let bundle = URL(
+ filePath: NSString.path(withComponents: Array(components[...app])),
+ directoryHint: .isDirectory
+ )
return FileManager.default.fileExists(atPath: bundle.path(percentEncoded: false)) ? nil : bundle
}
@@ -246,7 +280,8 @@ public struct OrphanScanner: Sendable {
) async -> String? {
if kind == .commandLineTools {
guard let bundle = goneApp(behind: url) else { return nil }
- return goneBundles[PathPattern.comparablePath(of: bundle)] ?? bundle.deletingPathExtension().lastPathComponent
+ return goneBundles[PathPattern.comparablePath(of: bundle)]
+ ?? bundle.deletingPathExtension().lastPathComponent
}
let name = url.lastPathComponent
guard
@@ -267,7 +302,12 @@ public struct OrphanScanner: Sendable {
]
/// The app that left whose name `url` bears, in one of `namedPlaces`, while no installed app claims that name.
- static func goneApp(named url: URL, kind: SearchLocation.Kind, goneNames: [String: String], ownership: AppOwnership) async -> String? {
+ static func goneApp(
+ named url: URL,
+ kind: SearchLocation.Kind,
+ goneNames: [String: String],
+ ownership: AppOwnership
+ ) async -> String? {
let name = url.lastPathComponent
guard
namedPlaces.contains(kind), !isSensitive(fileName: name),
@@ -322,7 +362,13 @@ public struct OrphanScanner: Sendable {
// What the guard refuses outright is never listed, whether an installed app claims it or not.
guard !ProtectedData.refuses(url.path(percentEncoded: false), home: home) else { continue }
var namedAfter: String?
- var identifier = await orphanIdentifier(of: url, kind: location.kind, ownership: ownership, jobs: jobs, goneBundles: goneBundles)
+ var identifier = await orphanIdentifier(
+ of: url,
+ kind: location.kind,
+ ownership: ownership,
+ jobs: jobs,
+ goneBundles: goneBundles
+ )
if identifier == nil {
namedAfter = await goneApp(named: url, kind: location.kind, goneNames: goneNames, ownership: ownership)
identifier = namedAfter
@@ -333,7 +379,9 @@ public struct OrphanScanner: Sendable {
}
// A few walks at a time, so a few folders that never answer do not each hold the location for a whole budget.
- let walked = await candidates.map(\.url).concurrentMap(width: LeftoverScanner.concurrentMeasurements) { await walk($0) }
+ let walked = await candidates.map(\.url).concurrentMap(width: LeftoverScanner.concurrentMeasurements) {
+ await walk($0)
+ }
var found: [(identifier: String, item: OrphanItem)] = []
for ((url, identifier, namedAfter), contents) in zip(candidates, walked) {
// The item's own date changes when something is taken out of it, but not when a file inside is
diff --git a/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swift b/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swift
index fa7b1348..e6706291 100644
--- a/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Packages/PackageReceipts.swift
@@ -52,7 +52,11 @@ public enum PackageReceipts {
/// Lists every installed package except Apple's, sorted by identifier. `pkgutil` is a parameter so a test
/// can say what is installed instead of asking the real tool.
@concurrent
- static func list(exclusions: Exclusions, pkgutil: @escaping Pkgutil, environment: SearchEnvironment = .current) async -> PackageScan {
+ static func list(
+ exclusions: Exclusions,
+ pkgutil: @escaping Pkgutil,
+ environment: SearchEnvironment = .current
+ ) async -> PackageScan {
let removalGuard = RemovalGuard(environment: environment, exclusions: exclusions)
let reach = HelperReach(environment: environment)
let shared = sharedFolders(in: environment)
@@ -66,17 +70,37 @@ public enum PackageReceipts {
var results: [PackageReceipt] = []
for _ in 0..<concurrentReceipts {
guard let identifier = pending.next() else { break }
- group.addTask { await Self.receipt(identifier, exclusions: exclusions, pkgutil: pkgutil, removalGuard: removalGuard, reach: reach, shared: shared).receipt }
+ group.addTask {
+ await Self.receipt(
+ identifier,
+ exclusions: exclusions,
+ pkgutil: pkgutil,
+ removalGuard: removalGuard,
+ reach: reach,
+ shared: shared
+ ).receipt
+ }
}
while let result = await group.next() {
results.append(result)
if let identifier = pending.next() {
- group.addTask { await Self.receipt(identifier, exclusions: exclusions, pkgutil: pkgutil, removalGuard: removalGuard, reach: reach, shared: shared).receipt }
+ group.addTask {
+ await Self.receipt(
+ identifier,
+ exclusions: exclusions,
+ pkgutil: pkgutil,
+ removalGuard: removalGuard,
+ reach: reach,
+ shared: shared
+ ).receipt
+ }
}
}
return results
}
- return PackageScan(receipts: receipts.sorted { $0.identifier.localizedStandardCompare($1.identifier) == .orderedAscending })
+ return PackageScan(
+ receipts: receipts.sorted { $0.identifier.localizedStandardCompare($1.identifier) == .orderedAscending }
+ )
}
/// Returns the receipts of the packages that installed `url`, asking `pkgutil` about that one path instead
@@ -91,7 +115,11 @@ public enum PackageReceipts {
/// the leading folders are dropped one at a time until a package answers, and the answer counts only if that
/// package really installed this path.
@concurrent
- static func receipts(installing url: URL, exclusions: Exclusions, pkgutil: @escaping Pkgutil) async -> [PackageReceipt] {
+ static func receipts(
+ installing url: URL,
+ exclusions: Exclusions,
+ pkgutil: @escaping Pkgutil
+ ) async -> [PackageReceipt] {
let wanted = PathPattern.comparablePath(of: PathPattern.canonical(url))
var identifiers: Set<String> = []
for path in Self.spellings(of: wanted) where identifiers.isEmpty && !Task.isCancelled {
@@ -103,7 +131,14 @@ public enum PackageReceipts {
let reach = HelperReach(environment: .current)
let shared = sharedFolders(in: .current)
for identifier in identifiers.sorted() where !Task.isCancelled {
- let found = await receipt(identifier, exclusions: exclusions, pkgutil: pkgutil, removalGuard: removalGuard, reach: reach, shared: shared)
+ let found = await receipt(
+ identifier,
+ exclusions: exclusions,
+ pkgutil: pkgutil,
+ removalGuard: removalGuard,
+ reach: reach,
+ shared: shared
+ )
guard found.installs(wanted) else { continue }
receipts.append(found.receipt)
}
@@ -152,7 +187,10 @@ public enum PackageReceipts {
// `pkgutil` named the package but did not describe it. It stays listed, with what it installed unknown,
// rather than vanishing from the page.
let unknown = PackageReceipt(
- identifier: identifier, version: nil, installDate: nil, volume: URL(filePath: "/", directoryHint: .isDirectory),
+ identifier: identifier,
+ version: nil,
+ installDate: nil,
+ volume: URL(filePath: "/", directoryHint: .isDirectory),
items: [], nothingLeftOnDisk: false, isFileListKnown: false
)
return Found(receipt: unknown, paths: [])
diff --git a/Packages/PeelCore/Sources/PeelCore/Plugins/Plugins.swift b/Packages/PeelCore/Sources/PeelCore/Plugins/Plugins.swift
index dc9c537e..8de98358 100644
--- a/Packages/PeelCore/Sources/PeelCore/Plugins/Plugins.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Plugins/Plugins.swift
@@ -93,12 +93,19 @@ public enum Plugins {
}
@concurrent
- public static func scan(environment: SearchEnvironment = .current, exclusions: Exclusions = .none) async -> [Plugin] {
+ public static func scan(
+ environment: SearchEnvironment = .current,
+ exclusions: Exclusions = .none
+ ) async -> [Plugin] {
await scan(environment: environment, exclusions: exclusions, measure: FileSize.measure)
}
@concurrent
- static func scan(environment: SearchEnvironment, exclusions: Exclusions, measure: FileSize.Measure) async -> [Plugin] {
+ static func scan(
+ environment: SearchEnvironment,
+ exclusions: Exclusions,
+ measure: FileSize.Measure
+ ) async -> [Plugin] {
let libraries = [
(environment.homeDirectory.appending(path: "Library", directoryHint: .isDirectory), false),
(environment.rootDirectory.appending(path: "Library", directoryHint: .isDirectory), true),
@@ -108,7 +115,9 @@ public enum Plugins {
for (library, isForAllUsers) in libraries {
for (folder, category) in folders {
let directory = library.appending(path: folder, directoryHint: .isDirectory)
- for url in bundles(in: directory, category: category) where !Task.isCancelled && !exclusions.excludes(url) && !exclusions.holds(url) && !AppleCode.isApples(url) {
+ for url in bundles(in: directory, category: category)
+ where !Task.isCancelled && !exclusions.excludes(url) && !exclusions.holds(url)
+ && !AppleCode.isApples(url) {
let info = AppInspector.infoDictionary(in: url.appending(path: "Contents", directoryHint: .isDirectory))
plugins.append(Plugin(
url: url,
@@ -118,7 +127,8 @@ public enum Plugins {
category: category,
isInstalledForAllUsers: isForAllUsers,
size: await measure(url),
- requiresPrivileges: ParentAccess(url.deletingLastPathComponent()).requiresPrivileges(toRemove: url),
+ requiresPrivileges: ParentAccess(url.deletingLastPathComponent())
+ .requiresPrivileges(toRemove: url),
refusal: removalGuard.refusal(of: url)
))
}
@@ -163,7 +173,8 @@ public enum Plugins {
}
private static func entries(of directory: URL) -> [URL] {
- (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.isDirectoryKey])) ?? []
+ (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: [.isDirectoryKey]))
+ ?? []
}
private static func isFolder(_ url: URL) -> Bool {
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swift b/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swift
index afcc265c..8c9c05cb 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/AppReset.swift
@@ -86,7 +86,8 @@ public struct AppReset: Sendable {
static func group(for kind: SearchLocation.Kind) -> Group? {
switch kind {
- case .preferences, .preferencesByHost, .savedApplicationState, .caches, .logs, .recentDocuments, .temporaryItems:
+ case .preferences, .preferencesByHost, .savedApplicationState, .caches, .logs, .recentDocuments,
+ .temporaryItems:
.settings
case .cookies, .httpStorages, .webKit:
.webData
@@ -111,7 +112,13 @@ public struct AppReset: Sendable {
exclusions: Exclusions = .none,
environment: SearchEnvironment = .current
) async -> AppReset {
- await prepare(app, installedApps: installedApps, exclusions: exclusions, environment: environment, measure: LeftoverScanner.walk)
+ await prepare(
+ app,
+ installedApps: installedApps,
+ exclusions: exclusions,
+ environment: environment,
+ measure: LeftoverScanner.walk
+ )
}
@concurrent
@@ -125,7 +132,10 @@ public struct AppReset: Sendable {
guard !exclusions.excludes(app) else {
return AppReset(app: app, items: [], keepsAppData: false, needsFullDiskAccess: false)
}
- let scan = await LeftoverScanner(environment: environment, exclusions: exclusions).scan(app, installedApps: installedApps)
+ let scan = await LeftoverScanner(environment: environment, exclusions: exclusions).scan(
+ app,
+ installedApps: installedApps
+ )
let keepsAppData = dataIsNeverOffered.contains(app.bundleIdentifier)
// A container held back because of the documents or a wallet's keys inside it is still looked into: a reset
// never touches `Documents`, never offers a folder that holds keys, and the settings beside them are what a
@@ -156,7 +166,13 @@ public struct AppReset: Sendable {
needsFullDiskAccess = needsFullDiskAccess || access == .missing
continue
}
- items += await itemsInside(container.url, of: app, exclusions: exclusions, home: environment.homeDirectory, measure: measure)
+ items += await itemsInside(
+ container.url,
+ of: app,
+ exclusions: exclusions,
+ home: environment.homeDirectory,
+ measure: measure
+ )
}
return AppReset(
@@ -177,7 +193,8 @@ public struct AppReset: Sendable {
var items: [Item] = []
for folder in containerFolders {
let url = container.appending(path: folder.path, directoryHint: .isDirectory)
- guard url.isRealFolder, !exclusions.excludes(url), !exclusions.holds(url), !holdsKeys(url, home: home) else { continue }
+ guard url.isRealFolder, !exclusions.excludes(url), !exclusions.holds(url), !holdsKeys(url, home: home)
+ else { continue }
// What the uninstall would hold back is never offered: a wallet or a repository inside, or a folder that
// was not measured or not read.
let seen = await measure(url)
@@ -189,9 +206,14 @@ public struct AppReset: Sendable {
// Only the file named after the app, or after the container when it is a helper's: that is the file
// `defaults` reads. A name that merely starts the same (`com.foo.AppOther`) belongs to another app.
let names = Set([app.bundleIdentifier, container.lastPathComponent].map { $0.lowercased() + ".plist" })
- let contents = (try? FileManager.default.contentsOfDirectory(at: preferences, includingPropertiesForKeys: [.isSymbolicLinkKey])) ?? []
+ let contents = (try? FileManager.default.contentsOfDirectory(
+ at: preferences,
+ includingPropertiesForKeys: [.isSymbolicLinkKey]
+ )) ?? []
for file in contents where names.contains(file.lastPathComponent.lowercased()) {
- guard (try? file.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) != true, !exclusions.excludes(file) else { continue }
+ guard (try? file.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink) != true,
+ !exclusions.excludes(file)
+ else { continue }
let seen = await measure(file)
guard let seen, HoldBack.seen(in: seen) == nil else { continue }
items.append(Item(url: file, kind: .preferences, group: .settings, size: seen.size))
@@ -204,6 +226,7 @@ public struct AppReset: Sendable {
private static func holdsKeys(_ url: URL, home: URL) -> Bool {
let path = url.path(percentEncoded: false)
let home = home.path(percentEncoded: false)
- return ProtectedData.refuses(path, home: home) || ProtectedData.holds(path, home: home) || ProtectedData.holdsABrowserWallet(path)
+ return ProtectedData.refuses(path, home: home) || ProtectedData.holds(path, home: home)
+ || ProtectedData.holdsABrowserWallet(path)
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/Batches.swift b/Packages/PeelCore/Sources/PeelCore/Removal/Batches.swift
index 315c1504..21e4a609 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/Batches.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/Batches.swift
@@ -19,7 +19,8 @@ enum Batches {
let dates = batches.mapValues { $0.map(date).min() ?? .distantPast }
var total = sorted.count
var dropped: Set<Batch> = []
- for key in batches.keys.sorted(by: { dates[$0] ?? .distantPast < dates[$1] ?? .distantPast }) where total > maximum {
+ for key in batches.keys.sorted(by: { dates[$0] ?? .distantPast < dates[$1] ?? .distantPast })
+ where total > maximum {
guard !protected.contains(key) else { continue }
dropped.insert(key)
total -= batches[key]?.count ?? 0
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift b/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift
index 2c244afa..6cf7ee81 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/BulkUninstallation.swift
@@ -36,11 +36,13 @@ public struct BulkUninstallation: Sendable {
public var id: URL { url }
public var isApplication: Bool { match == nil }
public var isRecommended: Bool {
- guard !isExcluded, !isPeels, !isKeptByMacOS, !isBeyondTheHelper, !isInTheTrash, enclosingPackage == nil else {
+ guard !isExcluded, !isPeels, !isKeptByMacOS, !isBeyondTheHelper, !isInTheTrash, enclosingPackage == nil
+ else {
return false
}
guard let match else { return true }
- return sharedWithOthers.isEmpty && otherCopies.isEmpty && match.confidence >= .likely && match.heldBack == nil
+ return sharedWithOthers.isEmpty && otherCopies.isEmpty && match.confidence >= .likely
+ && match.heldBack == nil
}
}
@@ -57,7 +59,9 @@ public struct BulkUninstallation: Sendable {
uninstallations.contains { $0.scan.needsFullDiskAccess }
}
public var unreadableLocations: [SearchLocation] {
- Array(Set(uninstallations.flatMap { $0.scan.unreadableLocations })).sorted { $0.url.path(percentEncoded: false) < $1.url.path(percentEncoded: false) }
+ Array(Set(uninstallations.flatMap { $0.scan.unreadableLocations })).sorted {
+ $0.url.path(percentEncoded: false) < $1.url.path(percentEncoded: false)
+ }
}
public init(uninstallations: [Uninstallation]) {
@@ -65,9 +69,17 @@ public struct BulkUninstallation: Sendable {
self.uninstallations = uninstallations
self.items = items
total = SizeTotal(items
- .filter { !$0.isExcluded && !$0.isPeels && !($0.isApplication && $0.isKeptByMacOS) && !$0.isBeyondTheHelper && !$0.isInTheTrash && $0.enclosingPackage == nil && $0.match?.heldBack?.cannotBeMoved != true }
+ .filter {
+ !$0.isExcluded && !$0.isPeels && !($0.isApplication && $0.isKeptByMacOS) && !$0.isBeyondTheHelper
+ && !$0.isInTheTrash && $0.enclosingPackage == nil && $0.match?.heldBack?.cannotBeMoved != true
+ }
.map { $0.isMeasured ? $0.size : nil })
- privilegedURLs = Set(items.filter { $0.requiresPrivileges && !$0.isExcluded && !$0.isPeels && !$0.isBeyondTheHelper && !$0.isInTheTrash && $0.enclosingPackage == nil && !($0.isApplication && $0.isKeptByMacOS) }.map(\.url))
+ privilegedURLs = Set(
+ items.filter {
+ $0.requiresPrivileges && !$0.isExcluded && !$0.isPeels && !$0.isBeyondTheHelper && !$0.isInTheTrash
+ && $0.enclosingPackage == nil && !($0.isApplication && $0.isKeptByMacOS)
+ }.map(\.url)
+ )
}
@concurrent
@@ -81,7 +93,16 @@ public struct BulkUninstallation: Sendable {
) async -> BulkUninstallation {
var prepared: [Uninstallation] = []
for app in apps where !Task.isCancelled {
- prepared.append(await Uninstallation.prepare(app, installedApps: installedApps, exclusions: exclusions, casks: casks, receipts: receipts, environment: environment))
+ prepared.append(
+ await Uninstallation.prepare(
+ app,
+ installedApps: installedApps,
+ exclusions: exclusions,
+ casks: casks,
+ receipts: receipts,
+ environment: environment
+ )
+ )
}
return BulkUninstallation(uninstallations: prepared)
}
@@ -89,9 +110,12 @@ public struct BulkUninstallation: Sendable {
/// What is selected for the user at first. Nothing of an app that would stay, as on its own page, and that
/// includes what it shares with another chosen app: it goes on using it.
public func suggestedSelection(canUseHelper: Bool) -> Set<URL> {
- let staying = Set(uninstallations.filter { $0.appStays(canUseHelper: canUseHelper) }.map(\.app.bundleIdentifier))
+ let staying = Set(
+ uninstallations.filter { $0.appStays(canUseHelper: canUseHelper) }.map(\.app.bundleIdentifier)
+ )
return Set(items.filter { item in
- item.isRecommended && (canUseHelper || !item.requiresPrivileges) && !item.apps.contains(where: staying.contains)
+ item.isRecommended && (canUseHelper || !item.requiresPrivileges)
+ && !item.apps.contains(where: staying.contains)
}.map(\.url))
}
@@ -100,7 +124,8 @@ public struct BulkUninstallation: Sendable {
/// another package, or that the helper may not move, and nothing of Peel.
public func selectable(canUseHelper: Bool) -> Set<URL> {
Set(items.filter { item in
- !item.isExcluded && !item.isPeels && !item.isBeyondTheHelper && !item.isInTheTrash && item.enclosingPackage == nil
+ !item.isExcluded && !item.isPeels && !item.isBeyondTheHelper && !item.isInTheTrash
+ && item.enclosingPackage == nil
&& !(item.isApplication && item.isKeptByMacOS) && item.match?.heldBack?.cannotBeMoved != true
&& (canUseHelper || !item.requiresPrivileges)
}.map(\.url))
@@ -116,7 +141,9 @@ public struct BulkUninstallation: Sendable {
/// includes an app that cannot go (`Uninstallation.appStays(canUseHelper:)`), since its bundle never is, and
/// leaves out a copy already in the Trash, which stays nowhere.
public func staying(selected: Set<URL>) -> Set<String> {
- Set(uninstallations.filter { !$0.isAppInTheTrash && !selected.contains($0.app.url) }.map(\.app.bundleIdentifier))
+ Set(
+ uninstallations.filter { !$0.isAppInTheTrash && !selected.contains($0.app.url) }.map(\.app.bundleIdentifier)
+ )
}
/// Returns the selection in the order it is moved: leftovers first, then the apps. Excluded items and Peel's
@@ -140,7 +167,8 @@ public struct BulkUninstallation: Sendable {
kind: existing.kind ?? item.kind,
requiresPrivileges: existing.requiresPrivileges || item.requiresPrivileges,
apps: existing.apps + item.apps.filter { !existing.apps.contains($0) },
- match: existing.match.flatMap { known in item.match.map(known.combined) } ?? existing.match ?? item.match,
+ match: existing.match.flatMap { known in item.match.map(known.combined) } ?? existing.match
+ ?? item.match,
sharedWithOthers: existing.sharedWithOthers.filter(item.sharedWithOthers.contains),
otherCopies: existing.otherCopies + item.otherCopies.filter { !existing.otherCopies.contains($0) },
isExcluded: existing.isExcluded || item.isExcluded,
@@ -169,7 +197,9 @@ public struct BulkUninstallation: Sendable {
apps: [identifier],
match: leftover.match,
sharedWithOthers: leftover.match.sharedWith.filter { !chosen.contains($0) },
- otherCopies: leftover.match.otherCopies.filter { !chosenBundles.contains(PathPattern.comparablePath(of: $0)) },
+ otherCopies: leftover.match.otherCopies.filter {
+ !chosenBundles.contains(PathPattern.comparablePath(of: $0))
+ },
isExcluded: leftover.match.heldBack == .holdsAnExclusion,
isKeptByMacOS: uninstallation.app.isSystemProtected,
isMeasured: leftover.isMeasured,
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swift b/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swift
index 93a5f202..b1ccf90e 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/HelperReach.swift
@@ -36,7 +36,9 @@ struct HelperReach: Sendable {
var info = stat()
guard lstat(path, &info) == 0, info.st_mode & S_IFMT == S_IFLNK else { return true }
guard let destination = PrivilegedPathPolicy.resolvedPath(path) else { return false }
- guard let leaving, let app = PrivilegedPathPolicy.resolvedPath(leaving.path(percentEncoded: false)) else { return true }
+ guard let leaving, let app = PrivilegedPathPolicy.resolvedPath(leaving.path(percentEncoded: false)) else {
+ return true
+ }
return !PathComponents.isPath(destination, atOrInside: app)
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/PreferenceBackup.swift b/Packages/PeelCore/Sources/PeelCore/Removal/PreferenceBackup.swift
index a6627232..fa0cb4fb 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/PreferenceBackup.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/PreferenceBackup.swift
@@ -39,7 +39,13 @@ public enum PreferenceBackup {
/// Exports every existing preference domain among `urls` into a new folder in `directory`. If any one
/// cannot be copied, the result is `failed` and nothing may be cleared: the copy is what makes clearing safe.
@concurrent
- static func save(_ urls: [URL], for app: InstalledApp, in directory: URL, through service: TrashService, run: Run) async -> Saved {
+ static func save(
+ _ urls: [URL],
+ for app: InstalledApp,
+ in directory: URL,
+ through service: TrashService,
+ run: Run
+ ) async -> Saved {
let domains = PreferenceCleanup.domains(for: urls, ownedBy: app.bundleIdentifier)
return await save(domains, of: app.bundleIdentifier, in: directory, through: service, run: run)
}
@@ -115,7 +121,14 @@ public enum PreferenceBackup {
isOpen: @Sendable () async -> Bool
) async -> Restored {
let service = TrashService(exclusions: exclusions)
- return await restore(from: folder, of: bundleIdentifier, in: directory, through: service, run: run, isOpen: isOpen)
+ return await restore(
+ from: folder,
+ of: bundleIdentifier,
+ in: directory,
+ through: service,
+ run: run,
+ isOpen: isOpen
+ )
}
static func restore(
@@ -128,7 +141,9 @@ public enum PreferenceBackup {
) async -> Restored {
guard await !isOpen() else { return .appIsOpen }
let files = (try? FileManager.default.contentsOfDirectory(at: folder, includingPropertiesForKeys: nil)) ?? []
- let saved = files.filter { $0.pathExtension == "plist" }.compactMap { file in domain(from: file.lastPathComponent).map { ($0, file) } }
+ let saved = files.filter { $0.pathExtension == "plist" }.compactMap { file in
+ domain(from: file.lastPathComponent).map { ($0, file) }
+ }
// A copy that is not a readable property list would put nothing back once the delete had cleared the
// settings in use, so it is refused before anything is cleared.
let readable = saved.filter { isAPropertyList($0.1) }
@@ -165,7 +180,8 @@ public enum PreferenceBackup {
/// (bundle identifier, then time, then a number for a second copy in the same second) count; anything else is
/// ignored.
public static func copies(in directory: URL = PreferenceBackup.defaultDirectory) -> [Copy] {
- let folders = (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? []
+ let folders =
+ (try? FileManager.default.contentsOfDirectory(at: directory, includingPropertiesForKeys: nil)) ?? []
return folders.compactMap { folder -> (copy: Copy, number: Int)? in
// An identifier has no space, so the name reads as the identifier, the day, the time, and a number.
let parts = folder.lastPathComponent.split(separator: " ", omittingEmptySubsequences: false)
@@ -210,7 +226,12 @@ public enum PreferenceBackup {
}
/// Formats a time as `2026-09-20 093000`, in local time, since people read the folder name in Finder.
- private static let stampStyle = Date.ISO8601FormatStyle(dateSeparator: .dash, dateTimeSeparator: .space, timeSeparator: .omitted, timeZone: .current)
+ private static let stampStyle = Date.ISO8601FormatStyle(
+ dateSeparator: .dash,
+ dateTimeSeparator: .space,
+ timeSeparator: .omitted,
+ timeZone: .current
+ )
.year().month().day().time(includingFractionalSeconds: false)
private static func stamp() -> String {
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/PrivacyReset.swift b/Packages/PeelCore/Sources/PeelCore/Removal/PrivacyReset.swift
index bc297e97..c9a31b8a 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/PrivacyReset.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/PrivacyReset.swift
@@ -25,7 +25,10 @@ public enum PrivacyReset {
switch await Subprocess.run("/usr/bin/tccutil", ["reset", "All", bundleIdentifier], timeout: 10) {
case .success(let output):
- return result(status: output.status, output: (output.text + output.errorText).trimmingCharacters(in: .whitespacesAndNewlines))
+ return result(
+ status: output.status,
+ output: (output.text + output.errorText).trimmingCharacters(in: .whitespacesAndNewlines)
+ )
case .failure(let failure):
return .couldNotAsk(failure.explanation)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/PrivilegedHelper.swift b/Packages/PeelCore/Sources/PeelCore/Removal/PrivilegedHelper.swift
index 82a60e7a..f2657cdc 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/PrivilegedHelper.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/PrivilegedHelper.swift
@@ -136,7 +136,10 @@ public enum PrivilegedHelper {
for start in stride(from: 0, to: urls.count, by: limit) {
let batch = Array(urls[start..<min(start + limit, urls.count)])
// Read before the move, so that if the answer is lost, moved items can be found in the Trash by identity.
- let links = Dictionary(batch.map { ($0, FileIdentity.Link.of($0)) }, uniquingKeysWith: { first, _ in first })
+ let links = Dictionary(
+ batch.map { ($0, FileIdentity.Link.of($0)) },
+ uniquingKeysWith: { first, _ in first }
+ )
let paths = batch.map { $0.path(percentEncoded: false) }
let reply: HelperTrashReply? = await withHelper(fallback: nil) { helper, finish in
helper.moveItemsToTrash(version: HelperIdentity.protocolVersion, atPaths: paths) { moved, failed in
@@ -154,15 +157,30 @@ public enum PrivilegedHelper {
/// once, at the end. With no answer (the helper was uninstalled midway or crashed), the items that did move
/// are found in the Trash by identity: History is the only way back for what the helper moved, and
/// reporting them all as failed would leave them out of History.
- static func result(for urls: [URL], reply: HelperTrashReply?, links: [URL: FileIdentity.Link?], trash: URL) -> TrashResult {
+ static func result(
+ for urls: [URL],
+ reply: HelperTrashReply?,
+ links: [URL: FileIdentity.Link?],
+ trash: URL
+ ) -> TrashResult {
var result = TrashResult()
for url in urls {
let path = url.path(percentEncoded: false)
if let destination = reply?.moved[path] {
let trashedURL = URL(filePath: destination)
- result.trashed.append(TrashedItem(originalURL: url, trashedURL: trashedURL, date: .now, identity: .init(ofItemAt: trashedURL)))
- } else if reply == nil, !url.isThere, let link = links[url] ?? nil, let found = TrashService.item(link, in: trash) {
- result.trashed.append(TrashedItem(originalURL: url, trashedURL: found, date: .now, identity: .init(ofItemAt: found)))
+ result.trashed.append(
+ TrashedItem(
+ originalURL: url,
+ trashedURL: trashedURL,
+ date: .now,
+ identity: .init(ofItemAt: trashedURL)
+ )
+ )
+ } else if reply == nil, !url.isThere, let link = links[url] ?? nil,
+ let found = TrashService.item(link, in: trash) {
+ result.trashed.append(
+ TrashedItem(originalURL: url, trashedURL: found, date: .now, identity: .init(ofItemAt: found))
+ )
} else {
result.failures.append(TrashFailure(url: url, reason: .failed(reply?.failed[path] ?? Self.unavailable)))
}
@@ -174,7 +192,11 @@ public enum PrivilegedHelper {
@concurrent
static func runDaemonCommand(_ command: DaemonCommand, label: String) async -> String? {
await withHelper(fallback: Self.unavailable) { helper, finish in
- helper.runDaemonCommand(version: HelperIdentity.protocolVersion, command: command.rawValue, label: label) { failure in
+ helper.runDaemonCommand(
+ version: HelperIdentity.protocolVersion,
+ command: command.rawValue,
+ label: label
+ ) { failure in
finish(failure)
}
}
@@ -258,7 +280,10 @@ public enum PrivilegedHelper {
// the wait. `longestWait` outlasts any request: at most `HelperRequest.maximumItems` renames, or one
// `launchctl` run that the helper stops after 30 seconds.
DispatchQueue.global(qos: .utility).asyncAfter(deadline: .now() + longestWait) { finish(fallback) }
- guard let helper = connection.remoteObjectProxyWithErrorHandler({ _ in finish(fallback) }) as? any PeelHelperProtocol else {
+ guard
+ let helper = connection.remoteObjectProxyWithErrorHandler({ _ in finish(fallback) })
+ as? any PeelHelperProtocol
+ else {
finish(fallback)
return
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
index 57bf3bf7..bb81ce6c 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RefusalLog.swift
@@ -16,7 +16,14 @@ public struct RefusalRecord: Sendable, Codable, Hashable, Identifiable {
public let sourceKey: String?
public let tool: String
- public init(failure: TrashFailure, date: Date = .now, source: String, sourceKey: String? = nil, tool: String, batch: UUID? = nil) {
+ public init(
+ failure: TrashFailure,
+ date: Date = .now,
+ source: String,
+ sourceKey: String? = nil,
+ tool: String,
+ batch: UUID? = nil
+ ) {
id = UUID()
self.batch = batch
url = failure.url
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swift
index 0832c61a..ca9c192f 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGrouping.swift
@@ -84,7 +84,9 @@ public struct RemovalPart: Sendable, Hashable {
first[part] = min(first[part] ?? date, date)
}
return first
- .sorted { $0.value != $1.value ? $0.value < $1.value : ($0.key.tool, $0.key.source) < ($1.key.tool, $1.key.source) }
+ .sorted {
+ $0.value != $1.value ? $0.value < $1.value : ($0.key.tool, $0.key.source) < ($1.key.tool, $1.key.source)
+ }
.map(\.key)
}
}
@@ -94,7 +96,14 @@ extension RemovalPart {
/// where it was not measured.
public func records(of result: TrashResult, sizes: [URL: Int64], batch: UUID) -> [RemovalRecord] {
result.trashed.map {
- RemovalRecord(batch: batch, item: $0, size: sizes[$0.originalURL], source: source, sourceKey: sourceKey, tool: tool)
+ RemovalRecord(
+ batch: batch,
+ item: $0,
+ size: sizes[$0.originalURL],
+ source: source,
+ sourceKey: sourceKey,
+ tool: tool
+ )
}
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGuard.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGuard.swift
index 023e40ef..78e72fc4 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGuard.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalGuard.swift
@@ -82,7 +82,9 @@ struct RemovalGuard: Sendable {
/// reached through a link, and Spotlight names files by the disk they are on, so both forms must match.
private static func names(of path: String) -> Set<String> {
let path = normalized(path)
- return ProtectedData.spellings(of: path).union(PathPattern.locatedWithoutOpening(path).map(ProtectedData.spellings) ?? [])
+ return ProtectedData.spellings(of: path).union(
+ PathPattern.locatedWithoutOpening(path).map(ProtectedData.spellings) ?? []
+ )
}
func allowsRemoval(of url: URL) -> Bool {
@@ -128,7 +130,9 @@ struct RemovalGuard: Sendable {
// are the spellings the exclusions would work out themselves.
let spelled = Dictionary(uniqueKeysWithValues: names.map { ($0, ProtectedData.spellings(of: $0)) })
for (name, spellings) in spelled {
- guard !exclusions.excludes(spellings: spellings), !exclusions.holds(spellings: spellings) else { return .excluded }
+ guard !exclusions.excludes(spellings: spellings), !exclusions.holds(spellings: spellings) else {
+ return .excluded
+ }
if let refusal = protectedObjects.refusal(of: name) { return refusal }
// The rules the helper follows. They protect every account's keychain and mail, not only those of the
// account Peel runs in.
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift
index 562e4437..44b0d904 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHistory.swift
@@ -20,7 +20,15 @@ public struct RemovalRecord: Sendable, Codable, Hashable, Identifiable {
/// History can show it in the user's language. `source` then holds the English name, which `peel` prints.
public let sourceKey: String?
- public init(id: UUID = UUID(), batch: UUID, item: TrashedItem, size: Int64?, source: String, sourceKey: String? = nil, tool: String) {
+ public init(
+ id: UUID = UUID(),
+ batch: UUID,
+ item: TrashedItem,
+ size: Int64?,
+ source: String,
+ sourceKey: String? = nil,
+ tool: String
+ ) {
self.id = id
self.batch = batch
originalURL = item.originalURL
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift
index e07c2227..c53cf90f 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalHygiene.swift
@@ -97,13 +97,21 @@ enum PreferenceCleanup {
guard path.hasSuffix(".plist") else { return nil }
let parent = PathPattern.comparablePath(of: url.deletingLastPathComponent())
let isByHost = parent == byHost
- let name = LeftoverMatcher.key(from: url.lastPathComponent, kind: isByHost ? .preferencesByHost : .preferences)
- guard isByHost || parent == plain || isTheSettingsFile(name, in: parent, ofTheAppBeingReset: owner, home: home) else { return nil }
+ let name = LeftoverMatcher.key(
+ from: url.lastPathComponent,
+ kind: isByHost ? .preferencesByHost : .preferences
+ )
+ guard
+ isByHost || parent == plain
+ || isTheSettingsFile(name, in: parent, ofTheAppBeingReset: owner, home: home)
+ else { return nil }
guard isUsableName(name) else { return nil }
// A ByHost file is named `<domain>.<host UUID>.plist`. `-currentHost` always means the current Mac, so
// a file another Mac left behind names no domain here.
let fileHost = url.lastPathComponent.removingSuffix(".plist").dropFirst(name.count + 1)
- guard !isByHost || (!host.isEmpty && fileHost.caseInsensitiveCompare(host) == .orderedSame) else { return nil }
+ guard !isByHost || (!host.isEmpty && fileHost.caseInsensitiveCompare(host) == .orderedSame) else {
+ return nil
+ }
// Apple's name whatever its case, since the disk ignores it, and behind a team or group prefix too.
guard !ProtectedData.isApplesName(name) || isOwned(name, by: owner) else { return nil }
let domain = Domain(name: name, isByHost: isByHost)
@@ -116,7 +124,12 @@ enum PreferenceCleanup {
/// Whether `name` is the settings file of the app being reset, inside that app's container. A sandboxed app
/// keeps its settings there, and `defaults` reads the app's domain from that file. No other file in a
/// container has a name `defaults` would find it by.
- private static func isTheSettingsFile(_ name: String, in parent: String, ofTheAppBeingReset owner: String?, home: URL) -> Bool {
+ private static func isTheSettingsFile(
+ _ name: String,
+ in parent: String,
+ ofTheAppBeingReset owner: String?,
+ home: URL
+ ) -> Bool {
guard isOwned(name, by: owner) else { return false }
let container = PathPattern.comparablePath(of: home.appending(path: "Library/Containers/\(name)/Data/Library/Preferences", directoryHint: .isDirectory))
return parent.caseInsensitiveCompare(container) == .orderedSame
@@ -138,7 +151,8 @@ enum PreferenceCleanup {
if domain.isByHost {
folder.append(path: "ByHost", directoryHint: .isDirectory)
}
- guard let names = try? FileManager.default.contentsOfDirectory(atPath: folder.path(percentEncoded: false)) else {
+ guard let names = try? FileManager.default.contentsOfDirectory(atPath: folder.path(percentEncoded: false))
+ else {
// A folder that exists but cannot be read may hold the file, and an unknown answer is not safe. It
// does not matter whether TCC or the file permissions refused the read.
var info = stat()
@@ -146,7 +160,8 @@ enum PreferenceCleanup {
}
let kind: SearchLocation.Kind = domain.isByHost ? .preferencesByHost : .preferences
let kept = names.filter {
- $0.hasSuffix(".plist") && LeftoverMatcher.key(from: $0, kind: kind).caseInsensitiveCompare(domain.name) == .orderedSame
+ $0.hasSuffix(".plist")
+ && LeftoverMatcher.key(from: $0, kind: kind).caseInsensitiveCompare(domain.name) == .orderedSame
}
guard !kept.isEmpty else { return false }
let going = urls.map(PathPattern.comparablePath)
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
index 3194b404..0179d607 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalLog.swift
@@ -63,7 +63,9 @@ public actor RemovalLog {
guard !records.isEmpty else { return RemovalLogOutcome(records: current(), problem: problem) }
guard let existing = current() else { return RemovalLogOutcome(records: nil, problem: problem) }
let updated = Self.trimmed(existing + records, keeping: Set(records.map(\.batch)))
- guard write(updated, orNote: .couldNotRecord) else { return RemovalLogOutcome(records: nil, problem: problem) }
+ guard write(updated, orNote: .couldNotRecord) else {
+ return RemovalLogOutcome(records: nil, problem: problem)
+ }
RemovalTotals.change(at: totals) { $0.add(records) }
journal.forget(records.map(\.trashedItem))
// A removal that is recorded clears an earlier `.couldNotRecord`.
@@ -186,7 +188,10 @@ public actor RemovalLog {
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
do {
let data = try encoder.encode(records)
- try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(
+ at: url.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
// `.atomic` writes a temporary file and renames it, so a crash leaves either the old log or the new one.
try data.write(to: url, options: .atomic)
return true
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalTotals.swift b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalTotals.swift
index 8517707a..1b9a6feb 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/RemovalTotals.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/RemovalTotals.swift
@@ -88,7 +88,9 @@ public struct RemovalTotals: Sendable, Equatable, Codable {
}
private static func startedAgain(at url: URL) -> RemovalTotals? {
- guard BoundedRead.data(at: url, maximum: maximumBytes) != nil, DamagedFile.setAside(url) != nil else { return nil }
+ guard BoundedRead.data(at: url, maximum: maximumBytes) != nil, DamagedFile.setAside(url) != nil else {
+ return nil
+ }
return RemovalTotals()
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
index b80c4cbe..17d4b479 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
@@ -310,7 +310,12 @@ public struct TrashService: Sendable {
}
do {
let trashedURL = try moveToTrash(url)
- let item = TrashedItem(originalURL: url, trashedURL: trashedURL, date: .now, identity: .init(ofItemAt: trashedURL))
+ let item = TrashedItem(
+ originalURL: url,
+ trashedURL: trashedURL,
+ date: .now,
+ identity: .init(ofItemAt: trashedURL)
+ )
if let removal {
journal?.note([item], batch: removal)
}
@@ -384,7 +389,12 @@ public struct TrashService: Sendable {
/// Stops the jobs and forgets the preference domains of what really moved. It runs after the move: a job
/// stopped before a move that fails would stay stopped with its file in place, and cfprefsd would forget
/// settings that are still on disk.
- private func finish(_ result: TrashResult, stopping jobs: [LaunchdCleanup.Job], canUseHelper: Bool, owner: String?) async {
+ private func finish(
+ _ result: TrashResult,
+ stopping jobs: [LaunchdCleanup.Job],
+ canUseHelper: Bool,
+ owner: String?
+ ) async {
let moved = result.trashed.map(\.originalURL)
await stopJobs(jobs.filter { moved.contains($0.plist) }, canUseHelper)
await forgetDomains(moved, owner)
@@ -415,7 +425,9 @@ public struct TrashService: Sendable {
private func moveBack(_ item: TrashedItem, canUseHelper: Bool) async -> RestoreFailure? {
// The record comes from a file any process of the user can rewrite, so it is a request, not a fact.
// Putting an item back must not write where removal is refused, or move a file that is not in a Trash.
- guard removalGuard.allowsPuttingBack(item.trashedURL, at: item.originalURL), isInATrash(item.trashedURL) else { return .notAllowed }
+ guard removalGuard.allowsPuttingBack(item.trashedURL, at: item.originalURL), isInATrash(item.trashedURL) else {
+ return .notAllowed
+ }
let fileManager = FileManager.default
guard item.isInTheTrash else { return .missingFromTrash }
@@ -454,7 +466,8 @@ public struct TrashService: Sendable {
if let identity = item.identity, trashed.identity.map(TrashedItem.Identity.init) != identity {
throw NotTheItemThatMoved()
}
- let folder = try DirectoryHandle.at(item.originalURL.deletingLastPathComponent().path(percentEncoded: false)).get()
+ let folder = try DirectoryHandle.at(item.originalURL.deletingLastPathComponent().path(percentEncoded: false))
+ .get()
guard let held = folder.currentPath else { throw POSIXError(.ENOENT) }
let name = item.originalURL.lastPathComponent
let destination = URL(filePath: held, directoryHint: .isDirectory).appending(path: name)
@@ -483,7 +496,9 @@ public struct TrashService: Sendable {
/// The Trashes an item in `folder` could be in, with links resolved: the home's, and its volume's.
private func trashes(forItemsIn folder: String) -> [String] {
- var trashes = [URL.homeDirectory, environment.homeDirectory].map { $0.appending(path: ".Trash", directoryHint: .isDirectory) }
+ var trashes = [URL.homeDirectory, environment.homeDirectory].map {
+ $0.appending(path: ".Trash", directoryHint: .isDirectory)
+ }
if let volume = try? URL(filePath: folder).resourceValues(forKeys: [.volumeURLKey]).volume {
trashes.append(volume.appending(path: ".Trashes/\(getuid())", directoryHint: .isDirectory))
}
@@ -495,10 +510,16 @@ public struct TrashService: Sendable {
static func reason(for error: any Error) -> TrashFailure.Reason {
if let refused = error as? RefusedOnceHeld { return .guarded(refused.refusal) }
if error is MovedWithoutATrace { return .movedWithoutATrace }
- if let moved = error as? SomethingElseMoved { return .somethingElseMoved(named: moved.trashedURL.lastPathComponent) }
+ if let moved = error as? SomethingElseMoved {
+ return .somethingElseMoved(named: moved.trashedURL.lastPathComponent)
+ }
let error = error as NSError
- if error.domain == NSCocoaErrorDomain, [NSFileWriteNoPermissionError, NSFileReadNoPermissionError].contains(error.code) { return .notPermitted }
- let codes = ([error] + error.underlyingErrors.map { $0 as NSError }).filter { $0.domain == NSPOSIXErrorDomain }.map(\.code)
+ if error.domain == NSCocoaErrorDomain,
+ [NSFileWriteNoPermissionError, NSFileReadNoPermissionError].contains(error.code) {
+ return .notPermitted
+ }
+ let codes = ([error] + error.underlyingErrors.map { $0 as NSError }).filter { $0.domain == NSPOSIXErrorDomain }
+ .map(\.code)
if codes.contains(Int(EPERM)) || codes.contains(Int(EACCES)) { return .notPermitted }
return .failed(error.localizedDescription)
}
@@ -565,7 +586,12 @@ public struct TrashService: Sendable {
let folder = url.deletingLastPathComponent()
guard
let link,
- let trash = try? FileManager.default.url(for: .trashDirectory, in: .userDomainMask, appropriateFor: folder, create: false),
+ let trash = try? FileManager.default.url(
+ for: .trashDirectory,
+ in: .userDomainMask,
+ appropriateFor: folder,
+ create: false
+ ),
let trashedURL = item(link, in: trash)
else { throw MovedWithoutATrace() }
return trashedURL
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/UninstallSelection.swift b/Packages/PeelCore/Sources/PeelCore/Removal/UninstallSelection.swift
index 3d0794a9..78271dcc 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/UninstallSelection.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/UninstallSelection.swift
@@ -26,7 +26,11 @@ public struct UninstallSelection: Sendable {
public init() {}
- public mutating func update(_ selected: Set<URL>, in uninstallation: Uninstallation, canUseHelper: Bool) -> Set<URL> {
+ public mutating func update(
+ _ selected: Set<URL>,
+ in uninstallation: Uninstallation,
+ canUseHelper: Bool
+ ) -> Set<URL> {
let app = App(
stays: uninstallation.appStays(canUseHelper: canUseHelper),
files: Set(uninstallation.scan.leftovers.map(\.url)),
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift
index 11081cbe..110096a9 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/Uninstallation.swift
@@ -45,9 +45,19 @@ public struct Uninstallation: Sendable {
let matcher = await scanner.matcher(for: app, installedApps: installedApps)
var scan = await scanner.scan(app, matcher: matcher)
if let evidence = CaskEvidence.evidence(for: app, casks: casks, home: environment.homeDirectory) {
- scan = scan.adding(await caskLeftovers(evidence, app: app, exclusions: exclusions, matcher: matcher, environment: environment))
+ scan = scan.adding(
+ await caskLeftovers(
+ evidence,
+ app: app,
+ exclusions: exclusions,
+ matcher: matcher,
+ environment: environment
+ )
+ )
}
- scan = scan.adding(await receiptLeftovers(for: app, receipts: receipts, exclusions: exclusions, environment: environment))
+ scan = scan.adding(
+ await receiptLeftovers(for: app, receipts: receipts, exclusions: exclusions, environment: environment)
+ )
let reach = HelperReach(environment: environment)
scan = scan.holdingBack(beyond: reach, leaving: app.url)
let appRequiresPrivileges = FileAccess.requiresPrivilegesToRemove(app.url)
@@ -74,7 +84,8 @@ public struct Uninstallation: Sendable {
let identifier = app.bundleIdentifier.lowercased()
var leftovers: [Leftover] = []
for receipt in receipts.filter({ PackageReceipts.proves($0, isThe: identifier) }).sorted() {
- for url in PackageActions.receiptFiles(of: receipt, onVolume: environment.rootDirectory) where !exclusions.excludes(url) {
+ for url in PackageActions.receiptFiles(of: receipt, onVolume: environment.rootDirectory)
+ where !exclusions.excludes(url) {
leftovers.append(await LeftoverScanner.leftover(
at: url,
kind: .receipts,
@@ -133,7 +144,10 @@ public struct Uninstallation: Sendable {
/// The kind of scanned location `url` sits in, which says how its name is read (a `.plist` in Preferences
/// names a domain), and the path components from that location down to the item. Outside every scanned
/// location, the kind is `.elsewhere`.
- static func place(of url: URL, in environment: SearchEnvironment) -> (kind: SearchLocation.Kind, components: [String]) {
+ static func place(
+ of url: URL,
+ in environment: SearchEnvironment
+ ) -> (kind: SearchLocation.Kind, components: [String]) {
let path = PathPattern.comparablePath(of: url)
let names = PathComponents.of(path)
let inside = environment.locations
@@ -169,7 +183,9 @@ public struct Uninstallation: Sendable {
/// an app that would stay (`appStays(canUseHelper:)`).
public func suggestedSelection(canUseHelper: Bool) -> Set<URL> {
guard !appStays(canUseHelper: canUseHelper) else { return [] }
- var selection = Set(scan.leftovers.filter { $0.match.isRecommended && (canUseHelper || !$0.requiresPrivileges) }.map(\.url))
+ var selection = Set(
+ scan.leftovers.filter { $0.match.isRecommended && (canUseHelper || !$0.requiresPrivileges) }.map(\.url)
+ )
if !isAppInTheTrash {
selection.insert(app.url)
}
@@ -201,7 +217,8 @@ public struct Uninstallation: Sendable {
let namespace = app.bundleIdentifier.lowercased() + "."
let own = scan.leftovers.filter { leftover in
leftover.match.isRecommended && !leftover.requiresPrivileges
- && (leftover.match.confidence == .certain || leftover.url.lastPathComponent.lowercased().hasPrefix(namespace))
+ && (leftover.match.confidence == .certain
+ || leftover.url.lastPathComponent.lowercased().hasPrefix(namespace))
}
return order(of: Set(own.map(\.url)).union([app.url]))
}
@@ -222,7 +239,9 @@ public struct Uninstallation: Sendable {
public var privilegedURLs: Set<URL> {
guard !isExcluded, !isPeel else { return [] }
- var urls = Set(scan.leftovers.filter { $0.requiresPrivileges && $0.match.heldBack != .beyondTheHelper }.map(\.url))
+ var urls = Set(
+ scan.leftovers.filter { $0.requiresPrivileges && $0.match.heldBack != .beyondTheHelper }.map(\.url)
+ )
if appRequiresPrivileges, !app.isSystemProtected, app.enclosingPackage == nil, !isAppBeyondTheHelper,
!isAppInTheTrash {
urls.insert(app.url)
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/VendorRemoval.swift b/Packages/PeelCore/Sources/PeelCore/Removal/VendorRemoval.swift
index 467d6296..2c52f411 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/VendorRemoval.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/VendorRemoval.swift
@@ -6,7 +6,10 @@ internal import PeelPrivileged
public enum VendorRemoval {
/// An uninstaller for `app`: one inside its bundle or beside it, or else one named for the app in the
/// folders where makers keep their uninstallers.
- public static func uninstaller(for app: InstalledApp, applicationsFolders: [URL] = AppCatalog.defaultDirectories) -> URL? {
+ public static func uninstaller(
+ for app: InstalledApp,
+ applicationsFolders: [URL] = AppCatalog.defaultDirectories
+ ) -> URL? {
shippedOrBeside(app, applicationsFolders: applicationsFolders) ?? namedForIt(app, in: applicationsFolders)
}
@@ -25,7 +28,8 @@ public enum VendorRemoval {
for (folder, isInsideTheBundle) in folders {
let names = (try? fileManager.contentsOfDirectory(atPath: folder.path(percentEncoded: false))) ?? []
- if let match = names.sorted().first(where: { isUninstallerName($0, app: app, isInsideTheBundle: isInsideTheBundle) }) {
+ if let match = names.sorted()
+ .first(where: { isUninstallerName($0, app: app, isInsideTheBundle: isInsideTheBundle) }) {
return folder.appending(path: match)
}
}
@@ -41,7 +45,10 @@ public enum VendorRemoval {
let utilities = applicationsFolders.map { $0.appending(path: "Utilities", directoryHint: .isDirectory) }
let makers = utilities.flatMap { folder in
((try? fileManager.contentsOfDirectory(at: folder, includingPropertiesForKeys: [.isDirectoryKey])) ?? [])
- .filter { $0.pathExtension != "app" && (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true }
+ .filter {
+ $0.pathExtension != "app"
+ && (try? $0.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true
+ }
}
for folder in applicationsFolders + utilities + makers {
let names = (try? fileManager.contentsOfDirectory(atPath: folder.path(percentEncoded: false))) ?? []
@@ -88,10 +95,17 @@ public enum VendorRemoval {
/// What a package installed outside the app's bundle and is still there, folders included: a support folder
/// is the most common thing a package leaves outside. Items another receipt also lists are left out, since
/// they are not this package's alone.
- public static func filesOutsideBundle(of receipt: PackageReceipt, app: InstalledApp, otherReceipts: [PackageReceipt]) -> [PackageReceipt.Item] {
+ public static func filesOutsideBundle(
+ of receipt: PackageReceipt,
+ app: InstalledApp,
+ otherReceipts: [PackageReceipt]
+ ) -> [PackageReceipt.Item] {
// Compared as paths: the catalog writes an app's URL with a trailing slash, and a receipt's items without.
let bundle = PathPattern.comparablePath(of: app.url)
- let claimedElsewhere = Set(otherReceipts.filter { $0.identifier != receipt.identifier }.flatMap(\.items).map { PathPattern.comparablePath(of: $0.url) })
+ let claimedElsewhere = Set(
+ otherReceipts.filter { $0.identifier != receipt.identifier }.flatMap(\.items)
+ .map { PathPattern.comparablePath(of: $0.url) }
+ )
return receipt.items.filter { item in
let path = PathPattern.comparablePath(of: item.url)
guard !PathComponents.isPath(path, atOrInside: bundle) else { return false }
diff --git a/Packages/PeelCore/Sources/PeelCore/Search/FileSearch.swift b/Packages/PeelCore/Sources/PeelCore/Search/FileSearch.swift
index a0fe5b5c..a3274288 100644
--- a/Packages/PeelCore/Sources/PeelCore/Search/FileSearch.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Search/FileSearch.swift
@@ -68,7 +68,8 @@ public enum FileSearch {
public static func trash(_ files: [FoundFile], using trashService: TrashService) async -> TrashResult {
var result = TrashResult()
for file in files {
- guard let identity = file.identity, FileIdentity.of(file.url)?.holdsTheSameContents(as: identity) == true else {
+ guard let identity = file.identity, FileIdentity.of(file.url)?.holdsTheSameContents(as: identity) == true
+ else {
result.failures.append(TrashFailure(url: file.url, reason: .changedSinceScan))
continue
}
@@ -83,7 +84,11 @@ public enum FileSearch {
/// removal guard allows. Files in a Library folder come after the rest, and each part is sorted largest first.
/// Stopping the task stops the query.
@concurrent
- public static func run(_ criteria: FileSearchCriteria, environment: SearchEnvironment = .current, exclusions: Exclusions = .none) async -> FileSearchResults {
+ public static func run(
+ _ criteria: FileSearchCriteria,
+ environment: SearchEnvironment = .current,
+ exclusions: Exclusions = .none
+ ) async -> FileSearchResults {
await run(criteria, environment: environment, exclusions: exclusions) { await SpotlightGathering($0).paths() }
}
@@ -94,7 +99,9 @@ public enum FileSearch {
exclusions: Exclusions = .none,
gather: Gather
) async -> FileSearchResults {
- guard criteria.isSearchable, let query = makeQuery(for: criteria) else { return FileSearchResults(didRun: false) }
+ guard criteria.isSearchable, let query = makeQuery(for: criteria) else {
+ return FileSearchResults(didRun: false)
+ }
let scope = criteria.scope == .home ? kMDQueryScopeHome : kMDQueryScopeComputer
MDQuerySetSearchScope(query, [scope] as CFArray, 0)
guard let paths = await gather(query), !Task.isCancelled else { return FileSearchResults(didRun: false) }
@@ -116,7 +123,9 @@ public enum FileSearch {
for path in paths {
guard !Task.isCancelled else { return FileSearchResults(didRun: false) }
var info = stat()
- guard lstat(path, &info) == 0, info.st_mode & S_IFMT == S_IFREG, holdsItsContentsHere(info) else { continue }
+ guard lstat(path, &info) == 0, info.st_mode & S_IFMT == S_IFREG, holdsItsContentsHere(info) else {
+ continue
+ }
candidates.append((path, info, appData.holds(path)))
}
// In the list's order before the guard is asked, so it is asked only about files that can make the list.
@@ -200,7 +209,9 @@ public enum FileSearch {
guard count > 0, count <= 4 else { return "kMDItemFSName == \"*\(escaped(name))*\"cd" }
var variants = [""]
for character in name {
- variants = letters.contains(character) ? variants.flatMap { [$0 + "i", $0 + "I"] } : variants.map { $0 + String(character) }
+ variants = letters.contains(character)
+ ? variants.flatMap { [$0 + "i", $0 + "I"] }
+ : variants.map { $0 + String(character) }
}
let names = [name] + variants.filter { $0 != name }
return "(" + names.map { "kMDItemFSName == \"*\(escaped($0))*\"cd" }.joined(separator: " || ") + ")"
diff --git a/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swift b/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swift
index f56a851e..e87ea9e8 100644
--- a/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Space/CloudStorage.swift
@@ -206,7 +206,9 @@ public enum CloudStorage {
// Only an error on the root counts: without Full Disk Access nothing under it can be read. A
// missing root (`NSFileReadNoSuchFileError`) means iCloud Drive was never set up, which is
// nothing to list rather than a refusal.
- let isMissing = (error as NSError).domain == NSCocoaErrorDomain && (error as NSError).code == NSFileReadNoSuchFileError
+ let isMissing =
+ (error as NSError).domain == NSCocoaErrorDomain
+ && (error as NSError).code == NSFileReadNoSuchFileError
if PathPattern.comparablePath(of: url) == rootPath, !isMissing { collector.unreadable() }
return true
}
@@ -319,7 +321,9 @@ public enum CloudStorage {
if folder == "com~apple~CloudDocs" {
// Finder's name for the folder, in the user's language (iCloud云盘 in Simplified Chinese), for search.
- let shown = FileManager.default.displayName(atPath: root.appending(path: folder).path(percentEncoded: false))
+ let shown = FileManager.default.displayName(
+ atPath: root.appending(path: folder).path(percentEncoded: false)
+ )
return shown == folder ? "iCloud Drive" : shown
}
var name = folder.replacingOccurrences(of: "~", with: ".")
diff --git a/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift b/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift
index 062283bc..4bcb54fe 100644
--- a/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Space/Installers.swift
@@ -82,7 +82,14 @@ public enum Installers {
exclusions: Exclusions = .none,
minimumSize: Int64 = Installers.minimumSize
) async -> InstallerScan {
- await scan(installedApps: installedApps, home: home, root: root, exclusions: exclusions, minimumSize: minimumSize, measure: LeftoverScanner.walk)
+ await scan(
+ installedApps: installedApps,
+ home: home,
+ root: root,
+ exclusions: exclusions,
+ minimumSize: minimumSize,
+ measure: LeftoverScanner.walk
+ )
}
@concurrent
@@ -128,7 +135,13 @@ public enum Installers {
} else if isArchive {
guard let inside = installerInside(zip: url) else { continue }
items.append(
- appInstaller(at: url, size: size, heldBack: heldBack, installedApps: installedApps, named: inside)
+ appInstaller(
+ at: url,
+ size: size,
+ heldBack: heldBack,
+ installedApps: installedApps,
+ named: inside
+ )
)
} else {
items.append(
@@ -223,7 +236,10 @@ public enum Installers {
}
/// What measuring `url` gave: its size, and why what it saw leaves the item for the person to choose.
- private static func measured(_ url: URL, by measure: LeftoverScanner.Measure) async -> (size: Int64?, heldBack: HoldBack?) {
+ private static func measured(
+ _ url: URL,
+ by measure: LeftoverScanner.Measure
+ ) async -> (size: Int64?, heldBack: HoldBack?) {
let contents = await measure(url)
return (contents.flatMap { $0.couldNotBeRead ? nil : $0.size }, HoldBack.seen(in: contents))
}
@@ -235,7 +251,13 @@ public enum Installers {
/// Makes the item for an app installer. For an archive, `name` is what is inside it, which is matched
/// instead of the file name: a download can be called anything, such as `download (3).zip`.
- static func appInstaller(at url: URL, size: Int64?, heldBack: HoldBack?, installedApps: [InstalledApp], named name: String? = nil) -> InstallerItem {
+ static func appInstaller(
+ at url: URL,
+ size: Int64?,
+ heldBack: HoldBack?,
+ installedApps: [InstalledApp],
+ named name: String? = nil
+ ) -> InstallerItem {
let match = installedApp(named: name ?? url.deletingPathExtension().lastPathComponent, in: installedApps)
return InstallerItem(
url: url,
@@ -352,7 +374,9 @@ public enum Installers {
guard !exclusions.excludes(url), !exclusions.holds(url) else { continue }
let (size, seen) = await measured(url, by: measure)
guard isWorthARow(size, minimumSize) else { continue }
- let version = AppInspector.infoDictionary(in: url.appending(path: "Contents", directoryHint: .isDirectory))?["CFBundleShortVersionString"] as? String
+ let version = AppInspector.infoDictionary(
+ in: url.appending(path: "Contents", directoryHint: .isDirectory)
+ )?["CFBundleShortVersionString"] as? String
items.append(InstallerItem(
url: url,
kind: .macOSInstaller,
@@ -370,7 +394,12 @@ public enum Installers {
return items
}
- static func firmwareFiles(home: URL, exclusions: Exclusions, minimumSize: Int64, measure: LeftoverScanner.Measure) async -> [InstallerItem] {
+ static func firmwareFiles(
+ home: URL,
+ exclusions: Exclusions,
+ minimumSize: Int64,
+ measure: LeftoverScanner.Measure
+ ) async -> [InstallerItem] {
let folders = ["iPhone", "iPad", "iPod", "Apple TV", "HomePod", "Watch"].map {
home.appending(path: "Library/iTunes/\($0) Software Updates", directoryHint: .isDirectory)
}
@@ -519,7 +548,9 @@ public enum Installers {
static func backups(in folder: URL, measure: LeftoverScanner.Measure) async -> [InstallerItem] {
var items: [InstallerItem] = []
for url in files(in: folder) {
- guard (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true, !Task.isCancelled else { continue }
+ guard (try? url.resourceValues(forKeys: [.isDirectoryKey]).isDirectory) == true, !Task.isCancelled else {
+ continue
+ }
let info = plist(at: url.appending(path: "Info.plist"))
let manifest = plist(at: url.appending(path: "Manifest.plist"))
var notes: [InstallerItem.Note] = []
diff --git a/Packages/PeelCore/Sources/PeelCore/Space/SpaceRemoval.swift b/Packages/PeelCore/Sources/PeelCore/Space/SpaceRemoval.swift
index c0da99ed..928e1099 100644
--- a/Packages/PeelCore/Sources/PeelCore/Space/SpaceRemoval.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Space/SpaceRemoval.swift
@@ -74,7 +74,10 @@ public enum SpaceRemoval {
?? (systemCaches.keeps(child) ? .keptByMacOS : HoldBack.seen(in: contents))
}
return Plan(
- removable: children.removable, inUse: children.inUse, leftToDeveloper: children.leftToDeveloper, sizes: sizes,
+ removable: children.removable,
+ inUse: children.inUse,
+ leftToDeveloper: children.leftToDeveloper,
+ sizes: sizes,
heldBack: heldBack, needsTheHelper: needsTheHelper, refused: children.refused
)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Space/SpaceReport.swift b/Packages/PeelCore/Sources/PeelCore/Space/SpaceReport.swift
index 69509772..eb5de651 100644
--- a/Packages/PeelCore/Sources/PeelCore/Space/SpaceReport.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Space/SpaceReport.swift
@@ -423,12 +423,16 @@ public enum SpaceInventory {
storage: DeviceInfo.storage(of: home),
purgeable: purgeableSpace(of: home),
snapshots: await LocalSnapshots.list(),
- needsFullDiskAccess: items.contains { $0.size == nil && $0.urls.contains { FullDiskAccess.canList($0) == .missing } }
+ needsFullDiskAccess: items.contains {
+ $0.size == nil && $0.urls.contains { FullDiskAccess.canList($0) == .missing }
+ }
)
}
static func purgeableSpace(of url: URL) -> Int64? {
- let values = try? url.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey, .volumeAvailableCapacityKey])
+ let values = try? url.resourceValues(forKeys: [
+ .volumeAvailableCapacityForImportantUsageKey, .volumeAvailableCapacityKey,
+ ])
guard let important = values?.volumeAvailableCapacityForImportantUsage,
let free = values?.volumeAvailableCapacity else { return nil }
return max(0, important - Int64(free))
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swift b/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swift
index 3d31038b..ce07351c 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/Exclusions.swift
@@ -41,7 +41,8 @@ public struct Exclusions: Sendable, Codable, Hashable {
/// Compares what is excluded. `spellings` is left out, since it is worked out from `paths`.
public static func == (one: Exclusions, other: Exclusions) -> Bool {
- one.paths == other.paths && one.bundleIdentifiers == other.bundleIdentifiers && one.isUnreadable == other.isUnreadable
+ one.paths == other.paths && one.bundleIdentifiers == other.bundleIdentifiers
+ && one.isUnreadable == other.isUnreadable
&& one.hasBeenRead == other.hasBeenRead
}
@@ -76,7 +77,10 @@ public struct Exclusions: Sendable, Codable, Hashable {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.init(
paths: Set(try container.decodeIfPresent([Entry<URL>].self, forKey: .paths)?.compactMap(\.value) ?? []),
- bundleIdentifiers: Set(try container.decodeIfPresent([Entry<String>].self, forKey: .bundleIdentifiers)?.compactMap(\.value) ?? [])
+ bundleIdentifiers: Set(
+ try container.decodeIfPresent([Entry<String>].self, forKey: .bundleIdentifiers)?.compactMap(\.value)
+ ?? []
+ )
)
}
@@ -271,7 +275,8 @@ public struct ExclusionStore: Sendable {
private func read() -> Exclusions {
guard !url.isMissing else { return .none }
- guard let data = BoundedRead.data(at: url), let saved = try? JSONDecoder().decode(Exclusions.self, from: data) else {
+ guard let data = BoundedRead.data(at: url), let saved = try? JSONDecoder().decode(Exclusions.self, from: data)
+ else {
return .unreadable
}
return saved
@@ -283,7 +288,10 @@ public struct ExclusionStore: Sendable {
guard let data = try? encoder.encode(exclusions) else { return false }
if read().isUnreadable, DamagedFile.setAside(url) == nil { return false }
do {
- try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(
+ at: url.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
try data.write(to: url, options: .atomic)
return true
} catch {
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/FileIdentity.swift b/Packages/PeelCore/Sources/PeelCore/Support/FileIdentity.swift
index 97a9249a..9e70bd60 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/FileIdentity.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/FileIdentity.swift
@@ -39,7 +39,10 @@ public struct FileIdentity: Sendable, Hashable {
modificationTime = Self.nanoseconds(info.st_mtimespec)
statusChangeTime = Self.nanoseconds(info.st_ctimespec)
creationTime = Self.nanoseconds(info.st_birthtimespec)
- modificationDate = Date(timeIntervalSince1970: TimeInterval(info.st_mtimespec.tv_sec) + TimeInterval(info.st_mtimespec.tv_nsec) / 1_000_000_000)
+ modificationDate = Date(
+ timeIntervalSince1970: TimeInterval(info.st_mtimespec.tv_sec)
+ + TimeInterval(info.st_mtimespec.tv_nsec) / 1_000_000_000
+ )
}
public static func of(_ url: URL) -> FileIdentity? {
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/FileSize.swift b/Packages/PeelCore/Sources/PeelCore/Support/FileSize.swift
index f02ea861..3f693597 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/FileSize.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/FileSize.swift
@@ -21,7 +21,13 @@ public struct FolderContents: Sendable, Hashable {
/// container is refused outright.
public let couldNotBeRead: Bool
- init(size: Int64, holdsRepository: Bool, holdsWallet: Bool = false, newestChange: Date? = nil, couldNotBeRead: Bool = false) {
+ init(
+ size: Int64,
+ holdsRepository: Bool,
+ holdsWallet: Bool = false,
+ newestChange: Date? = nil,
+ couldNotBeRead: Bool = false
+ ) {
self.size = size
self.holdsRepository = holdsRepository
self.holdsWallet = holdsWallet
@@ -129,7 +135,9 @@ public enum FileSize {
private static func immediateContents(of url: URL) -> FolderContents {
ScanCount.current?.add(1)
do {
- let values = try url.resourceValues(forKeys: [.totalFileAllocatedSizeKey, .contentModificationDateKey, .linkCountKey, .mayShareFileContentKey])
+ let values = try url.resourceValues(forKeys: [
+ .totalFileAllocatedSizeKey, .contentModificationDateKey, .linkCountKey, .mayShareFileContentKey,
+ ])
return FolderContents(
size: (values.linkCount ?? 1) > 1 ? 0 : freed(by: url, values),
holdsRepository: repositoryMarkers.contains(url.lastPathComponent),
@@ -157,7 +165,8 @@ public enum FileSize {
/// Walks everything under `url`. Nil when `isStopped` turns true on the way, since half a walk is no answer.
static func walk(_ url: URL, countingFor scan: ScanCount? = nil, unless isStopped: () -> Bool) -> FolderContents? {
let fileKeys: Set<URLResourceKey> = [
- .isRegularFileKey, .totalFileAllocatedSizeKey, .linkCountKey, .fileIdentifierKey, .contentModificationDateKey,
+ .isRegularFileKey, .totalFileAllocatedSizeKey, .linkCountKey, .fileIdentifierKey,
+ .contentModificationDateKey,
.mayShareFileContentKey,
]
// Notes whether the folder, or a folder inside it, failed to open. The enumerator reports that only to the
@@ -194,7 +203,9 @@ public enum FileSize {
if repositoryMarkers.contains(file.lastPathComponent) { holdsRepository = true }
if isWallet(file.lastPathComponent) { holdsWallet = true }
guard let values = try? file.resourceValues(forKeys: fileKeys) else { return .next }
- if let written = values.contentModificationDate, written > newestChange ?? .distantPast { newestChange = written }
+ if let written = values.contentModificationDate, written > newestChange ?? .distantPast {
+ newestChange = written
+ }
guard values.isRegularFile == true else {
if isDataless(file) { enumerator.skipDescendants() }
return .next
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/MeasureFile.swift b/Packages/PeelCore/Sources/PeelCore/Support/MeasureFile.swift
index 05e89018..01954abe 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/MeasureFile.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/MeasureFile.swift
@@ -14,7 +14,11 @@ public struct MeasureFile: Sendable {
/// Appends `lines`, making the folder and the file when needed, and never through a link put at that name.
public func append(_ lines: [String]) {
try? FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
- let descriptor = open(url.path(percentEncoded: false), O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW | O_CLOEXEC, 0o600)
+ let descriptor = open(
+ url.path(percentEncoded: false),
+ O_WRONLY | O_APPEND | O_CREAT | O_NOFOLLOW | O_CLOEXEC,
+ 0o600
+ )
guard descriptor >= 0 else { return }
defer { close(descriptor) }
let data = Data(lines.map { $0 + "\n" }.joined().utf8)
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/ParentAccess.swift b/Packages/PeelCore/Sources/PeelCore/Support/ParentAccess.swift
index e5341e30..3984d723 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/ParentAccess.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/ParentAccess.swift
@@ -20,7 +20,10 @@ struct ParentAccess {
let path = url.path(percentEncoded: false)
var info = stat()
guard lstat(path, &info) == 0 else { return false }
- if let stickyOwner, Self.stickyFolderKeeps(itemOwnedBy: info.st_uid, folderOwnedBy: stickyOwner, from: getuid()) { return true }
+ if let stickyOwner,
+ Self.stickyFolderKeeps(itemOwnedBy: info.st_uid, folderOwnedBy: stickyOwner, from: getuid()) {
+ return true
+ }
if info.st_mode & S_IFMT == S_IFDIR { return access(path, W_OK) != 0 }
return false
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/SlowRead.swift b/Packages/PeelCore/Sources/PeelCore/Support/SlowRead.swift
index cc80f964..71c7cf22 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/SlowRead.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/SlowRead.swift
@@ -30,7 +30,10 @@ enum SlowRead {
/// Runs `read` on a thread of its own and returns its answer, or nil when it does not come within `budget`
/// or the task is canceled. A read that works in steps can check `isGivenUp` and stop once nobody waits.
- static func answer<T: Sendable>(within budget: TimeInterval, _ read: @escaping @Sendable (_ isGivenUp: @escaping @Sendable () -> Bool) -> T) async -> T? {
+ static func answer<T: Sendable>(
+ within budget: TimeInterval,
+ _ read: @escaping @Sendable (_ isGivenUp: @escaping @Sendable () -> Bool) -> T
+ ) async -> T? {
guard !Task.isCancelled else { return nil }
let answer = Answer<T>()
let thread = Thread { answer.give(read { answer.isGivenUp }) }
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/TextEditing.swift b/Packages/PeelCore/Sources/PeelCore/Support/TextEditing.swift
index eaeceb62..909905a4 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/TextEditing.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/TextEditing.swift
@@ -87,7 +87,8 @@ public final class TextEditing {
return
}
let names: [Notification.Name] = [
- .NSUndoManagerCheckpoint, .NSUndoManagerDidCloseUndoGroup, .NSUndoManagerDidUndoChange, .NSUndoManagerDidRedoChange,
+ .NSUndoManagerCheckpoint, .NSUndoManagerDidCloseUndoGroup, .NSUndoManagerDidUndoChange,
+ .NSUndoManagerDidRedoChange,
]
undoObservers = names.map { name in
NotificationCenter.default.addObserver(forName: name, object: undoManager, queue: nil) { [weak self] _ in
diff --git a/Packages/PeelCore/Sources/PeelCore/Support/ZipDirectory.swift b/Packages/PeelCore/Sources/PeelCore/Support/ZipDirectory.swift
index b36d512d..58cf7a54 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/ZipDirectory.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/ZipDirectory.swift
@@ -28,7 +28,8 @@ enum ZipDirectory {
var directoryOffset = UInt64(tail.number(UInt32.self, at: end + 16))
if entries == 0xFFFF || directorySize == 0xFFFF_FFFF || directoryOffset == 0xFFFF_FFFF {
let locator = Int64(tailStart) + Int64(end) - 20
- guard locator >= 0, let located = read(handle, at: UInt64(locator), count: 20), located.number(UInt32.self, at: 0) == zip64Locator,
+ guard locator >= 0, let located = read(handle, at: UInt64(locator), count: 20),
+ located.number(UInt32.self, at: 0) == zip64Locator,
let record = read(handle, at: located.number(UInt64.self, at: 8), count: 56),
record.number(UInt32.self, at: 0) == zip64EndRecord else { return nil }
entries = record.number(UInt64.self, at: 32)
@@ -42,7 +43,9 @@ enum ZipDirectory {
var names: [String] = []
var offset = 0
for _ in 0..<entries {
- guard offset + 46 <= directory.count, directory.number(UInt32.self, at: offset) == directoryEntry else { return nil }
+ guard offset + 46 <= directory.count, directory.number(UInt32.self, at: offset) == directoryEntry else {
+ return nil
+ }
let nameLength = Int(directory.number(UInt16.self, at: offset + 28))
let extraLength = Int(directory.number(UInt16.self, at: offset + 30))
let commentLength = Int(directory.number(UInt16.self, at: offset + 32))
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/GitSetting.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/GitSetting.swift
index e24302b6..36827f21 100644
--- a/Packages/PeelCore/Sources/PeelCore/Terminal/GitSetting.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/GitSetting.swift
@@ -93,7 +93,9 @@ public enum GitSetting: CaseIterable, Sendable {
default:
values(signingKey: nil).allSatisfy { wanted in
let found = settings[wanted.key.lowercased()]
- return wanted.value == "true" ? Self.isTrue(found) : Self.value(found)?.lowercased() == wanted.value.lowercased()
+ return wanted.value == "true"
+ ? Self.isTrue(found)
+ : Self.value(found)?.lowercased() == wanted.value.lowercased()
}
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/HushLogin.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/HushLogin.swift
index de6c5aab..f20f0bc2 100644
--- a/Packages/PeelCore/Sources/PeelCore/Terminal/HushLogin.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/HushLogin.swift
@@ -10,7 +10,11 @@ public enum HushLogin {
}
public static func turnOn(in home: URL) -> Bool {
- let descriptor = open(url(in: home).path(percentEncoded: false), O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o644)
+ let descriptor = open(
+ url(in: home).path(percentEncoded: false),
+ O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC,
+ 0o644
+ )
if descriptor >= 0 {
close(descriptor)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/SSHFile.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/SSHFile.swift
index e79b0bbf..28fc121a 100644
--- a/Packages/PeelCore/Sources/PeelCore/Terminal/SSHFile.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/SSHFile.swift
@@ -26,12 +26,17 @@ public enum SSHFile {
if url.isMissing {
return []
}
- return BoundedRead.data(at: url, maximum: maximumBytes).map { settings(in: String(decoding: $0, as: UTF8.self)) }
+ return BoundedRead.data(at: url, maximum: maximumBytes).map {
+ settings(in: String(decoding: $0, as: UTF8.self))
+ }
}
public static func write(_ settings: Set<SSHSetting>, to url: URL) -> Bool {
do {
- try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(
+ at: url.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
try Data(contents(of: settings).utf8).write(to: url, options: .atomic)
return true
} catch {
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift
index f5460d24..4fd90969 100644
--- a/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellFile.swift
@@ -52,7 +52,10 @@ public enum ShellFile {
public static func write(_ choices: Choices, to url: URL) -> Bool {
do {
- try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(
+ at: url.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
try Data(contents(of: choices).utf8).write(to: url, options: .atomic)
return true
} catch {
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/ShellSessions.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellSessions.swift
index c2a9262b..c1ae56f4 100644
--- a/Packages/PeelCore/Sources/PeelCore/Terminal/ShellSessions.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/ShellSessions.swift
@@ -5,7 +5,12 @@ public enum ShellSessions: Sendable, Equatable {
case bash
public static func inTerminal(_ terminal: TerminalSettings, home: URL = .homeDirectory) -> ShellSessions? {
- of(terminalSetting: terminal.shell(), loginShell: loginShell(), zdotdir: ProcessInfo.processInfo.environment["ZDOTDIR"], home: home)
+ of(
+ terminalSetting: terminal.shell(),
+ loginShell: loginShell(),
+ zdotdir: ProcessInfo.processInfo.environment["ZDOTDIR"],
+ home: home
+ )
}
static func of(terminalSetting: String?, loginShell: String?, zdotdir: String?, home: URL) -> ShellSessions? {
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalProfile.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalProfile.swift
index be7209ba..7b0f4ca2 100644
--- a/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalProfile.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalProfile.swift
@@ -33,7 +33,8 @@ public enum TerminalProfile {
}
public static func fingerprint(of settings: [String: Any]) -> String? {
- guard let data = try? PropertyListSerialization.data(fromPropertyList: settings, format: .xml, options: 0) else { return nil }
+ guard let data = try? PropertyListSerialization.data(fromPropertyList: settings, format: .xml, options: 0)
+ else { return nil }
return SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined()
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalSettings.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalSettings.swift
index 6a222e15..6102dc6f 100644
--- a/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalSettings.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalSettings.swift
@@ -19,7 +19,8 @@ public struct TerminalSettings: TerminalSettingsStoring, Sendable {
public func profiles() -> [String: [String: Any]] {
CFPreferencesAppSynchronize(Self.identifier as CFString)
- return CFPreferencesCopyAppValue(Self.profilesKey as CFString, Self.identifier as CFString) as? [String: [String: Any]] ?? [:]
+ return CFPreferencesCopyAppValue(Self.profilesKey as CFString, Self.identifier as CFString)
+ as? [String: [String: Any]] ?? [:]
}
public func setProfiles(_ profiles: [String: [String: Any]]) -> Bool {
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalThemeLedger.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalThemeLedger.swift
index 7e0758a7..46f454d7 100644
--- a/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalThemeLedger.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalThemeLedger.swift
@@ -13,7 +13,11 @@ public struct TerminalThemeLedger {
public init(stored: [String: Any] = [:]) {
before = (stored["before"] as? [String: String]).map { names in
- Dictionary(uniqueKeysWithValues: names.compactMap { role, name in TerminalProfileRole(rawValue: role).map { ($0, name) } })
+ Dictionary(
+ uniqueKeysWithValues: names.compactMap { role, name in
+ TerminalProfileRole(rawValue: role).map { ($0, name) }
+ }
+ )
}
chosen = stored["chosen"] as? String
written = stored["written"] as? [String: String] ?? [:]
@@ -44,7 +48,11 @@ public struct TerminalThemeLedger {
return Set(TerminalOption.allCases.filter { $0.isOn(in: profile) })
}
- public mutating func set(_ option: TerminalOption, to isOn: Bool, in terminal: some TerminalSettingsStoring) -> Outcome {
+ public mutating func set(
+ _ option: TerminalOption,
+ to isOn: Bool,
+ in terminal: some TerminalSettingsStoring
+ ) -> Outcome {
guard !terminal.isTerminalOpen else { return .terminalIsOpen }
guard !terminal.isManaged else { return .managed }
guard let name = theme(in: terminal)?.profileName else { return .unchanged }
@@ -67,7 +75,8 @@ public struct TerminalThemeLedger {
let settings = try TerminalProfile.settings(for: theme, options: options(in: terminal) ?? [])
guard let fingerprint = TerminalProfile.fingerprint(of: settings) else { return .refused }
var profiles = terminal.profiles()
- let isStillPeels = written[name] != nil && profiles[name].flatMap(TerminalProfile.fingerprint(of:)) == written[name]
+ let isStillPeels =
+ written[name] != nil && profiles[name].flatMap(TerminalProfile.fingerprint(of:)) == written[name]
let rewritesProfile = profiles[name] == nil || (isStillPeels && written[name] != fingerprint)
let isInUse = TerminalProfileRole.allCases.allSatisfy { terminal.profileName(for: $0) == name }
guard rewritesProfile || !isInUse else { return .unchanged }
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalTool.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalTool.swift
index 0a0aa5f7..ae545198 100644
--- a/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalTool.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalTool.swift
@@ -126,7 +126,9 @@ public enum TerminalTool: CaseIterable, Sendable {
}
public func isInstalled(prefix: URL) -> Bool {
- formulae.allSatisfy { FileManager.default.fileExists(atPath: prefix.appending(path: "opt/\($0)").path(percentEncoded: false)) }
+ formulae.allSatisfy {
+ FileManager.default.fileExists(atPath: prefix.appending(path: "opt/\($0)").path(percentEncoded: false))
+ }
}
/// Whether Homebrew still offers the tool: `known` is every formula name it knows, and `packages` what it said
diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalWindows.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalWindows.swift
index 2071ee9c..31332181 100644
--- a/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalWindows.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/TerminalWindows.swift
@@ -3,7 +3,10 @@ import Foundation
public enum TerminalWindows {
public static func switchMatters(in store: TweakStore = TweakStore()) -> Bool {
let tweak = TweakCatalog.terminalWindows
- return switchMatters(keptByTerminal: store.storedValue(of: tweak), readByTerminal: store.valueInEffect(of: tweak))
+ return switchMatters(
+ keptByTerminal: store.storedValue(of: tweak),
+ readByTerminal: store.valueInEffect(of: tweak)
+ )
}
static func switchMatters(keptByTerminal: Any?, readByTerminal: CFPropertyList?) -> Bool {
diff --git a/Packages/PeelCore/Sources/PeelCore/Tweaks/TweakStore.swift b/Packages/PeelCore/Sources/PeelCore/Tweaks/TweakStore.swift
index 39a3750d..a712aefb 100644
--- a/Packages/PeelCore/Sources/PeelCore/Tweaks/TweakStore.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Tweaks/TweakStore.swift
@@ -107,7 +107,12 @@ public struct TweakStore: Sendable, TweakStoring {
private static func copy(_ key: CFString, from name: String) -> CFPropertyList? {
name == globalDomain
- ? CFPreferencesCopyValue(key, kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost)
+ ? CFPreferencesCopyValue(
+ key,
+ kCFPreferencesAnyApplication,
+ kCFPreferencesCurrentUser,
+ kCFPreferencesAnyHost
+ )
: CFPreferencesCopyAppValue(key, name as CFString)
}
@@ -117,7 +122,13 @@ public struct TweakStore: Sendable, TweakStoring {
private static func set(_ key: CFString, to value: CFPropertyList?, in name: String) {
if name == globalDomain {
- CFPreferencesSetValue(key, value, kCFPreferencesAnyApplication, kCFPreferencesCurrentUser, kCFPreferencesAnyHost)
+ CFPreferencesSetValue(
+ key,
+ value,
+ kCFPreferencesAnyApplication,
+ kCFPreferencesCurrentUser,
+ kCFPreferencesAnyHost
+ )
} else {
CFPreferencesSetAppValue(key, value, name as CFString)
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/AppStoreLookup.swift b/Packages/PeelCore/Sources/PeelCore/Updates/AppStoreLookup.swift
index c1c24583..e08fe8bb 100644
--- a/Packages/PeelCore/Sources/PeelCore/Updates/AppStoreLookup.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Updates/AppStoreLookup.swift
@@ -25,7 +25,11 @@ enum AppStoreLookup {
static func answer(in data: Data) -> Answer {
guard let results = (try? JSONDecoder().decode(Response.self, from: data))?.results else { return .unreadable }
guard let mac = results.first(where: { $0.kind == "mac-software" }), let version = mac.version else { return .noMacRecord }
- return .mac(version: version, page: mac.trackViewUrl.flatMap(URL.init(string:)), developer: mac.artistName.flatMap { $0.isEmpty ? nil : $0 })
+ return .mac(
+ version: version,
+ page: mac.trackViewUrl.flatMap(URL.init(string:)),
+ developer: mac.artistName.flatMap { $0.isEmpty ? nil : $0 }
+ )
}
private struct Response: Decodable {
diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/Appcast.swift b/Packages/PeelCore/Sources/PeelCore/Updates/Appcast.swift
index bd7ffc38..88bf0290 100644
--- a/Packages/PeelCore/Sources/PeelCore/Updates/Appcast.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Updates/Appcast.swift
@@ -37,9 +37,15 @@ enum Appcast {
guard parser.parse() else { return .unreadable }
let releases = delegate.items.filter { item in
- guard item.channel == nil, item.displayVersion != nil, item.system == nil || item.system == "macos" else { return false }
- if let minimum = item.minimumSystemVersion, VersionComparison.isNewer(minimum, than: systemVersion) { return false }
- if let maximum = item.maximumSystemVersion, VersionComparison.isNewer(systemVersion, than: maximum) { return false }
+ guard item.channel == nil, item.displayVersion != nil, item.system == nil || item.system == "macos" else {
+ return false
+ }
+ if let minimum = item.minimumSystemVersion, VersionComparison.isNewer(minimum, than: systemVersion) {
+ return false
+ }
+ if let maximum = item.maximumSystemVersion, VersionComparison.isNewer(systemVersion, than: maximum) {
+ return false
+ }
if !isAppleSilicon, item.hardwareRequirements.contains("arm64") { return false }
return true
}
@@ -49,7 +55,10 @@ enum Appcast {
/// Picks the release notes link in the user's language, then a link with no language, then the first link.
/// `Bundle.preferredLocalizations` returns a language even when none matches (the first one offered, or `en`
/// when none is offered), so its pick is used only when the user reads that language and a link has it.
- static func preferred(_ links: [(language: String, url: URL)], languages: [String] = Locale.preferredLanguages) -> URL? {
+ static func preferred(
+ _ links: [(language: String, url: URL)],
+ languages: [String] = Locale.preferredLanguages
+ ) -> URL? {
func base(_ tag: String) -> String { Locale(identifier: tag).language.languageCode?.identifier ?? tag }
let tagged = links.map(\.language).filter { !$0.isEmpty }
if let best = Bundle.preferredLocalizations(from: tagged, forPreferences: languages).first,
@@ -78,7 +87,13 @@ enum Appcast {
private var notes: [String: [(language: String, url: URL)]] = [:]
private var noteLanguage = ""
- func parser(_ parser: XMLParser, didStartElement elementName: String, namespaceURI: String?, qualifiedName: String?, attributes: [String: String] = [:]) {
+ func parser(
+ _ parser: XMLParser,
+ didStartElement elementName: String,
+ namespaceURI: String?,
+ qualifiedName: String?,
+ attributes: [String: String] = [:]
+ ) {
text = ""
switch elementName {
case "item":
@@ -87,7 +102,9 @@ enum Appcast {
case "sparkle:releaseNotesLink", "releaseNotesLink", "sparkle:fullReleaseNotesLink", "link":
noteLanguage = attributes["xml:lang"] ?? ""
case "enclosure":
- guard var item = current, item.version == nil, item.shortVersion == nil, item.system == nil else { break }
+ guard var item = current, item.version == nil, item.shortVersion == nil, item.system == nil else {
+ break
+ }
item.version = attributes["sparkle:version"]
item.shortVersion = attributes["sparkle:shortVersionString"]
item.system = attributes["sparkle:os"]
@@ -105,14 +122,21 @@ enum Appcast {
text += String(decoding: CDATABlock, as: UTF8.self)
}
- func parser(_ parser: XMLParser, didEndElement elementName: String, namespaceURI: String?, qualifiedName: String?) {
+ func parser(
+ _ parser: XMLParser,
+ didEndElement elementName: String,
+ namespaceURI: String?,
+ qualifiedName: String?
+ ) {
let value = text.trimmingCharacters(in: .whitespacesAndNewlines)
switch elementName {
case "item":
if var item = current {
item.version = item.version ?? elementVersion
item.shortVersion = item.shortVersion ?? elementShortVersion
- item.releaseNotes = ["sparkle:releaseNotesLink", "releaseNotesLink", "sparkle:fullReleaseNotesLink", "link"].lazy.compactMap { self.notes[$0].flatMap { Appcast.preferred($0) } }.first
+ item.releaseNotes =
+ ["sparkle:releaseNotesLink", "releaseNotesLink", "sparkle:fullReleaseNotesLink", "link"]
+ .lazy.compactMap { self.notes[$0].flatMap { Appcast.preferred($0) } }.first
items.append(item)
}
current = nil
@@ -128,7 +152,9 @@ enum Appcast {
current?.channel = value
case "sparkle:hardwareRequirements":
let separators = CharacterSet.whitespaces.union(CharacterSet(charactersIn: ","))
- current?.hardwareRequirements = Set(value.lowercased().components(separatedBy: separators).filter { !$0.isEmpty })
+ current?.hardwareRequirements = Set(
+ value.lowercased().components(separatedBy: separators).filter { !$0.isEmpty }
+ )
case "sparkle:releaseNotesLink", "releaseNotesLink", "sparkle:fullReleaseNotesLink", "link":
if current != nil, let url = URL(string: value), url.scheme == "https",
notes[elementName]?.contains(where: { $0.language == noteLanguage }) != true {
diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/TeamRegistry.swift b/Packages/PeelCore/Sources/PeelCore/Updates/TeamRegistry.swift
index 3d621d9b..745d5f87 100644
--- a/Packages/PeelCore/Sources/PeelCore/Updates/TeamRegistry.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Updates/TeamRegistry.swift
@@ -62,7 +62,8 @@ public struct TeamRegistry: Sendable {
var entries = stored
var changes: [Change] = []
- for (identifier, copies) in Dictionary(grouping: apps, by: \.bundleIdentifier).sorted(by: { $0.key < $1.key }) {
+ for (identifier, copies) in Dictionary(grouping: apps, by: \.bundleIdentifier)
+ .sorted(by: { $0.key < $1.key }) {
let teams = Set(copies.compactMap(\.teamIdentifier).filter { !$0.isEmpty })
guard var entry = entries[identifier] else {
if let first = teams.sorted().first { entries[identifier] = Entry(team: first) }
@@ -125,7 +126,10 @@ public struct TeamRegistry: Sendable {
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
do {
let data = try encoder.encode(entries)
- try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(
+ at: url.deletingLastPathComponent(),
+ withIntermediateDirectories: true
+ )
try data.write(to: url, options: .atomic)
return true
} catch {
diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift
index e5bc6ed1..1810abb2 100644
--- a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateChecker.swift
@@ -44,14 +44,22 @@ public struct UpdateChecker: Sendable {
/// Returns the update status of `app`, without installing anything. `preference` decides which source to
/// believe when an app can be updated in more than one way.
@concurrent
- public func status(for app: InstalledApp, preference: UpdateSource = .automatic, casks: [HomebrewPackage] = []) async -> UpdateStatus {
+ public func status(
+ for app: InstalledApp,
+ preference: UpdateSource = .automatic,
+ casks: [HomebrewPackage] = []
+ ) async -> UpdateStatus {
await answer(for: app, preference: preference, casks: casks).status
}
/// Returns the update status, and the developer's name when the App Store answered. An App Store app is
/// signed by Apple, so its signature does not name the developer, but the store's record does.
@concurrent
- public func answer(for app: InstalledApp, preference: UpdateSource = .automatic, casks: [HomebrewPackage] = []) async -> UpdateAnswer {
+ public func answer(
+ for app: InstalledApp,
+ preference: UpdateSource = .automatic,
+ casks: [HomebrewPackage] = []
+ ) async -> UpdateAnswer {
switch preference {
case .homebrew:
// A cask Homebrew knows but never installed says nothing about this app's version, so the
@@ -70,7 +78,9 @@ public struct UpdateChecker: Sendable {
// An app from a cask may have no feed of its own, and a feed can be down. In both cases what Homebrew
// knows is used rather than "Can't check for updates".
let feed = await feedAnswer(for: app)
- if let homebrew, feed.status == .unsupported || feed.status == .failed { return UpdateAnswer(status: homebrew, developer: feed.developer) }
+ if let homebrew, feed.status == .unsupported || feed.status == .failed {
+ return UpdateAnswer(status: homebrew, developer: feed.developer)
+ }
return feed
}
}
@@ -113,7 +123,9 @@ public struct UpdateChecker: Sendable {
} else {
VersionComparison.isNewer(latest, than: installed)
}
- return isNewer ? .updateAvailable(version: latest, source: .developer, releaseNotes: item.releaseNotes) : .upToDate
+ return isNewer
+ ? .updateAvailable(version: latest, source: .developer, releaseNotes: item.releaseNotes)
+ : .upToDate
}
private func electronStatus(installed: String, at url: URL) async -> UpdateStatus {
diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateFeed.swift b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateFeed.swift
index 841a8cf9..813c0b3b 100644
--- a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateFeed.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateFeed.swift
@@ -59,7 +59,12 @@ public enum UpdateStatus: Sendable, Hashable, Codable {
}
extension UpdateFeed {
- static func detect(info: [String: Any], contents: URL, isFromAppStore: Bool, isSystemProtected: Bool) -> UpdateFeed? {
+ static func detect(
+ info: [String: Any],
+ contents: URL,
+ isFromAppStore: Bool,
+ isSystemProtected: Bool
+ ) -> UpdateFeed? {
guard !isSystemProtected else { return nil }
if isFromAppStore {
return .appStore
diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateMemory.swift b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateMemory.swift
index 66f0d4cf..2b211745 100644
--- a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateMemory.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateMemory.swift
@@ -17,7 +17,13 @@ public struct UpdateMemory: Codable, Equatable, Sendable {
/// does not name the developer, and the next check may be a week away.
public let developer: String?
- public init(status: UpdateStatus, schedule: UpdateSchedule, checked: Date?, describing app: InstalledApp, developer: String? = nil) {
+ public init(
+ status: UpdateStatus,
+ schedule: UpdateSchedule,
+ checked: Date?,
+ describing app: InstalledApp,
+ developer: String? = nil
+ ) {
self.status = status
self.schedule = schedule
self.checked = checked
@@ -37,7 +43,11 @@ public struct UpdateMemory: Codable, Equatable, Sendable {
/// Returns the entries that still apply to `apps`. An entry is dropped when no installed copy is the build it
/// describes, which also makes that app due at once, or when the app is not installed and the entry is more
/// than `longestAbsence` past due. With two copies at two builds, the entry describes one of them and stays.
- public static func recalled(from memory: [String: UpdateMemory], for apps: [InstalledApp], now: Date = .now) -> [String: UpdateMemory] {
+ public static func recalled(
+ from memory: [String: UpdateMemory],
+ for apps: [InstalledApp],
+ now: Date = .now
+ ) -> [String: UpdateMemory] {
let installed = Dictionary(grouping: apps, by: \.bundleIdentifier)
return memory.filter { identifier, entry in
guard let copies = installed[identifier] else {
diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/UpdatePreferences.swift b/Packages/PeelCore/Sources/PeelCore/Updates/UpdatePreferences.swift
index c669aab0..add5d668 100644
--- a/Packages/PeelCore/Sources/PeelCore/Updates/UpdatePreferences.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Updates/UpdatePreferences.swift
@@ -15,7 +15,11 @@ public struct UpdatePreferences: Sendable, Hashable {
/// The version the user chose to skip for each app, by bundle identifier.
public var skippedVersions: [String: String]
- public init(source: UpdateSource = .automatic, ignoredIdentifiers: Set<String> = [], skippedVersions: [String: String] = [:]) {
+ public init(
+ source: UpdateSource = .automatic,
+ ignoredIdentifiers: Set<String> = [],
+ skippedVersions: [String: String] = [:]
+ ) {
self.source = source
self.ignoredIdentifiers = ignoredIdentifiers
self.skippedVersions = skippedVersions
diff --git a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateSchedule.swift b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateSchedule.swift
index dd9e6f72..d79bfd6f 100644
--- a/Packages/PeelCore/Sources/PeelCore/Updates/UpdateSchedule.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Updates/UpdateSchedule.swift
@@ -35,7 +35,12 @@ public struct UpdateSchedule: Sendable, Equatable, Codable {
// An "up to date" found before the app was due (Rescan, or a bundle that changed) says nothing about how
// often the app ships, so the wait stays the same and only restarts from `now`.
if let previous, !previous.isDue(at: now), status == .upToDate, !previous.isRetrying {
- return UpdateSchedule(wait: previous.wait, due: now.addingTimeInterval(previous.wait), isRetrying: false, healthyWait: nil)
+ return UpdateSchedule(
+ wait: previous.wait,
+ due: now.addingTimeInterval(previous.wait),
+ isRetrying: false,
+ healthyWait: nil
+ )
}
let wait = wait(after: status, following: previous)
return UpdateSchedule(