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
Read a cask's paths the way Homebrew reads them
Țugui Dragoș44ba88e979c9
diff --git a/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift b/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swiftindex 7e05e6c9..4d34f425 100644--- a/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift+++ b/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift@@ -206,7 +206,7 @@ public enum DeveloperCaches {case .userTemporary: userTemporary}guard let root else { return [] }- var places = PathPattern.expand(path, home: root, limited: false)+ var places = PathPattern.expand(path, home: root, from: .peel)places += movedBy?.places(preference: preference, settings: settings).map(\.place) ?? []var seen: Set<String> = []return places.filter { seen.insert(PathPattern.comparablePath(of: $0)).inserted }diff --git a/Packages/PeelCore/Sources/PeelCore/Homebrew/CaskEvidence.swift b/Packages/PeelCore/Sources/PeelCore/Homebrew/CaskEvidence.swiftindex 969ae7be..82349024 100644--- a/Packages/PeelCore/Sources/PeelCore/Homebrew/CaskEvidence.swift+++ b/Packages/PeelCore/Sources/PeelCore/Homebrew/CaskEvidence.swift@@ -179,11 +179,13 @@ public struct CaskEvidence: Sendable, Hashable {return true}- /// A cask only ever names absolute paths; anything else is ignored. Its patterns are data read from Homebrew,- /// so `glob` keeps them within its limits.+ /// A cask's path read as Homebrew reads one (`each_resolved_path` in its `abstract_uninstall.rb`): `~` is the home+ /// folder only before a slash, and a relative path or one with a `.` or `..` in it is skipped.static func expand(_ pattern: String, home: URL) -> [URL] {- guard pattern.hasPrefix("/") || pattern.hasPrefix("~") else { return [] }- return PathPattern.expand(pattern, home: home, limited: true)+ guard pattern.hasPrefix("/") || pattern == "~" || pattern.hasPrefix("~/"),+ !PathComponents.of(pattern).contains(where: { $0 == "." || $0 == ".." })+ else { return [] }+ return PathPattern.expand(pattern, home: home, from: .cask)}static func isInLibrary(_ url: URL, home: URL) -> Bool {diff --git a/Packages/PeelCore/Sources/PeelCore/Support/PathPattern.swift b/Packages/PeelCore/Sources/PeelCore/Support/PathPattern.swiftindex dad9d745..27c7b3cd 100644--- a/Packages/PeelCore/Sources/PeelCore/Support/PathPattern.swift+++ b/Packages/PeelCore/Sources/PeelCore/Support/PathPattern.swift@@ -89,11 +89,22 @@ public enum PathPattern {|| ProtectedData.refuses(canonical(url).path(percentEncoded: false), home: home)}+ /// Where a pattern comes from, which says how it is read.+ enum Source {+ /// Peel's own, a shell pattern for a tool's folders: every match counts.+ case peel+ /// A cask's, read as Homebrew reads it with Ruby's `Dir.glob`: `{a,b}` for each alternative, a backslash+ /// quoting the next character, and `**/` for any number of folders but hidden ones and links. Being data from+ /// elsewhere, it keeps `glob`'s limits: 128 paths on macOS whatever `gl_matchc` says (`GLOB_LIMIT_STAT` in+ /// Libc's `glob.c`), and as many entries read as `GLOB_LIMIT_READDIR`, for a `**/` too.+ case cask+ }++ private static let entriesAStarReads = 16_384+/// The existing files `pattern` names, leaving out irreplaceable ones (`isIrreplaceable`). A pattern without a- /// leading `/` or `~` is read relative to `home`. A `limited` pattern is expanded within `glob`'s own limits,- /// which keep it from walking the whole disk and stop it at 128 paths on macOS, whatever `gl_matchc` says- /// (`GLOB_LIMIT_STAT` in Libc's `glob.c`).- static func expand(_ pattern: String, home: URL, limited: Bool) -> [URL] {+ /// leading `/` or `~` is read relative to `home`.+ static func expand(_ pattern: String, home: URL, from source: Source) -> [URL] {let root = comparablePath(of: home)var path = patternif path.hasPrefix("~") {@@ -101,10 +112,57 @@ public enum PathPattern {} else if !path.hasPrefix("/") {path = root + "/" + path}+ guard source == .cask, path.contains("/**/") else { return matches(of: path, root: root, source: source) }+ var unread = entriesAStarReads+ return matchesThroughStars(of: path, root: root, unread: &unread)+ }++ /// What a cask's `path` names when its first `**/` stands for the folder before it and every folder below.+ private static func matchesThroughStars(of path: String, root: String, unread: inout Int) -> [URL] {+ guard let star = path.range(of: "/**/") else { return matches(of: path, root: root, source: .cask) }+ let rest = path[star.upperBound...]+ var found: [URL] = []+ for start in matches(of: String(path[..<star.lowerBound]), root: root, source: .cask) where start.isRealFolder {+ for folder in folders(from: start, unread: &unread) {+ let inside = quoted(comparablePath(of: folder)) + "/" + rest+ found += matchesThroughStars(of: inside, root: root, unread: &unread)+ }+ }+ return found+ }++ /// `start` and every folder below it, level by level, but hidden ones and links, until `unread` entries are read.+ private static func folders(from start: URL, unread: inout Int) -> [URL] {+ var found = [start]+ var level = [start]+ while !level.isEmpty {+ var below: [URL] = []+ for folder in level where unread > 0 {+ let entries = (try? FileManager.default.contentsOfDirectory(+ at: folder, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey]+ )) ?? []+ unread -= entries.count+ below += entries.filter { !$0.lastPathComponent.hasPrefix(".") && $0.isRealFolder }+ .sorted { $0.lastPathComponent < $1.lastPathComponent }+ }+ found += below+ level = below+ }+ return found+ }++ /// `path` with every character `glob` reads as a pattern quoted, so a folder's own name is taken as written.+ private static func quoted(_ path: String) -> String {+ path.reduce(into: "") { text, character in+ if "\\*?[]{}".contains(character) { text.append("\\") }+ text.append(character)+ }+ }- // A path without `*` or `?` that exists is taken as written, so a bracket in a real name- // (`App [Beta]`) is not read as a character class.- let isPattern = path.contains("*") || path.contains("?")+ private static func matches(of path: String, root: String, source: Source) -> [URL] {+ // A path with no wildcard (`*`, `?`, and for a cask `{`) that exists is taken as written, so a bracket in a+ // real name (`App [Beta]`) is not read as a character class.+ let isPattern = path.contains("*") || path.contains("?") || (source == .cask && path.contains("{"))if !isPattern, FileManager.default.fileExists(atPath: path) {let url = entry(named: path)return isIrreplaceable(url, home: root) ? [] : [url]@@ -113,8 +171,12 @@ public enum PathPattern {var results = glob_t()defer { globfree(&results) }+ let flags = switch source {+ case .peel: GLOB_NOSORT | GLOB_NOESCAPE+ case .cask: GLOB_NOSORT | GLOB_BRACE | GLOB_LIMIT+ }// At its limit, `glob` returns GLOB_NOSPACE with the paths found so far.- let code = glob(path, GLOB_NOSORT | GLOB_NOESCAPE | (limited ? GLOB_LIMIT : 0), nil, &results)+ let code = glob(path, flags, nil, &results)guard code == 0 || code == GLOB_NOSPACE, results.gl_pathv != nil else { return [] }return (0..<Int(results.gl_pathc)).compactMap { index inguard let pointer = results.gl_pathv[index] else { return nil }diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AttackPathProducerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AttackPathProducerTests.swiftindex 3301f920..2dd242ee 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/AttackPathProducerTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/AttackPathProducerTests.swift@@ -27,10 +27,10 @@ struct AttackPathProducerTests {at: home.appending(path: ".config"))- let cased = PathPattern.expand("Library/mobile documents/com~apple~CloudDocs/dotfiles", home: home, limited: false)+ let cased = PathPattern.expand("Library/mobile documents/com~apple~CloudDocs/dotfiles", home: home, from: .peel)#expect(cased.first?.path(percentEncoded: false).contains("mobile documents") != true, "expand hands back a spelling the guard cannot read")- let throughLink = PathPattern.expand(".config/gcloud/logs", home: home, limited: false)+ let throughLink = PathPattern.expand(".config/gcloud/logs", home: home, from: .peel)#expect(throughLink.isEmpty, "expand walked through a symbolic link out of the home folder")}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/CaskEvidenceTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/CaskEvidenceTests.swiftindex 44af0699..25aeafef 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/CaskEvidenceTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/CaskEvidenceTests.swift@@ -142,6 +142,56 @@ struct CaskEvidenceTests {#expect(CaskEvidence.expand("relative/path", home: home).isEmpty)}+ /// Braces, `**/` without hidden folders or links, and no path with `.`, `..` or another account's `~`.+ @Test func readsACasksPathAsHomebrewDoes() throws {+ let directory = try TemporaryDirectory()+ let home = directory.url.appending(path: "home", directoryHint: .isDirectory)+ let icons = "home/.local/share/icons/hicolor"+ try directory.directory("home/Library/Application Support/Adobe/CEP/extensions")+ try directory.file("\(icons)/application-x-wine-top.png")+ try directory.file("\(icons)/48x48/mimetypes/application-x-wine-extension.png")+ try directory.file("\(icons)/.hidden/application-x-wine-hidden.png")+ try directory.file("\(icons)/size [1]/application-x-wine-named.png")+ try directory.file("elsewhere/application-x-wine-linked.png")+ try FileManager.default.createSymbolicLink(+ at: directory.url.appending(path: "\(icons)/linked"), withDestinationURL: directory.url.appending(path: "elsewhere")+ )+ try directory.directory("homeother/Library")+ let root = PathPattern.comparablePath(of: home) + "/"+ let found = { (pattern: String) in+ Set(CaskEvidence.expand(pattern, home: home).map {+ String($0.path(percentEncoded: false).dropFirst(root.count))+ })+ }++ #expect(found("~/Library/Application Support/Adobe{/CEP{/extensions,},}") == [+ "Library/Application Support/Adobe", "Library/Application Support/Adobe/CEP",+ "Library/Application Support/Adobe/CEP/extensions",+ ])+ #expect(found("~/.local/share/icons/hicolor/**/application-x-wine*") == [+ ".local/share/icons/hicolor/application-x-wine-top.png",+ ".local/share/icons/hicolor/48x48/mimetypes/application-x-wine-extension.png",+ ".local/share/icons/hicolor/size [1]/application-x-wine-named.png",+ ])+ #expect(found("~/Library/Application Support/../Application Support/Adobe").isEmpty)+ #expect(found("~/Library/./Application Support/Adobe").isEmpty)+ #expect(CaskEvidence.expand("~other/Library", home: home).isEmpty)+ }++ @Test func aCasksDoubleStarLooksNoDeeperOnceItHasReadGlobsShare() throws {+ let directory = try TemporaryDirectory()+ let wide = try directory.directory("Library/Logs/Example/a-wide")+ for index in 0..<16_384 {+ FileManager.default.createFile(atPath: wide.appending(path: "\(index).log").path(percentEncoded: false), contents: nil)+ }+ try directory.file("Library/Logs/Example/b-near/trace.log")+ try directory.file("Library/Logs/Example/c-deep/deeper/trace.log")++ let found = CaskEvidence.expand("~/Library/Logs/Example/**/trace.log", home: directory.url)++ #expect(found.map { $0.deletingLastPathComponent().lastPathComponent } == ["b-near"])+ }+/// A cask's patterns are data from elsewhere, so `glob` keeps them within its limits.@Test func aCasksPatternStaysWithinGlobsLimits() throws {let directory = try TemporaryDirectory()diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PathPatternTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PathPatternTests.swiftindex 5de4cdaf..13604289 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/PathPatternTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/PathPatternTests.swift@@ -7,9 +7,9 @@ struct PathPatternTests {let directory = try TemporaryDirectory()try directory.file("Library/Caches/tool/file", bytes: 16)- #expect(PathPattern.expand("Library/Caches/tool", home: directory.url, limited: false).count == 1)- #expect(PathPattern.expand("~/Library/Caches/tool", home: directory.url, limited: false).count == 1)- #expect(PathPattern.expand("Library/Caches/missing", home: directory.url, limited: false).isEmpty)+ #expect(PathPattern.expand("Library/Caches/tool", home: directory.url, from: .peel).count == 1)+ #expect(PathPattern.expand("~/Library/Caches/tool", home: directory.url, from: .peel).count == 1)+ #expect(PathPattern.expand("Library/Caches/missing", home: directory.url, from: .peel).isEmpty)}/// A pattern that ends in `/` matches folders only, and each comes back named as the entry itself, without the@@ -22,11 +22,11 @@ struct PathPatternTests {let link = directory.url.appending(path: ".virtualenvs/fast")try FileManager.default.createSymbolicLink(at: link, withDestinationURL: elsewhere)- let matches = PathPattern.expand(".virtualenvs/*/", home: directory.url, limited: false).map { $0.path(percentEncoded: false) }+ let matches = PathPattern.expand(".virtualenvs/*/", home: directory.url, from: .peel).map { $0.path(percentEncoded: false) }#expect(Set(matches) == Set([web, link].map(PathPattern.comparablePath(of:))))#expect(- PathPattern.expand(".virtualenvs/web/", home: directory.url, limited: false).map { $0.path(percentEncoded: false) } == [+ PathPattern.expand(".virtualenvs/web/", home: directory.url, from: .peel).map { $0.path(percentEncoded: false) } == [PathPattern.comparablePath(of: web)])@@ -38,19 +38,19 @@ struct PathPatternTests {try directory.directory("Library/Caches/Google/AndroidStudio2026.2")try directory.directory("Library/Caches/Google/Chrome")- let matches = PathPattern.expand("Library/Caches/Google/AndroidStudio*", home: directory.url, limited: false)+ let matches = PathPattern.expand("Library/Caches/Google/AndroidStudio*", home: directory.url, from: .peel)#expect(matches.map(\.lastPathComponent).sorted() == ["AndroidStudio2026.1", "AndroidStudio2026.2"])}- /// A limited pattern stops where `glob` does, keeping the paths found by then, and any other finds every match.- @Test func onlyALimitedPatternStopsAtGlobsLimit() throws {+ /// A cask's pattern stops where `glob` does, keeping the paths found by then, and Peel's own finds every match.+ @Test func onlyACasksPatternStopsAtGlobsLimit() throws {let directory = try TemporaryDirectory()for index in 0..<300 {try directory.directory("Library/Caches/tool/run-\(index)")}- let limited = PathPattern.expand("Library/Caches/tool/run-*", home: directory.url, limited: true)- let whole = PathPattern.expand("Library/Caches/tool/run-*", home: directory.url, limited: false)+ let limited = PathPattern.expand("Library/Caches/tool/run-*", home: directory.url, from: .cask)+ let whole = PathPattern.expand("Library/Caches/tool/run-*", home: directory.url, from: .peel)#expect(limited.count == 128)#expect(Set(limited).count == limited.count)@@ -62,6 +62,6 @@ struct PathPatternTests {let directory = try TemporaryDirectory()try directory.directory("Library/Caches/App [Beta]")- #expect(PathPattern.expand("Library/Caches/App [Beta]", home: directory.url, limited: false).map(\.lastPathComponent) == ["App [Beta]"])+ #expect(PathPattern.expand("Library/Caches/App [Beta]", home: directory.url, from: .peel).map(\.lastPathComponent) == ["App [Beta]"])}}