From 76e6b39d112ed22c1ec2d704bdded5267b2029a0 Mon Sep 17 00:00:00 2001 From: Ian Leitch Date: Mon, 19 Aug 2024 15:08:17 +0200 Subject: [PATCH] Add SwiftFormat (#794) --- .swiftformat | 6 + Makefile | 3 + Package.swift | 97 ++++---- Sources/Frontend/Commands/ScanBehavior.swift | 6 +- Sources/Frontend/GuidedSetup.swift | 10 +- Sources/Frontend/Project.swift | 14 +- Sources/Frontend/Scan.swift | 2 +- Sources/Frontend/UpdateChecker.swift | 35 +-- Sources/Frontend/main.swift | 12 +- Sources/Indexer/Indexer.swift | 1 + Sources/Indexer/InfoPlistParser.swift | 2 +- Sources/Indexer/SourceFileCollector.swift | 8 +- Sources/Indexer/SwiftIndexer.swift | 37 ++-- Sources/PeripheryKit/Results/Baseline.swift | 4 +- .../Results/CheckstyleFormatter.swift | 8 +- .../Results/CodeClimateFormatter.swift | 22 +- .../PeripheryKit/Results/CsvFormatter.swift | 7 +- .../Results/GitHubActionsFormatter.swift | 4 +- .../PeripheryKit/Results/JsonFormatter.swift | 6 +- .../Results/OutputDeclarationFilter.swift | 4 +- .../Results/OutputFormatter.swift | 24 +- .../PeripheryKit/Results/XcodeFormatter.swift | 2 +- Sources/PeripheryKit/ScanResultBuilder.swift | 9 +- .../ProjectDrivers/BazelProjectDriver.swift | 18 +- Sources/ProjectDrivers/ProjectDriver.swift | 10 +- Sources/ProjectDrivers/SPMProjectDriver.swift | 8 +- .../ProjectDrivers/XcodeProjectDriver.swift | 208 +++++++++--------- Sources/Shared/Configuration.swift | 10 +- .../Extensions/Collection+Extension.swift | 2 +- .../Extensions/FilePath+Extension.swift | 6 +- Sources/Shared/Extensions/FilePath+Glob.swift | 26 +-- .../Extensions/Sequence+Extension.swift | 4 +- .../Shared/Extensions/String+Extension.swift | 6 +- Sources/Shared/Logger.swift | 51 ++--- Sources/Shared/PeripheryError.swift | 14 +- Sources/Shared/SPM.swift | 4 +- Sources/Shared/SetupGuide.swift | 15 +- Sources/Shared/Shell.swift | 41 ++-- Sources/Shared/SwiftVersion.swift | 7 +- Sources/Shared/SwiftVersionParser.swift | 2 +- Sources/Shared/UnfairLock.swift | 42 ++-- .../SourceGraph/Elements/Accessibility.swift | 10 +- .../SourceGraph/Elements/AssetReference.swift | 2 +- .../SourceGraph/Elements/Declaration.swift | 90 ++++---- Sources/SourceGraph/Elements/Location.swift | 10 +- .../Elements/ProjectFileKind.swift | 8 +- Sources/SourceGraph/Elements/Reference.swift | 6 +- .../Mutators/AccessibilityCascader.swift | 4 +- .../AncestralReferenceEliminator.swift | 2 +- .../Mutators/AssetReferenceRetainer.swift | 4 +- ...ssignOnlyPropertyReferenceEliminator.swift | 2 +- .../CapitalSelfFunctionCallRetainer.swift | 2 +- .../CodingKeyEnumReferenceBuilder.swift | 2 +- ...plexPropertyAccessorReferenceBuilder.swift | 2 +- .../DefaultConstructorReferenceBuilder.swift | 6 +- .../DynamicMemberLookupReferenceBuilder.swift | 2 +- .../EntryPointAttributeRetainer.swift | 10 +- .../Mutators/EnumCaseReferenceBuilder.swift | 2 +- .../Mutators/ExtensionReferenceBuilder.swift | 2 +- ...eProtocolConformanceReferenceRemover.swift | 6 +- ...AndStructConstructorReferenceBuilder.swift | 2 +- .../InterfaceBuilderPropertyRetainer.swift | 2 +- .../Mutators/ObjCAccessibleRetainer.swift | 19 +- .../Mutators/PropertyWrapperRetainer.swift | 2 +- .../ProtocolConformanceReferenceBuilder.swift | 8 +- .../ProtocolExtensionReferenceBuilder.swift | 2 +- .../Mutators/PubliclyAccessibleRetainer.swift | 2 +- ...antExplicitPublicAccessibilityMarker.swift | 21 +- .../Mutators/RedundantProtocolMarker.swift | 4 +- .../Mutators/ResultBuilderRetainer.swift | 4 +- ...rpolationAppendInterpolationRetainer.swift | 17 +- ...tImplicitInitializerReferenceBuilder.swift | 2 +- .../Mutators/SwiftUIRetainer.swift | 2 +- .../Mutators/UnusedImportMarker.swift | 2 +- .../Mutators/UnusedParameterRetainer.swift | 8 +- .../Mutators/UsedDeclarationMarker.swift | 4 +- .../SourceGraph/Mutators/XCTestRetainer.swift | 2 +- Sources/SourceGraph/SourceGraph.swift | 8 +- .../SourceGraphMutatorRunner.swift | 4 +- Sources/SyntaxAnalysis/CommentCommand.swift | 4 +- .../DeclarationSyntaxVisitor.swift | 47 ++-- .../SyntaxAnalysis/ImportSyntaxVisitor.swift | 5 +- .../MultiplexingSyntaxVisitor.swift | 88 ++++---- .../SourceLocationBuilder.swift | 2 +- .../UnusedParameterAnalyzer.swift | 25 ++- .../UnusedParameterParser.swift | 58 ++--- Sources/XcodeSupport/XcodeProject.swift | 11 +- .../XcodeSupport/XcodeProjectSetupGuide.swift | 2 +- Sources/XcodeSupport/XcodeWorkspace.swift | 18 +- Sources/XcodeSupport/Xcodebuild.swift | 21 +- .../RedundantPublicAccessibilityTest.swift | 12 +- .../Extensions/FilePathGlobTest.swift | 16 +- .../ObjcAccessibleRetentionTest.swift | 100 ++++----- .../ObjcAnnotatedRetentionTest.swift | 44 ++-- Tests/PeripheryTests/RetentionTest.swift | 9 +- Tests/PeripheryTests/ShellTest.swift | 2 +- .../Syntax/FunctionVisitTest.swift | 38 ++-- .../Syntax/PropertyVisitTest.swift | 8 +- .../Syntax/TypeSyntaxInspectorTest.swift | 22 +- Tests/SPMTests/SPMProject/Package.swift | 8 +- Tests/Shared/SPMSourceGraphTestCase.swift | 2 +- Tests/Shared/SourceGraphTestCase.swift | 13 +- Tests/Shared/XCTestCase+Extensions.swift | 6 +- .../XcodeTests/XcodeSourceGraphTestCase.swift | 2 +- .../XcodebuildBuildProjectTest.swift | 4 +- scripts/lint/swiftformat.sh | 11 + 106 files changed, 844 insertions(+), 818 deletions(-) create mode 100644 .swiftformat create mode 100755 scripts/lint/swiftformat.sh diff --git a/.swiftformat b/.swiftformat new file mode 100644 index 0000000000..da563d4617 --- /dev/null +++ b/.swiftformat @@ -0,0 +1,6 @@ +--swiftversion 5.10 + +--exclude Tests/Fixtures/ +--exclude Tests/AccessibilityTests/AccessibilityProject/ +--exclude Tests/XcodeTests/UIKitProject/ +--exclude Tests/XcodeTests/SwiftUIProject/ \ No newline at end of file diff --git a/Makefile b/Makefile index 6b5533aab5..e179b10300 100644 --- a/Makefile +++ b/Makefile @@ -20,3 +20,6 @@ build_release: clean build_x86_64 build_arm64 show_bin_path: @echo ${EXECUTABLE} + +swiftformat: + @./scripts/lint/swiftformat.sh \ No newline at end of file diff --git a/Package.swift b/Package.swift index 4280c20c66..6657cc9113 100644 --- a/Package.swift +++ b/Package.swift @@ -8,40 +8,39 @@ var dependencies: [Package.Dependency] = [ .package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.0"), .package(url: "https://github.com/ileitch/swift-indexstore", from: "9.0.4"), .package(url: "https://github.com/apple/swift-syntax", from: "510.0.3"), - .package(url: "https://github.com/ileitch/swift-filename-matcher", from: "0.0.0") + .package(url: "https://github.com/ileitch/swift-filename-matcher", from: "0.0.0"), ] #if os(macOS) -dependencies.append( - .package( - url: "https://github.com/tuist/xcodeproj", - from: "8.16.0" + dependencies.append( + .package( + url: "https://github.com/tuist/xcodeproj", + from: "8.16.0" + ) ) -) #endif var projectDriverDependencies: [PackageDescription.Target.Dependency] = [ - .target(name: "SourceGraph"), - .target(name: "Shared"), - .target(name: "Indexer"), + .target(name: "SourceGraph"), + .target(name: "Shared"), + .target(name: "Indexer"), ] #if os(macOS) -projectDriverDependencies.append(.target(name: "XcodeSupport")) + projectDriverDependencies.append(.target(name: "XcodeSupport")) #endif - var targets: [PackageDescription.Target] = [ .executableTarget( name: "Frontend", dependencies: [ - .target(name: "Shared"), - .target(name: "SourceGraph"), - .target(name: "PeripheryKit"), - .target(name: "ProjectDrivers"), - .product(name: "ArgumentParser", package: "swift-argument-parser"), - .product(name: "FilenameMatcher", package: "swift-filename-matcher") - ] + .target(name: "Shared"), + .target(name: "SourceGraph"), + .target(name: "PeripheryKit"), + .target(name: "ProjectDrivers"), + .product(name: "ArgumentParser", package: "swift-argument-parser"), + .product(name: "FilenameMatcher", package: "swift-filename-matcher"), + ] ), .target( name: "PeripheryKit", @@ -54,7 +53,7 @@ var targets: [PackageDescription.Target] = [ .product(name: "SwiftSyntax", package: "swift-syntax"), .product(name: "SwiftParser", package: "swift-syntax"), .product(name: "SwiftIndexStore", package: "swift-indexstore"), - .product(name: "FilenameMatcher", package: "swift-filename-matcher") + .product(name: "FilenameMatcher", package: "swift-filename-matcher"), ] ), .target( @@ -66,8 +65,8 @@ var targets: [PackageDescription.Target] = [ ] ), .target( - name: "ProjectDrivers", - dependencies: projectDriverDependencies + name: "ProjectDrivers", + dependencies: projectDriverDependencies ), .target( name: "SyntaxAnalysis", @@ -82,7 +81,7 @@ var targets: [PackageDescription.Target] = [ name: "SourceGraph", dependencies: [ .product(name: "SwiftSyntax", package: "swift-syntax"), - .target(name: "Shared") + .target(name: "Shared"), ] ), .target( @@ -90,14 +89,14 @@ var targets: [PackageDescription.Target] = [ dependencies: [ .product(name: "Yams", package: "Yams"), .product(name: "SystemPackage", package: "swift-system"), - .product(name: "FilenameMatcher", package: "swift-filename-matcher") + .product(name: "FilenameMatcher", package: "swift-filename-matcher"), ] ), .target( name: "TestShared", dependencies: [ .target(name: "PeripheryKit"), - .target(name: "ProjectDrivers") + .target(name: "ProjectDrivers"), ], path: "Tests/Shared" ), @@ -105,14 +104,14 @@ var targets: [PackageDescription.Target] = [ name: "PeripheryTests", dependencies: [ .target(name: "TestShared"), - .target(name: "PeripheryKit") + .target(name: "PeripheryKit"), ] ), .testTarget( name: "SPMTests", dependencies: [ .target(name: "TestShared"), - .target(name: "PeripheryKit") + .target(name: "PeripheryKit"), ], exclude: ["SPMProject"] ), @@ -120,33 +119,33 @@ var targets: [PackageDescription.Target] = [ name: "AccessibilityTests", dependencies: [ .target(name: "TestShared"), - .target(name: "PeripheryKit") + .target(name: "PeripheryKit"), ], exclude: ["AccessibilityProject"] - ) + ), ] #if os(macOS) -targets.append(contentsOf: [ - .target( - name: "XcodeSupport", - dependencies: [ - .target(name: "SourceGraph"), - .target(name: "Shared"), - .target(name: "PeripheryKit"), - .product(name: "XcodeProj", package: "XcodeProj") - ] - ), - .testTarget( - name: "XcodeTests", - dependencies: [ - .target(name: "ProjectDrivers"), - .target(name: "TestShared"), - .target(name: "PeripheryKit"), - ], - exclude: ["UIKitProject", "SwiftUIProject"] - ) -]) + targets.append(contentsOf: [ + .target( + name: "XcodeSupport", + dependencies: [ + .target(name: "SourceGraph"), + .target(name: "Shared"), + .target(name: "PeripheryKit"), + .product(name: "XcodeProj", package: "XcodeProj"), + ] + ), + .testTarget( + name: "XcodeTests", + dependencies: [ + .target(name: "ProjectDrivers"), + .target(name: "TestShared"), + .target(name: "PeripheryKit"), + ], + exclude: ["UIKitProject", "SwiftUIProject"] + ), + ]) #endif let package = Package( @@ -154,7 +153,7 @@ let package = Package( platforms: [.macOS(.v13)], products: [ .executable(name: "periphery", targets: ["Frontend"]), - .library(name: "PeripheryKit", targets: ["PeripheryKit"]) + .library(name: "PeripheryKit", targets: ["PeripheryKit"]), ], dependencies: dependencies, targets: targets, diff --git a/Sources/Frontend/Commands/ScanBehavior.swift b/Sources/Frontend/Commands/ScanBehavior.swift index e77dda4fe5..aeb35809ba 100644 --- a/Sources/Frontend/Commands/ScanBehavior.swift +++ b/Sources/Frontend/Commands/ScanBehavior.swift @@ -12,7 +12,7 @@ final class ScanBehavior { self.logger = logger } - func setup(_ configPath: FilePath?) -> Result<(), PeripheryError> { + func setup(_ configPath: FilePath?) -> Result { do { try configuration.load(from: configPath) } catch let error as PeripheryError { @@ -24,7 +24,7 @@ final class ScanBehavior { return .success(()) } - func main(_ block: (Project) throws -> [ScanResult]) -> Result<(), PeripheryError> { + func main(_ block: (Project) throws -> [ScanResult]) -> Result { logger.contextualized(with: "version").debug(PeripheryVersion) let project: Project @@ -82,7 +82,7 @@ final class ScanBehavior { updateChecker.notifyIfAvailable() - if !filteredResults.isEmpty && configuration.strict { + if !filteredResults.isEmpty, configuration.strict { throw PeripheryError.foundIssues(count: filteredResults.count) } } catch let error as PeripheryError { diff --git a/Sources/Frontend/GuidedSetup.swift b/Sources/Frontend/GuidedSetup.swift index a14b1bcfcb..7d618b4a39 100644 --- a/Sources/Frontend/GuidedSetup.swift +++ b/Sources/Frontend/GuidedSetup.swift @@ -2,7 +2,7 @@ import Foundation import Shared #if canImport(XcodeSupport) -import XcodeSupport + import XcodeSupport #endif final class GuidedSetup: SetupGuideHelpers { @@ -23,16 +23,16 @@ final class GuidedSetup: SetupGuideHelpers { } #if canImport(XcodeSupport) - if let guide = XcodeProjectSetupGuide.detect() { - projectGuides.append(guide) - } + if let guide = XcodeProjectSetupGuide.detect() { + projectGuides.append(guide) + } #endif var projectGuide_: SetupGuide? if projectGuides.count > 1 { print(colorize("Please select which project to use:", .bold)) - let kindName = select(single: projectGuides.map { $0.projectKindName }) + let kindName = select(single: projectGuides.map(\.projectKindName)) projectGuide_ = projectGuides.first { $0.projectKindName == kindName } print("") } else { diff --git a/Sources/Frontend/Project.swift b/Sources/Frontend/Project.swift index e9e396faad..8c5e1deb4c 100644 --- a/Sources/Frontend/Project.swift +++ b/Sources/Frontend/Project.swift @@ -11,8 +11,8 @@ final class Project { return self.init(kind: .xcode(projectPath: path)) } else if let path = configuration.genericProjectConfig { return self.init(kind: .generic(genericProjectConfig: path)) - } else if BazelProjectDriver.isSupported && configuration.bazel { - return self.init(kind: .bazel) + } else if BazelProjectDriver.isSupported, configuration.bazel { + return self.init(kind: .bazel) } else if SPM.isSupported { return self.init(kind: .spm) } @@ -28,17 +28,17 @@ final class Project { func driver() throws -> ProjectDriver { switch kind { - case .xcode(let projectPath): + case let .xcode(projectPath): #if canImport(XcodeSupport) - return try XcodeProjectDriver.build(projectPath: projectPath) + return try XcodeProjectDriver.build(projectPath: projectPath) #else - fatalError("Xcode projects are not supported on this platform.") + fatalError("Xcode projects are not supported on this platform.") #endif case .spm: return try SPMProjectDriver.build() case .bazel: - return try BazelProjectDriver.build() - case .generic(let genericProjectConfig): + return try BazelProjectDriver.build() + case let .generic(genericProjectConfig): return try GenericProjectDriver.build(genericProjectConfig: genericProjectConfig) } } diff --git a/Sources/Frontend/Scan.swift b/Sources/Frontend/Scan.swift index b0bac2e358..755e35648d 100644 --- a/Sources/Frontend/Scan.swift +++ b/Sources/Frontend/Scan.swift @@ -1,7 +1,7 @@ import Foundation -import ProjectDrivers import Indexer import PeripheryKit +import ProjectDrivers import Shared import SourceGraph diff --git a/Sources/Frontend/UpdateChecker.swift b/Sources/Frontend/UpdateChecker.swift index dbd7db27da..83fc25bd53 100644 --- a/Sources/Frontend/UpdateChecker.swift +++ b/Sources/Frontend/UpdateChecker.swift @@ -2,7 +2,7 @@ import Foundation import Shared #if canImport(FoundationNetworking) -import FoundationNetworking + import FoundationNetworking #endif final class UpdateChecker { @@ -17,7 +17,7 @@ final class UpdateChecker { required init(logger: Logger = .init(), configuration: Configuration = .shared) { self.logger = logger - self.debugLogger = logger.contextualized(with: "update-check") + debugLogger = logger.contextualized(with: "update-check") self.configuration = configuration let config = URLSessionConfiguration.ephemeral urlSession = URLSession(configuration: config) @@ -33,7 +33,7 @@ final class UpdateChecker { // We only perform the update check with xcode format because it may interfere with // parsing json and csv. guard !configuration.disableUpdateCheck, - configuration.outputFormat.supportsAuxiliaryOutput else { return } + configuration.outputFormat.supportsAuxiliaryOutput else { return } var urlRequest = URLRequest(url: latestReleaseURL) urlRequest.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept") @@ -50,22 +50,23 @@ final class UpdateChecker { } guard let jsonData = data, - let jsonObject = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [AnyHashable: Any], - let tagName = jsonObject["tag_name"] as? String else { - var json = "N/A" - - if let data { - let decoded = String(decoding: data, as: UTF8.self) - if !decoded.isEmpty { - json = decoded - } + let jsonObject = try? JSONSerialization.jsonObject(with: jsonData, options: []) as? [AnyHashable: Any], + let tagName = jsonObject["tag_name"] as? String + else { + var json = "N/A" + + if let data { + let decoded = String(decoding: data, as: UTF8.self) + if !decoded.isEmpty { + json = decoded } + } - let message = "Failed to identify latest release tag in: \(json)" - strongSelf.error = PeripheryError.updateCheckError(message: message) - strongSelf.debugLogger.debug(message) - strongSelf.semaphore.signal() - return + let message = "Failed to identify latest release tag in: \(json)" + strongSelf.error = PeripheryError.updateCheckError(message: message) + strongSelf.debugLogger.debug(message) + strongSelf.semaphore.signal() + return } strongSelf.latestVersion = tagName diff --git a/Sources/Frontend/main.swift b/Sources/Frontend/main.swift index 599d5b1491..9e7ed7f387 100644 --- a/Sources/Frontend/main.swift +++ b/Sources/Frontend/main.swift @@ -8,10 +8,10 @@ struct PeripheryCommand: FrontendCommand { static let configuration = CommandConfiguration( commandName: "periphery", subcommands: [ - ScanCommand.self, - CheckUpdateCommand.self, - ClearCacheCommand.self, - VersionCommand.self + ScanCommand.self, + CheckUpdateCommand.self, + ClearCacheCommand.self, + VersionCommand.self, ] ) } @@ -19,8 +19,8 @@ struct PeripheryCommand: FrontendCommand { signal(SIGINT) { _ in let logger = Logger() logger.warn( - "Termination can result in a corrupt index. Try the '--clean-build' flag if you get erroneous results such as false-positives and incorrect source file locations.", - newlinePrefix: true // Print a newline after ^C + "Termination can result in a corrupt index. Try the '--clean-build' flag if you get erroneous results such as false-positives and incorrect source file locations.", + newlinePrefix: true // Print a newline after ^C ) Shell.shared.interruptRunning() exit(0) diff --git a/Sources/Indexer/Indexer.swift b/Sources/Indexer/Indexer.swift index e3772d778b..8bd993b430 100644 --- a/Sources/Indexer/Indexer.swift +++ b/Sources/Indexer/Indexer.swift @@ -3,6 +3,7 @@ import Foundation import Shared import SourceGraph import SystemPackage + class Indexer { private let configuration: Configuration diff --git a/Sources/Indexer/InfoPlistParser.swift b/Sources/Indexer/InfoPlistParser.swift index a1fe0c9f3d..a6dac4d7e5 100644 --- a/Sources/Indexer/InfoPlistParser.swift +++ b/Sources/Indexer/InfoPlistParser.swift @@ -7,7 +7,7 @@ import SystemPackage final class InfoPlistParser { private static let elements = [ "UISceneClassName", "UISceneDelegateClassName", "NSPrincipalClass", - "NSExtensionPrincipalClass", "CLKComplicationPrincipalClass", "WKExtensionDelegateClassName" + "NSExtensionPrincipalClass", "CLKComplicationPrincipalClass", "WKExtensionDelegateClassName", ] private let path: FilePath diff --git a/Sources/Indexer/SourceFileCollector.swift b/Sources/Indexer/SourceFileCollector.swift index 7e80b4b589..d02a820959 100644 --- a/Sources/Indexer/SourceFileCollector.swift +++ b/Sources/Indexer/SourceFileCollector.swift @@ -51,17 +51,17 @@ public struct SourceFileCollector { return nil } } - .reduce(into: [FilePath: [(IndexStore, IndexStoreUnit, String?)]](), { result, tuple in + .reduce(into: [FilePath: [(IndexStore, IndexStoreUnit, String?)]]()) { result, tuple in let (file, indexStore, unit, module) = tuple result[file, default: []].append((indexStore, unit, module)) - }) - .reduce(into: [SourceFile: [IndexUnit]](), { result, pair in + } + .reduce(into: [SourceFile: [IndexUnit]]()) { result, pair in let (file, tuples) = pair let modules = tuples.compactMapSet { $0.2 } let sourceFile = SourceFile(path: file, modules: modules) let units = tuples.map { IndexUnit(store: $0.0, unit: $0.1) } result[sourceFile] = units - }) + } } // MARK: - Private diff --git a/Sources/Indexer/SwiftIndexer.swift b/Sources/Indexer/SwiftIndexer.swift index ede546a757..3231bc6ec9 100644 --- a/Sources/Indexer/SwiftIndexer.swift +++ b/Sources/Indexer/SwiftIndexer.swift @@ -136,6 +136,7 @@ final class SwiftIndexer: Indexer { Key(kind: kind, name: name, isImplicit: isImplicit, isObjcAccessible: isObjcAccessible, location: location) } } + // swiftlint:enable nesting /// Phase one reads the index store and establishes the declaration hierarchy and the majority of references. @@ -152,7 +153,7 @@ final class SwiftIndexer: Indexer { try unit.store.forEachOccurrences(for: record, language: .swift) { occurrence in guard let usr = occurrence.symbol.usr, let location = try transformLocation(occurrence.location) - else { return true } + else { return true } if !occurrence.roles.isDisjoint(with: [.definition, .declaration]) { if let (decl, relations) = try parseRawDeclaration(occurrence, usr, location, unit.store) { @@ -161,11 +162,11 @@ final class SwiftIndexer: Indexer { } if occurrence.roles.contains(.reference) { - references.formUnion(try parseReference(occurrence, usr, location, unit.store)) + try references.formUnion(parseReference(occurrence, usr, location, unit.store)) } if occurrence.roles.contains(.implicit) { - references.formUnion(try parseImplicit(occurrence, usr, location, unit.store)) + try references.formUnion(parseImplicit(occurrence, usr, location, unit.store)) } return true @@ -189,12 +190,12 @@ final class SwiftIndexer: Indexer { graph.markRetained(decl) } - if decl.isObjcAccessible && configuration.retainObjcAccessible { + if decl.isObjcAccessible, configuration.retainObjcAccessible { graph.markRetained(decl) } - let relations = values.flatMap { $0.1 } - references.formUnion(try parseDeclaration(decl, relations)) + let relations = values.flatMap(\.1) + try references.formUnion(parseDeclaration(decl, relations)) newDeclarations.insert(decl) declarations.append(decl) @@ -301,7 +302,7 @@ final class SwiftIndexer: Indexer { for ref in danglingReferences { let sameLineCandidateDecls = declsByLocation[ref.location] ?? - declsByLine[ref.location.line] + declsByLine[ref.location.line] var candidateDecls = [Declaration]() if let sameLineCandidateDecls { @@ -396,10 +397,10 @@ final class SwiftIndexer: Indexer { } private func retainHierarchy(_ decls: [Declaration]) { - decls.forEach { - graph.markRetained($0) - $0.unusedParameters.forEach { graph.markRetained($0) } - retainHierarchy(Array($0.declarations)) + for decl in decls { + graph.markRetained(decl) + decl.unusedParameters.forEach { graph.markRetained($0) } + retainHierarchy(Array(decl.declarations)) } } @@ -420,7 +421,7 @@ final class SwiftIndexer: Indexer { } private func identifyUnusedParameters(using syntaxVisitor: MultiplexingSyntaxVisitor) { - let functionDecls = declarations.filter { $0.kind.isFunctionKind } + let functionDecls = declarations.filter(\.kind.isFunctionKind) let functionDeclsByLocation = functionDecls.reduce(into: [Location: Declaration]()) { $0[$1.location] = $1 } @@ -430,7 +431,8 @@ final class SwiftIndexer: Indexer { file: syntaxVisitor.sourceFile, syntax: syntaxVisitor.syntax, locationConverter: syntaxVisitor.locationConverter, - parseProtocols: true) + parseProtocols: true + ) for (function, params) in paramsByFunction { guard let functionDecl = functionDeclsByLocation[function.location] else { @@ -488,7 +490,8 @@ final class SwiftIndexer: Indexer { name: occurrence.symbol.name, isImplicit: occurrence.roles.contains(.implicit), isObjcAccessible: usr.hasPrefix("c:"), - location: location) + location: location + ) var relations: [RawRelation] = [] @@ -520,7 +523,7 @@ final class SwiftIndexer: Indexer { for rel in relations { if rel.roles.contains(.childOf) { if let parentUsr = rel.symbol.usr { - self.childDeclsByParentUsr[parentUsr, default: []].insert(decl) + childDeclsByParentUsr[parentUsr, default: []].insert(decl) } } @@ -554,7 +557,7 @@ final class SwiftIndexer: Indexer { ) reference.name = decl.name references.insert(reference) - self.referencesByUsr[referencerUsr, default: []].insert(reference) + referencesByUsr[referencerUsr, default: []].insert(reference) } } } @@ -601,7 +604,7 @@ final class SwiftIndexer: Indexer { _ indexStore: IndexStore ) throws -> [Reference] { guard let kind = transformDeclarationKind(occurrence.symbol.kind, occurrence.symbol.subKind) - else { return [] } + else { return [] } guard kind != .varParameter else { // Ignore indexed parameters as unused parameter identification is performed separately using SwiftSyntax. diff --git a/Sources/PeripheryKit/Results/Baseline.swift b/Sources/PeripheryKit/Results/Baseline.swift index 8a6fb5ae89..7f558269d0 100644 --- a/Sources/PeripheryKit/Results/Baseline.swift +++ b/Sources/PeripheryKit/Results/Baseline.swift @@ -6,8 +6,8 @@ public enum Baseline: Codable { public var usrs: Set { switch self { - case .v1(let usrs): - return Set(usrs) + case let .v1(usrs): + Set(usrs) } } } diff --git a/Sources/PeripheryKit/Results/CheckstyleFormatter.swift b/Sources/PeripheryKit/Results/CheckstyleFormatter.swift index 6e1b2fee84..706f76ed62 100644 --- a/Sources/PeripheryKit/Results/CheckstyleFormatter.swift +++ b/Sources/PeripheryKit/Results/CheckstyleFormatter.swift @@ -5,7 +5,7 @@ import SystemPackage final class CheckstyleFormatter: OutputFormatter { let configuration: Configuration - lazy var currentFilePath: FilePath = { .current }() + lazy var currentFilePath: FilePath = .current init(configuration: Configuration) { self.configuration = configuration @@ -19,7 +19,7 @@ final class CheckstyleFormatter: OutputFormatter { .group(by: { outputPath($0.0).string.escapedForXML() }) .sorted(by: { $0.key < $1.key }) .map(generateForFile).joined(), - "\n" + "\n", ].joined() } @@ -29,7 +29,7 @@ final class CheckstyleFormatter: OutputFormatter { [ "\n\t\n", results.map(generateForResult).joined(), - "\t" + "\t", ].joined() } @@ -41,7 +41,7 @@ final class CheckstyleFormatter: OutputFormatter { "\t\t\n" + "message=\"", result.1.escapedForXML(), "\"/>\n", ].joined() } } diff --git a/Sources/PeripheryKit/Results/CodeClimateFormatter.swift b/Sources/PeripheryKit/Results/CodeClimateFormatter.swift index b7f901274e..c3400ce795 100644 --- a/Sources/PeripheryKit/Results/CodeClimateFormatter.swift +++ b/Sources/PeripheryKit/Results/CodeClimateFormatter.swift @@ -4,7 +4,7 @@ import SystemPackage final class CodeClimateFormatter: OutputFormatter { let configuration: Configuration - lazy var currentFilePath: FilePath = { .current }() + lazy var currentFilePath: FilePath = .current init(configuration: Configuration) { self.configuration = configuration @@ -15,34 +15,34 @@ final class CodeClimateFormatter: OutputFormatter { for result in results { let lines: [AnyHashable: Any] = [ - "begin": result.declaration.location.line + "begin": result.declaration.location.line, ] let location: [AnyHashable: Any] = [ "path": outputPath(result.declaration.location).url.relativePath, - "lines": lines + "lines": lines, ] let description = describe(result, colored: false) - .map { $0.1 } + .map(\.1) .joined(separator: ", ") - let fingerprint: String - if result.declaration.kind == .varParameter, - let parentFingerprint = result.declaration.parent?.usrs.joined(separator: "."), - let argumentName = result.declaration.name { + let fingerprint: String = if result.declaration.kind == .varParameter, + let parentFingerprint = result.declaration.parent?.usrs.joined(separator: "."), + let argumentName = result.declaration.name + { // As function parameters do not have a mangled name that can be used for the fingerprint // we take the mangled name of the function and append the position - fingerprint = "\(parentFingerprint)-\(argumentName)" + "\(parentFingerprint)-\(argumentName)" } else { - fingerprint = result.declaration.usrs.joined(separator: ".") + result.declaration.usrs.joined(separator: ".") } let object: [AnyHashable: Any] = [ "description": description, "fingerprint": fingerprint, "severity": "major", - "location": location + "location": location, ] jsonObject.append(object) diff --git a/Sources/PeripheryKit/Results/CsvFormatter.swift b/Sources/PeripheryKit/Results/CsvFormatter.swift index 5a674dc0fe..280f70122d 100644 --- a/Sources/PeripheryKit/Results/CsvFormatter.swift +++ b/Sources/PeripheryKit/Results/CsvFormatter.swift @@ -5,14 +5,14 @@ import SystemPackage final class CsvFormatter: OutputFormatter { let configuration: Configuration - lazy var currentFilePath: FilePath = { .current }() + lazy var currentFilePath: FilePath = .current init(configuration: Configuration) { self.configuration = configuration } func format(_ results: [ScanResult]) -> String { - var lines: [String] = ["Kind,Name,Modifiers,Attributes,Accessibility,IDs,Location,Hints"] + var lines = ["Kind,Name,Modifiers,Attributes,Accessibility,IDs,Location,Hints"] for result in results { let line = format( @@ -38,7 +38,8 @@ final class CsvFormatter: OutputFormatter { accessibility: nil, usrs: [ref.usr], location: ref.location, - hint: redundantConformanceHint(with: inherited)) + hint: redundantConformanceHint(with: inherited) + ) lines.append(line) } default: diff --git a/Sources/PeripheryKit/Results/GitHubActionsFormatter.swift b/Sources/PeripheryKit/Results/GitHubActionsFormatter.swift index 89a57bf7e3..b20af84d73 100644 --- a/Sources/PeripheryKit/Results/GitHubActionsFormatter.swift +++ b/Sources/PeripheryKit/Results/GitHubActionsFormatter.swift @@ -5,7 +5,7 @@ import SystemPackage final class GitHubActionsFormatter: OutputFormatter { let configuration: Configuration - lazy var currentFilePath: FilePath = { .current }() + lazy var currentFilePath: FilePath = .current init(configuration: Configuration) { self.configuration = configuration @@ -13,7 +13,7 @@ final class GitHubActionsFormatter: OutputFormatter { func format(_ results: [ScanResult]) throws -> String { guard !results.isEmpty else { return "" } - guard configuration.relativeResults else { throw PeripheryError.usageError("`periphery scan` must be ran with `--relative-results` when using the GitHub Actions formatter")} + guard configuration.relativeResults else { throw PeripheryError.usageError("`periphery scan` must be ran with `--relative-results` when using the GitHub Actions formatter") } return results.flatMap { result in describe(result, colored: false).map { location, description in diff --git a/Sources/PeripheryKit/Results/JsonFormatter.swift b/Sources/PeripheryKit/Results/JsonFormatter.swift index 1eaa6e02ca..5e802d5a5d 100644 --- a/Sources/PeripheryKit/Results/JsonFormatter.swift +++ b/Sources/PeripheryKit/Results/JsonFormatter.swift @@ -4,7 +4,7 @@ import SystemPackage final class JsonFormatter: OutputFormatter { let configuration: Configuration - lazy var currentFilePath: FilePath = { .current }() + lazy var currentFilePath: FilePath = .current init(configuration: Configuration) { self.configuration = configuration @@ -23,7 +23,7 @@ final class JsonFormatter: OutputFormatter { "accessibility": result.declaration.accessibility.value.rawValue, "ids": Array(result.declaration.usrs), "hints": [describe(result.annotation)], - "location": locationDescription(result.declaration.location) + "location": locationDescription(result.declaration.location), ] jsonObject.append(object) @@ -38,7 +38,7 @@ final class JsonFormatter: OutputFormatter { "accessibility": "", "ids": [ref.usr], "hints": [redundantConformanceHint(with: inherited)], - "location": locationDescription(ref.location) + "location": locationDescription(ref.location), ] jsonObject.append(object) } diff --git a/Sources/PeripheryKit/Results/OutputDeclarationFilter.swift b/Sources/PeripheryKit/Results/OutputDeclarationFilter.swift index 89361c1a5f..89379f492c 100644 --- a/Sources/PeripheryKit/Results/OutputDeclarationFilter.swift +++ b/Sources/PeripheryKit/Results/OutputDeclarationFilter.swift @@ -11,7 +11,7 @@ public final class OutputDeclarationFilter { public required init(configuration: Configuration = .shared, logger: Logger = .init()) { self.configuration = configuration self.logger = logger - self.contextualLogger = logger.contextualized(with: "report:filter") + contextualLogger = logger.contextualized(with: "report:filter") } public func filter(_ declarations: [ScanResult], with baseline: Baseline?) throws -> [ScanResult] { @@ -32,7 +32,7 @@ public final class OutputDeclarationFilter { } } - if configuration.reportInclude.isEmpty && configuration.reportExclude.isEmpty { + if configuration.reportInclude.isEmpty, configuration.reportExclude.isEmpty { return declarations.sorted { $0.declaration < $1.declaration } } diff --git a/Sources/PeripheryKit/Results/OutputFormatter.swift b/Sources/PeripheryKit/Results/OutputFormatter.swift index 6493623e43..807ea3ad08 100644 --- a/Sources/PeripheryKit/Results/OutputFormatter.swift +++ b/Sources/PeripheryKit/Results/OutputFormatter.swift @@ -24,18 +24,18 @@ extension OutputFormatter { func describe(_ annotation: ScanResult.Annotation) -> String { switch annotation { case .unused: - return "unused" + "unused" case .assignOnlyProperty: - return "assignOnlyProperty" + "assignOnlyProperty" case .redundantProtocol: - return "redundantProtocol" + "redundantProtocol" case .redundantPublicAccessibility: - return "redundantPublicAccessibility" + "redundantPublicAccessibility" } } func describe(_ result: ScanResult, colored: Bool) -> [(Location, String)] { - var description: String = "" + var description = "" var secondaryResults: [(Location, String)] = [] if var name = result.declaration.name { @@ -89,7 +89,7 @@ extension OutputFormatter { [ outputPath(location).string, String(location.line), - String(location.column) + String(location.column), ] .joined(separator: ":") } @@ -100,17 +100,17 @@ public extension OutputFormat { var formatter: OutputFormatter.Type { switch self { case .xcode: - return XcodeFormatter.self + XcodeFormatter.self case .csv: - return CsvFormatter.self + CsvFormatter.self case .codeclimate: - return CodeClimateFormatter.self + CodeClimateFormatter.self case .json: - return JsonFormatter.self + JsonFormatter.self case .checkstyle: - return CheckstyleFormatter.self + CheckstyleFormatter.self case .githubActions: - return GitHubActionsFormatter.self + GitHubActionsFormatter.self } } } diff --git a/Sources/PeripheryKit/Results/XcodeFormatter.swift b/Sources/PeripheryKit/Results/XcodeFormatter.swift index b96a30ef82..674d1fcddb 100644 --- a/Sources/PeripheryKit/Results/XcodeFormatter.swift +++ b/Sources/PeripheryKit/Results/XcodeFormatter.swift @@ -5,7 +5,7 @@ import SystemPackage final class XcodeFormatter: OutputFormatter { let configuration: Configuration - lazy var currentFilePath: FilePath = { .current }() + lazy var currentFilePath: FilePath = .current init(configuration: Configuration) { self.configuration = configuration diff --git a/Sources/PeripheryKit/ScanResultBuilder.swift b/Sources/PeripheryKit/ScanResultBuilder.swift index 6355858c93..fc3d1a053d 100644 --- a/Sources/PeripheryKit/ScanResultBuilder.swift +++ b/Sources/PeripheryKit/ScanResultBuilder.swift @@ -15,7 +15,8 @@ public enum ScanResultBuilder { if removableDeclaration.kind.isExtendableKind, !graph.retainedDeclarations.contains(removableDeclaration), - !graph.ignoredDeclarations.contains(removableDeclaration) { + !graph.ignoredDeclarations.contains(removableDeclaration) + { let decls = removableDeclaration.descendentDeclarations.union([removableDeclaration]) for decl in decls { @@ -47,9 +48,9 @@ public enum ScanResultBuilder { return allAnnotatedDeclarations .filter { !$0.declaration.isImplicit && - !$0.declaration.kind.isAccessorKind && - !graph.ignoredDeclarations.contains($0.declaration) && - !graph.retainedDeclarations.contains($0.declaration) + !$0.declaration.kind.isAccessorKind && + !graph.ignoredDeclarations.contains($0.declaration) && + !graph.retainedDeclarations.contains($0.declaration) } } } diff --git a/Sources/ProjectDrivers/BazelProjectDriver.swift b/Sources/ProjectDrivers/BazelProjectDriver.swift index 2f2bec34b8..02e045ef08 100644 --- a/Sources/ProjectDrivers/BazelProjectDriver.swift +++ b/Sources/ProjectDrivers/BazelProjectDriver.swift @@ -14,7 +14,7 @@ public class BazelProjectDriver: ProjectDriver { return self.init(configuration: configuration) } - private static let topLevelKinds = [ + private static let topLevelKinds = [ // rules_apple, iOS "ios_app_clip", "ios_application", @@ -66,9 +66,7 @@ public class BazelProjectDriver: ProjectDriver { private let outputPath = FilePath("/var/tmp/periphery_bazel") - private lazy var contextLogger: ContextualLogger = { - logger.contextualized(with: "bazel") - }() + private lazy var contextLogger: ContextualLogger = logger.contextualized(with: "bazel") required init( configuration: Configuration = .shared, @@ -84,7 +82,7 @@ public class BazelProjectDriver: ProjectDriver { public func build() throws { guard let executablePath = Bundle.main.executablePath else { - fatalError("Expected executable path.") + fatalError("Expected executable path.") } try fileManager.createDirectory(at: outputPath.url, withIntermediateDirectories: true) @@ -124,7 +122,7 @@ public class BazelProjectDriver: ProjectDriver { "bazel", "run", "--ui_event_filters=-info,-debug,-warning", - "@periphery//bazel:scan" + "@periphery//bazel:scan", ]) // The actual scan is performed by Bazel. @@ -135,9 +133,9 @@ public class BazelProjectDriver: ProjectDriver { private func queryTargets() throws -> [String] { try shell - .exec(["bazel", "query", query], stderr: false) - .split(separator: "\n") - .map { "\"@@\($0)\"" } + .exec(["bazel", "query", query], stderr: false) + .split(separator: "\n") + .map { "\"@@\($0)\"" } } private var query: String { @@ -152,7 +150,7 @@ public class BazelProjectDriver: ProjectDriver { """ if let pattern = configuration.bazelFilter { - return "filter('\(pattern)', \(query))" + return "filter('\(pattern)', \(query))" } return query diff --git a/Sources/ProjectDrivers/ProjectDriver.swift b/Sources/ProjectDrivers/ProjectDriver.swift index 51ffab7636..7a439ea966 100644 --- a/Sources/ProjectDrivers/ProjectDriver.swift +++ b/Sources/ProjectDrivers/ProjectDriver.swift @@ -8,10 +8,10 @@ public protocol ProjectDriver { func plan(logger: ContextualLogger) throws -> IndexPlan } -extension ProjectDriver { - public func build() throws {} +public extension ProjectDriver { + func build() throws {} - public func plan(logger: ContextualLogger) throws -> IndexPlan { - IndexPlan(sourceFiles: [:]) - } + func plan(logger _: ContextualLogger) throws -> IndexPlan { + IndexPlan(sourceFiles: [:]) + } } diff --git a/Sources/ProjectDrivers/SPMProjectDriver.swift b/Sources/ProjectDrivers/SPMProjectDriver.swift index 21d752e7ac..a462fd0a04 100644 --- a/Sources/ProjectDrivers/SPMProjectDriver.swift +++ b/Sources/ProjectDrivers/SPMProjectDriver.swift @@ -44,12 +44,10 @@ extension SPMProjectDriver: ProjectDriver { } public func plan(logger: ContextualLogger) throws -> IndexPlan { - let indexStorePaths: Set - - if !configuration.indexStorePath.isEmpty { - indexStorePaths = Set(configuration.indexStorePath) + let indexStorePaths: Set = if !configuration.indexStorePath.isEmpty { + Set(configuration.indexStorePath) } else { - indexStorePaths = [pkg.path.appending(".build/debug/index/store")] + [pkg.path.appending(".build/debug/index/store")] } let excludedTestTargets = configuration.excludeTests ? try pkg.testTargetNames() : [] diff --git a/Sources/ProjectDrivers/XcodeProjectDriver.swift b/Sources/ProjectDrivers/XcodeProjectDriver.swift index 81fbdd00a8..1d67b53fdc 100644 --- a/Sources/ProjectDrivers/XcodeProjectDriver.swift +++ b/Sources/ProjectDrivers/XcodeProjectDriver.swift @@ -1,127 +1,123 @@ #if os(macOS) -import Foundation -import XcodeSupport -import Indexer -import Shared -import SourceGraph -import SystemPackage - -public final class XcodeProjectDriver { - public static func build(projectPath: FilePath) throws -> Self { - let configuration = Configuration.shared - let xcodebuild = Xcodebuild() - - guard !configuration.schemes.isEmpty else { - throw PeripheryError.usageError("The '--schemes' option is required.") - } - - try xcodebuild.ensureConfigured() + import Foundation + import Indexer + import Shared + import SourceGraph + import SystemPackage + import XcodeSupport + + public final class XcodeProjectDriver { + public static func build(projectPath: FilePath) throws -> Self { + let configuration = Configuration.shared + let xcodebuild = Xcodebuild() + + guard !configuration.schemes.isEmpty else { + throw PeripheryError.usageError("The '--schemes' option is required.") + } - let project: XcodeProjectlike + try xcodebuild.ensureConfigured() - if projectPath.extension == "xcworkspace" { - project = try XcodeWorkspace(path: .makeAbsolute(projectPath)) - } else { - project = try XcodeProject(path: .makeAbsolute(projectPath)) - } + let project: XcodeProjectlike = if projectPath.extension == "xcworkspace" { + try XcodeWorkspace(path: .makeAbsolute(projectPath)) + } else { + try XcodeProject(path: .makeAbsolute(projectPath)) + } - let schemes: Set + let schemes: Set - if configuration.skipSchemesValidation { - schemes = Set(configuration.schemes) - } else { - // Ensure schemes exist within the project - schemes = try project.schemes( - additionalArguments: configuration.xcodeListArguments - ).filter { configuration.schemes.contains($0) } - let validSchemeNames = schemes.mapSet { $0 } + if configuration.skipSchemesValidation { + schemes = Set(configuration.schemes) + } else { + // Ensure schemes exist within the project + schemes = try project.schemes( + additionalArguments: configuration.xcodeListArguments + ).filter { configuration.schemes.contains($0) } + let validSchemeNames = schemes.mapSet { $0 } - if let scheme = Set(configuration.schemes).subtracting(validSchemeNames).first { - throw PeripheryError.invalidScheme(name: scheme, project: project.path.lastComponent?.string ?? "") + if let scheme = Set(configuration.schemes).subtracting(validSchemeNames).first { + throw PeripheryError.invalidScheme(name: scheme, project: project.path.lastComponent?.string ?? "") + } } + + return self.init( + configuration: configuration, + xcodebuild: xcodebuild, + project: project, + schemes: schemes + ) } - return self.init( - configuration: configuration, - xcodebuild: xcodebuild, - project: project, - schemes: schemes - ) + private let logger: Logger + private let configuration: Configuration + private let xcodebuild: Xcodebuild + private let project: XcodeProjectlike + private let schemes: Set + + // swiftlint:disable:next function_default_parameter_at_end + init( + logger: Logger = .init(), + configuration: Configuration, + xcodebuild: Xcodebuild, + project: XcodeProjectlike, + schemes: Set + ) { + self.logger = logger + self.configuration = configuration + self.xcodebuild = xcodebuild + self.project = project + self.schemes = schemes + } } - private let logger: Logger - private let configuration: Configuration - private let xcodebuild: Xcodebuild - private let project: XcodeProjectlike - private let schemes: Set - - // swiftlint:disable:next function_default_parameter_at_end - init( - logger: Logger = .init(), - configuration: Configuration, - xcodebuild: Xcodebuild, - project: XcodeProjectlike, - schemes: Set - ) { - self.logger = logger - self.configuration = configuration - self.xcodebuild = xcodebuild - self.project = project - self.schemes = schemes - } -} + extension XcodeProjectDriver: ProjectDriver { + public func build() throws { + guard !configuration.skipBuild else { return } -extension XcodeProjectDriver: ProjectDriver { - public func build() throws { - guard !configuration.skipBuild else { return } + if configuration.cleanBuild { + try xcodebuild.removeDerivedData(for: project, allSchemes: Array(schemes)) + } - if configuration.cleanBuild { - try xcodebuild.removeDerivedData(for: project, allSchemes: Array(schemes)) - } + for scheme in schemes { + if configuration.outputFormat.supportsAuxiliaryOutput { + let asterisk = colorize("*", .boldGreen) + logger.info("\(asterisk) Building \(scheme)...") + } - for scheme in schemes { - if configuration.outputFormat.supportsAuxiliaryOutput { - let asterisk = colorize("*", .boldGreen) - logger.info("\(asterisk) Building \(scheme)...") + try xcodebuild.build(project: project, + scheme: scheme, + allSchemes: Array(schemes), + additionalArguments: configuration.buildArguments) } - - try xcodebuild.build(project: project, - scheme: scheme, - allSchemes: Array(schemes), - additionalArguments: configuration.buildArguments) } - } - public func plan(logger: ContextualLogger) throws -> IndexPlan { - let indexStorePaths: Set + public func plan(logger: ContextualLogger) throws -> IndexPlan { + let indexStorePaths: Set = if !configuration.indexStorePath.isEmpty { + Set(configuration.indexStorePath) + } else { + try [xcodebuild.indexStorePath(project: project, schemes: Array(schemes))] + } - if !configuration.indexStorePath.isEmpty { - indexStorePaths = Set(configuration.indexStorePath) - } else { - indexStorePaths = [try xcodebuild.indexStorePath(project: project, schemes: Array(schemes))] + let targets = project.targets + try targets.forEach { try $0.identifyFiles() } + let excludedTestTargets = configuration.excludeTests ? project.targets.filter(\.isTestTarget).mapSet(\.name) : [] + let collector = SourceFileCollector( + indexStorePaths: indexStorePaths, + excludedTestTargets: excludedTestTargets, + logger: logger + ) + let sourceFiles = try collector.collect() + let infoPlistPaths = targets.flatMapSet { $0.files(kind: .infoPlist) } + let xibPaths = targets.flatMapSet { $0.files(kind: .interfaceBuilder) } + let xcDataModelPaths = targets.flatMapSet { $0.files(kind: .xcDataModel) } + let xcMappingModelPaths = targets.flatMapSet { $0.files(kind: .xcMappingModel) } + + return IndexPlan( + sourceFiles: sourceFiles, + plistPaths: infoPlistPaths, + xibPaths: xibPaths, + xcDataModelPaths: xcDataModelPaths, + xcMappingModelPaths: xcMappingModelPaths + ) } - - let targets = project.targets - try targets.forEach { try $0.identifyFiles() } - let excludedTestTargets = configuration.excludeTests ? project.targets.filter(\.isTestTarget).mapSet(\.name) : [] - let collector = SourceFileCollector( - indexStorePaths: indexStorePaths, - excludedTestTargets: excludedTestTargets, - logger: logger - ) - let sourceFiles = try collector.collect() - let infoPlistPaths = targets.flatMapSet { $0.files(kind: .infoPlist) } - let xibPaths = targets.flatMapSet { $0.files(kind: .interfaceBuilder) } - let xcDataModelPaths = targets.flatMapSet { $0.files(kind: .xcDataModel) } - let xcMappingModelPaths = targets.flatMapSet { $0.files(kind: .xcMappingModel) } - - return IndexPlan( - sourceFiles: sourceFiles, - plistPaths: infoPlistPaths, - xibPaths: xibPaths, - xcDataModelPaths: xcDataModelPaths, - xcMappingModelPaths: xcMappingModelPaths - ) } -} #endif diff --git a/Sources/Shared/Configuration.swift b/Sources/Shared/Configuration.swift index cf863d192b..a0bed551f1 100644 --- a/Sources/Shared/Configuration.swift +++ b/Sources/Shared/Configuration.swift @@ -216,13 +216,9 @@ public final class Configuration { _retainFilesMatchers = nil } - public lazy var reportExcludeMatchers: [FilenameMatcher] = { - buildFilenameMatchers(with: reportExclude) - }() + public lazy var reportExcludeMatchers: [FilenameMatcher] = buildFilenameMatchers(with: reportExclude) - public lazy var reportIncludeMatchers: [FilenameMatcher] = { - buildFilenameMatchers(with: reportInclude) - }() + public lazy var reportIncludeMatchers: [FilenameMatcher] = buildFilenameMatchers(with: reportInclude) // MARK: - Private @@ -273,7 +269,7 @@ protocol AbstractSetting { setter: @escaping Setter = { $0 as? Value } ) { self.key = key - self.value = defaultValue + value = defaultValue self.defaultValue = defaultValue self.setter = setter } diff --git a/Sources/Shared/Extensions/Collection+Extension.swift b/Sources/Shared/Extensions/Collection+Extension.swift index 8a30d6810a..69d20967e8 100644 --- a/Sources/Shared/Extensions/Collection+Extension.swift +++ b/Sources/Shared/Extensions/Collection+Extension.swift @@ -3,7 +3,7 @@ import Foundation public extension Collection { /// Returns the element at the specified index iff it is within bounds, otherwise nil. @inlinable - subscript (safe index: Index) -> Element? { + subscript(safe index: Index) -> Element? { indices.contains(index) ? self[index] : nil } } diff --git a/Sources/Shared/Extensions/FilePath+Extension.swift b/Sources/Shared/Extensions/FilePath+Extension.swift index 449040fc5f..715e5cf479 100644 --- a/Sources/Shared/Extensions/FilePath+Extension.swift +++ b/Sources/Shared/Extensions/FilePath+Extension.swift @@ -36,8 +36,8 @@ public extension FilePath { @inlinable func relativeTo(_ relativePath: FilePath) -> FilePath { - let components = lexicallyNormalized().components.map { $0.string } - let relativePathComponents = relativePath.lexicallyNormalized().components.map { $0.string } + let components = lexicallyNormalized().components.map(\.string) + let relativePathComponents = relativePath.lexicallyNormalized().components.map(\.string) var commonPathComponents: [String] = [] for component in components { @@ -46,7 +46,7 @@ public extension FilePath { commonPathComponents.append(component) } - let relative = Array(repeating: "..", count: (relativePathComponents.count - commonPathComponents.count)) + let relative = Array(repeating: "..", count: relativePathComponents.count - commonPathComponents.count) let suffix = components.suffix(components.count - commonPathComponents.count) var newComponents = (relative + suffix).compactMap { Component($0) } diff --git a/Sources/Shared/Extensions/FilePath+Glob.swift b/Sources/Shared/Extensions/FilePath+Glob.swift index 43250c20c4..eae07c6a32 100644 --- a/Sources/Shared/Extensions/FilePath+Glob.swift +++ b/Sources/Shared/Extensions/FilePath+Glob.swift @@ -21,11 +21,11 @@ public extension FilePath { } } - /// Finds files on the file system using Bash v4 style pattern matching. - /// - A double globstar (**) causes recursive matching in subdirectories. - /// - Files from the root directory of the globstar are also included. - /// For example, with the pattern "dir/**/*.ext" the file "dir/file.ext" is also included. - /// - When the pattern ends with a trailing slash, only directories are matched. +/// Finds files on the file system using Bash v4 style pattern matching. +/// - A double globstar (**) causes recursive matching in subdirectories. +/// - Files from the root directory of the globstar are also included. +/// For example, with the pattern "dir/**/*.ext" the file "dir/file.ext" is also included. +/// - When the pattern ends with a trailing slash, only directories are matched. private class Glob { private let excludedDirectories: [String] private let logger: Logger @@ -142,16 +142,16 @@ private class Glob { } private func populateFiles(gt: glob_t, includeFiles: Bool) { -#if os(macOS) - let matches = Int(gt.gl_matchc) -#else - let matches = Int(gt.gl_pathc) -#endif - for i in 0..(_ transform: (Element) throws -> Set) rethrows -> Set { try reduce(into: .init()) { result, element in - result.formUnion(try transform(element)) + try result.formUnion(transform(element)) } } @inlinable func mapSet(_ transform: (Element) throws -> T) rethrows -> Set { try reduce(into: .init()) { result, element in - result.insert(try transform(element)) + try result.insert(transform(element)) } } diff --git a/Sources/Shared/Extensions/String+Extension.swift b/Sources/Shared/Extensions/String+Extension.swift index 07852c8e97..f59c683a44 100644 --- a/Sources/Shared/Extensions/String+Extension.swift +++ b/Sources/Shared/Extensions/String+Extension.swift @@ -13,7 +13,7 @@ public extension String { ("\"", """), ("'", "'"), (">", ">"), - ("<", "<") + ("<", "<"), ] var newString = self for (key, value) in htmlEscapes { @@ -25,8 +25,8 @@ public extension String { // http://www.cse.yorku.ca/~oz/hash.html @inlinable var djb2: Int { unicodeScalars - .map { $0.value } - .reduce(5_381) { ($0 << 5) &+ $0 &+ Int($1) } + .map(\.value) + .reduce(5381) { ($0 << 5) &+ $0 &+ Int($1) } } @inlinable var djb2Hex: String { diff --git a/Sources/Shared/Logger.swift b/Sources/Shared/Logger.swift index c32f0476c2..c5821169b8 100644 --- a/Sources/Shared/Logger.swift +++ b/Sources/Shared/Logger.swift @@ -1,7 +1,7 @@ import Foundation #if canImport(os) -import os + import os #endif public enum ANSIColor: String { @@ -23,8 +23,9 @@ public enum ANSIColor: String { @usableFromInline var isColorOutputCapable: Bool = { guard let term = ProcessInfo.processInfo.environment["TERM"], - term.lowercased() != "dumb", - isatty(fileno(stdout)) != 0 else { + term.lowercased() != "dumb", + isatty(fileno(stdout)) != 0 + else { return false } @@ -43,7 +44,7 @@ public final class BaseLogger { @usableFromInline let outputQueue: DispatchQueue private init() { - self.outputQueue = DispatchQueue(label: "BaseLogger.outputQueue") + outputQueue = DispatchQueue(label: "BaseLogger.outputQueue") } @inlinable @@ -59,7 +60,7 @@ public final class BaseLogger { @inlinable func warn(_ text: String, newlinePrefix: Bool = false) { if newlinePrefix { - log("", output: stderr) + log("", output: stderr) } let text = colorize("warning: ", .boldYellow) + text log(text, output: stderr) @@ -94,7 +95,7 @@ public final class Logger { @usableFromInline let configuration: Configuration #if canImport(os) - @usableFromInline let signposter = OSSignposter() + @usableFromInline let signposter = OSSignposter() #endif @inlinable @@ -134,18 +135,18 @@ public final class Logger { @inlinable public func beginInterval(_ name: StaticString) -> SignpostInterval { #if canImport(os) - let id = signposter.makeSignpostID() - let state = signposter.beginInterval(name, id: id) - return .init(name: name, state: state) + let id = signposter.makeSignpostID() + let state = signposter.beginInterval(name, id: id) + return .init(name: name, state: state) #else - return SignpostInterval() + return SignpostInterval() #endif } @inlinable public func endInterval(_ interval: SignpostInterval) { #if canImport(os) - signposter.endInterval(interval.name, interval.state) + signposter.endInterval(interval.name, interval.state) #endif } } @@ -182,20 +183,20 @@ public struct ContextualLogger { } #if canImport(os) -public struct SignpostInterval { - @usableFromInline let name: StaticString - @usableFromInline let state: OSSignpostIntervalState - - @inlinable - init(name: StaticString, state: OSSignpostIntervalState) { - self.name = name - self.state = state + public struct SignpostInterval { + @usableFromInline let name: StaticString + @usableFromInline let state: OSSignpostIntervalState + + @inlinable + init(name: StaticString, state: OSSignpostIntervalState) { + self.name = name + self.state = state + } } -} #else -public struct SignpostInterval { - // swiftlint:disable:next unneeded_synthesized_initializer - @usableFromInline - init() {} -} + public struct SignpostInterval { + // swiftlint:disable:next unneeded_synthesized_initializer + @usableFromInline + init() {} + } #endif diff --git a/Sources/Shared/PeripheryError.swift b/Sources/Shared/PeripheryError.swift index 7f0a4c2560..516fd85efc 100644 --- a/Sources/Shared/PeripheryError.swift +++ b/Sources/Shared/PeripheryError.swift @@ -33,21 +33,21 @@ public enum PeripheryError: Error, LocalizedError, CustomStringConvertible { return describe(error) case let .invalidScheme(name, project): return "Scheme '\(name)' does not exist in '\(project)'." - case .sourceGraphIntegrityError(let message): + case let .sourceGraphIntegrityError(message): return message - case .guidedSetupError(let message): + case let .guidedSetupError(message): return "\(message). Please refer to the documentation for instructions on configuring Periphery manually - https://github.com/peripheryapp/periphery/blob/master/README.md" - case .updateCheckError(let message): + case let .updateCheckError(message): return message case .xcodebuildNotConfigured: return "Xcode is not configured for command-line use. Please run 'sudo xcode-select -s /Applications/Xcode.app'." - case .pathDoesNotExist(let path): + case let .pathDoesNotExist(path): return "No such file or directory: \(path)." - case .foundIssues(let count): + case let .foundIssues(count): return "Found \(count) \(count > 1 ? "issues" : "issue")." - case .packageError(let message): + case let .packageError(message): return message - case .swiftVersionParseError(let fullVersion): + case let .swiftVersionParseError(fullVersion): return "Failed to parse Swift version from: \(fullVersion)" case let .swiftVersionUnsupportedError(version, minimumVersion): return "This version of Periphery only supports Swift >= \(minimumVersion), you're using \(version)." diff --git a/Sources/Shared/SPM.swift b/Sources/Shared/SPM.swift index b6fb655943..307c880df7 100644 --- a/Sources/Shared/SPM.swift +++ b/Sources/Shared/SPM.swift @@ -11,8 +11,8 @@ public enum SPM { public struct Package { public let path: FilePath = .current let configuration: Configuration = .shared - - public init() { } + + public init() {} var exists: Bool { path.appending(packageFile).exists diff --git a/Sources/Shared/SetupGuide.swift b/Sources/Shared/SetupGuide.swift index ad2132effc..21e43b561f 100644 --- a/Sources/Shared/SetupGuide.swift +++ b/Sources/Shared/SetupGuide.swift @@ -12,8 +12,8 @@ public enum SetupSelection { public var selectedValues: [String] { switch self { - case .all(let values), .some(let values): - return values + case let .all(values), let .some(values): + values } } } @@ -37,7 +37,8 @@ open class SetupGuideHelpers { print(colorize("> ", .bold), terminator: "") if let strChoice = readLine(strippingNewline: true)?.trimmed, - let choice = Int(strChoice) { + let choice = Int(strChoice) + { if let option = options[safe: choice - 1] { return option } else { @@ -61,14 +62,15 @@ open class SetupGuideHelpers { print(colorize("> ", .bold), terminator: "") if let strChoices = readLine(strippingNewline: true)?.trimmed.split(separator: " ", omittingEmptySubsequences: true) { - if allowAll && strChoices.contains("all") { + if allowAll, strChoices.contains("all") { return .all(options) } else { var selected: [String] = [] for strChoice in strChoices { if let choice = Int(strChoice), - let option = options[safe: choice - 1] { + let option = options[safe: choice - 1] + { selected.append(option) } else { print(colorize("\nInvalid option: \(strChoice)\n", .boldYellow)) @@ -94,7 +96,8 @@ open class SetupGuideHelpers { ) if let answer = readLine(strippingNewline: true)?.trimmed.lowercased(), - !answer.isEmpty { + !answer.isEmpty + { if ["y", "yes"].contains(answer) { return true } else if ["n", "no"].contains(answer) { diff --git a/Sources/Shared/Shell.swift b/Sources/Shared/Shell.swift index e90c630398..4db373d573 100644 --- a/Sources/Shared/Shell.swift +++ b/Sources/Shared/Shell.swift @@ -1,9 +1,7 @@ import Foundation open class Shell { - public static let shared: Shell = { - Shell(environment: ProcessInfo.processInfo.environment, logger: Logger()) - }() + public static let shared: Shell = .init(environment: ProcessInfo.processInfo.environment, logger: Logger()) private var tasks: Set = [] private var tasksQueue = DispatchQueue(label: "Shell.tasksQueue") @@ -17,12 +15,12 @@ open class Shell { } public func interruptRunning() { - tasksQueue.sync { - tasks.forEach { - $0.interrupt() - $0.waitUntilExit() + tasksQueue.sync { + for task in tasks { + task.interrupt() + task.waitUntilExit() + } } - } } lazy var pristineEnvironment: [String: String] = { @@ -41,7 +39,7 @@ open class Shell { } let preservedKeys = ["TERM", "PATH", "DEVELOPER_DIR", "SSH_AUTH_SOCK"] - preservedKeys.forEach { key in + for key in preservedKeys { if let value = environment[key] { newEnv[key] = value } @@ -69,15 +67,15 @@ open class Shell { ) } - @discardableResult - open func execStatus( - _ args: [String], - stderr: Bool = true - ) throws -> Int32 { - let env = environment - let (status, _) = try exec(args, stderr: stderr, captureOutput: false, environment: env) - return status - } + @discardableResult + open func execStatus( + _ args: [String], + stderr: Bool = true + ) throws -> Int32 { + let env = environment + let (status, _) = try exec(args, stderr: stderr, captureOutput: false, environment: env) + return status + } // MARK: - Private @@ -102,7 +100,7 @@ open class Shell { task.launchPath = launchPath task.environment = environment task.arguments = newArgs - + logger.debug("\(launchPath) \(newArgs.joined(separator: " "))") tasksQueue.sync { _ = tasks.insert(task) } @@ -116,10 +114,11 @@ open class Shell { task.launch() - var output: String = "" + var output = "" if let outputPipe, - let outputData = try outputPipe.fileHandleForReading.readToEnd() { + let outputData = try outputPipe.fileHandleForReading.readToEnd() + { guard let str = String(data: outputData, encoding: .utf8) else { tasksQueue.sync { _ = tasks.remove(task) } throw PeripheryError.shellOutputEncodingFailed( diff --git a/Sources/Shared/SwiftVersion.swift b/Sources/Shared/SwiftVersion.swift index fd964d496a..aa19effbfc 100644 --- a/Sources/Shared/SwiftVersion.swift +++ b/Sources/Shared/SwiftVersion.swift @@ -9,15 +9,16 @@ public struct SwiftVersion { public let fullVersion: String init(shell: Shell = .shared) { - self.fullVersion = try! shell.exec(["swift", "-version"]).trimmed - self.version = try! SwiftVersionParser.parse(fullVersion) + fullVersion = try! shell.exec(["swift", "-version"]).trimmed + version = try! SwiftVersionParser.parse(fullVersion) } public func validateVersion() throws { if Self.current.version.isVersion(lessThan: Self.minimumVersion) { throw PeripheryError.swiftVersionUnsupportedError( version: SwiftVersion.current.fullVersion, - minimumVersion: Self.minimumVersion) + minimumVersion: Self.minimumVersion + ) } } } diff --git a/Sources/Shared/SwiftVersionParser.swift b/Sources/Shared/SwiftVersionParser.swift index 8cd952be94..ad484c00e1 100644 --- a/Sources/Shared/SwiftVersionParser.swift +++ b/Sources/Shared/SwiftVersionParser.swift @@ -1,6 +1,6 @@ import Foundation -struct SwiftVersionParser { +enum SwiftVersionParser { static func parse(_ fullVersion: String) throws -> VersionString { guard let rawVersion = fullVersion.components(separatedBy: "Swift version").last?.split(separator: " ").first else { throw PeripheryError.swiftVersionParseError(fullVersion: fullVersion) diff --git a/Sources/Shared/UnfairLock.swift b/Sources/Shared/UnfairLock.swift index 21cedae308..40ebc1fb42 100644 --- a/Sources/Shared/UnfairLock.swift +++ b/Sources/Shared/UnfairLock.swift @@ -1,31 +1,31 @@ import Foundation #if canImport(os) -import os + import os #endif public final class UnfairLock { #if canImport(os) - private var _osAllocatedUnfairLock: Any? + private var _osAllocatedUnfairLock: Any? - private var osAllocatedUnfairLock: OSAllocatedUnfairLock { - // swiftlint:disable:next force_cast - _osAllocatedUnfairLock as! OSAllocatedUnfairLock - } + private var osAllocatedUnfairLock: OSAllocatedUnfairLock { + // swiftlint:disable:next force_cast + _osAllocatedUnfairLock as! OSAllocatedUnfairLock + } #else - private var _nsLock: Any? + private var _nsLock: Any? - private var nsLock: NSLock { - // swiftlint:disable:next force_cast - _nsLock as! NSLock - } + private var nsLock: NSLock { + // swiftlint:disable:next force_cast + _nsLock as! NSLock + } #endif public init() { #if canImport(os) - _osAllocatedUnfairLock = OSAllocatedUnfairLock() + _osAllocatedUnfairLock = OSAllocatedUnfairLock() #else - _nsLock = NSLock() + _nsLock = NSLock() #endif } @@ -33,15 +33,15 @@ public final class UnfairLock { @inline(__always) public func perform(_ operation: () throws -> T) rethrows -> T { #if canImport(os) - osAllocatedUnfairLock.lock() - let value = try operation() - osAllocatedUnfairLock.unlock() - return value + osAllocatedUnfairLock.lock() + let value = try operation() + osAllocatedUnfairLock.unlock() + return value #else - nsLock.lock() - let value = try operation() - nsLock.unlock() - return value + nsLock.lock() + let value = try operation() + nsLock.unlock() + return value #endif } } diff --git a/Sources/SourceGraph/Elements/Accessibility.swift b/Sources/SourceGraph/Elements/Accessibility.swift index 6a9bb2ed52..bc6fa41a55 100644 --- a/Sources/SourceGraph/Elements/Accessibility.swift +++ b/Sources/SourceGraph/Elements/Accessibility.swift @@ -1,9 +1,9 @@ import Foundation public enum Accessibility: String { - case `public` = "public" - case `internal` = "internal" - case `private` = "private" - case `fileprivate` = "fileprivate" - case `open` = "open" + case `public` + case `internal` + case `private` + case `fileprivate` + case open } diff --git a/Sources/SourceGraph/Elements/AssetReference.swift b/Sources/SourceGraph/Elements/AssetReference.swift index 3aa8c110f9..c2ea1b3888 100644 --- a/Sources/SourceGraph/Elements/AssetReference.swift +++ b/Sources/SourceGraph/Elements/AssetReference.swift @@ -6,7 +6,7 @@ public struct AssetReference: Hashable { if let name = absoluteName.split(separator: ".").last { self.name = String(name) } else { - self.name = absoluteName + name = absoluteName } self.source = source } diff --git a/Sources/SourceGraph/Elements/Declaration.swift b/Sources/SourceGraph/Elements/Declaration.swift index 9ddd4149a7..7aa5c17b08 100644 --- a/Sources/SourceGraph/Elements/Declaration.swift +++ b/Sources/SourceGraph/Elements/Declaration.swift @@ -2,11 +2,11 @@ import Foundation public final class Declaration { public enum Kind: String, RawRepresentable, CaseIterable { - case `associatedtype` = "associatedtype" - case `class` = "class" - case `enum` = "enum" - case enumelement = "enumelement" - case `extension` = "extension" + case `associatedtype` + case `class` + case `enum` + case enumelement + case `extension` case extensionClass = "extension.class" case extensionEnum = "extension.enum" case extensionProtocol = "extension.protocol" @@ -32,21 +32,21 @@ public final class Declaration { case functionOperatorPrefix = "function.operator.prefix" case functionSubscript = "function.subscript" case genericTypeParam = "generic_type_param" - case module = "module" + case module case precedenceGroup = "precedencegroup" - case `protocol` = "protocol" - case `struct` = "struct" - case `typealias` = "typealias" + case `protocol` + case `struct` + case `typealias` case varClass = "var.class" case varGlobal = "var.global" case varInstance = "var.instance" case varLocal = "var.local" case varParameter = "var.parameter" case varStatic = "var.static" - case macro = "macro" + case macro static var functionKinds: Set { - Set(Kind.allCases.filter { $0.isFunctionKind }) + Set(Kind.allCases.filter(\.isFunctionKind)) } static var protocolMemberKinds: [Kind] { @@ -74,7 +74,7 @@ public final class Declaration { } static var variableKinds: Set { - Set(Kind.allCases.filter { $0.isVariableKind }) + Set(Kind.allCases.filter(\.isVariableKind)) } public var isVariableKind: Bool { @@ -91,40 +91,40 @@ public final class Declaration { .extensionClass, .extensionStruct, .extensionProtocol, - .varGlobal + .varGlobal, ] static var extensionKinds: Set { - Set(Kind.allCases.filter { $0.isExtensionKind }) + Set(Kind.allCases.filter(\.isExtensionKind)) } public var extendedKind: Kind? { switch self { case .extensionClass: - return .class + .class case .extensionStruct: - return .struct + .struct case .extensionEnum: - return .enum + .enum case .extensionProtocol: - return .protocol + .protocol default: - return nil + nil } } public var extensionKind: Kind? { switch self { case .class: - return .extensionClass + .extensionClass case .struct: - return .extensionStruct + .extensionStruct case .enum: - return .extensionEnum + .extensionEnum case .protocol: - return .extensionProtocol + .extensionProtocol default: - return nil + nil } } @@ -157,7 +157,7 @@ public final class Declaration { } static var accessorKinds: Set { - Set(Kind.allCases.filter { $0.isAccessorKind }) + Set(Kind.allCases.filter(\.isAccessorKind)) } static var accessibleKinds: Set { @@ -175,35 +175,35 @@ public final class Declaration { public var displayName: String? { switch self { case .module: - return "imported module" + "imported module" case .class: - return "class" + "class" case .protocol: - return "protocol" + "protocol" case .struct: - return "struct" + "struct" case .enum: - return "enum" + "enum" case .enumelement: - return "enum case" + "enum case" case .typealias: - return "typealias" + "typealias" case .associatedtype: - return "associatedtype" + "associatedtype" case .functionConstructor: - return "initializer" + "initializer" case .extension, .extensionEnum, .extensionClass, .extensionStruct, .extensionProtocol: - return "extension" + "extension" case .functionMethodClass, .functionMethodStatic, .functionMethodInstance, .functionFree, .functionOperator, .functionSubscript: - return "function" + "function" case .varStatic, .varInstance, .varClass, .varGlobal, .varLocal: - return "property" + "property" case .varParameter: - return "parameter" + "parameter" case .genericTypeParam: - return "generic type parameter" + "generic type parameter" default: - return nil + nil } } } @@ -260,12 +260,12 @@ public final class Declaration { declarations.contains { if [ .functionAccessorWillset, - .functionAccessorDidset + .functionAccessorDidset, ].contains($0.kind) { return true } - if $0.kind.isAccessorKind && !$0.references.isEmpty { + if $0.kind.isAccessorKind, !$0.references.isEmpty { return true } @@ -285,7 +285,7 @@ public final class Declaration { self.kind = kind self.usrs = usrs self.location = location - self.hashValueCache = usrs.hashValue + hashValueCache = usrs.hashValue } func isDeclaredInExtension(kind: Declaration.Kind) -> Bool { @@ -315,7 +315,7 @@ extension Declaration: CustomStringConvertible { let formattedName = name != nil ? "'\(name!)'" : "nil" let formattedAttributes = "[" + attributes.sorted().joined(separator: ", ") + "]" let formattedModifiers = "[" + modifiers.sorted().joined(separator: ", ") + "]" - let formattedCommentCommands = "[" + commentCommands.map { $0.description }.sorted().joined(separator: ", ") + "]" + let formattedCommentCommands = "[" + commentCommands.map(\.description).sorted().joined(separator: ", ") + "]" let formattedUsrs = "[" + usrs.sorted().joined(separator: ", ") + "]" let implicitOrExplicit = isImplicit ? "implicit" : "explicit" return [ @@ -327,7 +327,7 @@ extension Declaration: CustomStringConvertible { formattedAttributes, formattedCommentCommands, formattedUsrs, - location.shortDescription + location.shortDescription, ] } } diff --git a/Sources/SourceGraph/Elements/Location.swift b/Sources/SourceGraph/Elements/Location.swift index 4ac23dad49..bf3353c308 100644 --- a/Sources/SourceGraph/Elements/Location.swift +++ b/Sources/SourceGraph/Elements/Location.swift @@ -12,7 +12,7 @@ public class Location { self.file = file self.line = line self.column = column - self.hashValueCache = [file.hashValue, line, column].hashValue + hashValueCache = [file.hashValue, line, column].hashValue } func relativeTo(_ path: FilePath) -> Location { @@ -28,13 +28,9 @@ public class Location { [path, line.description, column.description].joined(separator: ":") } - private lazy var descriptionInternal: String = { - buildDescription(path: file.path.string) - }() + private lazy var descriptionInternal: String = buildDescription(path: file.path.string) - private lazy var shortDescriptionInternal: String = { - buildDescription(path: file.path.lastComponent?.string ?? "") - }() + private lazy var shortDescriptionInternal: String = buildDescription(path: file.path.lastComponent?.string ?? "") } extension Location: Equatable { diff --git a/Sources/SourceGraph/Elements/ProjectFileKind.swift b/Sources/SourceGraph/Elements/ProjectFileKind.swift index 44fe528089..94c12c3717 100644 --- a/Sources/SourceGraph/Elements/ProjectFileKind.swift +++ b/Sources/SourceGraph/Elements/ProjectFileKind.swift @@ -7,13 +7,13 @@ public enum ProjectFileKind { public var extensions: [String] { switch self { case .interfaceBuilder: - return ["xib", "storyboard"] + ["xib", "storyboard"] case .infoPlist: - return ["plist"] + ["plist"] case .xcDataModel: - return ["xcdatamodeld"] + ["xcdatamodeld"] case .xcMappingModel: - return ["xcmappingmodel"] + ["xcmappingmodel"] } } } diff --git a/Sources/SourceGraph/Elements/Reference.swift b/Sources/SourceGraph/Elements/Reference.swift index 4d4412c258..3a77929762 100644 --- a/Sources/SourceGraph/Elements/Reference.swift +++ b/Sources/SourceGraph/Elements/Reference.swift @@ -16,9 +16,9 @@ public final class Reference { var isPubliclyExposable: Bool { switch self { case .varType, .returnType, .parameterType, .genericParameterType, .genericRequirementType, .inheritedType, .refinedProtocolType, .initializerType, .variableInitFunctionCall, .functionCallMetatypeArgument: - return true + true default: - return false + false } } } @@ -39,7 +39,7 @@ public final class Reference { self.usr = usr self.isRelated = isRelated self.location = location - self.hashValueCache = [usr.hashValue, location.hashValue, isRelated.hashValue].hashValue + hashValueCache = [usr.hashValue, location.hashValue, isRelated.hashValue].hashValue } var descendentReferences: Set { diff --git a/Sources/SourceGraph/Mutators/AccessibilityCascader.swift b/Sources/SourceGraph/Mutators/AccessibilityCascader.swift index 7a29f688b2..8b12bb5804 100644 --- a/Sources/SourceGraph/Mutators/AccessibilityCascader.swift +++ b/Sources/SourceGraph/Mutators/AccessibilityCascader.swift @@ -4,7 +4,7 @@ import Shared final class AccessibilityCascader: SourceGraphMutator { private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } @@ -22,7 +22,7 @@ final class AccessibilityCascader: SourceGraphMutator { private func cascadeAccessibility(for decls: [Declaration], only kinds: Set = []) throws { for decl in decls where decl.accessibility.isExplicit { for childDecl in decl.declarations { - if !kinds.isEmpty && !kinds.contains(childDecl.kind) { + if !kinds.isEmpty, !kinds.contains(childDecl.kind) { continue } diff --git a/Sources/SourceGraph/Mutators/AncestralReferenceEliminator.swift b/Sources/SourceGraph/Mutators/AncestralReferenceEliminator.swift index 683fbe3c94..dccc97cdff 100644 --- a/Sources/SourceGraph/Mutators/AncestralReferenceEliminator.swift +++ b/Sources/SourceGraph/Mutators/AncestralReferenceEliminator.swift @@ -4,7 +4,7 @@ import Shared final class AncestralReferenceEliminator: SourceGraphMutator { private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } diff --git a/Sources/SourceGraph/Mutators/AssetReferenceRetainer.swift b/Sources/SourceGraph/Mutators/AssetReferenceRetainer.swift index cab2c4fb04..3d96aef5a1 100644 --- a/Sources/SourceGraph/Mutators/AssetReferenceRetainer.swift +++ b/Sources/SourceGraph/Mutators/AssetReferenceRetainer.swift @@ -6,9 +6,9 @@ final class AssetReferenceRetainer: SourceGraphMutator { private let graph: SourceGraph private let interfaceBuilderPropertyRetainer: InterfaceBuilderPropertyRetainer - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph - self.interfaceBuilderPropertyRetainer = .init(graph: graph) + interfaceBuilderPropertyRetainer = .init(graph: graph) } func mutate() { diff --git a/Sources/SourceGraph/Mutators/AssignOnlyPropertyReferenceEliminator.swift b/Sources/SourceGraph/Mutators/AssignOnlyPropertyReferenceEliminator.swift index ed22b8d97c..64f1d58a7b 100644 --- a/Sources/SourceGraph/Mutators/AssignOnlyPropertyReferenceEliminator.swift +++ b/Sources/SourceGraph/Mutators/AssignOnlyPropertyReferenceEliminator.swift @@ -11,7 +11,7 @@ final class AssignOnlyPropertyReferenceEliminator: SourceGraphMutator { required init(graph: SourceGraph, configuration: Configuration) { self.graph = graph self.configuration = configuration - self.retainAssignOnlyPropertyTypes = defaultRetainedTypes + configuration.retainAssignOnlyPropertyTypes + retainAssignOnlyPropertyTypes = defaultRetainedTypes + configuration.retainAssignOnlyPropertyTypes } func mutate() throws { diff --git a/Sources/SourceGraph/Mutators/CapitalSelfFunctionCallRetainer.swift b/Sources/SourceGraph/Mutators/CapitalSelfFunctionCallRetainer.swift index 00489635cf..8c3093ae92 100644 --- a/Sources/SourceGraph/Mutators/CapitalSelfFunctionCallRetainer.swift +++ b/Sources/SourceGraph/Mutators/CapitalSelfFunctionCallRetainer.swift @@ -7,7 +7,7 @@ import Shared final class CapitalSelfFunctionCallRetainer: SourceGraphMutator { private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } diff --git a/Sources/SourceGraph/Mutators/CodingKeyEnumReferenceBuilder.swift b/Sources/SourceGraph/Mutators/CodingKeyEnumReferenceBuilder.swift index b38c75f5e6..163d7864a3 100644 --- a/Sources/SourceGraph/Mutators/CodingKeyEnumReferenceBuilder.swift +++ b/Sources/SourceGraph/Mutators/CodingKeyEnumReferenceBuilder.swift @@ -5,7 +5,7 @@ import Shared final class CodingKeyEnumReferenceBuilder: SourceGraphMutator { private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } diff --git a/Sources/SourceGraph/Mutators/ComplexPropertyAccessorReferenceBuilder.swift b/Sources/SourceGraph/Mutators/ComplexPropertyAccessorReferenceBuilder.swift index 2b2334c07f..ed7c659173 100644 --- a/Sources/SourceGraph/Mutators/ComplexPropertyAccessorReferenceBuilder.swift +++ b/Sources/SourceGraph/Mutators/ComplexPropertyAccessorReferenceBuilder.swift @@ -8,7 +8,7 @@ import Shared final class ComplexPropertyAccessorReferenceBuilder: SourceGraphMutator { private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } diff --git a/Sources/SourceGraph/Mutators/DefaultConstructorReferenceBuilder.swift b/Sources/SourceGraph/Mutators/DefaultConstructorReferenceBuilder.swift index 4466c371f5..e17a7f7ee6 100644 --- a/Sources/SourceGraph/Mutators/DefaultConstructorReferenceBuilder.swift +++ b/Sources/SourceGraph/Mutators/DefaultConstructorReferenceBuilder.swift @@ -4,7 +4,7 @@ import Shared final class DefaultConstructorReferenceBuilder: SourceGraphMutator { private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } @@ -22,7 +22,7 @@ final class DefaultConstructorReferenceBuilder: SourceGraphMutator { $0.name == "init()" || $0.isImplicit } - defaultConstructors.forEach { constructor in + for constructor in defaultConstructors { if let parent = constructor.parent { for usr in constructor.usrs { let reference = Reference(kind: .functionConstructor, @@ -37,7 +37,7 @@ final class DefaultConstructorReferenceBuilder: SourceGraphMutator { } private func referenceDestructors() { - graph.declarations(ofKind: .functionDestructor).forEach { destructor in + for destructor in graph.declarations(ofKind: .functionDestructor) { if let parent = destructor.parent { for usr in destructor.usrs { let reference = Reference(kind: .functionDestructor, diff --git a/Sources/SourceGraph/Mutators/DynamicMemberLookupReferenceBuilder.swift b/Sources/SourceGraph/Mutators/DynamicMemberLookupReferenceBuilder.swift index 56807d2641..202201fa4b 100644 --- a/Sources/SourceGraph/Mutators/DynamicMemberLookupReferenceBuilder.swift +++ b/Sources/SourceGraph/Mutators/DynamicMemberLookupReferenceBuilder.swift @@ -4,7 +4,7 @@ import Shared final class DynamicMemberLookupReferenceBuilder: SourceGraphMutator { private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } diff --git a/Sources/SourceGraph/Mutators/EntryPointAttributeRetainer.swift b/Sources/SourceGraph/Mutators/EntryPointAttributeRetainer.swift index 835717439d..6b1a5dc157 100644 --- a/Sources/SourceGraph/Mutators/EntryPointAttributeRetainer.swift +++ b/Sources/SourceGraph/Mutators/EntryPointAttributeRetainer.swift @@ -4,7 +4,7 @@ import Shared final class EntryPointAttributeRetainer: SourceGraphMutator { private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } @@ -14,15 +14,15 @@ final class EntryPointAttributeRetainer: SourceGraphMutator { .lazy .filter { $0.attributes.contains("NSApplicationMain") || - $0.attributes.contains("UIApplicationMain") || - $0.attributes.contains("main") + $0.attributes.contains("UIApplicationMain") || + $0.attributes.contains("main") } .forEach { graph.markRetained($0) graph.markMainAttributed($0) - $0.ancestralDeclarations.forEach { - graph.markRetained($0) + for ancestralDeclaration in $0.ancestralDeclarations { + graph.markRetained(ancestralDeclaration) } if $0.attributes.contains("main") { diff --git a/Sources/SourceGraph/Mutators/EnumCaseReferenceBuilder.swift b/Sources/SourceGraph/Mutators/EnumCaseReferenceBuilder.swift index 706a23841a..468e9535e3 100644 --- a/Sources/SourceGraph/Mutators/EnumCaseReferenceBuilder.swift +++ b/Sources/SourceGraph/Mutators/EnumCaseReferenceBuilder.swift @@ -5,7 +5,7 @@ import Shared final class EnumCaseReferenceBuilder: SourceGraphMutator { private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } diff --git a/Sources/SourceGraph/Mutators/ExtensionReferenceBuilder.swift b/Sources/SourceGraph/Mutators/ExtensionReferenceBuilder.swift index 20adf409c4..47363b36a1 100644 --- a/Sources/SourceGraph/Mutators/ExtensionReferenceBuilder.swift +++ b/Sources/SourceGraph/Mutators/ExtensionReferenceBuilder.swift @@ -6,7 +6,7 @@ import Shared final class ExtensionReferenceBuilder: SourceGraphMutator { private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } diff --git a/Sources/SourceGraph/Mutators/ExternalTypeProtocolConformanceReferenceRemover.swift b/Sources/SourceGraph/Mutators/ExternalTypeProtocolConformanceReferenceRemover.swift index 7db00498ba..84bfde6d02 100644 --- a/Sources/SourceGraph/Mutators/ExternalTypeProtocolConformanceReferenceRemover.swift +++ b/Sources/SourceGraph/Mutators/ExternalTypeProtocolConformanceReferenceRemover.swift @@ -5,7 +5,7 @@ import Shared final class ExternalTypeProtocolConformanceReferenceRemover: SourceGraphMutator { private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } @@ -21,7 +21,7 @@ final class ExternalTypeProtocolConformanceReferenceRemover: SourceGraphMutator guard !protocolDecls.isEmpty else { continue } // Find all related references that may be protocol members. - let relatedRefs = extDecl.related.filter { $0.kind.isProtocolMemberKind } + let relatedRefs = extDecl.related.filter(\.kind.isProtocolMemberKind) for relatedRef in relatedRefs { // Ensure the relatedDecl is a member of a protocol. @@ -29,7 +29,7 @@ final class ExternalTypeProtocolConformanceReferenceRemover: SourceGraphMutator let relatedDecl = graph.explicitDeclaration(withUsr: relatedRef.usr), let parentDecl = relatedDecl.parent, protocolDecls.contains(parentDecl) - else { continue } + else { continue } // Retain all parameters from the protocol declaration as altering the function signature would break // conformance. diff --git a/Sources/SourceGraph/Mutators/GenericClassAndStructConstructorReferenceBuilder.swift b/Sources/SourceGraph/Mutators/GenericClassAndStructConstructorReferenceBuilder.swift index be1baa8fbd..1daecaf869 100644 --- a/Sources/SourceGraph/Mutators/GenericClassAndStructConstructorReferenceBuilder.swift +++ b/Sources/SourceGraph/Mutators/GenericClassAndStructConstructorReferenceBuilder.swift @@ -9,7 +9,7 @@ final class GenericClassAndStructConstructorReferenceBuilder: SourceGraphMutator private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } diff --git a/Sources/SourceGraph/Mutators/InterfaceBuilderPropertyRetainer.swift b/Sources/SourceGraph/Mutators/InterfaceBuilderPropertyRetainer.swift index b98ba96c93..a3873d046a 100644 --- a/Sources/SourceGraph/Mutators/InterfaceBuilderPropertyRetainer.swift +++ b/Sources/SourceGraph/Mutators/InterfaceBuilderPropertyRetainer.swift @@ -21,7 +21,7 @@ class InterfaceBuilderPropertyRetainer { func retainPropertiesDeclared(in declaration: Declaration) { let inheritedDeclarations = graph.inheritedDeclarations(of: declaration) - let descendentInheritedDeclarations = inheritedDeclarations.map { $0.declarations }.joined() + let descendentInheritedDeclarations = inheritedDeclarations.map(\.declarations).joined() let allDeclarations = declaration.declarations.union(descendentInheritedDeclarations) for declaration in allDeclarations where declaration.attributes.contains(where: { ibAttributes.contains($0) }) { diff --git a/Sources/SourceGraph/Mutators/ObjCAccessibleRetainer.swift b/Sources/SourceGraph/Mutators/ObjCAccessibleRetainer.swift index aa872994aa..cc013a5d5a 100644 --- a/Sources/SourceGraph/Mutators/ObjCAccessibleRetainer.swift +++ b/Sources/SourceGraph/Mutators/ObjCAccessibleRetainer.swift @@ -15,17 +15,17 @@ final class ObjCAccessibleRetainer: SourceGraphMutator { for decl in graph.declarations(ofKinds: Declaration.Kind.accessibleKinds) { guard decl.attributes.contains("objc") || - decl.attributes.contains("objc.name") || - decl.attributes.contains("objcMembers") else { continue } + decl.attributes.contains("objc.name") || + decl.attributes.contains("objcMembers") else { continue } decl.isObjcAccessible = true graph.markRetained(decl) if configuration.retainObjcAnnotated { if decl.attributes.contains("objcMembers") || decl.kind == .protocol || decl.kind == .extensionClass { - decl.declarations.forEach { - $0.isObjcAccessible = true - graph.markRetained($0) + for declaration in decl.declarations { + declaration.isObjcAccessible = true + graph.markRetained(declaration) } } } @@ -34,10 +34,11 @@ final class ObjCAccessibleRetainer: SourceGraphMutator { if configuration.retainObjcAnnotated { for extDecl in graph.declarations(ofKind: .extensionClass) { if let extendedClass = try graph.extendedDeclaration(forExtension: extDecl), - extendedClass.attributes.contains("objcMembers") { - extDecl.declarations.forEach { - $0.isObjcAccessible = true - graph.markRetained($0) + extendedClass.attributes.contains("objcMembers") + { + for declaration in extDecl.declarations { + declaration.isObjcAccessible = true + graph.markRetained(declaration) } } } diff --git a/Sources/SourceGraph/Mutators/PropertyWrapperRetainer.swift b/Sources/SourceGraph/Mutators/PropertyWrapperRetainer.swift index ba8f4d117f..a3a313d279 100644 --- a/Sources/SourceGraph/Mutators/PropertyWrapperRetainer.swift +++ b/Sources/SourceGraph/Mutators/PropertyWrapperRetainer.swift @@ -5,7 +5,7 @@ final class PropertyWrapperRetainer: SourceGraphMutator { private let graph: SourceGraph private let specialProperties = ["wrappedValue", "projectedValue"] - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } diff --git a/Sources/SourceGraph/Mutators/ProtocolConformanceReferenceBuilder.swift b/Sources/SourceGraph/Mutators/ProtocolConformanceReferenceBuilder.swift index ede3f04a79..36d4a505ed 100644 --- a/Sources/SourceGraph/Mutators/ProtocolConformanceReferenceBuilder.swift +++ b/Sources/SourceGraph/Mutators/ProtocolConformanceReferenceBuilder.swift @@ -4,7 +4,7 @@ import Shared final class ProtocolConformanceReferenceBuilder: SourceGraphMutator { private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } @@ -44,13 +44,13 @@ final class ProtocolConformanceReferenceBuilder: SourceGraphMutator { let superclassDecls = graph.inheritedTypeReferences(of: conformingClass) .filter { $0.kind == .class } .compactMap { graph.explicitDeclaration(withUsr: $0.usr) } - .flatMap { $0.declarations } + .flatMap(\.declarations) for unimplementedProtoDecl in unimplementedProtoDecls { // Find the implementation declaration in a superclass. let declInSuperclass = superclassDecls.first { $0.kind == unimplementedProtoDecl.kind && - $0.name == unimplementedProtoDecl.name + $0.name == unimplementedProtoDecl.name } if let declInSuperclass { @@ -101,7 +101,7 @@ final class ProtocolConformanceReferenceBuilder: SourceGraphMutator { } guard equivalentDeclarationKinds.contains(conformingDeclaration.kind), - conformingDeclaration.name == relatedReference.name else { continue } + conformingDeclaration.name == relatedReference.name else { continue } if let protocolDeclaration = graph.explicitDeclaration(withUsr: relatedReference.usr) { // Invert the related reference such that instead of the conforming declaration diff --git a/Sources/SourceGraph/Mutators/ProtocolExtensionReferenceBuilder.swift b/Sources/SourceGraph/Mutators/ProtocolExtensionReferenceBuilder.swift index d24aa5a21c..46681dead5 100644 --- a/Sources/SourceGraph/Mutators/ProtocolExtensionReferenceBuilder.swift +++ b/Sources/SourceGraph/Mutators/ProtocolExtensionReferenceBuilder.swift @@ -4,7 +4,7 @@ import Shared final class ProtocolExtensionReferenceBuilder: SourceGraphMutator { private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } diff --git a/Sources/SourceGraph/Mutators/PubliclyAccessibleRetainer.swift b/Sources/SourceGraph/Mutators/PubliclyAccessibleRetainer.swift index 6f5a2b3b4b..80e8ca712c 100644 --- a/Sources/SourceGraph/Mutators/PubliclyAccessibleRetainer.swift +++ b/Sources/SourceGraph/Mutators/PubliclyAccessibleRetainer.swift @@ -25,7 +25,7 @@ final class PubliclyAccessibleRetainer: SourceGraphMutator { publicDeclarations .lazy .filter { $0.kind == .enum } - .flatMap { $0.declarations } + .flatMap(\.declarations) .filter { $0.kind == .enumelement } .forEach { graph.markRetained($0) } } diff --git a/Sources/SourceGraph/Mutators/RedundantExplicitPublicAccessibilityMarker.swift b/Sources/SourceGraph/Mutators/RedundantExplicitPublicAccessibilityMarker.swift index 086ec79a49..2075369872 100644 --- a/Sources/SourceGraph/Mutators/RedundantExplicitPublicAccessibilityMarker.swift +++ b/Sources/SourceGraph/Mutators/RedundantExplicitPublicAccessibilityMarker.swift @@ -15,7 +15,7 @@ final class RedundantExplicitPublicAccessibilityMarker: SourceGraphMutator { guard !configuration.disableRedundantPublicAnalysis else { return } let nonExtensionKinds = graph.rootDeclarations.filter { !$0.kind.isExtensionKind } - let extensionKinds = graph.rootDeclarations.filter { $0.kind.isExtensionKind } + let extensionKinds = graph.rootDeclarations.filter(\.kind.isExtensionKind) for decl in nonExtensionKinds { // Open declarations are not yet implemented. @@ -35,10 +35,11 @@ final class RedundantExplicitPublicAccessibilityMarker: SourceGraphMutator { private func validate(_ decl: Declaration) throws { // Check if the declaration is public, and is referenced cross module. if decl.accessibility.isExplicitly(.public) { - if !graph.isRetained(decl) && - !isReferencedCrossModule(decl) && - !isExposedPubliclyByAnotherDeclaration(decl) && - !isProtocolIndirectlyReferencedCrossModuleByExtensionMember(decl) { + if !graph.isRetained(decl), + !isReferencedCrossModule(decl), + !isExposedPubliclyByAnotherDeclaration(decl), + !isProtocolIndirectlyReferencedCrossModuleByExtensionMember(decl) + { // Public accessibility is redundant. mark(decl) markExplicitPublicDescendentDeclarations(from: decl) @@ -58,7 +59,8 @@ final class RedundantExplicitPublicAccessibilityMarker: SourceGraphMutator { // If the extended kind is already marked as having redundant public accessibility, then this extension // must also have redundant accessibility. if let extendedDecl = try graph.extendedDeclaration(forExtension: decl), - graph.redundantPublicAccessibility.keys.contains(extendedDecl) { + graph.redundantPublicAccessibility.keys.contains(extendedDecl) + { mark(decl) } } @@ -90,7 +92,8 @@ final class RedundantExplicitPublicAccessibilityMarker: SourceGraphMutator { // default types can cause misalignment between the positions of the two. if let functionRef = $0.parent?.references.first(where: { $0.role == .variableInitFunctionCall }), let functionDecl = graph.explicitDeclaration(withUsr: functionRef.usr), - functionDecl.hasGenericFunctionReturnedMetatypeParameters { + functionDecl.hasGenericFunctionReturnedMetatypeParameters + { return $0.parent } @@ -143,7 +146,7 @@ final class RedundantExplicitPublicAccessibilityMarker: SourceGraphMutator { .compactMap { ref -> Declaration? in guard let parent = ref.parent else { return nil } - if parent.kind == .extensionProtocol && parent.name == decl.name { + if parent.kind == .extensionProtocol, parent.name == decl.name { return parent } @@ -162,7 +165,7 @@ final class RedundantExplicitPublicAccessibilityMarker: SourceGraphMutator { } private func nonTestableModulesReferencing(_ decl: Declaration) -> Set { - let referenceFiles = graph.references(to: decl).map { $0.location.file } + let referenceFiles = graph.references(to: decl).map(\.location.file) return referenceFiles.flatMapSet { file -> Set in let importsDeclModuleTestable = file.importStatements.contains(where: { diff --git a/Sources/SourceGraph/Mutators/RedundantProtocolMarker.swift b/Sources/SourceGraph/Mutators/RedundantProtocolMarker.swift index 2b0b10fa4a..4d3caf318d 100644 --- a/Sources/SourceGraph/Mutators/RedundantProtocolMarker.swift +++ b/Sources/SourceGraph/Mutators/RedundantProtocolMarker.swift @@ -5,7 +5,7 @@ import Shared final class RedundantProtocolMarker: SourceGraphMutator { private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } @@ -34,7 +34,7 @@ final class RedundantProtocolMarker: SourceGraphMutator { .lazy .filter { $0.kind == .extensionProtocol } .compactMap { self.graph.explicitDeclaration(withUsr: $0.usr) } - .flatMap { $0.declarations } + .flatMap(\.declarations) .allSatisfy { unusedDeclarations.contains($0) } guard areAllExtensionsMembersUnused else { continue } diff --git a/Sources/SourceGraph/Mutators/ResultBuilderRetainer.swift b/Sources/SourceGraph/Mutators/ResultBuilderRetainer.swift index 3d0e28e763..055c4bf217 100644 --- a/Sources/SourceGraph/Mutators/ResultBuilderRetainer.swift +++ b/Sources/SourceGraph/Mutators/ResultBuilderRetainer.swift @@ -12,10 +12,10 @@ final class ResultBuilderRetainer: SourceGraphMutator { "buildArray(_:)", "buildBlock(_:)", "buildFinalResult(_:)", - "buildLimitedAvailability(_:)" + "buildLimitedAvailability(_:)", ]) - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } diff --git a/Sources/SourceGraph/Mutators/StringInterpolationAppendInterpolationRetainer.swift b/Sources/SourceGraph/Mutators/StringInterpolationAppendInterpolationRetainer.swift index 9ac1dec648..4ae57cd457 100644 --- a/Sources/SourceGraph/Mutators/StringInterpolationAppendInterpolationRetainer.swift +++ b/Sources/SourceGraph/Mutators/StringInterpolationAppendInterpolationRetainer.swift @@ -7,19 +7,18 @@ final class StringInterpolationAppendInterpolationRetainer: SourceGraphMutator { // swiftlint:disable:previous type_name private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } func mutate() { - graph.declarations(ofKind: .extensionStruct) - .forEach { - $0.declarations.filter { - $0.kind == .functionMethodInstance && - ($0.name ?? "").hasPrefix("appendInterpolation(") - }.forEach { - graph.markRetained($0) - } + for declaration in graph.declarations(ofKind: .extensionStruct) { + declaration.declarations.filter { + $0.kind == .functionMethodInstance && + ($0.name ?? "").hasPrefix("appendInterpolation(") + }.forEach { + graph.markRetained($0) } + } } } diff --git a/Sources/SourceGraph/Mutators/StructImplicitInitializerReferenceBuilder.swift b/Sources/SourceGraph/Mutators/StructImplicitInitializerReferenceBuilder.swift index 365e9ca6d8..77e092c716 100644 --- a/Sources/SourceGraph/Mutators/StructImplicitInitializerReferenceBuilder.swift +++ b/Sources/SourceGraph/Mutators/StructImplicitInitializerReferenceBuilder.swift @@ -6,7 +6,7 @@ final class StructImplicitInitializerReferenceBuilder: SourceGraphMutator { // swiftlint:disable:previous type_name private let graph: SourceGraph - init(graph: SourceGraph, configuration: Configuration) { + init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } diff --git a/Sources/SourceGraph/Mutators/SwiftUIRetainer.swift b/Sources/SourceGraph/Mutators/SwiftUIRetainer.swift index 41a5f7f3af..646f8d7e80 100644 --- a/Sources/SourceGraph/Mutators/SwiftUIRetainer.swift +++ b/Sources/SourceGraph/Mutators/SwiftUIRetainer.swift @@ -41,7 +41,7 @@ final class SwiftUIRetainer: SourceGraphMutator { graph .mainAttributedDeclarations .lazy - .flatMap { $0.declarations } + .flatMap(\.declarations) .filter { $0.kind == .varInstance } .filter { $0.references.contains { diff --git a/Sources/SourceGraph/Mutators/UnusedImportMarker.swift b/Sources/SourceGraph/Mutators/UnusedImportMarker.swift index 03386fd6c7..ec0dc1c737 100644 --- a/Sources/SourceGraph/Mutators/UnusedImportMarker.swift +++ b/Sources/SourceGraph/Mutators/UnusedImportMarker.swift @@ -47,7 +47,7 @@ final class UnusedImportMarker: SourceGraphMutator { // Only consider modules that have been indexed as we need to see which modules // they export. graph.indexedModules.contains($0.module) && - !referencedModules.contains($0.module) + !referencedModules.contains($0.module) } for unreferencedImport in unreferencedImports { diff --git a/Sources/SourceGraph/Mutators/UnusedParameterRetainer.swift b/Sources/SourceGraph/Mutators/UnusedParameterRetainer.swift index 97192b6bac..1d84f2afe7 100644 --- a/Sources/SourceGraph/Mutators/UnusedParameterRetainer.swift +++ b/Sources/SourceGraph/Mutators/UnusedParameterRetainer.swift @@ -22,7 +22,7 @@ final class UnusedParameterRetainer: SourceGraphMutator { for protoFuncDecl in protoFuncDecls { let relatedFuncDecls = protoFuncDecl.related - .filter { $0.kind.isFunctionKind } + .filter(\.kind.isFunctionKind) .compactMapSet { graph.explicitDeclaration(withUsr: $0.usr) } let extFuncDecls = relatedFuncDecls.filter { $0.parent?.kind.isExtensionKind ?? false } let conformingDecls = relatedFuncDecls.subtracting(extFuncDecls) @@ -64,12 +64,12 @@ final class UnusedParameterRetainer: SourceGraphMutator { visitedDecls.formUnion(allFunctionDecls) if didResolveBase { - if baseFunctionDecl.accessibility.value == .open && configuration.retainPublic { + if baseFunctionDecl.accessibility.value == .open, configuration.retainPublic { retainAllUnusedParams(inMethods: allFunctionDecls) } else if hasExternalRelatedReferences(from: baseFunctionDecl) { retainAllUnusedParams(inMethods: allFunctionDecls) } else { - let params = allFunctionDecls.flatMap { $0.unusedParameters } + let params = allFunctionDecls.flatMap(\.unusedParameters) retain(params: params, usedIn: allFunctionDecls) } } else { @@ -85,7 +85,7 @@ final class UnusedParameterRetainer: SourceGraphMutator { private func retainAllUnusedParams(inMethods methodDeclarations: [Declaration]) { methodDeclarations .lazy - .flatMap { $0.unusedParameters } + .flatMap(\.unusedParameters) .forEach { graph.markRetained($0) } } diff --git a/Sources/SourceGraph/Mutators/UsedDeclarationMarker.swift b/Sources/SourceGraph/Mutators/UsedDeclarationMarker.swift index d3effcf3db..f7bc024d77 100644 --- a/Sources/SourceGraph/Mutators/UsedDeclarationMarker.swift +++ b/Sources/SourceGraph/Mutators/UsedDeclarationMarker.swift @@ -4,7 +4,7 @@ import Shared final class UsedDeclarationMarker: SourceGraphMutator { private let graph: SourceGraph - required init(graph: SourceGraph, configuration: Configuration) { + required init(graph: SourceGraph, configuration _: Configuration) { self.graph = graph } @@ -68,7 +68,7 @@ final class UsedDeclarationMarker: SourceGraphMutator { private func ignoreUnusedDescendents(in decls: Set, unusedDeclarations: Set) { for decl in decls { guard !decl.declarations.isEmpty || !decl.unusedParameters.isEmpty - else { continue } + else { continue } if unusedDeclarations.contains(decl) { decl.descendentDeclarations.forEach { graph.markIgnored($0) } diff --git a/Sources/SourceGraph/Mutators/XCTestRetainer.swift b/Sources/SourceGraph/Mutators/XCTestRetainer.swift index 2659f8e354..5a02427668 100644 --- a/Sources/SourceGraph/Mutators/XCTestRetainer.swift +++ b/Sources/SourceGraph/Mutators/XCTestRetainer.swift @@ -7,7 +7,7 @@ final class XCTestRetainer: SourceGraphMutator { required init(graph: SourceGraph, configuration: Configuration) { self.graph = graph - self.testCaseClassNames = Set(configuration.externalTestCaseClasses + ["XCTestCase"]) + testCaseClassNames = Set(configuration.externalTestCaseClasses + ["XCTestCase"]) } func mutate() { diff --git a/Sources/SourceGraph/SourceGraph.swift b/Sources/SourceGraph/SourceGraph.swift index f7b4a31208..9c5b1109f4 100644 --- a/Sources/SourceGraph/SourceGraph.swift +++ b/Sources/SourceGraph/SourceGraph.swift @@ -254,7 +254,7 @@ public final class SourceGraph { // Recursively check if the module is exported transitively. return exportingModules.contains { nestedExportingModule in isModuleUnsafe(nestedExportingModule, exportedBy: exportingModule) && - isModuleUnsafe(module, exportedBy: nestedExportingModule) + isModuleUnsafe(module, exportedBy: nestedExportingModule) } } @@ -338,10 +338,10 @@ public final class SourceGraph { let baseDecl = references(to: decl) .filter { $0.isRelated && - $0.kind == decl.kind && - $0.name == decl.name + $0.kind == decl.kind && + $0.name == decl.name } - .compactMap { $0.parent } + .compactMap(\.parent) .first guard let baseDecl else { diff --git a/Sources/SourceGraph/SourceGraphMutatorRunner.swift b/Sources/SourceGraph/SourceGraphMutatorRunner.swift index 4d92462157..311fd9bf05 100644 --- a/Sources/SourceGraph/SourceGraphMutatorRunner.swift +++ b/Sources/SourceGraph/SourceGraphMutatorRunner.swift @@ -49,7 +49,7 @@ public final class SourceGraphMutatorRunner { AssignOnlyPropertyReferenceEliminator.self, UsedDeclarationMarker.self, - RedundantProtocolMarker.self + RedundantProtocolMarker.self, ] private let graph: SourceGraph @@ -67,7 +67,7 @@ public final class SourceGraphMutatorRunner { let elapsed = try Benchmark.measure { let interval = logger.beginInterval("mutator:run") try mutator.init(graph: graph, configuration: configuration).mutate() - logger.endInterval(interval) + logger.endInterval(interval) } logger.debug("\(mutator) (\(elapsed)s)") } diff --git a/Sources/SyntaxAnalysis/CommentCommand.swift b/Sources/SyntaxAnalysis/CommentCommand.swift index e8083608c9..4480b417eb 100644 --- a/Sources/SyntaxAnalysis/CommentCommand.swift +++ b/Sources/SyntaxAnalysis/CommentCommand.swift @@ -9,9 +9,9 @@ extension CommentCommand { let .blockComment(comment), let .docLineComment(comment), let .docBlockComment(comment): - return comment + comment default: - return nil + nil } } ?? [] diff --git a/Sources/SyntaxAnalysis/DeclarationSyntaxVisitor.swift b/Sources/SyntaxAnalysis/DeclarationSyntaxVisitor.swift index 36f177e18c..d70e3ce4ea 100644 --- a/Sources/SyntaxAnalysis/DeclarationSyntaxVisitor.swift +++ b/Sources/SyntaxAnalysis/DeclarationSyntaxVisitor.swift @@ -37,7 +37,7 @@ public final class DeclarationSyntaxVisitor: PeripherySyntaxVisitor { public init(sourceLocationBuilder: SourceLocationBuilder) { self.sourceLocationBuilder = sourceLocationBuilder - self.typeSyntaxInspector = .init(sourceLocationBuilder: sourceLocationBuilder) + typeSyntaxInspector = .init(sourceLocationBuilder: sourceLocationBuilder) } public func visitPost(_ node: ActorDeclSyntax) { @@ -205,7 +205,8 @@ public final class DeclarationSyntaxVisitor: PeripherySyntaxVisitor { node: node, pattern: tuplePatternSyntax, typeTuple: binding.typeAnnotation?.type.as(TupleTypeSyntax.self)?.elements, - initializerTuple: binding.initializer?.value.as(TupleExprSyntax.self)?.elements) + initializerTuple: binding.initializer?.value.as(TupleExprSyntax.self)?.elements + ) } else { parse( modifiers: node.modifiers, @@ -233,7 +234,8 @@ public final class DeclarationSyntaxVisitor: PeripherySyntaxVisitor { node: node, pattern: elementTuplePattern, typeTuple: typeTuple, - initializerTuple: initializerTuple) + initializerTuple: initializerTuple + ) } else { parse( modifiers: node.modifiers, @@ -241,7 +243,8 @@ public final class DeclarationSyntaxVisitor: PeripherySyntaxVisitor { trivia: node.leadingTrivia, variableType: type?.type, variableInitFunctionCallExpr: initializer?.expression.as(FunctionCallExprSyntax.self), - at: element.positionAfterSkippingLeadingTrivia) + at: element.positionAfterSkippingLeadingTrivia + ) } } } @@ -290,7 +293,8 @@ public final class DeclarationSyntaxVisitor: PeripherySyntaxVisitor { public func visit(_ node: FunctionCallExprSyntax) { if let identifierExpr = node.calledExpression.as(DeclReferenceExprSyntax.self), - identifierExpr.baseName.tokenKind == .keyword(.Self) { + identifierExpr.baseName.tokenKind == .keyword(.Self) + { didVisitCapitalSelfFunctionCall = true } } @@ -315,7 +319,7 @@ public final class DeclarationSyntaxVisitor: PeripherySyntaxVisitor { consumeCapitalSelfFunctionCalls: Bool = false, at position: AbsolutePosition ) { - let modifierNames = modifiers?.map { $0.name.text } ?? [] + let modifierNames = modifiers?.map(\.name.text) ?? [] let accessibility = modifierNames.mapFirst { Accessibility(rawValue: $0) } let attributeNames = attributes?.compactMap { AttributeSyntax($0)?.attributeName.trimmedDescription ?? AttributeSyntax($0)?.attributeName.firstToken(viewMode: .sourceAccurate)?.text @@ -329,13 +333,14 @@ public final class DeclarationSyntaxVisitor: PeripherySyntaxVisitor { } let returnClauseTypeLocations = typeNameLocations(for: returnClause) - let parameterClauseTypes = parameterClause?.parameters.map { $0.type } ?? [] - let closureParameterClauseTypes = closureParameterClause?.parameters.compactMap { $0.type } ?? [] - let enumCaseParameterClauseTypes = enumCaseParameterClause?.parameters.map { $0.type } ?? [] + let parameterClauseTypes = parameterClause?.parameters.map(\.type) ?? [] + let closureParameterClauseTypes = closureParameterClause?.parameters.compactMap(\.type) ?? [] + let enumCaseParameterClauseTypes = enumCaseParameterClause?.parameters.map(\.type) ?? [] let hasGenericFunctionReturnedMetatypeParameters = hasGenericFunctionReturnedMetatypeParameters( genericParameterClause: genericParameterClause, parameterClauseTypes: parameterClauseTypes + closureParameterClauseTypes + enumCaseParameterClauseTypes, - returnClauseTypeLocations: returnClauseTypeLocations) + returnClauseTypeLocations: returnClauseTypeLocations + ) let parameterClauseLocations = typeLocations(for: parameterClause) let closureParameterClauseLocations = typeLocations(for: closureParameterClause) @@ -381,7 +386,8 @@ public final class DeclarationSyntaxVisitor: PeripherySyntaxVisitor { .contains { if let baseTypeName = $0.as(MetatypeTypeSyntax.self)?.baseType.trimmedDescription, genericParameterNames.contains(baseTypeName), - returnClauseTypeLocations.contains(where: { $0.name == baseTypeName }) { + returnClauseTypeLocations.contains(where: { $0.name == baseTypeName }) + { return true } @@ -402,13 +408,13 @@ public final class DeclarationSyntaxVisitor: PeripherySyntaxVisitor { private func typeLocations(for clause: FunctionParameterClauseSyntax?) -> Set { guard let clause else { return [] } - return clause.parameters.reduce(into: .init(), { result, param in + return clause.parameters.reduce(into: .init()) { result, param in result.formUnion(typeSyntaxInspector.typeLocations(for: param.type)) if let defaultValue = param.defaultValue?.value { result.formUnion(identifierLocations(for: defaultValue)) } - }) + } } private func identifierLocations(for expr: ExprSyntax) -> Set { @@ -426,19 +432,19 @@ public final class DeclarationSyntaxVisitor: PeripherySyntaxVisitor { private func typeLocations(for clause: ClosureParameterClauseSyntax?) -> Set { guard let clause else { return [] } - return clause.parameters.reduce(into: .init(), { result, param in + return clause.parameters.reduce(into: .init()) { result, param in if let type = param.type { result.formUnion(typeSyntaxInspector.typeLocations(for: type)) } - }) + } } private func typeLocations(for clause: EnumCaseParameterClauseSyntax?) -> Set { guard let clause else { return [] } - return clause.parameters.reduce(into: .init(), { result, param in + return clause.parameters.reduce(into: .init()) { result, param in result.formUnion(typeSyntaxInspector.typeLocations(for: param.type)) - }) + } } private func typeNameLocations(for clause: ReturnClauseSyntax?) -> Set { @@ -504,13 +510,14 @@ public final class DeclarationSyntaxVisitor: PeripherySyntaxVisitor { return call .arguments - .reduce(into: .init(), { result, argument in + .reduce(into: .init()) { result, argument in if let memberExpr = argument.expression.as(MemberAccessExprSyntax.self), memberExpr.declName.baseName.tokenKind == .keyword(.`self`), - let baseIdentifier = memberExpr.base?.as(DeclReferenceExprSyntax.self) { + let baseIdentifier = memberExpr.base?.as(DeclReferenceExprSyntax.self) + { let location = sourceLocationBuilder.location(at: baseIdentifier.positionAfterSkippingLeadingTrivia) result.insert(location) } - }) + } } } diff --git a/Sources/SyntaxAnalysis/ImportSyntaxVisitor.swift b/Sources/SyntaxAnalysis/ImportSyntaxVisitor.swift index 01bf2bf31f..17b155d6e9 100644 --- a/Sources/SyntaxAnalysis/ImportSyntaxVisitor.swift +++ b/Sources/SyntaxAnalysis/ImportSyntaxVisitor.swift @@ -12,7 +12,7 @@ public final class ImportSyntaxVisitor: PeripherySyntaxVisitor { } public func visit(_ node: ImportDeclSyntax) { - let parts = node.path.map { $0.name.text } + let parts = node.path.map(\.name.text) let module = parts.first ?? "" let attributes = node.attributes.compactMap { $0.as(AttributeSyntax.self)?.attributeName.trimmedDescription } let location = sourceLocationBuilder.location(at: node.positionAfterSkippingLeadingTrivia) @@ -20,7 +20,8 @@ public final class ImportSyntaxVisitor: PeripherySyntaxVisitor { module: module, isTestable: attributes.contains("testable"), isExported: attributes.contains("_exported"), - location: location) + location: location + ) importStatements.append(statement) } } diff --git a/Sources/SyntaxAnalysis/MultiplexingSyntaxVisitor.swift b/Sources/SyntaxAnalysis/MultiplexingSyntaxVisitor.swift index 722aeb612d..ee150ad4b8 100644 --- a/Sources/SyntaxAnalysis/MultiplexingSyntaxVisitor.swift +++ b/Sources/SyntaxAnalysis/MultiplexingSyntaxVisitor.swift @@ -49,46 +49,46 @@ public protocol PeripherySyntaxVisitor { } // swiftlint:disable:next extension_access_modifier -extension PeripherySyntaxVisitor { - public func visit(_ node: ActorDeclSyntax) { } - public func visit(_ node: ClassDeclSyntax) { } - public func visit(_ node: ProtocolDeclSyntax) { } - public func visit(_ node: StructDeclSyntax) { } - public func visit(_ node: EnumDeclSyntax) { } - public func visit(_ node: EnumCaseDeclSyntax) { } - public func visit(_ node: ExtensionDeclSyntax) { } - public func visit(_: FunctionDeclSyntax) { } - public func visit(_ node: InitializerDeclSyntax) { } - public func visit(_ node: DeinitializerDeclSyntax) { } - public func visit(_ node: SubscriptDeclSyntax) { } - public func visit(_ node: VariableDeclSyntax) { } - public func visit(_ node: TypeAliasDeclSyntax) { } - public func visit(_ node: AssociatedTypeDeclSyntax) { } - public func visit(_ node: OperatorDeclSyntax) { } - public func visit(_ node: PrecedenceGroupDeclSyntax) { } - public func visit(_ node: ImportDeclSyntax) { } - public func visit(_ node: OptionalBindingConditionSyntax) {} - public func visit(_ node: FunctionCallExprSyntax) {} - - public func visitPost(_ node: ActorDeclSyntax) {} - public func visitPost(_ node: ClassDeclSyntax) {} - public func visitPost(_ node: ProtocolDeclSyntax) {} - public func visitPost(_ node: StructDeclSyntax) {} - public func visitPost(_ node: EnumDeclSyntax) {} - public func visitPost(_ node: EnumCaseDeclSyntax) {} - public func visitPost(_ node: ExtensionDeclSyntax) {} - public func visitPost(_ node: FunctionDeclSyntax) {} - public func visitPost(_ node: InitializerDeclSyntax) {} - public func visitPost(_ node: DeinitializerDeclSyntax) {} - public func visitPost(_ node: SubscriptDeclSyntax) {} - public func visitPost(_ node: VariableDeclSyntax) {} - public func visitPost(_ node: TypeAliasDeclSyntax) {} - public func visitPost(_ node: AssociatedTypeDeclSyntax) {} - public func visitPost(_ node: OperatorDeclSyntax) {} - public func visitPost(_ node: PrecedenceGroupDeclSyntax) {} - public func visitPost(_ node: ImportDeclSyntax) {} - public func visitPost(_ node: OptionalBindingConditionSyntax) {} - public func visitPost(_ node: FunctionCallExprSyntax) {} +public extension PeripherySyntaxVisitor { + func visit(_: ActorDeclSyntax) {} + func visit(_: ClassDeclSyntax) {} + func visit(_: ProtocolDeclSyntax) {} + func visit(_: StructDeclSyntax) {} + func visit(_: EnumDeclSyntax) {} + func visit(_: EnumCaseDeclSyntax) {} + func visit(_: ExtensionDeclSyntax) {} + func visit(_: FunctionDeclSyntax) {} + func visit(_: InitializerDeclSyntax) {} + func visit(_: DeinitializerDeclSyntax) {} + func visit(_: SubscriptDeclSyntax) {} + func visit(_: VariableDeclSyntax) {} + func visit(_: TypeAliasDeclSyntax) {} + func visit(_: AssociatedTypeDeclSyntax) {} + func visit(_: OperatorDeclSyntax) {} + func visit(_: PrecedenceGroupDeclSyntax) {} + func visit(_: ImportDeclSyntax) {} + func visit(_: OptionalBindingConditionSyntax) {} + func visit(_: FunctionCallExprSyntax) {} + + func visitPost(_: ActorDeclSyntax) {} + func visitPost(_: ClassDeclSyntax) {} + func visitPost(_: ProtocolDeclSyntax) {} + func visitPost(_: StructDeclSyntax) {} + func visitPost(_: EnumDeclSyntax) {} + func visitPost(_: EnumCaseDeclSyntax) {} + func visitPost(_: ExtensionDeclSyntax) {} + func visitPost(_: FunctionDeclSyntax) {} + func visitPost(_: InitializerDeclSyntax) {} + func visitPost(_: DeinitializerDeclSyntax) {} + func visitPost(_: SubscriptDeclSyntax) {} + func visitPost(_: VariableDeclSyntax) {} + func visitPost(_: TypeAliasDeclSyntax) {} + func visitPost(_: AssociatedTypeDeclSyntax) {} + func visitPost(_: OperatorDeclSyntax) {} + func visitPost(_: PrecedenceGroupDeclSyntax) {} + func visitPost(_: ImportDeclSyntax) {} + func visitPost(_: OptionalBindingConditionSyntax) {} + func visitPost(_: FunctionCallExprSyntax) {} } public final class MultiplexingSyntaxVisitor: SyntaxVisitor { @@ -100,11 +100,11 @@ public final class MultiplexingSyntaxVisitor: SyntaxVisitor { private var visitors: [PeripherySyntaxVisitor] = [] public required init(file: SourceFile) throws { - self.sourceFile = file + sourceFile = file let source = try String(contentsOf: file.path.url) - self.syntax = Parser.parse(source: source) - self.locationConverter = SourceLocationConverter(fileName: file.path.string, tree: syntax) - self.sourceLocationBuilder = SourceLocationBuilder(file: file, locationConverter: locationConverter) + syntax = Parser.parse(source: source) + locationConverter = SourceLocationConverter(fileName: file.path.string, tree: syntax) + sourceLocationBuilder = SourceLocationBuilder(file: file, locationConverter: locationConverter) super.init(viewMode: .sourceAccurate) } diff --git a/Sources/SyntaxAnalysis/SourceLocationBuilder.swift b/Sources/SyntaxAnalysis/SourceLocationBuilder.swift index e4b7f96e46..18c112e23b 100644 --- a/Sources/SyntaxAnalysis/SourceLocationBuilder.swift +++ b/Sources/SyntaxAnalysis/SourceLocationBuilder.swift @@ -16,4 +16,4 @@ public final class SourceLocationBuilder { line: location.line, column: location.column) } - } +} diff --git a/Sources/SyntaxAnalysis/UnusedParameterAnalyzer.swift b/Sources/SyntaxAnalysis/UnusedParameterAnalyzer.swift index badaf7dd4f..eb2bfad324 100644 --- a/Sources/SyntaxAnalysis/UnusedParameterAnalyzer.swift +++ b/Sources/SyntaxAnalysis/UnusedParameterAnalyzer.swift @@ -10,14 +10,15 @@ public final class UnusedParameterAnalyzer { case shadowed } - public init() { } + public init() {} public func analyze(file: SourceFile, syntax: SourceFileSyntax, locationConverter: SourceLocationConverter, parseProtocols: Bool) -> [Function: Set] { let functions = UnusedParameterParser.parse( file: file, syntax: syntax, locationConverter: locationConverter, - parseProtocols: parseProtocols) + parseProtocols: parseProtocols + ) return functions.reduce(into: [Function: Set]()) { result, function in let params = analyze(function: function) @@ -58,12 +59,12 @@ public final class UnusedParameterAnalyzer { private func isFunctionFatalErrorOnly(_ function: Function) -> Bool { guard let codeBlockList = function.items.first as? GenericItem, - codeBlockList.node.is(CodeBlockItemListSyntax.self), - codeBlockList.items.count == 1, - let funcCallExpr = codeBlockList.items.first as? GenericItem, - funcCallExpr.node.is(FunctionCallExprSyntax.self), - let identifier = funcCallExpr.items.first as? Identifier - else { return false } + codeBlockList.node.is(CodeBlockItemListSyntax.self), + codeBlockList.items.count == 1, + let funcCallExpr = codeBlockList.items.first as? GenericItem, + funcCallExpr.node.is(FunctionCallExprSyntax.self), + let identifier = funcCallExpr.items.first as? Identifier + else { return false } return identifier.name == "fatalError" } @@ -86,9 +87,9 @@ public final class UnusedParameterAnalyzer { private func isParam(_ param: Parameter, usedIn item: Item) -> Bool { switch usage(of: param, in: item) { case .used: - return true + true case .shadowed, .unused: - return false + false } } @@ -137,8 +138,8 @@ public final class UnusedParameterAnalyzer { let parts = metatype.split(separator: ".").map { String($0) } guard let genericParam = parts.first, - let member = parts.last, - member == "Type" else { return false } + let member = parts.last, + member == "Type" else { return false } return function.genericParameters.contains(genericParam) } diff --git a/Sources/SyntaxAnalysis/UnusedParameterParser.swift b/Sources/SyntaxAnalysis/UnusedParameterParser.swift index c2ecd10ed6..801839543a 100644 --- a/Sources/SyntaxAnalysis/UnusedParameterParser.swift +++ b/Sources/SyntaxAnalysis/UnusedParameterParser.swift @@ -175,49 +175,48 @@ struct UnusedParameterParser { parse(nodes: Array(children), collecting: collecting) } - private func parse(nodes: [Syntax], collecting: T.Type) -> [T] { + private func parse(nodes: [Syntax], collecting _: T.Type) -> [T] { let collector = Collector() nodes.forEach { _ = parse(node: $0, collector) } return collector.collection } - private func parse(node anyNode: SyntaxProtocol?, _ collector: Collector? = nil) -> Item? { + private func parse(node anyNode: SyntaxProtocol?, _ collector: Collector? = nil) -> Item? { guard let node = anyNode?._syntaxNode else { return nil } - let parsed: Item? - - if let node = node.as(MemberAccessExprSyntax.self) { + let parsed: Item? = if let node = node.as(MemberAccessExprSyntax.self) { // It's not possible for the member itself to be a reference to a parameter, // however the base expression may be. - parsed = parse(node: node.base, collector) + parse(node: node.base, collector) } else if let node = node.as(CodeBlockItemSyntax.self) { - parsed = parse(node: node.item, collector) + parse(node: node.item, collector) } else if let node = node.as(FunctionParameterClauseSyntax.self) { - parsed = parse(node: node.parameters, collector) + parse(node: node.parameters, collector) } else if let node = node.as(VariableDeclSyntax.self) { - parsed = parse(variableDecl: node, collector) + parse(variableDecl: node, collector) } else if let node = node.as(ClosureExprSyntax.self) { - parsed = parse(closureExpr: node, collector) + parse(closureExpr: node, collector) } else if let node = node.as(DeclReferenceExprSyntax.self) { - parsed = parse(identifier: node.baseName) + parse(identifier: node.baseName) } else if let node = node.as(FunctionParameterSyntax.self) { - parsed = parse(functionParameter: node) + parse(functionParameter: node) } else if let node = node.as(FunctionDeclSyntax.self) { - parsed = parse(functionDecl: node, collector) + parse(functionDecl: node, collector) } else if let node = node.as(InitializerDeclSyntax.self) { - parsed = parse(initializerDecl: node, collector) + parse(initializerDecl: node, collector) } else if let optBindingCondition = node.as(OptionalBindingConditionSyntax.self) { if optBindingCondition.initializer == nil, let pattern = optBindingCondition.pattern.as(IdentifierPatternSyntax.self), let parentStmt = optBindingCondition.parent?.parent?.parent, - parentStmt.is(IfExprSyntax.self) || parentStmt.is(GuardStmtSyntax.self) { + parentStmt.is(IfExprSyntax.self) || parentStmt.is(GuardStmtSyntax.self) + { // Handle `let x {}` syntax. - parsed = parse(identifier: pattern.identifier) + parse(identifier: pattern.identifier) } else { - parsed = parse(childrenFrom: node, collector) + parse(childrenFrom: node, collector) } } else { - parsed = parse(childrenFrom: node, collector) + parse(childrenFrom: node, collector) } if let collector, let parsed { @@ -227,7 +226,7 @@ struct UnusedParameterParser { return parsed } - private func parse(childrenFrom node: Syntax, _ collector: Collector?) -> Item? { + private func parse(childrenFrom node: Syntax, _ collector: Collector?) -> Item? { let items = node.children(viewMode: .sourceAccurate).compactMap { parse(node: $0, collector) } if !items.isEmpty { return GenericItem(node: node, items: items) @@ -259,15 +258,15 @@ struct UnusedParameterParser { location: location) } - private func parse(closureExpr syntax: ClosureExprSyntax, _ collector: Collector?) -> Closure? { + private func parse(closureExpr syntax: ClosureExprSyntax, _ collector: Collector?) -> Closure? { let signature = syntax.children(viewMode: .sourceAccurate).mapFirst { $0.as(ClosureSignatureSyntax.self) } let rawParams = signature?.parameterClause?.children(viewMode: .sourceAccurate).compactMap { $0.as(ClosureShorthandParameterSyntax.self) } - let params = rawParams?.map { $0.name.text } ?? [] + let params = rawParams?.map(\.name.text) ?? [] let items = syntax.statements.compactMap { parse(node: $0.item, collector) } return Closure(params: params, items: items) } - private func parse(variableDecl syntax: VariableDeclSyntax, _ collector: Collector?) -> Variable { + private func parse(variableDecl syntax: VariableDeclSyntax, _ collector: Collector?) -> Variable { let bindings = syntax.bindings let names = bindings.flatMap { binding -> [String] in @@ -300,7 +299,7 @@ struct UnusedParameterParser { return Identifier(name: name) } - private func parse(functionDecl syntax: FunctionDeclSyntax, _ collector: Collector?) -> Item? { + private func parse(functionDecl syntax: FunctionDeclSyntax, _ collector: Collector?) -> Item? { build(function: syntax.signature, attributes: syntax.attributes, genericParams: syntax.genericParameterClause, @@ -310,7 +309,7 @@ struct UnusedParameterParser { collector) } - private func parse(initializerDecl syntax: InitializerDeclSyntax, _ collector: Collector?) -> Item? { + private func parse(initializerDecl syntax: InitializerDeclSyntax, _ collector: Collector?) -> Item? { build(function: syntax.signature, attributes: syntax.attributes, genericParams: syntax.genericParameterClause, @@ -321,16 +320,16 @@ struct UnusedParameterParser { } // swiftlint:disable:next function_parameter_count - private func build( + private func build( function syntax: SyntaxProtocol, attributes: AttributeListSyntax?, genericParams: GenericParameterClauseSyntax?, body: CodeBlockSyntax?, named name: String, position: AbsolutePosition, - _ collector: Collector? + _ collector: Collector? ) -> Function? { - if body == nil && !parseProtocols { + if body == nil, !parseProtocols { // Function has no body, must be a protocol declaration. return nil } @@ -339,7 +338,7 @@ struct UnusedParameterParser { let params = parse(children: syntax.children(viewMode: .sourceAccurate), collecting: Parameter.self) let items = parse(node: body, collector)?.items ?? [] let fullName = buildFullName(for: name, with: params) - let genericParamNames = genericParams?.parameters.compactMap { $0.name.text } ?? [] + let genericParamNames = genericParams?.parameters.map(\.name.text) ?? [] let attributeNames = attributes?.children(viewMode: .sourceAccurate).compactMap { AttributeSyntax($0)?.attributeName.trimmedDescription } ?? [] let function = Function( @@ -349,7 +348,8 @@ struct UnusedParameterParser { items: items, parameters: params, genericParameters: genericParamNames, - attributes: attributeNames) + attributes: attributeNames + ) params.forEach { $0.function = function } return function diff --git a/Sources/XcodeSupport/XcodeProject.swift b/Sources/XcodeSupport/XcodeProject.swift index 6d1464c832..de3b8f3a68 100644 --- a/Sources/XcodeSupport/XcodeProject.swift +++ b/Sources/XcodeSupport/XcodeProject.swift @@ -31,21 +31,20 @@ public final class XcodeProject: XcodeProjectlike { public private(set) var targets: Set = [] let xcodeProject: XcodeProj - - private let xcodebuild: Xcodebuild + private let xcodebuild: Xcodebuild public required init(path: FilePath, xcodebuild: Xcodebuild = .init(), logger: Logger = .init()) throws { logger.contextualized(with: "xcode:project").debug("Loading \(path)") self.path = path self.xcodebuild = xcodebuild - self.name = self.path.lastComponent?.stem ?? "" - self.sourceRoot = self.path.removingLastComponent() + name = self.path.lastComponent?.stem ?? "" + sourceRoot = self.path.removingLastComponent() do { - self.xcodeProject = try XcodeProj(pathString: self.path.lexicallyNormalized().string) - } catch let error { + xcodeProject = try XcodeProj(pathString: self.path.lexicallyNormalized().string) + } catch { throw PeripheryError.underlyingError(error) } diff --git a/Sources/XcodeSupport/XcodeProjectSetupGuide.swift b/Sources/XcodeSupport/XcodeProjectSetupGuide.swift index f12412017e..88bf394adb 100644 --- a/Sources/XcodeSupport/XcodeProjectSetupGuide.swift +++ b/Sources/XcodeSupport/XcodeProjectSetupGuide.swift @@ -12,7 +12,7 @@ public final class XcodeProjectSetupGuide: SetupGuideHelpers, SetupGuide { } let projectPaths = FilePath.glob("**/*.xcodeproj") - if workspacePaths.isEmpty && projectPaths.isEmpty { + if workspacePaths.isEmpty, projectPaths.isEmpty { return nil } diff --git a/Sources/XcodeSupport/XcodeWorkspace.swift b/Sources/XcodeSupport/XcodeWorkspace.swift index e0c223097e..f81be4a314 100644 --- a/Sources/XcodeSupport/XcodeWorkspace.swift +++ b/Sources/XcodeSupport/XcodeWorkspace.swift @@ -20,16 +20,16 @@ public final class XcodeWorkspace: XcodeProjectlike { self.path = path self.xcodebuild = xcodebuild self.configuration = configuration - self.sourceRoot = self.path.removingLastComponent() + sourceRoot = self.path.removingLastComponent() do { - self.xcworkspace = try XCWorkspace(pathString: self.path.string) - } catch let error { + xcworkspace = try XCWorkspace(pathString: self.path.string) + } catch { throw PeripheryError.underlyingError(error) } let projectPaths = collectProjectPaths(in: xcworkspace.data.children) - let projects = try projectPaths.compactMapSet { try XcodeProject.build(path: (sourceRoot.pushing($0)), referencedBy: self.path) } + let projects = try projectPaths.compactMapSet { try XcodeProject.build(path: sourceRoot.pushing($0), referencedBy: self.path) } targets = projects.reduce(into: .init()) { result, project in result.formUnion(project.targets) @@ -47,15 +47,15 @@ public final class XcodeWorkspace: XcodeProjectlike { for child in elements { switch child { - case .file(let ref): - let basePath = FilePath(groups.map { $0.location.path }.filter { !$0.isEmpty }.joined(separator: "/")) + case let .file(ref): + let basePath = FilePath(groups.map(\.location.path).filter { !$0.isEmpty }.joined(separator: "/")) let path = FilePath(ref.location.path) let fullPath = basePath.pushing(path) - if fullPath.extension == "xcodeproj" && shouldLoadProject(fullPath) { + if fullPath.extension == "xcodeproj", shouldLoadProject(fullPath) { paths.append(fullPath) } - case .group(let group): + case let .group(group): paths += collectProjectPaths(in: group.children, groups: groups + [group]) } } @@ -64,7 +64,7 @@ public final class XcodeWorkspace: XcodeProjectlike { } private func shouldLoadProject(_ path: FilePath) -> Bool { - if configuration.guidedSetup && path.string.contains("Pods.xcodeproj") { + if configuration.guidedSetup, path.string.contains("Pods.xcodeproj") { return false } diff --git a/Sources/XcodeSupport/Xcodebuild.swift b/Sources/XcodeSupport/Xcodebuild.swift index bfb56b2657..9efbf65079 100644 --- a/Sources/XcodeSupport/Xcodebuild.swift +++ b/Sources/XcodeSupport/Xcodebuild.swift @@ -25,7 +25,7 @@ public final class Xcodebuild { public func ensureConfigured() throws { do { - logger.debug(try version()) + try logger.debug(version()) } catch { throw PeripheryError.xcodebuildNotConfigured } @@ -33,20 +33,20 @@ public final class Xcodebuild { @discardableResult public func build(project: XcodeProjectlike, scheme: String, allSchemes: [String], additionalArguments: [String] = []) throws -> String { - let args = [ + let args = try [ "-\(project.type)", "'\(project.path.lexicallyNormalized().string)'", "-scheme", "'\(scheme)'", "-parallelizeTargets", - "-derivedDataPath", "'\(try derivedDataPath(for: project, schemes: allSchemes).string)'", + "-derivedDataPath", "'\(derivedDataPath(for: project, schemes: allSchemes).string)'", "-quiet", - "build-for-testing" + "build-for-testing", ] let envs = [ "CODE_SIGNING_ALLOWED=\"NO\"", "ENABLE_BITCODE=\"NO\"", "DEBUG_INFORMATION_FORMAT=\"dwarf\"", "COMPILER_INDEX_STORE_ENABLE=\"YES\"", - "INDEX_ENABLE_DATA_STORE=\"YES\"" + "INDEX_ENABLE_DATA_STORE=\"YES\"", ] let quotedArguments = quote(arguments: additionalArguments) @@ -55,7 +55,7 @@ public final class Xcodebuild { } public func removeDerivedData(for project: XcodeProjectlike, allSchemes: [String]) throws { - try shell.exec(["rm", "-rf", try derivedDataPath(for: project, schemes: allSchemes).string]) + try shell.exec(["rm", "-rf", derivedDataPath(for: project, schemes: allSchemes).string]) } public func indexStorePath(project: XcodeProjectlike, schemes: [String]) throws -> FilePath { @@ -80,7 +80,7 @@ public final class Xcodebuild { let args = [ "-\(type)", "'\(path)'", "-list", - "-json" + "-json", ] let quotedArguments = quote(arguments: additionalArguments) @@ -99,8 +99,8 @@ public final class Xcodebuild { let jsonString = jsonLines.joined(separator: "\n") guard let json = try deserialize(jsonString), - let details = json[type] as? [String: Any], - let schemes = details["schemes"] as? [String] else { return [] } + let details = json[type] as? [String: Any], + let schemes = details["schemes"] as? [String] else { return [] } return Set(schemes) } @@ -138,7 +138,8 @@ public final class Xcodebuild { let value = arguments[safe: i + 1], !value.hasPrefix("-"), !value.hasPrefix("\""), - !value.hasPrefix("\'") { + !value.hasPrefix("\'") + { quotedArguments[i + 1] = "\"\(value)\"" } } diff --git a/Tests/AccessibilityTests/RedundantPublicAccessibilityTest.swift b/Tests/AccessibilityTests/RedundantPublicAccessibilityTest.swift index b8421abe09..e2b9fa33b6 100644 --- a/Tests/AccessibilityTests/RedundantPublicAccessibilityTest.swift +++ b/Tests/AccessibilityTests/RedundantPublicAccessibilityTest.swift @@ -128,14 +128,14 @@ class RedundantPublicAccessibilityTest: SPMSourceGraphTestCase { } #if os(macOS) - func testPublicClassAdoptingExternalProtocolObjcAccessible() { - configuration.retainObjcAccessible = true - Self.index() + func testPublicClassAdoptingExternalProtocolObjcAccessible() { + configuration.retainObjcAccessible = true + Self.index() - assertNotRedundantPublicAccessibility(.class("PublicClassAdoptingExternalProtocolObjcAccessible")) { - self.assertNotRedundantPublicAccessibility(.functionMethodInstance("someExternalProtocolMethod()")) + assertNotRedundantPublicAccessibility(.class("PublicClassAdoptingExternalProtocolObjcAccessible")) { + self.assertNotRedundantPublicAccessibility(.functionMethodInstance("someExternalProtocolMethod()")) + } } - } #endif func testPublicClassAdoptingInternalProtocol() { diff --git a/Tests/PeripheryTests/Extensions/FilePathGlobTest.swift b/Tests/PeripheryTests/Extensions/FilePathGlobTest.swift index a3d5d34620..a0f2e546bf 100644 --- a/Tests/PeripheryTests/Extensions/FilePathGlobTest.swift +++ b/Tests/PeripheryTests/Extensions/FilePathGlobTest.swift @@ -49,7 +49,7 @@ final class FilePathGlobTest: XCTestCase { "\(baseDir)/dir1/dir2/dir3", "\(baseDir)/dir1/dir2/dir3/file2.ext", "\(baseDir)/dir1/file1.ext", - "\(baseDir)/foo" + "\(baseDir)/foo", ]) } @@ -61,7 +61,7 @@ final class FilePathGlobTest: XCTestCase { baseDir, "\(baseDir)/dir1", "\(baseDir)/dir1/dir2", - "\(baseDir)/dir1/dir2/dir3" + "\(baseDir)/dir1/dir2/dir3", ]) } @@ -77,7 +77,7 @@ final class FilePathGlobTest: XCTestCase { "\(baseDir)/dir1/dir2/dir3", "\(baseDir)/dir1/dir2/dir3/file2.ext", "\(baseDir)/dir1/file1.ext", - "\(baseDir)/foo" + "\(baseDir)/foo", ]) } @@ -86,7 +86,7 @@ final class FilePathGlobTest: XCTestCase { let paths = FilePath.glob(pattern).sorted() XCTAssertPathsEqual(paths, [ "\(baseDir)/dir1/dir2/dir3", - "\(baseDir)/dir1/dir2/dir3/file2.ext" + "\(baseDir)/dir1/dir2/dir3/file2.ext", ]) } @@ -96,7 +96,7 @@ final class FilePathGlobTest: XCTestCase { let paths = FilePath.glob(pattern).sorted() XCTAssertPathsEqual(paths, [ "\(baseDir)/dir1/dir2/dir3/file2.ext", - "\(baseDir)/dir1/file1.ext" + "\(baseDir)/dir1/file1.ext", ]) } } @@ -106,7 +106,7 @@ final class FilePathGlobTest: XCTestCase { let pattern = "../bar" let paths = FilePath.glob(pattern).sorted() XCTAssertPathsEqual(paths, [ - "\(baseDir)/bar" + "\(baseDir)/bar", ]) } @@ -115,7 +115,7 @@ final class FilePathGlobTest: XCTestCase { let paths = FilePath.glob(pattern).sorted() XCTAssertPathsEqual(paths, [ "\(baseDir)/dir1/dir2/dir3/file2.ext", - "\(baseDir)/dir1/file1.ext" + "\(baseDir)/dir1/file1.ext", ]) } } @@ -123,7 +123,7 @@ final class FilePathGlobTest: XCTestCase { // MARK: - Private private func XCTAssertPathsEqual(_ filePaths: [FilePath], _ stringPaths: [String], file: StaticString = #file, line: UInt = #line) { - let convertedFilePaths = filePaths.map { $0.string } + let convertedFilePaths = filePaths.map(\.string) XCTAssertEqual(convertedFilePaths, stringPaths, file: file, line: line) } } diff --git a/Tests/PeripheryTests/ObjcAccessibleRetentionTest.swift b/Tests/PeripheryTests/ObjcAccessibleRetentionTest.swift index d0f5cad844..10c4fdb547 100644 --- a/Tests/PeripheryTests/ObjcAccessibleRetentionTest.swift +++ b/Tests/PeripheryTests/ObjcAccessibleRetentionTest.swift @@ -3,77 +3,77 @@ import SystemPackage import XCTest #if os(macOS) // swiftlint:disable:next balanced_xctest_lifecycle -final class ObjcAccessibleRetentionTest: FixtureSourceGraphTestCase { - let performKnownFailures = false + final class ObjcAccessibleRetentionTest: FixtureSourceGraphTestCase { + let performKnownFailures = false - // https://github.com/apple/swift/issues/56327 - func testRetainsOptionalProtocolMethodImplementedInSubclass() { - guard performKnownFailures else { return } + // https://github.com/apple/swift/issues/56327 + func testRetainsOptionalProtocolMethodImplementedInSubclass() { + guard performKnownFailures else { return } - analyze(retainPublic: true) { - assertReferenced(.class("FixtureClass125Base")) - assertReferenced(.class("FixtureClass125")) { - self.assertReferenced(.functionMethodInstance("fileManager(_:shouldRemoveItemAtPath:)")) + analyze(retainPublic: true) { + assertReferenced(.class("FixtureClass125Base")) + assertReferenced(.class("FixtureClass125")) { + self.assertReferenced(.functionMethodInstance("fileManager(_:shouldRemoveItemAtPath:)")) + } } } - } - func testRetainsOptionalProtocolMethod() { - analyze(retainPublic: true) { - assertReferenced(.class("FixtureClass127")) { - self.assertReferenced(.functionMethodInstance("someFunc()")) - } - assertReferenced(.protocol("FixtureProtocol127")) { - self.assertReferenced(.functionMethodInstance("optionalFunc()")) + func testRetainsOptionalProtocolMethod() { + analyze(retainPublic: true) { + assertReferenced(.class("FixtureClass127")) { + self.assertReferenced(.functionMethodInstance("someFunc()")) + } + assertReferenced(.protocol("FixtureProtocol127")) { + self.assertReferenced(.functionMethodInstance("optionalFunc()")) + } } } - } - func testRetainsObjcAnnotatedClass() { - analyze(retainObjcAccessible: true) { - assertReferenced(.class("FixtureClass21")) + func testRetainsObjcAnnotatedClass() { + analyze(retainObjcAccessible: true) { + assertReferenced(.class("FixtureClass21")) + } } - } - func testRetainsImplicitlyObjcAccessibleClass() { - analyze(retainObjcAccessible: true) { - assertReferenced(.class("FixtureClass126")) + func testRetainsImplicitlyObjcAccessibleClass() { + analyze(retainObjcAccessible: true) { + assertReferenced(.class("FixtureClass126")) + } } - } - func testRetainsObjcAnnotatedMembers() { - analyze(retainObjcAccessible: true) { - assertReferenced(.class("FixtureClass22")) { - self.assertReferenced(.varInstance("someVar")) - self.assertReferenced(.functionMethodInstance("someMethod()")) - self.assertReferenced(.functionMethodInstance("somePrivateMethod()")) + func testRetainsObjcAnnotatedMembers() { + analyze(retainObjcAccessible: true) { + assertReferenced(.class("FixtureClass22")) { + self.assertReferenced(.varInstance("someVar")) + self.assertReferenced(.functionMethodInstance("someMethod()")) + self.assertReferenced(.functionMethodInstance("somePrivateMethod()")) + } } } - } - func testDoesNotRetainObjcAnnotatedWithoutOption() { - analyze { - assertNotReferenced(.class("FixtureClass23")) + func testDoesNotRetainObjcAnnotatedWithoutOption() { + analyze { + assertNotReferenced(.class("FixtureClass23")) + } } - } - func testDoesNotRetainMembersOfObjcAnnotatedClass() { - analyze(retainObjcAccessible: true) { - assertReferenced(.class("FixtureClass24")) { - self.assertNotReferenced(.functionMethodInstance("someMethod()")) - self.assertNotReferenced(.varInstance("someVar")) + func testDoesNotRetainMembersOfObjcAnnotatedClass() { + analyze(retainObjcAccessible: true) { + assertReferenced(.class("FixtureClass24")) { + self.assertNotReferenced(.functionMethodInstance("someMethod()")) + self.assertNotReferenced(.varInstance("someVar")) + } } } - } - func testObjcMembersAnnotationRetainsMembers() { - analyze(retainObjcAccessible: true) { - assertReferenced(.class("FixtureClass25")) { - self.assertReferenced(.varInstance("someVar")) - self.assertReferenced(.functionMethodInstance("someMethod()")) - self.assertNotReferenced(.functionMethodInstance("somePrivateMethod()")) + func testObjcMembersAnnotationRetainsMembers() { + analyze(retainObjcAccessible: true) { + assertReferenced(.class("FixtureClass25")) { + self.assertReferenced(.varInstance("someVar")) + self.assertReferenced(.functionMethodInstance("someMethod()")) + self.assertNotReferenced(.functionMethodInstance("somePrivateMethod()")) + } } } } -} #endif diff --git a/Tests/PeripheryTests/ObjcAnnotatedRetentionTest.swift b/Tests/PeripheryTests/ObjcAnnotatedRetentionTest.swift index 2b359e0ef1..a0f8dee25f 100644 --- a/Tests/PeripheryTests/ObjcAnnotatedRetentionTest.swift +++ b/Tests/PeripheryTests/ObjcAnnotatedRetentionTest.swift @@ -3,38 +3,38 @@ import SystemPackage import XCTest #if os(macOS) // swiftlint:disable:next balanced_xctest_lifecycle -final class ObjcAnnotatedRetentionTest: FixtureSourceGraphTestCase { - func testRetainsAnnotatedExtensionDeclarations() { - analyze(retainObjcAnnotated: true) { - assertReferenced(.class("FixtureClass214")) { - self.assertReferenced(.functionMethodInstance("methodInExtension()")) + final class ObjcAnnotatedRetentionTest: FixtureSourceGraphTestCase { + func testRetainsAnnotatedExtensionDeclarations() { + analyze(retainObjcAnnotated: true) { + assertReferenced(.class("FixtureClass214")) { + self.assertReferenced(.functionMethodInstance("methodInExtension()")) + } } } - } - func testRetainsExtensionDeclarationsOnObjcMembersAnnotatedClass() { - analyze(retainObjcAnnotated: true) { - assertReferenced(.class("FixtureClass217")) { - self.assertReferenced(.functionMethodInstance("methodInExtension()")) + func testRetainsExtensionDeclarationsOnObjcMembersAnnotatedClass() { + analyze(retainObjcAnnotated: true) { + assertReferenced(.class("FixtureClass217")) { + self.assertReferenced(.functionMethodInstance("methodInExtension()")) + } } } - } - func testRetainsObjcProtocolMembers() { - analyze(retainObjcAnnotated: true) { - assertReferenced(.protocol("FixtureProtocol215")) { - self.assertReferenced(.functionMethodInstance("methodInProtocol()")) + func testRetainsObjcProtocolMembers() { + analyze(retainObjcAnnotated: true) { + assertReferenced(.protocol("FixtureProtocol215")) { + self.assertReferenced(.functionMethodInstance("methodInProtocol()")) + } } } - } - func testRetainsObjcProtocolConformingDeclarations() { - analyze(retainObjcAnnotated: true) { - assertReferenced(.protocol("FixtureProtocol216")) - assertReferenced(.class("FixtureClass216")) { - self.assertReferenced(.functionMethodInstance("methodInProtocol()")) + func testRetainsObjcProtocolConformingDeclarations() { + analyze(retainObjcAnnotated: true) { + assertReferenced(.protocol("FixtureProtocol216")) + assertReferenced(.class("FixtureClass216")) { + self.assertReferenced(.functionMethodInstance("methodInProtocol()")) + } } } } -} #endif diff --git a/Tests/PeripheryTests/RetentionTest.swift b/Tests/PeripheryTests/RetentionTest.swift index 8507eba952..6e98ad76d9 100644 --- a/Tests/PeripheryTests/RetentionTest.swift +++ b/Tests/PeripheryTests/RetentionTest.swift @@ -2,6 +2,7 @@ import Shared import SystemPackage @testable import TestShared import XCTest + final class RetentionTest: FixtureSourceGraphTestCase { let performKnownFailures = false @@ -136,9 +137,9 @@ final class RetentionTest: FixtureSourceGraphTestCase { assertReferenced(.protocol("FixtureProtocol114")) assertRedundantProtocol("FixtureProtocol114", implementedBy: - .class("FixtureClass114"), // swiftlint:disable vertical_parameter_alignment_on_call - .class("FixtureClass115"), - .struct("FixtureStruct116")) // swiftlint:enable vertical_parameter_alignment_on_call + .class("FixtureClass114"), // swiftlint:disable vertical_parameter_alignment_on_call + .class("FixtureClass115"), + .struct("FixtureStruct116")) // swiftlint:enable vertical_parameter_alignment_on_call } } @@ -1180,7 +1181,7 @@ final class RetentionTest: FixtureSourceGraphTestCase { self.assertNotAssignOnlyProperty(.varInstance("retainedMultipleBindingPropertyA")) #if canImport(Combine) - self.assertReferenced(.varInstance("retainedAnyCancellable")) + self.assertReferenced(.varInstance("retainedAnyCancellable")) #endif self.assertAssignOnlyProperty(.varInstance("notRetainedSimpleProperty")) diff --git a/Tests/PeripheryTests/ShellTest.swift b/Tests/PeripheryTests/ShellTest.swift index 2adc2080fc..88b091bc5c 100644 --- a/Tests/PeripheryTests/ShellTest.swift +++ b/Tests/PeripheryTests/ShellTest.swift @@ -7,7 +7,7 @@ final class ShellTest: XCTestCase { let developerDir = "/path/to/Xcode.app/Contents/Developer" let environment = [ "PATH": path, - "DEVELOPER_DIR": developerDir + "DEVELOPER_DIR": developerDir, ] let shell = Shell(environment: environment, logger: .init()) XCTAssertEqual(shell.pristineEnvironment["PATH"], path) diff --git a/Tests/PeripheryTests/Syntax/FunctionVisitTest.swift b/Tests/PeripheryTests/Syntax/FunctionVisitTest.swift index 46102f3f9f..64c901ebd4 100644 --- a/Tests/PeripheryTests/Syntax/FunctionVisitTest.swift +++ b/Tests/PeripheryTests/Syntax/FunctionVisitTest.swift @@ -33,7 +33,7 @@ final class FunctionVisitTest: XCTestCase { let result = results[fixtureLocation(line: 5)] XCTAssertEqual(result?.returnTypeLocations, [ fixtureLocation(line: 5, column: 40), - fixtureLocation(line: 5, column: 48) + fixtureLocation(line: 5, column: 48), ]) XCTAssertTrue(result?.parameterTypeLocations.isEmpty ?? false) XCTAssertTrue(result?.genericParameterLocations.isEmpty ?? false) @@ -44,7 +44,7 @@ final class FunctionVisitTest: XCTestCase { let result = results[fixtureLocation(line: 9)] XCTAssertEqual(result?.returnTypeLocations, [ fixtureLocation(line: 9, column: 42), - fixtureLocation(line: 9, column: 48) + fixtureLocation(line: 9, column: 48), ]) XCTAssertTrue(result?.parameterTypeLocations.isEmpty ?? false) XCTAssertTrue(result?.genericParameterLocations.isEmpty ?? false) @@ -55,7 +55,7 @@ final class FunctionVisitTest: XCTestCase { let result = results[fixtureLocation(line: 13)] XCTAssertEqual(result?.returnTypeLocations, [ fixtureLocation(line: 13, column: 42), - fixtureLocation(line: 13, column: 50) + fixtureLocation(line: 13, column: 50), ]) XCTAssertTrue(result?.parameterTypeLocations.isEmpty ?? false) XCTAssertTrue(result?.genericParameterLocations.isEmpty ?? false) @@ -66,7 +66,7 @@ final class FunctionVisitTest: XCTestCase { let result = results[fixtureLocation(line: 18)] XCTAssertEqual(result?.parameterTypeLocations, [ fixtureLocation(line: 18, column: 31), - fixtureLocation(line: 18, column: 42) + fixtureLocation(line: 18, column: 42), ]) XCTAssertTrue(result?.returnTypeLocations.isEmpty ?? false) XCTAssertTrue(result?.genericParameterLocations.isEmpty ?? false) @@ -76,14 +76,14 @@ final class FunctionVisitTest: XCTestCase { func testFunctionWithGenericArguments() throws { let result = results[fixtureLocation(line: 20)] XCTAssertEqual(result?.parameterTypeLocations, [ - fixtureLocation(line: 20, column: 70) + fixtureLocation(line: 20, column: 70), ]) XCTAssertEqual(result?.genericParameterLocations, [ fixtureLocation(line: 20, column: 37), - fixtureLocation(line: 20, column: 54) + fixtureLocation(line: 20, column: 54), ]) XCTAssertEqual(result?.genericConformanceRequirementLocations, [ - fixtureLocation(line: 20, column: 87) + fixtureLocation(line: 20, column: 87), ]) XCTAssertTrue(result?.returnTypeLocations.isEmpty ?? false) } @@ -91,7 +91,7 @@ final class FunctionVisitTest: XCTestCase { func testFunctionWithSomeReturnType() throws { let result = results[fixtureLocation(line: 23)] XCTAssertEqual(result?.returnTypeLocations, [ - fixtureLocation(line: 23, column: 43) + fixtureLocation(line: 23, column: 43), ]) XCTAssertTrue(result?.parameterTypeLocations.isEmpty ?? false) XCTAssertTrue(result?.genericParameterLocations.isEmpty ?? false) @@ -102,7 +102,7 @@ final class FunctionVisitTest: XCTestCase { let result = results[fixtureLocation(line: 26, column: 5)] XCTAssertEqual(result?.parameterTypeLocations, [ fixtureLocation(line: 26, column: 13), - fixtureLocation(line: 26, column: 24) + fixtureLocation(line: 26, column: 24), ]) XCTAssertTrue(result?.returnTypeLocations.isEmpty ?? false) XCTAssertTrue(result?.genericParameterLocations.isEmpty ?? false) @@ -112,14 +112,14 @@ final class FunctionVisitTest: XCTestCase { func testInitializerWithGenericArguments() throws { let result = results[fixtureLocation(line: 30, column: 5)] XCTAssertEqual(result?.parameterTypeLocations, [ - fixtureLocation(line: 30, column: 46) + fixtureLocation(line: 30, column: 46), ]) XCTAssertEqual(result?.genericParameterLocations, [ fixtureLocation(line: 30, column: 13), - fixtureLocation(line: 30, column: 30) + fixtureLocation(line: 30, column: 30), ]) XCTAssertEqual(result?.genericConformanceRequirementLocations, [ - fixtureLocation(line: 30, column: 63) + fixtureLocation(line: 30, column: 63), ]) XCTAssertTrue(result?.returnTypeLocations.isEmpty ?? false) } @@ -128,10 +128,10 @@ final class FunctionVisitTest: XCTestCase { let result = results[fixtureLocation(line: 34, column: 5)] XCTAssertEqual(result?.parameterTypeLocations, [ fixtureLocation(line: 34, column: 18), - fixtureLocation(line: 34, column: 26) + fixtureLocation(line: 34, column: 26), ]) XCTAssertEqual(result?.returnTypeLocations, [ - fixtureLocation(line: 34, column: 37) + fixtureLocation(line: 34, column: 37), ]) XCTAssertTrue(result?.genericParameterLocations.isEmpty ?? false) XCTAssertTrue(result?.genericConformanceRequirementLocations.isEmpty ?? false) @@ -140,24 +140,24 @@ final class FunctionVisitTest: XCTestCase { func testSubscriptWithGenericArguments() throws { let result = results[fixtureLocation(line: 35, column: 5)] XCTAssertEqual(result?.parameterTypeLocations, [ - fixtureLocation(line: 35, column: 51) + fixtureLocation(line: 35, column: 51), ]) XCTAssertEqual(result?.returnTypeLocations, [ - fixtureLocation(line: 35, column: 62) + fixtureLocation(line: 35, column: 62), ]) XCTAssertEqual(result?.genericParameterLocations, [ fixtureLocation(line: 35, column: 18), - fixtureLocation(line: 35, column: 35) + fixtureLocation(line: 35, column: 35), ]) XCTAssertEqual(result?.genericConformanceRequirementLocations, [ - fixtureLocation(line: 35, column: 75) + fixtureLocation(line: 35, column: 75), ]) } // MARK: - Private private var fixturePath: SourceFile { - let path = FixturesProjectPath.appending( "Sources/DeclarationVisitorFixtures/FunctionFixture.swift") + let path = FixturesProjectPath.appending("Sources/DeclarationVisitorFixtures/FunctionFixture.swift") return SourceFile(path: path, modules: ["DeclarationVisitorFixtures"]) } diff --git a/Tests/PeripheryTests/Syntax/PropertyVisitTest.swift b/Tests/PeripheryTests/Syntax/PropertyVisitTest.swift index 9cdd08a477..67a959d2c8 100644 --- a/Tests/PeripheryTests/Syntax/PropertyVisitTest.swift +++ b/Tests/PeripheryTests/Syntax/PropertyVisitTest.swift @@ -56,7 +56,7 @@ final class PropertyVisitTest: XCTestCase { XCTAssertEqual(result.variableType, "Set") XCTAssertEqual(result.variableTypeLocations, [ fixtureLocation(line: 13, column: 26), - fixtureLocation(line: 13, column: 30) + fixtureLocation(line: 13, column: 30), ]) } @@ -65,7 +65,7 @@ final class PropertyVisitTest: XCTestCase { XCTAssertEqual(result.variableType, "(Int, String)") XCTAssertEqual(result.variableTypeLocations, [ fixtureLocation(line: 14, column: 25), - fixtureLocation(line: 14, column: 30) + fixtureLocation(line: 14, column: 30), ]) } @@ -85,7 +85,7 @@ final class PropertyVisitTest: XCTestCase { XCTAssertEqual(propertyC.variableType, "CustomType.NestedType") XCTAssertEqual(propertyC.variableTypeLocations, [ fixtureLocation(line: 19, column: 10), - fixtureLocation(line: 19, column: 21) + fixtureLocation(line: 19, column: 21), ]) XCTAssertEqual(propertyD.variableType, "CustomType.NestedType.NestedScalar") @@ -120,7 +120,7 @@ final class PropertyVisitTest: XCTestCase { // MARK: - Private private var fixturePath: SourceFile { - let path = FixturesProjectPath.appending( "Sources/DeclarationVisitorFixtures/PropertyFixture.swift") + let path = FixturesProjectPath.appending("Sources/DeclarationVisitorFixtures/PropertyFixture.swift") return SourceFile(path: path, modules: ["DeclarationVisitorFixtures"]) } diff --git a/Tests/PeripheryTests/Syntax/TypeSyntaxInspectorTest.swift b/Tests/PeripheryTests/Syntax/TypeSyntaxInspectorTest.swift index 1f72bb3bbf..db7480e87c 100644 --- a/Tests/PeripheryTests/Syntax/TypeSyntaxInspectorTest.swift +++ b/Tests/PeripheryTests/Syntax/TypeSyntaxInspectorTest.swift @@ -39,7 +39,7 @@ final class TypeSyntaxInspectorTest: XCTestCase { XCTAssertEqual(memberType?.type, "Swift.String") XCTAssertEqual(memberType?.locations, [ fixtureLocation(line: 5, column: 17), - fixtureLocation(line: 5, column: 23) + fixtureLocation(line: 5, column: 23), ]) } @@ -48,7 +48,7 @@ final class TypeSyntaxInspectorTest: XCTestCase { XCTAssertEqual(tupleType?.type, "(String, Int)") XCTAssertEqual(tupleType?.locations, [ fixtureLocation(line: 6, column: 17), - fixtureLocation(line: 6, column: 25) + fixtureLocation(line: 6, column: 25), ]) } @@ -57,7 +57,7 @@ final class TypeSyntaxInspectorTest: XCTestCase { XCTAssertEqual(result?.type, "[String: Int]") XCTAssertEqual(result?.locations, [ fixtureLocation(line: 7, column: 22), - fixtureLocation(line: 7, column: 30) + fixtureLocation(line: 7, column: 30), ]) } @@ -78,7 +78,7 @@ final class TypeSyntaxInspectorTest: XCTestCase { XCTAssertEqual(functionClosureReturnType?.type, "(Int) -> String") XCTAssertEqual(functionClosureReturnType?.locations, [ fixtureLocation(line: 10, column: 38), - fixtureLocation(line: 10, column: 46) + fixtureLocation(line: 10, column: 46), ]) } @@ -96,14 +96,14 @@ final class TypeSyntaxInspectorTest: XCTestCase { let genericFunctionArgument = results[fixtureLocation(line: 15, column: 58)] XCTAssertEqual(genericFunctionArgument?.type, "T.Type") XCTAssertEqual(genericFunctionArgument?.locations, [ - fixtureLocation(line: 15, column: 58) + fixtureLocation(line: 15, column: 58), ]) let genericParamClause = results[fixtureLocation(line: 15, column: 25)] XCTAssertEqual(genericParamClause?.type, "StringProtocol & AnyObject") XCTAssertEqual(genericParamClause?.locations, [ fixtureLocation(line: 15, column: 25), - fixtureLocation(line: 15, column: 42) + fixtureLocation(line: 15, column: 42), ]) let genericWhereClause = results[fixtureLocation(line: 15, column: 75)] @@ -120,7 +120,7 @@ final class TypeSyntaxInspectorTest: XCTestCase { // MARK: - Private private var fixturePath: SourceFile { - let path = FixturesProjectPath.appending( "Sources/TypeSyntaxInspectorFixtures/TypeSyntaxInspectorFixture.swift") + let path = FixturesProjectPath.appending("Sources/TypeSyntaxInspectorFixtures/TypeSyntaxInspectorFixture.swift") return SourceFile(path: path, modules: ["TypeSyntaxInspectorFixtures"]) } @@ -141,10 +141,10 @@ private class TypeSyntaxInspectorTestVisitor: SyntaxVisitor { init(file: SourceFile) throws { let source = try String(contentsOf: file.path.url) - self.syntax = Parser.parse(source: source) - self.locationConverter = .init(fileName: file.path.string, tree: syntax) - self.sourceLocationBuilder = .init(file: file, locationConverter: locationConverter) - self.typeSyntaxInspector = .init(sourceLocationBuilder: sourceLocationBuilder) + syntax = Parser.parse(source: source) + locationConverter = .init(fileName: file.path.string, tree: syntax) + sourceLocationBuilder = .init(file: file, locationConverter: locationConverter) + typeSyntaxInspector = .init(sourceLocationBuilder: sourceLocationBuilder) super.init(viewMode: .sourceAccurate) } diff --git a/Tests/SPMTests/SPMProject/Package.swift b/Tests/SPMTests/SPMProject/Package.swift index da0a285717..b0a76063fb 100644 --- a/Tests/SPMTests/SPMProject/Package.swift +++ b/Tests/SPMTests/SPMProject/Package.swift @@ -7,14 +7,16 @@ let package = Package( .executable( name: "frontend", targets: ["Frontend"] - ) + ), ], targets: [ .executableTarget( name: "Frontend", - dependencies: ["SPMProjectKit"]), + dependencies: ["SPMProjectKit"] + ), .target( name: "SPMProjectKit", - dependencies: []) + dependencies: [] + ), ] ) diff --git a/Tests/Shared/SPMSourceGraphTestCase.swift b/Tests/Shared/SPMSourceGraphTestCase.swift index b1f2a70c7f..8275abd44f 100644 --- a/Tests/Shared/SPMSourceGraphTestCase.swift +++ b/Tests/Shared/SPMSourceGraphTestCase.swift @@ -1,6 +1,6 @@ import Foundation -import Shared import ProjectDrivers +import Shared import SystemPackage class SPMSourceGraphTestCase: SourceGraphTestCase { diff --git a/Tests/Shared/SourceGraphTestCase.swift b/Tests/Shared/SourceGraphTestCase.swift index 7e8472f74d..0935d04656 100644 --- a/Tests/Shared/SourceGraphTestCase.swift +++ b/Tests/Shared/SourceGraphTestCase.swift @@ -97,7 +97,7 @@ open class SourceGraphTestCase: XCTestCase { guard let declaration = materialize(.protocol(name), file: file, line: line) else { return } if let tuple = Self.results.redundantProtocolDeclarations[declaration] { - let decls = tuple.references.compactMap { $0.parent } + let decls = tuple.references.compactMap(\.parent) for conformance in conformances where !decls.contains(where: { $0.kind == conformance.kind && $0.name == conformance.name }) { XCTFail("Expected \(conformance) to implement protocol '\(name)'.", file: file, line: line) @@ -198,14 +198,11 @@ open class SourceGraphTestCase: XCTestCase { // swiftlint:disable:next function_default_parameter_at_end discouraged_optional_collection private func materialize(_ description: DeclarationDescription, in defaultDeclarations: Set? = nil, fail: Bool = true, file: StaticString, line: UInt) -> Declaration? { let declarations = scopedDeclarations(from: defaultDeclarations) - let matchingDeclarations = declarations.filter { $0.kind == description.kind && $0.name == description.name } - var matchedDeclaration: Declaration? - - if let line = description.line { - matchedDeclaration = matchingDeclarations.first(where: { $0.location.line == line }) + let matchedDeclaration = if let line = description.line { + matchingDeclarations.first(where: { $0.location.line == line }) } else { - matchedDeclaration = matchingDeclarations.first + matchingDeclarations.first } if matchedDeclaration == nil, fail { @@ -236,7 +233,7 @@ open class SourceGraphTestCase: XCTestCase { } } -private extension Array where Element == ScanResult { +private extension [ScanResult] { var unusedDeclarations: Set { compactMapSet { if case .unused = $0.annotation { diff --git a/Tests/Shared/XCTestCase+Extensions.swift b/Tests/Shared/XCTestCase+Extensions.swift index 741bd8970f..ddcf0503d3 100644 --- a/Tests/Shared/XCTestCase+Extensions.swift +++ b/Tests/Shared/XCTestCase+Extensions.swift @@ -4,12 +4,12 @@ import XCTest public extension XCTestCase { var testFixturePath: FilePath { #if os(macOS) - let testName = String(name.split(separator: " ").last!).replacingOccurrences(of: "]", with: "") + let testName = String(name.split(separator: " ").last!).replacingOccurrences(of: "]", with: "") #else - let testName = String(name.split(separator: ".", maxSplits: 1).last!) + let testName = String(name.split(separator: ".", maxSplits: 1).last!) #endif let suiteName = String(describing: Self.self).dropLast(4) - return FixturesProjectPath.appending("Sources/\(suiteName)Fixtures/\(testName).swift") + return FixturesProjectPath.appending("Sources/\(suiteName)Fixtures/\(testName).swift") } } diff --git a/Tests/XcodeTests/XcodeSourceGraphTestCase.swift b/Tests/XcodeTests/XcodeSourceGraphTestCase.swift index 0b5036605b..43fe207b37 100644 --- a/Tests/XcodeTests/XcodeSourceGraphTestCase.swift +++ b/Tests/XcodeTests/XcodeSourceGraphTestCase.swift @@ -1,6 +1,6 @@ import Foundation -import Shared import ProjectDrivers +import Shared import SystemPackage @testable import TestShared diff --git a/Tests/XcodeTests/XcodebuildBuildProjectTest.swift b/Tests/XcodeTests/XcodebuildBuildProjectTest.swift index 8cae378267..63c798fd34 100644 --- a/Tests/XcodeTests/XcodebuildBuildProjectTest.swift +++ b/Tests/XcodeTests/XcodebuildBuildProjectTest.swift @@ -63,7 +63,7 @@ class ShellMock: Shell { self.init(environment: ProcessInfo.processInfo.environment, logger: Logger()) } - override func exec(_ args: [String], stderr: Bool = true) throws -> String { + override func exec(_: [String], stderr _: Bool = true) throws -> String { output } } @@ -72,7 +72,7 @@ private let XcodebuildListOutputs = [ XcodebuildListOutputA, XcodebuildListOutputB, XcodebuildListOutputC, - XcodebuildListOutputD + XcodebuildListOutputD, ] private let XcodebuildListOutputA = """ diff --git a/scripts/lint/swiftformat.sh b/scripts/lint/swiftformat.sh new file mode 100755 index 0000000000..c3014445cd --- /dev/null +++ b/scripts/lint/swiftformat.sh @@ -0,0 +1,11 @@ +#!/usr/bin/env bash + +VERSION="0.54.3" +INSTALLED_VERSION=$(swiftformat --version) + +if [[ "$INSTALLED_VERSION" != "$VERSION" ]]; then + echo "ERROR: SwiftFormat ${VERSION} is required, installed version is ${INSTALLED_VERSION}." + exit 1 +fi + +swiftformat . \ No newline at end of file