Improve trailing newline performance

This sidesteps the previous method of reversing the entire string from
every file by only checking the minimum number of trailing characters
for each file.
This commit is contained in:
Keith Smiley
2015-08-14 20:21:19 -07:00
parent 047922610b
commit 65f6715915
2 changed files with 12 additions and 8 deletions
@@ -14,16 +14,20 @@ public struct TrailingNewlineRule: Rule {
public let identifier = "trailing_newline"
public func validateFile(file: File) -> [StyleViolation] {
let countOfTrailingNewlines = file.contents.countOfTailingCharactersInSet(
NSCharacterSet.newlineCharacterSet()
)
if countOfTrailingNewlines != 1 {
let string = file.contents
let start = advance(string.endIndex, -2, string.startIndex)
let range = Range(start: start, end: string.endIndex)
let substring = string[range].utf16
let newLineSet = NSCharacterSet.newlineCharacterSet()
let slices = split(substring, allowEmptySlices: true) { !newLineSet.characterIsMember($0) }
if let slice = slices.last where count(slice) != 1 {
return [StyleViolation(type: .TrailingNewline,
location: Location(file: file.path, line: file.contents.lines().count + 1),
severity: .Medium,
reason: "File should have a single trailing newline: " +
"currently has \(countOfTrailingNewlines)")]
reason: "File should have a single trailing newline")]
}
return []
}
@@ -34,11 +34,11 @@ class StringRuleTests: XCTestCase {
XCTAssertEqual(violations(""), [StyleViolation(type: .TrailingNewline,
location: Location(file: nil, line: 1),
severity: .Medium,
reason: "File should have a single trailing newline: currently has 0")])
reason: "File should have a single trailing newline")])
XCTAssertEqual(violations("//\n\n"), [StyleViolation(type: .TrailingNewline,
location: Location(file: nil, line: 3),
severity: .Medium,
reason: "File should have a single trailing newline: currently has 2")])
reason: "File should have a single trailing newline")])
}
func testFileLengths() {