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.

Find every folder of a developer tool, not the first 128

Țugui Dragoș895ad5a13842
diff --git a/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift b/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift
index 0dd35909..7e05e6c9 100644
--- a/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Developer/DeveloperCaches.swift
@@ -135,7 +135,6 @@ public enum DeveloperCaches {
let storeInside: String?
/// How far inside the folder its rows are: 0 lists it whole, 1 lists each folder in it, as Xcode keeps one per
/// system version, and 2 each folder two levels down, as Xcode keeps each archive in a folder for its day.
- /// Listed rather than globbed, since `glob` stops at 128 paths.
let rowsDepth: Int
/// The ending every row's name has, such as `.xcarchive`, or nil for any.
let rowEnding: String?
@@ -207,7 +206,7 @@ public enum DeveloperCaches {
case .userTemporary: userTemporary
}
guard let root else { return [] }
- var places = PathPattern.expand(path, home: root)
+ var places = PathPattern.expand(path, home: root, limited: false)
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.swift
index 68e42eff..969ae7be 100644
--- a/Packages/PeelCore/Sources/PeelCore/Homebrew/CaskEvidence.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Homebrew/CaskEvidence.swift
@@ -162,13 +162,16 @@ public struct CaskEvidence: Sendable, Hashable {
return byID.values.sorted { $0.id < $1.id }
}
+ /// Past this many folders, `holdsNothing` answers no rather than walk on.
+ private static let foldersLookedInto = 200
+
/// Homebrew's rule for `rmdir`: a real folder with nothing in it but folders and `.DS_Store`, all the way down.
static func holdsNothing(_ folder: URL) -> Bool {
var pending = [folder]
var visited = 0
while let next = pending.popLast() {
visited += 1
- guard visited <= PathPattern.maximumMatches, next.isRealFolder,
+ guard visited <= foldersLookedInto, next.isRealFolder,
let children = try? FileManager.default.contentsOfDirectory(at: next, includingPropertiesForKeys: nil)
else { return false }
pending += children.filter { $0.lastPathComponent != ".DS_Store" }
@@ -176,10 +179,11 @@ public struct CaskEvidence: Sendable, Hashable {
return true
}
- /// A cask only ever names absolute paths; anything else is ignored.
+ /// 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.
static func expand(_ pattern: String, home: URL) -> [URL] {
guard pattern.hasPrefix("/") || pattern.hasPrefix("~") else { return [] }
- return PathPattern.expand(pattern, home: home)
+ return PathPattern.expand(pattern, home: home, limited: true)
}
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.swift
index c1f94bf7..dad9d745 100644
--- a/Packages/PeelCore/Sources/PeelCore/Support/PathPattern.swift
+++ b/Packages/PeelCore/Sources/PeelCore/Support/PathPattern.swift
@@ -5,8 +5,6 @@ internal import PeelPrivileged
/// Works with paths Peel is given: expands `~` and shell wildcards into the files that exist, and finds the
/// names and spellings one file answers to, so paths can be compared safely.
public enum PathPattern {
- static let maximumMatches = 200
-
/// A folder path with no trailing slash, so two URLs for the same folder compare equal.
public static func comparablePath(of url: URL) -> String {
var path = url.standardizedFileURL.path(percentEncoded: false)
@@ -91,9 +89,11 @@ public enum PathPattern {
|| ProtectedData.refuses(canonical(url).path(percentEncoded: false), home: home)
}
- /// The existing files `pattern` names, at most `maximum`, leaving out irreplaceable ones (`isIrreplaceable`).
- /// A pattern without a leading `/` or `~` is read relative to `home`.
- static func expand(_ pattern: String, home: URL, maximum: Int = maximumMatches) -> [URL] {
+ /// 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] {
let root = comparablePath(of: home)
var path = pattern
if path.hasPrefix("~") {
@@ -113,13 +113,10 @@ public enum PathPattern {
var results = glob_t()
defer { globfree(&results) }
- // GLOB_LIMIT keeps a pattern from walking the whole disk. It stops at `gl_matchc` paths (`man 3 glob`),
- // and on macOS 26 at 128 even when `gl_matchc` is higher. At the limit, `glob` returns GLOB_NOSPACE
- // with the paths found so far.
- results.gl_matchc = Int32(clamping: maximum)
- let code = glob(path, GLOB_NOSORT | GLOB_LIMIT | GLOB_NOESCAPE, nil, &results)
+ // 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)
guard code == 0 || code == GLOB_NOSPACE, results.gl_pathv != nil else { return [] }
- return (0..<Int(results.gl_pathc)).prefix(maximum).compactMap { index in
+ return (0..<Int(results.gl_pathc)).compactMap { index in
guard let pointer = results.gl_pathv[index] else { return nil }
let url = entry(named: String(cString: pointer))
return isIrreplaceable(url, home: root) ? nil : url
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/AttackPathProducerTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/AttackPathProducerTests.swift
index 3560deec..3301f920 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)
+ let cased = PathPattern.expand("Library/mobile documents/com~apple~CloudDocs/dotfiles", home: home, limited: false)
#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)
+ let throughLink = PathPattern.expand(".config/gcloud/logs", home: home, limited: false)
#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.swift
index aa9b070a..44af0699 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/CaskEvidenceTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/CaskEvidenceTests.swift
@@ -142,6 +142,16 @@ struct CaskEvidenceTests {
#expect(CaskEvidence.expand("relative/path", home: home).isEmpty)
}
+ /// A cask's patterns are data from elsewhere, so `glob` keeps them within its limits.
+ @Test func aCasksPatternStaysWithinGlobsLimits() throws {
+ let directory = try TemporaryDirectory()
+ for index in 0..<300 {
+ try directory.directory("Library/Logs/Example/run-\(index)")
+ }
+
+ #expect(CaskEvidence.expand("~/Library/Logs/Example/run-*", home: directory.url).count == 128)
+ }
+
@Test func marksPathsOutsideLibraryAsNotRecommended() async throws {
let directory = try TemporaryDirectory()
let home = directory.url
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swift
index 26a0e544..22a2bab0 100644
--- a/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swift
+++ b/Packages/PeelCore/Tests/PeelCoreTests/DeveloperCachesTests.swift
@@ -1442,4 +1442,97 @@ struct DeveloperCachesTests {
#expect(!offered.contains { $0 != path && path.hasPrefix($0 + "/") }, "\(path) sits inside another offered folder")
}
}
+
+ /// `glob` asked to limit itself stops at 128 paths on macOS, while Playwright leaves a folder in the temporary
+ /// folder for every run that ended early. Every pattern of the table finds all 200 of its matches here.
+ @Test func eachPatternFindsEveryMatch() throws {
+ let count = 200
+ for definition in DeveloperCaches.definitions {
+ for folder in definition.folders {
+ let names = (0..<count).compactMap { Self.name(matching: folder.path, number: $0) }
+ guard names.count == count else {
+ #expect(names.count < 128, "\(folder.path) names \(names.count) at most and was not checked")
+ continue
+ }
+ let directory = try TemporaryDirectory()
+ let root = directory.url.appending(path: "root", directoryHint: .isDirectory)
+ for name in names {
+ try directory.directory("root/\(name)")
+ }
+
+ let places = folder.places(
+ home: root, userCache: root, userTemporary: root, preference: { _ in nil },
+ settings: ToolSettings(home: root)
+ )
+
+ #expect(places.count == count, "\(folder.path) found \(places.count) of \(count)")
+ }
+ }
+ }
+
+ /// A path `pattern` matches, made distinct by `number`: its first `*` holds the number or, with no `*`, its `?`
+ /// and bracket classes spell it digit by digit. Nil for a plain path, or when the classes can't spell that many.
+ private static func name(matching pattern: String, number: Int) -> String? {
+ let pattern = pattern.hasSuffix("/") ? String(pattern.dropLast()) : pattern
+ guard pattern.contains(where: { "*?[".contains($0) }) else { return nil }
+ let placesTheNumber = pattern.contains("*")
+ let characters = Array(pattern)
+ var name = ""
+ var remaining = number
+ var numbered = false
+ // The classes are filled from the last one, so the digits read in order.
+ var spelled: [Int: Character] = [:]
+ if !placesTheNumber {
+ var index = characters.count - 1
+ while index >= 0 {
+ if characters[index] == "?" {
+ spelled[index] = Character(String(remaining % 16, radix: 16))
+ remaining /= 16
+ } else if characters[index] == "]", let open = characters[..<index].lastIndex(of: "[") {
+ let choices = Self.classMembers(String(characters[(open + 1)..<index]))
+ spelled[open] = choices[remaining % choices.count]
+ remaining /= choices.count
+ index = open
+ }
+ index -= 1
+ }
+ guard remaining == 0 else { return nil }
+ }
+ var index = 0
+ while index < characters.count {
+ let character = characters[index]
+ if character == "*" {
+ name += numbered ? "x" : "m\(number)"
+ numbered = true
+ } else if character == "?" {
+ name.append(spelled[index] ?? "a")
+ } else if character == "[", let close = characters[index...].firstIndex(of: "]") {
+ name.append(spelled[index] ?? Self.classMembers(String(characters[(index + 1)..<close]))[0])
+ index = close
+ } else {
+ name.append(character)
+ }
+ index += 1
+ }
+ return name
+ }
+
+ /// The characters a bracket class such as `0-9a-f` stands for.
+ private static func classMembers(_ members: String) -> [Character] {
+ let characters = Array(members)
+ var result: [Character] = []
+ var index = 0
+ while index < characters.count {
+ if index + 2 < characters.count, characters[index + 1] == "-",
+ let low = characters[index].unicodeScalars.first?.value,
+ let high = characters[index + 2].unicodeScalars.first?.value, low <= high {
+ result += (low...high).compactMap { Unicode.Scalar($0).map(Character.init) }
+ index += 3
+ } else {
+ result.append(characters[index])
+ index += 1
+ }
+ }
+ return result
+ }
}
diff --git a/Packages/PeelCore/Tests/PeelCoreTests/PathPatternTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/PathPatternTests.swift
index 2020ccd3..5de4cdaf 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).count == 1)
- #expect(PathPattern.expand("~/Library/Caches/tool", home: directory.url).count == 1)
- #expect(PathPattern.expand("Library/Caches/missing", home: directory.url).isEmpty)
+ #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)
}
/// 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).map { $0.path(percentEncoded: false) }
+ let matches = PathPattern.expand(".virtualenvs/*/", home: directory.url, limited: false).map { $0.path(percentEncoded: false) }
#expect(Set(matches) == Set([web, link].map(PathPattern.comparablePath(of:))))
#expect(
- PathPattern.expand(".virtualenvs/web/", home: directory.url).map { $0.path(percentEncoded: false) } == [
+ PathPattern.expand(".virtualenvs/web/", home: directory.url, limited: false).map { $0.path(percentEncoded: false) } == [
PathPattern.comparablePath(of: web)
]
)
@@ -38,31 +38,23 @@ 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)
+ let matches = PathPattern.expand("Library/Caches/Google/AndroidStudio*", home: directory.url, limited: false)
#expect(matches.map(\.lastPathComponent).sorted() == ["AndroidStudio2026.1", "AndroidStudio2026.2"])
}
- @Test func stopsAtTheMatchLimit() throws {
- let directory = try TemporaryDirectory()
- for index in 0..<5 {
- try directory.directory("Library/Caches/tool/run-\(index)")
- }
-
- #expect(PathPattern.expand("Library/Caches/tool/run-*", home: directory.url, maximum: 2).count == 2)
- }
-
- /// At its limit, `glob` returns `GLOB_NOSPACE` along with the paths found so far. Those paths are kept, so a
- /// folder with more entries than the limit still lists what was found.
- @Test func keepsWhatWasFoundWhenThereIsMoreThanTheLimit() throws {
+ /// A limited pattern stops where `glob` does, keeping the paths found by then, and any other finds every match.
+ @Test func onlyALimitedPatternStopsAtGlobsLimit() throws {
let directory = try TemporaryDirectory()
for index in 0..<300 {
try directory.directory("Library/Caches/tool/run-\(index)")
}
- let matches = PathPattern.expand("Library/Caches/tool/run-*", home: directory.url)
- #expect(!matches.isEmpty)
- #expect(matches.count <= PathPattern.maximumMatches)
- #expect(Set(matches).count == matches.count)
+ 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)
+
+ #expect(limited.count == 128)
+ #expect(Set(limited).count == limited.count)
+ #expect(whole.count == 300)
}
/// A bracket in a real name is not a character class: `App [Beta]` has to find itself.
@@ -70,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).map(\.lastPathComponent) == ["App [Beta]"])
+ #expect(PathPattern.expand("Library/Caches/App [Beta]", home: directory.url, limited: false).map(\.lastPathComponent) == ["App [Beta]"])
}
}