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.

6.5 KB
Raw Blame
import ArgumentParser
import Foundation
import PeelCore

/// A removal from the command line, once a command has worked out what would move. Every command that removes
/// goes through here, so they all ask, record, and exit the same way. The tool never uses the privileged helper,
/// so an item that needs administrator access stays, and the list says why.
struct Cleanup {
    struct Item {
        let url: URL
        /// Nil when the size isn't known, as for a folder that didn't answer in time. It is never shown as zero.
        let size: Int64?
        /// Why the item stays, or nil when it moves: the removal guard's answer, or `.needsHelper`.
        let refusal: TrashFailure.Reason?
    }

    let items: [Item]
    let source: String
    /// `"tool"` when `source` is the tool's own name, so the app's History can show it in the user's language.
    var sourceKey: String?
    let tool: String

    var moving: [Item] { items.filter { $0.refusal == nil } }
    var staying: [Item] { items.filter { $0.refusal != nil } }
    var total: SizeTotal { SizeTotal(moving.map(\.size)) }

    /// Builds a cleanup, judging each item before anything is printed, so the list shows what the move will
    /// really do.
    static func of(
        _ items: [(url: URL, size: Int64?)],
        source: String,
        sourceKey: String? = nil,
        tool: String,
        needingAdministrator: Set<URL> = [],
        service: TrashService
    ) -> Cleanup {
        Cleanup(
            items: items.map {
                Item(
                    url: $0.url,
                    size: $0.size,
                    refusal: needingAdministrator.contains($0.url) ? .needsHelper : service.refusal(of: $0.url)
                )
            },
            source: source,
            sourceKey: sourceKey,
            tool: tool
        )
    }

    static func refuseJSON() throws {
        throw ValidationError("--json lists what is there. Leave --remove off to get the list, or leave --json off to move it.")
    }

    /// Prints the list, with `notes` under it, and, unless `dryRun` is set, asks, moves what can go, and records it
    /// in History. A declined answer exits 2; a failed move, a plan where everything stays, and a move History could
    /// not record exit 1.
    func run(
        question: String,
        notes: [String] = [],
        dryRun: Bool,
        yes: Bool,
        using service: TrashService,
        recordingIn log: RemovalLog = RemovalLog(),
        refusals: RefusalLog = RefusalLog(),
        move: (TrashService, [URL]) async -> TrashResult = { await $0.trash($1) },
        checkingAgain: () async throws -> Void = {}
    ) async throws {
        if let note = UnreadableHistory.note(at: log.url) {
            Output.note(note)
        }
        // A third column, saying which items move and why the others stay, appears only when some item stays.
        let saysWhyItStays = !staying.isEmpty
        Output.table(items.map { item in
            [Output.size(item.size), Output.path(item.url)] + (saysWhyItStays ? [item.refusal.map { "stays: \($0.summary)" } ?? "moves"] : [])
        })
        if !moving.isEmpty {
            Output.line("Total: \(Output.size(total))")
        }
        notes.forEach(Output.note)
        let tooMany = Self.tooMany(moving.map(\.url))

        guard !dryRun else {
            if let tooMany { Output.note(tooMany) }
            Output.line(moving.isEmpty ? "Nothing here can be moved." : "Dry run: nothing was moved.")
            return
        }
        // The guard then refuses everything, which says nothing of the items, so no refusal is recorded.
        guard service.knowsTheExclusions else {
            throw AppLookup.Failure.exclusionsUnreadable(
                ExclusionStore.defaultURL.path(percentEncoded: false), service.whyExclusionsAreUnreadable
            )
        }
        // Refused items never reach the move, so their failures are built here and recorded, just as the app
        // records the refusals its service reports.
        let refused = items.compactMap { item in item.refusal.map { TrashFailure(url: item.url, reason: $0) } }
        guard !moving.isEmpty else {
            Output.line("Nothing here can be moved.")
            if let problem = await refusals.add(refused, source: source, sourceKey: sourceKey, tool: tool) {
                Output.note(problem.summary)
            }
            if !refused.isEmpty { throw ExitCode.failure }
            return
        }
        if let tooMany { throw CommandFailure(tooMany) }
        if !yes {
            try Output.confirm(question)
        }
        try await checkingAgain()

        let (result, recorded) = await Uninterrupted.run {
            let sizes = [URL: Int64](measured: items.map { ($0.url, $0.size) })
            let part = RemovalPart(source: source, sourceKey: sourceKey, tool: tool)
            let recordedAs = RecordedRemoval(batch: UUID(), part: part, sizes: sizes)
            let result = await RecordedRemoval.$current.withValue(recordedAs) { await move(service, moving.map(\.url)) }
            let recorded = await Removals.record(
                TrashResult(trashed: result.trashed, failures: result.failures + refused),
                from: source,
                key: sourceKey,
                sizes: sizes,
                tool: tool,
                in: log,
                refusals: refusals
            )
            return (result, recorded)
        }

        Output.line("Moved \(Output.count(result.trashed.count, "item", "items")) to the Trash.")
        if !recorded {
            Output.note("Peel couldn't write this to its History, so drag these back out of the Trash in Finder if you need to.")
        }
        for failure in result.failures {
            Output.note("\(Output.plain(Output.path(failure.url))) stayed: \(failure.reason.summary)")
        }
        try Self.end(failed: !result.failures.isEmpty, recorded: recorded)
    }

    /// Why History couldn't keep a removal of `urls`, or nil when it can.
    private static func tooMany(_ urls: [URL]) -> String? {
        let most = RemovalLog.mostAtOnce(of: urls)
        guard most < urls.count else { return nil }
        return "Peel can't move \(Output.count(urls.count, "item", "items")) at once: History can keep at most \(Output.number(most)) in one removal, so it can put them back. Move fewer at a time."
    }

    /// Ends a removal that ran: exit 1 when something failed, or when History could not record it, since then only
    /// the Trash knows what moved.
    static func end(failed: Bool, recorded: Bool) throws {
        guard !failed, recorded else { throw ExitCode.failure }
    }
}