forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTrailingWhitespaceRule.swift
62 lines (56 loc) · 2.16 KB
/
TrailingWhitespaceRule.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
//
// TrailingWhitespaceRule.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 2015 Realm. All rights reserved.
//
import SourceKittenFramework
public struct TrailingWhitespaceRule: CorrectableRule {
public init() {}
public static let description = RuleDescription(
identifier: "trailing_whitespace",
name: "Trailing Whitespace",
description: "Lines should not have trailing whitespace.",
nonTriggeringExamples: [ "//\n" ],
triggeringExamples: [ "// \n" ],
corrections: [ "// \n": "//\n" ]
)
public func validateFile(file: File) -> [StyleViolation] {
return file.lines.filter {
$0.content.hasTrailingWhitespace()
}.map {
StyleViolation(ruleDescription: self.dynamicType.description,
location: Location(file: file.path, line: $0.index))
}
}
public func correctFile(file: File) -> [Correction] {
let whitespaceCharacterSet = NSCharacterSet.whitespaceCharacterSet()
var correctedLines = [String]()
var corrections = [Correction]()
let fileRegions = file.regions()
for line in file.lines {
let correctedLine = (line.content as NSString)
.stringByTrimmingTrailingCharactersInSet(whitespaceCharacterSet)
let region = fileRegions.filter {
$0.contains(Location(file: file.path, line: line.index, character: 0))
}.first
if region?.isRuleDisabled(self) == true {
correctedLines.append(line.content)
continue
}
if line.content != correctedLine {
let description = self.dynamicType.description
let location = Location(file: file.path, line: line.index)
corrections.append(Correction(ruleDescription: description, location: location))
}
correctedLines.append(correctedLine)
}
if !corrections.isEmpty {
// join and re-add trailing newline
file.write(correctedLines.joinWithSeparator("\n") + "\n")
return corrections
}
return []
}
}