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.

21.3 KB
Raw Blame
import ArgumentParser
import Foundation
import PeelCore

extension RemovalPart {
    /// The tool that moved the part, or nil for a removal that was interrupted, which names none.
    fileprivate var namedTool: String? { tool.isEmpty ? nil : tool }
}

/// One removal, as History shows it: everything that went in one go, grouped and dated as the app does.
struct Batch {
    let group: RemovalGroup
    let disks: MountedDisks

    var id: UUID { group.id }
    var records: [RemovalRecord] { group.records }
    var date: Date { group.date }
    /// Where the removal moved from: one part, or one for each tool whose selection it moved.
    var parts: [RemovalPart] { group.parts }
    /// Every part's source, as `--json` writes it.
    var source: String { Output.list(parts.map(\.source)) }
    /// The removal's name in the table: every part's source, or the first few and how many more pages there are.
    var name: String {
        RemovalPart.name(parts.map(\.source), more: { Output.count($0, "more page", "more pages") }, list: Output.list)
    }
    /// The tool the removal moved from, or nil for one that moved from several or was interrupted.
    var tool: String? { parts.count == 1 ? parts[0].namedTool : nil }
    var size: SizeTotal { group.size }
    /// The records whose items are still in the Trash of a disk that is connected. An item emptied from the Trash
    /// can't be put back.
    var restorable: [RemovalRecord] { records.filter { $0.isOnAConnectedDisk(disks) && $0.isStillInTrash } }
    /// The records on a disk that isn't connected: their items may still be in its Trash.
    var waiting: [RemovalRecord] { records.filter { !$0.isOnAConnectedDisk(disks) } }
    /// The records on a connected disk that macOS won't let Peel look at, which may still be in the Trash.
    var notKnown: [RemovalRecord] {
        records.filter { record in
            guard record.isOnAConnectedDisk(disks), case .notKnown = record.standing else { return false }
            return true
        }
    }

    /// What macOS answered when Peel looked for those, each answer once.
    var whyNotKnown: String {
        var answers: [String] = []
        for case .notKnown(let error) in notKnown.map(\.standing) where !answers.contains(error.localizedDescription) {
            answers.append(error.localizedDescription)
        }
        return Output.plain(answers.joined(separator: " "))
    }

    /// Each record where its disk is mounted now.
    static func all(in records: [RemovalRecord], disks: MountedDisks = .now()) -> [Batch] {
        RemovalRecord.grouped(records.map { $0.located(on: disks) }).map { Batch(group: $0, disks: disks) }
    }

    /// The first eight characters of the batch ID, which `peel history` shows and `peel restore` accepts.
    var shortID: String { String(id.uuidString.prefix(8)).lowercased() }

    var state: String {
        if !waiting.isEmpty { return "on a disk that isn't connected" }
        if records.allSatisfy(\.isStillInTrash) { return "in the Trash" }
        if !notKnown.isEmpty { return "can't look in the Trash" }
        return restorable.isEmpty ? "gone from the Trash" : "partly gone from the Trash"
    }
}

struct HistoryCommand: AsyncParsableCommand {
    static let configuration = CommandConfiguration(
        commandName: "history",
        abstract: "List what Peel moved to the Trash.",
        discussion: "The same History the Peel app shows, written by both. Put a removal back with `peel restore`. With --refused, lists what Peel was asked to move and wouldn't, which nothing else keeps."
    )

    static let defaultLimit = 20

    @Option(help: "Show at most this many removals. Without it, \(defaultLimit).")
    var limit: Int?

    @Flag(help: "List what stayed and why, instead of what moved.")
    var refused = false

    @Flag(help: "Move the record of every refusal to the Trash. Only with --refused.")
    var clear = false

    @Flag(name: .shortAndLong, help: "Don't ask for confirmation. Only with --clear.")
    var yes = false

    @OptionGroup var output: OutputOptions

    private struct Record: Encodable {
        struct Part: Encodable {
            let source: String
            let tool: String?

            private enum CodingKeys: String, CodingKey {
                case source, tool
            }

            /// Written by hand so an interrupted part says `"tool": null` rather than leaving the key out.
            func encode(to encoder: any Encoder) throws {
                var container = encoder.container(keyedBy: CodingKeys.self)
                try container.encode(source, forKey: .source)
                try container.encode(tool, forKey: .tool)
            }
        }

        let batch: String
        let date: Date
        let source: String
        let tool: String?
        let parts: [Part]
        let size: MeasuredSize
        let itemCount: Int
        let restorableCount: Int
        let files: [FileRecord]

        private enum CodingKeys: String, CodingKey {
            case batch, date, source, tool, parts, size, itemCount, restorableCount, files
        }

