Skip to content

Commit

Permalink
SwiftLint rule updates (#795)
Browse files Browse the repository at this point in the history
  • Loading branch information
ileitch authored Aug 19, 2024
1 parent edb9dcf commit 850960f
Show file tree
Hide file tree
Showing 41 changed files with 246 additions and 295 deletions.
2 changes: 1 addition & 1 deletion .swiftformat
Original file line number Diff line number Diff line change
Expand Up @@ -3,4 +3,4 @@
--exclude Tests/Fixtures/
--exclude Tests/AccessibilityTests/AccessibilityProject/
--exclude Tests/XcodeTests/UIKitProject/
--exclude Tests/XcodeTests/SwiftUIProject/
--exclude Tests/XcodeTests/SwiftUIProject/
78 changes: 24 additions & 54 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
@@ -1,68 +1,38 @@
included:
- Sources
- Tests
- Package.swift
excluded:
- .build
- Tests/Fixtures
- Tests/AccessibilityTests/AccessibilityProject
- Tests/XcodeTests/UIKitProject
- Tests/XcodeTests/SwiftUIProject

# Enabled/disabled rules
analyzer_rules:
- all
opt_in_rules:
- all
- single_test_class

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
# Formatting is handled by SwiftFormat
- trailing_comma
- opening_brace
- vertical_parameter_alignment_on_call
- let_var_whitespace
- indentation_width
- attributes
- 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

# Length/size rules
- cyclomatic_complexity
- closure_body_length
- function_body_length
- type_body_length
- file_length
- contrasted_opening_brace
- unused_parameter
- no_empty_block
- prefer_key_path
- file_length
- line_length
- identifier_name
- type_name
- large_tuple
- function_parameter_count

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
# Other
- discouraged_optional_collection
- non_optional_string_data_conversion # https://github.com/realm/SwiftLint/issues/5263#issuecomment-2115182747
- balanced_xctest_lifecycle
- todo
7 changes: 6 additions & 1 deletion Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -22,4 +22,9 @@ show_bin_path:
@echo ${EXECUTABLE}

swiftformat:
@./scripts/lint/swiftformat.sh
@./scripts/lint/swiftformat.sh

swiftlint:
@./scripts/lint/swiftlint.sh

lint: swiftlint swiftformat
19 changes: 9 additions & 10 deletions Sources/Frontend/UpdateChecker.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,12 @@ 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 }
guard let self else { return }

if let error {
strongSelf.debugLogger.debug("error: \(error.localizedDescription)")
strongSelf.error = error
strongSelf.semaphore.signal()
debugLogger.debug("error: \(error.localizedDescription)")
self.error = error
semaphore.signal()
return
}

Expand All @@ -63,14 +62,14 @@ final class UpdateChecker {
}

let message = "Failed to identify latest release tag in: \(json)"
strongSelf.error = PeripheryError.updateCheckError(message: message)
strongSelf.debugLogger.debug(message)
strongSelf.semaphore.signal()
self.error = PeripheryError.updateCheckError(message: message)
debugLogger.debug(message)
semaphore.signal()
return
}

strongSelf.latestVersion = tagName
strongSelf.semaphore.signal()
latestVersion = tagName
semaphore.signal()
}

