forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrailingNewlineRule.swift
76 lines (68 loc) · 2.28 KB
/
TrailingNewlineRule.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
//
// TrailingNewlineRule.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import SourceKittenFramework
extension String {
private func countOfTrailingCharactersInSet(characterSet: NSCharacterSet) -> Int {
var count = 0
for char in utf16.lazy.reverse() {
if !characterSet.characterIsMember(char) {
break
}
count++
}
return count
}
private func trailingNewlineCount() -> Int? {
return countOfTrailingCharactersInSet(NSCharacterSet.newlineCharacterSet())
}
}
public struct TrailingNewlineRule: CorrectableRule {
public init() {}
public static let description = RuleDescription(
identifier: "trailing_newline",
name: "Trailing Newline",
description: "Files should have a single trailing newline.",
nonTriggeringExamples: [
"let a = 0\n"
],
triggeringExamples: [
"let a = 0",
"let a = 0\n\n"
],
corrections: [
"let a = 0": "let a = 0\n",
"let b = 0\n\n": "let b = 0\n",
"let c = 0\n\n\n\n": "let c = 0\n"
]
)
public func validateFile(file: File) -> [StyleViolation] {
if file.contents.trailingNewlineCount() == 1 {
return []
}
return [StyleViolation(ruleDescription: self.dynamicType.description,
location: Location(file: file.path, line: max(file.lines.count, 1)))]
}
public func correctFile(file: File) -> [Correction] {
guard let count = file.contents.trailingNewlineCount() where count != 1 else {
return []
}
let region = file.regions().filter {
$0.contains(Location(file: file.path, line: max(file.lines.count, 1)))
}.first
if region?.isRuleDisabled(self) == true {
return []
}
if count < 1 {
file.append("\n")
} else {
file.write(file.contents.substringToIndex(file.contents.endIndex.advancedBy(1 - count)))
}
let location = Location(file: file.path, line: max(file.lines.count, 1))
return [Correction(ruleDescription: self.dynamicType.description, location: location)]
}
}