        /// Written by hand so a removal from several tools says `"tool": null` rather than leaving the key out.
        func encode(to encoder: any Encoder) throws {
            var container = encoder.container(keyedBy: CodingKeys.self)
            try container.encode(batch, forKey: .batch)
            try container.encode(date, forKey: .date)
            try container.encode(source, forKey: .source)
            try container.encode(tool, forKey: .tool)
            try container.encode(parts, forKey: .parts)
            try container.encode(size, forKey: .size)
            try container.encode(itemCount, forKey: .itemCount)
            try container.encode(restorableCount, forKey: .restorableCount)
            try container.encode(files, forKey: .files)
        }
    }

    /// One removal's refusals, as `--refused --json` writes them.
    private struct RefusedRemoval: Encodable {
        struct Item: Encodable {
            let path: String
            let reason: String
            let detail: String?
            let why: String

            private enum CodingKeys: String, CodingKey {
                case path, reason, detail, why
            }

            /// Written by hand so a refusal with no detail says `"detail": null` rather than leaving the key out.
            func encode(to encoder: any Encoder) throws {
                var container = encoder.container(keyedBy: CodingKeys.self)
                try container.encode(path, forKey: .path)
                try container.encode(reason, forKey: .reason)
                try container.encode(detail, forKey: .detail)
                try container.encode(why, forKey: .why)
            }
        }

        let batch: String
        let date: Date
        let source: String
        let tool: String?
        let items: [Item]

        private enum CodingKeys: String, CodingKey {
            case batch, date, source, tool, items
        }

        /// Written by hand so a removal from several tools says `"tool": null` rather than leaving the key out.
        func encode(to encoder: any Encoder) throws {
            var container = encoder.container(keyedBy: CodingKeys.self)
            try container.encode(batch, forKey: .batch)
            try container.encode(date, forKey: .date)
            try container.encode(source, forKey: .source)
            try container.encode(tool, forKey: .tool)
            try container.encode(items, forKey: .items)
        }
    }

    func validate() throws {
        if let limit, limit < 1 { throw ValidationError("--limit has to be at least 1.") }
        guard !clear || refused else { throw ValidationError("--clear only goes with --refused. What moved is forgotten from History in the Peel app.") }
        guard !clear || !output.json else {
            throw ValidationError("--clear writes nothing to read, so it doesn't go with --json.")
        }
        guard !yes || clear else { throw ValidationError("--yes only goes with --clear.") }
        if clear, !yes {
            try Output.requireConfirmable()
        }
    }

    private var shown: Int { limit ?? Self.defaultLimit }

    func run() async throws {
        let trash = TrashService(exclusions: await ExclusionStore().load())
        try await run(in: RemovalLog(), refusals: RefusalLog(), trash: trash)
    }

    func run(in log: RemovalLog, refusals: RefusalLog, trash: TrashService) async throws {
        guard !refused else { return try await listRefusals(in: refusals, trash: trash) }
        let outcome = await log.load()
        guard let records = outcome.records else {
            throw CommandFailure("Peel couldn't read its History.\(outcome.problem.map { " \($0.summary)" } ?? "")")
        }
        let all = Batch.all(in: records)
        let batches = Array(all.prefix(shown))

        if output.json {
            try Output.json(batches.map { batch in
                Record(
                    batch: batch.id.uuidString,
                    date: batch.date,
                    source: batch.source,
                    tool: batch.tool,
                    parts: batch.parts.map { Record.Part(source: $0.source, tool: $0.namedTool) },
                    size: MeasuredSize(batch.size),
                    itemCount: batch.records.count,
                    restorableCount: batch.restorable.count,
                    files: batch.records.map {
                        FileRecord(path: Output.path($0.originalURL), size: MeasuredSize($0.size))
                    }
                )
            })
        } else if batches.isEmpty {
            // Put Back and Forget can empty a History Peel did write to.
            let hasMoved = outcome.noLongerListed > 0 || RemovalTotals.read(beside: log.url).items > 0
            Output.line(hasMoved ? "History lists no removals." : "Peel hasn't moved anything to the Trash yet.")
        } else {
            Output.table(Self.rows(for: batches))
        }
        // Said where the list reaches History's oldest removal, below which the older ones would be.
        let reachesTheEnd = batches.count == all.count
        if outcome.noLongerListed > 0, reachesTheEnd {
            let removals = Output.count(outcome.noLongerListed, "older removal", "older removals")
            Output.note("History no longer lists \(removals). What was moved is still in the Trash unless you emptied it.")
        }
        // What stayed is listed apart, by --refused, so the list says how many removals of its time left something.
        let since = reachesTheEnd ? nil : batches.last?.date
        let stayed = RefusalRecord.grouped(await refusals.load().records ?? []).filter { removal in
            since.map { removal.date >= $0 } ?? true
        }
        if !stayed.isEmpty {
            let removals = Output.count(stayed.count, "removal also has", "removals also have")
            Output.note("\(removals) items that stayed. See `peel history --refused`.")
        }
        if let problem = outcome.problem {
            Output.note(problem.summary)
        }
    }