task.resume()
Expand Down
1 change: 0 additions & 1 deletion Sources/PeripheryKit/Results/CsvFormatter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -52,7 +52,6 @@ final class CsvFormatter: OutputFormatter {

// MARK: - Private

// swiftlint:disable:next function_parameter_count
private func format(
kind: String,
name: String?,
Expand Down
2 changes: 0 additions & 2 deletions Sources/PeripheryKit/Results/OutputFormatter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ extension OutputFormatter {
var secondaryResults: [(Location, String)] = []

if var name = result.declaration.name {
// swiftlint:disable:next identifier_name
if let kind = result.declaration.kind.displayName, let first_ = kind.first {
let first = String(first_)
description += "\(first.uppercased())\(kind.dropFirst()) "
Expand Down Expand Up @@ -95,7 +94,6 @@ extension OutputFormatter {
}
}

// swiftlint:disable:next no_extension_access_modifier
public extension OutputFormat {
var formatter: OutputFormatter.Type {
switch self {
Expand Down
1 change: 0 additions & 1 deletion Sources/ProjectDrivers/XcodeProjectDriver.swift
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,6 @@
private let project: XcodeProjectlike
private let schemes: Set<String>

// swiftlint:disable:next function_default_parameter_at_end
init(
logger: Logger = .init(),
configuration: Configuration,
Expand Down
11 changes: 3 additions & 8 deletions Sources/Shared/Configuration.swift
Original file line number Diff line number Diff line change
Expand Up @@ -144,10 +144,8 @@ public final class Configuration {
public func asYaml() throws -> String {
var config: [String: Any?] = [:]

for setting in settings {
if setting.hasNonDefaultValue {
config[setting.key] = setting.wrappedValue
}
for setting in settings where setting.hasNonDefaultValue {
config[setting.key] = setting.wrappedValue
}

return try Yams.dump(object: config)
Expand Down Expand Up @@ -187,7 +185,6 @@ public final class Configuration {
}
}

// swiftlint:disable:next discouraged_optional_collection
private var _indexExcludeMatchers: [FilenameMatcher]?
public var indexExcludeMatchers: [FilenameMatcher] {
if let _indexExcludeMatchers {
Expand All @@ -199,7 +196,6 @@ public final class Configuration {
return matchers
}

// swiftlint:disable:next discouraged_optional_collection
private var _retainFilesMatchers: [FilenameMatcher]?
public var retainFilesMatchers: [FilenameMatcher] {
if let _retainFilesMatchers {
Expand Down Expand Up @@ -263,7 +259,7 @@ protocol AbstractSetting {
private let setter: Setter
private var value: Value

fileprivate init(
init(
key: String,
defaultValue: Value,
setter: @escaping Setter = { $0 as? Value }
Expand Down Expand Up @@ -292,7 +288,6 @@ protocol AbstractSetting {
func reset() {
wrappedValue = defaultValue
}
// swiftlint:enable strict_fileprivate
}

private let filePathSetter: (Any) -> FilePath? = { value in
Expand Down
1 change: 0 additions & 1 deletion Sources/Shared/Extensions/Array+Extension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import Foundation
public extension Array {
@inlinable
func group<U: Hashable>(by transform: (Element) -> U) -> [U: [Element]] {
// swiftlint:disable:next reduce_into
reduce([:]) { dictionary, element in
var dictionary = dictionary
let key = transform(element)
Expand Down
3 changes: 0 additions & 3 deletions Sources/Shared/Extensions/FilePath+Glob.swift
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
// swiftlint:disable file_header
// Created by Eric Firestone on 3/22/16.
// Copyright © 2016 Square, Inc. All rights reserved.
// Released under the Apache v2 License.
Expand Down Expand Up @@ -31,7 +30,6 @@ private class Glob {
private let logger: Logger
private var isDirectoryCache: [String: Bool] = [:]

// swiftlint:disable:next strict_fileprivate
fileprivate var paths: Set<String> = []

init(
Expand Down Expand Up @@ -99,7 +97,6 @@ private class Glob {

for directory in directories {
let partiallyResolvedPattern = directory.appendingPathComponent(lastPart)
// swiftlint:disable:next legacy_objc_type
let standardizedPattern = (partiallyResolvedPattern.relativePath as NSString).standardizingPath
results.append(contentsOf: expandGlobstar(pattern: standardizedPattern))
}
Expand Down
8 changes: 4 additions & 4 deletions Sources/Shared/Shell.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ open class Shell {
stderr: Bool = true
) throws -> String {
let env = environment
let (status, output) = try exec(args, stderr: stderr, environment: env)
let (status, output) = try exec(args, environment: env, stderr: stderr)

if status == 0 {
return output
Expand All @@ -73,17 +73,17 @@ open class Shell {
stderr: Bool = true
) throws -> Int32 {
let env = environment
let (status, _) = try exec(args, stderr: stderr, captureOutput: false, environment: env)
let (status, _) = try exec(args, environment: env, stderr: stderr, captureOutput: false)
return status
}

// MARK: - Private

private func exec(
_ args: [String],
environment: [String: String],
stderr: Bool = false,
captureOutput: Bool = true,
environment: [String: String]
captureOutput: Bool = true
) throws -> (Int32, String) {
let launchPath: String
let newArgs: [String]
Expand Down
4 changes: 2 additions & 2 deletions Sources/Shared/SwiftVersion.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,8 @@ public struct SwiftVersion {
public let fullVersion: String

init(shell: Shell = .shared) {
fullVersion = try! shell.exec(["swift", "-version"]).trimmed
version = try! SwiftVersionParser.parse(fullVersion)
fullVersion = try! shell.exec(["swift", "-version"]).trimmed // swiftlint:disable:this force_try
version = try! SwiftVersionParser.parse(fullVersion) // swiftlint:disable:this force_try
}

public func validateVersion() throws {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import Foundation
import Shared

// swiftlint:disable:next type_name
final class ExternalTypeProtocolConformanceReferenceRemover: SourceGraphMutator {
private let graph: SourceGraph

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,6 @@ import Shared
/// Constructors on a class/struct with generic type parameters are not referenced despite being used.
/// We therefore must reference the constructor from the class/struct.
final class GenericClassAndStructConstructorReferenceBuilder: SourceGraphMutator {
// swiftlint:disable:previous type_name

private let graph: SourceGraph

required init(graph: SourceGraph, configuration _: Configuration) {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import Shared

// swiftlint:disable:next type_name
final class RedundantExplicitPublicAccessibilityMarker: SourceGraphMutator {
private let graph: SourceGraph
private let configuration: Configuration
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import Shared
// https://github.com/apple/swift/issues/56189
// The index store does not contain references to `appendInterpolation` functions from their use in string literals.
final class StringInterpolationAppendInterpolationRetainer: SourceGraphMutator {
// swiftlint:disable:previous type_name
private let graph: SourceGraph

required init(graph: SourceGraph, configuration _: Configuration) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import Shared

/// Builds references from struct implicit initializers to the properties it assigns.
final class StructImplicitInitializerReferenceBuilder: SourceGraphMutator {
// swiftlint:disable:previous type_name
private let graph: SourceGraph

init(graph: SourceGraph, configuration _: Configuration) {
Expand Down
4 changes: 0 additions & 4 deletions Sources/SyntaxAnalysis/DeclarationSyntaxVisitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ import SourceGraph
import SwiftSyntax

public final class DeclarationSyntaxVisitor: PeripherySyntaxVisitor {
// swiftlint:disable:next large_tuple
public typealias Result = (
location: Location,
accessibility: Accessibility?,
Expand Down Expand Up @@ -220,10 +219,8 @@ public final class DeclarationSyntaxVisitor: PeripherySyntaxVisitor {

func visitVariableTupleBinding(node: VariableDeclSyntax, pattern: TuplePatternSyntax, typeTuple: TupleTypeElementListSyntax?, initializerTuple: LabeledExprListSyntax?) {
let elements = Array(pattern.elements)
// swiftlint:disable array_init
let types: [TupleTypeElementSyntax?] = typeTuple?.map { $0 } ?? Array(repeating: nil, count: elements.count)
let initializers: [LabeledExprSyntax?] = initializerTuple?.map { $0 } ?? Array(repeating: nil, count: elements.count)
// swiftlint:enable array_init

for (element, (type, initializer)) in zip(elements, zip(types, initializers)) {
if let elementTuplePattern = element.pattern.as(TuplePatternSyntax.self) {
Expand Down Expand Up @@ -301,7 +298,6 @@ public final class DeclarationSyntaxVisitor: PeripherySyntaxVisitor {

// MARK: - Private

// swiftlint:disable:next function_default_parameter_at_end
private func parse(
modifiers: DeclModifierListSyntax?,
attributes: AttributeListSyntax?,
Expand Down
1 change: 0 additions & 1 deletion Sources/SyntaxAnalysis/MultiplexingSyntaxVisitor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,6 @@ public protocol PeripherySyntaxVisitor {
func visitPost(_ node: FunctionCallExprSyntax)
}

// swiftlint:disable:next extension_access_modifier
public extension PeripherySyntaxVisitor {
func visit(_: ActorDeclSyntax) {}
func visit(_: ClassDeclSyntax) {}
Expand Down
1 change: 0 additions & 1 deletion Sources/SyntaxAnalysis/UnusedParameterParser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -319,7 +319,6 @@ struct UnusedParameterParser {
collector)
}

// swiftlint:disable:next function_parameter_count
private func build(
function syntax: SyntaxProtocol,
attributes: AttributeListSyntax?,
Expand Down
1 change: 0 additions & 1 deletion Sources/XcodeSupport/Xcodebuild.swift
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,6 @@ public final class Xcodebuild {

// MARK: - Private

// swiftlint:disable:next discouraged_optional_collection
private func deserialize(_ jsonString: String) throws -> [String: Any]? {
do {
guard let jsonData = jsonString.data(using: .utf8) else { return nil }
Expand Down
3 changes: 3 additions & 0 deletions Tests/.swiftlint.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
disabled_rules:
- implicitly_unwrapped_optional
- force_try
Loading

0 comments on commit 850960f

Please sign in to comment.