mirror of
https://github.com/realm/SwiftLint.git
synced 2026-06-06 20:18:40 +00:00
Over the years, SwiftLintFramework had become a fairly massive monolith, containing over 400 source files with both core infrastructure and rules. Architecturally, the rules should rely on the core infrastructure but not the other way around. There are two exceptions to this: `custom_rules` and `superfluous_disable_command` which need special integration with the linter infrastructure. Now the time has come to formalize this architecture and one way to do that is to move the core SwiftLint functionality out of SwiftLintFramework and into a new SwiftLintCore module that the rules can depend on. Beyond enforcing architectural patterns, this also has the advantage of speeding up incremental compilation by skipping rebuilding the core functionality when iterating on rules. Because the core functionality is always useful when building rules, I'm opting to import SwiftLintCore in SwiftLintFramework as `@_exported` so that it's implicitly available to all files in SwiftLintFramework without needing to import it directly. In a follow-up I'll also split the built-in rules and the extra rules into their own modules. More modularization is possible from there, but not planned. The bulk of this PR just moves files from `Source/SwiftLintFramework/*` to `Source/SwiftLintCore/*`. There are some other changes that can't be split up into their own PRs: * Change jazzy to document the SwiftLintCore module instead of SwiftLintFramework. * Change imports in unit tests to reflect where code was moved to. * Update `sourcery` make rule to reflect where code was moved to. * Create a new `coreRules` array and register those rules with the registry. This allows the `custom_rules` and `superfluous_disable_command` rule implementations to remain internal to the SwiftLintCore module, preventing more implementation details from leaking across architectural layers. * Move `RuleRegistry.registerAllRulesOnce()` out of the type declaration and up one level so it can access rules defined downstream from SwiftLintCore.
140 lines
5.6 KiB
Swift
140 lines
5.6 KiB
Swift
import Foundation
|
|
import SourceKittenFramework
|
|
|
|
/// A rule configuration used for defining custom rules in yaml.
|
|
public struct RegexConfiguration: SeverityBasedRuleConfiguration, Hashable, CacheDescriptionProvider {
|
|
/// The identifier for this custom rule.
|
|
public let identifier: String
|
|
/// The name for this custom rule.
|
|
public var name: String?
|
|
/// The message to be presented when producing violations.
|
|
public var message = "Regex matched"
|
|
/// The regular expression to apply to trigger violations for this custom rule.
|
|
public var regex: NSRegularExpression!
|
|
/// Regular expressions to include when matching the file path.
|
|
public var included: [NSRegularExpression] = []
|
|
/// Regular expressions to exclude when matching the file path.
|
|
public var excluded: [NSRegularExpression] = []
|
|
/// The syntax kinds to exclude from matches. If the regex matched syntax kinds from this list, it would
|
|
/// be ignored and not count as a rule violation.
|
|
public var excludedMatchKinds = Set<SyntaxKind>()
|
|
public var severityConfiguration = SeverityConfiguration(.warning)
|
|
/// The index of the regex capture group to match.
|
|
public var captureGroup: Int = 0
|
|
|
|
public var consoleDescription: String {
|
|
return "\(severity.rawValue): \(regex.pattern)"
|
|
}
|
|
|
|
public var cacheDescription: String {
|
|
let jsonObject: [String] = [
|
|
identifier,
|
|
name ?? "",
|
|
message,
|
|
regex.pattern,
|
|
included.map(\.pattern).joined(separator: ","),
|
|
excluded.map(\.pattern).joined(separator: ","),
|
|
SyntaxKind.allKinds.subtracting(excludedMatchKinds)
|
|
.map({ $0.rawValue }).sorted(by: <).joined(separator: ","),
|
|
severityConfiguration.consoleDescription
|
|
]
|
|
if let jsonData = try? JSONSerialization.data(withJSONObject: jsonObject),
|
|
let jsonString = String(data: jsonData, encoding: .utf8) {
|
|
return jsonString
|
|
}
|
|
queuedFatalError("Could not serialize regex configuration for cache")
|
|
}
|
|
|
|
/// The `RuleDescription` for the custom rule defined here.
|
|
public var description: RuleDescription {
|
|
return RuleDescription(identifier: identifier, name: name ?? identifier,
|
|
description: "", kind: .style)
|
|
}
|
|
|
|
/// Create a `RegexConfiguration` with the specified identifier, with other properties to be set later.
|
|
///
|
|
/// - parameter identifier: The rule identifier to use.
|
|
public init(identifier: String) {
|
|
self.identifier = identifier
|
|
}
|
|
|
|
public mutating func apply(configuration: Any) throws {
|
|
guard let configurationDict = configuration as? [String: Any],
|
|
let regexString = configurationDict["regex"] as? String else {
|
|
throw ConfigurationError.unknownConfiguration
|
|
}
|
|
|
|
regex = try .cached(pattern: regexString)
|
|
|
|
if let includedString = configurationDict["included"] as? String {
|
|
included = [try .cached(pattern: includedString)]
|
|
} else if let includedArray = configurationDict["included"] as? [String] {
|
|
included = try includedArray.map { pattern in
|
|
try .cached(pattern: pattern)
|
|
}
|
|
}
|
|
|
|
if let excludedString = configurationDict["excluded"] as? String {
|
|
excluded = [try .cached(pattern: excludedString)]
|
|
} else if let excludedArray = configurationDict["excluded"] as? [String] {
|
|
excluded = try excludedArray.map { pattern in
|
|
try .cached(pattern: pattern)
|
|
}
|
|
}
|
|
|
|
if let name = configurationDict["name"] as? String {
|
|
self.name = name
|
|
}
|
|
if let message = configurationDict["message"] as? String {
|
|
self.message = message
|
|
}
|
|
if let severityString = configurationDict["severity"] as? String {
|
|
try severityConfiguration.apply(configuration: severityString)
|
|
}
|
|
if let captureGroup = configurationDict["capture_group"] as? Int {
|
|
guard (0 ... regex.numberOfCaptureGroups).contains(captureGroup) else {
|
|
throw ConfigurationError.unknownConfiguration
|
|
}
|
|
self.captureGroup = captureGroup
|
|
}
|
|
|
|
self.excludedMatchKinds = try self.excludedMatchKinds(from: configurationDict)
|
|
}
|
|
|
|
public func hash(into hasher: inout Hasher) {
|
|
hasher.combine(identifier)
|
|
}
|
|
|
|
func shouldValidate(filePath: String) -> Bool {
|
|
let pathRange = filePath.fullNSRange
|
|
let isIncluded = included.isEmpty || included.contains { regex in
|
|
regex.firstMatch(in: filePath, range: pathRange) != nil
|
|
}
|
|
|
|
guard isIncluded else {
|
|
return false
|
|
}
|
|
|
|
return excluded.allSatisfy { regex in
|
|
regex.firstMatch(in: filePath, range: pathRange) == nil
|
|
}
|
|
}
|
|
|
|
private func excludedMatchKinds(from configurationDict: [String: Any]) throws -> Set<SyntaxKind> {
|
|
let matchKinds = [String].array(of: configurationDict["match_kinds"])
|
|
let excludedMatchKinds = [String].array(of: configurationDict["excluded_match_kinds"])
|
|
|
|
switch (matchKinds, excludedMatchKinds) {
|
|
case (.some(let matchKinds), nil):
|
|
let includedKinds = Set(try matchKinds.map({ try SyntaxKind(shortName: $0) }))
|
|
return SyntaxKind.allKinds.subtracting(includedKinds)
|
|
case (nil, .some(let excludedMatchKinds)):
|
|
return Set(try excludedMatchKinds.map({ try SyntaxKind(shortName: $0) }))
|
|
case (nil, nil):
|
|
return .init()
|
|
case (.some, .some):
|
|
throw ConfigurationError.ambiguousMatchKindParameters
|
|
}
|
|
}
|
|
}
|