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.

Move what Duplicates and File Search take as one removal

Țugui Dragoș1b574c6348b2
diff --git a/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateRemoval.swift b/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateRemoval.swift
index a2655c75..5aa0a3ca 100644
--- a/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateRemoval.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Duplicates/DuplicateRemoval.swift
@@ -1,9 +1,10 @@
public import Foundation
public enum DuplicateRemoval {
- /// Moves the selected folders, then the selected copies, to the Trash. A copy moves only while it and at
- /// least one unselected copy of its group are unchanged since the scan. The kept copy is checked again
- /// before each move, because a sync client, Finder, or another window can remove it while this runs.
+ /// Moves the selected folders, then the selected copies, to the Trash as one removal. A copy moves only while
+ /// it and at least one unselected copy of its group are unchanged since the scan, and a folder only while it
+ /// and an unselected folder of its group still hold exactly what was compared. Each is checked right before its
+ /// own move, because a sync client, Finder, or another window can change the kept one while this runs.
@concurrent
public static func trash(
_ selection: Set<URL>,
@@ -13,60 +14,38 @@ public enum DuplicateRemoval {
) async -> TrashResult {
// The scan never offers a file on its own when it sits inside an offered folder, so the two selections
// never ask for the same bytes.
- var result = await trash(folders: folders, from: scan, using: trashService)
-
+ var urls: [URL] = []
+ var selectedFolders: [URL: (folder: DuplicateFolder, kept: [DuplicateFolder])] = [:]
+ for group in scan.folderGroups {
+ let selected = group.folders.filter { folders.contains($0.url) }
+ guard !selected.isEmpty else { continue }
+ let kept = group.folders.filter { !folders.contains($0.url) }
+ for folder in selected {
+ urls.append(folder.url)
+ selectedFolders[folder.url] = (folder, kept)
+ }
+ }
+ var selectedFiles: [URL: (file: DuplicateFile, kept: [DuplicateFile])] = [:]
for group in scan.groups {
let selected = group.files.filter { selection.contains($0.url) }
guard !selected.isEmpty else { continue }
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 {
- result.failures.append(TrashFailure(url: file.url, reason: .lastCopy))
- continue
- }
- guard FileIdentity.of(file.url)?.holdsTheSameContents(as: file.identity) == true else {
- result.failures.append(TrashFailure(url: file.url, reason: .changedSinceScan))
- continue
- }
- let moved = await trashService.trash([file.url])
- result.trashed += moved.trashed
- result.failures += moved.failures
+ urls.append(file.url)
+ selectedFiles[file.url] = (file, kept)
}
}
- return result
- }
-
- /// 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 {
- var result = TrashResult()
-
- for group in scan.folderGroups {
- let selected = group.folders.filter { folders.contains($0.url) }
- guard !selected.isEmpty else { continue }
- let kept = group.folders.filter { !folders.contains($0.url) }
-
- for folder in selected {
- guard kept.contains(where: FolderDuplicates.holdsTheSameContents) else {
- result.failures.append(TrashFailure(url: folder.url, reason: .lastCopy))
- continue
- }
- guard FolderDuplicates.holdsTheSameContents(folder) else {
- result.failures.append(TrashFailure(url: folder.url, reason: .changedSinceScan))
- continue
- }
- let moved = await trashService.trash([folder.url])
- result.trashed += moved.trashed
- result.failures += moved.failures
+ let checkedFolders = selectedFolders
+ let checkedFiles = selectedFiles
+ return await trashService.trash(urls, refusing: { url in
+ if let entry = checkedFolders[url] {
+ guard entry.kept.contains(where: FolderDuplicates.holdsTheSameContents) else { return .lastCopy }
+ return FolderDuplicates.holdsTheSameContents(entry.folder) ? nil : .changedSinceScan
}
- }
- return result
+ guard let entry = checkedFiles[url] else { return nil }
+ guard entry.kept.contains(where: { FileIdentity.of($0.url)?.holdsTheSameContents(as: $0.identity) == true })
+ else { return .lastCopy }
+ return FileIdentity.of(url)?.holdsTheSameContents(as: entry.file.identity) == true ? nil : .changedSinceScan
+ })
}
}
diff --git a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
index 7062d8b8..5437ded7 100644
--- a/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Removal/TrashService.swift
@@ -390,11 +390,16 @@ public struct TrashService: Sendable {
/// Moves `urls` to the Trash as the current user, then stops the launchd jobs and forgets the preference
/// domains of what moved. `owner` is the bundle identifier of the app being reset: its own preference domain
- /// is forgotten even when Apple wrote the app.
+ /// is forgotten even when Apple wrote the app. `refusing` is asked about each item right before it moves, for a
+ /// check that reads the item as it is then, such as whether it changed since it was listed.
@concurrent
- public func trash(_ urls: [URL], ownedBy owner: String? = nil) async -> TrashResult {
+ public func trash(
+ _ urls: [URL],
+ ownedBy owner: String? = nil,
+ refusing: (@Sendable (URL) -> TrashFailure.Reason?)? = nil
+ ) async -> TrashResult {
if let refused = refusingAllWhileHistoryCannotBeRead(urls) { return refused }
- return await trash(urls, ownedBy: owner, removal: UUID(), lettingTheirProgramsRun: [])
+ return await trash(urls, ownedBy: owner, removal: UUID(), lettingTheirProgramsRun: [], refusing: refusing)
}
/// Moves files Peel made for itself, which History never lists, such as a copy of settings it could not
@@ -409,7 +414,8 @@ public struct TrashService: Sendable {
_ urls: [URL],
ownedBy owner: String?,
removal: UUID?,
- lettingTheirProgramsRun apps: Set<URL>
+ lettingTheirProgramsRun apps: Set<URL>,
+ refusing: (@Sendable (URL) -> TrashFailure.Reason?)? = nil
) async -> TrashResult {
// The guard reads the disk, so it is asked once for each item.
let refusals = urls.reduce(into: [URL: GuardRefusal]()) { $0[$1] = removalGuard.refusal(of: $1) }
@@ -429,6 +435,10 @@ public struct TrashService: Sendable {
// An item inside a folder that just moved went with it: it is neither moved again nor a failure.
let path = PathPattern.comparablePath(of: url)
guard !moved.hold(path) else { continue }
+ if let refusal = refusing?(url) {
+ result.failures.append(TrashFailure(url: url, reason: refusal))
+ continue
+ }
if let held = openFiles.refusal(of: url, lettingItsProgramsRun: apps.contains(url)) {
result.failures.append(TrashFailure(url: url, reason: held))
continue
diff --git a/Packages/PeelCore/Sources/PeelCore/Search/FileSearch.swift b/Packages/PeelCore/Sources/PeelCore/Search/FileSearch.swift
index 30c970dc..f72c9162 100644
--- a/Packages/PeelCore/Sources/PeelCore/Search/FileSearch.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Search/FileSearch.swift
@@ -59,22 +59,17 @@ public enum FileSearch {
/// Runs a Spotlight query and returns the paths it found, or nil when it could not run or was stopped.
typealias Gather = @concurrent @Sendable (sending MDQuery) async -> [String]?
- /// Moves `files` to the Trash. A file written again under the same name after it was listed is a different
- /// file, so it fails with `changedSinceScan` instead.
+ /// Moves `files` to the Trash as one removal. A file written again under the same name after it was
+ /// listed is a different file, so it fails with `changedSinceScan` instead, checked right before its own move.
@concurrent
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 {
- result.failures.append(TrashFailure(url: file.url, reason: .changedSinceScan))
- continue
- }
- let moved = await trashService.trash([file.url])
- result.trashed += moved.trashed
- result.failures += moved.failures
- }
- return result
+ let listed = Dictionary(files.map { ($0.url, $0) }) { first, _ in first }
+ return await trashService.trash(files.map(\.url), refusing: { url in
+ guard let identity = listed[url]?.identity,
+ FileIdentity.of(url)?.holdsTheSameContents(as: identity) == true
+ else { return .changedSinceScan }
+ return nil
+ })
}
/// Returns up to `maximumResults` regular files from the Spotlight index that match `criteria` and that the
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift
index c5694b52..fb2ea38a 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/DuplicateFinderTests.swift
@@ -733,4 +733,32 @@ struct DuplicateRemovalTests {
#expect(result.failures.isEmpty, "the tagged copy was read as changed")
#expect(result.trashed.map(\.originalURL) == [copy])
}
+
+ @Test func movesEveryCopyAsOneRemoval() async throws {
+ let directory = try TemporaryDirectory()
+ let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
+ for name in ["one", "two"] {
+ let contents = Data((0..<4_000).map { _ in UInt8.random(in: 0...255) })
+ try directory.file("home/Documents/\(name).bin", contents: contents)
+ try directory.file("home/Documents/\(name) copy.bin", contents: contents)
+ }
+ let scan = try await DuplicateFinder(homeDirectory: home).scan(.everySize(in: [home]))
+ #expect(scan.groups.count == 2)
+ let journal = RemovalJournal(beside: home.appending(path: "removals.json"))
+ let trash = try directory.directory("Trash")
+ let environment = SearchEnvironment(
+ homeDirectory: home, rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)
+ )
+ let service = TrashService(environment: environment, journal: journal) { url in
+ let destination = trash.appending(path: UUID().uuidString)
+ try FileManager.default.moveItem(at: url, to: destination)
+ return destination
+ }
+
+ let result = await DuplicateRemoval.trash(scan.suggestedSelection, from: scan, using: service)
+
+ #expect(result.trashed.count == 2)
+ #expect(result.failures.isEmpty)
+ #expect(Set(journal.entries().map(\.batch)).count == 1)
+ }
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/FileSearchTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/FileSearchTests.swift
index 1f5c5e1d..35578cca 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/FileSearchTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/FileSearchTests.swift
@@ -214,4 +214,32 @@ struct FileSearchTests {
#expect(results.files.map(\.url) == [other])
}
+
+ @Test func movesTheFilesItListedAsOneRemoval() async throws {
+ let directory = try TemporaryDirectory()
+ let home = directory.url.appending(path: "home", directoryHint: .isDirectory)
+ let first = try directory.file("home/Documents/first.txt")
+ let second = try directory.file("home/Documents/second.txt")
+ let files = [first, second].map {
+ FoundFile(
+ url: $0, size: 16, modificationDate: .now, requiresPrivileges: false, identity: FileIdentity.of($0)
+ )
+ }
+ let journal = RemovalJournal(beside: home.appending(path: "removals.json"))
+ let trash = try directory.directory("Trash")
+ let environment = SearchEnvironment(
+ homeDirectory: home, rootDirectory: directory.url.appending(path: "root", directoryHint: .isDirectory)
+ )
+ let service = TrashService(environment: environment, journal: journal) { url in
+ let destination = trash.appending(path: UUID().uuidString)
+ try FileManager.default.moveItem(at: url, to: destination)
+ return destination
+ }
+
+ let result = await FileSearch.trash(files, using: service)
+
+ #expect(result.trashed.count == 2)
+ #expect(result.failures.isEmpty)
+ #expect(Set(journal.entries().map(\.batch)).count == 1)
+ }
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
index c38410d9..91423cec 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/TrashServiceTests.swift
@@ -37,6 +37,26 @@ struct TrashServiceTests {
}
}
+ @Test func asksTheCallersQuestionBesideEachMove() async throws {
+ let directory = try TemporaryDirectory()
+ let service = try service(in: directory)
+ let first = try directory.file("home/Documents/first.txt")
+ let second = try directory.file("home/Documents/second.txt")
+ let third = try directory.file("home/Documents/third.txt")
+ let asked = Mutex<[URL]>([])
+
+ let result = await service.trash([first, second, third]) { url in
+ asked.withLock { $0.append(url) }
+ return url == second ? .changedSinceScan : nil
+ }
+
+ #expect(asked.withLock { $0 } == [first, second, third])
+ #expect(result.trashed.map(\.originalURL) == [first, third])
+ #expect(result.failures.map(\.url) == [second])
+ #expect(result.failures.map(\.reason) == [.changedSinceScan])
+ #expect(FileManager.default.fileExists(atPath: second.path(percentEncoded: false)))
+ }
+
/// Records the jobs launchd would have been asked to stop, since a test never asks launchd.
private actor Stopped {
private(set) var labels: [String] = []