diff --git a/Xcodes/Backend/AppState+Runtimes.swift b/Xcodes/Backend/AppState+Runtimes.swift index d43ce543..f442acf1 100644 --- a/Xcodes/Backend/AppState+Runtimes.swift +++ b/Xcodes/Backend/AppState+Runtimes.swift @@ -22,7 +22,14 @@ extension AppState { let runtimes = try await store.updateDownloadableRuntimes() try Task.checkCancellation() - self.downloadableRuntimes = runtimes + let activeStates: [String: RuntimeInstallState] = Dictionary(self.downloadableRuntimes.compactMap { runtime in + self.runtimeTasks[runtime.identifier] == nil ? nil : (runtime.identifier, runtime.installState) + }, uniquingKeysWith: { existing, _ in existing }) + self.downloadableRuntimes = runtimes.map { runtime in + var runtime = runtime + runtime.installState = activeStates[runtime.identifier] ?? runtime.installState + return runtime + } } catch is CancellationError { } catch { Logger.appState.error("Error downloading runtimes: \(error.localizedDescription)") @@ -55,131 +62,184 @@ extension AppState { } } - func downloadRuntime(runtime: DownloadableRuntime) { - do { - let method = try RuntimeInstallPolicy().installMethod( - for: runtime, - selectedXcodeVersion: allXcodes.first(where: { $0.selected })?.version + private func installRuntime(_ runtime: DownloadableRuntime, for xcodeID: XcodeID?, taskID: UUID) async throws { + if runtime.contentType == .diskImage { + let archiveURL = try await downloadRuntimeArchive(runtime: runtime, taskID: taskID) + let xcode = try await xcodeForRuntime(runtime, preferredID: xcodeID) + let developerDirectory = xcode.selected ? nil : xcode.developerDirectory + try await runtimeArchiveInstallService(developerDirectory: developerDirectory).install( + runtime: runtime, + archiveURL: archiveURL, + stepChanged: { step in + await self.setRuntimeStep(step, runtime: runtime, taskID: taskID, postNotification: true) + } ) - - switch method { - case .archive: - downloadRuntimeViaArchive(runtime: runtime) - case let .xcodebuild(architecture): - downloadRuntimeViaXcodeBuild(runtime: runtime, architecture: architecture) + } else { + let preferredInstall = xcodeID.flatMap { installationTasks[$0] } + let xcode = try await xcodeForRuntime(runtime, preferredID: xcodeID) + let method = try RuntimeInstallPolicy().installMethod(for: runtime, selectedXcodeVersion: xcode.version) + guard case let .xcodebuild(architecture) = method else { + throw XcodesKitError("This simulator runtime format is unsupported.") + } + do { + try await installRuntimeWithXcodebuild( + runtime, architecture: architecture, + developerDirectory: xcode.selected ? nil : xcode.developerDirectory, taskID: taskID + ) + } catch let error as ProcessExecutionError { + // A parallel attempt may have used a different Xcode. Retry once with the + // requested Xcode if it was still installing when the download began. + try Task.checkCancellation() + guard let xcodeID, xcodeID != xcode.id, let preferredInstall else { throw error } + try await waitForXcodeInstall(preferredInstall, runtime: runtime) + guard let preferred = allXcodes.first(where: { $0.id == xcodeID }), + preferred.installState.installed, + (try? RuntimeInstallPolicy().installMethod(for: runtime, selectedXcodeVersion: preferred.version)) == method, + let directory = preferred.developerDirectory else { throw error } + try await installRuntimeWithXcodebuild( + runtime, architecture: architecture, developerDirectory: directory, taskID: taskID + ) } - } catch { - presentRuntimeInstallPolicyError(error) } } - private func presentRuntimeInstallPolicyError(_ error: Error) { - Logger.appState.error("Trying to download a runtime we can't download: \(error.localizedDescription)") - - if let error = error as? RuntimeInstallPolicyError { - switch error { - case .noSelectedXcode: - presentedAlert = .generic(title: localizeString("Alert.Install.Error.Title"), message: "No selected Xcode. Please make an Xcode active") - case .xcode16_1OrGreaterRequired: - presentedAlert = .generic(title: localizeString("Alert.Install.Error.Title"), message: localizeString("Alert.Install.Error.Need.Xcode16.1")) - case .xcode26OrGreaterRequired: - presentedAlert = .generic(title: localizeString("Alert.Install.Error.Title"), message: localizeString("Alert.Install.Error.Need.Xcode26")) + private func xcodeForRuntime(_ runtime: DownloadableRuntime, preferredID: XcodeID?) async throws -> Xcode { + try Task.checkCancellation() + let policy = RuntimeInstallPolicy() + func compatible(_ xcode: Xcode) -> Bool { + (try? policy.installMethod(for: runtime, selectedXcodeVersion: xcode.version)) != nil + } + func installedXcode() -> Xcode? { + let installed = allXcodes.filter { + $0.installState.installed && installationTasks[$0.id] == nil && compatible($0) } - } else { - presentedAlert = .generic(title: localizeString("Alert.Install.Error.Title"), message: error.legibleLocalizedDescription) + return installed.first { $0.id == preferredID } + ?? installed.first { xcode in + xcode.platformSDKBuilds.contains { runtime.sdkBuildUpdate?.contains($0) == true } + } + ?? installed.first(where: \.selected) + ?? installed.max { $0.version < $1.version } } - } - func downloadRuntimeViaXcodeBuild(runtime: DownloadableRuntime, architecture: String? = nil) { - runtimeTasks[runtime.identifier]?.cancel() - let runtimeTaskID = UUID() - runtimeTaskIDs[runtime.identifier] = runtimeTaskID - runtimeTasks[runtime.identifier] = Task { @MainActor [weak self] in - guard let self = self else { return } - defer { - if self.runtimeTaskIDs[runtime.identifier] == runtimeTaskID { - self.runtimeTasks[runtime.identifier] = nil - self.runtimeTaskIDs[runtime.identifier] = nil - } + let available = installedXcode() + if runtime.betaNumber != nil, let preferredID, let task = installationTasks[preferredID], + available?.id != preferredID, + available?.platformSDKBuilds.contains(where: { runtime.sdkBuildUpdate?.contains($0) == true }) != true { + // A toolchain that meets the platform minimum can still stall on a newer beta asset. + try await waitForXcodeInstall(task, runtime: runtime) + guard let xcode = installedXcode(), xcode.id == preferredID else { + throw XcodesKitError(localizeString("Xcode installation did not finish. Install Xcode and try this simulator runtime again.")) } - do { - try await RuntimeXcodebuildInstallService(download: Current.shell.downloadRuntime).downloadAndInstall( - runtime: runtime, - architecture: architecture - ) { progress in - Task { @MainActor [weak self] in - guard - let self, - self.runtimeTaskIDs[runtime.identifier] == runtimeTaskID - else { return } - - if progress.isIndeterminate { - self.setInstallationStep(of: runtime, to: .installing, postNotification: false) - } else { - self.setInstallationStep(of: runtime, to: .downloading(progress: progress), postNotification: false) - } - } - } - try Task.checkCancellation() - Logger.appState.debug("Done downloading runtime - \(runtime.name)") + return xcode + } + if let available { return available } + + let pending = allXcodes.filter { installationTasks[$0.id] != nil && compatible($0) } + if let xcode = pending.first(where: { $0.id == preferredID }) ?? pending.max(by: { $0.version < $1.version }), + let task = installationTasks[xcode.id] { + try await waitForXcodeInstall(task, runtime: runtime) + if let xcode = installedXcode() { return xcode } + throw XcodesKitError(localizeString("Xcode installation did not finish. Install Xcode and try this simulator runtime again.")) + } - guard let index = self.downloadableRuntimes.firstIndex(where: { $0.identifier == runtime.identifier }) else { return } - self.downloadableRuntimes[index].installState = .installed - self.update() + _ = try policy.installMethod(for: runtime, selectedXcodeVersion: allXcodes.first(where: \.selected)?.version) + throw RuntimeInstallPolicyError.noSelectedXcode + } - } catch is CancellationError { - } catch { - Logger.appState.error("Error downloading runtime: \(error.localizedDescription)") - self.error = error - if let error = error as? XcodesKitError { - self.presentedAlert = .generic(title: localizeString("Alert.Install.Error.Title"), message: error.message) - } else { - self.presentedAlert = .generic(title: localizeString("Alert.Install.Error.Title"), message: error.legibleLocalizedDescription) - } + private func waitForXcodeInstall(_ task: Task, runtime: DownloadableRuntime) async throws { + waitingForXcodeRuntimes.insert(runtime.identifier) + await task.value + try Task.checkCancellation() + waitingForXcodeRuntimes.remove(runtime.identifier) + } + + private func installRuntimeWithXcodebuild( + _ runtime: DownloadableRuntime, + architecture: String?, + developerDirectory: String?, + taskID: UUID + ) async throws { + setRuntimeStep(.downloading(progress: Progress(totalUnitCount: 100)), runtime: runtime, taskID: taskID) + let download = Current.shell.downloadRuntime + try await RuntimeXcodebuildInstallService(download: { platform, build, architecture in + download(platform, build, architecture, developerDirectory) + }).downloadAndInstall(runtime: runtime, architecture: architecture) { progress in + Task { @MainActor [weak self] in + let step: RuntimeInstallationStep = progress.isIndeterminate ? .installing : .downloading(progress: progress) + self?.setRuntimeStep(step, runtime: runtime, taskID: taskID) } } } - func downloadRuntimeViaArchive(runtime: DownloadableRuntime) { - runtimeTasks[runtime.identifier]?.cancel() - let runtimeTaskID = UUID() - runtimeTaskIDs[runtime.identifier] = runtimeTaskID - runtimeTasks[runtime.identifier] = Task { @MainActor [weak self] in - guard let self = self else { return } + private func setRuntimeStep( + _ step: RuntimeInstallationStep, + runtime: DownloadableRuntime, + taskID: UUID, + postNotification: Bool = false + ) { + guard runtimeTaskIDs[runtime.identifier] == taskID else { return } + setInstallationStep(of: runtime, to: step, postNotification: postNotification) + } + + func downloadRuntime(runtime: DownloadableRuntime, for xcodeID: XcodeID? = nil) { + let id = runtime.identifier + guard runtimeTasks[id] == nil, !isRemovingRuntime(runtime) else { return } + + let taskID = UUID() + runtimeTaskIDs[id] = taskID + setInstallationStep(of: runtime, to: .downloading(progress: Progress(totalUnitCount: 100)), postNotification: false) + runtimeTasks[id] = Task { @MainActor [weak self] in + guard let self else { return } defer { - if self.runtimeTaskIDs[runtime.identifier] == runtimeTaskID { - self.runtimeTasks[runtime.identifier] = nil - self.runtimeTaskIDs[runtime.identifier] = nil + if self.runtimeTaskIDs[id] == taskID { + self.waitingForXcodeRuntimes.remove(id) + self.runtimeTasks[id] = nil + self.runtimeTaskIDs[id] = nil } } do { - let downloadedURL = try await downloadRuntimeArchive(runtime: runtime, taskID: runtimeTaskID) try Task.checkCancellation() - Logger.appState.debug("Installing runtime: \(runtime.name)") - try await self.runtimeArchiveInstallService.install( - runtime: runtime, - archiveURL: downloadedURL, - stepChanged: { step in - await self.setInstallationStep(of: runtime, to: step) - } - ) - - guard let index = self.downloadableRuntimes.firstIndex(where: { $0.identifier == runtime.identifier }) else { return } - self.downloadableRuntimes[index].installState = .installed - updateInstalledRuntimes() - } catch is CancellationError { + try await self.installRuntime(runtime, for: xcodeID, taskID: taskID) + try Task.checkCancellation() + if let index = self.downloadableRuntimes.firstIndex(where: { $0.identifier == id }) { + self.downloadableRuntimes[index].installState = .installed + } + self.updateInstalledRuntimes() } catch { - Logger.appState.error("Error downloading runtime: \(error.localizedDescription)") - self.error = error - if let error = error as? XcodesKitError { - self.presentedAlert = .generic(title: localizeString("Alert.Install.Error.Title"), message: error.message) - } else { - self.presentedAlert = .generic(title: localizeString("Alert.Install.Error.Title"), message: error.legibleLocalizedDescription) + guard !Task.isCancelled, self.runtimeTaskIDs[id] == taskID else { return } + if let index = self.downloadableRuntimes.firstIndex(where: { $0.identifier == id }) { + self.downloadableRuntimes[index].installState = .notInstalled } + self.presentRuntimeInstallError(error, runtime: runtime) } } } + private func presentRuntimeInstallError(_ error: Error, runtime: DownloadableRuntime) { + self.error = error + let message: String + switch error { + case let error as ProcessExecutionError: + Logger.appState.error("Simulator runtime command exited with status \(error.terminationStatus): \(error.standardError, privacy: .public)") + message = error.runtimeFailureMessage + case let error as RuntimeInstallPolicyError: + switch error { + case .noSelectedXcode: + message = localizeString("Install a compatible version of Xcode, then try installing this simulator runtime again.") + case .xcode16_1OrGreaterRequired: + message = localizeString("Alert.Install.Error.Need.Xcode16.1") + case .xcode26OrGreaterRequired: + message = localizeString("Alert.Install.Error.Need.Xcode26") + } + case let error as XcodesKitError: + message = error.message + default: + message = error.legibleLocalizedDescription + } + presentedAlert = .generic(title: localizeString("Unable to install simulator runtime"), + message: runtime.visibleIdentifier + "\n\n" + message) + } + func downloadRuntimeArchive(runtime: DownloadableRuntime, taskID: UUID? = nil) async throws -> URL { let downloader = Downloader(rawValue: Current.defaults.string(forKey: "downloader") ?? "aria2") ?? .aria2 @@ -229,11 +289,17 @@ extension AppState { ) } - private var runtimeArchiveInstallService: RuntimeArchiveInstallService { + private func runtimeArchiveInstallService(developerDirectory: String?) -> RuntimeArchiveInstallService { let runtimeService = self.runtimeService return RuntimeArchiveInstallService( installDiskImage: { url in - try await runtimeService.installRuntimeImage(dmgURL: url) + guard let developerDirectory else { + try await runtimeService.installRuntimeImage(dmgURL: url) + return + } + _ = try await Process.runAsync(URL(fileURLWithPath: "/usr/bin/env"), [ + "DEVELOPER_DIR=\(developerDirectory)", "/usr/bin/xcrun", "simctl", "runtime", "add", url.path + ]) }, removeArchive: { url in try Current.files.removeItem(at: url) @@ -249,6 +315,7 @@ extension AppState { runtimeTasks[runtime.identifier]?.cancel() runtimeTasks[runtime.identifier] = nil runtimeTaskIDs[runtime.identifier] = nil + waitingForXcodeRuntimes.remove(runtime.identifier) ArchiveCancellationCleanupService( removeItem: { try Current.files.removeItem(at: $0) } @@ -273,21 +340,94 @@ extension AppState { .coreSimulatorImage(for: runtime, in: installedRuntimes) } - func deleteRuntime(runtime: DownloadableRuntime) async throws { - if let info = coreSimulatorInfo(runtime: runtime) { - try await runtimeService.deleteRuntime(identifier: info.uuid) + func isRemovingRuntime(_ runtime: DownloadableRuntime) -> Bool { + guard let image = coreSimulatorInfo(runtime: runtime) else { return false } + return removingRuntimeImages.contains(image.uuid.uppercased()) + } - // give it some time to actually finish deleting before updating - try await Task.sleep(nanoseconds: 500_000_000) - updateInstalledRuntimes() - } else { + func deleteRuntime(runtime: DownloadableRuntime, using xcodePath: Path? = nil) async throws { + guard let info = coreSimulatorInfo(runtime: runtime) else { throw XcodesKitError("No simulator found with \(runtime.identifier)") } + + let imageID = info.uuid.uppercased() + guard removingRuntimeImages.insert(imageID).inserted else { + throw XcodesKitError(localizeString("This simulator runtime is being removed.")) + } + defer { removingRuntimeImages.remove(imageID) } + + do { + try await requestRuntimeRemoval(identifier: info.uuid, using: xcodePath) + } catch { + guard Self.isRuntimeRemovalInProgress(runtimeDeletionErrorMessage(error)) else { throw error } + } + + let clock = ContinuousClock() + let deadline = clock.now + .seconds(210) + while clock.now < deadline { + try Task.checkCancellation() + if let inventory = try? await runtimeService.localInstalledRuntimes(), + !inventory.contains(where: { $0.uuid.uppercased() == imageID }) { + installedRuntimes.removeAll { $0.uuid.uppercased() == imageID } + updateInstalledRuntimes() + if let index = downloadableRuntimes.firstIndex(where: { $0.identifier == runtime.identifier }), + downloadableRuntimes[index].installState == .installed { + downloadableRuntimes[index].installState = .notInstalled + } + return + } + try await Task.sleep(for: .seconds(1)) + } + throw XcodesKitError(localizeString("CoreSimulator is still removing this runtime. Try again if it remains installed.")) + } + + static func isRuntimeRemovalInProgress(_ message: String) -> Bool { + message.contains("com.apple.CoreSimulator.simdiskimaged.SimDiskImageError") + && message.contains("code=24)") + && message.localizedCaseInsensitiveContains("Attempting to delete image") + } + + private func requestRuntimeRemoval(identifier: String, using xcodePath: Path?) async throws { + if let xcodePath { + try await deleteRuntime(identifier: identifier, using: xcodePath) + } else { + do { + try await runtimeService.deleteRuntime(identifier: identifier) + } catch { + guard Self.isMissingDeveloperToolError(runtimeDeletionErrorMessage(error)), + let path = newestInstalledXcode()?.installedPath else { throw error } + try await deleteRuntime(identifier: identifier, using: path) + } + } + } + + private func deleteRuntime(identifier: String, using xcodePath: Path) async throws { + let developerDirectory = xcodePath.url.appendingPathComponent("Contents/Developer").path + try await Current.shell.deleteRuntimeWithDeveloperDirectory(identifier, developerDirectory) + } + + func newestInstalledXcode(excluding id: XcodeID? = nil) -> Xcode? { + allXcodes.filter { $0.id != id && $0.installState.installed }.max { $0.version < $1.version } + } + + func removeRuntimesForUninstall(_ runtimes: [DownloadableRuntime], using path: Path) async -> Bool { + for runtime in runtimes where coreSimulatorInfo(runtime: runtime) != nil { + do { + try Task.checkCancellation() + try await deleteRuntime(runtime: runtime, using: path) + } catch is CancellationError { + return false + } catch { + presentRuntimeDeletionError(error, runtime: runtime, inSettings: false) + return false + } + } + return true } /// - Parameter presentErrorInSettings: Show failures in the Settings window (Platforms list) instead of the main window. func confirmDeleteRuntime(runtime: DownloadableRuntime, presentErrorInSettings: Bool = true) { - deleteRuntimeTask?.cancel() + guard deleteRuntimeTask == nil, !isRemovingRuntime(runtime) else { return } let taskID = UUID() deleteRuntimeTaskID = taskID deleteRuntimeTask = Task { @MainActor [weak self] in @@ -357,6 +497,9 @@ extension AppState { return error.message } + if let error = error as? ProcessExecutionError { + return error.runtimeFailureMessage + } return error.localizedDescription } } @@ -457,7 +600,7 @@ extension AppState { guard !runtimes.isEmpty else { return } Logger.appState.info("Automatically downloading platforms: \(runtimes.map(\.name).joined(separator: ", "))") - runtimes.forEach(downloadRuntime(runtime:)) + runtimes.forEach { downloadRuntime(runtime: $0, for: availableXcode.xcodeID) } } } @@ -508,25 +651,11 @@ extension AppState { .sorted { ($0.platform.displayOrder, $1.name) < ($1.platform.displayOrder, $0.name) } } - /// Uninstalls an Xcode, then removes the given simulator runtimes. - @discardableResult - func uninstall(xcode: Xcode, removingRuntimes runtimes: [DownloadableRuntime]) -> Task? { - guard let installedPath = xcode.installedPath else { return nil } - uninstall(xcode: xcode) - guard !runtimes.isEmpty, let removalTask = uninstallTask else { return uninstallTask } - return Task { @MainActor [weak self] in - await removalTask.value - // Failed or cancelled removal leaves the Xcode in the list. Keep its platforms too. - guard let self, !Task.isCancelled, !removalTask.isCancelled, - !self.allXcodes.contains(where: { $0.installedPath == installedPath }) else { return } - for runtime in runtimes { - do { - try await self.deleteRuntime(runtime: runtime) - } catch { - self.presentRuntimeDeletionError(error, runtime: runtime, inSettings: false) - return - } - } - } + +} + +private extension Xcode { + var developerDirectory: String? { + installedPath?.url.appendingPathComponent("Contents/Developer").path } } diff --git a/Xcodes/Backend/AppState.swift b/Xcodes/Backend/AppState.swift index 96249de0..ac13f70a 100644 --- a/Xcodes/Backend/AppState.swift +++ b/Xcodes/Backend/AppState.swift @@ -195,6 +195,8 @@ class AppState: ObservableObject { // MARK: - Runtimes @Published var downloadableRuntimes: [DownloadableRuntime] = [] + @Published var waitingForXcodeRuntimes: Set = [] + @Published var removingRuntimeImages: Set = [] @Published var installedRuntimes: [CoreSimulatorImage] = [] // MARK: - Operation State @@ -780,8 +782,10 @@ class AppState: ObservableObject { } // MARK: - Uninstall - func uninstall(xcode: Xcode) { - guard let installedXcodePath = xcode.installedPath else { return } + @discardableResult + func uninstall(xcode: Xcode, removingRuntimes runtimes: [DownloadableRuntime] = []) -> Task? { + guard let installedXcodePath = xcode.installedPath, xcode.installState.installed else { return nil } + let survivingXcode = newestInstalledXcode(excluding: xcode.id) if let index = allXcodes.firstIndex(where: { $0.id == xcode.id }) { allXcodes[index].installState = .uninstalling(installedXcodePath) @@ -798,11 +802,28 @@ class AppState: ObservableObject { } } do { + try Task.checkCancellation() + if survivingXcode == nil, !runtimes.isEmpty { + // The last full Xcode supplies simctl. Preserve it if runtime removal fails. + guard Current.files.fileExists(atPath: installedXcodePath.string) else { + throw FileError.fileNotFound(installedXcodePath.string) + } + guard await removeRuntimesForUninstall(runtimes, using: installedXcodePath) else { + try Task.checkCancellation() + if let index = allXcodes.firstIndex(where: { $0.id == xcode.id }) { + allXcodes[index].installState = .installed(installedXcodePath) + } + return + } + } try Task.checkCancellation() try await uninstallXcodeAsync(path: installedXcodePath) try Task.checkCancellation() await updateInstalledXcodesAsync() await updateSelectedXcodePathAsync() + if let survivingPath = survivingXcode?.installedPath, !runtimes.isEmpty { + _ = await removeRuntimesForUninstall(runtimes, using: survivingPath) + } } catch is CancellationError { } catch { if let index = allXcodes.firstIndex(where: { $0.id == xcode.id }) { @@ -816,6 +837,7 @@ class AppState: ObservableObject { } } } + return uninstallTask } func reveal(_ path: Path?) { diff --git a/Xcodes/Backend/Environment.swift b/Xcodes/Backend/Environment.swift index 4373d470..16907030 100644 --- a/Xcodes/Backend/Environment.swift +++ b/Xcodes/Backend/Environment.swift @@ -66,8 +66,14 @@ public struct Shell: Sendable { return try await Process.runAsync(unxipPath.url, workingDirectory: url.deletingLastPathComponent(), ["\(url.path)"]) } - public var downloadRuntime: @Sendable (String, String, String?) -> AsyncThrowingStream = { platform, version, architecture in - XcodebuildRuntimeDownloadService().download(platform: platform, buildVersion: version, architecture: architecture) + public var deleteRuntimeWithDeveloperDirectory: @Sendable (String, String) async throws -> Void = { identifier, directory in + _ = try await CleanupOperations.runSimctl(["runtime", "delete", identifier], developerDirectory: directory) + } + + public var downloadRuntime: @Sendable (String, String, String?, String?) -> AsyncThrowingStream = { platform, version, architecture, developerDirectory in + XcodebuildRuntimeDownloadService.download( + platform: platform, buildVersion: version, architecture: architecture, developerDirectory: developerDirectory + ) } } diff --git a/Xcodes/Backend/Process.swift b/Xcodes/Backend/Process.swift index d922c20f..06ece0f4 100644 --- a/Xcodes/Backend/Process.swift +++ b/Xcodes/Backend/Process.swift @@ -1,4 +1,5 @@ import Foundation +import os import Path import XcodesKit @@ -16,3 +17,136 @@ extension Process { try await XcodesProcess.run(executable, workingDirectory: workingDirectory, input: input, arguments) } } + +extension XcodebuildRuntimeDownloadService { + /// Runs with a per-process Xcode selection so a runtime can use an inactive Xcode. + static func download( + platform: String, + buildVersion: String, + architecture: String?, + developerDirectory: String? + ) -> AsyncThrowingStream { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/usr/bin/xcodebuild") + if let developerDirectory { + process.environment = ProcessInfo.processInfo.environment.merging(["DEVELOPER_DIR": developerDirectory]) { _, scoped in scoped } + } + process.arguments = ["-downloadPlatform", platform, "-buildVersion", buildVersion] + if let architecture { + process.arguments?.append(contentsOf: ["-architectureVariant", architecture]) + } + return runtimeProgressStream(for: process) + } + + static func runtimeProgressStream(for process: Process) -> AsyncThrowingStream { + AsyncThrowingStream { continuation in + let stdout = Pipe() + let stderr = Pipe() + process.standardOutput = stdout + process.standardError = stderr + let output = OSAllocatedUnfairLock(initialState: RuntimeCommandOutput()) + let progress = Progress(totalUnitCount: 100) + progress.kind = .file + progress.fileOperationKind = .downloading + continuation.yield(progress) + + // Wait for exit and both pipes to drain so the final diagnostic is available. + let finish: @Sendable () -> Void = { + let result = output.withLock { $0.completedOutput() } + guard let result else { return } + if process.terminationReason == .exit, process.terminationStatus == 0 { + continuation.finish() + } else { + continuation.finish(throwing: ProcessExecutionError( + process: process, terminationStatus: process.terminationStatus, + standardOutput: result.stdout, standardError: result.stderr + )) + } + } + + for (pipe, isError) in [(stdout, false), (stderr, true)] { + pipe.fileHandleForReading.readabilityHandler = { handle in + let data = handle.availableData + if data.isEmpty { handle.readabilityHandler = nil } + output.withLock { + if data.isEmpty { + $0.closedPipes += 1 + } else if isError { + $0.stderr.append(data) + } else { + $0.stdout.append(data) + $0.progressBuffer.append(data) + if let lastDelimiter = $0.progressBuffer.lastIndex(where: { $0 == 10 || $0 == 13 }) { + let records = String(decoding: $0.progressBuffer[...lastDelimiter], as: UTF8.self) + $0.progressBuffer.removeSubrange(...lastDelimiter) + for record in records.split(whereSeparator: \.isNewline) { + let line = record.trimmingCharacters(in: .whitespaces) + if line.hasPrefix("Installing") { + if !$0.installing { + $0.installing = true + continuation.yield(Progress(totalUnitCount: -1)) + } + } else if !$0.installing, line.contains("%") { + progress.updateFromXcodebuild(text: line) + continuation.yield(progress) + } + } + } + } + } + if data.isEmpty { finish() } + } + } + + process.terminationHandler = { process in + process.terminationHandler = nil + output.withLock { $0.exited = true } + finish() + } + continuation.onTermination = { reason in + if case .cancelled = reason, process.isRunning { process.terminate() } + } + do { + try process.run() + } catch { + stdout.fileHandleForReading.readabilityHandler = nil + stderr.fileHandleForReading.readabilityHandler = nil + process.terminationHandler = nil + continuation.finish(throwing: error) + } + } + } +} + +private struct RuntimeCommandOutput { + var stdout = Data() + var stderr = Data() + var progressBuffer = Data() + var installing = false + var closedPipes = 0 + var exited = false + var finished = false + + mutating func completedOutput() -> (stdout: String, stderr: String)? { + guard exited, closedPipes == 2, !finished else { return nil } + finished = true + return (String(decoding: stdout, as: UTF8.self), String(decoding: stderr, as: UTF8.self)) + } +} + +extension ProcessExecutionError { + var runtimeFailureMessage: String { + let diagnostics = standardError.trimmingCharacters(in: .whitespacesAndNewlines) + let summary = String(format: localizeString("Xcode’s simulator runtime command failed (exit code %d)."), terminationStatus) + if !diagnostics.isEmpty { + return summary + "\n\n" + diagnostics + } + + // Some Xcode versions report errors on stdout alongside carriage-return progress. + let failure = standardOutput.split(whereSeparator: \.isNewline).last { line in + line.localizedCaseInsensitiveContains("error") || line.localizedCaseInsensitiveContains("failed") + || line.localizedCaseInsensitiveContains("cancelled") + } + return failure.map { summary + "\n\n" + $0 } ?? summary + } +} diff --git a/Xcodes/Backend/XcodeCommands.swift b/Xcodes/Backend/XcodeCommands.swift index 344c7ebd..bc7e24cf 100644 --- a/Xcodes/Backend/XcodeCommands.swift +++ b/Xcodes/Backend/XcodeCommands.swift @@ -58,11 +58,7 @@ struct CancelInstallButton: View { let xcode: Xcode? var body: some View { - Button(action: cancelInstall) { - Label("Cancel", systemImage: "xmark") - } - .help(localizeString("StopInstallation")) - .buttonStyle(.plain) + DownloadCancelButton(action: cancelInstall) } private func cancelInstall() { @@ -76,10 +72,7 @@ struct CancelRuntimeInstallButton: View { let runtime: DownloadableRuntime? var body: some View { - Button(action: cancelInstall) { - Image(systemName: "xmark.circle.fill") - }.help(localizeString("StopInstallation")) - .buttonStyle(.plain) + DownloadCancelButton(action: cancelInstall) } private func cancelInstall() { @@ -88,6 +81,19 @@ struct CancelRuntimeInstallButton: View { } } +struct DownloadCancelButton: View { + let action: () -> Void + + var body: some View { + Button(action: action) { + Image(systemName: "xmark.circle.fill") + } + .accessibilityLabel(Text("StopInstallation")) + .help(localizeString("StopInstallation")) + .buttonStyle(.plain) + } +} + struct SelectButton: View { @EnvironmentObject var appState: AppState let xcode: Xcode? @@ -233,6 +239,7 @@ struct CreateSymbolicLinkButton: View { struct DownloadRuntimeButton: View { @EnvironmentObject var appState: AppState let runtime: DownloadableRuntime? + let xcodeID: XcodeID var body: some View { Button(action: install) { @@ -243,7 +250,7 @@ struct DownloadRuntimeButton: View { private func install() { guard let runtime = runtime else { return } - appState.downloadRuntime(runtime: runtime) + appState.downloadRuntime(runtime: runtime, for: xcodeID) } } diff --git a/Xcodes/Frontend/Cleanup/CleanupModel+Simulators.swift b/Xcodes/Frontend/Cleanup/CleanupModel+Simulators.swift index 2e940a4f..1c34b8e7 100644 --- a/Xcodes/Frontend/Cleanup/CleanupModel+Simulators.swift +++ b/Xcodes/Frontend/Cleanup/CleanupModel+Simulators.swift @@ -106,6 +106,9 @@ extension CleanupModel { } func runtimeSelectionUnavailableReason(_ runtime: CleanupOperations.SimulatorRuntime) -> String? { + if appState?.removingRuntimeImages.contains(runtime.id) == true { + return "This simulator runtime is being removed." + } if isScanning || isShowingCachedResults { return "Wait for the scan to finish." } if runtimeInventoryUnavailable || runtimeAssociationCheckFailed { return "Could not check runtime associations. Rescan before removing runtimes." } guard runtime.deletable == true, ["Ready", "Unusable"].contains(runtime.state) else { return "CoreSimulator does not currently allow removal of this runtime." } diff --git a/Xcodes/Frontend/Common/XcodesAlert.swift b/Xcodes/Frontend/Common/XcodesAlert.swift index d35786b5..5c159f10 100644 --- a/Xcodes/Frontend/Common/XcodesAlert.swift +++ b/Xcodes/Frontend/Common/XcodesAlert.swift @@ -1,3 +1,4 @@ +import AppKit import Foundation import SwiftUI import XcodesKit @@ -48,7 +49,7 @@ extension Alert { /// Removing a platform runs `simctl`, which only comes with Xcode. Offers to make the newest installed release active and retry. @MainActor static func noActiveXcode(appState: AppState, runtime: DownloadableRuntime, xcode: Xcode?, inSettings: Bool) -> Alert { - let explanation = String(format: localizeString("Alert.NoActiveXcode.Message"), runtime.name, appState.selectedXcodePath ?? "–") + let explanation = String(format: localizeString("Alert.NoActiveXcode.Message"), runtime.name, appState.selectedXcodePath?.trimmingCharacters(in: .whitespacesAndNewlines) ?? "–") guard let xcode else { return Alert( title: Text("Alert.NoActiveXcode.Title"), @@ -161,3 +162,22 @@ private struct HelperSettingsButton: View { } } } + +/// Native alerts size to their message. Keep the buttons visible even for command output. +@MainActor +func boundedErrorAlert(title: String, message: String) -> Alert { + let lines = message.split(omittingEmptySubsequences: false, whereSeparator: \.isNewline) + let preview = String(lines.prefix(6).joined(separator: "\n").prefix(480)) + guard preview != message else { + return Alert(title: Text(title), message: Text(message), dismissButton: .default(Text("OK"))) + } + return Alert( + title: Text(title), + message: Text(preview + "…"), + primaryButton: .default(Text("OK")), + secondaryButton: .default(Text("Copy Details"), action: { + NSPasteboard.general.clearContents() + NSPasteboard.general.setString(message, forType: .string) + }) + ) +} diff --git a/Xcodes/Frontend/InfoPane/PlatformsView.swift b/Xcodes/Frontend/InfoPane/PlatformsView.swift index 9e7c5596..6e6351cd 100644 --- a/Xcodes/Frontend/InfoPane/PlatformsView.swift +++ b/Xcodes/Frontend/InfoPane/PlatformsView.swift @@ -81,6 +81,8 @@ struct PlatformsView: View { @ViewBuilder func runtimeView(runtime: DownloadableRuntime) -> some View { + let waitingForXcode = appState.waitingForXcodeRuntimes.contains(runtime.identifier) + let isInstalled = appState.coreSimulatorInfo(runtime: runtime) != nil VStack(spacing: 10) { HStack { runtime.icon() @@ -96,28 +98,38 @@ struct PlatformsView: View { Spacer() // TODO: Update the downloadableRuntimes with the appropriate installState so we don't have to check path awkwardly - if appState.runtimeInstallPath(xcode: xcode, runtime: runtime) != nil { + if appState.isRemovingRuntime(runtime) { + ProgressView().controlSize(.small) + Text("Removing…").foregroundStyle(.secondary) + } else if isInstalled { Button("Uninstall", role: .destructive) { appState.presentedAlert = .deletePlatform(runtime: runtime) } .help("Alert.DeletePlatform.PrimaryButton") - } else if runtime.installState == .notInstalled { - DownloadRuntimeButton(runtime: runtime) + } else if appState.runtimeTasks[runtime.identifier] == nil && !waitingForXcode { + DownloadRuntimeButton(runtime: runtime, xcodeID: xcode.id) } Text(runtime.downloadFileSizeString) .font(.subheadline) - .frame(width: 70, alignment: .trailing) + .frame(width: 70, alignment: .trailing) + } + + if !isInstalled, waitingForXcode { + HStack { + Text("Waiting for Xcode to finish installing…") + Spacer() + CancelRuntimeInstallButton(runtime: runtime) + } + } else if !isInstalled, appState.runtimeTasks[runtime.identifier] != nil, + case let .installing(installationStep) = runtime.installState { + HStack(alignment: .top, spacing: 5) { + RuntimeInstallationStepDetailView(installationStep: installationStep) + .fixedSize(horizontal: false, vertical: true) + Spacer() + CancelRuntimeInstallButton(runtime: runtime) + } } - - if case let .installing(installationStep) = runtime.installState { - HStack(alignment: .top, spacing: 5){ - RuntimeInstallationStepDetailView(installationStep: installationStep) - .fixedSize(horizontal: false, vertical: true) - Spacer() - CancelRuntimeInstallButton(runtime: runtime) - } - } } } diff --git a/Xcodes/Frontend/MainWindow.swift b/Xcodes/Frontend/MainWindow.swift index b6a6213b..c79a3e95 100644 --- a/Xcodes/Frontend/MainWindow.swift +++ b/Xcodes/Frontend/MainWindow.swift @@ -212,14 +212,7 @@ struct MainWindow: View { secondaryButton: .cancel(Text("Done")) ) case let .generic(title, message): - return Alert( - title: Text(title), - message: Text(message), - dismissButton: .default( - Text("OK"), - action: { appState.presentedAlert = nil } - ) - ) + return boundedErrorAlert(title: title, message: message) case .unauthenticated: return Alert( title: Text("Alert.Install.Error.Title"), diff --git a/Xcodes/Frontend/XcodeList/InstallationStepRowView.swift b/Xcodes/Frontend/XcodeList/InstallationStepRowView.swift index edfe4979..0314ac32 100644 --- a/Xcodes/Frontend/XcodeList/InstallationStepRowView.swift +++ b/Xcodes/Frontend/XcodeList/InstallationStepRowView.swift @@ -6,7 +6,7 @@ struct InstallationStepRowView: View { let cancel: () -> Void var body: some View { - Button(action: cancel) { + HStack(spacing: 6) { switch installationStep { case let .downloading(progress): // FB8955769 ProgressView.init(_: Progress) doesn't ensure that changes from the Progress object are applied to the UI on the main thread @@ -16,13 +16,12 @@ struct InstallationStepRowView: View { // A retry can replace the Progress without changing the installation step. .id(ObjectIdentifier(progress)) case .authenticating, .unarchiving, .moving, .trashingArchive, .checkingSecurity, .finishing: - InstallProgressRing(fractionCompleted: nil) + InstallProgressRing(fractionCompleted: nil, showsStopGlyph: false) .help(installationStep.stepDescription()) } + DownloadCancelButton(action: cancel) + .accessibilityValue(Text(installationStep.stepDescription())) } - .buttonStyle(PlainButtonStyle()) - .accessibilityLabel(Text("StopInstallation")) - .accessibilityValue(Text(installationStep.stepDescription())) .frame(minWidth: 65) } } @@ -38,7 +37,8 @@ private struct DownloadProgressRing: View { var body: some View { InstallProgressRing( - fractionCompleted: progress.progress.isIndeterminate ? nil : progress.progress.fractionCompleted + fractionCompleted: progress.progress.isIndeterminate ? nil : progress.progress.fractionCompleted, + showsStopGlyph: false ) .help(helpText) } diff --git a/Xcodes/XcodesApp.swift b/Xcodes/XcodesApp.swift index 0106ed5f..bc7896e4 100644 --- a/Xcodes/XcodesApp.swift +++ b/Xcodes/XcodesApp.swift @@ -110,14 +110,7 @@ struct XcodesApp: App { case let .noActiveXcode(runtime, xcode): return .noActiveXcode(appState: appState, runtime: runtime, xcode: xcode, inSettings: true) case let .generic(title, message): - return Alert( - title: Text(title), - message: Text(message), - dismissButton: .default( - Text("OK"), - action: { appState.presentedAlert = nil } - ) - ) + return boundedErrorAlert(title: title, message: message) } } } diff --git a/XcodesTests/AppStateTests.swift b/XcodesTests/AppStateTests.swift index 325ebabc..ca4f551d 100644 --- a/XcodesTests/AppStateTests.swift +++ b/XcodesTests/AppStateTests.swift @@ -682,97 +682,189 @@ class AppStateTests: XCTestCase { XCTAssertEqual(subject.authenticationState, .unauthenticated) } - func test_DownloadRuntimeViaXcodeBuild_ClearsRuntimeTaskWhenComplete() async throws { - let runtime = try Self.downloadableRuntime() + func test_DownloadRuntime_WaitsForFirstXcodeThenUsesItsDeveloperDirectory() async throws { + try await assertRuntimeUsesNewXcode(olderXcodeInstalled: false) + } + + func test_DownloadRuntime_RetriesFailedParallelAttemptWithNewXcode() async throws { + try await assertRuntimeUsesNewXcode(olderXcodeInstalled: true) + } + + func test_DownloadRuntime_BetaWaitsForMatchingXcodeInsteadOfUsingOlderToolchain() async throws { + try await assertRuntimeUsesNewXcode(olderXcodeInstalled: true, betaRuntime: true) + } + + private func assertRuntimeUsesNewXcode(olderXcodeInstalled: Bool, betaRuntime: Bool = false) async throws { + var runtime = try Self.downloadableRuntime(contentType: "cryptexDiskImage") + if betaRuntime { runtime.seedNumber = 1 } + let path = Path("/Applications/Test Xcode.app")! + var xcode = Xcode(version: Version("27.3.0")!, installState: .notInstalled, selected: false, icon: nil) + let xcodeID = xcode.id + subject.allXcodes = [xcode] + if olderXcodeInstalled { + subject.allXcodes.append( + Xcode(version: Version("27.2.0")!, installState: .installed(Path("/Applications/Older Xcode.app")!), + selected: true, icon: nil) + ) + } subject.downloadableRuntimes = [runtime] - Current.shell.downloadRuntime = { _, _, _ in - let (stream, continuation) = AsyncThrowingStream.makeStream(of: Progress.self, throwing: Error.self) - continuation.finish() - return stream + + let dependency = OneShotContinuation() + subject.installationTasks[xcodeID] = Task { @MainActor in + try? await dependency.value {} + xcode.installState = .installed(path) + subject.allXcodes = [xcode] + subject.installationTasks[xcodeID] = nil + } + + let directories = TestLockedBox<[String?]>([]) + Current.shell.downloadRuntime = { _, _, _, directory in + directories.withValue { $0.append(directory) } + return AsyncThrowingStream { continuation in + if directory == nil { + continuation.finish(throwing: ProcessExecutionError( + process: Process(), terminationStatus: 70, standardOutput: nil, standardError: "Runtime unavailable" + )) + } else { + continuation.finish() + } + } } - subject.downloadRuntimeViaXcodeBuild(runtime: runtime) + subject.downloadRuntime(runtime: runtime, for: xcodeID) let task = try XCTUnwrap(subject.runtimeTasks[runtime.identifier]) - try await task.value + for _ in 0..<100 where !subject.waitingForXcodeRuntimes.contains(runtime.identifier) { + await Task.yield() + } + XCTAssertTrue(subject.waitingForXcodeRuntimes.contains(runtime.identifier)) + let expectedFirstAttempts: [String?] = olderXcodeInstalled && !betaRuntime ? [nil] : [] + XCTAssertEqual(directories.read { $0 }, expectedFirstAttempts) + XCTAssertNil(subject.presentedAlert) + + dependency.resume() + await task.value + XCTAssertEqual(directories.read { $0 }, expectedFirstAttempts + ["/Applications/Test Xcode.app/Contents/Developer"]) + XCTAssertFalse(subject.waitingForXcodeRuntimes.contains(runtime.identifier)) XCTAssertNil(subject.runtimeTasks[runtime.identifier]) - XCTAssertNil(subject.runtimeTaskIDs[runtime.identifier]) XCTAssertEqual(subject.downloadableRuntimes.first?.installState, .installed) } - func test_DownloadRuntimeViaXcodeBuild_OldTaskDoesNotClearReplacementTask() async throws { - let runtime = try Self.downloadableRuntime() - subject.downloadableRuntimes = [runtime] - let continuations = TestLockedBox<[AsyncThrowingStream.Continuation]>([]) - Current.shell.downloadRuntime = { _, _, _ in - let (stream, continuation) = AsyncThrowingStream.makeStream(of: Progress.self, throwing: Error.self) - continuations.withValue { $0.append(continuation) } - return stream - } - - subject.downloadRuntimeViaXcodeBuild(runtime: runtime) - for _ in 0..<100 where continuations.read({ $0.count }) < 1 { - await Task.yield() + func test_RuntimeCommandStreamsDownloadProgressThenInstallingAndPreservesFailure() async throws { + let process = Process() + process.executableURL = URL(fileURLWithPath: "/bin/sh") + process.arguments = ["-c", """ + printf 'Finding content...\\n\\rDownloading iOS: 63.' + printf '0%% (1.2 GB of 2.0 GB)\\rInstalling iOS Simulator\\n' + printf 'runtime diagnostic\\n' >&2 + exit 70 + """] + + var sawDownload = false + var sawInstalling = false + do { + for try await progress in XcodebuildRuntimeDownloadService.runtimeProgressStream(for: process) { + sawDownload = sawDownload || progress.completedUnitCount == 63 + sawInstalling = sawInstalling || progress.isIndeterminate + } + XCTFail("Expected the command to fail") + } catch let error as ProcessExecutionError { + XCTAssertEqual(error.terminationStatus, 70) + XCTAssertEqual(error.standardError, "runtime diagnostic\n") } - let firstTask = try XCTUnwrap(subject.runtimeTasks[runtime.identifier]) - XCTAssertEqual(continuations.read { $0.count }, 1) + XCTAssertTrue(sawDownload) + XCTAssertTrue(sawInstalling) + } - subject.downloadRuntimeViaXcodeBuild(runtime: runtime) - for _ in 0..<100 where continuations.read({ $0.count }) < 2 { - await Task.yield() + func test_DownloadRuntime_FailureShowsStderrAndAllowsRetry() async throws { + let runtime = try Self.downloadableRuntime(contentType: "cryptexDiskImage") + subject.downloadableRuntimes = [runtime] + subject.allXcodes = [ + Xcode(version: Version("27.3.0")!, installState: .installed(Path("/Applications/Xcode.app")!), + selected: true, icon: nil) + ] + Current.shell.downloadRuntime = { _, _, _, _ in + AsyncThrowingStream { + $0.finish(throwing: ProcessExecutionError( + process: Process(), terminationStatus: 70, + standardOutput: String(repeating: "Downloading iOS: 50%\r", count: 1_000), + standardError: "Download failed: Connection lost." + )) + } } - let replacementTask = try XCTUnwrap(subject.runtimeTasks[runtime.identifier]) - XCTAssertEqual(continuations.read { $0.count }, 2) - continuations.read { $0[0] }.finish() - try await firstTask.value - XCTAssertNotNil(subject.runtimeTasks[runtime.identifier]) + subject.downloadRuntime(runtime: runtime) + let task = try XCTUnwrap(subject.runtimeTasks[runtime.identifier]) + await task.value - continuations.read { $0[1] }.finish() - try await replacementTask.value + guard case let .generic(_, message) = subject.presentedAlert else { + return XCTFail("Expected a runtime install error") + } + XCTAssertTrue(message.contains("Connection lost")) + XCTAssertTrue(message.contains("70")) + XCTAssertFalse(message.contains("Downloading iOS")) + XCTAssertEqual(subject.downloadableRuntimes.first?.installState, .notInstalled) XCTAssertNil(subject.runtimeTasks[runtime.identifier]) - XCTAssertNil(subject.runtimeTaskIDs[runtime.identifier]) } - func test_ConfirmDeleteRuntime_OldTaskDoesNotClearReplacementTask() async throws { + func test_ConfirmDeleteRuntime_IgnoresDuplicateAndAcceptsRemovalInProgress() async throws { let runtime = try Self.downloadableRuntime() let installedRuntime = CoreSimulatorImage( uuid: "runtime-uuid", path: ["relative": "/Library/Developer/CoreSimulator/Images/runtime.dmg"], runtimeInfo: CoreSimulatorRuntimeInfo(build: runtime.simulatorVersion.buildUpdate) ) + let registeredImage = try PropertyListSerialization.data(fromPropertyList: [ + "images": [[ + "uuid": installedRuntime.uuid, + "path": installedRuntime.path, + "runtimeInfo": ["build": installedRuntime.runtimeInfo.build], + ]] + ], format: .binary, options: 0) + let emptyInventory = try PropertyListSerialization.data(fromPropertyList: ["images": []], format: .binary, options: 0) let deletedIdentifiers = TestLockedBox<[String]>([]) - let continuations = TestLockedBox<[CheckedContinuation]>([]) + let inventory = TestLockedBox(registeredImage) + let firstRead = OneShotContinuation() subject = AppState( - runtimeService: Self.runtimeService { identifier in + runtimeService: Self.runtimeService(contentsAtPath: { _ in + let snapshot = inventory.read { $0 } + firstRead.resume() + return snapshot + }) { identifier in deletedIdentifiers.withValue { $0.append(identifier) } - return try await withCheckedThrowingContinuation { continuation in - continuations.withValue { $0.append(continuation) } - } + throw ProcessExecutionError( + process: Process(), terminationStatus: 24, standardOutput: nil, + standardError: """ + (domain=com.apple.CoreSimulator.simdiskimaged.SimDiskImageError, code=24): + Attempting to delete image: runtime-uuid (Please retry in 174s, if the image is not removed) + """ + ) } ) subject.installedRuntimes = [installedRuntime] subject.confirmDeleteRuntime(runtime: runtime) - for _ in 0..<100 where continuations.read({ $0.count }) < 1 { - await Task.yield() + let task = try XCTUnwrap(subject.deleteRuntimeTask) + let observedInventory = expectation(description: "CoreSimulator still lists the runtime after the first delete") + let observation = Task { + try await firstRead.value {} + observedInventory.fulfill() } - let firstTask = try XCTUnwrap(subject.deleteRuntimeTask) - XCTAssertEqual(deletedIdentifiers.read { $0 }, [installedRuntime.uuid]) + await fulfillment(of: [observedInventory], timeout: 2) + observation.cancel() - subject.confirmDeleteRuntime(runtime: runtime) - for _ in 0..<100 where continuations.read({ $0.count }) < 2 { - await Task.yield() - } - let replacementTask = try XCTUnwrap(subject.deleteRuntimeTask) - XCTAssertEqual(deletedIdentifiers.read { $0 }, [installedRuntime.uuid, installedRuntime.uuid]) + XCTAssertTrue(subject.isRemovingRuntime(runtime)) + XCTAssertNotNil(subject.coreSimulatorInfo(runtime: runtime)) + XCTAssertNil(subject.presentedPreferenceAlert) - continuations.read { $0[0] }.resume(returning: ProcessOutput(status: 0, out: "", err: "")) - await firstTask.value - XCTAssertNotNil(subject.deleteRuntimeTask) + subject.confirmDeleteRuntime(runtime: runtime) + inventory.withValue { $0 = emptyInventory } + await task.value - continuations.read { $0[1] }.resume(returning: ProcessOutput(status: 0, out: "", err: "")) - await replacementTask.value + XCTAssertEqual(deletedIdentifiers.read { $0 }, [installedRuntime.uuid]) + XCTAssertNil(subject.presentedPreferenceAlert) + XCTAssertNil(subject.coreSimulatorInfo(runtime: runtime)) + XCTAssertFalse(subject.isRemovingRuntime(runtime)) XCTAssertNil(subject.deleteRuntimeTask) XCTAssertNil(subject.deleteRuntimeTaskID) } @@ -1020,7 +1112,7 @@ class AppStateTests: XCTestCase { ) } - private static func downloadableRuntime() throws -> DownloadableRuntime { + private static func downloadableRuntime(contentType: String = "diskImage") throws -> DownloadableRuntime { let json = """ { "category": "simulator", @@ -1031,7 +1123,7 @@ class AppStateTests: XCTestCase { "source": "https://example.com/iOS_16_Runtime.dmg", "architectures": null, "dictionaryVersion": 1, - "contentType": "diskImage", + "contentType": "\(contentType)", "platform": "com.apple.platform.iphoneos", "identifier": "com.apple.CoreSimulator.SimRuntime.iOS-16-0", "version": "16.0", @@ -1052,24 +1144,14 @@ class AppStateTests: XCTestCase { } private static func runtimeService( + contentsAtPath: @escaping RuntimeService.ContentsAtPath, deleteRuntimeOutput: @escaping @Sendable (String) async throws -> ProcessOutput ) -> RuntimeService { RuntimeService( loadData: { request in (Data(), HTTPURLResponse(url: request.url!, statusCode: 200, httpVersion: nil, headerFields: nil)!) }, - contentsAtPath: { _ in - Data(""" - - - - - images - - - - """.utf8) - }, + contentsAtPath: contentsAtPath, installedRuntimesOutput: { ProcessOutput(status: 0, out: "{}", err: "") }, diff --git a/XcodesTests/AppStateUpdateTests.swift b/XcodesTests/AppStateUpdateTests.swift index 986fd972..6f2b211a 100644 --- a/XcodesTests/AppStateUpdateTests.swift +++ b/XcodesTests/AppStateUpdateTests.swift @@ -165,6 +165,32 @@ class AppStateUpdateTests: XCTestCase { XCTAssertEqual(subject.allXcodes.first?.installedPath, xcode.installedPath) } + func test_UninstallWithPlatforms_UsesLastXcodeBeforeRemovingIt() async throws { + let path = Path("/Applications/Test Xcode.app")! + let xcode = Xcode(version: Version("27.3.0-beta.1")!, installState: .installed(path), selected: true, icon: nil) + subject.allXcodes = [xcode] + let platform = try runtime(platform: "iphoneos", identifier: "ios-test", sdkBuild: "24A1", simulatorBuild: "24A2", architectures: ["arm64"]) + subject.installedRuntimes = [ + CoreSimulatorImage(uuid: "test-runtime", path: [:], runtimeInfo: CoreSimulatorRuntimeInfo(build: "24A2", supportedArchitectures: [.arm64])) + ] + let operations = AppStateUpdateTestLockedBox<[String]>([]) + Current.shell.deleteRuntimeWithDeveloperDirectory = { id, directory in + operations.withValue { $0.append("delete " + id + " using " + directory) } + } + Current.files.trashItem = { url in + operations.withValue { $0.append("trash " + url.path) } + return url + } + + let task = try XCTUnwrap(subject.uninstall(xcode: xcode, removingRuntimes: [platform])) + await task.value + + XCTAssertEqual(operations.read { $0 }, [ + "delete test-runtime using /Applications/Test Xcode.app/Contents/Developer", + "trash /Applications/Test Xcode.app" + ]) + } + func test_InstalledRuntimesUsedOnlyByXcode_SkipsSharedAndNotInstalledPlatforms() throws { subject.downloadableRuntimes = try [ platformRuntime(platform: "iphoneos", identifier: "ios-27.0", sdkBuild: "24A430", simulatorBuild: "24A434"),