    static func rows(for batches: [Batch]) -> [[String]] {
        [["ID", "WHEN", "WHAT", "ITEMS", "SIZE", "STATE"]] + batches.map { batch in
            [
                batch.shortID,
                Output.day(batch.date),
                batch.name,
                Output.number(batch.records.count),
                Output.size(batch.size),
                batch.state,
            ]
        }
    }

    static func rows(for records: [RefusalRecord]) -> [[String]] {
        [["WHEN", "WHAT", "WHY", "PATH"]] + records.map { record in
            [Output.day(record.date), record.source, why(record), Output.path(record.url)]
        }
    }

    /// Why an item stayed, in the words the rest of `peel` uses. A reason a newer Peel wrote reads as recorded.
    static func why(_ record: RefusalRecord) -> String {
        record.failureReason?.summary ?? record.detail ?? record.reason
    }

    private func listRefusals(in log: RefusalLog, trash: TrashService) async throws {
        guard !clear else {
            guard await !log.holdsNothing() else {
                Output.line("Peel hasn't refused anything it was asked to move.")
                return
            }
            if !yes {
                try Output.confirm("Move the record of every refusal to the Trash?")
            }
            guard await log.clear(through: trash) else {
                throw CommandFailure("Peel couldn't move its record of refusals to the Trash.")
            }
            Output.line("Moved the record of every refusal to the Trash.")
            return
        }
        let read = await log.load()
        guard let records = read.records else { throw CommandFailure((read.problem ?? .unreadable(nil)).summary) }
        if let problem = read.problem {
            Output.note(problem.summary)
        }
        let removals = Array(RefusalRecord.grouped(records).prefix(shown))

        if output.json {
            try Output.json(removals.map { removal in
                RefusedRemoval(
                    batch: removal.id.uuidString,
                    date: removal.date,
                    source: Output.list(removal.parts.map(\.source)),
                    tool: removal.parts.count == 1 ? removal.parts[0].namedTool : nil,
                    items: removal.records.map { record in
                        RefusedRemoval.Item(
                            path: Output.path(record.url), reason: record.reason,
                            detail: record.failureReason?.detail ?? record.detail,
                            why: Self.why(record)
                        )
                    }
                )
            })
        } else if removals.isEmpty {
            Output.line("Peel hasn't refused anything it was asked to move.")
        } else {
            Output.table(Self.rows(for: removals.flatMap(\.records)))
        }
        if read.noLongerListed > 0 {
            let older = Output.count(read.noLongerListed, "older removal", "older removals")
            Output.note("This list no longer lists \(older). What each refused stayed where it was.")
        }
    }
}

struct RestoreCommand: AsyncParsableCommand {
    static let configuration = CommandConfiguration(
        commandName: "restore",
        abstract: "Put a removal back where it came from.",
        discussion: """
            ID is what `peel history` shows in its first column; the first few characters are enough.
            Items that need administrator access are left for the Peel app. Answering no exits with code 2; a \
            restore that couldn't finish exits 1.
            """
    )

    @Argument(help: "The removal to put back.")
    var id: String

    @Flag(help: "Show what would go back without moving anything.")
    var dryRun = false

    @Flag(name: .shortAndLong, help: "Don't ask for confirmation.")
    var yes = false

    func validate() throws {
        guard !id.isEmpty else { throw ValidationError("Give the ID of a removal. See `peel history`.") }
        if !yes, !dryRun {
            try Output.requireConfirmable()
        }
    }

    /// Returns the one batch whose ID starts with `id`, ignoring case. A prefix that fits two batches is refused
    /// rather than guessed at.
    static func batch(matching id: String, in batches: [Batch]) throws -> Batch {
        let wanted = id.lowercased()
        let found = batches.filter { $0.id.uuidString.lowercased().hasPrefix(wanted) }
        guard !found.isEmpty else {
            throw CommandFailure("No removal starts with \(Output.quoted(id)). See `peel history`.")
        }
        guard found.count == 1 else {
            throw CommandFailure("\(Output.count(found.count, "removal starts", "removals start")) with \(Output.quoted(id)): \(found.map(\.shortID).joined(separator: ", ")).")
        }
        return found[0]
    }

    func run() async throws {
        try await run(in: RemovalLog(), using: TrashService(exclusions: await ExclusionStore().load()))
    }

