-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathConfiguration+Parsing.swift
More file actions
305 lines (276 loc) · 12.9 KB
/
Configuration+Parsing.swift
File metadata and controls
305 lines (276 loc) · 12.9 KB
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
extension Configuration {
// MARK: - Subtypes
internal enum Key: String, CaseIterable {
case cachePath = "cache_path"
case disabledRules = "disabled_rules"
case enabledRules = "enabled_rules" // deprecated in favor of optInRules
case excluded = "excluded"
case included = "included"
case optInRules = "opt_in_rules"
case reporter = "reporter"
case swiftlintVersion = "swiftlint_version"
case warningThreshold = "warning_threshold"
case onlyRules = "only_rules"
case indentation = "indentation"
case analyzerRules = "analyzer_rules"
case allowZeroLintableFiles = "allow_zero_lintable_files"
case strict = "strict"
case lenient = "lenient"
case baseline = "baseline"
case writeBaseline = "write_baseline"
case checkForUpdates = "check_for_updates"
case childConfig = "child_config"
case parentConfig = "parent_config"
case remoteConfigTimeout = "remote_timeout"
case remoteConfigTimeoutIfCached = "remote_timeout_if_cached"
}
// MARK: - Properties
private static let validGlobalKeys: Set<String> = Set(Key.allCases.map(\.rawValue))
// MARK: - Initializers
/// Creates a Configuration value based on the specified parameters.
///
/// - parameter parentConfiguration: The parent configuration, if any.
/// - parameter dict: The untyped dictionary to serve as the input for this typed configuration.
/// Typically generated from a YAML-formatted file.
/// - parameter ruleList: The list of rules to be available to this configuration.
/// - parameter enableAllRules: Whether all rules from `ruleList` should be enabled, regardless of the
/// settings in `dict`.
/// - parameter cachePath: The location of the persisted cache on disk.
public init(
parentConfiguration: Configuration? = nil,
dict: [String: Any],
ruleList: RuleList = RuleRegistry.shared.list,
enableAllRules: Bool = false,
onlyRule: [String] = [],
cachePath: String? = nil
) throws {
func defaultStringArray(_ object: Any?) -> [String] { [String].array(of: object) ?? [] }
// Use either the new 'opt_in_rules' or fallback to the deprecated 'enabled_rules'
let optInRules = defaultStringArray(dict[Key.optInRules.rawValue] ?? dict[Key.enabledRules.rawValue])
let disabledRules = defaultStringArray(dict[Key.disabledRules.rawValue])
let onlyRules = defaultStringArray(dict[Key.onlyRules.rawValue])
let analyzerRules = defaultStringArray(dict[Key.analyzerRules.rawValue])
Self.warnAboutInvalidKeys(configurationDictionary: dict, ruleList: ruleList)
Self.warnAboutDeprecations(
configurationDictionary: dict, disabledRules: disabledRules,
optInRules: optInRules, onlyRules: onlyRules, ruleList: ruleList
)
Self.warnAboutMisplacedAnalyzerRules(optInRules: optInRules, ruleList: ruleList)
let allRulesWrapped: [ConfigurationRuleWrapper]
do {
allRulesWrapped = try ruleList.allRulesWrapped(configurationDict: dict)
} catch let RuleListError.duplicatedConfigurations(ruleType) {
let aliases = ruleType.description.deprecatedAliases.map { "'\($0)'" }.joined(separator: ", ")
let identifier = ruleType.identifier
throw Issue.genericWarning(
"Multiple configurations found for '\(identifier)'. Check for any aliases: \(aliases)."
)
}
let rulesMode = try RulesMode(
enableAllRules: enableAllRules,
onlyRule: onlyRule,
onlyRules: onlyRules,
optInRules: optInRules,
disabledRules: disabledRules,
analyzerRules: analyzerRules
)
if onlyRule.isEmpty {
Self.validateConfiguredRulesAreEnabled(
parentConfiguration: parentConfiguration,
configurationDictionary: dict,
ruleList: ruleList,
rulesMode: rulesMode,
customRuleIdentifiers: Set(allRulesWrapped.customRules?.customRuleIdentifiers ?? [])
)
}
self.init(
rulesMode: rulesMode,
allRulesWrapped: allRulesWrapped,
ruleList: ruleList,
includedPaths: defaultStringArray(dict[Key.included.rawValue]),
excludedPaths: defaultStringArray(dict[Key.excluded.rawValue]),
indentation: Self.getIndentationLogIfInvalid(from: dict),
warningThreshold: dict[Key.warningThreshold.rawValue] as? Int,
reporter: dict[Key.reporter.rawValue] as? String ?? XcodeReporter.identifier,
cachePath: cachePath ?? dict[Key.cachePath.rawValue] as? String,
pinnedVersion: dict[Key.swiftlintVersion.rawValue].map { ($0 as? String) ?? String(describing: $0) },
allowZeroLintableFiles: dict[Key.allowZeroLintableFiles.rawValue] as? Bool ?? false,
strict: dict[Key.strict.rawValue] as? Bool ?? false,
lenient: dict[Key.lenient.rawValue] as? Bool ?? false,
baseline: dict[Key.baseline.rawValue] as? String,
writeBaseline: dict[Key.writeBaseline.rawValue] as? String,
checkForUpdates: dict[Key.checkForUpdates.rawValue] as? Bool ?? false
)
}
// MARK: - Methods: Validations
private static func validKeys(ruleList: RuleList) -> Set<String> {
validGlobalKeys.union(ruleList.allValidIdentifiers())
}
private static func getIndentationLogIfInvalid(from dict: [String: Any]) -> IndentationStyle {
if let rawIndentation = dict[Key.indentation.rawValue] {
if let indentationStyle = Self.IndentationStyle(rawIndentation) {
return indentationStyle
}
Issue.invalidConfiguration(ruleID: Key.indentation.rawValue).print()
return .default
}
return .default
}
private static func warnAboutDeprecations(
configurationDictionary dict: [String: Any],
disabledRules: [String] = [],
optInRules: [String] = [],
onlyRules: [String] = [],
ruleList: RuleList
) {
// Deprecation warning for "enabled_rules"
if dict[Key.enabledRules.rawValue] != nil {
Issue.renamedIdentifier(old: Key.enabledRules.rawValue, new: Key.optInRules.rawValue).print()
}
// Deprecation warning for rules
let deprecatedRulesIdentifiers = ruleList.list.flatMap { identifier, rule -> [(String, String)] in
rule.description.deprecatedAliases.map { ($0, identifier) }
}
let userProvidedRuleIDs = Set(disabledRules + optInRules + onlyRules)
let deprecatedUsages = deprecatedRulesIdentifiers.filter { deprecatedIdentifier, _ in
dict[deprecatedIdentifier] != nil || userProvidedRuleIDs.contains(deprecatedIdentifier)
}
for (deprecatedIdentifier, identifier) in deprecatedUsages {
Issue.renamedIdentifier(old: deprecatedIdentifier, new: identifier).print()
}
}
private static func warnAboutInvalidKeys(configurationDictionary dict: [String: Any], ruleList: RuleList) {
// Log an error when supplying invalid keys in the configuration dictionary
let invalidKeys = Set(dict.keys).subtracting(validKeys(ruleList: ruleList))
if invalidKeys.isNotEmpty {
Issue.invalidRuleIDs(invalidKeys).print()
}
}
private static func validateConfiguredRulesAreEnabled(
parentConfiguration: Configuration?,
configurationDictionary dict: [String: Any],
ruleList: RuleList,
rulesMode: RulesMode,
customRuleIdentifiers: Set<String>
) {
for key in dict.keys where !validGlobalKeys.contains(key) {
guard let identifier = ruleList.identifier(for: key),
let ruleType = ruleList.list[identifier] else {
continue
}
switch rulesMode {
case .allCommandLine, .onlyCommandLine:
return
case .onlyConfiguration(let onlyRules):
let issue = validateConfiguredRuleIsEnabled(
onlyRules: onlyRules,
ruleType: ruleType,
customRuleIdentifiers: customRuleIdentifiers
)
issue?.print()
case let .defaultConfiguration(disabled: disabledRules, optIn: optInRules):
let issue = validateConfiguredRuleIsEnabled(
parentConfiguration: parentConfiguration,
disabledRules: disabledRules,
optInRules: optInRules,
ruleType: ruleType
)
issue?.print()
}
}
}
static func validateConfiguredRuleIsEnabled(
parentConfiguration: Configuration?,
disabledRules: Set<String>,
optInRules: Set<String>,
ruleType: any Rule.Type
) -> Issue? {
var enabledInParentRules: Set<String> = []
var disabledInParentRules: Set<String> = []
var allEnabledRules: Set<String> = []
if case .onlyConfiguration(let onlyRules) = parentConfiguration?.rulesMode {
enabledInParentRules = onlyRules
} else if case let .defaultConfiguration(
parentDisabledRules, parentOptInRules
) = parentConfiguration?.rulesMode {
enabledInParentRules = parentOptInRules
disabledInParentRules = parentDisabledRules
}
allEnabledRules = enabledInParentRules
.subtracting(disabledInParentRules)
.union(optInRules)
.subtracting(disabledRules)
return validateConfiguredRuleIsEnabled(
parentConfiguration: parentConfiguration,
enabledInParentRules: enabledInParentRules,
disabledInParentRules: disabledInParentRules,
disabledRules: disabledRules,
optInRules: optInRules,
allEnabledRules: allEnabledRules,
ruleType: ruleType
)
}
static func validateConfiguredRuleIsEnabled(
onlyRules: Set<String>,
ruleType: any Rule.Type,
customRuleIdentifiers: Set<String> = []
) -> Issue? {
if onlyRules.isDisjoint(with: ruleType.description.allIdentifiers) {
if ruleType is CustomRules.Type, !customRuleIdentifiers.isDisjoint(with: onlyRules) {
return nil
}
return Issue.ruleNotPresentInOnlyRules(ruleID: ruleType.identifier)
}
return nil
}
// swiftlint:disable:next function_parameter_count
static func validateConfiguredRuleIsEnabled(
parentConfiguration: Configuration?,
enabledInParentRules: Set<String>,
disabledInParentRules: Set<String>,
disabledRules: Set<String>,
optInRules: Set<String>,
allEnabledRules: Set<String>,
ruleType: any Rule.Type
) -> Issue? {
if case .allCommandLine = parentConfiguration?.rulesMode {
if disabledRules.contains(ruleType.identifier) {
return Issue.ruleDisabledInDisabledRules(ruleID: ruleType.identifier)
}
return nil
}
let allIdentifiers = ruleType.description.allIdentifiers
if allEnabledRules.isDisjoint(with: allIdentifiers) {
if !disabledRules.isDisjoint(with: allIdentifiers) {
return Issue.ruleDisabledInDisabledRules(ruleID: ruleType.identifier)
}
if !disabledInParentRules.isDisjoint(with: allIdentifiers) {
return Issue.ruleDisabledInParentConfiguration(ruleID: ruleType.identifier)
}
if ruleType is any OptInRule.Type {
if enabledInParentRules.union(optInRules).isDisjoint(with: allIdentifiers) {
return Issue.ruleNotEnabledInOptInRules(ruleID: ruleType.identifier)
}
} else if case .onlyConfiguration(let enabledInParentRules) = parentConfiguration?.rulesMode,
enabledInParentRules.isDisjoint(with: allIdentifiers) {
return Issue.ruleNotEnabledInParentOnlyRules(ruleID: ruleType.identifier)
}
}
return nil
}
private static func warnAboutMisplacedAnalyzerRules(optInRules: [String], ruleList: RuleList) {
let analyzerRules = ruleList.list
.filter { $0.value.self is any AnalyzerRule.Type }
.map(\.key)
Set(analyzerRules).intersection(optInRules)
.sorted()
.forEach {
Issue.genericWarning(
"""
'\($0)' should be listed in the 'analyzer_rules' configuration section \
for more clarity as it is only run by 'swiftlint analyze'.
"""
).print()
}
}
}