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.

29.8 KB
Raw Blame
import Foundation
@testable import PeelCore
import PeelPrivileged
import Synchronization
import Testing

struct RemovalJournalTests {
    /// An item that moved at a time with more than milliseconds in it, as every real move has.
    private func item(
        _ name: String,
        in directory: borrowing TemporaryDirectory,
        at date: Date = Date(timeIntervalSince1970: 1_800_000_000.002_07)
    ) -> TrashedItem {
        TrashedItem(
            originalURL: directory.url.appending(path: "home/Library/Caches/\(name)"),
            trashedURL: directory.url.appending(path: "home/.Trash/\(name)"),
            date: date
        )
    }

    /// A process that has ended, which no running process can be taken for.
    private func endedProcess() throws -> RemovalJournal.Writer {
        let process = Process()
        process.executableURL = URL(filePath: "/usr/bin/true")
        try process.run()
        process.waitUntilExit()
        return RemovalJournal.Writer(pid: process.processIdentifier, started: 1)
    }

    private func service(
        in directory: borrowing TemporaryDirectory,
        journal: RemovalJournal,
        moveToTrash: @escaping @Sendable (URL) throws -> URL
    ) -> TrashService {
        TrashService(
            environment: SearchEnvironment(
                homeDirectory: directory.url.appending(path: "home"),
                rootDirectory: directory.url.appending(path: "root")
            ),
            journal: journal,
            moveToTrash: moveToTrash
        )
    }

    /// A removal cut short by a quit or a crash left what it moved in the journal: the next read of History takes it
    /// in, as an interrupted removal, and the journal lets it go.
    @Test func aRemovalCutShortIsInHistoryTheNextTimeItIsRead() async throws {
        let directory = try TemporaryDirectory()
        let history = directory.url.appending(path: "Peel/removals.json")
        let journal = RemovalJournal(beside: history)
        let moved = item("com.example.app", in: directory)
        journal.note([moved], batch: UUID(), by: try endedProcess())

        let records = try #require(await RemovalLog(url: history).load().records)

        #expect(records.map(\.trashedURL) == [moved.trashedURL])
        #expect(records.first?.sourceKey == "interrupted")
        #expect(records.first?.size == nil)
        #expect(journal.entries().isEmpty)
    }

