forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSortedImportsRule.swift
More file actions
54 lines (46 loc) · 1.9 KB
/
SortedImportsRule.swift
File metadata and controls
54 lines (46 loc) · 1.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
//
// SortedImportsRule.swift
// SwiftLint
//
// Created by Scott Berrevoets on 12/15/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct SortedImportsRule: ConfigurationProviderRule, OptInRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "sorted_imports",
name: "Sorted Imports",
description: "Imports should be sorted.",
nonTriggeringExamples: [
"import AAA\nimport BBB\nimport CCC\nimport DDD"
],
triggeringExamples: [
"import AAA\nimport ZZZ\nimport ↓BBB\nimport CCC"
]
)
public func validate(file: File) -> [StyleViolation] {
let importRanges = file.match(pattern: "import\\s+\\w+", with: [.keyword, .identifier])
let contents = file.contents.bridge()
let importLength = 6
let modulesAndOffsets: [(String, Int)] = importRanges.map { range in
let moduleRange = NSRange(location: range.location + importLength,
length: range.length - importLength)
let moduleName = contents.substring(with: moduleRange)
.trimmingCharacters(in: .whitespacesAndNewlines)
let offset = NSMaxRange(range) - moduleName.bridge().length
return (moduleName, offset)
}
let modulePairs = zip(modulesAndOffsets, modulesAndOffsets.dropFirst())
let violatingOffsets = modulePairs.flatMap { previous, current in
return current < previous ? current.1 : nil
}
return violatingOffsets.map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0))
}
}
}