forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrailingSemicolonRule.swift
77 lines (69 loc) · 2.74 KB
/
TrailingSemicolonRule.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
//
// TrailingSemiColonRule.swift
// SwiftLint
//
// Created by JP Simard on 11/17/15.
// Copyright © 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
extension File {
fileprivate func violatingTrailingSemicolonRanges() -> [NSRange] {
return match(pattern: "(;+([^\\S\\n]?)*)+;?$",
excludingSyntaxKinds: SyntaxKind.commentAndStringKinds())
}
}
public struct TrailingSemicolonRule: CorrectableRule, ConfigurationProviderRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "trailing_semicolon",
name: "Trailing Semicolon",
description: "Lines should not have trailing semicolons.",
nonTriggeringExamples: [ "let a = 0\n" ],
triggeringExamples: [
"let a = 0↓;\n",
"let a = 0↓;\nlet b = 1\n",
"let a = 0↓;;\n",
"let a = 0↓; ;;\n",
"let a = 0↓; ; ;\n"
],
corrections: [
"let a = 0↓;\n": "let a = 0\n",
"let a = 0↓;\nlet b = 1\n": "let a = 0\nlet b = 1\n",
"let a = 0↓;;\n": "let a = 0\n",
"let a = 0↓; ;;\n": "let a = 0\n",
"let a = 0↓; ; ;\n": "let a = 0\n"
]
)
public func validate(file: File) -> [StyleViolation] {
return file.violatingTrailingSemicolonRanges().map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.location))
}
}
public func correct(file: File) -> [Correction] {
let violatingRanges = file.ruleEnabled(violatingRanges: file.violatingTrailingSemicolonRanges(), for: self)
let adjustedRanges = violatingRanges.reduce([NSRange]()) { adjustedRanges, element in
let adjustedLocation = element.location - adjustedRanges.count
let adjustedRange = NSRange(location: adjustedLocation, length: element.length)
return adjustedRanges + [adjustedRange]
}
if adjustedRanges.isEmpty {
return []
}
var correctedContents = file.contents
for range in adjustedRanges {
if let indexRange = correctedContents.nsrangeToIndexRange(range) {
correctedContents = correctedContents
.replacingCharacters(in: indexRange, with: "")
}
}
file.write(correctedContents)
return adjustedRanges.map {
Correction(ruleDescription: type(of: self).description,
location: Location(file: file, characterOffset: $0.location))
}
}
}