Free, open-source macOS cleaner. CleanMyMac alternative with zero telemetry. Native SwiftUI, scheduled auto-cleaning, Xcode/Homebrew/system cache cleanup. MIT licensed.
Swift cache-cleanercleanmymaccleanupdisk-cleanerdisk-spacehomebrewmac-utilitymacosmacos-appmacos-cleanermacosxnativeossosxprivacyswiftswiftuisystem-cleanerxcode-cleaner
xcode: list and delete simulator runtimes via simctl (#147)
omartio2f79a64dbf5a
diff --git a/PureMac/Logic/Utilities/SimulatorRuntimeSupport.swift b/PureMac/Logic/Utilities/SimulatorRuntimeSupport.swiftnew file mode 100644index 0000000..07017e4--- /dev/null+++ b/PureMac/Logic/Utilities/SimulatorRuntimeSupport.swift@@ -0,0 +1,166 @@+import Foundation++/// Parsing + selection policy for `xcrun simctl runtime`.+/// Kept free of Process I/O so unit tests can cover the scan/clean contract+/// without talking to CoreSimulator.+enum SimulatorRuntimeSupport {+ static let xcrunPath = "/usr/bin/xcrun"+ static let xcodeSelectPath = "/usr/bin/xcode-select"+ static let missingXcrunMessage =+ "Xcode command-line tools not found — install Xcode or run xcode-select --install"++ struct RuntimeInfo: Equatable {+ let identifier: String+ let displayName: String+ let sizeBytes: Int64+ let deletable: Bool+ let lastUsedAt: Date?+ }++ /// True when an active developer directory is configured. `/usr/bin/xcrun`+ /// is a base-OS shim and exists even without developer tools; invoking it+ /// in that state can show Apple's command-line-tools installer dialog.+ static func isXcrunAvailable(+ statusRunner: (_ executablePath: String, _ arguments: [String]) -> Int32 = runStatus+ ) -> Bool {+ statusRunner(xcodeSelectPath, ["-p"]) == 0+ }++ /// Parse stdout from `xcrun simctl runtime list -j`.+ /// Returns nil when the payload is empty or not the expected dictionary.+ static func parseRuntimeListJSON(_ jsonText: String) -> [RuntimeInfo]? {+ let trimmed = jsonText.trimmingCharacters(in: .whitespacesAndNewlines)+ guard !trimmed.isEmpty,+ let data = trimmed.data(using: .utf8),+ let json = try? JSONSerialization.jsonObject(with: data) as? [String: [String: Any]]+ else {+ return nil+ }++ let isoFormatter = ISO8601DateFormatter()+ isoFormatter.formatOptions = [.withInternetDateTime]++ var runtimes: [RuntimeInfo] = []+ for (key, info) in json {+ let identifier = (info["identifier"] as? String) ?? key+ let version = info["version"] as? String+ let build = info["build"] as? String+ let platform = platformName(from: info["platformIdentifier"] as? String)+ let sizeBytes = (info["sizeBytes"] as? NSNumber)?.int64Value ?? 0+ let deletable = info["deletable"] as? Bool ?? true+ let lastUsedAt: Date? = {+ guard let raw = info["lastUsedAt"] as? String else { return nil }+ return isoFormatter.date(from: raw)+ }()++ let displayName: String = {+ var parts: [String] = []+ if let platform { parts.append(platform) }+ if let version { parts.append(version) }+ let base = parts.isEmpty ? "Simulator Runtime" : parts.joined(separator: " ")+ if let build { return "\(base) (\(build))" }+ return base+ }()++ runtimes.append(RuntimeInfo(+ identifier: identifier,+ displayName: displayName,+ sizeBytes: sizeBytes,+ deletable: deletable,+ lastUsedAt: lastUsedAt+ ))+ }++ return runtimes.sorted {+ if $0.sizeBytes != $1.sizeBytes { return $0.sizeBytes > $1.sizeBytes }+ return $0.displayName.localizedStandardCompare($1.displayName) == .orderedAscending+ }+ }++ /// Build opt-in cleanable rows. Runtime downloads are recoverable only by+ /// downloading them again, so Smart Scan must never preselect them.+ static func makeCleanableItems(from runtimes: [RuntimeInfo]) -> [CleanableItem] {+ runtimes.compactMap { runtime in+ guard runtime.sizeBytes > 0 else { return nil }+ return CleanableItem(+ name: runtime.displayName,+ path: CleanableItem.simctlRuntimePathPrefix + runtime.identifier,+ size: runtime.sizeBytes,+ category: .xcodeJunk,+ isSelected: false,+ lastModified: runtime.lastUsedAt+ )+ }+ }++ static func platformName(from platformIdentifier: String?) -> String? {+ guard let platformIdentifier else { return nil }+ switch platformIdentifier {+ case "com.apple.platform.iphonesimulator": return "iOS"+ case "com.apple.platform.watchsimulator": return "watchOS"+ case "com.apple.platform.appletvsimulator": return "tvOS"+ case "com.apple.platform.xrsimulator": return "visionOS"+ default:+ if platformIdentifier.contains("iphone") { return "iOS" }+ if platformIdentifier.contains("watch") { return "watchOS" }+ if platformIdentifier.contains("tv") { return "tvOS" }+ if platformIdentifier.contains("xr") || platformIdentifier.contains("vision") {+ return "visionOS"+ }+ return nil+ }+ }++ /// Run `/usr/bin/xcrun` after an availability check. Returns status -1 and+ /// `missingXcrunMessage` when the binary is absent so callers can skip+ /// scan rows / surface a clean delete error.+ static func runXcrun(+ _ arguments: [String],+ availabilityCheck: () -> Bool = { isXcrunAvailable() }+ ) -> (status: Int32, stdout: String, stderr: String) {+ guard availabilityCheck() else {+ Logger.shared.log("No active developer directory reported by xcode-select", level: .warning)+ return (-1, "", missingXcrunMessage)+ }++ let task = Process()+ task.executableURL = URL(fileURLWithPath: xcrunPath)+ task.arguments = arguments+ let stdoutPipe = Pipe()+ let stderrPipe = Pipe()+ task.standardOutput = stdoutPipe+ task.standardError = stderrPipe+ do {+ try task.run()+ } catch {+ Logger.shared.log(+ "xcrun \(arguments.joined(separator: " ")) failed to launch: \(error.localizedDescription)",+ level: .warning+ )+ return (-1, "", error.localizedDescription)+ }+ let outData = stdoutPipe.fileHandleForReading.readDataToEndOfFile()+ let errData = stderrPipe.fileHandleForReading.readDataToEndOfFile()+ task.waitUntilExit()+ return (+ task.terminationStatus,+ String(data: outData, encoding: .utf8) ?? "",+ String(data: errData, encoding: .utf8) ?? ""+ )+ }++ static func runStatus(_ executablePath: String, _ arguments: [String]) -> Int32 {+ let task = Process()+ task.executableURL = URL(fileURLWithPath: executablePath)+ task.arguments = arguments+ task.standardOutput = Pipe()+ task.standardError = Pipe()+ do {+ try task.run()+ task.waitUntilExit()+ return task.terminationStatus+ } catch {+ return -1+ }+ }+}diff --git a/PureMac/Models/Models.swift b/PureMac/Models/Models.swiftindex d08b30e..6d186d5 100644--- a/PureMac/Models/Models.swift+++ b/PureMac/Models/Models.swift@@ -49,7 +49,7 @@ enum CleaningCategory: String, CaseIterable, Identifiable, Codable {case .trashBins: return "Files in your Trash"case .largeFiles: return "Files over 100 MB or older than 1 year"case .purgeableSpace: return "Reserved by macOS - freed automatically when space is needed"- case .xcodeJunk: return "Derived data, archives, and simulators"+ 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 .dockerCache: return "Docker images, containers, and build cache"@@ -138,6 +138,11 @@ enum ScanState: Equatable {// MARK: - Cleanable Itemstruct CleanableItem: Identifiable, Hashable {+ /// Path prefix for virtual items cleaned via `xcrun simctl runtime delete`+ /// rather than a filesystem unlink. The UUID after the colon is the+ /// runtime disk-image identifier from `simctl runtime list`.+ static let simctlRuntimePathPrefix = "simctl-runtime:"+let id = UUID()let name: Stringlet path: String@@ -150,6 +155,18 @@ struct CleanableItem: Identifiable, Hashable {ByteCountFormatter.string(fromByteCount: size, countStyle: .file)}+ /// True for action-only items (Docker prune, simctl runtimes) that have+ /// no real filesystem path to reveal in Finder.+ var isActionItem: Bool {+ path.isEmpty || path.hasPrefix(Self.simctlRuntimePathPrefix)+ }++ var simctlRuntimeIdentifier: String? {+ guard path.hasPrefix(Self.simctlRuntimePathPrefix) else { return nil }+ let id = String(path.dropFirst(Self.simctlRuntimePathPrefix.count))+ return id.isEmpty ? nil : id+ }+func hash(into hasher: inout Hasher) {hasher.combine(id)}diff --git a/PureMac/Services/CleaningEngine.swift b/PureMac/Services/CleaningEngine.swiftindex 8ab11c1..d240487 100644--- a/PureMac/Services/CleaningEngine.swift+++ b/PureMac/Services/CleaningEngine.swift@@ -91,6 +91,22 @@ actor CleaningEngine {continue}+ if let runtimeID = item.simctlRuntimeIdentifier {+ // Simulator runtimes live in CoreSimulator's secure storage;+ // deleting the mount path by hand leaves orphaned disk images.+ // Always go through `xcrun simctl runtime delete`.+ let deleteOutcome = await deleteSimulatorRuntime(identifier: runtimeID, reportedSize: item.size)+ result.freedSpace += deleteOutcome.freed+ if deleteOutcome.cleaned {+ result.itemsCleaned += 1+ result.cleanedPaths.insert(item.path)+ }+ if let error = deleteOutcome.error {+ result.errors.append(error)+ }+ continue+ }+do {let itemURL = URL(fileURLWithPath: item.path)guard fileManager.fileExists(atPath: item.path) else { continue }@@ -352,6 +368,36 @@ actor CleaningEngine {return (0, nil)}+ // MARK: - Simulator Runtimes++ /// Deletes one simulator runtime disk image via+ /// `xcrun simctl runtime delete <identifier>`. Uses the scan-time size as+ /// the freed estimate — simctl does not print reclaimable bytes.+ /// When `xcrun` is missing, returns a clear error and does not attempt+ /// a Process launch (avoids a cryptic "No such file" failure).+ func deleteSimulatorRuntime(identifier: String, reportedSize: Int64) async -> (freed: Int64, cleaned: Bool, error: String?) {+ guard SimulatorRuntimeSupport.isXcrunAvailable() else {+ return (0, false, SimulatorRuntimeSupport.missingXcrunMessage)+ }++ let result = SimulatorRuntimeSupport.runXcrun(["simctl", "runtime", "delete", identifier])+ guard result.status == 0 else {+ let detail = result.stderr.isEmpty ? result.stdout : result.stderr+ if detail == SimulatorRuntimeSupport.missingXcrunMessage {+ return (0, false, SimulatorRuntimeSupport.missingXcrunMessage)+ }+ if detail.localizedCaseInsensitiveContains("CoreSimulator")+ || detail.localizedCaseInsensitiveContains("simdiskimaged") {+ return (0, false, "Simulator services unavailable — open Xcode once, then try again")+ }+ Logger.shared.log("simctl runtime delete \(identifier) exited \(result.status): \(detail)", level: .error)+ return (0, false, "Couldn't delete simulator runtime \(identifier)")+ }++ Logger.shared.log("Deleted simulator runtime \(identifier) (~\(reportedSize) bytes)", level: .info)+ return (reportedSize, true, nil)+ }+/// Parse Docker's compact size format ("1.23GB", "456MB", "789kB", "0B").private func parseDockerBytes(_ s: String) -> Int64? {let trimmed = s.trimmingCharacters(in: .whitespaces)diff --git a/PureMac/Services/ScanEngine.swift b/PureMac/Services/ScanEngine.swiftindex 87a2684..9d4d815 100644--- a/PureMac/Services/ScanEngine.swift+++ b/PureMac/Services/ScanEngine.swift@@ -473,10 +473,51 @@ actor ScanEngine {}}+ // Downloaded simulator runtimes (often multi-GB each). Listed via+ // `xcrun simctl runtime list -j` and deleted via+ // `xcrun simctl runtime delete <id>` — not a plain filesystem unlink,+ // so paths use the simctl-runtime: prefix (see CleaningEngine).+ // Runtime downloads are always opt-in because restoring one requires+ // downloading multiple gigabytes again.+ items.append(contentsOf: scanSimulatorRuntimes())+let totalSize = items.reduce(0) { $0 + $1.size }return CategoryResult(category: .xcodeJunk, items: items, totalSize: totalSize)}+ /// Enumerate installed simulator runtime disk images via simctl.+ /// When `xcrun` is missing (no Xcode / CLT), returns an empty list —+ /// Xcode Junk still surfaces DerivedData and the rest of the filesystem+ /// targets; runtime rows are simply omitted.+ private func scanSimulatorRuntimes() -> [CleanableItem] {+ guard SimulatorRuntimeSupport.isXcrunAvailable() else {+ Logger.shared.log(SimulatorRuntimeSupport.missingXcrunMessage, level: .info)+ return []+ }+ guard let runtimes = listSimulatorRuntimes() else { return [] }+ let items = SimulatorRuntimeSupport.makeCleanableItems(from: runtimes)+ for item in items {+ report(item.name)+ }+ return items+ }++ /// Parse `xcrun simctl runtime list -j` into per-image rows.+ private func listSimulatorRuntimes() -> [SimulatorRuntimeSupport.RuntimeInfo]? {+ let result = SimulatorRuntimeSupport.runXcrun(["simctl", "runtime", "list", "-j"])+ guard result.status == 0, !result.stdout.isEmpty else {+ if !result.stderr.isEmpty {+ Logger.shared.log("simctl runtime list failed: \(result.stderr)", level: .warning)+ }+ return nil+ }+ guard let runtimes = SimulatorRuntimeSupport.parseRuntimeListJSON(result.stdout) else {+ Logger.shared.log("simctl runtime list: could not parse JSON", level: .warning)+ return nil+ }+ return runtimes+ }+private func scanBrewCache() -> CategoryResult {var items: [CleanableItem] = []diff --git a/PureMac/ViewModels/AppState.swift b/PureMac/ViewModels/AppState.swiftindex 4f6cf76..435e741 100644--- a/PureMac/ViewModels/AppState.swift+++ b/PureMac/ViewModels/AppState.swift@@ -997,7 +997,9 @@ final class AppState: ObservableObject {Logger.shared.log("Skipped \(result.skippedProtected) macOS-protected item(s): \(protectedList)", level: .info)}return items.filter {- !result.cleanedPaths.contains($0.path) && !result.protectedPaths.contains($0.path)+ !$0.isActionItem &&+ !result.cleanedPaths.contains($0.path) &&+ !result.protectedPaths.contains($0.path)}}diff --git a/PureMac/Views/CategoryDetailView.swift b/PureMac/Views/CategoryDetailView.swiftindex 1c7f824..2b5d9c3 100644--- a/PureMac/Views/CategoryDetailView.swift+++ b/PureMac/Views/CategoryDetailView.swift@@ -263,12 +263,17 @@ private struct FileRowView: View {.lineLimit(1).truncationMode(.middle)- if !item.path.isEmpty {+ if !item.isActionItem {Text(item.path).font(.caption).foregroundStyle(.tertiary).lineLimit(1).truncationMode(.middle)+ } else if item.simctlRuntimeIdentifier != nil {+ Text(String(localized: "Simulator runtime"))+ .font(.caption)+ .foregroundStyle(.tertiary)+ .lineLimit(1)}}@@ -276,7 +281,7 @@ private struct FileRowView: View {// Hover-revealed Finder shortcut; stays in the layout so the// trailing size never shifts sideways.- if !item.path.isEmpty {+ if !item.isActionItem {Button {NSWorkspace.shared.selectFile(item.path, inFileViewerRootedAtPath: "")} label: {@@ -319,7 +324,7 @@ private struct FileRowView: View {.animation(reduceMotion ? nil : .easeOut(duration: 0.15), value: isSelected).onHover { hovering = $0 }.contextMenu {- if !item.path.isEmpty {+ if !item.isActionItem {Button("Reveal in Finder") {NSWorkspace.shared.selectFile(item.path, inFileViewerRootedAtPath: "")}@@ -328,6 +333,9 @@ private struct FileRowView: View {}private var fileIcon: String {+ if item.simctlRuntimeIdentifier != nil {+ return "iphone"+ }let ext = (item.name as NSString).pathExtension.lowercased()switch ext {case "log", "txt": return "doc.text"diff --git a/PureMac/ar.lproj/Localizable.strings b/PureMac/ar.lproj/Localizable.stringsindex 56a9762..e3ed9a6 100644--- a/PureMac/ar.lproj/Localizable.strings+++ b/PureMac/ar.lproj/Localizable.strings@@ -456,3 +456,6 @@"Twelve-layer storage inspection model" = "Twelve-layer storage inspection model";"Xcode and package tools" = "Xcode and package tools";"Your Mac is in good shape." = "Your Mac is in good shape.";++/* Simulator runtimes */+"Simulator runtime" = "وقت تشغيل المحاكي";diff --git a/PureMac/en.lproj/Localizable.strings b/PureMac/en.lproj/Localizable.stringsindex ed03bda..dd8057d 100644--- a/PureMac/en.lproj/Localizable.strings+++ b/PureMac/en.lproj/Localizable.strings@@ -456,3 +456,6 @@"Twelve-layer storage inspection model" = "Twelve-layer storage inspection model";"Xcode and package tools" = "Xcode and package tools";"Your Mac is in good shape." = "Your Mac is in good shape.";++/* Simulator runtimes */+"Simulator runtime" = "Simulator runtime";diff --git a/PureMac/es.lproj/Localizable.strings b/PureMac/es.lproj/Localizable.stringsindex aa5df28..c51e48b 100644--- a/PureMac/es.lproj/Localizable.strings+++ b/PureMac/es.lproj/Localizable.strings@@ -456,3 +456,6 @@"Twelve-layer storage inspection model" = "Twelve-layer storage inspection model";"Xcode and package tools" = "Xcode and package tools";"Your Mac is in good shape." = "Your Mac is in good shape.";++/* Simulator runtimes */+"Simulator runtime" = "Runtime del simulador";diff --git a/PureMac/ja.lproj/Localizable.strings b/PureMac/ja.lproj/Localizable.stringsindex 34e2f46..c664460 100644--- a/PureMac/ja.lproj/Localizable.strings+++ b/PureMac/ja.lproj/Localizable.strings@@ -456,3 +456,6 @@"Twelve-layer storage inspection model" = "Twelve-layer storage inspection model";"Xcode and package tools" = "Xcode and package tools";"Your Mac is in good shape." = "Your Mac is in good shape.";++/* Simulator runtimes */+"Simulator runtime" = "シミュレータランタイム";diff --git a/PureMac/pl.lproj/Localizable.strings b/PureMac/pl.lproj/Localizable.stringsindex 52cb89a..d7f1a20 100644--- a/PureMac/pl.lproj/Localizable.strings+++ b/PureMac/pl.lproj/Localizable.strings@@ -456,3 +456,6 @@"Twelve-layer storage inspection model" = "Twelve-layer storage inspection model";"Xcode and package tools" = "Xcode and package tools";"Your Mac is in good shape." = "Your Mac is in good shape.";++/* Simulator runtimes */+"Simulator runtime" = "Środowisko uruchomieniowe symulatora";diff --git a/PureMac/pt-BR.lproj/Localizable.strings b/PureMac/pt-BR.lproj/Localizable.stringsindex 4e3e7f8..3eaf559 100644--- a/PureMac/pt-BR.lproj/Localizable.strings+++ b/PureMac/pt-BR.lproj/Localizable.strings@@ -456,3 +456,6 @@"Twelve-layer storage inspection model" = "Modelo de inspeção de armazenamento em doze camadas";"Xcode and package tools" = "Xcode e gerenciadores";"Your Mac is in good shape." = "Seu Mac está em boa forma.";++/* Simulator runtimes */+"Simulator runtime" = "Runtime do simulador";diff --git a/PureMac/ru.lproj/Localizable.strings b/PureMac/ru.lproj/Localizable.stringsindex f522070..79361cb 100644--- a/PureMac/ru.lproj/Localizable.strings+++ b/PureMac/ru.lproj/Localizable.strings@@ -456,3 +456,6 @@"Twelve-layer storage inspection model" = "Twelve-layer storage inspection model";"Xcode and package tools" = "Xcode and package tools";"Your Mac is in good shape." = "Your Mac is in good shape.";++/* Simulator runtimes */+"Simulator runtime" = "Среда выполнения симулятора";diff --git a/PureMac/uk.lproj/Localizable.strings b/PureMac/uk.lproj/Localizable.stringsindex 6602b35..4f68940 100644--- a/PureMac/uk.lproj/Localizable.strings+++ b/PureMac/uk.lproj/Localizable.strings@@ -456,3 +456,6 @@"Twelve-layer storage inspection model" = "Twelve-layer storage inspection model";"Xcode and package tools" = "Xcode and package tools";"Your Mac is in good shape." = "Your Mac is in good shape.";++/* Simulator runtimes */+"Simulator runtime" = "Середовище виконання симулятора";diff --git a/PureMac/zh-Hans.lproj/Localizable.strings b/PureMac/zh-Hans.lproj/Localizable.stringsindex 98de252..77fdd7e 100644--- a/PureMac/zh-Hans.lproj/Localizable.strings+++ b/PureMac/zh-Hans.lproj/Localizable.strings@@ -456,3 +456,6 @@"Twelve-layer storage inspection model" = "Twelve-layer storage inspection model";"Xcode and package tools" = "Xcode and package tools";"Your Mac is in good shape." = "Your Mac is in good shape.";++/* Simulator runtimes */+"Simulator runtime" = "模拟器运行时";diff --git a/PureMac/zh-Hant.lproj/Localizable.strings b/PureMac/zh-Hant.lproj/Localizable.stringsindex 7c68a04..4d13fa5 100644--- a/PureMac/zh-Hant.lproj/Localizable.strings+++ b/PureMac/zh-Hant.lproj/Localizable.strings@@ -456,3 +456,6 @@"Twelve-layer storage inspection model" = "Twelve-layer storage inspection model";"Xcode and package tools" = "Xcode and package tools";"Your Mac is in good shape." = "Your Mac is in good shape.";++/* Simulator runtimes */+"Simulator runtime" = "模擬器執行環境";diff --git a/PureMacTests/SimulatorRuntimeSupportTests.swift b/PureMacTests/SimulatorRuntimeSupportTests.swiftnew file mode 100644index 0000000..10a012b--- /dev/null+++ b/PureMacTests/SimulatorRuntimeSupportTests.swift@@ -0,0 +1,202 @@+import XCTest+@testable import PureMac++final class SimulatorRuntimeSupportTests: XCTestCase {++ // MARK: - JSON list parsing++ func testParseRuntimeListJSONExtractsFieldsAndSortsBySizeDescending() throws {+ let json = """+ {+ "small-id": {+ "identifier": "11111111-1111-1111-1111-111111111111",+ "version": "18.5",+ "build": "22F77",+ "platformIdentifier": "com.apple.platform.iphonesimulator",+ "sizeBytes": 1000,+ "deletable": true,+ "lastUsedAt": "2026-08-05T18:46:32Z"+ },+ "large-id": {+ "identifier": "22222222-2222-2222-2222-222222222222",+ "version": "26.5",+ "build": "23F77",+ "platformIdentifier": "com.apple.platform.iphonesimulator",+ "sizeBytes": 9000,+ "deletable": false+ }+ }+ """++ let runtimes = try XCTUnwrap(SimulatorRuntimeSupport.parseRuntimeListJSON(json))+ XCTAssertEqual(runtimes.count, 2)+ XCTAssertEqual(runtimes[0].identifier, "22222222-2222-2222-2222-222222222222")+ XCTAssertEqual(runtimes[0].displayName, "iOS 26.5 (23F77)")+ XCTAssertEqual(runtimes[0].sizeBytes, 9000)+ XCTAssertFalse(runtimes[0].deletable)+ XCTAssertNil(runtimes[0].lastUsedAt)++ XCTAssertEqual(runtimes[1].identifier, "11111111-1111-1111-1111-111111111111")+ XCTAssertEqual(runtimes[1].displayName, "iOS 18.5 (22F77)")+ XCTAssertEqual(runtimes[1].sizeBytes, 1000)+ XCTAssertTrue(runtimes[1].deletable)+ XCTAssertNotNil(runtimes[1].lastUsedAt)+ }++ func testParseRuntimeListJSONReturnsNilForEmptyOrInvalidPayload() {+ XCTAssertNil(SimulatorRuntimeSupport.parseRuntimeListJSON(""))+ XCTAssertNil(SimulatorRuntimeSupport.parseRuntimeListJSON(" "))+ XCTAssertNil(SimulatorRuntimeSupport.parseRuntimeListJSON("not-json"))+ XCTAssertNil(SimulatorRuntimeSupport.parseRuntimeListJSON("[]"))+ XCTAssertNil(SimulatorRuntimeSupport.parseRuntimeListJSON("\"string\""))+ }++ func testParseRuntimeListJSONFallsBackToDictionaryKeyAsIdentifier() throws {+ let json = """+ {+ "ABCDEF01-2345-6789-ABCD-EF0123456789": {+ "version": "2.0",+ "build": "22N318",+ "platformIdentifier": "com.apple.platform.xrsimulator",+ "sizeBytes": 50+ }+ }+ """+ let runtimes = try XCTUnwrap(SimulatorRuntimeSupport.parseRuntimeListJSON(json))+ XCTAssertEqual(runtimes.count, 1)+ XCTAssertEqual(runtimes[0].identifier, "ABCDEF01-2345-6789-ABCD-EF0123456789")+ XCTAssertEqual(runtimes[0].displayName, "visionOS 2.0 (22N318)")+ XCTAssertTrue(runtimes[0].deletable) // default when key absent+ }++ func testPlatformNameMapping() {+ XCTAssertEqual(+ SimulatorRuntimeSupport.platformName(from: "com.apple.platform.iphonesimulator"),+ "iOS"+ )+ XCTAssertEqual(+ SimulatorRuntimeSupport.platformName(from: "com.apple.platform.watchsimulator"),+ "watchOS"+ )+ XCTAssertEqual(+ SimulatorRuntimeSupport.platformName(from: "com.apple.platform.appletvsimulator"),+ "tvOS"+ )+ XCTAssertEqual(+ SimulatorRuntimeSupport.platformName(from: "com.apple.platform.xrsimulator"),+ "visionOS"+ )+ XCTAssertNil(SimulatorRuntimeSupport.platformName(from: nil))+ XCTAssertNil(SimulatorRuntimeSupport.platformName(from: "com.apple.platform.unknown"))+ }++ // MARK: - Selection policy (Smart Scan)++ func testMakeCleanableItemsNeverAutoSelectsRuntimeDownloads() {+ let runtimes = [+ SimulatorRuntimeSupport.RuntimeInfo(+ identifier: "deletable",+ displayName: "iOS 17.0 (21A)",+ sizeBytes: 100,+ deletable: true,+ lastUsedAt: nil+ ),+ SimulatorRuntimeSupport.RuntimeInfo(+ identifier: "locked",+ displayName: "iOS 16.0 (20A)",+ sizeBytes: 200,+ deletable: false,+ lastUsedAt: nil+ ),+ SimulatorRuntimeSupport.RuntimeInfo(+ identifier: "zero",+ displayName: "iOS 0",+ sizeBytes: 0,+ deletable: true,+ lastUsedAt: nil+ )+ ]++ let items = SimulatorRuntimeSupport.makeCleanableItems(from: runtimes)++ XCTAssertEqual(items.count, 2) // zero-size dropped++ let byID = Dictionary(uniqueKeysWithValues: items.map {+ ($0.simctlRuntimeIdentifier ?? "", $0)+ })++ XCTAssertEqual(byID["deletable"]?.name, "iOS 17.0 (21A)")+ XCTAssertEqual(byID["deletable"]?.isSelected, false)+ XCTAssertEqual(byID["deletable"]?.category, .xcodeJunk)+ XCTAssertTrue(byID["deletable"]?.isActionItem == true)+ XCTAssertEqual(byID["locked"]?.isSelected, false)+ XCTAssertNil(byID["zero"])+ }++ // MARK: - CleanableItem path helpers++ func testSimctlRuntimePathHelpers() {+ let item = CleanableItem(+ name: "iOS 18.5",+ path: CleanableItem.simctlRuntimePathPrefix + "F666EEDE-1029-48D9-BCAB-CF0E12B1D632",+ size: 1,+ category: .xcodeJunk,+ isSelected: false,+ lastModified: nil+ )+ XCTAssertTrue(item.isActionItem)+ XCTAssertEqual(item.simctlRuntimeIdentifier, "F666EEDE-1029-48D9-BCAB-CF0E12B1D632")++ let fileItem = CleanableItem(+ name: "DerivedData",+ path: "/Users/test/Library/Developer/Xcode/DerivedData",+ size: 1,+ category: .xcodeJunk,+ isSelected: true,+ lastModified: nil+ )+ XCTAssertFalse(fileItem.isActionItem)+ XCTAssertNil(fileItem.simctlRuntimeIdentifier)++ let dockerPrune = CleanableItem(+ name: "Docker prune",+ path: "",+ size: 1,+ category: .dockerCache,+ isSelected: false,+ lastModified: nil+ )+ XCTAssertTrue(dockerPrune.isActionItem)+ XCTAssertNil(dockerPrune.simctlRuntimeIdentifier)+ }++ // MARK: - Missing developer tools++ func testIsXcrunAvailableUsesXcodeSelectStatus() {+ XCTAssertFalse(SimulatorRuntimeSupport.isXcrunAvailable { path, arguments in+ XCTAssertEqual(path, SimulatorRuntimeSupport.xcodeSelectPath)+ XCTAssertEqual(arguments, ["-p"])+ return 2+ })+ XCTAssertTrue(SimulatorRuntimeSupport.isXcrunAvailable { _, _ in 0 })+ }++ func testRunXcrunReturnsFriendlyErrorWhenDeveloperToolsMissing() {+ let result = SimulatorRuntimeSupport.runXcrun(+ ["simctl", "runtime", "list", "-j"],+ availabilityCheck: { false }+ )+ XCTAssertEqual(result.status, -1)+ XCTAssertTrue(result.stdout.isEmpty)+ XCTAssertEqual(result.stderr, SimulatorRuntimeSupport.missingXcrunMessage)+ }++ func testDeleteSimulatorRuntimeReportsMissingXcrun() async {+ let result = SimulatorRuntimeSupport.runXcrun(+ ["simctl", "runtime", "delete", "deadbeef"],+ availabilityCheck: { false }+ )+ XCTAssertEqual(result.status, -1)+ XCTAssertEqual(result.stderr, SimulatorRuntimeSupport.missingXcrunMessage)+ }+}diff --git a/README.md b/README.mdindex 4457d80..b2597a7 100644--- a/README.md+++ b/README.md@@ -126,7 +126,7 @@ Smart Scan runs every category in parallel. Each category is its own deliberate- **Mail Files** - downloaded mail attachments- **Trash Bins** - empties all bins, including external volumes- **Large & Old Files** - >100 MB or older than 1 year (never auto-selected)-- **Xcode Junk** - DerivedData, Archives, simulator caches+- **Xcode Junk** - DerivedData, Archives, simulator caches, and downloaded simulator runtimes (deleted via `simctl runtime delete`; never auto-selected)- **Brew Cache** - respects custom `HOMEBREW_CACHE`- **Node Cache** - npm, yarn classic, pnpm content-addressable store- **Docker Cache** - images, containers, build cachediff --git a/docs/README.ar.md b/docs/README.ar.mdindex 8c7abff..7686b3a 100644--- a/docs/README.ar.md+++ b/docs/README.ar.md@@ -89,7 +89,7 @@ open build/Build/Products/Release/PureMac.app- **سلة المهملات** — تفريغ كل سلال المهملات- **الملفات الكبيرة والقديمة** — ملفات يزيد حجمها عن 100 ميغابايت أو أقدم من سنة- **المساحة القابلة للإزالة** — اكتشاف المساحة القابلة للإزالة في APFS-- **ملفات Xcode غير المرغوبة** — DerivedData والأرشيفات وذاكرة التخزين المؤقت للمحاكيات+- **ملفات Xcode غير المرغوبة** — DerivedData والأرشيفات وذاكرة التخزين المؤقت للمحاكيات وأنظمة تشغيل المحاكي المحمّلة (تُحذف عبر `simctl runtime delete`؛ لا تُحدد تلقائيًا أبدًا)- **ذاكرة التخزين المؤقت لـ Brew** — ذاكرة تنزيلات Homebrew (مع دعم HOMEBREW_CACHE مخصص)- **التنظيف المجدوَل** — فحص تلقائي وفق فترات قابلة للتخصيصdiff --git a/docs/README.es.md b/docs/README.es.mdindex 1d58ec0..dd96bc3 100644--- a/docs/README.es.md+++ b/docs/README.es.md@@ -88,7 +88,7 @@ open build/Build/Products/Release/PureMac.app- **Papeleras** — vacía todas las papeleras- **Archivos grandes y antiguos** — archivos de más de 100 MB o con más de 1 año- **Espacio purgable** — detección de espacio purgable APFS-- **Basura de Xcode** — DerivedData, Archives, cachés de simuladores+- **Basura de Xcode** — DerivedData, Archives, cachés de simuladores y runtimes descargados (se eliminan vía `simctl runtime delete`; nunca se auto-seleccionan)- **Caché de Brew** — caché de descargas de Homebrew (detecta HOMEBREW_CACHE personalizado)- **Limpieza programada** — análisis automático en intervalos configurablesdiff --git a/docs/README.ja.md b/docs/README.ja.mdindex e3be115..cf8eff9 100644--- a/docs/README.ja.md+++ b/docs/README.ja.md@@ -88,7 +88,7 @@ open build/Build/Products/Release/PureMac.app- **ゴミ箱** — すべてのゴミ箱を空に- **大容量・古いファイル** — 100 MB を超える、または 1 年以上経過したファイル- **消去可能領域** — APFS の消去可能ディスク領域を検出-- **Xcode ジャンク** — DerivedData、Archives、シミュレータキャッシュ+- **Xcode ジャンク** — DerivedData、Archives、シミュレータキャッシュ、ダウンロード済み simulator runtimes(`simctl runtime delete` 経由で削除、自動選択されません)- **Brew キャッシュ** — Homebrew ダウンロードキャッシュ(カスタム HOMEBREW_CACHE も検出)- **スケジュールクリーニング** — 設定可能な間隔での自動スキャンdiff --git a/docs/README.zh-Hans.md b/docs/README.zh-Hans.mdindex 413363e..6d36406 100644--- a/docs/README.zh-Hans.md+++ b/docs/README.zh-Hans.md@@ -88,7 +88,7 @@ open build/Build/Products/Release/PureMac.app- **废纸篓** — 清空所有废纸篓- **大文件与旧文件** — 超过 100 MB 或超过 1 年的文件- **可清除空间** — 检测 APFS 可清除磁盘空间-- **Xcode 垃圾** — DerivedData、Archives、模拟器缓存+- **Xcode 垃圾** — DerivedData、Archives、模拟器缓存与已下载的 simulator runtimes(通过 `simctl runtime delete` 删除,不会自动勾选)- **Brew 缓存** — Homebrew 下载缓存(可识别自定义 HOMEBREW_CACHE)- **定时清理** — 按可配置的间隔自动扫描diff --git a/docs/README.zh-Hant.md b/docs/README.zh-Hant.mdindex 0a91ac7..ce6e2dc 100644--- a/docs/README.zh-Hant.md+++ b/docs/README.zh-Hant.md@@ -88,7 +88,7 @@ open build/Build/Products/Release/PureMac.app- **垃圾桶** — 清空所有垃圾桶- **大型與舊檔案** — 超過 100 MB 或超過 1 年的檔案- **可清除空間** — 偵測 APFS 可清除磁碟空間-- **Xcode 垃圾** — DerivedData、Archives、模擬器快取+- **Xcode 垃圾** — DerivedData、Archives、模擬器快取與下載的 simulator runtimes(透過 `simctl runtime delete` 刪除,不會自動勾選)- **Brew 快取** — Homebrew 下載快取(可辨識自訂的 HOMEBREW_CACHE)- **排程清理** — 以可設定的間隔自動掃描