    @Test func aPassStoppedBetweenPartsStaysOneRemoval() async throws {
        let directory = try TemporaryDirectory()
        let history = directory.url.appending(path: "Peel/removals.json")
        let journal = RemovalJournal(beside: history)
        let first = try directory.file("home/Library/Caches/com.example.one/cache.db").deletingLastPathComponent()
        let second = try directory.file("home/Library/Caches/com.example.two/cache.db").deletingLastPathComponent()
        let service = service(in: directory, journal: journal) { url in
            directory.url.appending(path: "home/.Trash/\(url.lastPathComponent)")
        }
        let batch = UUID()
        let developer = RemovalPart(source: "npm", sourceKey: nil, tool: "developer")
        let space = RemovalPart(source: "App Caches", sourceKey: "space.appCaches", tool: "space")
        let firstMoved = await RecordedRemoval.$current.withValue(RecordedRemoval(batch: batch, part: developer)) {
            await service.trash([first])
        }
        _ = await RemovalLog(url: history).add(developer.records(of: firstMoved, sizes: [:], batch: batch))
        _ = await RecordedRemoval.$current.withValue(RecordedRemoval(batch: batch, part: space)) {
            await service.trash([second])
        }

        let left = journal.entries()
        #expect(left.map(\.batch) == [batch])
        #expect(left.map(\.part) == [space])
        // The process stops before it records the second part.
        journal.forget(Set(left))
        for entry in left {
            let recorded = RecordedRemoval(batch: entry.batch, part: try #require(entry.part))
            journal.note([entry.item], batch: entry.batch, recordedAs: recorded, by: try endedProcess())
        }

        let records = try #require(await RemovalLog(url: history).load().records)
        let removals = RemovalRecord.grouped(records)
        #expect(removals.count == 1, "the part that stopped came back as a removal of its own")
        #expect(removals.first?.parts == [developer, space])
    }

    @Test func aRemovalCutShortKeepsTheSizesItsPageMeasured() async throws {
        let directory = try TemporaryDirectory()
        let history = directory.url.appending(path: "Peel/removals.json")
        let journal = RemovalJournal(beside: history)
        let measured = try directory.file("home/Library/Caches/com.example.one/cache.db").deletingLastPathComponent()
        let shared = try directory.file("home/Library/Caches/com.example.two/cache.db").deletingLastPathComponent()
        let service = service(in: directory, journal: journal) { url in
            directory.url.appending(path: "home/.Trash/\(url.lastPathComponent)")
        }
        let part = RemovalPart(source: "App Caches", sourceKey: "space.appCaches", tool: "space")
        let recorded = RecordedRemoval(batch: UUID(), part: part, sizes: [measured: 4_000], sharingStorage: [shared])
        _ = await RecordedRemoval.$current.withValue(recorded) { await service.trash([measured, shared]) }

        // The process stops before it records the part.
        let left = journal.entries()
        journal.forget(Set(left))
        for entry in left {
            journal.note([entry.item], batch: entry.batch, recordedAs: recorded, by: try endedProcess())
        }

        let records = try #require(await RemovalLog(url: history).load().records)
        let byPlace = Dictionary(uniqueKeysWithValues: records.map { ($0.originalURL.lastPathComponent, $0) })
        #expect(byPlace["com.example.one"]?.size == 4_000)
        #expect(byPlace["com.example.two"]?.size == nil)
        #expect(byPlace["com.example.two"]?.sharedStorage == true)
        #expect(byPlace["com.example.one"]?.sharedStorage == nil)
    }

    @Test func aMakersFolderLeftEmptyIsJournaledAsFreeingNothing() async throws {
        let directory = try TemporaryDirectory()
        let journal = RemovalJournal(beside: directory.url.appending(path: "Peel/removals.json"))
        let product = try directory.file("home/Library/Application Support/Example/Notes/notes.db")
            .deletingLastPathComponent()
        let trash = try directory.directory("home/.Trash")
        let service = service(in: directory, journal: journal) { url in
            let target = trash.appending(path: url.lastPathComponent)
            try FileManager.default.moveItem(at: url, to: target)
            return target
        }
        let app = InstalledApp(url: URL(filePath: "/Applications/Notes.app"), bundleIdentifier: "org.example.notes", name: "Notes")
        let part = RemovalPart(source: "Notes", sourceKey: nil, tool: "applications")
        let recorded = RecordedRemoval(batch: UUID(), part: part, sizes: [product: 2_000])

        let result = await RecordedRemoval.$current.withValue(recorded) {
            await service.trash(
                apps: [], thenFiles: { _ in [product] }, usingHelperFor: [], lettingTheirProgramsRun: [],
                emptiedFoldersNamed: MakersFolders.names(of: [app])
            )
        }

        #expect(result.emptied.map(\.lastPathComponent) == ["Example"])
        let sizes = Dictionary(
            uniqueKeysWithValues: journal.entries().map { ($0.item.originalURL.lastPathComponent, $0.size) }
        )
        #expect(sizes["Notes"] == .some(2_000))
        #expect(sizes["Example"] == .some(0))
    }

    /// While the process that moved an item still runs, it records the item itself, in its own words: a read of
    /// History meanwhile, from the app or from `peel`, leaves the journal alone.
    @Test func aRemovalStillUnderWayIsLeftToRecordItself() async throws {
        let directory = try TemporaryDirectory()
        let history = directory.url.appending(path: "Peel/removals.json")
        let journal = RemovalJournal(beside: history)
        let moved = item("com.example.app", in: directory)
        journal.note([moved], batch: UUID(), by: .current)

        #expect(await RemovalLog(url: history).load().records?.isEmpty == true)
        #expect(journal.entries().count == 1)

        let record = RemovalRecord(batch: UUID(), item: moved, size: 10, source: "Editor", tool: "applications")
        _ = await RemovalLog(url: history).add([record])

        #expect(journal.entries().isEmpty, "History recorded the item and the journal kept it")
    }

    @Test func historyIsOnTheDriveBeforeTheJournalLetsGo() async throws {
        let directory = try TemporaryDirectory()
        let history = directory.url.appending(path: "Peel/removals.json")
        let journal = RemovalJournal(beside: history)
        let moved = item("com.example.app", in: directory)
        journal.note([moved], batch: UUID(), by: .current)
        let flushed = Mutex<[(path: String, waiting: Int)]>([])
        let log = RemovalLog(url: history) { path in
            flushed.withLock { $0.append((path, journal.entries().count)) }
            return true
        }

        let record = RemovalRecord(batch: UUID(), item: moved, size: 10, source: "Editor", tool: "applications")
        _ = await log.add([record])
        _ = await log.remove([record.id])

        #expect(flushed.withLock { $0.map(\.path) } == [history.path(percentEncoded: false)])
        #expect(flushed.withLock { $0.first?.waiting } == 1, "the journal let the item go before History was on the drive")
    }

    @Test func historyIsOnTheDriveBeforeTheJournalLetsGoOfARemovalCutShort() async throws {
        let directory = try TemporaryDirectory()
        let history = directory.url.appending(path: "Peel/removals.json")
        let journal = RemovalJournal(beside: history)
        journal.note([item("com.example.app", in: directory)], batch: UUID(), by: try endedProcess())
        let flushed = Mutex<[Int]>([])
        let log = RemovalLog(url: history) { _ in
            flushed.withLock { $0.append(journal.entries().count) }
            return true
        }

        _ = await log.load()

        #expect(flushed.withLock { $0 } == [1], "the journal let the item go before History was on the drive")
        #expect(journal.entries().isEmpty)
    }

    @Test func aRemovalCutShortStaysInTheJournalWhileHistoryIsNotOnTheDrive() async throws {
        let directory = try TemporaryDirectory()
        let history = directory.url.appending(path: "Peel/removals.json")
        let journal = RemovalJournal(beside: history)
        let moved = item("com.example.app", in: directory)
        journal.note([moved], batch: UUID(), by: try endedProcess())
        let log = RemovalLog(url: history) { _ in false }

        let first = await log.load()
        let second = await log.load()

        #expect(journal.entries().count == 1)
        #expect(first.records?.count == 1)
        #expect(second.records?.count == 1, "it was taken in twice")
    }

    @Test func nothingMovesWhileTheJournalCannotBeWritten() throws {
        let directory = try TemporaryDirectory()
        let history = directory.url.appending(path: "Peel/removals.json")
        let journal = RemovalJournal(beside: history)
        try FileManager.default.createDirectory(at: journal.url, withIntermediateDirectories: true)

        #expect(RemovalLog.writeProblem(at: history) == .journalUnreadable(journal.url))
        #expect(journal.historyWriteProblem == .journalUnreadable(journal.url))
    }

    @Test func aJournalThatCannotBeReadIsKeptAsideAndSaid() async throws {
        let directory = try TemporaryDirectory()
        let history = directory.url.appending(path: "Peel/removals.json")
        let journal = RemovalJournal(beside: history)
        try FileManager.default.createDirectory(at: journal.url, withIntermediateDirectories: true)

        let outcome = await RemovalLog(url: history).load()

        guard case .damaged(let aside) = outcome.problem else {
            Issue.record("nothing said: \(String(describing: outcome.problem))")
            return
        }
        #expect(aside.isThere)
        #expect(journal.url.isMissing)
        #expect(RemovalLog.writeProblem(at: history) == nil)
    }

    @Test func aJournalThatCannotBeReadIsKeptAsideWithoutReadingHistory() async throws {
        let directory = try TemporaryDirectory()
        let history = try directory.file("Peel/removals.json", contents: Data("[]".utf8))
        let journal = RemovalJournal(beside: history)
        try FileManager.default.createDirectory(at: journal.url, withIntermediateDirectories: true)

        let problem = await RemovalLog(url: history).setAsideAnUnreadableJournal()

        guard case .damaged(let aside) = problem else {
            Issue.record("nothing said: \(String(describing: problem))")
            return
        }
        #expect(aside.isThere)
        #expect(journal.url.isMissing)
        #expect(RemovalLog.writeProblem(at: history) == nil)
    }

    @Test(.permissionsHold) func aJournalThisAccountCannotWriteIsNamed() throws {
        let directory = try TemporaryDirectory()
        let history = try directory.file("Peel/removals.json", contents: Data("[]".utf8))
        let journal = RemovalJournal(beside: history)
        _ = try directory.file("Peel/removals.journal", contents: Data())
        try directory.setPermissions(0o444, of: "Peel/removals.journal")
        defer { try? directory.setPermissions(0o644, of: "Peel/removals.journal") }

        #expect(RemovalLog.writeProblem(at: history) == .journalNotWritable(journal.url))
    }

    @Test func anItemPutBackLeavesTheJournal() async throws {
        let directory = try TemporaryDirectory()
        let history = directory.url.appending(path: "home/Peel/removals.json")
        let journal = RemovalJournal(beside: history)
        let trash = try directory.directory("home/.Trash")
        let file = try directory.file("home/Library/Caches/com.example.app/file", bytes: 10)
        let folder = file.deletingLastPathComponent()
        let service = service(in: directory, journal: journal) { url in
            let destination = trash.appending(path: url.lastPathComponent)
            try FileManager.default.moveItem(at: url, to: destination)
            return destination
        }

        let moved = await service.trash([folder])
        let item = try #require(moved.trashed.first)
        #expect(journal.entries().count == 1)

        #expect(await service.restore(item) == nil)

        #expect(journal.entries().isEmpty, "it would come back as a removal whose items are no longer in the Trash")
    }

    @Test func anItemsDiskIsTheOneItMovedOn() throws {
        let directory = try TemporaryDirectory()
        let disk = try JSONDecoder().decode(
            TrashedDisk.self, from: Data(#"{"volume": "ABC", "path": ".Trashes/501/file"}"#.utf8)
        )
        let entry = RemovalJournal.Entry(
            writer: .current, batch: UUID(), item: item("com.example.app", in: directory), disk: disk
        )

        #expect(entry.recordToTakeIn.disk == disk)
    }

    /// An item History already has is never recorded twice, as when a process wrote History and stopped before it
    /// could let the journal go.
    @Test func anItemHistoryHasIsNotRecordedAgain() async throws {
        let directory = try TemporaryDirectory()
        let history = directory.url.appending(path: "Peel/removals.json")
        let journal = RemovalJournal(beside: history)
        let moved = item("com.example.app", in: directory)
        let record = RemovalRecord(batch: UUID(), item: moved, size: 10, source: "Editor", tool: "applications")
        _ = await RemovalLog(url: history).add([record])
        journal.note([moved], batch: UUID(), by: try endedProcess())

        let records = try #require(await RemovalLog(url: history).load().records)

        #expect(records.map(\.id) == [record.id])
        #expect(journal.entries().isEmpty)
    }

    /// An older record at the same places, an item that moved there before and has left the Trash since, is
    /// another item: the one that moved now is still recorded.
    @Test func anOlderItemAtTheSamePlacesIsAnotherItem() async throws {
        let directory = try TemporaryDirectory()
        let history = directory.url.appending(path: "Peel/removals.json")
        let journal = RemovalJournal(beside: history)
        let older = item("com.example.app", in: directory)
        _ = await RemovalLog(url: history).add([RemovalRecord(batch: UUID(), item: older, size: 10, source: "Editor", tool: "applications")])
        let newer = item("com.example.app", in: directory, at: older.date.addingTimeInterval(86_400))
        journal.note([newer], batch: UUID(), by: try endedProcess())

        let records = try #require(await RemovalLog(url: history).load().records)

        #expect(records.count == 2)
        #expect(records.contains { $0.sourceKey == "interrupted" && LogTime.text(for: $0.date) == LogTime.text(for: newer.date) })
    }

    /// Each item is written down as soon as it has moved, before the next one moves and before the service returns,
    /// so a stop at any point loses no more than the item moving then.
    @Test func theServiceWritesDownEachItemAsItMoves() async throws {
        let directory = try TemporaryDirectory()
        let first = try directory.file("home/Library/Caches/com.example.one/cache.db").deletingLastPathComponent()
        let second = try directory.file("home/Library/Caches/com.example.two/cache.db").deletingLastPathComponent()
        let journal = RemovalJournal(beside: directory.url.appending(path: "Peel/removals.json"))
        let written = Mutex<[Int]>([])
        let service = service(in: directory, journal: journal) { url in
            written.withLock { $0.append(journal.entries().count) }
            return directory.url.appending(path: "home/.Trash/\(url.lastPathComponent)")
        }

        let result = await service.trash([first, second])

        #expect(result.trashed.count == 2)
        #expect(written.withLock { $0 } == [0, 1], "the first item was not written down before the second moved")
        #expect(Set(journal.entries().map(\.item.trashedURL)) == Set(result.trashed.map(\.trashedURL)))
    }

    @Test func whatTheHelperMovesIsWrittenDownAfterEachRequest() async throws {
        let directory = try TemporaryDirectory()
        let journal = RemovalJournal(beside: directory.url.appending(path: "Peel/removals.json"))
        let items = try (0...HelperRequest.maximumItems).map {
            try directory.file("home/Library/Caches/com.example.app\($0)/cache.db").deletingLastPathComponent()
        }
        let written = Mutex<[Int]>([])
        let service = TrashService(
            environment: SearchEnvironment(
                homeDirectory: directory.url.appending(path: "home"),
                rootDirectory: directory.url.appending(path: "root")
            ),
            moveThroughHelper: { urls in
                written.withLock { $0.append(journal.entries().count) }
                return TrashResult(trashed: urls.map {
                    TrashedItem(
                        originalURL: $0,
                        trashedURL: directory.url.appending(path: "home/.Trash/\($0.lastPathComponent)"),
                        date: .now
                    )
                })
            },
            journal: journal,
            moveToTrash: { _ in throw CocoaError(.fileWriteNoPermission) }
        )

        let result = await service.trash(items, usingHelperFor: Set(items))

        #expect(result.trashed.count == items.count)
        #expect(written.withLock { $0 } == [0, HelperRequest.maximumItems], "a request went before the last answer was written down")
        #expect(journal.entries().count == items.count)
    }

    /// While History cannot be read nothing moves, since what moved could not be listed for Put Back. An item the
    /// guard refuses keeps that reason, and Peel's own files, which History never lists, still go.
    @Test(.permissionsHold) func nothingMovesWhileHistoryCannotBeRead() async throws {
        let directory = try TemporaryDirectory()
        let history = try directory.file("home/Library/Application Support/Peel/removals.json", contents: Data("[]".utf8))
        try directory.setPermissions(0, of: "home/Library/Application Support/Peel/removals.json")
        defer { try? directory.setPermissions(0o644, of: "home/Library/Application Support/Peel/removals.json") }
        let item = try directory.file("home/Library/Caches/com.example.app/cache.db").deletingLastPathComponent()
        let keychains = try directory.directory("home/Library/Keychains")
        let moved = Mutex<[URL]>([])
        let service = service(in: directory, journal: RemovalJournal(beside: history)) { url in
            moved.withLock { $0.append(url) }
            return directory.url.appending(path: "home/.Trash/\(url.lastPathComponent)")
        }

        #expect(service.refusal(of: item) == .historyUnreadable)
        #expect(service.refusal(of: keychains) == .guarded(.protectedLocation))
        let result = await service.trash([item, keychains])
        let throughTheHelper = await service.trash([item], usingHelperFor: [item])

        #expect(moved.withLock { $0 }.isEmpty)
        #expect(result.failures.map(\.reason) == [.historyUnreadable, .guarded(.protectedLocation)])
        #expect(throughTheHelper.failures.map(\.reason) == [.historyUnreadable])
        #expect(await service.trashOwnFiles([item]).trashed.count == 1, "Peel's own files waited for History")
    }

    @Test func aRemovalHistoryCouldNotRecordComesBackAsWhatItWas() async throws {
        let directory = try TemporaryDirectory()
        let history = try directory.file("home/Library/Application Support/Peel/removals.json", contents: Data("[]".utf8))
        let journal = RemovalJournal(beside: history)
        let moved = item("com.example.app", in: directory)
        journal.note([moved], batch: UUID(), by: try endedProcess())
        let record = RemovalRecord(batch: UUID(), item: moved, size: 512, source: "Xcode", tool: "developer")
        let path = history.path(percentEncoded: false)
        #expect(chflags(path, UInt32(UF_IMMUTABLE)) == 0)
        defer { chflags(path, 0) }

        #expect(await RemovalLog(url: history).add([record]).records == nil)
        chflags(path, 0)
        let taken = try #require(await RemovalLog(url: history).load().records?.first)

        #expect(taken.source == "Xcode" && taken.tool == "developer" && taken.size == 512)
    }

    @Test(.permissionsHold) func nothingMovesWhileHistoryCannotBeWritten() async throws {
        let directory = try TemporaryDirectory()
        let history = try directory.file("home/Library/Application Support/Peel/removals.json", contents: Data("[]".utf8))
        try directory.setPermissions(0o555, of: "home/Library/Application Support/Peel")
        defer { try? directory.setPermissions(0o755, of: "home/Library/Application Support/Peel") }
        let item = try directory.file("home/Library/Caches/com.example.app/cache.db").deletingLastPathComponent()
        let moved = Mutex<[URL]>([])
        let service = service(in: directory, journal: RemovalJournal(beside: history)) { url in
            moved.withLock { $0.append(url) }
            return directory.url.appending(path: "home/.Trash/\(url.lastPathComponent)")
        }

        let folder = history.deletingLastPathComponent()
        let refusal = TrashFailure.Reason.historyCannotBeWritten(.folderNotWritable(folder))
        #expect(service.refusalOfEveryMove == refusal)
        let result = await service.trash([item])

        #expect(moved.withLock { $0 }.isEmpty)
        #expect(result.failures.map(\.reason) == [refusal])
    }

    @Test func historyNeedsRoomForTheCopyItsWriteMakes() throws {
        let directory = try TemporaryDirectory()
        let history = try directory.file("Peel/removals.json", contents: Data("[]".utf8))

        #expect(RemovalLog.writeProblem(at: history) == nil)
        #expect(RemovalLog.writeProblem(at: directory.url.appending(path: "Missing/Peel/removals.json")) == nil)
        let full = HistoryWriteProblem.diskFull(free: 1_000, needed: 1_000_002)
        #expect(RemovalLog.writeProblem(at: history, freeSpace: { _ in 1_000 }) == full)
        let folder = history.deletingLastPathComponent()
        #expect(RemovalLog.writeProblem(at: history, freeSpace: { _ in nil }) == .freeSpaceNotKnown(folder))
    }

    /// Peel's folder holds the journal, and Peel moves it last as it removes itself: that move is not written
    /// down, since History went with the folder and writing the line would make the folder again.
    @Test func theMoveOfTheFolderThatHoldsTheJournalMakesNothingAgain() async throws {
        let directory = try TemporaryDirectory()
        let folder = try directory.directory("home/Library/Application Support/Peel")
        let trash = try directory.directory("home/.Trash")
        let journal = RemovalJournal(beside: folder.appending(path: "removals.json"))
        let service = service(in: directory, journal: journal) { url in
            let landed = trash.appending(path: url.lastPathComponent)
            try FileManager.default.moveItem(at: url, to: landed)
            return landed
        }

        let result = await service.trash([folder])

        #expect(result.trashed.map(\.originalURL) == [folder])
        #expect(!FileManager.default.fileExists(atPath: folder.path(percentEncoded: false)), "the folder was made again")
    }

    /// A copy of settings Peel could not finish goes to the Trash as its own file, which History never lists, so
    /// nothing is written down that would come back later as an interrupted removal.
    @Test func aCopyPeelCouldNotFinishIsNotWrittenDown() async throws {
        let directory = try TemporaryDirectory()
        let backups = try directory.directory("home/Library/Application Support/Peel/Preference Backups")
        let journal = RemovalJournal(beside: directory.url.appending(path: "home/Library/Application Support/Peel/removals.json"))
        let moved = Mutex<[URL]>([])
        let service = service(in: directory, journal: journal) { url in
            moved.withLock { $0.append(url) }
            return directory.url.appending(path: "home/.Trash/\(url.lastPathComponent)")
        }
        let app = InstalledApp(url: URL(filePath: "/Applications/Example.app"), bundleIdentifier: "com.example.app", name: "Example")
        let preferences = URL.homeDirectory.appending(path: "Library/Preferences")
        let exports = Mutex(0)

        // The first domain is copied, the second is not, so the copy is left half made.
        let saved = await PreferenceBackup.save(
            [preferences.appending(path: "com.example.app.plist"), preferences.appending(path: "com.example.app.helper.plist")],
            for: app,
            in: backups,
            through: service
        ) { arguments in
            guard arguments.first == "export", let file = arguments.last else { return .yes }
            guard exports.withLock({ $0 += 1; return $0 }) == 1 else { return .no }
            FileManager.default.createFile(atPath: file, contents: Data())
            return .yes
        }

        #expect(saved == .failed(.notExported(domain: "com.example.app.helper")))
        #expect(moved.withLock { $0.count } == 1, "the half made copy did not go to the Trash")
        #expect(journal.entries().isEmpty)
    }

    /// A line cut short, as when the disk filled up, costs only itself: the next line starts on a line of its own.
    @Test func aLineCutShortCostsOnlyItself() throws {
        let directory = try TemporaryDirectory()
        let journal = RemovalJournal(beside: directory.url.appending(path: "Peel/removals.json"))
        let moved = item("com.example.app", in: directory)
        try FileManager.default.createDirectory(
            at: journal.url.deletingLastPathComponent(),
            withIntermediateDirectories: true
        )
        try Data(#"{"batch":"#.utf8).write(to: journal.url)

        journal.note([moved], batch: UUID())

        #expect(journal.entries().map(\.item.trashedURL) == [moved.trashedURL])
    }

    /// With no journal there is nothing to take in: reading it or letting lines go makes nothing on the disk.
    @Test func withNoJournalNothingIsMade() throws {
        let directory = try TemporaryDirectory()
        let folder = directory.url.appending(path: "Peel")
        let journal = RemovalJournal(beside: folder.appending(path: "removals.json"))

        #expect(journal.entries().isEmpty)
        journal.forget([item("com.example.app", in: directory)])

        #expect(!FileManager.default.fileExists(atPath: folder.path(percentEncoded: false)))
    }

    /// Every place in the Trash Peel put something, from any process: what History records and what a removal under
    /// way has written down so far, as long as that item is still there.
    @Test func knowsWhatPeelPutInTheTrashFromAnyProcess() async throws {
        let directory = try TemporaryDirectory()
        let log = RemovalLog(url: directory.url.appending(path: "Peel/removals.json"))
        let recorded = try directory.directory("Trash/Recorded.app")
        let underWay = try directory.directory("Trash/UnderWay.app")
        let emptied = directory.url.appending(path: "Trash/Emptied.app")
        try directory.directory("Trash/Thrown.app")
        func item(_ trashed: URL) -> TrashedItem {
            let original = URL(filePath: "/Applications/\(trashed.lastPathComponent)")
            return TrashedItem(originalURL: original, trashedURL: trashed, date: .now)
        }
        _ = await log.add([
            RemovalRecord(batch: UUID(), item: item(recorded), size: 1, source: "Recorded", tool: "applications"),
            RemovalRecord(batch: UUID(), item: item(emptied), size: 1, source: "Emptied", tool: "applications"),
        ])
        RemovalJournal(beside: log.url).note([item(underWay)], batch: UUID(), by: .current)

        let places = await log.placesInTheTrash()

        #expect(places == Set([recorded, underWay].map(PathPattern.comparablePath(of:))))
    }

}