Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions PureMac.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
objects = {

/* Begin PBXBuildFile section */
003A90E388877ECFE1D77245 /* DevToolCachesTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = FE78E0476F240C0AA3061DC9 /* DevToolCachesTests.swift */; };
013EF7B96BF046D4DB38FBC5 /* Localizable.strings in Resources */ = {isa = PBXBuildFile; fileRef = 241E0895B09C71AB423B2F9E /* Localizable.strings */; };
0BB6BC2EAFB02407FBC6CDA6 /* ApplicationUpdater.swift in Sources */ = {isa = PBXBuildFile; fileRef = 59873E44B520DE069F80CCD6 /* ApplicationUpdater.swift */; };
0CC9A41781D1B1883279693E /* ProtectionView.swift in Sources */ = {isa = PBXBuildFile; fileRef = F270D47D1DD94D4577482B90 /* ProtectionView.swift */; };
Expand Down Expand Up @@ -53,6 +54,7 @@
826A750D2D7EC14C2AE306A3 /* Models.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3667D46D8E2004EB4D73835A /* Models.swift */; };
8947F0CE448791BD50EECF46 /* Conditions.swift in Sources */ = {isa = PBXBuildFile; fileRef = CB94E06E145558123BB5BFB3 /* Conditions.swift */; };
89D5B9A5B4F25EA729B5B08B /* DeviceBackupCoordinationTests.swift in Sources */ = {isa = PBXBuildFile; fileRef = 6BA1FC37E3821117365707CD /* DeviceBackupCoordinationTests.swift */; };
8B1437BFEBA81234563A186C /* DevToolCaches.swift in Sources */ = {isa = PBXBuildFile; fileRef = 1CF7D5C710181AD0A2C537FF /* DevToolCaches.swift */; };
8B541441926847072DC5B75B /* DashboardCharts.swift in Sources */ = {isa = PBXBuildFile; fileRef = 08C60E04A0CA3F227816DB63 /* DashboardCharts.swift */; };
91751CF033E1541BFD39B12C /* MenuBarMonitorView.swift in Sources */ = {isa = PBXBuildFile; fileRef = A27DB5A70FA829B6C3ED0AC3 /* MenuBarMonitorView.swift */; };
93743B036059418560D876E6 /* SettingsView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 3A8D39C3C250F26302EC45AB /* SettingsView.swift */; };
Expand Down Expand Up @@ -136,6 +138,7 @@
1AB003A7751F05727DBFD1A5 /* AppTheme.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = AppTheme.swift; sourceTree = "<group>"; };
1B8BE07AD70610A91E735E78 /* zh-Hans */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = "zh-Hans"; path = "zh-Hans.lproj/ServicesMenu.strings"; sourceTree = "<group>"; };
1C0D9A6F75D0B8ADDB32FC2A /* uk */ = {isa = PBXFileReference; lastKnownFileType = text.plist.strings; name = uk; path = uk.lproj/Localizable.strings; sourceTree = "<group>"; };
1CF7D5C710181AD0A2C537FF /* DevToolCaches.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DevToolCaches.swift; sourceTree = "<group>"; };
1D3AC5F17D7CA94FAB1E8D7A /* StringNormalization.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = StringNormalization.swift; sourceTree = "<group>"; };
1FC5F44AB9CA4CD2DE774973 /* XcodeBuildMCPDerivedDataSupport.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = XcodeBuildMCPDerivedDataSupport.swift; sourceTree = "<group>"; };
22B679C0120F1E3DDCB27FE2 /* CleaningEngineTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CleaningEngineTests.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -246,6 +249,7 @@
F77B9D7D5353CD42BD03ADBB /* ApplicationUpdaterTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ApplicationUpdaterTests.swift; sourceTree = "<group>"; };
F9DCBD97CC88D77AE8DB01A4 /* PermissionCoordinator.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = PermissionCoordinator.swift; sourceTree = "<group>"; };
FE52AA3D827BF3A574DC5822 /* ProcessResourceMonitor.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = ProcessResourceMonitor.swift; sourceTree = "<group>"; };
FE78E0476F240C0AA3061DC9 /* DevToolCachesTests.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = DevToolCachesTests.swift; sourceTree = "<group>"; };
/* End PBXFileReference section */

