Skip to content

Commit

Permalink
Initial swiftlint file and fixes (#781)
Browse files Browse the repository at this point in the history
  • Loading branch information
mildm8nnered authored Aug 10, 2024
1 parent 12b22b5 commit a4b6cf1
Show file tree
Hide file tree
Showing 107 changed files with 546 additions and 397 deletions.
68 changes: 68 additions & 0 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
included:
- Sources
- Tests
- Package.swift
excluded:
- Tests/Fixtures
- Tests/AccessibilityTests/AccessibilityProject
- Tests/XcodeTests/UIKitProject

# Enabled/disabled rules
analyzer_rules:
- all
opt_in_rules:
- all
disabled_rules:
- anyobject_protocol
- inert_defer
- unused_capture_list
- explicit_acl
- explicit_type_interface
- missing_docs
- required_deinit
- line_length
- type_contents_order
- prefer_nimble
- explicit_top_level_acl
- anonymous_argument_in_multiline_closure
- one_declaration_per_file
- conditional_returns_on_newline
- vertical_whitespace_between_cases
- no_grouping_extension
- explicit_enum_raw_value
- file_types_order
- indentation_width
- identifier_name
- trailing_closure
- multiline_arguments_brackets
- multiline_function_chains
- no_extension_access_modifier
- force_try
- switch_case_on_newline
- sorted_enum_cases
- prefer_self_in_static_references
- superfluous_else
- force_unwrapping
- file_name
- todo
- no_magic_numbers
- prefixed_toplevel_constant
- untyped_error_in_catch
- cyclomatic_complexity
- closure_body_length
- function_body_length
- type_body_length
- file_length
- contrasted_opening_brace
- unused_parameter
- no_empty_block
- prefer_key_path

balanced_xctest_lifecycle: &unit_test_configuration
test_parent_classes:
- SourceGraphTestCase
- FixtureSourceGraphTestCase
- XCTestCase
empty_xctest_method: *unit_test_configuration
final_test_case: *unit_test_configuration
single_test_class: *unit_test_configuration
2 changes: 1 addition & 1 deletion Sources/Frontend/Commands/CheckUpdateCommand.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Foundation
import ArgumentParser
import Foundation
import Shared

struct CheckUpdateCommand: FrontendCommand {
Expand Down
2 changes: 1 addition & 1 deletion Sources/Frontend/Commands/ClearCacheCommand.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Foundation
import ArgumentParser
import Foundation
import Shared

struct ClearCacheCommand: FrontendCommand {
Expand Down
8 changes: 4 additions & 4 deletions Sources/Frontend/Commands/ScanBehavior.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Foundation
import SystemPackage
import Shared
import PeripheryKit
import Shared
import SystemPackage

final class ScanBehavior {
private let configuration: Configuration
Expand All @@ -16,7 +16,7 @@ final class ScanBehavior {
do {
var path: FilePath?

if let configPath = configPath {
if let configPath {
path = FilePath(configPath)
}
try configuration.load(from: path)
Expand Down Expand Up @@ -90,7 +90,7 @@ final class ScanBehavior {
logger.info(output, canQuiet: false)
logger.endInterval(interval)

if filteredResults.count > 0,
if !filteredResults.isEmpty,
configuration.outputFormat.supportsAuxiliaryOutput {
logger.info(
colorize("\n* ", .boldGreen) +
Expand Down
4 changes: 2 additions & 2 deletions Sources/Frontend/Commands/ScanCommand.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Foundation
import ArgumentParser
import SystemPackage
import Foundation
import Shared
import SystemPackage

struct ScanCommand: FrontendCommand {
static let configuration = CommandConfiguration(
Expand Down
2 changes: 1 addition & 1 deletion Sources/Frontend/Commands/VersionCommand.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Foundation
import ArgumentParser
import Foundation

struct VersionCommand: FrontendCommand {
static let configuration = CommandConfiguration(
Expand Down
2 changes: 1 addition & 1 deletion Sources/Frontend/Project.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Foundation
import SystemPackage
import PeripheryKit
import Shared
import SystemPackage

#if canImport(XcodeSupport)
import XcodeSupport
Expand Down
3 changes: 1 addition & 2 deletions Sources/Frontend/SPMProjectSetupGuide.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import Foundation
import SystemPackage
import PeripheryKit
import Shared
import SystemPackage

final class SPMProjectSetupGuide: SetupGuideHelpers, ProjectSetupGuide {
private let configuration: Configuration
Expand Down Expand Up @@ -51,5 +51,4 @@ final class SPMProjectSetupGuide: SetupGuideHelpers, ProjectSetupGuide {
let targetNames = targets.map { $0.name }.sorted()
return select(multiple: targetNames, allowAll: true)
}

}
2 changes: 1 addition & 1 deletion Sources/Frontend/Scan.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Foundation
import Shared
import PeripheryKit
import Shared
import SourceGraph

final class Scan {
Expand Down
16 changes: 10 additions & 6 deletions Sources/Frontend/UpdateChecker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,10 @@ final class UpdateChecker {
urlRequest.setValue("application/vnd.github.v3+json", forHTTPHeaderField: "Accept")

let task = urlSession.dataTask(with: urlRequest) { [weak self] data, _, error in
// swiftlint:disable:next self_binding
guard let strongSelf = self else { return }

if let error = error {
if let error {
strongSelf.debugLogger.debug("error: \(error.localizedDescription)")
strongSelf.error = error
strongSelf.semaphore.signal()
Expand All @@ -53,8 +54,11 @@ final class UpdateChecker {
let tagName = jsonObject["tag_name"] as? String else {
var json = "N/A"

if let data = data {
json = String(data: data, encoding: .utf8) ?? "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)"
Expand All @@ -72,7 +76,7 @@ final class UpdateChecker {
}

func notifyIfAvailable() {
guard let latestVersion = latestVersion else { return }
guard let latestVersion else { return }

debugLogger.debug("latest: \(latestVersion)")

Expand All @@ -91,15 +95,15 @@ final class UpdateChecker {
func wait() -> Result<String, PeripheryError> {
let waitResult = semaphore.wait(timeout: .now() + 60)

if let error = error {
if let error {
return .failure(.underlyingError(error))
}

if waitResult == .timedOut {
return .failure(PeripheryError.updateCheckError(message: "Timed out while checking for update."))
}

if let latestVersion = latestVersion {
if let latestVersion {
return .success(latestVersion)
}

Expand Down
2 changes: 1 addition & 1 deletion Sources/Frontend/main.swift
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import Foundation
import ArgumentParser
import Foundation
import Shared

Logger.configureBuffering()
Expand Down
4 changes: 2 additions & 2 deletions Sources/Indexer/Indexer.swift
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import FilenameMatcher
import Foundation
import SystemPackage
import Shared
import FilenameMatcher
import SystemPackage

public class Indexer {
private let configuration: Configuration
Expand Down
8 changes: 4 additions & 4 deletions Sources/Indexer/InfoPlistIndexer.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Shared
import SystemPackage
import SourceGraph
import SystemPackage

public final class InfoPlistIndexer: Indexer {
private let infoPlistFiles: Set<FilePath>
Expand All @@ -19,15 +19,15 @@ public final class InfoPlistIndexer: Indexer {
excludedFiles.forEach { self.logger.debug("Excluding \($0.string)") }

try JobPool(jobs: Array(includedFiles)).forEach { [weak self] path in
guard let self = self else { return }
guard let self else { return }

let elapsed = try Benchmark.measure {
try InfoPlistParser(path: path)
.parse()
.forEach { self.graph.add($0) }
.forEach { self.graph.add($0) }
}

self.logger.debug("\(path.string) (\(elapsed)s)")
logger.debug("\(path.string) (\(elapsed)s)")
}
}
}
7 changes: 4 additions & 3 deletions Sources/Indexer/InfoPlistParser.swift
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
import Foundation
import SystemPackage
import AEXML
import Foundation
import Shared
import SourceGraph
import SystemPackage

final class InfoPlistParser {
private static let elements = [
"UISceneClassName", "UISceneDelegateClassName", "NSPrincipalClass",
"NSExtensionPrincipalClass", "CLKComplicationPrincipalClass", "WKExtensionDelegateClassName"]
"NSExtensionPrincipalClass", "CLKComplicationPrincipalClass", "WKExtensionDelegateClassName"
]
private let path: FilePath

required init(path: FilePath) {
Expand Down
4 changes: 2 additions & 2 deletions Sources/Indexer/JobPool.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ struct JobPool<T> {
}
}

if let error = error {
if let error {
throw error
}
}
Expand All @@ -43,7 +43,7 @@ struct JobPool<T> {
}
}

if let error = error {
if let error {
throw error
}

Expand Down
22 changes: 12 additions & 10 deletions Sources/Indexer/SwiftIndexer.swift
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
import Foundation
import SwiftIndexStore
import SystemPackage
import Shared
import SourceGraph
import SwiftIndexStore
import SyntaxAnalysis
import SystemPackage

public final class SwiftIndexer: Indexer {
private let sourceFiles: [FilePath: Set<IndexTarget>]
Expand Down Expand Up @@ -39,6 +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)

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

Expand Down Expand Up @@ -71,8 +72,8 @@ public final class SwiftIndexer: Indexer {
retainedFiles = allSourceFiles.filter { configuration.retainFilesMatchers.anyMatch(filename: $0.string) }
}

let jobs = unitsByFile.map { (file, units) -> Job in
return Job(
let jobs = unitsByFile.map { file, units -> Job in
Job(
file: file,
units: units,
retainAllDeclarations: retainedFiles.contains(file),
Expand Down Expand Up @@ -128,7 +129,6 @@ public final class SwiftIndexer: Indexer {
graph: SourceGraph,
logger: ContextualLogger,
configuration: Configuration

) {
self.file = file
self.units = units
Expand All @@ -138,6 +138,7 @@ public final class SwiftIndexer: Indexer {
self.configuration = configuration
}

// swiftlint:disable nesting
struct RawRelation {
struct Symbol {
let name: String?
Expand Down Expand Up @@ -170,6 +171,7 @@ public 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.
/// Some references may depend upon declarations in other files, and thus their association is deferred until
Expand Down Expand Up @@ -280,7 +282,7 @@ public final class SwiftIndexer: Indexer {
private func getSourceFile() throws -> SourceFile {
if let sourceFile { return sourceFile }

let modules = try units.reduce(into: Set<String>()) { (set, tuple) in
let modules = try units.reduce(into: Set<String>()) { set, tuple in
let (indexStore, unit) = tuple
if let name = try indexStore.moduleName(for: unit) {
set.insert(name)
Expand Down Expand Up @@ -340,11 +342,11 @@ public final class SwiftIndexer: Indexer {

let explicitDeclarations = declarations.filter { !$0.isImplicit }
let declsByLocation = explicitDeclarations
.reduce(into: [Location: [Declaration]]()) { (result, decl) in
.reduce(into: [Location: [Declaration]]()) { result, decl in
result[decl.location, default: []].append(decl)
}
let declsByLine = explicitDeclarations
.reduce(into: [Int: [Declaration]]()) { (result, decl) in
.reduce(into: [Int: [Declaration]]()) { result, decl in
result[decl.location.line, default: []].append(decl)
}
let sortedDeclLines = declsByLine.keys.sorted().reversed()
Expand All @@ -370,7 +372,7 @@ public final class SwiftIndexer: Indexer {
// a decl without a parent, as the reference may be a related type of a class/struct/etc.
if let decl = candidateDecls.first(where: { $0.parent == nil }) {
associate(ref, with: decl)
} else if let decl = candidateDecls.sorted().first {
} else if let decl = candidateDecls.min() {
// Fallback to using the first declaration.
// Sorting the declarations helps in the situation where the candidate declarations includes a
// property/subscript, and a getter on the same line. The property/subscript is more likely to be
Expand Down Expand Up @@ -694,7 +696,7 @@ public final class SwiftIndexer: Indexer {
}

private func transformLocation(_ input: IndexStoreOccurrence.Location) throws -> Location? {
return Location(file: try getSourceFile(), line: Int(input.line), column: Int(input.column))
Location(file: try getSourceFile(), line: Int(input.line), column: Int(input.column))
}

private func transformDeclarationKind(_ kind: IndexStoreSymbol.Kind, _ subKind: IndexStoreSymbol.SubKind) -> Declaration.Kind? {
Expand Down
Loading

0 comments on commit a4b6cf1

Please sign in to comment.