diff --git a/Sources/Basics/AuthorizationProvider.swift b/Sources/Basics/AuthorizationProvider.swift index 22d6c31b7c9..fbc0960c4bf 100644 --- a/Sources/Basics/AuthorizationProvider.swift +++ b/Sources/Basics/AuthorizationProvider.swift @@ -97,7 +97,7 @@ public class NetrcAuthorizationProvider: AuthorizationProvider, AuthorizationWri let contents = try? self.fileSystem.readFileContents(self.path).contents try self.fileSystem.writeFileContents(self.path) { stream in // Write existing contents - if let contents = contents, !contents.isEmpty { + if let contents, !contents.isEmpty { stream.write(contents) stream.write("\n") } diff --git a/Sources/Basics/Concurrency/SendableBox.swift b/Sources/Basics/Concurrency/SendableBox.swift index 851555f16a3..bf983e982d0 100644 --- a/Sources/Basics/Concurrency/SendableBox.swift +++ b/Sources/Basics/Concurrency/SendableBox.swift @@ -25,13 +25,13 @@ public actor SendableBox { extension SendableBox where Value == Int { func increment() { - if let value = self.value { + if let value { self.value = value + 1 } } func decrement() { - if let value = self.value { + if let value { self.value = value - 1 } } diff --git a/Sources/Basics/FileSystem/VirtualFileSystem.swift b/Sources/Basics/FileSystem/VirtualFileSystem.swift index 31fcaf1d83f..5881d7f9cdd 100644 --- a/Sources/Basics/FileSystem/VirtualFileSystem.swift +++ b/Sources/Basics/FileSystem/VirtualFileSystem.swift @@ -215,7 +215,7 @@ public class VirtualFileSystem: FileSystem { switch node { case .directory(_, _, _): throw Errors.notAFile(path: path) case .file(_, _, _, let contents): - if let contents = contents { + if let contents { return ByteString(contents) } else { return "" diff --git a/Sources/Basics/HTTPClient/URLSessionHTTPClient.swift b/Sources/Basics/HTTPClient/URLSessionHTTPClient.swift index b1bc4a5cd4e..98a2819b432 100644 --- a/Sources/Basics/HTTPClient/URLSessionHTTPClient.swift +++ b/Sources/Basics/HTTPClient/URLSessionHTTPClient.swift @@ -157,7 +157,7 @@ private class DataTaskManager: NSObject, URLSessionDataDelegate { guard let task = self.tasks.removeValue(forKey: task.taskIdentifier) else { return } - if let error = error { + if let error { task.completionHandler(.failure(error)) } else if let response = task.response { task.completionHandler(.success(response.response(body: task.buffer))) @@ -294,7 +294,7 @@ private class DownloadTaskManager: NSObject, URLSessionDownloadDelegate { } do { - if let error = error { + if let error { throw HTTPClientError.downloadError("\(error)") } else if let error = task.moveFileError { throw error diff --git a/Sources/Basics/SQLite.swift b/Sources/Basics/SQLite.swift index 8614b604468..f547c35f3fe 100644 --- a/Sources/Basics/SQLite.swift +++ b/Sources/Basics/SQLite.swift @@ -87,7 +87,7 @@ public final class SQLite { sqlite3_free(query) - if let err = err { + if let err { let errorString = String(cString: err) sqlite3_free(err) throw StringError(errorString) @@ -286,7 +286,7 @@ public final class SQLite { case "database or disk is full": throw Errors.databaseFull default: - if let prefix = prefix { + if let prefix { description = "\(prefix): \(description)" } throw StringError(description) @@ -309,8 +309,8 @@ private func sqlite_callback( _ columns: UnsafeMutablePointer?>?, _ columnNames: UnsafeMutablePointer?>? ) -> Int32 { - guard let ctx = ctx else { return 0 } - guard let columnNames = columnNames, let columns = columns else { return 0 } + guard let ctx else { return 0 } + guard let columnNames, let columns else { return 0 } let numColumns = Int(numColumns) var result: [SQLite.Column] = [] diff --git a/Sources/Basics/SwiftVersion.swift b/Sources/Basics/SwiftVersion.swift index 968f969cdda..b92fa0c3250 100644 --- a/Sources/Basics/SwiftVersion.swift +++ b/Sources/Basics/SwiftVersion.swift @@ -35,7 +35,7 @@ public struct SwiftVersion { if self.isDevelopment { result += "-dev" } - if let buildIdentifier = self.buildIdentifier { + if let buildIdentifier { result += " (" + buildIdentifier + ")" } return result diff --git a/Sources/Build/BuildDescription/ClangTargetBuildDescription.swift b/Sources/Build/BuildDescription/ClangTargetBuildDescription.swift index 03e5e29389c..ca2a904dc39 100644 --- a/Sources/Build/BuildDescription/ClangTargetBuildDescription.swift +++ b/Sources/Build/BuildDescription/ClangTargetBuildDescription.swift @@ -231,7 +231,7 @@ public final class ClangTargetBuildDescription { // Include the path to the resource header unless the arguments are // being evaluated for a C file. A C file cannot depend on the resource // accessor header due to it exporting a Foundation type (`NSBundle`). - if let resourceAccessorHeaderFile = self.resourceAccessorHeaderFile, !isC { + if let resourceAccessorHeaderFile, !isC { args += ["-include", resourceAccessorHeaderFile.pathString] } @@ -304,7 +304,7 @@ public final class ClangTargetBuildDescription { /// Generate the resource bundle accessor, if appropriate. private func generateResourceAccessor() throws { // Only generate access when we have a bundle and ObjC files. - guard let bundlePath = self.bundlePath, clangTarget.sources.containsObjcFiles else { return } + guard let bundlePath, clangTarget.sources.containsObjcFiles else { return } // Compute the basename of the bundle. let bundleBasename = bundlePath.basename diff --git a/Sources/Build/BuildDescription/SwiftTargetBuildDescription.swift b/Sources/Build/BuildDescription/SwiftTargetBuildDescription.swift index 4e3303e3ddf..88db228c96a 100644 --- a/Sources/Build/BuildDescription/SwiftTargetBuildDescription.swift +++ b/Sources/Build/BuildDescription/SwiftTargetBuildDescription.swift @@ -240,7 +240,7 @@ public final class SwiftTargetBuildDescription { self.toolsVersion = toolsVersion self.buildParameters = buildParameters // Unless mentioned explicitly, use the target type to determine if this is a test target. - if let testTargetRole = testTargetRole { + if let testTargetRole { self.testTargetRole = testTargetRole } else if target.type == .test { self.testTargetRole = .default @@ -336,7 +336,7 @@ public final class SwiftTargetBuildDescription { /// Generate the resource bundle accessor, if appropriate. private func generateResourceAccessor() throws { // Do nothing if we're not generating a bundle. - guard let bundlePath = self.bundlePath else { return } + guard let bundlePath else { return } let mainPathSubstitution: String if self.buildParameters.triple.isWASI() { diff --git a/Sources/Build/BuildOperation.swift b/Sources/Build/BuildOperation.swift index 7eeb4139dcc..cb02a4ce6f0 100644 --- a/Sources/Build/BuildOperation.swift +++ b/Sources/Build/BuildOperation.swift @@ -319,7 +319,7 @@ public final class BuildOperation: PackageStructureDelegate, SPMBuildCore.BuildS // Compiles a single plugin, emitting its output and throwing an error if it // fails. func compilePlugin(_ plugin: PluginDescription) throws { - guard let pluginConfiguration = self.pluginConfiguration else { + guard let pluginConfiguration else { throw InternalError("unknown plugin script runner") } // Compile the plugin, getting back a PluginCompilationResult. @@ -408,7 +408,7 @@ public final class BuildOperation: PackageStructureDelegate, SPMBuildCore.BuildS let buildToolPluginInvocationResults: [ResolvedTarget: [BuildToolPluginInvocationResult]] let prebuildCommandResults: [ResolvedTarget: [PrebuildCommandResult]] // Invoke any build tool plugins in the graph to generate prebuild commands and build commands. - if let pluginConfiguration = self.pluginConfiguration { + if let pluginConfiguration { let buildOperationForPluginDependencies = try BuildOperation(buildParameters: self.buildParameters.withDestination(self.buildParameters.hostTriple), cacheBuildManifest: false, packageGraphLoader: { return graph }, additionalFileRules: self.additionalFileRules, pkgConfigDirectories: self.pkgConfigDirectories, outputStream: self.outputStream, logLevel: self.logLevel, fileSystem: self.fileSystem, observabilityScope: self.observabilityScope) buildToolPluginInvocationResults = try graph.invokeBuildToolPlugins( outputDir: pluginConfiguration.workDirectory.appending("outputs"), diff --git a/Sources/Build/BuildOperationBuildSystemDelegateHandler.swift b/Sources/Build/BuildOperationBuildSystemDelegateHandler.swift index 3165f3768dd..0c23e695b14 100644 --- a/Sources/Build/BuildOperationBuildSystemDelegateHandler.swift +++ b/Sources/Build/BuildOperationBuildSystemDelegateHandler.swift @@ -916,7 +916,7 @@ private struct CommandTaskTracker { let fileNameStartIndex = command.description.index(after: lastDirectorySeparatorIndex) let fileName = command.description[fileNameStartIndex...] - if let targetName = targetName { + if let targetName { return "\(action) \(targetName) \(fileName)" } else { return "\(action) \(fileName)" diff --git a/Sources/Build/LLBuildManifestBuilder.swift b/Sources/Build/LLBuildManifestBuilder.swift index c298f9ec79d..01dc7db6e07 100644 --- a/Sources/Build/LLBuildManifestBuilder.swift +++ b/Sources/Build/LLBuildManifestBuilder.swift @@ -292,10 +292,10 @@ extension LLBuildManifestBuilder { // Check if an explicit pre-build dependency job has already been // added as a part of this build. - if let uniqueDependencyTracker = uniqueExplicitDependencyTracker, + if let uniqueExplicitDependencyTracker, job.isExplicitDependencyPreBuildJob { - if try !uniqueDependencyTracker.registerExplicitDependencyBuildJob(job) { + if try !uniqueExplicitDependencyTracker.registerExplicitDependencyBuildJob(job) { // This is a duplicate of a previously-seen identical job. // Skip adding it to the manifest continue @@ -619,10 +619,10 @@ extension LLBuildManifestBuilder { // Depend on the binary for executable targets. if target.type == .executable { // FIXME: Optimize. - let _product = try plan.graph.allProducts.first { + let product = try plan.graph.allProducts.first { try $0.type == .executable && $0.executableTarget == target } - if let product = _product { + if let product { guard let planProduct = plan.productMap[product] else { throw InternalError("unknown product \(product)") } @@ -855,8 +855,8 @@ extension LLBuildManifestBuilder { // Add language standard flag if needed. if let ext = path.source.extension { for (standard, validExtensions) in standards { - if let languageStandard = standard, validExtensions.contains(ext) { - args += ["-std=\(languageStandard)"] + if let standard, validExtensions.contains(ext) { + args += ["-std=\(standard)"] } } } diff --git a/Sources/Commands/PackageTools/ArchiveSource.swift b/Sources/Commands/PackageTools/ArchiveSource.swift index 96cff0a07f2..ff4b74f61a7 100644 --- a/Sources/Commands/PackageTools/ArchiveSource.swift +++ b/Sources/Commands/PackageTools/ArchiveSource.swift @@ -36,7 +36,7 @@ extension SwiftPackageTool { let packageDirectory = try globalOptions.locations.packageDirectory ?? swiftTool.getPackageRoot() let archivePath: AbsolutePath - if let output = output { + if let output { archivePath = output } else { let graph = try swiftTool.loadPackageGraph() diff --git a/Sources/Commands/PackageTools/Learn.swift b/Sources/Commands/PackageTools/Learn.swift index 4bdf1eec04d..2ecf75eeee3 100644 --- a/Sources/Commands/PackageTools/Learn.swift +++ b/Sources/Commands/PackageTools/Learn.swift @@ -33,7 +33,7 @@ extension SwiftPackageTool { .map { try AbsolutePath(validating: $0, relativeTo: directory) } .filter { fileSystem.isFile($0) } - guard let fileExtension = fileExtension else { + guard let fileExtension else { return files } diff --git a/Sources/Commands/PackageTools/ToolsVersionCommand.swift b/Sources/Commands/PackageTools/ToolsVersionCommand.swift index 2894ed867a4..951ac0947fb 100644 --- a/Sources/Commands/PackageTools/ToolsVersionCommand.swift +++ b/Sources/Commands/PackageTools/ToolsVersionCommand.swift @@ -40,7 +40,7 @@ struct ToolsVersionCommand: SwiftCommand { var toolsVersionMode: ToolsVersionMode { // TODO: enforce exclusivity - if let set = set { + if let set { return .set(set) } else if setCurrent { return .setCurrent diff --git a/Sources/Commands/Snippets/CardStack.swift b/Sources/Commands/Snippets/CardStack.swift index cd4a7c3e607..538c9b32ec0 100644 --- a/Sources/Commands/Snippets/CardStack.swift +++ b/Sources/Commands/Snippets/CardStack.swift @@ -58,7 +58,7 @@ struct CardStack { } func askForLineInput(prompt: String?) -> String? { - if let prompt = prompt { + if let prompt { print(brightBlack { prompt }.terminalString()) } terminal.write(">>> ", inColor: .green, bold: true) @@ -99,7 +99,7 @@ struct CardStack { break askForLine case let .pop(error): cards.removeLast() - if let error = error { + if let error { self.swiftTool.observabilityScope.emit(error) needsToClearScreen = false } else { diff --git a/Sources/Commands/SwiftBuildTool.swift b/Sources/Commands/SwiftBuildTool.swift index 5c44e7335d6..7560bca9cbb 100644 --- a/Sources/Commands/SwiftBuildTool.swift +++ b/Sources/Commands/SwiftBuildTool.swift @@ -43,12 +43,12 @@ struct BuildToolOptions: ParsableArguments { func buildSubset(observabilityScope: ObservabilityScope) -> BuildSubset? { var allSubsets: [BuildSubset] = [] - if let productName = product { - allSubsets.append(.product(productName)) + if let product { + allSubsets.append(.product(product)) } - if let targetName = target { - allSubsets.append(.target(targetName)) + if let target { + allSubsets.append(.target(target)) } if buildTests { diff --git a/Sources/Commands/SwiftTestTool.swift b/Sources/Commands/SwiftTestTool.swift index 42cd13745c1..6de43c73a16 100644 --- a/Sources/Commands/SwiftTestTool.swift +++ b/Sources/Commands/SwiftTestTool.swift @@ -668,13 +668,13 @@ final class TestRunner { throw TestError.xctestNotAvailable } args = [xctestPath.pathString] - if let xctestArg = xctestArg { + if let xctestArg { args += ["-XCTest", xctestArg] } args += [testPath.pathString] #else args += [testPath.description] - if let xctestArg = xctestArg { + if let xctestArg { args += [xctestArg] } #endif diff --git a/Sources/Commands/Utilities/APIDigester.swift b/Sources/Commands/Utilities/APIDigester.swift index 244251eefd6..2ca82a63c13 100644 --- a/Sources/Commands/Utilities/APIDigester.swift +++ b/Sources/Commands/Utilities/APIDigester.swift @@ -226,7 +226,7 @@ public struct SwiftAPIDigester { "-module", module ] args.append(contentsOf: try buildPlan.createAPIToolCommonArgs(includeLibrarySearchPaths: false)) - if let breakageAllowlistPath = breakageAllowlistPath { + if let breakageAllowlistPath { args.append(contentsOf: ["-breakage-allowlist-path", breakageAllowlistPath.pathString]) } diff --git a/Sources/Commands/Utilities/DescribedPackage.swift b/Sources/Commands/Utilities/DescribedPackage.swift index 5a884210f5c..b9a8fd4f5e3 100644 --- a/Sources/Commands/Utilities/DescribedPackage.swift +++ b/Sources/Commands/Utilities/DescribedPackage.swift @@ -350,7 +350,7 @@ public struct PlainTextEncoder { private mutating func emit(_ key: CodingKey, _ value: String?) { outputStream <<< String(repeating: " ", count: codingPath.count) outputStream <<< displayName(for: key) <<< ":" - if let value = value { outputStream <<< " " <<< value } + if let value { outputStream <<< " " <<< value } outputStream <<< "\n" } mutating func encodeNil(forKey key: Key) throws { emit(key, "nil") } diff --git a/Sources/CoreCommands/SwiftTool.swift b/Sources/CoreCommands/SwiftTool.swift index 3e8cc4febb3..2e515d61ca8 100644 --- a/Sources/CoreCommands/SwiftTool.swift +++ b/Sources/CoreCommands/SwiftTool.swift @@ -114,8 +114,8 @@ extension SwiftCommand { // wait for all observability items to process swiftTool.waitForObservabilityEvents(timeout: .now() + 5) - if let error = toolError { - throw error + if let toolError { + throw toolError } } } @@ -150,8 +150,8 @@ extension AsyncSwiftCommand { // wait for all observability items to process swiftTool.waitForObservabilityEvents(timeout: .now() + 5) - if let error = toolError { - throw error + if let toolError { + throw toolError } } } @@ -690,7 +690,7 @@ public final class SwiftTool { customLogLevel: Basics.Diagnostic.Severity? = .none, customObservabilityScope: ObservabilityScope? = .none ) throws -> BuildSystem { - guard let buildSystemProvider = buildSystemProvider else { + guard let buildSystemProvider else { fatalError("build system provider not initialized") } diff --git a/Sources/CoreCommands/SwiftToolObservabilityHandler.swift b/Sources/CoreCommands/SwiftToolObservabilityHandler.swift index edadaec2f6e..a40786fb1a3 100644 --- a/Sources/CoreCommands/SwiftToolObservabilityHandler.swift +++ b/Sources/CoreCommands/SwiftToolObservabilityHandler.swift @@ -181,7 +181,7 @@ private struct InteractiveWriter { /// Write the string to the contained terminal or stream. func write(_ string: String, inColor color: TerminalController.Color = .noColor, bold: Bool = false) { - if let term = self.term { + if let term { term.write(string, inColor: color, bold: bold) } else { string.write(to: stream) @@ -190,7 +190,7 @@ private struct InteractiveWriter { } func format(_ string: String, inColor color: TerminalController.Color = .noColor, bold: Bool = false) -> String { - if let term = self.term { + if let term { return term.wrap(string, inColor: color, bold: bold) } else { return string @@ -202,7 +202,7 @@ private struct InteractiveWriter { // we should remove this as we make use of the new scope and metadata to provide better contextual information extension ObservabilityMetadata { fileprivate var diagnosticPrefix: String? { - if let packageIdentity = self.packageIdentity { + if let packageIdentity { return "'\(packageIdentity)'" } else { return .none diff --git a/Sources/CrossCompilationDestinationsTool/Configuration/SetConfiguration.swift b/Sources/CrossCompilationDestinationsTool/Configuration/SetConfiguration.swift index 933006a580e..9155778c709 100644 --- a/Sources/CrossCompilationDestinationsTool/Configuration/SetConfiguration.swift +++ b/Sources/CrossCompilationDestinationsTool/Configuration/SetConfiguration.swift @@ -87,18 +87,18 @@ struct SetConfiguration: ConfigurationCommand { let currentWorkingDirectory = fileSystem.currentWorkingDirectory - if let sdkRootPath = sdkRootPath { + if let sdkRootPath { configuration.sdkRootPath = try AbsolutePath(validating: sdkRootPath, relativeTo: currentWorkingDirectory) updatedProperties.append(CodingKeys.sdkRootPath.stringValue) } - if let swiftResourcesPath = swiftResourcesPath { + if let swiftResourcesPath { configuration.swiftResourcesPath = try AbsolutePath(validating: swiftResourcesPath, relativeTo: currentWorkingDirectory) updatedProperties.append(CodingKeys.swiftResourcesPath.stringValue) } - if let swiftStaticResourcesPath = swiftStaticResourcesPath { + if let swiftStaticResourcesPath { configuration.swiftResourcesPath = try AbsolutePath(validating: swiftStaticResourcesPath, relativeTo: currentWorkingDirectory) updatedProperties.append(CodingKeys.swiftStaticResourcesPath.stringValue) @@ -147,7 +147,7 @@ struct SetConfiguration: ConfigurationCommand { extension AbsolutePath { fileprivate init(validating string: String, relativeTo basePath: AbsolutePath?) throws { - if let basePath = basePath { + if let basePath { try self.init(validating: string, relativeTo: basePath) } else { try self.init(validating: string) diff --git a/Sources/CrossCompilationDestinationsTool/DestinationCommand.swift b/Sources/CrossCompilationDestinationsTool/DestinationCommand.swift index 937e625e576..9533ff95d57 100644 --- a/Sources/CrossCompilationDestinationsTool/DestinationCommand.swift +++ b/Sources/CrossCompilationDestinationsTool/DestinationCommand.swift @@ -84,8 +84,8 @@ extension DestinationCommand { // wait for all observability items to process observabilityHandler.wait(timeout: .now() + 5) - if let error = commandError { - throw error + if let commandError { + throw commandError } } } diff --git a/Sources/LLBuildManifest/Tools.swift b/Sources/LLBuildManifest/Tools.swift index 7291681e8ea..f3e3b4a904d 100644 --- a/Sources/LLBuildManifest/Tools.swift +++ b/Sources/LLBuildManifest/Tools.swift @@ -142,7 +142,7 @@ public struct ShellTool: ToolProtocol { if !environment.isEmpty { stream["env"] = environment } - if let workingDirectory = workingDirectory { + if let workingDirectory { stream["working-directory"] = workingDirectory } if allowMissingInputs { @@ -177,7 +177,7 @@ public struct ClangTool: ToolProtocol { public func write(to stream: ManifestToolStream) { stream["description"] = description stream["args"] = arguments - if let dependencies = dependencies { + if let dependencies { stream["deps"] = dependencies } } @@ -279,7 +279,7 @@ public struct SwiftCompilerTool: ToolProtocol { public func write(to stream: ManifestToolStream) { stream["executable"] = executable stream["module-name"] = moduleName - if let moduleAliases = moduleAliases { + if let moduleAliases { // Format the key and value to pass to -module-alias flag let formatted = moduleAliases.map {$0.key + "=" + $0.value} stream["module-aliases"] = formatted diff --git a/Sources/PackageCollections/PackageCollections+Validation.swift b/Sources/PackageCollections/PackageCollections+Validation.swift index ba2f88dd6a5..bfd48e75984 100644 --- a/Sources/PackageCollections/PackageCollections+Validation.swift +++ b/Sources/PackageCollections/PackageCollections+Validation.swift @@ -42,7 +42,7 @@ extension Model.CollectionSource { if absolutePath == nil { appendMessage(.error("Invalid file path: \(self.url.path). It must be an absolute file system path.")) - } else if let absolutePath = absolutePath, !fileSystem.exists(absolutePath) { + } else if let absolutePath, !fileSystem.exists(absolutePath) { appendMessage(.error("\(self.url.path) is either a non-local path or the file does not exist.")) } } diff --git a/Sources/PackageCollections/PackageCollections.swift b/Sources/PackageCollections/PackageCollections.swift index a6426dc14b3..7ebbc53efe3 100644 --- a/Sources/PackageCollections/PackageCollections.swift +++ b/Sources/PackageCollections/PackageCollections.swift @@ -565,7 +565,7 @@ public struct PackageCollections: PackageCollectionsProtocol, Closable { callback(.failure(error)) case .success(let sources): var collectionIdentifiers = sources.map { Model.CollectionIdentifier(from: $0) } - if let collections = collections { + if let collections { collectionIdentifiers = collectionIdentifiers.filter { collections.contains($0) } } if collectionIdentifiers.isEmpty { @@ -579,7 +579,7 @@ public struct PackageCollections: PackageCollectionsProtocol, Closable { callback(.failure(error)) case .success(let packagesCollections): let matches: [PackageCollectionsModel.Package] - if let location = location { + if let location { // A package identity can be associated with multiple repository URLs matches = packagesCollections.packages.filter { CanonicalPackageLocation($0.location) == CanonicalPackageLocation(location) } } diff --git a/Sources/PackageCollections/Providers/GitHubPackageMetadataProvider.swift b/Sources/PackageCollections/Providers/GitHubPackageMetadataProvider.swift index f7a9a6a86ad..4aa7dae257a 100644 --- a/Sources/PackageCollections/Providers/GitHubPackageMetadataProvider.swift +++ b/Sources/PackageCollections/Providers/GitHubPackageMetadataProvider.swift @@ -190,7 +190,7 @@ struct GitHubPackageMetadataProvider: PackageMetadataProvider, Closable { private func createContext(apiHost: String?, error: Error?) -> PackageMetadataProviderContext? { // We can't do anything if we can't determine API host - guard let apiHost = apiHost else { + guard let apiHost else { return nil } @@ -202,7 +202,7 @@ struct GitHubPackageMetadataProvider: PackageMetadataProvider, Closable { return nil } - guard let error = error else { + guard let error else { // It's possible for the request to complete successfully without auth token configured, in // which case we will hit the API limit much more easily, so we should always communicate // auth token state to the caller (e.g., so it can prompt user to configure auth token). diff --git a/Sources/PackageCollections/Storage/SQLitePackageCollectionsStorage.swift b/Sources/PackageCollections/Storage/SQLitePackageCollectionsStorage.swift index 3c803394511..9e2c1c70a78 100644 --- a/Sources/PackageCollections/Storage/SQLitePackageCollectionsStorage.swift +++ b/Sources/PackageCollections/Storage/SQLitePackageCollectionsStorage.swift @@ -228,7 +228,7 @@ final class SQLitePackageCollectionsStorage: PackageCollectionsStorage, Closable callback: @escaping (Result<[Model.Collection], Error>) -> Void) { // try read to cache let cached = identifiers?.compactMap { self.cache[$0] } - if let cached = cached, cached.count > 0, cached.count == identifiers?.count { + if let cached, cached.count > 0, cached.count == identifiers?.count { return callback(.success(cached)) } @@ -236,7 +236,7 @@ final class SQLitePackageCollectionsStorage: PackageCollectionsStorage, Closable DispatchQueue.sharedConcurrent.async { do { var blobs = [Data]() - if let identifiers = identifiers { + if let identifiers { var index = 0 while index < identifiers.count { let slice = identifiers[index ..< min(index + self.configuration.batchSize, identifiers.count)] diff --git a/Sources/PackageCollectionsSigning/Certificate/CertificatePolicy.swift b/Sources/PackageCollectionsSigning/Certificate/CertificatePolicy.swift index 213c5f939ee..591e277ec19 100644 --- a/Sources/PackageCollectionsSigning/Certificate/CertificatePolicy.swift +++ b/Sources/PackageCollectionsSigning/Certificate/CertificatePolicy.swift @@ -82,10 +82,10 @@ extension CertificatePolicy { return wrappedCallback(.failure(CertificatePolicyError.trustSetupFailure)) } - if let anchorCerts = anchorCerts { + if let anchorCerts { SecTrustSetAnchorCertificates(trust, anchorCerts.map { $0.underlying } as CFArray) } - if let verifyDate = verifyDate { + if let verifyDate { SecTrustSetVerifyDate(trust, verifyDate as CFDate) } @@ -167,7 +167,7 @@ extension CertificatePolicy { } var ctxFlags: CInt = 0 - if let verifyDate = verifyDate { + if let verifyDate { CCryptoBoringSSL_X509_STORE_CTX_set_time(x509StoreCtx, 0, numericCast(Int(verifyDate.timeIntervalSince1970))) ctxFlags = ctxFlags | X509_V_FLAG_USE_CHECK_TIME } @@ -219,7 +219,7 @@ extension CertificatePolicy { return nil } - if let error = error { + if let error { return wrappedCallback(.failure(error)) } @@ -372,7 +372,7 @@ private struct BoringSSLOCSPClient { let response = d2i_OCSP_RESPONSE_bio(bio, nil) defer { OCSP_RESPONSE_free(response) } - guard let response = response else { + guard let response else { results.append(.failure(OCSPError.responseConversionFailure)) return } @@ -380,7 +380,7 @@ private struct BoringSSLOCSPClient { let basicResp = OCSP_response_get1_basic(response) defer { OCSP_BASICRESP_free(basicResp) } - guard let basicResp = basicResp else { + guard let basicResp else { results.append(.failure(OCSPError.responseConversionFailure)) return } @@ -628,10 +628,10 @@ struct DefaultCertificatePolicy: CertificatePolicy { fatalError("Unsupported: \(#function)") #else var trustedRoots = [Certificate]() - if let trustedRootCertsDir = trustedRootCertsDir { + if let trustedRootCertsDir { trustedRoots.append(contentsOf: Self.loadCerts(at: trustedRootCertsDir ,observabilityScope: observabilityScope)) } - if let additionalTrustedRootCerts = additionalTrustedRootCerts { + if let additionalTrustedRootCerts { trustedRoots.append(contentsOf: additionalTrustedRootCerts) } self.trustedRoots = trustedRoots.isEmpty ? nil : trustedRoots @@ -658,7 +658,7 @@ struct DefaultCertificatePolicy: CertificatePolicy { do { // Check if subject user ID matches - if let expectedSubjectUserID = self.expectedSubjectUserID { + if let expectedSubjectUserID { guard try certChain[0].subject().userID == expectedSubjectUserID else { return wrappedCallback(.failure(CertificatePolicyError.subjectUserIDMismatch)) } @@ -720,10 +720,10 @@ struct AppleSwiftPackageCollectionCertificatePolicy: CertificatePolicy { fatalError("Unsupported: \(#function)") #else var trustedRoots = [Certificate]() - if let trustedRootCertsDir = trustedRootCertsDir { + if let trustedRootCertsDir { trustedRoots.append(contentsOf: Self.loadCerts(at: trustedRootCertsDir, observabilityScope: observabilityScope)) } - if let additionalTrustedRootCerts = additionalTrustedRootCerts { + if let additionalTrustedRootCerts { trustedRoots.append(contentsOf: additionalTrustedRootCerts) } self.trustedRoots = trustedRoots.isEmpty ? nil : trustedRoots @@ -754,7 +754,7 @@ struct AppleSwiftPackageCollectionCertificatePolicy: CertificatePolicy { do { // Check if subject user ID matches - if let expectedSubjectUserID = self.expectedSubjectUserID { + if let expectedSubjectUserID { guard try certChain[0].subject().userID == expectedSubjectUserID else { return wrappedCallback(.failure(CertificatePolicyError.subjectUserIDMismatch)) } @@ -824,10 +824,10 @@ struct AppleDistributionCertificatePolicy: CertificatePolicy { fatalError("Unsupported: \(#function)") #else var trustedRoots = [Certificate]() - if let trustedRootCertsDir = trustedRootCertsDir { + if let trustedRootCertsDir { trustedRoots.append(contentsOf: Self.loadCerts(at: trustedRootCertsDir, observabilityScope: observabilityScope)) } - if let additionalTrustedRootCerts = additionalTrustedRootCerts { + if let additionalTrustedRootCerts { trustedRoots.append(contentsOf: additionalTrustedRootCerts) } self.trustedRoots = trustedRoots.isEmpty ? nil : trustedRoots @@ -858,7 +858,7 @@ struct AppleDistributionCertificatePolicy: CertificatePolicy { do { // Check if subject user ID matches - if let expectedSubjectUserID = self.expectedSubjectUserID { + if let expectedSubjectUserID { guard try certChain[0].subject().userID == expectedSubjectUserID else { return wrappedCallback(.failure(CertificatePolicyError.subjectUserIDMismatch)) } @@ -907,8 +907,8 @@ extension CertificatePolicy { } } - if let error = extensionError { - throw error + if let extensionError { + throw extensionError } return false } diff --git a/Sources/PackageCollectionsTool/SwiftPackageCollectionsTool.swift b/Sources/PackageCollectionsTool/SwiftPackageCollectionsTool.swift index ca9377e5045..3312fadcb43 100644 --- a/Sources/PackageCollectionsTool/SwiftPackageCollectionsTool.swift +++ b/Sources/PackageCollectionsTool/SwiftPackageCollectionsTool.swift @@ -257,7 +257,7 @@ public struct SwiftPackageCollectionsTool: ParsableCommand { var globalOptions: GlobalOptions private func printVersion(_ version: PackageCollectionsModel.Package.Version?) -> String? { - guard let version = version else { + guard let version else { return nil } guard let defaultManifest = version.defaultManifest else { @@ -371,7 +371,7 @@ private func indent(levels: Int = 1) -> String { } private func optionalRow(_ title: String, _ contents: String?, indentationLevel: Int = 1) -> String { - if let contents = contents, !contents.isEmpty { + if let contents, !contents.isEmpty { return "\n\(indent(levels: indentationLevel))\(title): \(contents)" } else { return "" diff --git a/Sources/PackageDescription/BuildSettings.swift b/Sources/PackageDescription/BuildSettings.swift index f1190884f0c..556f7cde7c0 100644 --- a/Sources/PackageDescription/BuildSettings.swift +++ b/Sources/PackageDescription/BuildSettings.swift @@ -151,7 +151,7 @@ public struct CSetting { @available(_PackageDescription, introduced: 5.0) public static func define(_ name: String, to value: String? = nil, _ condition: BuildSettingCondition? = nil) -> CSetting { var settingValue = name - if let value = value { + if let value { settingValue += "=" + value } return CSetting(name: "define", value: [settingValue], condition: condition) @@ -220,7 +220,7 @@ public struct CXXSetting { @available(_PackageDescription, introduced: 5.0) public static func define(_ name: String, to value: String? = nil, _ condition: BuildSettingCondition? = nil) -> CXXSetting { var settingValue = name - if let value = value { + if let value { settingValue += "=" + value } return CXXSetting(name: "define", value: [settingValue], condition: condition) @@ -381,7 +381,7 @@ public struct SwiftSetting { _ condition: BuildSettingCondition? = nil ) -> SwiftSetting { var values: [String] = [mode.rawValue] - if let version = version { + if let version { values.append(version) } return SwiftSetting( diff --git a/Sources/PackageDescription/PackageDescription.swift b/Sources/PackageDescription/PackageDescription.swift index 478af0e339c..36f53ff03cd 100644 --- a/Sources/PackageDescription/PackageDescription.swift +++ b/Sources/PackageDescription/PackageDescription.swift @@ -448,7 +448,7 @@ var errors: [String] = [] private var dumpInfo: (package: Package, handle: Int)? private func dumpPackageAtExit(_ package: Package, to handle: Int) { let dump: @convention(c) () -> Void = { - guard let dumpInfo = dumpInfo else { return } + guard let dumpInfo else { return } let hFile: HANDLE = HANDLE(bitPattern: dumpInfo.handle)! // NOTE: `_open_osfhandle` transfers ownership of the HANDLE to the file @@ -472,7 +472,7 @@ private func dumpPackageAtExit(_ package: Package, to handle: Int) { private var dumpInfo: (package: Package, fileDesc: Int32)? private func dumpPackageAtExit(_ package: Package, to fileDesc: Int32) { func dump() { - guard let dumpInfo = dumpInfo else { return } + guard let dumpInfo else { return } guard let fd = fdopen(dumpInfo.fileDesc, "w") else { return } fputs(manifestToJSON(dumpInfo.package), fd) fclose(fd) diff --git a/Sources/PackageDescription/Version+StringLiteralConvertible.swift b/Sources/PackageDescription/Version+StringLiteralConvertible.swift index ce59a9a4df4..58dbc187e39 100644 --- a/Sources/PackageDescription/Version+StringLiteralConvertible.swift +++ b/Sources/PackageDescription/Version+StringLiteralConvertible.swift @@ -71,7 +71,7 @@ extension Version: LosslessStringConvertible { self.minor = minor self.patch = patch - if let prereleaseDelimiterIndex = prereleaseDelimiterIndex { + if let prereleaseDelimiterIndex { let prereleaseStartIndex = versionString.index(after: prereleaseDelimiterIndex) let prereleaseIdentifiers = versionString[prereleaseStartIndex..<(metadataDelimiterIndex ?? versionString.endIndex)].split(separator: ".", omittingEmptySubsequences: false) guard prereleaseIdentifiers.allSatisfy({ $0.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "-" })}) else { return nil } @@ -80,7 +80,7 @@ extension Version: LosslessStringConvertible { self.prereleaseIdentifiers = [] } - if let metadataDelimiterIndex = metadataDelimiterIndex { + if let metadataDelimiterIndex { let metadataStartIndex = versionString.index(after: metadataDelimiterIndex) let buildMetadataIdentifiers = versionString[metadataStartIndex...].split(separator: ".", omittingEmptySubsequences: false) guard buildMetadataIdentifiers.allSatisfy({ $0.allSatisfy({ $0.isLetter || $0.isNumber || $0 == "-" })}) else { return nil } diff --git a/Sources/PackageDescription/Version.swift b/Sources/PackageDescription/Version.swift index 48fa370b64c..661c4f74b3e 100644 --- a/Sources/PackageDescription/Version.swift +++ b/Sources/PackageDescription/Version.swift @@ -143,7 +143,7 @@ extension Version: Comparable { let lhsNumericPrereleaseIdentifier = Int(lhsPrereleaseIdentifier) let rhsNumericPrereleaseIdentifier = Int(rhsPrereleaseIdentifier) - if let lhsNumericPrereleaseIdentifier = lhsNumericPrereleaseIdentifier, + if let lhsNumericPrereleaseIdentifier, let rhsNumericPrereleaseIdentifier = rhsNumericPrereleaseIdentifier { return lhsNumericPrereleaseIdentifier < rhsNumericPrereleaseIdentifier } else if lhsNumericPrereleaseIdentifier != nil { diff --git a/Sources/PackageGraph/ModuleAliasTracker.swift b/Sources/PackageGraph/ModuleAliasTracker.swift index 53a568a5f93..8ae51381500 100644 --- a/Sources/PackageGraph/ModuleAliasTracker.swift +++ b/Sources/PackageGraph/ModuleAliasTracker.swift @@ -122,7 +122,7 @@ class ModuleAliasTracker { // pkgID is not nil here so can be force unwrapped pkgID = childToParentID[pkgID!] } - guard let rootPkg = rootPkg else { return } + guard let rootPkg else { return } if let productToAllTargets = idToProductToAllTargets[rootPkg] { // First, propagate aliases upstream diff --git a/Sources/PackageGraph/PackageGraph+Loading.swift b/Sources/PackageGraph/PackageGraph+Loading.swift index c249766ffc1..d77eba66521 100644 --- a/Sources/PackageGraph/PackageGraph+Loading.swift +++ b/Sources/PackageGraph/PackageGraph+Loading.swift @@ -468,7 +468,7 @@ private func createResolvedPackages( // Find the product in this package's dependency products. // Look it up by ID if module aliasing is used, otherwise by name. let product = lookupByProductIDs ? productDependencyMap[productRef.identity] : productDependencyMap[productRef.name] - guard let product = product else { + guard let product else { // Only emit a diagnostic if there are no other diagnostics. // This avoids flooding the diagnostics with product not // found errors when there are more important errors to @@ -744,8 +744,8 @@ private class ResolvedBuilder { /// Note that once the object is constructed, future calls to /// this method will return the same object. final func construct() throws -> T { - if let constructedObject = _constructedObject { - return constructedObject + if let _constructedObject { + return _constructedObject } let constructedObject = try self.constructImpl() _constructedObject = constructedObject diff --git a/Sources/PackageGraph/PackageGraph.swift b/Sources/PackageGraph/PackageGraph.swift index 9fc91f807ab..e571e1c3f16 100644 --- a/Sources/PackageGraph/PackageGraph.swift +++ b/Sources/PackageGraph/PackageGraph.swift @@ -249,8 +249,8 @@ extension PackageGraphError: CustomStringConvertible { return "multiple aliases: ['\(aliases.joined(separator: "', '"))'] found for target '\(target)' in product '\(product)' from package '\(package)'" case .unsupportedPluginDependency(let targetName, let dependencyName, let dependencyType, let dependencyPackage): var trailingMsg = "" - if let depPkg = dependencyPackage { - trailingMsg = " from package '\(depPkg)'" + if let dependencyPackage { + trailingMsg = " from package '\(dependencyPackage)'" } return "plugin '\(targetName)' cannot depend on '\(dependencyName)' of type '\(dependencyType)'\(trailingMsg); this dependency is unsupported" } diff --git a/Sources/PackageGraph/PackageGraphRoot.swift b/Sources/PackageGraph/PackageGraphRoot.swift index 4da7830140d..78a32b2dda8 100644 --- a/Sources/PackageGraph/PackageGraphRoot.swift +++ b/Sources/PackageGraph/PackageGraphRoot.swift @@ -71,9 +71,9 @@ public struct PackageGraphRoot { // But in the future it might be worth providing a way of declaring them in the manifest without a dummy target, // at which time the current special casing can be deprecated. var adjustedDependencies = input.dependencies - if let product = explicitProduct { + if let explicitProduct { for dependency in manifests.values.lazy.map({ $0.dependenciesRequired(for: .everything) }).joined() { - adjustedDependencies.append(dependency.filtered(by: .specific([product]))) + adjustedDependencies.append(dependency.filtered(by: .specific([explicitProduct]))) } } diff --git a/Sources/PackageGraph/PubGrub/DiagnosticReportBuilder.swift b/Sources/PackageGraph/PubGrub/DiagnosticReportBuilder.swift index 08048baa82d..469949d9dc2 100644 --- a/Sources/PackageGraph/PubGrub/DiagnosticReportBuilder.swift +++ b/Sources/PackageGraph/PubGrub/DiagnosticReportBuilder.swift @@ -87,7 +87,7 @@ struct DiagnosticReportBuilder { let conflictLine = self.lineNumbers[cause.conflict] let otherLine = self.lineNumbers[cause.other] - if let conflictLine = conflictLine, let otherLine = otherLine { + if let conflictLine, let otherLine { self.record( incompatibility, message: "\(incompatibilityDesc) because \(try self.description(for: cause.conflict)) (\(conflictLine)) and \(try self.description(for: cause.other)) (\(otherLine).", @@ -97,7 +97,7 @@ struct DiagnosticReportBuilder { let withLine: Incompatibility let withoutLine: Incompatibility let line: Int - if let conflictLine = conflictLine { + if let conflictLine { withLine = cause.conflict withoutLine = cause.other line = conflictLine @@ -140,7 +140,7 @@ struct DiagnosticReportBuilder { let derived = cause.conflict.cause.isConflict ? cause.conflict : cause.other let ext = cause.conflict.cause.isConflict ? cause.other : cause.conflict let derivedLine = self.lineNumbers[derived] - if let derivedLine = derivedLine { + if let derivedLine { self.record( incompatibility, message: "\(incompatibilityDesc) because \(try self.description(for: ext)) and \(try self.description(for: derived)) (\(derivedLine)).", diff --git a/Sources/PackageGraph/PubGrub/PubGrubDependencyResolver.swift b/Sources/PackageGraph/PubGrub/PubGrubDependencyResolver.swift index 83ec9feb731..79056e1a80d 100644 --- a/Sources/PackageGraph/PubGrub/PubGrubDependencyResolver.swift +++ b/Sources/PackageGraph/PubGrub/PubGrubDependencyResolver.swift @@ -562,7 +562,7 @@ public struct PubGrubDependencyResolver { if mostRecentTerm == term { difference = mostRecentSatisfier?.term.difference(with: term) - if let difference = difference { + if let difference { previousSatisfierLevel = max(previousSatisfierLevel, try state.solution.satisfier(for: difference.inverse).decisionLevel) } } @@ -600,11 +600,11 @@ public struct PubGrubDependencyResolver { ) createdIncompatibility = true - if let term = mostRecentTerm { - if let diff = difference { - self.delegate?.partiallySatisfied(term: term, by: _mostRecentSatisfier, incompatibility: incompatibility, difference: diff) + if let mostRecentTerm { + if let difference { + self.delegate?.partiallySatisfied(term: mostRecentTerm, by: _mostRecentSatisfier, incompatibility: incompatibility, difference: difference) } else { - self.delegate?.satisfied(term: term, by: _mostRecentSatisfier, incompatibility: incompatibility) + self.delegate?.satisfied(term: mostRecentTerm, by: _mostRecentSatisfier, incompatibility: incompatibility) } } diff --git a/Sources/PackageGraph/PubGrub/PubGrubPackageContainer.swift b/Sources/PackageGraph/PubGrub/PubGrubPackageContainer.swift index d509bddcd6b..adafaf5af44 100644 --- a/Sources/PackageGraph/PubGrub/PubGrubPackageContainer.swift +++ b/Sources/PackageGraph/PubGrub/PubGrubPackageContainer.swift @@ -46,7 +46,7 @@ internal final class PubGrubPackageContainer { /// Returns the numbers of versions that are satisfied by the given version requirement. func versionCount(_ requirement: VersionSetSpecifier) throws -> Int { - if let pinnedVersion = self.pinnedVersion, requirement.contains(pinnedVersion) { + if let pinnedVersion, requirement.contains(pinnedVersion) { return 1 } return try self.underlying.versionsDescending().filter(requirement.contains).count @@ -79,7 +79,7 @@ internal final class PubGrubPackageContainer { let versionSet = term.requirement // Restrict the selection to the pinned version if is allowed by the current requirements. - if let pinnedVersion = self.pinnedVersion { + if let pinnedVersion { if versionSet.contains(pinnedVersion) { // Make sure the pinned version is still available let version = try self.underlying.versionsDescending().first { pinnedVersion == $0 } diff --git a/Sources/PackageLoading/ManifestLoader.swift b/Sources/PackageLoading/ManifestLoader.swift index 9f8261bccbe..911f9baabd4 100644 --- a/Sources/PackageLoading/ManifestLoader.swift +++ b/Sources/PackageLoading/ManifestLoader.swift @@ -44,7 +44,7 @@ extension ManifestParseError: CustomStringConvertible { return "'\(manifestPath)' is empty" case .invalidManifestFormat(let error, _, let compilerCommandLine): let suffix: String - if let compilerCommandLine = compilerCommandLine { + if let compilerCommandLine { suffix = " (compiled with: \(compilerCommandLine))" } else { suffix = "" @@ -56,7 +56,7 @@ extension ManifestParseError: CustomStringConvertible { return "invalid manifest, imports restricted modules: \(modules.joined(separator: ", "))" case .unsupportedVersion(let version, let underlyingError): let message = "serialized JSON uses unsupported version \(version), indicating use of a mismatched PackageDescription library" - if let underlyingError = underlyingError { + if let underlyingError { return "\(message), underlying error: \(underlyingError)" } return message @@ -606,7 +606,7 @@ public final class ManifestLoader: ManifestLoaderProtocol { var cmd: [String] = [] cmd += [self.toolchain.swiftCompilerPathForManifests.pathString] - if let vfsOverlayPath = vfsOverlayPath { + if let vfsOverlayPath { cmd += ["-vfsoverlay", vfsOverlayPath.pathString] } @@ -640,7 +640,7 @@ public final class ManifestLoader: ManifestLoaderProtocol { cmd += self.toolchain.swiftCompilerFlags cmd += self.interpreterFlags(for: toolsVersion) - if let moduleCachePath = moduleCachePath { + if let moduleCachePath { cmd += ["-module-cache-path", moduleCachePath.pathString] } diff --git a/Sources/PackageLoading/PackageBuilder.swift b/Sources/PackageLoading/PackageBuilder.swift index 15cecd07ee4..585405dc372 100644 --- a/Sources/PackageLoading/PackageBuilder.swift +++ b/Sources/PackageLoading/PackageBuilder.swift @@ -697,7 +697,7 @@ public final class PackageBuilder { $0.compactMap{ usage in switch usage { case .plugin(let name, let package): - if let package = package { + if let package { return .product(Target.ProductReference(name: name, package: package), conditions: []) } else { @@ -747,7 +747,7 @@ public final class PackageBuilder { /// Validates module alias key and value pairs and throws an error if empty or contains invalid characters. private func validateModuleAliases(_ aliases: [String: String]?) throws { - guard let aliases = aliases else { return } + guard let aliases else { return } for (aliasKey, aliasValue) in aliases { if !aliasKey.isValidIdentifier || !aliasValue.isValidIdentifier || @@ -763,7 +763,7 @@ public final class PackageBuilder { manifestTarget: TargetDescription?, dependencies: [Target.Dependency] ) throws -> Target? { - guard let manifestTarget = manifestTarget else { return nil } + guard let manifestTarget else { return nil } // Create system library target. if potentialModule.type == .system { @@ -941,7 +941,7 @@ public final class PackageBuilder { /// Creates build setting assignment table for the given target. func buildSettings(for target: TargetDescription?, targetRoot: AbsolutePath) throws -> BuildSettings.AssignmentTable { var table = BuildSettings.AssignmentTable() - guard let target = target else { return table } + guard let target else { return table } // Process each setting. for setting in target.settings { @@ -1130,7 +1130,7 @@ public final class PackageBuilder { /// Find the test entry point file for the package. private func findTestEntryPoint(in testTargets: [Target]) throws -> AbsolutePath? { - if let testEntryPointPath = testEntryPointPath { + if let testEntryPointPath { return testEntryPointPath } diff --git a/Sources/PackageLoading/Target+PkgConfig.swift b/Sources/PackageLoading/Target+PkgConfig.swift index 981e9b9e0c3..cffc2136066 100644 --- a/Sources/PackageLoading/Target+PkgConfig.swift +++ b/Sources/PackageLoading/Target+PkgConfig.swift @@ -180,7 +180,7 @@ extension SystemPackageProviderDescription { switch self { case .brew(let packages): let brewPrefix: String - if let brewPrefixOverride = brewPrefixOverride { + if let brewPrefixOverride { brewPrefix = brewPrefixOverride.pathString } else { // Homebrew can have multiple versions of the same package. The diff --git a/Sources/PackageLoading/TargetSourcesBuilder.swift b/Sources/PackageLoading/TargetSourcesBuilder.swift index 239a03dc926..c2fb42c846d 100644 --- a/Sources/PackageLoading/TargetSourcesBuilder.swift +++ b/Sources/PackageLoading/TargetSourcesBuilder.swift @@ -93,7 +93,7 @@ public struct TargetSourcesBuilder { } let declaredSources = target.sources?.compactMap { try? AbsolutePath(validating: $0, relativeTo: path) } - if let declaredSources = declaredSources { + if let declaredSources { // Diagnose duplicate entries. let duplicates = declaredSources.spm_findDuplicateElements() if !duplicates.isEmpty { @@ -213,7 +213,7 @@ public struct TargetSourcesBuilder { } // Match any sources explicitly declared in the manifest file. - if let declaredSources = declaredSources { + if let declaredSources { for sourcePath in declaredSources { if path.isDescendantOfOrEqual(to: sourcePath) { if matchedRule != .none { diff --git a/Sources/PackageModel/Destination.swift b/Sources/PackageModel/Destination.swift index 8a2b53c8cc5..9148d2de9f1 100644 --- a/Sources/PackageModel/Destination.swift +++ b/Sources/PackageModel/Destination.swift @@ -195,7 +195,7 @@ public struct Destination: Equatable { /// - properties: properties of the destination for the given triple. /// - destinationDirectory: directory used for converting relative paths in `properties` to absolute paths. init(_ properties: SerializedDestinationV3.TripleProperties, destinationDirectory: AbsolutePath? = nil) throws { - if let destinationDirectory = destinationDirectory { + if let destinationDirectory { self.init( sdkRootPath: try AbsolutePath(validating: properties.sdkRootPath, relativeTo: destinationDirectory), swiftResourcesPath: try properties.swiftResourcesPath.map { diff --git a/Sources/PackageModel/DestinationBundle.swift b/Sources/PackageModel/DestinationBundle.swift index 030d495159c..be9c593c1ee 100644 --- a/Sources/PackageModel/DestinationBundle.swift +++ b/Sources/PackageModel/DestinationBundle.swift @@ -80,7 +80,7 @@ public struct DestinationBundle { hostTriple: Triple, observabilityScope: ObservabilityScope ) throws -> Destination { - guard let destinationsDirectory = destinationsDirectory else { + guard let destinationsDirectory else { throw StringError( """ No cross-compilation destinations directory found, specify one @@ -250,7 +250,7 @@ extension Array where Element == DestinationBundle { for destination in variant.destinations { if artifactID == selector { - if let matchedByID = matchedByID { + if let matchedByID { observabilityScope.emit( warning: """ @@ -267,7 +267,7 @@ extension Array where Element == DestinationBundle { } if destination.targetTriple?.tripleString == selector { - if let matchedByTriple = matchedByTriple { + if let matchedByTriple { observabilityScope.emit( warning: """ @@ -287,7 +287,7 @@ extension Array where Element == DestinationBundle { } } - if let matchedByID = matchedByID, let matchedByTriple = matchedByTriple, matchedByID != matchedByTriple { + if let matchedByID, let matchedByTriple, matchedByID != matchedByTriple { observabilityScope.emit( warning: """ diff --git a/Sources/PackageModel/Diagnostics.swift b/Sources/PackageModel/Diagnostics.swift index 8d2926cbad9..c5c656fb7f4 100644 --- a/Sources/PackageModel/Diagnostics.swift +++ b/Sources/PackageModel/Diagnostics.swift @@ -42,8 +42,8 @@ public struct RequireNewerTools: Error, CustomStringConvertible { public var description: String { var text = "package '\(self.packageIdentity)'" - if let version = self.packageVersion { - text += " @ \(version)" + if let packageVersion { + text += " @ \(packageVersion)" } text += " is using Swift tools version \(packageToolsVersion.description) but the installed version is \(installedToolsVersion.description)" return text @@ -82,8 +82,8 @@ public struct UnsupportedToolsVersion: Error, CustomStringConvertible { public var description: String { var text = "package '\(self.packageIdentity)'" - if let version = self.packageVersion { - text += " @ \(version)" + if let packageVersion { + text += " @ \(packageVersion)" } text += " is using Swift tools version \(packageToolsVersion.description) which is no longer supported; \(hintString)" return text diff --git a/Sources/PackageModel/Manifest/Manifest.swift b/Sources/PackageModel/Manifest/Manifest.swift index 31276e491c7..b2269aaa1ae 100644 --- a/Sources/PackageModel/Manifest/Manifest.swift +++ b/Sources/PackageModel/Manifest/Manifest.swift @@ -353,7 +353,7 @@ public final class Manifest: Sendable { case .target: break case .product(let product, let package, _, _): - if let package = package { // ≥ 5.2 + if let package { // ≥ 5.2 if !register( product: product, inPackage: packageIdentity(referencedBy: package), @@ -412,7 +412,7 @@ public final class Manifest: Sendable { ) { switch requiredPlugIn { case .plugin(let name, let package): - if let package = package { + if let package { if !register( product: name, inPackage: packageIdentity(referencedBy: package), diff --git a/Sources/PackageModel/Manifest/PackageConditionDescription.swift b/Sources/PackageModel/Manifest/PackageConditionDescription.swift index 55c3a4c66a0..3ce346bf84b 100644 --- a/Sources/PackageModel/Manifest/PackageConditionDescription.swift +++ b/Sources/PackageModel/Manifest/PackageConditionDescription.swift @@ -33,9 +33,9 @@ struct PackageConditionWrapper: Codable { var config: ConfigurationCondition? var condition: PackageConditionProtocol { - if let platform = platform { + if let platform { return platform - } else if let config = config { + } else if let config { return config } else { fatalError("unreachable") diff --git a/Sources/PackageModel/ManifestSourceGeneration.swift b/Sources/PackageModel/ManifestSourceGeneration.swift index ac6123dc9fd..46950ad481f 100644 --- a/Sources/PackageModel/ManifestSourceGeneration.swift +++ b/Sources/PackageModel/ManifestSourceGeneration.swift @@ -326,27 +326,27 @@ fileprivate extension SourceCodeFragment { switch dependency { case .target(name: let name, condition: let condition): params.append(SourceCodeFragment(key: "name", string: name)) - if let condition = condition { + if let condition { params.append(SourceCodeFragment(key: "condition", subnode: SourceCodeFragment(from: condition))) } self.init(enum: "target", subnodes: params) case .product(name: let name, package: let packageName, moduleAliases: let aliases, condition: let condition): params.append(SourceCodeFragment(key: "name", string: name)) - if let packageName = packageName { + if let packageName { params.append(SourceCodeFragment(key: "package", string: packageName)) } - if let aliases = aliases { + if let aliases { let vals = aliases.map { SourceCodeFragment(key: $0.key.quotedForPackageManifest, string: $0.value) } params.append(SourceCodeFragment(key: "moduleAliases", subnodes: vals)) } - if let condition = condition { + if let condition { params.append(SourceCodeFragment(key: "condition", subnode: SourceCodeFragment(from: condition))) } self.init(enum: "product", subnodes: params) case .byName(name: let name, condition: let condition): - if let condition = condition { + if let condition { params.append(SourceCodeFragment(key: "name", string: name)) params.append(SourceCodeFragment(key: "condition", subnode: SourceCodeFragment(from: condition))) self.init(enum: "byName", subnodes: params) @@ -420,7 +420,7 @@ fileprivate extension SourceCodeFragment { params.append(SourceCodeFragment(string: resource.path)) switch resource.rule { case .process(let localization): - if let localization = localization { + if let localization { params.append(SourceCodeFragment(key: "localization", enum: localization.rawValue)) } self.init(enum: "process", subnodes: params) @@ -516,7 +516,7 @@ fileprivate extension SourceCodeFragment { self.init(enum: setting.kind.name, subnodes: params) case .interoperabilityMode(let lang, let version): params.append(SourceCodeFragment(enum: lang.rawValue)) - if let version = version { + if let version { params.append(SourceCodeFragment(key: "version", string: version)) } self.init(enum: setting.kind.name, subnodes: params) @@ -630,7 +630,7 @@ public struct SourceCodeFragment { func generateSourceCode(indent: String = "") -> String { var string = literal - if let subnodes = subnodes { + if let subnodes { switch delimiters { case .none: break case .brackets: string.append("[") diff --git a/Sources/PackageModel/PackageIdentity.swift b/Sources/PackageModel/PackageIdentity.swift index ba3a79326b0..b744804c62c 100644 --- a/Sources/PackageModel/PackageIdentity.swift +++ b/Sources/PackageModel/PackageIdentity.swift @@ -172,7 +172,7 @@ extension PackageIdentity { } fileprivate init?(_ substring: String.SubSequence?) { - guard let substring = substring else { return nil } + guard let substring else { return nil } self.init(String(substring)) } @@ -256,7 +256,7 @@ extension PackageIdentity { } fileprivate init?(_ substring: String.SubSequence?) { - guard let substring = substring else { return nil } + guard let substring else { return nil } self.init(String(substring)) } @@ -576,7 +576,7 @@ extension String { ) -> Bool { guard let range = range(of: string) else { return false } - if let index = index, range.lowerBound >= index { + if let index, range.lowerBound >= index { return false } diff --git a/Sources/PackageModel/PackageModel.swift b/Sources/PackageModel/PackageModel.swift index 7a94e49b439..ac839743bb6 100644 --- a/Sources/PackageModel/PackageModel.swift +++ b/Sources/PackageModel/PackageModel.swift @@ -113,7 +113,7 @@ extension Package.Error: CustomStringConvertible { switch self { case .noManifest(let path, let version): var string = "\(path) has no Package.swift manifest" - if let version = version { + if let version { string += " for version \(version)" } return string diff --git a/Sources/PackageModel/Target.swift b/Sources/PackageModel/Target.swift index ab7d4e58e45..c3662bf9ab0 100644 --- a/Sources/PackageModel/Target.swift +++ b/Sources/PackageModel/Target.swift @@ -53,8 +53,8 @@ public class Target: PolymorphicCodableProtocol { /// Fully qualified name for this product dependency: package ID + name of the product public var identity: String { - if let pkg = package { - return pkg.lowercased() + "_" + name + if let package { + return package.lowercased() + "_" + name } else { // this is hit only if this product is referenced `.byName(name)` // which assumes the name of this product, its package, and its target diff --git a/Sources/PackageModel/ToolchainConfiguration.swift b/Sources/PackageModel/ToolchainConfiguration.swift index 70acff70f55..fd1a90eef90 100644 --- a/Sources/PackageModel/ToolchainConfiguration.swift +++ b/Sources/PackageModel/ToolchainConfiguration.swift @@ -83,7 +83,7 @@ extension ToolchainConfiguration { public init(manifestLibraryPath: AbsolutePath, manifestLibraryMinimumDeploymentTarget: PlatformVersion? = nil, pluginLibraryPath: AbsolutePath, pluginLibraryMinimumDeploymentTarget: PlatformVersion? = nil) { #if os(macOS) - if let manifestLibraryMinimumDeploymentTarget = manifestLibraryMinimumDeploymentTarget { + if let manifestLibraryMinimumDeploymentTarget { self.manifestLibraryMinimumDeploymentTarget = manifestLibraryMinimumDeploymentTarget } else if let manifestLibraryMinimumDeploymentTarget = try? MinimumDeploymentTarget.computeMinimumDeploymentTarget(of: Self.macOSManifestLibraryPath(for: manifestLibraryPath), platform: .macOS) { self.manifestLibraryMinimumDeploymentTarget = manifestLibraryMinimumDeploymentTarget @@ -91,7 +91,7 @@ extension ToolchainConfiguration { self.manifestLibraryMinimumDeploymentTarget = Self.defaultMinimumDeploymentTarget } - if let pluginLibraryMinimumDeploymentTarget = pluginLibraryMinimumDeploymentTarget { + if let pluginLibraryMinimumDeploymentTarget { self.pluginLibraryMinimumDeploymentTarget = pluginLibraryMinimumDeploymentTarget } else if let pluginLibraryMinimumDeploymentTarget = try? MinimumDeploymentTarget.computeMinimumDeploymentTarget(of: Self.macOSPluginLibraryPath(for: pluginLibraryPath), platform: .macOS) { self.pluginLibraryMinimumDeploymentTarget = pluginLibraryMinimumDeploymentTarget diff --git a/Sources/PackageModel/UserToolchain.swift b/Sources/PackageModel/UserToolchain.swift index 9e095dc65b0..036e8d54515 100644 --- a/Sources/PackageModel/UserToolchain.swift +++ b/Sources/PackageModel/UserToolchain.swift @@ -101,7 +101,7 @@ public final class UserToolchain: Toolchain { } toolPath = path } - guard let toolPath = toolPath else { + guard let toolPath else { throw InvalidToolchainDiagnostic("could not find CLI tool `\(name)` at any of these directories: \(binDirectories)") } return toolPath @@ -185,7 +185,7 @@ public final class UserToolchain: Toolchain { searchPaths: [AbsolutePath] ) throws -> SwiftCompilers { func validateCompiler(at path: AbsolutePath?) throws { - guard let path = path else { return } + guard let path else { return } guard localFileSystem.isExecutableFile(path) else { throw InvalidToolchainDiagnostic( "could not find the `swiftc\(hostExecutableSuffix)` at expected path \(path)" @@ -205,7 +205,7 @@ public final class UserToolchain: Toolchain { // We require there is at least one valid swift compiler, either in the // bin dir or SWIFT_EXEC. let resolvedBinDirCompiler: AbsolutePath - if let SWIFT_EXEC = SWIFT_EXEC { + if let SWIFT_EXEC { resolvedBinDirCompiler = SWIFT_EXEC } else if let binDirCompiler = try? UserToolchain.getTool("swiftc", binDirectories: binDirectories) { resolvedBinDirCompiler = binDirCompiler diff --git a/Sources/PackageRegistry/ChecksumTOFU.swift b/Sources/PackageRegistry/ChecksumTOFU.swift index d615a9ad640..f8761ea7215 100644 --- a/Sources/PackageRegistry/ChecksumTOFU.swift +++ b/Sources/PackageRegistry/ChecksumTOFU.swift @@ -137,7 +137,7 @@ struct PackageVersionChecksumTOFU { callbackQueue: DispatchQueue, completion: @escaping (Result) -> Void ) { - guard let fingerprintStorage = self.fingerprintStorage else { + guard let fingerprintStorage else { return completion(.success(nil)) } @@ -170,7 +170,7 @@ struct PackageVersionChecksumTOFU { callbackQueue: DispatchQueue, completion: @escaping (Result) -> Void ) { - guard let fingerprintStorage = self.fingerprintStorage else { + guard let fingerprintStorage else { return completion(.success(())) } diff --git a/Sources/PackageRegistry/RegistryClient.swift b/Sources/PackageRegistry/RegistryClient.swift index c317ec7fd31..b6143dc84c0 100644 --- a/Sources/PackageRegistry/RegistryClient.swift +++ b/Sources/PackageRegistry/RegistryClient.swift @@ -2265,7 +2265,7 @@ private struct RegistryClientSignatureValidationDelegate: SignatureValidation.De version: TSCUtility.Version, completion: (Bool) -> Void ) { - if let underlying = self.underlying { + if let underlying { underlying.onUnsigned(registry: registry, package: package, version: version, completion: completion) } else { // true == continue resolution @@ -2280,7 +2280,7 @@ private struct RegistryClientSignatureValidationDelegate: SignatureValidation.De version: TSCUtility.Version, completion: (Bool) -> Void ) { - if let underlying = self.underlying { + if let underlying { underlying.onUntrusted(registry: registry, package: package, version: version, completion: completion) } else { // true == continue resolution diff --git a/Sources/PackageRegistry/RegistryConfiguration.swift b/Sources/PackageRegistry/RegistryConfiguration.swift index 19b9bcf0d05..7290da6f874 100644 --- a/Sources/PackageRegistry/RegistryConfiguration.swift +++ b/Sources/PackageRegistry/RegistryConfiguration.swift @@ -78,16 +78,16 @@ public struct RegistryConfiguration: Hashable { let packageOverrides = self.security?.packageOverrides[package]?.signing var signing = Security.Signing.default - if let global = global { + if let global { signing.merge(global) } - if let registryOverrides = registryOverrides { + if let registryOverrides { signing.merge(registryOverrides) } - if let scopeOverrides = scopeOverrides { + if let scopeOverrides { signing.merge(scopeOverrides) } - if let packageOverrides = packageOverrides { + if let packageOverrides { signing.merge(packageOverrides) } diff --git a/Sources/PackageRegistry/RegistryDownloadsManager.swift b/Sources/PackageRegistry/RegistryDownloadsManager.swift index 520feb50efd..2f695a2f0cc 100644 --- a/Sources/PackageRegistry/RegistryDownloadsManager.swift +++ b/Sources/PackageRegistry/RegistryDownloadsManager.swift @@ -149,7 +149,7 @@ public class RegistryDownloadsManager: Cancellable { callbackQueue: DispatchQueue, completion: @escaping (Result) -> Void ) { - if let cachePath = self.cachePath { + if let cachePath { do { let relativePath = try package.downloadPath(version: version) let cachedPackagePath = cachePath.appending(relativePath) @@ -258,7 +258,7 @@ public class RegistryDownloadsManager: Cancellable { } public func purgeCache(observabilityScope: ObservabilityScope) { - guard let cachePath = self.cachePath else { + guard let cachePath else { return } diff --git a/Sources/PackageRegistry/SigningEntityTOFU.swift b/Sources/PackageRegistry/SigningEntityTOFU.swift index 9416bcf5e23..72762e62279 100644 --- a/Sources/PackageRegistry/SigningEntityTOFU.swift +++ b/Sources/PackageRegistry/SigningEntityTOFU.swift @@ -39,7 +39,7 @@ struct PackageSigningEntityTOFU { callbackQueue: DispatchQueue, completion: @escaping (Result) -> Void ) { - guard let signingEntityStorage = self.signingEntityStorage else { + guard let signingEntityStorage else { return completion(.success(())) } @@ -246,7 +246,7 @@ struct PackageSigningEntityTOFU { callbackQueue: DispatchQueue, completion: @escaping (Result) -> Void ) { - guard let signingEntityStorage = self.signingEntityStorage else { + guard let signingEntityStorage else { return completion(.success(())) } diff --git a/Sources/PackageRegistryTool/PackageRegistryTool+Auth.swift b/Sources/PackageRegistryTool/PackageRegistryTool+Auth.swift index 35b1dbbcf6d..833c5dd5a2b 100644 --- a/Sources/PackageRegistryTool/PackageRegistryTool+Auth.swift +++ b/Sources/PackageRegistryTool/PackageRegistryTool+Auth.swift @@ -97,7 +97,7 @@ extension SwiftPackageRegistryTool { throw ValidationError.invalidCredentialStore(error) } - guard let authorizationProvider = authorizationProvider else { + guard let authorizationProvider else { throw ValidationError.unknownCredentialStore } @@ -119,11 +119,11 @@ extension SwiftPackageRegistryTool { let storePassword: String var saveChanges = true - if let username = self.username { + if let username { authenticationType = .basic storeUsername = username - if let password = self.password { + if let password { // User provided password storePassword = password } else if let stored = authorizationProvider.authentication(for: registryURL), @@ -141,7 +141,7 @@ extension SwiftPackageRegistryTool { // All token auth accounts have the same placeholder value storeUsername = Self.PLACEHOLDER_TOKEN_USER - if let token = self.token { + if let token { // User provided token storePassword = token } else if let stored = authorizationProvider.authentication(for: registryURL), diff --git a/Sources/PackageRegistryTool/PackageRegistryTool+Publish.swift b/Sources/PackageRegistryTool/PackageRegistryTool+Publish.swift index a43ab44b76d..b1bd61c4b17 100644 --- a/Sources/PackageRegistryTool/PackageRegistryTool+Publish.swift +++ b/Sources/PackageRegistryTool/PackageRegistryTool+Publish.swift @@ -100,7 +100,7 @@ extension SwiftPackageRegistryTool { try registryURL.validateRegistryURL() // validate working directory path - if let customWorkingDirectory = self.customWorkingDirectory { + if let customWorkingDirectory { guard localFileSystem.isDirectory(customWorkingDirectory) else { throw StringError("Directory not found at '\(customWorkingDirectory)'.") } @@ -117,7 +117,7 @@ extension SwiftPackageRegistryTool { // validate custom metadata path let defaultMetadataPath = packageDirectory.appending(component: Self.metadataFilename) var metadataLocation: MetadataLocation? = .none - if let customMetadataPath = self.customMetadataPath { + if let customMetadataPath { guard localFileSystem.exists(customMetadataPath) else { throw StringError("Metadata file not found at '\(customMetadataPath)'.") } diff --git a/Sources/PackageRegistryTool/PackageRegistryTool.swift b/Sources/PackageRegistryTool/PackageRegistryTool.swift index c5dfa53567c..4a9227f2740 100644 --- a/Sources/PackageRegistryTool/PackageRegistryTool.swift +++ b/Sources/PackageRegistryTool/PackageRegistryTool.swift @@ -69,7 +69,7 @@ public struct SwiftPackageRegistryTool: ParsableCommand { let scope = try scope.map(PackageIdentity.Scope.init(validating:)) let set: (inout RegistryConfiguration) throws -> Void = { configuration in - if let scope = scope { + if let scope { configuration.scopedRegistries[scope] = .init(url: self.registryURL, supportsAvailability: false) } else { configuration.defaultRegistry = .init(url: self.registryURL, supportsAvailability: false) @@ -103,7 +103,7 @@ public struct SwiftPackageRegistryTool: ParsableCommand { let scope = try scope.map(PackageIdentity.Scope.init(validating:)) let unset: (inout RegistryConfiguration) throws -> Void = { configuration in - if let scope = scope { + if let scope { guard let _ = configuration.scopedRegistries[scope] else { throw ConfigurationError.missingScope(scope) } diff --git a/Sources/PackageSigning/X509Extensions.swift b/Sources/PackageSigning/X509Extensions.swift index 7140fe85618..8c1603138fa 100644 --- a/Sources/PackageSigning/X509Extensions.swift +++ b/Sources/PackageSigning/X509Extensions.swift @@ -78,7 +78,7 @@ extension RelativeDistinguishedName.Attribute { asn1StringBytes = try? ASN1UTF8String(asn1Any: self.value).bytes } - guard let asn1StringBytes = asn1StringBytes, + guard let asn1StringBytes, let stringValue = String(bytes: asn1StringBytes, encoding: .utf8) else { return nil diff --git a/Sources/SPMTestSupport/MockPackageContainer.swift b/Sources/SPMTestSupport/MockPackageContainer.swift index c572d2fbf3c..79aeaecece8 100644 --- a/Sources/SPMTestSupport/MockPackageContainer.swift +++ b/Sources/SPMTestSupport/MockPackageContainer.swift @@ -86,8 +86,8 @@ public class MockPackageContainer: CustomPackageContainer { } public func retrieve(at version: Version, progressHandler: ((Int64, Int64?) -> Void)?, observabilityScope: ObservabilityScope) throws -> AbsolutePath { - if let path = customRetrievalPath { - return path + if let customRetrievalPath { + return customRetrievalPath } else { throw StringError("no path configured for mock package container") } diff --git a/Sources/SPMTestSupport/MockRegistry.swift b/Sources/SPMTestSupport/MockRegistry.swift index b593b4c779d..9e848cacecc 100644 --- a/Sources/SPMTestSupport/MockRegistry.swift +++ b/Sources/SPMTestSupport/MockRegistry.swift @@ -49,8 +49,8 @@ public class MockRegistry { self.jsonEncoder = JSONEncoder.makeWithDefaults() var configuration = RegistryConfiguration() - if let baseURL = customBaseURL { - self.baseURL = baseURL + if let customBaseURL { + self.baseURL = customBaseURL } else { self.baseURL = URL("http://localhost/registry/mock") @@ -100,7 +100,7 @@ public class MockRegistry { } self.packageVersions[identity] = updatedVersions // source control URLs - if let sourceControlURLs = sourceControlURLs { + if let sourceControlURLs { var packageSourceControlURLs = self.packagesSourceControlURLs[identity] ?? [] packageSourceControlURLs.append(contentsOf: sourceControlURLs) self.packagesSourceControlURLs[identity] = packageSourceControlURLs @@ -201,7 +201,7 @@ public class MockRegistry { var headers = HTTPClientHeaders() headers.add(name: "Content-Version", value: "1") headers.add(name: "Content-Type", value: "application/json") - if let links = links { + if let links { headers.add(name: "Link", value: links) } @@ -262,7 +262,7 @@ public class MockRegistry { } let filename: String - if let toolsVersion = toolsVersion { + if let toolsVersion { filename = Manifest.basename + "@swift-\(toolsVersion).swift" } else { filename = Manifest.basename + ".swift" diff --git a/Sources/SourceControl/GitRepository.swift b/Sources/SourceControl/GitRepository.swift index 9606e5a42b1..0f18224c58c 100644 --- a/Sources/SourceControl/GitRepository.swift +++ b/Sources/SourceControl/GitRepository.swift @@ -79,7 +79,7 @@ public struct GitRepositoryProvider: RepositoryProvider, Cancellable { repository: RepositorySpecifier, failureMessage: String = "", progress: FetchProgress.Handler? = nil) throws -> String { - if let progress = progress { + if let progress { var stdoutBytes: [UInt8] = [], stderrBytes: [UInt8] = [] do { // Capture stdout and stderr from the Git subprocess invocation, but also pass along stderr to the handler. We count on it being line-buffered. @@ -369,7 +369,7 @@ public final class GitRepository: Repository, WorkingCheckout { environment: EnvironmentVariables = Git.environment, failureMessage: String = "", progress: FetchProgress.Handler? = nil) throws -> String { - if let progress = progress { + if let progress { var stdoutBytes: [UInt8] = [], stderrBytes: [UInt8] = [] do { // Capture stdout and stderr from the Git subprocess invocation, but also pass along stderr to the handler. We count on it being line-buffered. @@ -642,7 +642,7 @@ public final class GitRepository: Repository, WorkingCheckout { /// to the syntax accepted by `git rev-parse`. public func resolveHash(treeish: String, type: String? = nil) throws -> Hash { let specifier: String - if let type = type { + if let type { specifier = treeish + "^{\(type)}" } else { specifier = treeish diff --git a/Sources/SourceControl/RepositoryManager.swift b/Sources/SourceControl/RepositoryManager.swift index ab1308b470f..724e16678a7 100644 --- a/Sources/SourceControl/RepositoryManager.swift +++ b/Sources/SourceControl/RepositoryManager.swift @@ -302,7 +302,7 @@ public class RepositoryManager: Cancellable { // We are expecting handle.repository.url to always be a resolved absolute path. let shouldCacheLocalPackages = ProcessEnv.vars["SWIFTPM_TESTS_PACKAGECACHE"] == "1" || cacheLocalPackages - if let cachePath = self.cachePath, !(handle.repository.isLocal && !shouldCacheLocalPackages) { + if let cachePath, !(handle.repository.isLocal && !shouldCacheLocalPackages) { let cachedRepositoryPath = cachePath.appending(handle.repository.storagePath()) do { try self.initializeCacheIfNeeded(cachePath: cachePath) @@ -421,7 +421,7 @@ public class RepositoryManager: Cancellable { /// Purges the cached repositories from the cache. public func purgeCache(observabilityScope: ObservabilityScope) { - guard let cachePath = self.cachePath else { + guard let cachePath else { return } diff --git a/Sources/Workspace/DefaultPluginScriptRunner.swift b/Sources/Workspace/DefaultPluginScriptRunner.swift index f81213b8c5a..b129af79ac6 100644 --- a/Sources/Workspace/DefaultPluginScriptRunner.swift +++ b/Sources/Workspace/DefaultPluginScriptRunner.swift @@ -202,7 +202,7 @@ public struct DefaultPluginScriptRunner: PluginScriptRunner, Cancellable { // Honor any module cache override that's set in the environment. let moduleCachePath = ProcessEnv.vars["SWIFTPM_MODULECACHE_OVERRIDE"] ?? ProcessEnv.vars["SWIFTPM_TESTS_MODULECACHE"] - if let moduleCachePath = moduleCachePath { + if let moduleCachePath { commandLine += ["-module-cache-path", moduleCachePath] } @@ -315,7 +315,7 @@ public struct DefaultPluginScriptRunner: PluginScriptRunner, Cancellable { } // If we still have a compilation state, it means the executable is still valid and we don't need to do anything. - if let compilationState = compilationState { + if let compilationState { // Just call the completion handler with the persisted results. let result = PluginCompilationResult( succeeded: compilationState.succeeded, diff --git a/Sources/Workspace/Diagnostics.swift b/Sources/Workspace/Diagnostics.swift index 45f551d0f62..ef65b7119e1 100644 --- a/Sources/Workspace/Diagnostics.swift +++ b/Sources/Workspace/Diagnostics.swift @@ -165,7 +165,7 @@ extension Basics.Diagnostic { extension FileSystemError: CustomStringConvertible { public var description: String { - guard let path = path else { + guard let path else { switch self.kind { case .invalidAccess: return "invalid access" diff --git a/Sources/Workspace/ResolvedFileWatcher.swift b/Sources/Workspace/ResolvedFileWatcher.swift index c89edd2ac76..2c9a790c2b5 100644 --- a/Sources/Workspace/ResolvedFileWatcher.swift +++ b/Sources/Workspace/ResolvedFileWatcher.swift @@ -36,7 +36,7 @@ final class ResolvedFileWatcher { self.resolvedFile = resolvedFile let block = { [weak self] (paths: [AbsolutePath]) in - guard let self = self else { return } + guard let self else { return } // Check if resolved file is part of the received paths. let hasResolvedFile = paths.contains{ $0.appending(component: resolvedFile.basename) == resolvedFile } diff --git a/Sources/Workspace/SourceControlPackageContainer.swift b/Sources/Workspace/SourceControlPackageContainer.swift index 1bce74470a9..60370c55ac8 100644 --- a/Sources/Workspace/SourceControlPackageContainer.swift +++ b/Sources/Workspace/SourceControlPackageContainer.swift @@ -45,7 +45,7 @@ internal final class SourceControlPackageContainer: PackageContainer, CustomStri /// Description shown for errors of this kind. public var description: String { var desc = "\(underlyingError) in \(self.repository.location)" - if let suggestion = suggestion { + if let suggestion { desc += " (\(suggestion))" } return desc @@ -153,7 +153,7 @@ internal final class SourceControlPackageContainer: PackageContainer, CustomStri } func checkIntegrity(version: Version, revision: Revision) throws { - guard let fingerprintStorage = self.fingerprintStorage else { + guard let fingerprintStorage else { return } diff --git a/Sources/Workspace/Workspace+BinaryArtifacts.swift b/Sources/Workspace/Workspace+BinaryArtifacts.swift index ad552cfa42d..e012d503233 100644 --- a/Sources/Workspace/Workspace+BinaryArtifacts.swift +++ b/Sources/Workspace/Workspace+BinaryArtifacts.swift @@ -555,7 +555,7 @@ extension FileSystem { } // no acceptable extensions defined, so the single top-level directory is a good candidate - guard let acceptableExtensions = acceptableExtensions else { + guard let acceptableExtensions else { return true } diff --git a/Sources/Workspace/Workspace+Configuration.swift b/Sources/Workspace/Workspace+Configuration.swift index 13b20131741..261eea5e5c2 100644 --- a/Sources/Workspace/Workspace+Configuration.swift +++ b/Sources/Workspace/Workspace+Configuration.swift @@ -468,7 +468,7 @@ extension Workspace.Configuration { @discardableResult public func applyShared(handler: (inout DependencyMirrors) throws -> Void) throws -> DependencyMirrors { - guard let sharedMirrors = self.sharedMirrors else { + guard let sharedMirrors else { throw InternalError("shared mirrors not configured") } try sharedMirrors.apply(handler: handler) @@ -642,7 +642,7 @@ extension Workspace.Configuration { public func updateShared(with handler: (inout RegistryConfiguration) throws -> Void) throws -> RegistryConfiguration { - guard let sharedRegistries = self.sharedRegistries else { + guard let sharedRegistries else { throw InternalError("shared registries not configured") } try sharedRegistries.update(with: handler) diff --git a/Sources/Workspace/Workspace.swift b/Sources/Workspace/Workspace.swift index 53f894a5904..66df2fe2ebe 100644 --- a/Sources/Workspace/Workspace.swift +++ b/Sources/Workspace/Workspace.swift @@ -864,11 +864,11 @@ extension Workspace { // Compute the custom or extra constraint we need to impose. let requirement: PackageRequirement - if let version = version { + if let version { requirement = .versionSet(.exact(version)) - } else if let branch = branch { + } else if let branch { requirement = .revision(branch) - } else if let revision = revision { + } else if let revision { requirement = .revision(revision) } else { requirement = defaultRequirement @@ -1422,12 +1422,12 @@ extension Workspace { } // Emit warnings for branch and revision, if they're present. - if let checkoutBranch = checkoutBranch { + if let checkoutBranch { observabilityScope.emit(.editBranchNotCheckedOut( packageName: packageName, branchName: checkoutBranch)) } - if let revision = revision { + if let revision { observabilityScope.emit(.editRevisionNotUsed( packageName: packageName, revisionIdentifier: revision.identifier)) @@ -1455,7 +1455,7 @@ extension Workspace { if let branch = checkoutBranch, repo.exists(revision: Revision(identifier: branch)) { throw WorkspaceDiagnostics.BranchAlreadyExists(branch: branch) } - if let revision = revision, !repo.exists(revision: revision) { + if let revision, !repo.exists(revision: revision) { throw WorkspaceDiagnostics.RevisionDoesNotExist(revision: revision.identifier) } @@ -1469,7 +1469,7 @@ extension Workspace { } // For unmanaged dependencies, create the symlink under editables dir. - if let path = path { + if let path { try fileSystem.createDirectory(self.location.editsDirectory) // FIXME: We need this to work with InMem file system too. if !(fileSystem is InMemoryFileSystem) { @@ -1558,7 +1558,7 @@ extension Workspace { // Resolve the dependencies if workspace root is provided. We do this to // ensure the unedited version of this dependency is resolved properly. - if let root = root { + if let root { try self.resolve(root: root, observabilityScope: observabilityScope) } } @@ -2025,7 +2025,7 @@ extension Workspace { sync.enter() self.loadManagedManifest(for: package, observabilityScope: observabilityScope) { manifest in defer { sync.leave() } - if let manifest = manifest { + if let manifest { manifests[package.identity] = manifest } } @@ -2268,7 +2268,7 @@ extension Workspace { artifactsToAdd.append(artifact) } - if let existingArtifact = existingArtifact, isAtArtifactsDirectory(existingArtifact) { + if let existingArtifact, isAtArtifactsDirectory(existingArtifact) { // Remove the old extracted artifact, be it local archived or remote one. artifactsToRemove.append(existingArtifact) } @@ -2280,7 +2280,7 @@ extension Workspace { targetName: artifact.targetName ] - if let existingArtifact = existingArtifact { + if let existingArtifact { if case .remote(let existingURL, let existingChecksum) = existingArtifact.source { // If we already have an artifact with the same checksum, we don't need to download it again. if artifact.checksum == existingChecksum { @@ -2921,7 +2921,7 @@ extension Workspace { continue } - if let currentDependency = currentDependency { + if let currentDependency { switch currentDependency.state { case .fileSystem, .edited: packageStateChanges[packageRef.identity] = (packageRef, .unchanged) @@ -2958,11 +2958,11 @@ extension Workspace { } // First check if we have this dependency. - if let currentDependency = currentDependency { + if let currentDependency { // If current state and new state are equal, we don't need // to do anything. let newState: CheckoutState - if let branch = branch { + if let branch { newState = .branch(name: branch, revision: revision) } else { newState = .revision(revision) @@ -3745,7 +3745,7 @@ extension FileSystem { } // no acceptable extensions defined, so the single top-level directory is a good candidate - guard let acceptableExtensions = acceptableExtensions else { + guard let acceptableExtensions else { return true } diff --git a/Sources/XCBuildSupport/PIF.swift b/Sources/XCBuildSupport/PIF.swift index b4345527d07..6fcb64094e7 100644 --- a/Sources/XCBuildSupport/PIF.swift +++ b/Sources/XCBuildSupport/PIF.swift @@ -118,7 +118,7 @@ public enum PIF { try contents.encode(path, forKey: .path) if encoder.userInfo.keys.contains(.encodeForXCBuild) { - guard let signature = self.signature else { + guard let signature else { throw InternalError("Expected to have workspace signature when encoding for XCBuild") } try container.encode(signature, forKey: "signature") @@ -201,7 +201,7 @@ public enum PIF { try contents.encode(buildConfigurations, forKey: .buildConfigurations) if encoder.userInfo.keys.contains(.encodeForXCBuild) { - guard let signature = self.signature else { + guard let signature else { throw InternalError("Expected to have project signature when encoding for XCBuild") } try container.encode(signature, forKey: "signature") @@ -509,7 +509,7 @@ public enum PIF { try contents.encode(impartedBuildProperties, forKey: .impartedBuildProperties) if encoder.userInfo.keys.contains(.encodeForXCBuild) { - guard let signature = self.signature else { + guard let signature else { throw InternalError("Expected to have \(Swift.type(of: self)) signature when encoding for XCBuild") } try container.encode(signature, forKey: "signature") @@ -606,7 +606,7 @@ public enum PIF { try contents.encode(buildConfigurations, forKey: .buildConfigurations) if encoder.userInfo.keys.contains(.encodeForXCBuild) { - guard let signature = self.signature else { + guard let signature else { throw InternalError("Expected to have \(Swift.type(of: self)) signature when encoding for XCBuild") } try container.encode(signature, forKey: "signature") diff --git a/Sources/XCBuildSupport/PIFBuilder.swift b/Sources/XCBuildSupport/PIFBuilder.swift index 74373a0b300..d85a576f4ab 100644 --- a/Sources/XCBuildSupport/PIFBuilder.swift +++ b/Sources/XCBuildSupport/PIFBuilder.swift @@ -649,7 +649,7 @@ final class PackagePIFProjectBuilder: PIFProjectBuilder { throw InternalError("unexpected target") } - if let moduleMapFileContents = moduleMapFileContents { + if let moduleMapFileContents { settings[.MODULEMAP_PATH] = moduleMapFile settings[.MODULEMAP_FILE_CONTENTS] = moduleMapFileContents } diff --git a/Sources/XCBuildSupport/XcodeBuildSystem.swift b/Sources/XCBuildSupport/XcodeBuildSystem.swift index 28b8597fa23..d36815de0f7 100644 --- a/Sources/XCBuildSupport/XcodeBuildSystem.swift +++ b/Sources/XCBuildSupport/XcodeBuildSystem.swift @@ -115,7 +115,7 @@ public final class XcodeBuildSystem: SPMBuildCore.BuildSystem { // Do not generate a build parameters file if a custom one has been passed. if let flags = buildParameters.flags.xcbuildFlags, !flags.contains("--buildParametersFile") { buildParamsFile = try createBuildParametersFile() - if let buildParamsFile = buildParamsFile { + if let buildParamsFile { arguments += ["--buildParametersFile", buildParamsFile.pathString] } } else { @@ -149,7 +149,7 @@ public final class XcodeBuildSystem: SPMBuildCore.BuildSystem { try process.launch() let result = try process.waitUntilExit() - if let buildParamsFile = buildParamsFile { + if let buildParamsFile { try? self.fileSystem.removeFileTree(buildParamsFile) } diff --git a/Tests/CommandsTests/CommandsTestCase.swift b/Tests/CommandsTests/CommandsTestCase.swift index 953a2fcb820..730e6ea9a38 100644 --- a/Tests/CommandsTests/CommandsTestCase.swift +++ b/Tests/CommandsTests/CommandsTestCase.swift @@ -23,7 +23,7 @@ class CommandsTestCase: XCTestCase { } override func tearDown() { - if let originalWorkingDirectory = originalWorkingDirectory { + if let originalWorkingDirectory { try? localFileSystem.changeCurrentWorkingDirectory(to: originalWorkingDirectory) } } diff --git a/Tests/FunctionalTests/MiscellaneousTests.swift b/Tests/FunctionalTests/MiscellaneousTests.swift index 2ea6bd32e07..6cb08734140 100644 --- a/Tests/FunctionalTests/MiscellaneousTests.swift +++ b/Tests/FunctionalTests/MiscellaneousTests.swift @@ -278,7 +278,7 @@ class MiscellaneousTestCase: XCTestCase { var env = ProcessInfo.processInfo.environment let oldPath = env["PATH"] env["PATH"] = fakeGit.parentDirectory.description - if let oldPath = oldPath { + if let oldPath { env["PATH"] = env["PATH"]! + ":" + oldPath } diff --git a/Tests/FunctionalTests/PluginTests.swift b/Tests/FunctionalTests/PluginTests.swift index eee02b04620..85f2612b53f 100644 --- a/Tests/FunctionalTests/PluginTests.swift +++ b/Tests/FunctionalTests/PluginTests.swift @@ -748,7 +748,7 @@ class PluginTests: XCTestCase { delegateQueue.sync { pid = delegate.parsedProcessIdentifier } - guard let pid = pid else { + guard let pid else { throw XCTSkip("skipping test because no pid was received from the plugin; being investigated as rdar://88792829\n\(delegate.diagnostics.description)") } diff --git a/Tests/PackageGraphTests/PubgrubTests.swift b/Tests/PackageGraphTests/PubgrubTests.swift index 5a74c3c3b05..7cd5e2d0462 100644 --- a/Tests/PackageGraphTests/PubgrubTests.swift +++ b/Tests/PackageGraphTests/PubgrubTests.swift @@ -2910,7 +2910,7 @@ public class MockContainer: PackageContainer { } public func loadPackageReference(at boundVersion: BoundVersion) throws -> PackageReference { - if let manifestName = manifestName { + if let manifestName { self.package = self.package.withName(manifestName.identity.description) } return self.package diff --git a/Tests/PackageLoadingTests/PackageBuilderTests.swift b/Tests/PackageLoadingTests/PackageBuilderTests.swift index 861f9c2d475..40002660c36 100644 --- a/Tests/PackageLoadingTests/PackageBuilderTests.swift +++ b/Tests/PackageLoadingTests/PackageBuilderTests.swift @@ -3069,16 +3069,16 @@ final class PackageBuilderTester { } func check(c99name: String? = nil, type: PackageModel.Target.Kind? = nil, file: StaticString = #file, line: UInt = #line) { - if let c99name = c99name { + if let c99name { XCTAssertEqual(target.c99name, c99name, file: file, line: line) } - if let type = type { + if let type { XCTAssertEqual(target.type, type, file: file, line: line) } } func checkSources(root: String? = nil, sources paths: [String], file: StaticString = #file, line: UInt = #line) { - if let root = root { + if let root { XCTAssertEqual(target.sources.root, try! AbsolutePath(validating: root), file: file, line: line) } let sources = Set(self.target.sources.relativePaths.map({ $0.pathString })) diff --git a/Tests/WorkspaceTests/WorkspaceTests.swift b/Tests/WorkspaceTests/WorkspaceTests.swift index dff17270375..8d070581542 100644 --- a/Tests/WorkspaceTests/WorkspaceTests.swift +++ b/Tests/WorkspaceTests/WorkspaceTests.swift @@ -10878,7 +10878,7 @@ final class WorkspaceTests: XCTestCase { callbackQueue: DispatchQueue, completion: @escaping (Result) -> Void ) { - if let error = self.error { + if let error { callbackQueue.async { completion(.failure(error)) }