forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
LeadingWhitespaceRule.swift
60 lines (50 loc) · 2.22 KB
/
LeadingWhitespaceRule.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
//
// LeadingWhitespaceRule.swift
// SwiftLint
//
// Created by JP Simard on 5/16/15.
// Copyright © 2015 Realm. All rights reserved.
//
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: [ "//\n" ],
triggeringExamples: [ "\n", " //\n" ],
corrections: ["\n //": "//"]
)
public func validate(file: File) -> [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: type(of: self).description,
severity: configuration.severity,
location: Location(file: file.path, line: 1),
reason: reason)]
}
public func correct(file: File) -> [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).isEmpty else {
return []
}
let indexEnd = file.contents.index(
file.contents.startIndex,
offsetBy: spaceCount,
limitedBy: file.contents.endIndex) ?? file.contents.endIndex
file.write(file.contents.substring(from: indexEnd))
let location = Location(file: file.path, line: max(file.lines.count, 1))
return [Correction(ruleDescription: type(of: self).description, location: location)]
}
}