From 65f6715915c11eabc1700a6551798eeaeee4dde2 Mon Sep 17 00:00:00 2001 From: Keith Smiley Date: Fri, 14 Aug 2015 20:21:19 -0700 Subject: [PATCH] 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. --- .../Rules/TrailingNewlineRule.swift | 16 ++++++++++------ .../StringRuleTests.swift | 4 ++-- 2 files changed, 12 insertions(+), 8 deletions(-) diff --git a/Source/SwiftLintFramework/Rules/TrailingNewlineRule.swift b/Source/SwiftLintFramework/Rules/TrailingNewlineRule.swift index 22da55ff5..eccc53fc4 100644 --- a/Source/SwiftLintFramework/Rules/TrailingNewlineRule.swift +++ b/Source/SwiftLintFramework/Rules/TrailingNewlineRule.swift @@ -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 [] } diff --git a/Source/SwiftLintFrameworkTests/StringRuleTests.swift b/Source/SwiftLintFrameworkTests/StringRuleTests.swift index 2af9d5f3b..eac23b0db 100644 --- a/Source/SwiftLintFrameworkTests/StringRuleTests.swift +++ b/Source/SwiftLintFrameworkTests/StringRuleTests.swift @@ -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() {