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
Duplicates asks the guard only of files whose bytes match another's
Țugui Dragoș4da029420213
diff --git a/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateFinder.swift b/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateFinder.swiftindex 812710f8..4abb6073 100644--- a/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateFinder.swift+++ b/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateFinder.swift@@ -82,8 +82,15 @@ 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, removalGuard: removalGuard, progress: progress)- let sameSize = Dictionary(grouping: collected.candidates, by: \.identity.size).values.filter { $0.count > 1 }.flatMap { $0 }+ 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] = []+ for candidate in collected.candidates where exclusions.isKnown && !exclusions.excludes(candidate.url) {+ if names[candidate.identity.link] == nil { files.append(candidate) }+ names[candidate.identity.link, default: []].append(candidate)+ }+ 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@@ -92,7 +99,7 @@ public struct DuplicateFinder: Sendable {}}guard !Task.isCancelled else { throw CancellationError() }- let sampledGroups = Self.grouped(sampled)+ 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) }@@ -119,7 +126,7 @@ public struct DuplicateFinder: Sendable {let identity: FileIdentity}- private typealias HashedCandidate = (item: Candidate, digest: ContentDigest)+ typealias HashedCandidate = (item: Candidate, digest: ContentDigest)private struct ContentKey: Hashable {let size: Int64@@ -136,7 +143,6 @@ public struct DuplicateFinder: Sendable {in folders: [URL],spokenFor: Set<String>,neverProjects: Set<String>,- removalGuard: RemovalGuard,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@@ -203,26 +209,35 @@ public struct DuplicateFinder: Sendable {guard !Task.isCancelled else { throw CancellationError() }let outsideProjects = projects.isEmpty ? walked : walked.filter { !Self.isInside(projects, $0.url) }progress(.collecting(filesFound: outsideProjects.count))- let movable = try Self.movable(outsideProjects) { removalGuard.allowsRemoval(of: $0) && !$0.isInTheCloud }- return (movable, unreadable.urls)+ return (outsideProjects, unreadable.urls)}- /// The files that could be a copy of another and may be moved, each file once whatever names it has. Only a- /// file of the same size as another can be a copy, so `isMovable`, the guard and the cloud check, which open the- /// file and the folders above it, is asked of those alone, in the order the walk found them: a name it refuses- /// leaves the file to its next name.- static func movable(_ files: [Candidate], isMovable: (URL) -> Bool) throws(CancellationError) -> [Candidate] {- let sizes = Dictionary(files.map { ($0.identity.size, 1) }, uniquingKeysWith: +)- var seen = Set<FileIdentity.Link>()- var movable: [Candidate] = []+ /// The groups as they may move: each file under the first of its `names`, in the order the walk found them,+ /// that `isMovable` allows, and a group only while two files are left. `isMovable`, the guard and the cloud+ /// check, which open the file and the folders above it, is asked only here, of files whose first and last+ /// bytes already match another's.+ static func movable(+ _ groups: [[HashedCandidate]],+ names: [FileIdentity.Link: [Candidate]],+ isMovable: (URL) -> Bool+ ) throws(CancellationError) -> [[HashedCandidate]] {var asked = 0- for file in files where sizes[file.identity.size, default: 0] > 1 {- asked += 1- if asked.isMultiple(of: 256) {- guard !Task.isCancelled else { throw CancellationError() }+ var movable: [[HashedCandidate]] = []+ for group in groups {+ var kept: [HashedCandidate] = []+ for member in group {+ for name in names[member.item.identity.link] ?? [member.item] {+ asked += 1+ if asked.isMultiple(of: 256) {+ guard !Task.isCancelled else { throw CancellationError() }+ }+ if isMovable(name.url) {+ kept.append((item: name, digest: member.digest))+ break+ }+ }}- guard isMovable(file.url), seen.insert(file.identity.link).inserted else { continue }- movable.append(file)+ if kept.count > 1 { movable.append(kept) }}return movable}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DigestMemoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DigestMemoryTests.swiftindex d81acbb8..387bf900 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/DigestMemoryTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/DigestMemoryTests.swift@@ -41,6 +41,38 @@ struct DigestMemoryTests {memory.save(known)}+ @Test func neverReadsAnExcludedFile() async throws {+ let directory = try TemporaryDirectory()+ let memory = DigestMemory(url: directory.url.appending(path: "digests.bin"))+ let contents = randomData(count: FileDigest.sampleLength * 4)+ let first = try directory.file("home/Documents/first.bin", contents: contents)+ try directory.file("home/Pictures/second.bin", contents: contents)+ let excluded = try directory.file("home/Desktop/excluded.bin", contents: contents)+ let home = directory.url.appending(path: "home", directoryHint: .isDirectory)+ let finder = DuplicateFinder(homeDirectory: home, exclusions: Exclusions(paths: [excluded]), digestMemory: memory)++ let result = try await finder.scan(DuplicateScanOptions(folders: [home]))++ #expect(names(result).map(Set.init) == [["Documents/first.bin", "Pictures/second.bin"]])+ let known = memory.load()+ #expect(known.sample(of: try #require(FileIdentity.of(excluded))) == nil, "the excluded file was read")+ #expect(known.sample(of: try #require(FileIdentity.of(first))) != nil)+ }++ @Test func readsNothingBeforeTheExclusionsAreKnown() async throws {+ let directory = try TemporaryDirectory()+ let memory = DigestMemory(url: directory.url.appending(path: "digests.bin"))+ let contents = randomData(count: FileDigest.sampleLength * 4)+ let first = try directory.file("home/Documents/first.bin", contents: contents)+ try directory.file("home/Pictures/second.bin", contents: contents)+ let home = directory.url.appending(path: "home", directoryHint: .isDirectory)++ let result = try await DuplicateFinder(homeDirectory: home, exclusions: .notYetRead, digestMemory: memory).scan(DuplicateScanOptions(folders: [home]))++ #expect(result.groups.isEmpty)+ #expect(memory.load().sample(of: try #require(FileIdentity.of(first))) == nil, "a file was read")+ }+@Test func aScanRemembersWhatItRead() async throws {let directory = try TemporaryDirectory()let memory = DigestMemory(url: directory.url.appending(path: "digests.bin"))diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swiftindex 76085b62..97146090 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift@@ -60,30 +60,35 @@ struct DuplicateFinderTests {#expect(FileIdentity(late).modificationDate == Date(timeIntervalSince1970: 10_000_000_000.000000005))}- /// Only a file with another of its size can be a copy, so only those are asked whether they may move, which- /// opens the file and the folders above it. A name that may not move leaves the file to its next name.- @Test func asksWhetherAFileMayMoveOnlyWhenAnotherHasItsSize() throws {+ /// A name that may not move leaves the file to its next name, and a group left with one file is no group.+ @Test func asksWhetherAFileMayMoveOnlyOnceItsBytesMatchAnother() throws {let directory = try TemporaryDirectory()- let sizes = ["a": 10, "b": 10, "lonely": 11, "refused": 12, "other": 12]- for (name, size) in sizes {- try directory.file("files/\(name)", contents: randomData(count: size))+ for name in ["a", "b", "refused", "other", "alone", "partner"] {+ try directory.file("files/\(name)", contents: randomData(count: 10))}try FileManager.default.linkItem(at: directory.url.appending(path: "files/refused"), to: directory.url.appending(path: "files/linked"))- let files = try ["a", "b", "lonely", "refused", "linked", "other"].map { name in+ func candidate(_ name: String) throws -> DuplicateFinder.Candidate {let url = directory.url.appending(path: "files/\(name)")var info = stat()try #require(lstat(url.path(percentEncoded: false), &info) == 0)return DuplicateFinder.Candidate(url: url, identity: FileIdentity(info))}+ let digest = try #require(ContentDigest(bytes: [UInt8](repeating: 7, count: 32)))+ let refused = try candidate("refused")+ let groups: [[DuplicateFinder.HashedCandidate]] = [+ [(try candidate("a"), digest), (try candidate("b"), digest)],+ [(refused, digest), (try candidate("other"), digest)],+ [(try candidate("alone"), digest), (try candidate("partner"), digest)],+ ]var asked: [String] = []- let movable = try DuplicateFinder.movable(files) { url in+ let movable = try DuplicateFinder.movable(groups, names: [refused.identity.link: [refused, try candidate("linked")]]) { url inasked.append(url.lastPathComponent)- return url.lastPathComponent != "refused"+ return !["refused", "partner"].contains(url.lastPathComponent)}- #expect(asked == ["a", "b", "refused", "linked", "other"])- #expect(movable.map(\.url.lastPathComponent) == ["a", "b", "linked", "other"])+ #expect(asked == ["a", "b", "refused", "linked", "other", "alone", "partner"])+ #expect(movable.map { $0.map(\.item.url.lastPathComponent) } == [["a", "b"], ["linked", "other"]])}@Test func groupsFilesWithIdenticalContents() async throws {