Files
SwiftLint/Source/SwiftLintFramework/Rules/Style/LeadingWhitespaceRule.swift
T
Danny Mösch 449190d324 Verify examples in rules by default and enforce explicit exclusion (#4065)
A rule must conform to ManuallyTestedExamplesRule to skip generation of a test for its examples.
2022-08-09 22:32:09 +02:00

59 lines
2.3 KiB
Swift

import Foundation
import SourceKittenFramework
public struct LeadingWhitespaceRule: CorrectableRule, ConfigurationProviderRule, SourceKitFreeRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "leading_whitespace",
name: "Leading Whitespace",
description: "Files should not contain leading whitespace.",
kind: .style,
nonTriggeringExamples: [
Example("//\n")
],
triggeringExamples: [
Example("\n//\n"),
Example(" //\n")
].skipMultiByteOffsetTests().skipDisableCommandTests(),
corrections: [
Example("\n //", testMultiByteOffsets: false): Example("//")
]
)
public func validate(file: SwiftLintFile) -> [StyleViolation] {
let countOfLeadingWhitespace = file.contents.countOfLeadingCharacters(in: .whitespacesAndNewlines)
if countOfLeadingWhitespace == 0 {
return []
}
let reason = "File shouldn't start with whitespace: " +
"currently starts with \(countOfLeadingWhitespace) whitespace characters"
return [StyleViolation(ruleDescription: Self.description,
severity: configuration.severity,
location: Location(file: file.path, line: 1),
reason: reason)]
}
public func correct(file: SwiftLintFile) -> [Correction] {
let whitespaceAndNewline = CharacterSet.whitespacesAndNewlines
let spaceCount = file.contents.countOfLeadingCharacters(in: whitespaceAndNewline)
guard spaceCount > 0,
let firstLineRange = file.lines.first?.range,
file.ruleEnabled(violatingRanges: [firstLineRange], for: self).isNotEmpty else {
return []
}
let indexEnd = file.contents.index(
file.contents.startIndex,
offsetBy: spaceCount,
limitedBy: file.contents.endIndex) ?? file.contents.endIndex
file.write(String(file.contents[indexEnd...]))
let location = Location(file: file.path, line: max(file.lines.count, 1))
return [Correction(ruleDescription: Self.description, location: location)]
}
}