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
Show the outdated runtimes command only when this Mac's simctl knows it
Țugui Dragoș2836b92bccf9
diff --git a/Packages/PeelCore/Sources/PeelCore/Space/Simctl.swift b/Packages/PeelCore/Sources/PeelCore/Space/Simctl.swiftnew file mode 100644index 00000000..5e6a4291--- /dev/null+++ b/Packages/PeelCore/Sources/PeelCore/Space/Simctl.swift@@ -0,0 +1,27 @@+import Foundation+import PeelPrivileged++/// The simulator tool `xcrun simctl` runs. Xcode's `usr/bin/simctl` is a script that hands every call to+/// CoreSimulator's own program, first running `xcodebuild -runFirstLaunch`, which installs packages, whenever+/// CoreSimulator is missing or older than the one it expects. So Peel asks that program and never runs the script.+enum Simctl {+ static let program = URL(+ filePath: "/Library/Developer/PrivateFrameworks/CoreSimulator.framework/Versions/A/Resources/bin/simctl"+ )++ /// What `simctl help runtime` prints, which it writes to standard error. Nil when `xcrun` would find no `simctl`+ /// in the active developer folder, or the program did not answer.+ static func runtimeHelp() async -> String? {+ guard let developer = await DeveloperFolder.active(),+ FileManager.default.isExecutableFile(+ atPath: developer.appending(path: "usr/bin/simctl").path(percentEncoded: false)+ )+ else { return nil }+ let answer = await Subprocess.run(+ program.path(percentEncoded: false), ["help", "runtime"], environment: [:], timeout: 5,+ errorsIntoOutput: true+ )+ guard case .success(let output) = answer, output.status == 0 else { return nil }+ return output.text+ }+}diff --git a/Packages/PeelCore/Sources/PeelCore/Space/SpaceReport.swift b/Packages/PeelCore/Sources/PeelCore/Space/SpaceReport.swiftindex 024dc42f..20c35ce7 100644--- a/Packages/PeelCore/Sources/PeelCore/Space/SpaceReport.swift+++ b/Packages/PeelCore/Sources/PeelCore/Space/SpaceReport.swift@@ -59,6 +59,34 @@ public struct SpaceReport: Sendable {}public enum SpaceInventory {+ struct Command: Sendable, ExpressibleByStringLiteral {+ enum Need: Sendable {+ case simctl+ case simctlRuntimeOption(String)+ }++ let line: String+ var need: Need?++ init(stringLiteral line: String) {+ self.line = line+ }++ init(_ line: String, needs need: Need) {+ self.line = line+ self.need = need+ }++ func isKnown(simctlRuntimeHelp help: String?) -> Bool {+ switch need {+ case nil: true+ case .simctl: help != nil+ case .simctlRuntimeOption(let option):+ help?.split { !($0.isLetter || $0.isNumber || $0 == "-") }.contains { $0 == option } ?? false+ }+ }+ }+struct Definition: Sendable {let id: Stringlet category: SpaceItem.Category@@ -75,7 +103,7 @@ public enum SpaceInventory {var heldBack: HoldBack?var leavesMacOSsOwn = falsevar onlyFilesIn: [String] = []- var commands: [String] = []+ var commands: [Command] = []/// Each of `paths` on this Mac: one that starts with `/` is under `root`, the rest are in `home`.func urls(home: URL, root: URL, userCache: URL?) -> [URL] {@@ -109,7 +137,10 @@ public enum SpaceInventory {category: .development,paths: ["Library/Developer/CoreSimulator/Devices", "/Library/Developer/CoreSimulator/Images"],handling: .readOnly,- commands: ["xcrun simctl runtime delete --outdated", "xcrun simctl delete unavailable"]+ commands: [+ Command("xcrun simctl runtime delete --outdated", needs: .simctlRuntimeOption("--outdated")),+ Command("xcrun simctl delete unavailable", needs: .simctl),+ ]),Definition(id: "android-sdk",@@ -417,7 +448,8 @@ public enum SpaceInventory {userCache: URL? = nil,minimumSize: Int64,exclusions: Exclusions = .none,- measure: @escaping FileSize.Measure+ measure: @escaping FileSize.Measure,+ simctlRuntimeHelp: @escaping @Sendable () async -> String? = Simctl.runtimeHelp) async -> SpaceReport {let containers = appContainers(in: home)let groups = groupContainers(in: home)@@ -433,11 +465,13 @@ public enum SpaceInventory {let kept = urls.filter { !exclusions.excludes($0) }return kept.isEmpty ? nil : (definition, kept)}+ let asksSimctl = wanted.contains { definition, _ in definition.commands.contains { $0.need != nil } }+ async let simctlHelp = asksSimctl ? simctlRuntimeHelp() : nil// Four areas are measured at a time. One after another, the wait would be the sum of them all, and a// folder that never answers would delay every area after it by its whole budget. Four leaves room for// the rest of the app.- var items: [SpaceItem] = []+ var measured: [(definition: Definition, urls: [URL], size: Int64?)] = []await withTaskGroup(of: (Definition, [URL], Int64?).self) { group invar pending = wanted.makeIterator()func addNext() -> Bool {@@ -449,22 +483,25 @@ public enum SpaceInventory {return true}for _ in 0..<4 where addNext() {}- while let (definition, urls, size) = await group.next() {+ while let area = await group.next() {_ = addNext()- guard size.map({ $0 >= minimumSize }) ?? true else { continue }- items.append(SpaceItem(- id: definition.id,- category: definition.category,- urls: urls,- size: size,- handling: definition.handling,- heldBack: definition.heldBack,- leavesMacOSsOwn: definition.leavesMacOSsOwn,- onlyFilesIn: definition.onlyFilesIn(home: home, root: root),- commands: definition.commands- ))+ measured.append(area)}}+ let help = await simctlHelp+ let items = measured.filter { $0.size.map { $0 >= minimumSize } ?? true }.map { definition, urls, size in+ SpaceItem(+ id: definition.id,+ category: definition.category,+ urls: urls,+ size: size,+ handling: definition.handling,+ heldBack: definition.heldBack,+ leavesMacOSsOwn: definition.leavesMacOSsOwn,+ onlyFilesIn: definition.onlyFilesIn(home: home, root: root),+ commands: definition.commands.filter { $0.isKnown(simctlRuntimeHelp: help) }.map(\.line)+ )+ }return SpaceReport(// An unknown size sorts first: an area that ran out of time is most likely one of the biggest.diff --git a/Packages/PeelCore/Sources/PeelCore/Support/DeveloperFolder.swift b/Packages/PeelCore/Sources/PeelCore/Support/DeveloperFolder.swiftnew file mode 100644index 00000000..c4507579--- /dev/null+++ b/Packages/PeelCore/Sources/PeelCore/Support/DeveloperFolder.swift@@ -0,0 +1,10 @@+import Foundation+import PeelPrivileged++enum DeveloperFolder {+ static func active() async -> URL? {+ let answer = await Subprocess.run("/usr/bin/xcode-select", ["-p"], environment: [:], timeout: 10)+ guard case .success(let output) = answer, output.status == 0 else { return nil }+ return URL(filePath: output.text.trimmingCharacters(in: .whitespacesAndNewlines), directoryHint: .isDirectory)+ }+}diff --git a/Packages/PeelCore/Sources/PeelCore/Terminal/GitConfig.swift b/Packages/PeelCore/Sources/PeelCore/Terminal/GitConfig.swiftindex 4ce3d824..0efd48eb 100644--- a/Packages/PeelCore/Sources/PeelCore/Terminal/GitConfig.swift+++ b/Packages/PeelCore/Sources/PeelCore/Terminal/GitConfig.swift@@ -8,12 +8,7 @@ public struct GitConfig: Sendable {let home: URLpublic static func find(home: URL = .homeDirectory) async -> GitConfig? {- let developer = await Subprocess.run("/usr/bin/xcode-select", ["-p"], environment: [:], timeout: 10)- let folder: URL? = if case .success(let output) = developer, output.status == 0 {- URL(filePath: output.text.trimmingCharacters(in: .whitespacesAndNewlines), directoryHint: .isDirectory)- } else {- nil- }+ let folder = await DeveloperFolder.active()let homebrew = Homebrew.executableURL?.deletingLastPathComponent().deletingLastPathComponent()return find(developerFolder: folder, homebrewPrefix: homebrew, home: home)}diff --git a/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swift b/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swiftindex ecfa56d9..48115043 100644--- a/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swift+++ b/Packages/PeelCore/Tests/PeelCoreTests/SpaceInventoryTests.swift@@ -384,11 +384,55 @@ struct SpaceInventoryTests {#expect(Set(SpaceInventory.definitions.map(\.id)).count == SpaceInventory.definitions.count)}- @Test func theSimulatorsAreaGivesApplesCommandsThatThisMacsSimctlKnows() throws {- let simulators = try #require(SpaceInventory.definitions.first { $0.id == "simulators" })- #expect(simulators.commands == ["xcrun simctl runtime delete --outdated", "xcrun simctl delete unavailable"])- #expect(try simctlHelp("runtime").contains("--outdated"))- #expect(try simctlHelp("delete").contains("unavailable"))+ @Test func showsASimulatorCommandOnlyWhenTheSimulatorToolKnowsIt() {+ let outdated = SpaceInventory.Command(+ "xcrun simctl runtime delete --outdated", needs: .simctlRuntimeOption("--outdated")+ )+ let unavailable = SpaceInventory.Command("xcrun simctl delete unavailable", needs: .simctl)+ let knows = "delete (<identifier>|--notUsedSinceDays <days>|--unusable|--outdated) [--dry-run] [--keep-asset]"+ let older = "delete (<identifier>|--notUsedSinceDays <days>|--unusable) [--dry-run] [--keep-asset]"++ #expect(outdated.isKnown(simctlRuntimeHelp: knows))+ #expect(!outdated.isKnown(simctlRuntimeHelp: older))+ #expect(!outdated.isKnown(simctlRuntimeHelp: "delete [--outdatedOnly]"))+ #expect(!outdated.isKnown(simctlRuntimeHelp: nil))+ #expect(unavailable.isKnown(simctlRuntimeHelp: older))+ #expect(!unavailable.isKnown(simctlRuntimeHelp: nil))+ #expect(SpaceInventory.Command("colima delete --data").isKnown(simctlRuntimeHelp: nil))+ }++ /// An older simulator tool, which this Mac can't produce on demand, stands in as the help it prints.+ @Test func theSimulatorsAreaGivesOnlyTheCommandsTheSimulatorToolKnows() async throws {+ let directory = try TemporaryDirectory()+ try directory.directory("Library/Developer/CoreSimulator/Devices")+ let older = "delete (<identifier>|--notUsedSinceDays <days>|--unusable) [--dry-run] [--keep-asset]"++ func commands(_ help: String?) async throws -> [String] {+ let report = await SpaceInventory.scan(+ home: directory.url, root: directory.url, minimumSize: 0, measure: FileSize.measure,+ simctlRuntimeHelp: { help }+ )+ return try #require(report.items.first { $0.id == "simulators" }).commands+ }++ #expect(try await commands(older) == ["xcrun simctl delete unavailable"])+ #expect(try await commands(nil).isEmpty)+ }++ @Test func readsTheRuntimeHelpOfTheSimulatorToolXcrunWouldRun() async {+ let developer = await DeveloperFolder.active()+ let xcrunFindsOne = developer.map {+ FileManager.default.isExecutableFile(atPath: $0.appending(path: "usr/bin/simctl").path(percentEncoded: false))+ } ?? false+ let isInstalled = FileManager.default.isExecutableFile(atPath: Simctl.program.path(percentEncoded: false))++ let help = await Simctl.runtimeHelp()++ if xcrunFindsOne && isInstalled {+ #expect(help?.contains("Usage: simctl runtime") == true)+ } else {+ #expect(help == nil)+ }}@Test func showsRustToolchainsAndAndroidNDKsForTheirToolsToRemove() async throws {@@ -410,7 +454,7 @@ struct SpaceInventoryTests {@Test func colimaIsToldToDeleteItsDataDiskToo() throws {let colima = try #require(SpaceInventory.definitions.first { $0.id == "colima" })- #expect(colima.commands == ["colima delete --data"])+ #expect(colima.commands.map(\.line) == ["colima delete --data"])}@Test func onlyAnAreaPeelLeavesAloneGivesCommands() {@@ -419,19 +463,6 @@ struct SpaceInventoryTests {}}- private func simctlHelp(_ topic: String) throws -> String {- let process = Process()- let output = Pipe()- process.executableURL = URL(filePath: "/usr/bin/xcrun")- process.arguments = ["simctl", "help", topic]- process.standardOutput = output- process.standardError = output- try process.run()- let data = output.fileHandleForReading.readDataToEndOfFile()- process.waitUntilExit()- return String(decoding: data, as: UTF8.self)- }-/// Space says it leaves a read only area to the app that made it, so nothing in one is what Developer/// selects for the person to remove.@Test func noReadOnlyAreaHoldsWhatDeveloperSelects() {