Uninstall Mac apps with every file they leave behind, and see why each belongs. Free up space, fine-tune macOS, and set up Terminal.
Swift cache-cleanercleanerclideveloper-toolsdisk-cleanupdisk-spaceduplicate-finderhomebrewliquid-glassmac-cleanermacosmacos-appmacos-golden-gatemacos-tahoemacos-tweaksswiftswiftuiterminal-themesuninstalluninstaller
Keep Duplicates' reads and walks off the threads every task shares
Țugui Dragoș932cb7a1f31d
diff --git a/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateFinder.swift b/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateFinder.swiftindex 75632eea..e67a22b3 100644--- a/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateFinder.swift+++ b/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateFinder.swift@@ -111,6 +111,18 @@ public struct DuplicateFinder: Sendable {&& isDirectory.boolValue}+ /// Runs a walk as `BlockingWork`, so a folder that never answers holds no thread of the scan's task: it throws+ /// once the task is canceled, and the walk, asking `isGivenUp`, stops.+ static func walk<T: Sendable>(+ _ walk: @escaping @Sendable (_ isGivenUp: @escaping @Sendable () -> Bool) throws(CancellationError) -> T+ ) async throws(CancellationError) -> T {+ let answer: Result<T, CancellationError>? = await BlockingWork.run { isGivenUp in+ do throws(CancellationError) { return .success(try walk(isGivenUp)) } catch { return .failure(error) }+ }+ guard case .success(let value)? = answer else { throw CancellationError() }+ return value+ }+/// Whether `url` is a photo, music, or video library. Its files belong to the library's app, so none of them/// is offered as a copy, whatever its bytes.static func isAUserLibrary(_ url: URL) -> Bool {@@ -180,13 +192,16 @@ 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 await Self.walk { isGivenUp throws(CancellationError) in+ try collect(+ options,+ in: scannable,+ spokenFor: spokenFor,+ neverProjects: neverProjects,+ isGivenUp: isGivenUp,+ 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] = []@@ -262,6 +277,7 @@ public struct DuplicateFinder: Sendable {in folders: [URL],spokenFor: Set<String>,neverProjects: Set<String>,+ isGivenUp: () -> Bool,progress: (DuplicateScanProgress) -> Void) throws(CancellationError) -> (candidates: [Candidate], unreadableLocations: [URL]) {// The kind of a file is asked for only when a kind was chosen: working it out costs a lookup per@@ -275,7 +291,7 @@ public struct DuplicateFinder: Sendable {var visited = 0for folder in folders {- guard !Task.isCancelled else { throw CancellationError() }+ guard !isGivenUp() else { throw CancellationError() }let root = folder.resolvingSymlinksInPath()// A chosen folder is never an entry of its own walk, so one offered whole, or inside one, is skipped here.guard !spokenFor.contains(Self.path(of: root)), !Self.isInside(spokenFor, root) else { continue }@@ -294,7 +310,7 @@ public struct DuplicateFinder: Sendable {while let url = autoreleasepool(invoking: { enumerator.nextObject() as? URL }) {visited += 1if visited.isMultiple(of: 256) {- guard !Task.isCancelled else { throw CancellationError() }+ guard !isGivenUp() else { throw CancellationError() }progress(.collecting(filesFound: walked.count))}autoreleasepool {@@ -329,7 +345,7 @@ public struct DuplicateFinder: Sendable {}}}- guard !Task.isCancelled else { throw CancellationError() }+ guard !isGivenUp() else { throw CancellationError() }let outsideProjects = projects.isEmpty ? walked : walked.filter { !Self.isInside(projects, $0.url) }progress(.collecting(filesFound: outsideProjects.count))return (outsideProjects, unreadable.urls)diff --git a/Packages/PeelCore/Sources/PeelCore/Duplicates/FileDigest.swift b/Packages/PeelCore/Sources/PeelCore/Duplicates/FileDigest.swiftindex 2c78749b..91e90a9c 100644--- a/Packages/PeelCore/Sources/PeelCore/Duplicates/FileDigest.swift+++ b/Packages/PeelCore/Sources/PeelCore/Duplicates/FileDigest.swift@@ -16,8 +16,9 @@ enum FileDigest {identities.filter { known?.full(of: $0) == nil }.reduce(0) { $0 + $1.size }}- /// Digests `items`, `concurrentReads` at a time, leaving out any that cannot be read. Once the task is- /// canceled, no new read starts.+ /// Digests `items`, `concurrentReads` at a time, leaving out any that cannot be read. Each read runs as+ /// `BlockingWork`, so one that never answers holds no thread of the task's: once the task is canceled, the+ /// reads still under way are given up and no new read starts.static func many<Item: Sendable>(_ items: [Item],digest: @escaping @Sendable (Item) -> ContentDigest?,@@ -29,7 +30,7 @@ enum FileDigest {var completed = 0for _ in 0..<concurrentReads {guard let item = pending.next() else { break }- group.addTask { digest(item).map { (item: item, digest: $0) } }+ group.addTask { await read(item, digest) }}while let result = await group.next() {if let result {@@ -38,13 +39,20 @@ enum FileDigest {completed += 1onCompletion(completed)if !Task.isCancelled, let item = pending.next() {- group.addTask { digest(item).map { (item: item, digest: $0) } }+ group.addTask { await read(item, digest) }}}return results}}+ private static func read<Item: Sendable>(+ _ item: Item,+ _ digest: @escaping @Sendable (Item) -> ContentDigest?+ ) async -> (item: Item, digest: ContentDigest)? {+ (await BlockingWork.run { _ in digest(item) } ?? nil).map { (item: item, digest: $0) }+ }+/// SHA-256 of the first and last `sampleLength` bytes, or of the whole file when it isn't longer than both.static func sample(of url: URL, identity: FileIdentity, known: KnownDigests? = nil) -> ContentDigest? {if let digest = known?.sample(of: identity) { return digest }diff --git a/Packages/PeelCore/Sources/PeelCore/Duplicates/FolderDuplicates.swift b/Packages/PeelCore/Sources/PeelCore/Duplicates/FolderDuplicates.swiftindex b5a66e43..8218a594 100644--- a/Packages/PeelCore/Sources/PeelCore/Duplicates/FolderDuplicates.swift+++ b/Packages/PeelCore/Sources/PeelCore/Duplicates/FolderDuplicates.swift@@ -26,7 +26,8 @@ struct FolderDuplicates: Sendable {self.isDataless = isDataless}- private final class Folder {+ /// Built by one walk, then read and filled in by the comparison that waited for it, never by two at once.+ private final class Folder: @unchecked Sendable {let url: URLlet identity: FileIdentity/// A package, such as an app, a hidden folder, or a folder inside one of them: compared as part of the@@ -65,23 +66,9 @@ struct FolderDuplicates: Sendable {known: KnownDigests? = nil,progress: @escaping @Sendable (DuplicateScanProgress) -> Void) async throws(CancellationError) -> [DuplicateFolderGroup] {- var listed: [Folder] = []- var visited = Set<String>()- var found = 0- let listing = ReportThrottle()- 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- }- let folder = try list(root, identity: FileIdentity(info), depth: 0, isNeverOffered: false) {- found += 1- if listing.allows(isLast: false) { progress(.listing(foldersFound: found)) }- }- listed.append(folder)+ var listed = try await DuplicateFinder.walk { isGivenUp throws(CancellationError) in+ try self.listed(roots, isGivenUp: isGivenUp, progress: progress)}- progress(.listing(foldersFound: found))let candidates = self.candidates(in: listed, minimumSize: minimumSize)// Only the candidates are needed from here, and each holds the folders inside it.@@ -127,7 +114,9 @@ struct FolderDuplicates: Sendable {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: {})+ guard let folder = try? list(+ url, identity: FileIdentity(info), depth: 0, isNeverOffered: false, isGivenUp: { false }, onListing: {}+ )else { return nil }return identity(of: folder).map(\.hexadecimal)}@@ -145,15 +134,43 @@ struct FolderDuplicates: Sendable {return hasher.finalize()}+ private func listed(+ _ roots: [URL],+ isGivenUp: () -> Bool,+ progress: (DuplicateScanProgress) -> Void+ ) throws(CancellationError) -> [Folder] {+ var listed: [Folder] = []+ var visited = Set<String>()+ var found = 0+ let listing = ReportThrottle()+ 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+ }+ let folder = try list(+ root, identity: FileIdentity(info), depth: 0, isNeverOffered: false, isGivenUp: isGivenUp+ ) {+ found += 1+ if listing.allows(isLast: false) { progress(.listing(foldersFound: found)) }+ }+ listed.append(folder)+ }+ progress(.listing(foldersFound: found))+ return listed+ }+private func list(_ url: URL,identity: FileIdentity,depth: Int,isNeverOffered: Bool,+ isGivenUp: () -> Bool,onListing: () -> Void) throws(CancellationError) -> Folder {let folder = Folder(url: url, identity: identity, isNeverOffered: isNeverOffered)- guard !Task.isCancelled else { throw CancellationError() }+ guard !isGivenUp() else { throw CancellationError() }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.@@ -180,6 +197,7 @@ struct FolderDuplicates: Sendable {identity: identity,depth: depth + 1,isNeverOffered: isNeverOffered,+ isGivenUp: isGivenUp,onListing: onListing)guard !child.isProject else {diff --git a/Packages/PeelCore/Sources/PeelCore/Support/BlockingWork.swift b/Packages/PeelCore/Sources/PeelCore/Support/BlockingWork.swiftnew file mode 100644index 00000000..93d11591--- /dev/null+++ b/Packages/PeelCore/Sources/PeelCore/Support/BlockingWork.swift@@ -0,0 +1,20 @@+import Foundation++/// Runs work that may wait in the kernel, such as reads on a network volume that stopped answering, on a queue of its+/// own rather than on the threads Swift's tasks share, as `SlowRead` does with a thread, at a fraction of its cost per+/// item and with no budget. The task waits until the work answers or the task is canceled; the work can check+/// `isGivenUp` and stop, and whatever it gives after that is dropped.+enum BlockingWork {+ private static let queue = DispatchQueue(+ label: "com.tuguidragos.Peel.blocking-work", qos: .userInitiated, attributes: .concurrent+ )++ static func run<T: Sendable>(+ _ work: @escaping @Sendable (_ isGivenUp: @escaping @Sendable () -> Bool) -> T+ ) async -> T? {+ guard !Task.isCancelled else { return nil }+ let answer = SlowRead.Answer<T>()+ queue.async { answer.give(work { answer.isGivenUp }) }+ return await answer.wait(nil)+ }+}diff --git a/Packages/PeelCore/Sources/PeelCore/Support/SlowRead.swift b/Packages/PeelCore/Sources/PeelCore/Support/SlowRead.swiftindex 5ec4176c..7f59a326 100644--- a/Packages/PeelCore/Sources/PeelCore/Support/SlowRead.swift+++ b/Packages/PeelCore/Sources/PeelCore/Support/SlowRead.swift@@ -44,7 +44,7 @@ enum SlowRead {}/// Its one waiter is woken once: by the answer, by the end of the budget, or by its own cancellation.- private final class Answer<T: Sendable>: Sendable {+ final class Answer<T: Sendable>: Sendable {private struct State {var value: T?var waiter: CheckedContinuation<Void, Never>?@@ -69,7 +69,11 @@ enum SlowRead {waiter?.resume()}- func wait(_ budget: TimeInterval, while isAsked: @escaping @Sendable () -> Bool) async -> T? {+ /// With no `budget`, only the answer or the task's cancellation wakes the waiter.+ func wait(+ _ budget: TimeInterval?,+ while isAsked: @escaping @Sendable () -> Bool = AppDataQuestion.isOnScreen+ ) async -> T? {await withTaskCancellationHandler {await withCheckedContinuation { continuation inlet goesOnWaiting = state.withLock { state in@@ -78,6 +82,7 @@ enum SlowRead {return true}guard goesOnWaiting else { return continuation.resume() }+ guard let budget else { return }ReadBudget.end(after: budget, while: isAsked,isWaiting: { self.state.withLock { $0.value == nil && !$0.isWoken } }diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swiftindex 6da0f4fd..ded512c4 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift@@ -16,6 +16,74 @@ struct DuplicateFinderTests {/// Verifying reads a mebibyte at a time, and each report is a transaction on the main actor. So reports are/// let through at most once every 50 ms, and the last one is always let through.+ @Test func aReadThatNeverAnswersHoldsNeitherAStoppedScanNorItsThreads() async throws {+ let stuck = Stuck()+ let reading = Task {+ await FileDigest.many(Array(0..<8)) { _ -> ContentDigest? in+ stuck.hold()+ return nil+ }+ }+ await stuck.untilHeld()++ reading.cancel()+ _ = await reading.value++ #expect(stuck.isStillHeld, "the stopped scan waited for its reads to answer")+ stuck.letGo()+ }++ @Test func aWalkThatNeverAnswersHoldsNeitherAStoppedScanNorItsThreads() async throws {+ let stuck = Stuck()+ let walking = Task {+ try await DuplicateFinder.walk { _ throws(CancellationError) in+ stuck.hold()+ return 0+ }+ }+ await stuck.untilHeld()++ walking.cancel()+ let result = await walking.result++ #expect(stuck.isStillHeld, "the stopped scan waited for its walk to answer")+ #expect(throws: CancellationError.self) { try result.get() }+ stuck.letGo()+ }++ /// A read or a walk that never answers, as on a network volume that stopped answering. A test that would otherwise+ /// wait forever is let go after two minutes, so it fails rather than hangs.+ private final class Stuck: Sendable {+ private let gate = DispatchSemaphore(value: 0)+ private let isLetGo = Mutex(false)+ private let (holding, isHolding) = AsyncStream.makeStream(of: Void.self)++ var isStillHeld: Bool { isLetGo.withLock { !$0 } }++ func hold() {+ isHolding.yield()+ gate.wait()+ }++ func untilHeld() async {+ for await _ in holding { break }+ Task.detached { [self] in+ try? await Task.sleep(for: .seconds(120))+ letGo()+ }+ }++ /// Lets every read and walk held so far go, and any that comes after.+ func letGo() {+ let wasLetGo = isLetGo.withLock { isLetGo in+ defer { isLetGo = true }+ return isLetGo+ }+ guard !wasLetGo else { return }+ for _ in 0..<64 { gate.signal() }+ }+ }+@Test func reportsReadingAtARateTheScreenCanTake() {let reports = Mutex<[DuplicateScanProgress]>([])let reading = ReadProgress(bytesToRead: 1_000) { update in reports.withLock { $0.append(update) } }