-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Configuration.swift
262 lines (232 loc) · 9.86 KB
/
Configuration.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
//
// Configuration.swift
// SwiftLint
//
// Created by JP Simard on 2015-08-23.
// Copyright (c) 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
import Yaml
private let fileManager = NSFileManager.defaultManager()
extension Yaml {
var arrayOfStrings: [Swift.String]? {
return array?.flatMap { $0.string } ?? string.map { [$0] }
}
var arrayOfInts: [Swift.Int]? {
return array?.flatMap { $0.int } ?? int.map { [$0] }
}
}
public struct Configuration: Equatable {
public let disabledRules: [String] // disabled_rules
public let included: [String] // included
public let excluded: [String] // excluded
public let reporter: String // reporter (xcode, json, csv, checkstyle)
public let rules: [Rule]
public let useNestedConfigs: Bool // process nested configs, will default to false
public var rootPath: String? // the root path of the lint to search for nested configs
private var configPath: String? // if successfully load from a path
public var reporterFromString: Reporter.Type {
switch reporter {
case XcodeReporter.identifier:
return XcodeReporter.self
case JSONReporter.identifier:
return JSONReporter.self
case CSVReporter.identifier:
return CSVReporter.self
case CheckstyleReporter.identifier:
return CheckstyleReporter.self
default:
fatalError("no reporter with identifier '\(reporter)' available.")
}
}
public init?(disabledRules: [String] = [],
included: [String] = [],
excluded: [String] = [],
reporter: String = "xcode",
rules: [Rule] = Configuration.rulesFromYAML(),
useNestedConfigs: Bool = false) {
self.included = included
self.excluded = excluded
self.reporter = reporter
self.useNestedConfigs = useNestedConfigs
// Validate that all rule identifiers map to a defined rule
let validRuleIdentifiers = Configuration.rulesFromYAML().map {
$0.dynamicType.description.identifier
}
let validDisabledRules = disabledRules.filter({ validRuleIdentifiers.contains($0)})
let invalidRules = disabledRules.filter({ !validRuleIdentifiers.contains($0) })
if !invalidRules.isEmpty {
for invalidRule in invalidRules {
queuedPrintError("config error: '\(invalidRule)' is not a valid rule identifier")
}
let listOfValidRuleIdentifiers = validRuleIdentifiers.joinWithSeparator("\n")
queuedPrintError("Valid rule identifiers:\n\(listOfValidRuleIdentifiers)")
}
// Validate that rule identifiers aren't listed multiple times
let ruleSet = Set(validDisabledRules)
if ruleSet.count != validDisabledRules.count {
let duplicateRules = validDisabledRules.reduce([String: Int]()) { (var accu, element) in
accu[element] = accu[element]?.successor() ?? 1
return accu
}.filter { $0.1 > 1 }
queuedPrintError(duplicateRules.map { rule in
"config error: '\(rule.0)' is listed \(rule.1) times"
}.joinWithSeparator("\n"))
return nil
}
self.disabledRules = validDisabledRules
self.rules = rules.filter {
!validDisabledRules.contains($0.dynamicType.description.identifier)
}
}
public init?(yaml: String) {
guard let yamlConfig = Configuration.loadYaml(yaml) else {
return nil
}
self.init(yamlConfig: yamlConfig)
}
private init?(yamlConfig: Yaml) {
self.init(
disabledRules: yamlConfig["disabled_rules"].arrayOfStrings ?? [],
included: yamlConfig["included"].arrayOfStrings ?? [],
excluded: yamlConfig["excluded"].arrayOfStrings ?? [],
reporter: yamlConfig["reporter"].string ?? XcodeReporter.identifier,
rules: Configuration.rulesFromYAML(yamlConfig),
useNestedConfigs: yamlConfig["use_nested_configs"].bool ?? false
)
}
private static func loadYaml(yaml: String) -> Yaml? {
let yamlResult = Yaml.load(yaml)
if let yamlConfig = yamlResult.value {
return yamlConfig
}
if let error = yamlResult.error {
queuedPrint(error)
}
return nil
}
public init(path: String = ".swiftlint.yml", optional: Bool = true, silent: Bool = false) {
let fullPath = (path as NSString).absolutePathRepresentation()
let failIfRequired = {
if !optional { fatalError("Could not read configuration file at path '\(fullPath)'") }
}
if path.isEmpty || !NSFileManager.defaultManager().fileExistsAtPath(fullPath) {
failIfRequired()
self.init()!
return
}
do {
let yamlContents = try NSString(contentsOfFile: fullPath,
encoding: NSUTF8StringEncoding) as String
if let yamlConfig = Configuration.loadYaml(yamlContents) {
if !silent {
queuedPrintError("Loading configuration from '\(path)'")
}
self.init(yamlConfig: yamlConfig)!
configPath = fullPath
return
} else {
failIfRequired()
}
} catch {
failIfRequired()
}
self.init()!
}
public static func rulesFromYAML(yaml: Yaml? = nil) -> [Rule] {
return [
ClosingBraceRule(),
ColonRule(),
CommaRule(),
ControlStatementRule(),
ForceCastRule(),
ForceTryRule(),
LeadingWhitespaceRule(),
LegacyConstructorRule(),
NestingRule(),
OpeningBraceRule(),
OperatorFunctionWhitespaceRule(),
ReturnArrowWhitespaceRule(),
StatementPositionRule(),
TodoRule(),
TrailingNewlineRule(),
TrailingSemicolonRule(),
TrailingWhitespaceRule(),
TypeNameRule(),
ValidDocsRule(),
VariableNameRule(),
] + parameterRulesFromYAML(yaml)
}
private static func parameterRulesFromYAML(yaml: Yaml? = nil) -> [Rule] {
let intParams: (Rule.Type) -> [RuleParameter<Int>]? = {
(yaml?[.String($0.description.identifier)].arrayOfInts).map(ruleParametersFromArray)
}
// swiftlint:disable line_length
return [
intParams(FileLengthRule).map(FileLengthRule.init) ?? FileLengthRule(),
intParams(FunctionBodyLengthRule).map(FunctionBodyLengthRule.init) ?? FunctionBodyLengthRule(),
intParams(LineLengthRule).map(LineLengthRule.init) ?? LineLengthRule(),
intParams(TypeBodyLengthRule).map(TypeBodyLengthRule.init) ?? TypeBodyLengthRule(),
intParams(VariableNameMaxLengthRule).map(VariableNameMaxLengthRule.init) ?? VariableNameMaxLengthRule(),
intParams(VariableNameMinLengthRule).map(VariableNameMinLengthRule.init) ?? VariableNameMinLengthRule(),
]
// swiftlint:enable line_length
}
private static func ruleParametersFromArray<T>(array: [T]) -> [RuleParameter<T>] {
return zip([.Warning, .Error], array).map(RuleParameter.init)
}
public func lintablePathsForPath(path: String,
fileManager: NSFileManager = fileManager) -> [String] {
let pathsForPath = included.isEmpty ? fileManager.filesToLintAtPath(path) : []
let excludedPaths = excluded.flatMap(fileManager.filesToLintAtPath)
let includedPaths = included.flatMap(fileManager.filesToLintAtPath)
return (pathsForPath + includedPaths).filter({ !excludedPaths.contains($0) })
}
public func lintableFilesForPath(path: String) -> [File] {
let allPaths = self.lintablePathsForPath(path)
return allPaths.flatMap { File(path: $0) }
}
public func configForFile(file: File) -> Configuration {
if useNestedConfigs,
let containingDir = (file.path as NSString?)?.stringByDeletingLastPathComponent {
return configForPath(containingDir)
}
return self
}
}
// MARK: - Nested Configurations Extension
public extension Configuration {
func configForPath(path: String) -> Configuration {
let path = path as NSString
let configSearchPath = path.stringByAppendingPathComponent(".swiftlint.yml")
// If a config exists and it isn't us, load and merge the configs
if configSearchPath != configPath &&
NSFileManager.defaultManager().fileExistsAtPath(configSearchPath) {
return merge(Configuration(path: configSearchPath, optional: false, silent: true))
}
// If we are not at the root path, continue down the tree
if path != rootPath {
return configForPath(path.stringByDeletingLastPathComponent)
}
// If nothing else, return self
return self
}
// Currently merge simply overrides the current configuration with the new configuration.
// This requires that all config files be fully specified. In the future this will be changed
// to do a more intelligent merge allowing for partial nested configs.
func merge(config: Configuration) -> Configuration {
return config
}
}
// Mark - == Implementation
public func == (lhs: Configuration, rhs: Configuration) -> Bool {
return (lhs.disabledRules == rhs.disabledRules) &&
(lhs.excluded == rhs.excluded) &&
(lhs.included == rhs.included) &&
(lhs.reporter == rhs.reporter) &&
(lhs.useNestedConfigs == rhs.useNestedConfigs) &&
(lhs.configPath == rhs.configPath) &&
(lhs.rootPath == lhs.rootPath) &&
(lhs.rules == rhs.rules)
}