Skip to content

Commit

Permalink
Fix false positives on vertical_whitespace_between_cases
Browse files Browse the repository at this point in the history
  • Loading branch information
Ben Staveley-Taylor authored and sjavora committed Mar 9, 2019
1 parent 1b896ee commit 821b619
Showing 1 changed file with 24 additions and 2 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -104,6 +104,28 @@ public struct VerticalWhitespaceBetweenCasesRule: ConfigurationProviderRule {
]

private let pattern = "([^\\n{][ \\t]*\\n)([ \\t]*(?:case[^\\n]+|default):[ \\t]*\\n)"

private func violationRanges(in file: File) -> [NSRange] {
return file.violatingRanges(for: pattern).filter {
!isFalsePositive(in: file, range: $0)
}
}

private func isFalsePositive(in file: File, range: NSRange) -> Bool {
// Regex incorrectly flags blank lines that contain trailing whitespace (#2538)
let patternRegex = regex(pattern)
let substring = file.contents.substring(from: range.location, length: range.length)
let substringRange = NSRange(location: 0, length: substring.count)
guard let matchResult = patternRegex.firstMatch(in: substring, options: [], range: substringRange),
matchResult.numberOfRanges > 1 else {
return false
}

let matchFirstRange = matchResult.range(at: 1)
let matchFirstString = substring.substring(from: matchFirstRange.location, length: matchFirstRange.length)
let isAllWhitespace = matchFirstString.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
return isAllWhitespace
}
}

extension VerticalWhitespaceBetweenCasesRule: OptInRule, AutomaticTestableRule {
Expand All @@ -119,7 +141,7 @@ extension VerticalWhitespaceBetweenCasesRule: OptInRule, AutomaticTestableRule {

public func validate(file: File) -> [StyleViolation] {
let patternRegex = regex(pattern)
return file.violatingRanges(for: pattern).compactMap { violationRange in
return violationRanges(in: file).compactMap { violationRange in
let substring = file.contents.substring(from: violationRange.location, length: violationRange.length)
let substringRange = NSRange(location: 0, length: substring.count)
guard let matchResult = patternRegex.firstMatch(in: substring, options: [], range: substringRange) else {
Expand All @@ -140,7 +162,7 @@ extension VerticalWhitespaceBetweenCasesRule: OptInRule, AutomaticTestableRule {

extension VerticalWhitespaceBetweenCasesRule: CorrectableRule {
public func correct(file: File) -> [Correction] {
let violatingRanges = file.ruleEnabled(violatingRanges: file.violatingRanges(for: pattern), for: self)
let violatingRanges = file.ruleEnabled(violatingRanges: violationRanges(in: file), for: self)
guard !violatingRanges.isEmpty else { return [] }

let patternRegex = regex(pattern)
Expand Down

0 comments on commit 821b619

Please sign in to comment.