Enable `if_let_shadowing` rule and fix all violations (#4247)

This commit is contained in:
Danny Mösch 2023-01-31 22:31:38 +01:00 committed by GitHub
parent 60610cef84
commit 5eed8fe91b
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
51 changed files with 75 additions and 78 deletions

View File

@ -33,6 +33,7 @@ opt_in_rules:
- first_where - first_where
- flatmap_over_map_reduce - flatmap_over_map_reduce
- identical_operands - identical_operands
- if_let_shadowing
- joined_default_parameter - joined_default_parameter
- last_where - last_where
- legacy_multiple - legacy_multiple

View File

@ -55,7 +55,7 @@ extension Configuration {
// MARK: SwiftLint Cache (On-Disk) // MARK: SwiftLint Cache (On-Disk)
internal var cacheDescription: String { internal var cacheDescription: String {
if let computedCacheDescription = computedCacheDescription { if let computedCacheDescription {
return computedCacheDescription return computedCacheDescription
} }

View File

@ -118,7 +118,7 @@ internal extension Configuration.FileGraph.FilePath {
} }
private mutating func handleMissingNetwork(urlString: String, cachedFilePath: String?) throws -> String { private mutating func handleMissingNetwork(urlString: String, cachedFilePath: String?) throws -> String {
if let cachedFilePath = cachedFilePath { if let cachedFilePath {
queuedPrintError( queuedPrintError(
"warning: No internet connectivity: Unable to load remote config from \"\(urlString)\". " "warning: No internet connectivity: Unable to load remote config from \"\(urlString)\". "
+ "Using cached version as a fallback." + "Using cached version as a fallback."
@ -139,7 +139,7 @@ internal extension Configuration.FileGraph.FilePath {
taskDone: Bool, taskDone: Bool,
timeout: TimeInterval timeout: TimeInterval
) throws -> String { ) throws -> String {
if let cachedFilePath = cachedFilePath { if let cachedFilePath {
if taskDone { if taskDone {
queuedPrintError( queuedPrintError(
"warning: Unable to load remote config from \"\(urlString)\". Using cached version as a fallback." "warning: Unable to load remote config from \"\(urlString)\". Using cached version as a fallback."
@ -169,7 +169,7 @@ internal extension Configuration.FileGraph.FilePath {
} }
private mutating func handleFileWriteFailure(urlString: String, cachedFilePath: String?) throws -> String { private mutating func handleFileWriteFailure(urlString: String, cachedFilePath: String?) throws -> String {
if let cachedFilePath = cachedFilePath { if let cachedFilePath {
queuedPrintError("Unable to cache remote config from \"\(urlString)\". Using cached version as a fallback.") queuedPrintError("Unable to cache remote config from \"\(urlString)\". Using cached version as a fallback.")
self = .existing(path: cachedFilePath) self = .existing(path: cachedFilePath)
return cachedFilePath return cachedFilePath

View File

@ -29,7 +29,7 @@ internal extension Configuration {
defer { resultingRulesLock.unlock() } defer { resultingRulesLock.unlock() }
// Return existing value if it's available // Return existing value if it's available
if let cachedResultingRules = cachedResultingRules { return cachedResultingRules } if let cachedResultingRules { return cachedResultingRules }
// Calculate value // Calculate value
let customRulesFilter: (RegexConfiguration) -> (Bool) let customRulesFilter: (RegexConfiguration) -> (Bool)

View File

@ -89,7 +89,7 @@ public struct SourceKittenDictionary {
/// Returns byte range starting from `offset` with `length` bytes /// Returns byte range starting from `offset` with `length` bytes
var byteRange: ByteRange? { var byteRange: ByteRange? {
guard let offset = offset, let length = length else { return nil } guard let offset, let length else { return nil }
return ByteRange(location: offset, length: length) return ByteRange(location: offset, length: length)
} }

View File

@ -66,7 +66,7 @@ extension SourceKittenDictionary {
/// arguments appears in the view's substructure. /// arguments appears in the view's substructure.
func hasModifier(anyOf modifiers: [SwiftUIModifier], in file: SwiftLintFile) -> Bool { func hasModifier(anyOf modifiers: [SwiftUIModifier], in file: SwiftLintFile) -> Bool {
// SwiftUI ViewModifiers are treated as `call` expressions, and we make sure we can get the expression's name. // SwiftUI ViewModifiers are treated as `call` expressions, and we make sure we can get the expression's name.
guard expressionKind == .call, let name = name else { guard expressionKind == .call, let name else {
return false return false
} }
@ -169,7 +169,7 @@ extension SourceKittenDictionary {
/// Helper to get the value of an argument. /// Helper to get the value of an argument.
func getArgumentValue(in file: SwiftLintFile) -> String? { func getArgumentValue(in file: SwiftLintFile) -> String? {
guard expressionKind == .argument, let bodyByteRange = bodyByteRange else { guard expressionKind == .argument, let bodyByteRange else {
return nil return nil
} }
@ -178,7 +178,7 @@ extension SourceKittenDictionary {
/// Helper to get the value of a single unnamed argument to a function call. /// Helper to get the value of a single unnamed argument to a function call.
func getSingleUnnamedArgumentValue(in file: SwiftLintFile) -> String? { func getSingleUnnamedArgumentValue(in file: SwiftLintFile) -> String? {
guard expressionKind == .call, let bodyByteRange = bodyByteRange else { guard expressionKind == .call, let bodyByteRange else {
return nil return nil
} }

View File

@ -15,7 +15,7 @@ extension SourceKittenDictionary {
guard let range = dictionary.byteRange else { guard let range = dictionary.byteRange else {
return return
} }
if let byteOffset = byteOffset, !range.contains(byteOffset) { if let byteOffset, !range.contains(byteOffset) {
return return
} }
if let kind = dictionary.kind { if let kind = dictionary.kind {

View File

@ -40,7 +40,7 @@ extension String {
} }
internal func substring(from: Int, length: Int? = nil) -> String { internal func substring(from: Int, length: Int? = nil) -> String {
if let length = length { if let length {
return self[from..<from + length] return self[from..<from + length]
} }
return String(self[index(startIndex, offsetBy: from, limitedBy: endIndex)!...]) return String(self[index(startIndex, offsetBy: from, limitedBy: endIndex)!...])

View File

@ -33,7 +33,7 @@ extension SwiftDeclarationAttributeKind {
$0.swiftDeclarationAttributeKinds.contains(where: { $0.rawValue == rawAttribute }) $0.swiftDeclarationAttributeKinds.contains(where: { $0.rawValue == rawAttribute })
} }
if let modifierGroup = modifierGroup { if let modifierGroup {
self = modifierGroup self = modifierGroup
} else { } else {
return nil return nil

View File

@ -16,7 +16,7 @@ extension SwiftLintFile {
var regions = [Region]() var regions = [Region]()
var disabledRules = Set<RuleIdentifier>() var disabledRules = Set<RuleIdentifier>()
let commands: [Command] let commands: [Command]
if let restrictingRuleIdentifiers = restrictingRuleIdentifiers { if let restrictingRuleIdentifiers {
commands = self.commands().filter { command in commands = self.commands().filter { command in
return command.ruleIdentifiers.contains(where: restrictingRuleIdentifiers.contains) return command.ruleIdentifiers.contains(where: restrictingRuleIdentifiers.contains)
} }
@ -55,7 +55,7 @@ extension SwiftLintFile {
} }
internal func commands(in range: NSRange? = nil) -> [Command] { internal func commands(in range: NSRange? = nil) -> [Command] {
guard let range = range else { guard let range else {
return commands return commands
.flatMap { $0.expand() } .flatMap { $0.expand() }
} }
@ -233,7 +233,7 @@ extension SwiftLintFile {
guard let stringData = string.data(using: .utf8) else { guard let stringData = string.data(using: .utf8) else {
queuedFatalError("can't encode '\(string)' with UTF8") queuedFatalError("can't encode '\(string)' with UTF8")
} }
guard let path = path, let fileHandle = FileHandle(forWritingAtPath: path) else { guard let path, let fileHandle = FileHandle(forWritingAtPath: path) else {
queuedFatalError("can't write to path '\(String(describing: self.path))'") queuedFatalError("can't write to path '\(String(describing: self.path))'")
} }
_ = fileHandle.seekToEndOfFile() _ = fileHandle.seekToEndOfFile()
@ -250,7 +250,7 @@ extension SwiftLintFile {
if isVirtual { if isVirtual {
return return
} }
guard let path = path else { guard let path else {
queuedFatalError("file needs a path to call write(_:)") queuedFatalError("file needs a path to call write(_:)")
} }
guard let stringData = String(string).data(using: .utf8) else { guard let stringData = String(string).data(using: .utf8) else {

View File

@ -225,7 +225,7 @@ extension FunctionDeclSyntax {
/// How many times this function calls the `super` implementation in its body. /// How many times this function calls the `super` implementation in its body.
/// Returns 0 if the function has no body. /// Returns 0 if the function has no body.
func numberOfCallsToSuper() -> Int { func numberOfCallsToSuper() -> Int {
guard let body = body else { guard let body else {
return 0 return 0
} }

View File

@ -123,7 +123,7 @@ public struct Command: Equatable {
/// ///
/// - returns: The expanded commands. /// - returns: The expanded commands.
internal func expand() -> [Command] { internal func expand() -> [Command] {
guard let modifier = modifier else { guard let modifier else {
return [self] return [self]
} }
switch modifier { switch modifier {

View File

@ -132,7 +132,7 @@ public struct Configuration {
pinnedVersion: String? = nil, pinnedVersion: String? = nil,
allowZeroLintableFiles: Bool = false allowZeroLintableFiles: Bool = false
) { ) {
if let pinnedVersion = pinnedVersion, pinnedVersion != Version.current.value { if let pinnedVersion, pinnedVersion != Version.current.value {
queuedPrintError( queuedPrintError(
"Currently running SwiftLint \(Version.current.value) but " + "Currently running SwiftLint \(Version.current.value) but " +
"configuration specified version \(pinnedVersion)." "configuration specified version \(pinnedVersion)."

View File

@ -19,7 +19,7 @@ private extension Rule {
static func superfluousDisableCommandViolations(regions: [Region], static func superfluousDisableCommandViolations(regions: [Region],
superfluousDisableCommandRule: SuperfluousDisableCommandRule?, superfluousDisableCommandRule: SuperfluousDisableCommandRule?,
allViolations: [StyleViolation]) -> [StyleViolation] { allViolations: [StyleViolation]) -> [StyleViolation] {
guard regions.isNotEmpty, let superfluousDisableCommandRule = superfluousDisableCommandRule else { guard regions.isNotEmpty, let superfluousDisableCommandRule else {
return [] return []
} }
@ -240,7 +240,7 @@ public struct CollectedLinter {
deprecatedToValidIdentifier[key] = value deprecatedToValidIdentifier[key] = value
} }
if let cache = cache, let path = file.path { if let cache, let path = file.path {
cache.cache(violations: violations, forFile: path, configuration: configuration) cache.cache(violations: violations, forFile: path, configuration: configuration)
} }
@ -257,7 +257,7 @@ public struct CollectedLinter {
private func cachedStyleViolations(benchmark: Bool = false) -> ([StyleViolation], [(id: String, time: Double)])? { private func cachedStyleViolations(benchmark: Bool = false) -> ([StyleViolation], [(id: String, time: Double)])? {
let start: Date! = benchmark ? Date() : nil let start: Date! = benchmark ? Date() : nil
guard let cache = cache, let file = file.path, guard let cache, let file = file.path,
let cachedViolations = cache.violations(forFile: file, configuration: configuration) else { let cachedViolations = cache.violations(forFile: file, configuration: configuration) else {
return nil return nil
} }
@ -314,7 +314,7 @@ public struct CollectedLinter {
let formattedContents = try? file.file.format(trimmingTrailingWhitespace: true, let formattedContents = try? file.file.format(trimmingTrailingWhitespace: true,
useTabs: useTabs, useTabs: useTabs,
indentWidth: indentWidth) indentWidth: indentWidth)
if let formattedContents = formattedContents { if let formattedContents {
file.write(formattedContents) file.write(formattedContents)
} }
} }
@ -323,7 +323,7 @@ public struct CollectedLinter {
configuration: Configuration, configuration: Configuration,
superfluousDisableCommandRule: SuperfluousDisableCommandRule? superfluousDisableCommandRule: SuperfluousDisableCommandRule?
) -> [StyleViolation] { ) -> [StyleViolation] {
guard regions.isNotEmpty, let superfluousDisableCommandRule = superfluousDisableCommandRule else { guard regions.isNotEmpty, let superfluousDisableCommandRule else {
return [] return []
} }

View File

@ -128,7 +128,7 @@ public final class LinterCache {
return fileCache return fileCache
} }
guard let location = location else { guard let location else {
return .empty return .empty
} }

View File

@ -207,7 +207,7 @@ private extension DiscouragedNoneNameRule {
} }
}() }()
guard let type = type else { guard let type else {
return return
} }

View File

@ -194,7 +194,7 @@ private extension Line {
/// For "import A.B.C" returns slices [["A", "B", "C"], ["A", "B"], ["A"]] /// For "import A.B.C" returns slices [["A", "B", "C"], ["A", "B"], ["A"]]
var importSlices: [ImportSlice] { var importSlices: [ImportSlice] {
guard let importIdentifier = importIdentifier else { return [] } guard let importIdentifier else { return [] }
let importedSubpathParts = importIdentifier.split(separator: ".").map { String($0) } let importedSubpathParts = importIdentifier.split(separator: ".").map { String($0) }
guard !importedSubpathParts.isEmpty else { return [] } guard !importedSubpathParts.isEmpty else { return [] }

View File

@ -225,7 +225,7 @@ private extension ExplicitInitRule {
private extension MemberAccessExprSyntax { private extension MemberAccessExprSyntax {
var explicitInitPosition: AbsolutePosition? { var explicitInitPosition: AbsolutePosition? {
if let base = base, base.isTypeReferenceLike, name.text == "init" { if let base, base.isTypeReferenceLike, name.text == "init" {
return base.endPositionBeforeTrailingTrivia return base.endPositionBeforeTrailingTrivia
} else { } else {
return nil return nil

View File

@ -96,7 +96,7 @@ private extension ExplicitTopLevelACLRule {
} }
private func hasViolation(modifiers: ModifierListSyntax?) -> Bool { private func hasViolation(modifiers: ModifierListSyntax?) -> Bool {
guard let modifiers = modifiers else { guard let modifiers else {
return true return true
} }

View File

@ -182,7 +182,7 @@ private extension RedundantOptionalInitializationRule {
private extension PatternBindingSyntax { private extension PatternBindingSyntax {
var violationPosition: AbsolutePosition? { var violationPosition: AbsolutePosition? {
guard let initializer = initializer, guard let initializer,
let type = typeAnnotation, let type = typeAnnotation,
initializer.isInitializingToNil, initializer.isInitializingToNil,
type.isOptionalType else { type.isOptionalType else {

View File

@ -103,7 +103,7 @@ private extension RedundantStringEnumValueRule {
private extension EnumDeclSyntax { private extension EnumDeclSyntax {
var isStringEnum: Bool { var isStringEnum: Bool {
guard let inheritanceClause = inheritanceClause else { guard let inheritanceClause else {
return false return false
} }

View File

@ -129,7 +129,7 @@ private extension String {
} }
func strippingTrailingSwiftUIPreviewProvider(inheritedTypes: InheritedTypeListSyntax?) -> String { func strippingTrailingSwiftUIPreviewProvider(inheritedTypes: InheritedTypeListSyntax?) -> String {
guard let inheritedTypes = inheritedTypes, guard let inheritedTypes,
hasSuffix("_Previews"), hasSuffix("_Previews"),
let lastPreviewsIndex = lastIndex(of: "_Previews"), let lastPreviewsIndex = lastIndex(of: "_Previews"),
inheritedTypes.typeNames.contains("PreviewProvider") else { inheritedTypes.typeNames.contains("PreviewProvider") else {

View File

@ -41,7 +41,7 @@ private final class EmptyXCTestMethodRuleVisitor: ViolationsSyntaxVisitor {
private extension FunctionDeclSyntax { private extension FunctionDeclSyntax {
var hasEmptyBody: Bool { var hasEmptyBody: Bool {
if let body = body { if let body {
return body.statements.isEmpty return body.statements.isEmpty
} }
return false return false

View File

@ -99,7 +99,7 @@ struct ExpiringTodoRule: ConfigurationProviderRule, OptInRule {
} }
private func violationLevel(for expiryDate: Date?) -> ExpiryViolationLevel? { private func violationLevel(for expiryDate: Date?) -> ExpiryViolationLevel? {
guard let expiryDate = expiryDate else { guard let expiryDate else {
return .badFormatting return .badFormatting
} }
guard expiryDate.isAfterToday else { guard expiryDate.isAfterToday else {

View File

@ -159,7 +159,7 @@ private extension DeclModifierSyntax {
private extension SyntaxProtocol { private extension SyntaxProtocol {
func nearestNominalParent() -> Syntax? { func nearestNominalParent() -> Syntax? {
guard let parent = parent else { guard let parent else {
return nil return nil
} }
@ -167,7 +167,7 @@ private extension SyntaxProtocol {
} }
func nearestNominalExtensionDeclParent() -> Syntax? { func nearestNominalExtensionDeclParent() -> Syntax? {
guard let parent = parent, !parent.isNominalTypeDecl else { guard let parent, !parent.isNominalTypeDecl else {
return nil return nil
} }

View File

@ -53,7 +53,7 @@ struct OrphanedDocCommentRule: SourceKitFreeRule, ConfigurationProviderRule {
.compactMap { first, second in .compactMap { first, second in
let firstByteRange = first.range.toSourceKittenByteRange() let firstByteRange = first.range.toSourceKittenByteRange()
guard guard
let second = second, let second,
first.kind == .docLineComment || first.kind == .docBlockComment, first.kind == .docLineComment || first.kind == .docBlockComment,
second.kind == .lineComment || second.kind == .blockComment, second.kind == .lineComment || second.kind == .blockComment,
let firstString = file.stringView.substringWithByteRange(firstByteRange), let firstString = file.stringView.substringWithByteRange(firstByteRange),

View File

@ -244,7 +244,7 @@ private extension SourceKittenDictionary {
} }
func aclAtOffset(_ offset: ByteCount) -> AccessControlLevel? { func aclAtOffset(_ offset: ByteCount) -> AccessControlLevel? {
if let nameOffset = nameOffset, if let nameOffset,
nameOffset == offset, nameOffset == offset,
let acl = accessibility { let acl = accessibility {
return acl return acl
@ -288,7 +288,7 @@ private extension SourceKittenDictionary {
} }
func shouldSkipResultBuilder() -> Bool { func shouldSkipResultBuilder() -> Bool {
guard let name = name, declarationKind == .functionMethodStatic else { guard let name, declarationKind == .functionMethodStatic else {
return false return false
} }

View File

@ -257,7 +257,7 @@ private extension SwiftLintFile {
// Operators that are a part of some body are reported as method.static // Operators that are a part of some body are reported as method.static
func mightBeOperator(kind: String?) -> Bool { func mightBeOperator(kind: String?) -> Bool {
guard let kind = kind else { return false } guard let kind else { return false }
return [ return [
"source.lang.swift.ref.function.operator", "source.lang.swift.ref.function.operator",
"source.lang.swift.ref.function.method.static" "source.lang.swift.ref.function.method.static"

View File

@ -6,7 +6,7 @@ struct NumberSeparatorConfiguration: SeverityBasedRuleConfiguration, Equatable {
var consoleDescription: String { var consoleDescription: String {
let minimumFractionLengthDescription: String let minimumFractionLengthDescription: String
if let minimumFractionLength = minimumFractionLength { if let minimumFractionLength {
minimumFractionLengthDescription = ", minimum_fraction_length: \(minimumFractionLength)" minimumFractionLengthDescription = ", minimum_fraction_length: \(minimumFractionLength)"
} else { } else {
minimumFractionLengthDescription = ", minimum_fraction_length: none" minimumFractionLengthDescription = ", minimum_fraction_length: none"

View File

@ -20,7 +20,7 @@ public struct SeverityLevelsConfiguration: RuleConfiguration, Equatable {
var error: Int? var error: Int?
var params: [RuleParameter<Int>] { var params: [RuleParameter<Int>] {
if let error = error { if let error {
return [RuleParameter(severity: .error, value: error), return [RuleParameter(severity: .error, value: error),
RuleParameter(severity: .warning, value: warning)] RuleParameter(severity: .warning, value: warning)]
} }

View File

@ -169,7 +169,7 @@ private extension AttributeListSyntax {
// swiftlint:disable:next cyclomatic_complexity // swiftlint:disable:next cyclomatic_complexity
func makeHelper(locationConverter: SourceLocationConverter) -> RuleHelper? { func makeHelper(locationConverter: SourceLocationConverter) -> RuleHelper? {
guard let parent = parent else { guard let parent else {
return nil return nil
} }

View File

@ -71,7 +71,7 @@ private extension ClosingBraceRule {
private extension TokenSyntax { private extension TokenSyntax {
var hasClosingBraceViolation: Bool { var hasClosingBraceViolation: Bool {
guard tokenKind == .rightBrace, guard tokenKind == .rightBrace,
let nextToken = nextToken, let nextToken,
nextToken.tokenKind == .rightParen nextToken.tokenKind == .rightParen
else { else {
return false return false

View File

@ -230,7 +230,7 @@ private extension TokenSyntax {
return true return true
} else if case .newlines = nextToken?.leadingTrivia.first { } else if case .newlines = nextToken?.leadingTrivia.first {
return true return true
} else if let nextToken = nextToken, allowedKinds.contains(nextToken.tokenKind) { } else if let nextToken, allowedKinds.contains(nextToken.tokenKind) {
return true return true
} else { } else {
return false return false

View File

@ -76,7 +76,7 @@ private extension ConditionalReturnsOnNewlineRule {
} }
private func isReturn(_ returnStmt: ReturnStmtSyntax?, onTheSameLineAs token: TokenSyntax) -> Bool { private func isReturn(_ returnStmt: ReturnStmtSyntax?, onTheSameLineAs token: TokenSyntax) -> Bool {
guard let returnStmt = returnStmt else { guard let returnStmt else {
return false return false
} }

View File

@ -100,7 +100,7 @@ private extension EmptyParenthesesWithTrailingClosureRule {
private extension FunctionCallExprSyntax { private extension FunctionCallExprSyntax {
var violationPosition: AbsolutePosition? { var violationPosition: AbsolutePosition? {
guard trailingClosure != nil, guard trailingClosure != nil,
let leftParen = leftParen, let leftParen,
argumentList.isEmpty else { argumentList.isEmpty else {
return nil return nil
} }

View File

@ -60,7 +60,7 @@ struct FileHeaderRule: ConfigurationProviderRule, OptInRule {
let requiredRegex = configuration.requiredRegex(for: file) let requiredRegex = configuration.requiredRegex(for: file)
var violationsOffsets = [Int]() var violationsOffsets = [Int]()
if let firstToken = firstToken, let lastToken = lastToken { if let firstToken, let lastToken {
let start = firstToken.offset let start = firstToken.offset
let length = lastToken.offset + lastToken.length - firstToken.offset let length = lastToken.offset + lastToken.length - firstToken.offset
let byteRange = ByteRange(location: start, length: length) let byteRange = ByteRange(location: start, length: length)

View File

@ -69,7 +69,7 @@ private extension Array where Element == (kind: String, byteRange: ByteRange) {
return last return last
} }
guard let last = last else { guard let last else {
return nil return nil
} }

View File

@ -178,13 +178,9 @@ private extension SourceKittenDictionary {
} }
private func kindsAndOffsets(in declarationKinds: [SwiftDeclarationKind]) -> SourceKittenDictionary? { private func kindsAndOffsets(in declarationKinds: [SwiftDeclarationKind]) -> SourceKittenDictionary? {
guard let offset = offset, guard let offset, let declarationKind, declarationKinds.contains(declarationKind) else {
let declarationKind = declarationKind,
declarationKinds.contains(declarationKind)
else {
return nil return nil
} }
return SourceKittenDictionary(["key.kind": declarationKind.rawValue, "key.offset": Int64(offset.value)]) return SourceKittenDictionary(["key.kind": declarationKind.rawValue, "key.offset": Int64(offset.value)])
} }
} }

View File

@ -173,7 +173,7 @@ struct MultilineFunctionChainsRule: ASTRule, OptInRule, ConfigurationProviderRul
let subcalls = dictionary.subcalls let subcalls = dictionary.subcalls
if subcalls.isEmpty, let parentCallName = parentCallName, parentCallName.starts(with: name) { if subcalls.isEmpty, let parentCallName, parentCallName.starts(with: name) {
return [ByteRange(location: offset, length: length)] return [ByteRange(location: offset, length: length)]
} }

View File

@ -155,7 +155,7 @@ extension NumberSeparatorValidator {
private func isInValidRanges(number: String) -> Bool { private func isInValidRanges(number: String) -> Bool {
let doubleValue = Double(number.replacingOccurrences(of: "_", with: "")) let doubleValue = Double(number.replacingOccurrences(of: "_", with: ""))
if let doubleValue = doubleValue, configuration.excludeRanges.contains(where: { $0.contains(doubleValue) }) { if let doubleValue, configuration.excludeRanges.contains(where: { $0.contains(doubleValue) }) {
return true return true
} }

View File

@ -129,7 +129,7 @@ private struct ArrowViolation {
private extension TokenSyntax { private extension TokenSyntax {
var arrowViolation: ArrowViolation? { var arrowViolation: ArrowViolation? {
guard let previousToken = previousToken, let nextToken = nextToken else { guard let previousToken, let nextToken else {
return nil return nil
} }
@ -156,7 +156,7 @@ private extension TokenSyntax {
end = endPosition end = endPosition
} }
guard let start = start, let end = end else { guard let start, let end else {
return nil return nil
} }

View File

@ -20,7 +20,7 @@ extension SwiftLint {
func run() async throws { func run() async throws {
let allPaths: [String] let allPaths: [String]
if let path = path { if let path {
queuedPrintError(""" queuedPrintError("""
warning: The --path option is deprecated. Pass the path(s) to analyze last to the swiftlint command. warning: The --path option is deprecated. Pass the path(s) to analyze last to the swiftlint command.
""") """)

View File

@ -24,7 +24,7 @@ extension SwiftLint {
func run() async throws { func run() async throws {
let allPaths: [String] let allPaths: [String]
if let path = path { if let path {
queuedPrintError(""" queuedPrintError("""
warning: The --path option is deprecated. Pass the path(s) to lint last to the swiftlint command. warning: The --path option is deprecated. Pass the path(s) to lint last to the swiftlint command.
""") """)

View File

@ -24,7 +24,7 @@ extension SwiftLint {
var ruleID: String? var ruleID: String?
func run() throws { func run() throws {
if let ruleID = ruleID { if let ruleID {
guard let rule = primaryRuleList.list[ruleID] else { guard let rule = primaryRuleList.list[ruleID] else {
throw SwiftLintError.usageError(description: "No rule with identifier: \(ruleID)") throw SwiftLintError.usageError(description: "No rule with identifier: \(ruleID)")
} }
@ -87,7 +87,7 @@ private extension TextTable {
offsetBy: max(minWidth, maxWidth - configurationStartColumn), offsetBy: max(minWidth, maxWidth - configurationStartColumn),
limitedBy: stringWithNoNewlines.endIndex limitedBy: stringWithNoNewlines.endIndex
) )
if let truncatedEndIndex = truncatedEndIndex { if let truncatedEndIndex {
return stringWithNoNewlines[..<truncatedEndIndex] + "..." return stringWithNoNewlines[..<truncatedEndIndex] + "..."
} }
return stringWithNoNewlines return stringWithNoNewlines

View File

@ -96,7 +96,7 @@ struct LintableFilesVisitor {
self.forceExclude = forceExclude self.forceExclude = forceExclude
self.useExcludingByPrefix = useExcludingByPrefix self.useExcludingByPrefix = useExcludingByPrefix
self.cache = cache self.cache = cache
if let compilerInvocations = compilerInvocations { if let compilerInvocations {
self.mode = .analyze(allCompilerInvocations: compilerInvocations) self.mode = .analyze(allCompilerInvocations: compilerInvocations)
// SourceKit had some changes in 5.6 that makes it ~100x more expensive // SourceKit had some changes in 5.6 that makes it ~100x more expensive
// to process files concurrently. By processing files serially, it's // to process files concurrently. By processing files serially, it's

View File

@ -22,14 +22,14 @@ struct Signposts {
description = file description = file
} }
let signpostID = OSSignpostID(log: log) let signpostID = OSSignpostID(log: log)
if let description = description { if let description {
os_signpost(.begin, log: log, name: name, signpostID: signpostID, "%{public}s", description) os_signpost(.begin, log: log, name: name, signpostID: signpostID, "%{public}s", description)
} else { } else {
os_signpost(.begin, log: log, name: name, signpostID: signpostID) os_signpost(.begin, log: log, name: name, signpostID: signpostID)
} }
let result = try body() let result = try body()
if let description = description { if let description {
os_signpost(.end, log: log, name: name, signpostID: signpostID, "%{public}s", description) os_signpost(.end, log: log, name: name, signpostID: signpostID, "%{public}s", description)
} else { } else {
os_signpost(.end, log: log, name: name, signpostID: signpostID) os_signpost(.end, log: log, name: name, signpostID: signpostID)
@ -53,14 +53,14 @@ struct Signposts {
description = file description = file
} }
let signpostID = OSSignpostID(log: log) let signpostID = OSSignpostID(log: log)
if let description = description { if let description {
os_signpost(.begin, log: log, name: name, signpostID: signpostID, "%{public}s", description) os_signpost(.begin, log: log, name: name, signpostID: signpostID, "%{public}s", description)
} else { } else {
os_signpost(.begin, log: log, name: name, signpostID: signpostID) os_signpost(.begin, log: log, name: name, signpostID: signpostID)
} }
let result = try await body() let result = try await body()
if let description = description { if let description {
os_signpost(.end, log: log, name: name, signpostID: signpostID, "%{public}s", description) os_signpost(.end, log: log, name: name, signpostID: signpostID, "%{public}s", description)
} else { } else {
os_signpost(.end, log: log, name: name, signpostID: signpostID) os_signpost(.end, log: log, name: name, signpostID: signpostID)

View File

@ -54,7 +54,7 @@ struct SwiftPMCompilationDB: Codable {
.values .values
.first { $0.sources?.contains(swiftSource) == true } .first { $0.sources?.contains(swiftSource) == true }
guard let command = command, guard let command,
let module = command.module, let module = command.module,
let sources = command.sources, let sources = command.sources,
let arguments = command.args, let arguments = command.args,

View File

@ -147,13 +147,13 @@ private func execute(_ args: [String],
let process = Process() let process = Process()
process.launchPath = "/usr/bin/env" process.launchPath = "/usr/bin/env"
process.arguments = args process.arguments = args
if let directory = directory { if let directory {
process.currentDirectoryPath = directory.path process.currentDirectoryPath = directory.path
} }
let stdoutPipe = Pipe(), stderrPipe = Pipe() let stdoutPipe = Pipe(), stderrPipe = Pipe()
process.standardOutput = stdoutPipe process.standardOutput = stdoutPipe
process.standardError = stderrPipe process.standardError = stderrPipe
if let input = input { if let input {
let stdinPipe = Pipe() let stdinPipe = Pipe()
process.standardInput = stdinPipe.fileHandleForReading process.standardInput = stdinPipe.fileHandleForReading
stdinPipe.fileHandleForWriting.write(input) stdinPipe.fileHandleForWriting.write(input)

View File

@ -11,13 +11,13 @@ class FileNameRuleTests: XCTestCase {
let rule: FileNameRule let rule: FileNameRule
if let excluded = excludedOverride { if let excluded = excludedOverride {
rule = try FileNameRule(configuration: ["excluded": excluded]) rule = try FileNameRule(configuration: ["excluded": excluded])
} else if let prefixPattern = prefixPattern, let suffixPattern = suffixPattern { } else if let prefixPattern, let suffixPattern {
rule = try FileNameRule(configuration: ["prefix_pattern": prefixPattern, "suffix_pattern": suffixPattern]) rule = try FileNameRule(configuration: ["prefix_pattern": prefixPattern, "suffix_pattern": suffixPattern])
} else if let prefixPattern = prefixPattern { } else if let prefixPattern {
rule = try FileNameRule(configuration: ["prefix_pattern": prefixPattern]) rule = try FileNameRule(configuration: ["prefix_pattern": prefixPattern])
} else if let suffixPattern = suffixPattern { } else if let suffixPattern {
rule = try FileNameRule(configuration: ["suffix_pattern": suffixPattern]) rule = try FileNameRule(configuration: ["suffix_pattern": suffixPattern])
} else if let nestedTypeSeparator = nestedTypeSeparator { } else if let nestedTypeSeparator {
rule = try FileNameRule(configuration: ["nested_type_separator": nestedTypeSeparator]) rule = try FileNameRule(configuration: ["nested_type_separator": nestedTypeSeparator])
} else { } else {
rule = FileNameRule() rule = FileNameRule()

View File

@ -206,13 +206,13 @@ class IndentationWidthRuleTests: XCTestCase {
line: UInt = #line line: UInt = #line
) -> Int { ) -> Int {
var configDict: [String: Any] = [:] var configDict: [String: Any] = [:]
if let indentationWidth = indentationWidth { if let indentationWidth {
configDict["indentation_width"] = indentationWidth configDict["indentation_width"] = indentationWidth
} }
if let includeComments = includeComments { if let includeComments {
configDict["include_comments"] = includeComments configDict["include_comments"] = includeComments
} }
if let includeCompilerDirectives = includeCompilerDirectives { if let includeCompilerDirectives {
configDict["include_compiler_directives"] = includeCompilerDirectives configDict["include_compiler_directives"] = includeCompilerDirectives
} }

View File

@ -272,7 +272,7 @@ public func makeConfig(_ ruleConfiguration: Any?, _ identifier: String,
let identifiers: Set<String> = skipDisableCommandTests ? [identifier] let identifiers: Set<String> = skipDisableCommandTests ? [identifier]
: [identifier, superfluousDisableCommandRuleIdentifier] : [identifier, superfluousDisableCommandRuleIdentifier]
if let ruleConfiguration = ruleConfiguration, let ruleType = primaryRuleList.list[identifier] { if let ruleConfiguration, let ruleType = primaryRuleList.list[identifier] {
// The caller has provided a custom configuration for the rule under test // The caller has provided a custom configuration for the rule under test
return (try? ruleType.init(configuration: ruleConfiguration)).flatMap { configuredRule in return (try? ruleType.init(configuration: ruleConfiguration)).flatMap { configuredRule in
let rules = skipDisableCommandTests ? [configuredRule] : [configuredRule, SuperfluousDisableCommandRule()] let rules = skipDisableCommandTests ? [configuredRule] : [configuredRule, SuperfluousDisableCommandRule()]