    func run(in log: RemovalLog, using service: TrashService) async throws {
        guard service.knowsTheExclusions else {
            throw AppLookup.Failure.exclusionsUnreadable(
                ExclusionStore.defaultURL.path(percentEncoded: false), service.whyExclusionsAreUnreadable
            )
        }
        let outcome = await log.load()
        guard let records = outcome.records else {
            throw CommandFailure("Peel couldn't read its History.\(outcome.problem.map { " \($0.summary)" } ?? "")")
        }
        let batch = try Self.batch(matching: id, in: Batch.all(in: records))
        let inTheTrash = batch.restorable
        let refused = inTheTrash.compactMap { record in
            service.refusal(ofPuttingBack: record.trashedItem, canUseHelper: false)
                .map { (record: record, failure: $0) }
        }
        let going = inTheTrash.filter { record in !refused.contains { $0.record.id == record.id } }
        // An item in the Trash of a disk that isn't connected is still there, once the disk is.
        let waiting = batch.waiting
        let items = Output.count(waiting.count, "item is", "items are")
        let elsewhere = waiting.isEmpty
            ? nil
            : "\(items) on a disk that isn't connected. Connect it and run the command again."
        let notKnown = batch.notKnown
        guard !inTheTrash.isEmpty else {
            let nothing = notKnown.isEmpty
                ? "Nothing of that removal is in the Trash anymore, so there is nothing to put back."
                : "Peel can't look in the Trash right now, so it can't say what could go back. macOS answered: \(batch.whyNotKnown)"
            throw CommandFailure(elsewhere ?? nothing)
        }

        if !going.isEmpty {
            Output.table(going.map { [Output.size($0.size), Output.path($0.originalURL)] })
            Output.line("Total: \(Output.size(going.totalSize))")
        }
        let gone = batch.records.count - inTheTrash.count - waiting.count - notKnown.count
        if gone > 0 {
            let items = Output.count(gone, "item is", "items are")
            Output.note("\(items) no longer in the Trash and can't be put back.")
        }
        if !notKnown.isEmpty {
            let items = notKnown.count == 1 ? "1 item Peel can't look at in the Trash right now stays" :
                "\(Output.number(notKnown.count)) items Peel can't look at in the Trash right now stay"
            Output.note("\(items) listed.")
        }
        if let elsewhere {
            Output.note(elsewhere)
        }
        for (record, failure) in refused {
            Output.note("\(Output.plain(Output.path(record.originalURL))) stays: \(failure.summary)")
        }
        for record in going where record.trashedItem.replacementStandsInItsPlace {
            Output.note("\(Output.plain(Output.path(record.originalURL))): the version now in its place goes to the Trash first, and History keeps it.")
        }

        guard !going.isEmpty else {
            Output.line("Nothing of that removal can be put back from here.")
            if dryRun { return }
            throw ExitCode.failure
        }
        guard !dryRun else {
            Output.line("Dry run: nothing was moved.")
            return
        }
        // As for a move: History would go on listing what came back.
        if let problem = RemovalLog.writeProblem(at: log.url) {
            throw CommandFailure("Nothing was put back. \(TrashFailure.Reason.historyCannotBeWritten(problem).summary).")
        }
        if !yes {
            try Output.confirm("Put \(Output.count(going.count, "item", "items")) back?")
        }

        let (restored, failures, forgotten) = await Uninterrupted.run {
            var restored: Set<UUID> = []
            var failures: [(RemovalRecord, RestoreFailure)] = []
            let ordered = going.inPutBackOrder
            // `peel` never uses the helper: items that need administrator access are left for the Peel app.
            let answers = await service.restore(ordered.map(\.trashedItem), canUseHelper: false)
            for (record, answer) in zip(ordered, answers.failures) {
                if let failure = answer {
                    failures.append((record, failure))
                } else {
                    restored.insert(record.id)
                }
            }
            // What made room goes into History under the same part, so it can come back too.
            var aside: [RemovalRecord] = []
            for (record, movedAside) in zip(ordered, answers.movedAside) {
                guard let movedAside else { continue }
                let size = await FileSize.reclaimableSize(of: movedAside.trashedURL)
                let sizes = size.map { [movedAside.originalURL: $0] } ?? [:]
                aside += record.part.records(of: TrashResult(trashed: [movedAside]), sizes: sizes, batch: UUID())
            }
            let kept = aside.isEmpty ? true : await log.add(aside).records != nil
            return (restored, failures, await log.remove(restored).records != nil && kept)
        }

        Output.line("Put \(Output.count(restored.count, "item", "items")) back.")
        if !forgotten {
            Output.note("Peel couldn't write this to its History, so it may offer to put these back again.")
        }
        for (record, failure) in failures {
            Output.note("Couldn't put \(Output.plain(Output.path(record.originalURL))) back: \(failure.summary)")
        }
        let stayed = !failures.isEmpty || !refused.isEmpty || !waiting.isEmpty || !notKnown.isEmpty
        try Cleanup.end(failed: stayed, recorded: forgotten)
    }
}