forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCustomRules.swift
86 lines (67 loc) · 2.78 KB
/
CustomRules.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
//
// CustomRules.swift
// SwiftLint
//
// Created by Scott Hoyt on 1/21/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
// MARK: - CustomRulesConfiguration
public struct CustomRulesConfiguration: RuleConfiguration, Equatable {
public var consoleDescription: String { return "user-defined" }
public var customRuleConfigurations = [RegexConfiguration]()
public init() {}
public mutating func applyConfiguration(configuration: AnyObject) throws {
guard let configurationDict = configuration as? [String: AnyObject] else {
throw ConfigurationError.UnknownConfiguration
}
for (key, value) in configurationDict {
var ruleConfiguration = RegexConfiguration(identifier: key)
try ruleConfiguration.applyConfiguration(value)
customRuleConfigurations.append(ruleConfiguration)
}
}
}
public func == (lhs: CustomRulesConfiguration, rhs: CustomRulesConfiguration) -> Bool {
return lhs.customRuleConfigurations == rhs.customRuleConfigurations
}
// MARK: - CustomRules
public struct CustomRules: Rule, ConfigurationProviderRule {
public static let description = RuleDescription(
identifier: "custom_rules",
name: "Custom Rules",
description: "Create custom rules by providing a regex string. " +
"Optionally specify what syntax kinds to match against, the severity " +
"level, and what message to display.")
public var configuration = CustomRulesConfiguration()
public init() {}
public func validateFile(file: File) -> [StyleViolation] {
var configurations = configuration.customRuleConfigurations
if configurations.isEmpty {
return []
}
if let path = file.path {
configurations = configurations.filter { config in
let pattern = config.included.pattern
if pattern.isEmpty { return true }
let pathMatch = config.included.matchesInString(path, options: [],
range: NSRange(location: 0, length: (path as NSString).length))
return !pathMatch.isEmpty
}
}
return configurations.flatMap {
self.validate(file, configuration: $0)
}
}
private func validate(file: File, configuration: RegexConfiguration) -> [StyleViolation] {
return file.matchPattern(configuration.regex).filter {
!configuration.matchKinds.intersect($0.1).isEmpty
}.map {
StyleViolation(ruleDescription: configuration.description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.0.location),
reason: configuration.message)
}
}
}