Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixed multiple SwiftLint violations #772

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ 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.2"),
.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)
Expand Down Expand Up @@ -131,7 +131,7 @@ var targets: [PackageDescription.Target] = [
.target(name: "PeripheryKit")
],
exclude: ["AccessibilityProject"]
),
)
]

#if os(macOS)
Expand All @@ -142,7 +142,7 @@ targets.append(contentsOf: [
.target(name: "SourceGraph"),
.target(name: "Shared"),
.target(name: "PeripheryKit"),
.product(name: "XcodeProj", package: "XcodeProj"),
.product(name: "XcodeProj", package: "XcodeProj")
]
),
.target(
Expand Down
20 changes: 8 additions & 12 deletions Sources/PeripheryKit/Indexer/SwiftIndexer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ public final class SwiftIndexer: Indexer {
let indexStore = try IndexStore.open(store: URL(fileURLWithPath: indexStorePath.string), lib: .open())
let units = indexStore.units(includeSystem: false)

return try units.compactMap { unit -> (FilePath, IndexStore, IndexStoreUnit)? in
return try units.compactMap { unit -> (FilePath, IndexStore, IndexStoreUnit)? in
guard let filePath = try indexStore.mainFilePath(for: unit) else { return nil }

let file = FilePath.makeAbsolute(filePath, relativeTo: currentFilePath)
Expand Down Expand Up @@ -187,7 +187,7 @@ public final class SwiftIndexer: Indexer {
let location = try transformLocation(occurrence.location)
else { return true }

if !occurrence.roles.intersection([.definition, .declaration]).isEmpty {
if !occurrence.roles.isDisjoint(with: [.definition, .declaration]) {
if let (decl, relations) = try parseRawDeclaration(occurrence, usr, location, indexStore) {
rawDeclsByKey[decl.key, default: []].append((decl, relations))
}
Expand Down Expand Up @@ -257,10 +257,8 @@ public final class SwiftIndexer: Indexer {
sourceFile.importStatements = importSyntaxVisitor.importStatements

if !configuration.disableUnusedImportAnalysis {
for stmt in sourceFile.importStatements {
if stmt.isExported {
graph.addExportedModule(stmt.module, exportedBy: sourceFile.modules)
}
for stmt in sourceFile.importStatements where stmt.isExported {
graph.addExportedModule(stmt.module, exportedBy: sourceFile.modules)
}
}

Expand Down Expand Up @@ -388,10 +386,8 @@ public final class SwiftIndexer: Indexer {
if fileCommands.contains(.ignoreAll) {
retainHierarchy(declarations)
} else {
for decl in declarations {
if decl.commentCommands.contains(.ignore) {
retainHierarchy([decl])
}
for decl in declarations where decl.commentCommands.contains(.ignore) {
retainHierarchy([decl])
}
}
}
Expand Down Expand Up @@ -593,7 +589,7 @@ public final class SwiftIndexer: Indexer {
}
}

if !rel.roles.intersection([.baseOf, .calledBy, .extendedBy, .containedBy]).isEmpty {
if !rel.roles.isDisjoint(with: [.baseOf, .calledBy, .extendedBy, .containedBy]) {
let referencer = rel.symbol

if let referencerUsr = referencer.usr {
Expand Down Expand Up @@ -663,7 +659,7 @@ public final class SwiftIndexer: Indexer {
var refs = [Reference]()

indexStore.forEachRelations(for: occurrence) { rel -> Bool in
if !rel.roles.intersection([.baseOf, .calledBy, .containedBy, .extendedBy]).isEmpty {
if !rel.roles.isDisjoint(with: [.baseOf, .calledBy, .containedBy, .extendedBy]) {
let referencer = rel.symbol

if let referencerUsr = referencer.usr {
Expand Down
10 changes: 5 additions & 5 deletions Sources/PeripheryKit/Results/CodeClimateFormatter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,16 @@ final class CodeClimateFormatter: OutputFormatter {
let lines: [AnyHashable: Any] = [
"begin": result.declaration.location.line
]

let location: [AnyHashable: Any] = [
"path": outputPath(result.declaration.location).url.relativePath,
"lines": lines
]

let description = describe(result, colored: false)
.map { $0.1 }
.joined(separator: ", ")

let fingerprint: String
if result.declaration.kind == .varParameter,
let parentFingerprint = result.declaration.parent?.usrs.joined(separator: "."),
Expand All @@ -37,14 +37,14 @@ final class CodeClimateFormatter: OutputFormatter {
} else {
fingerprint = result.declaration.usrs.joined(separator: ".")
}

let object: [AnyHashable: Any] = [
"description": description,
"fingerprint": fingerprint,
"severity": "major",
"location": location
]

jsonObject.append(object)
}

Expand Down
4 changes: 2 additions & 2 deletions Sources/PeripheryKit/Results/JsonFormatter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,8 @@ final class JsonFormatter: OutputFormatter {
let object: [AnyHashable: Any] = [
"kind": ref.kind.rawValue,
"name": ref.name ?? "",
"modifiers": Array<String>(),
"attributes": Array<String>(),
"modifiers": [String](),
"attributes": [String](),
"accessibility": "",
"ids": [ref.usr],
"hints": [redundantConformanceHint(with: inherited)],
Expand Down
2 changes: 1 addition & 1 deletion Sources/PeripheryKit/Results/OutputFormatter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ extension OutputFormatter {
return "unused"
case .assignOnlyProperty:
return "assignOnlyProperty"
case .redundantProtocol(_, _):
case .redundantProtocol:
return "redundantProtocol"
case .redundantPublicAccessibility:
return "redundantPublicAccessibility"
Expand Down
2 changes: 1 addition & 1 deletion Sources/PeripheryKit/Syntax/ImportSyntaxVisitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ final class ImportSyntaxVisitor: PeripherySyntaxVisitor {
func visit(_ node: ImportDeclSyntax) {
let parts = node.path.map { $0.name.text }
let module = parts.first ?? ""
let attributes = node.attributes.compactMap { $0.as(AttributeSyntax.self)?.attributeName.trimmedDescription }
let attributes = node.attributes.compactMap { $0.as(AttributeSyntax.self)?.attributeName.trimmedDescription }
let location = sourceLocationBuilder.location(at: node.positionAfterSkippingLeadingTrivia)
let statement = ImportStatement(
module: module,
Expand Down
6 changes: 2 additions & 4 deletions Sources/PeripheryKit/Syntax/UnusedParameterAnalyzer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,8 @@ final class UnusedParameterAnalyzer {
case let item as Identifier:
return item.name == param.name ? .used : .unused
case let item as GenericItem where item.node.is(LabeledExprListSyntax.self): // function call arguments
for item in item.items {
if isParam(param, usedIn: item) {
return .used
}
for item in item.items where isParam(param, usedIn: item) {
return .used
}

return .unused
Expand Down
2 changes: 1 addition & 1 deletion Sources/Shared/Configuration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,7 @@ public final class Configuration {
if $retainCodableProperties.hasNonDefaultValue {
config[$retainCodableProperties.key] = retainCodableProperties
}

if $retainEncodableProperties.hasNonDefaultValue {
config[$retainEncodableProperties.key] = retainEncodableProperties
}
Expand Down
10 changes: 5 additions & 5 deletions Sources/Shared/Extensions/FilePath+Glob.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ public extension FilePath {

return Glob(
pattern: absolutePattern,
blacklistedDirectories: [".build", "node_modules", ".gems", "gems", ".swiftpm"],
excludedDirectories: [".build", "node_modules", ".gems", "gems", ".swiftpm"],
logger: Logger()
).paths.mapSet { FilePath($0).lexicallyNormalized() }
}
Expand All @@ -27,18 +27,18 @@ public extension FilePath {
/// 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 blacklistedDirectories: [String]
private let excludedDirectories: [String]
private let logger: Logger
private var isDirectoryCache: [String: Bool] = [:]

fileprivate var paths: Set<String> = []

init(
pattern: String,
blacklistedDirectories: [String],
excludedDirectories: [String],
logger: Logger
) {
self.blacklistedDirectories = blacklistedDirectories
self.excludedDirectories = excludedDirectories
self.logger = logger

let hasTrailingGlobstarSlash = pattern.hasSuffix("**/")
Expand Down Expand Up @@ -107,7 +107,7 @@ private class Glob {

private func exploreDirectories(url: URL) throws -> [URL] {
let subURLs = try FileManager.default.contentsOfDirectory(atPath: url.path).flatMap { subPath -> [URL] in
if blacklistedDirectories.contains(subPath) {
if excludedDirectories.contains(subPath) {
return []
}

Expand Down
4 changes: 2 additions & 2 deletions Sources/Shared/UnfairLock.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,13 @@ import os

public final class UnfairLock {
#if canImport(os)
private var _osAllocatedUnfairLock: Any? = nil
private var _osAllocatedUnfairLock: Any?

private var osAllocatedUnfairLock: OSAllocatedUnfairLock<Void> {
_osAllocatedUnfairLock as! OSAllocatedUnfairLock
}
#else
private var _nsLock: Any? = nil
private var _nsLock: Any?

private var nsLock: NSLock {
_nsLock as! NSLock
Expand Down
2 changes: 1 addition & 1 deletion Sources/SourceGraph/Elements/Declaration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ extension Declaration: Comparable {
public struct DeclarationAccessibility {
public let value: Accessibility
public let isExplicit: Bool

public init(value: Accessibility, isExplicit: Bool) {
self.value = value
self.isExplicit = isExplicit
Expand Down
2 changes: 1 addition & 1 deletion Sources/SourceGraph/Elements/ImportStatement.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ public struct ImportStatement {
public let isTestable: Bool
public let isExported: Bool
public let location: Location

public init(
module: String,
isTestable: Bool,
Expand Down
16 changes: 7 additions & 9 deletions Sources/SourceGraph/Mutators/AccessibilityCascader.swift
Original file line number Diff line number Diff line change
Expand Up @@ -20,16 +20,14 @@ final class AccessibilityCascader: SourceGraphMutator {
// MARK: - Private

private func cascadeAccessibility(for decls: [Declaration], only kinds: Set<Declaration.Kind> = []) throws {
for decl in decls {
if decl.accessibility.isExplicit {
for childDecl in decl.declarations {
if !kinds.isEmpty && !kinds.contains(childDecl.kind) {
continue
}
for decl in decls where decl.accessibility.isExplicit {
for childDecl in decl.declarations {
if !kinds.isEmpty && !kinds.contains(childDecl.kind) {
continue
}

if !childDecl.accessibility.isExplicit {
childDecl.accessibility = .init(value: decl.accessibility.value, isExplicit: false)
}
if !childDecl.accessibility.isExplicit {
childDecl.accessibility = .init(value: decl.accessibility.value, isExplicit: false)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,10 +13,8 @@ class InterfaceBuilderPropertyRetainer {
let extensions = graph.declarations(ofKind: .extensionClass)

for extDecl in extensions {
for decl in extDecl.declarations {
if decl.attributes.contains(where: { ibAttributes.contains($0) }) {
graph.markRetained(decl)
}
for decl in extDecl.declarations where decl.attributes.contains(where: { ibAttributes.contains($0) }) {
graph.markRetained(decl)
}
}
}
Expand All @@ -26,10 +24,8 @@ class InterfaceBuilderPropertyRetainer {
let descendentInheritedDeclarations = inheritedDeclarations.map { $0.declarations }.joined()
let allDeclarations = declaration.declarations.union(descendentInheritedDeclarations)

for declaration in allDeclarations {
if declaration.attributes.contains(where: { ibAttributes.contains($0) }) {
graph.markRetained(declaration)
}
for declaration in allDeclarations where declaration.attributes.contains(where: { ibAttributes.contains($0) }) {
graph.markRetained(declaration)
}
}
}
10 changes: 4 additions & 6 deletions Sources/SourceGraph/Mutators/PropertyWrapperRetainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,10 @@ final class PropertyWrapperRetainer: SourceGraphMutator {
}

func mutate() {
for decl in graph.declarations(ofKinds: Declaration.Kind.toplevelAttributableKind) {
if decl.attributes.contains("propertyWrapper") {
decl.declarations
.filter { $0.kind == .varInstance && specialProperties.contains($0.name ?? "") }
.forEach { graph.markRetained($0) }
}
for decl in graph.declarations(ofKinds: Declaration.Kind.toplevelAttributableKind) where decl.attributes.contains("propertyWrapper") {
decl.declarations
.filter { $0.kind == .varInstance && specialProperties.contains($0.name ?? "") }
.forEach { graph.markRetained($0) }
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ final class PubliclyAccessibleRetainer: SourceGraphMutator {
}

let publicDeclarations = declarations.filter { $0.accessibility.value == .public || $0.accessibility.value == .open }

publicDeclarations.forEach { graph.markRetained($0) }

// Enum cases inherit the accessibility of the enum.
Expand Down
12 changes: 5 additions & 7 deletions Sources/SourceGraph/Mutators/ResultBuilderRetainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,20 +12,18 @@ final class ResultBuilderRetainer: SourceGraphMutator {
"buildArray(_:)",
"buildBlock(_:)",
"buildFinalResult(_:)",
"buildLimitedAvailability(_:)",
"buildLimitedAvailability(_:)"
])

required init(graph: SourceGraph, configuration: Configuration) {
self.graph = graph
}

func mutate() {
for decl in graph.declarations(ofKinds: Declaration.Kind.toplevelAttributableKind) {
if decl.attributes.contains("resultBuilder") {
for childDecl in decl.declarations {
if let name = childDecl.name, resultBuilderMethods.contains(name) {
graph.markRetained(childDecl)
}
for decl in graph.declarations(ofKinds: Declaration.Kind.toplevelAttributableKind) where decl.attributes.contains("resultBuilder") {
for childDecl in decl.declarations {
if let name = childDecl.name, resultBuilderMethods.contains(name) {
graph.markRetained(childDecl)
}
}
}
Expand Down
8 changes: 3 additions & 5 deletions Sources/SourceGraph/Mutators/UnusedParameterRetainer.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ final class UnusedParameterRetainer: SourceGraphMutator {
functionDecl.unusedParameters.forEach { graph.markRetained($0) }
}
} else {
let overrideDecls = conformingDecls.flatMap { graph.allOverrideDeclarations(fromBase:$0) }
let overrideDecls = conformingDecls.flatMap { graph.allOverrideDeclarations(fromBase: $0) }
let allFunctionDecls = conformingDecls + overrideDecls + extFuncDecls + [protoFuncDecl]

for functionDecl in allFunctionDecls {
Expand Down Expand Up @@ -90,10 +90,8 @@ final class UnusedParameterRetainer: SourceGraphMutator {
}

private func retain(params: [Declaration], usedIn functionDecls: [Declaration]) {
for param in params {
if isParam(param, usedInAnyOf: functionDecls) {
graph.markRetained(param)
}
for param in params where isParam(param, usedInAnyOf: functionDecls) {
graph.markRetained(param)
}
}

Expand Down
4 changes: 2 additions & 2 deletions Tests/AccessibilityTests/AccessibilityProject/Package.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ let package = Package(
.executable(
name: "app",
targets: ["MainTarget"]
),
)
],
targets: [
.executableTarget(
Expand All @@ -23,6 +23,6 @@ let package = Package(
dependencies: ["ExternalTarget"]),
.testTarget(
name: "TestTarget",
dependencies: ["MainTarget", "TargetA"]),
dependencies: ["MainTarget", "TargetA"])
]
)
Original file line number Diff line number Diff line change
Expand Up @@ -8,4 +8,4 @@ public class IgnoreAllCommentCommandRetainer {
public func retain() {
_ = IgnoreAllCommentCommand()
}
}
}
Loading
Loading