/* Begin PBXGroup section */
Expand All @@ -272,6 +276,7 @@
6116C5E9B68F439F6B2E42E5 /* CleanupReviewTests.swift */,
6BA1FC37E3821117365707CD /* DeviceBackupCoordinationTests.swift */,
4D0D0E67A3C5B3740B858AD8 /* DeviceBackupServiceTests.swift */,
FE78E0476F240C0AA3061DC9 /* DevToolCachesTests.swift */,
D379BB1C513985CF9AB783D5 /* DuplicateFinderTests.swift */,
155CE1B8CDCCCA6F9FD028C1 /* LocalizationFilesTests.swift */,
0621A14395DCA19EC2995842 /* MonitoringLifecycleTests.swift */,
Expand Down Expand Up @@ -439,6 +444,7 @@
isa = PBXGroup;
children = (
01B2C5F66B6D812572BD4F05 /* CLI.swift */,
1CF7D5C710181AD0A2C537FF /* DevToolCaches.swift */,
7953B398E47A4C603DE287F1 /* FileProtection.swift */,
8CE522B406791BCE905BC55B /* FileSize.swift */,
5785762276FB5E3209C6DE4D /* Logger.swift */,
Expand Down Expand Up @@ -629,6 +635,7 @@
ABDDD4F35102A39CC1A2C325 /* ConfettiView.swift in Sources */,
8B541441926847072DC5B75B /* DashboardCharts.swift in Sources */,
A2AE68CC75CB72D6B10CBDF5 /* DashboardView.swift in Sources */,
8B1437BFEBA81234563A186C /* DevToolCaches.swift in Sources */,
2C3AD1E4511D0F07C8C7C9D1 /* DeviceBackupService.swift in Sources */,
D0E6B0AFF83228F121B4DDD3 /* DuplicateFinder.swift in Sources */,
74175B10C464D245E99BA6DB /* DuplicateFinderView.swift in Sources */,
Expand Down Expand Up @@ -690,6 +697,7 @@
2BCDC53C5E3AB58442C8E4B0 /* CleaningEngineTests.swift in Sources */,
B69BD60D8AB7EBB9F80C9965 /* CleanupExclusionsTests.swift in Sources */,
6BCC5E3773DF2E9189F75A6B /* CleanupReviewTests.swift in Sources */,
003A90E388877ECFE1D77245 /* DevToolCachesTests.swift in Sources */,
89D5B9A5B4F25EA729B5B08B /* DeviceBackupCoordinationTests.swift in Sources */,
5FF5942BC279628276CF6543 /* DeviceBackupServiceTests.swift in Sources */,
4FAAA6E9887181C4C0AA9F87 /* DuplicateFinderTests.swift in Sources */,
Expand Down
205 changes: 205 additions & 0 deletions PureMac/Logic/Utilities/DevToolCaches.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,205 @@
import Foundation

/// The "Dev Tool Caches" category: one row per cache root of a developer tool.
///
/// `roots` is the single GUI list. It mirrors the "Dev Tools" targets in
/// `cli/Sources/puremac/Core/Catalog.swift` (paths and `selectedByDefault`);
/// the deviations are listed in `docs/DEV-TOOL-CACHES.md`. Project-level
/// artifacts (`node_modules`, Rust `target`) are deliberately not here.
///
/// Every root is an exact directory. `CleaningEngine` removes only a path that
/// equals one of these roots, never a descendant and never a parent.
enum DevToolCaches {
/// How a root is emptied. The tool's own CLI is preferred whenever the tool
/// manages its cache (lock handling, read-only files).
enum Removal: Equatable {
/// Plain `FileManager.removeItem` on the root.
case unlink
/// Plain removal, refused while a Gradle daemon or build is running.
case unlinkUnlessGradleRunning
/// `uv cache clean --cache-dir <root>` when `uv` exists, else plain removal.
case uvCacheClean
/// `go clean -cache` when `go` exists, else plain removal.
case goCleanCache
/// `go clean -modcache` when `go` exists. Never removed without `go`:
/// module files are read-only, so plain removal fails midway.
case goCleanModcache
}

struct Root: Equatable {
/// Stable identifier, also used by tests and docs.
let id: String
/// Localization key shown as the row name.
let nameKey: String
/// Path relative to the home directory.
let relativePath: String
var selectedByDefault = true
var removal: Removal = .unlink

func path(home: String) -> String {
(home as NSString).appendingPathComponent(relativePath)
}
}

// Order matches the scan order shown in the UI.
static let roots: [Root] = [
Root(id: "bun", nameKey: "Bun cache", relativePath: ".bun/install/cache"),
Root(id: "uv-xdg", nameKey: "uv cache", relativePath: ".cache/uv", removal: .uvCacheClean),
Root(id: "uv-library", nameKey: "uv cache", relativePath: "Library/Caches/uv", removal: .uvCacheClean),
Root(id: "pip-library", nameKey: "pip cache", relativePath: "Library/Caches/pip"),
Root(id: "pip-xdg", nameKey: "pip cache", relativePath: ".cache/pip"),
Root(id: "poetry-library", nameKey: "Poetry cache", relativePath: "Library/Caches/pypoetry"),
Root(id: "poetry-xdg", nameKey: "Poetry cache", relativePath: ".cache/pypoetry"),
Root(id: "cocoapods", nameKey: "CocoaPods cache", relativePath: "Library/Caches/CocoaPods"),
Root(id: "swiftpm", nameKey: "Swift Package Manager cache", relativePath: "Library/Caches/org.swift.swiftpm"),
Root(id: "gradle-caches", nameKey: "Gradle caches", relativePath: ".gradle/caches", removal: .unlinkUnlessGradleRunning),
Root(id: "gradle-wrapper", nameKey: "Gradle wrapper distributions", relativePath: ".gradle/wrapper/dists", removal: .unlinkUnlessGradleRunning),
// Cargo: only these four. ~/.cargo/bin and ~/.cargo/config.toml are never touched.
Root(id: "cargo-registry-cache", nameKey: "Cargo registry cache", relativePath: ".cargo/registry/cache"),
Root(id: "cargo-registry-index", nameKey: "Cargo registry index", relativePath: ".cargo/registry/index"),
Root(id: "cargo-git-db", nameKey: "Cargo git database", relativePath: ".cargo/git/db"),
Root(id: "cargo-git-checkouts", nameKey: "Cargo git checkouts", relativePath: ".cargo/git/checkouts"),
Root(id: "go-build", nameKey: "Go build cache", relativePath: "Library/Caches/go-build", removal: .goCleanCache),
// The CLI lists go/pkg/mod/cache (the download subset). `go clean -modcache`
// removes all of GOMODCACHE, so the GUI row and its size cover go/pkg/mod.
Root(id: "go-modcache", nameKey: "Go module cache", relativePath: "go/pkg/mod", removal: .goCleanModcache),
Root(id: "deno-library", nameKey: "Deno cache", relativePath: "Library/Caches/deno"),
Root(id: "deno-xdg", nameKey: "Deno cache", relativePath: ".cache/deno"),
// The CLI lists all of ~/.pub-cache. bin/ and global_packages/ hold
// `dart pub global activate` tools, so only downloaded packages are listed.
Root(id: "pub-hosted", nameKey: "Dart pub packages", relativePath: ".pub-cache/hosted"),
Root(id: "pub-git", nameKey: "Dart pub git packages", relativePath: ".pub-cache/git"),
Root(id: "playwright-library", nameKey: "Playwright browsers", relativePath: "Library/Caches/ms-playwright"),
Root(id: "playwright-xdg", nameKey: "Playwright browsers", relativePath: ".cache/ms-playwright"),
Root(id: "puppeteer", nameKey: "Puppeteer browsers", relativePath: ".cache/puppeteer"),
Root(id: "node-gyp-library", nameKey: "node-gyp headers", relativePath: "Library/Caches/node-gyp"),
Root(id: "node-gyp-xdg", nameKey: "node-gyp headers", relativePath: ".cache/node-gyp"),
Root(id: "electron", nameKey: "Electron download cache", relativePath: "Library/Caches/electron"),
Root(id: "electron-builder", nameKey: "Electron Builder cache", relativePath: "Library/Caches/electron-builder"),
// Opt-in: these can hold things that are not re-downloadable.
Root(id: "maven", nameKey: "Maven repository (may hold local installs)", relativePath: ".m2/repository", selectedByDefault: false),
Root(id: "nuget-packages", nameKey: "NuGet packages (may hold local packages)", relativePath: ".nuget/packages", selectedByDefault: false),
Root(id: "nuget-http", nameKey: "NuGet HTTP cache", relativePath: ".local/share/NuGet/http-cache", selectedByDefault: false),
]

/// Directories searched for `uv` and `go`. The GUI app does not inherit the
/// shell `PATH`.
static func toolSearchDirectories(home: String) -> [String] {
[
"/opt/homebrew/bin",
"/usr/local/bin",
"/usr/local/go/bin",
"\(home)/.local/bin",
"\(home)/.cargo/bin",
]
}

/// Process command-line fragments that identify a live Gradle daemon,
/// wrapper client or test worker.
static let gradleProcessMarkers = [
"GradleDaemon",
"GradleWrapperMain",
"GradleWorkerMain",
"org.gradle.launcher.GradleMain",
]

/// Absolute, standardized root paths for `home`.
static func absolutePaths(home: String) -> [String] {
roots.map { ($0.path(home: home) as NSString).standardizingPath }
}

static func contains(_ path: String, home: String) -> Bool {
let normalized = (path as NSString).standardizingPath
return absolutePaths(home: home).contains {
normalized == $0 || normalized.hasPrefix($0 + "/")
}
}

/// The root whose path equals `path` exactly (after standardizing), or nil.
/// Descendants, parents and relative paths do not match.
static func root(forPath path: String, home: String) -> Root? {
guard path.hasPrefix("/"), !path.utf8.contains(0) else { return nil }
let standardized = (path as NSString).standardizingPath
guard standardized == path else { return nil }
let normalizedHome = (home as NSString).standardizingPath
return roots.first { ($0.path(home: normalizedHome) as NSString).standardizingPath == standardized }
}

/// True when `path` or any directory between `home` and `path` is a symbolic
/// link. `lstat` semantics: the link itself is inspected, never followed.
static func hasSymlinkBelowHome(_ path: String, home: String) -> Bool {
let normalizedHome = (home as NSString).standardizingPath
var current = (path as NSString).standardizingPath
guard current.hasPrefix(normalizedHome + "/") else { return true }
while current.count > normalizedHome.count {
var info = stat()
if lstat(current, &info) == 0, (info.st_mode & S_IFMT) == S_IFLNK { return true }
current = (current as NSString).deletingLastPathComponent
}
return false
}

/// True when any entry of `commandLines` names a Gradle process.
static func containsGradleProcess(_ commandLines: [String]) -> Bool {
commandLines.contains { line in
gradleProcessMarkers.contains { line.contains($0) }
}
}
}

/// Everything about the host that the dev tool cache scan and clean read:
/// where tools live, whether Gradle runs, how long a tool may take. Injected
/// by tests so no real `uv`, `go` or process list is ever consulted.
struct DevToolCacheEnvironment: Sendable {
/// Directories searched for `uv` and `go`. Empty means "use the defaults for home".
var searchDirectories: [String]?
/// Command line of every running process, read-only. nil when the process
/// list cannot be read; callers then treat Gradle as running.
var processCommandLines: @Sendable () -> [String]?
/// Upper bound for a single `uv` or `go` invocation.
var commandTimeout: TimeInterval
/// Test seam: runs with the root path after the clean's first checks and
/// before the final symlink re-check that precedes a plain unlink. Lets a
/// test swap the root for a symlink inside the race window.
var beforeUnlinkRecheck: @Sendable (String) -> Void = { _ in }

static let live = DevToolCacheEnvironment(
searchDirectories: nil,
processCommandLines: { DevToolCacheEnvironment.livePSCommandLines() },
commandTimeout: 300
)

func isGradleRunning() -> Bool {
guard let lines = processCommandLines() else { return true }
return DevToolCaches.containsGradleProcess(lines)
}

func locate(_ tool: String, home: String, fileManager: FileManager = .default) -> String? {
let directories = searchDirectories ?? DevToolCaches.toolSearchDirectories(home: home)
for directory in directories {
let candidate = (directory as NSString).appendingPathComponent(tool)
if fileManager.isExecutableFile(atPath: candidate) { return candidate }
}
return nil
}

/// `ps -axo command=`: read-only.
private static func livePSCommandLines() -> [String]? {
let task = Process()
task.executableURL = URL(fileURLWithPath: "/bin/ps")
task.arguments = ["-axo", "command="]
let pipe = Pipe()
task.standardOutput = pipe
task.standardError = Pipe()
do {
try task.run()
} catch {
Logger.shared.log("Dev tool caches: could not list processes: \(error.localizedDescription)", level: .warning)
return nil
}
let data = pipe.fileHandleForReading.readDataToEndOfFile()
task.waitUntilExit()
guard task.terminationStatus == 0 else { return nil }
return String(decoding: data, as: UTF8.self).split(separator: "\n").map(String.init)
}
}
9 changes: 9 additions & 0 deletions PureMac/Models/Models.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ enum CleaningCategory: String, CaseIterable, Identifiable, Codable {
case xcodeJunk = "Xcode Junk"
case brewCache = "Brew Cache"
case nodeCache = "Node Cache"
case devToolCaches = "Dev Tool Caches"
case dockerCache = "Docker Cache"
case universalBinaries = "Universal Binaries"
case languageFiles = "Language Files"
Expand All @@ -33,6 +34,7 @@ enum CleaningCategory: String, CaseIterable, Identifiable, Codable {
case .xcodeJunk: return "hammer.fill"
case .brewCache: return "mug.fill"
case .nodeCache: return "leaf.fill"
case .devToolCaches: return "wrench.and.screwdriver.fill"
case .dockerCache: return "shippingbox.fill"
case .universalBinaries: return "cpu"
case .languageFiles: return "globe"
Expand All @@ -52,6 +54,7 @@ enum CleaningCategory: String, CaseIterable, Identifiable, Codable {
case .xcodeJunk: return "Derived data, archives, and simulator runtimes"
case .brewCache: return "Homebrew download cache"
case .nodeCache: return "npm, yarn, and pnpm download caches"
case .devToolCaches: return "Package, build, and download caches of developer tools"
case .dockerCache: return "Docker images, containers, and build cache"
case .universalBinaries: return "Unused CPU architecture slices in app binaries"
case .languageFiles: return "Unused app localizations"
Expand All @@ -71,6 +74,7 @@ enum CleaningCategory: String, CaseIterable, Identifiable, Codable {
case .xcodeJunk: return .cyan
case .brewCache: return .mint
case .nodeCache: return .pink
case .devToolCaches: return .green
case .dockerCache: return .indigo
case .universalBinaries: return .brown
case .languageFiles: return .gray
Expand Down Expand Up @@ -150,6 +154,11 @@ struct CleanableItem: Identifiable, Hashable {
let category: CleaningCategory
var isSelected: Bool
let lastModified: Date?
/// Rows that can hold data the user cannot re-download (Maven's `~/.m2`,
/// NuGet packages). They start unselected and only a per-row toggle
/// selects them: "Select all", the category checkbox and "Select visible"
/// skip them.
var selectOnlyByHand: Bool = false

var formattedSize: String {
ByteCountFormatter.string(fromByteCount: size, countStyle: .file)
Expand Down
Loading