-
Notifications
You must be signed in to change notification settings - Fork 2.2k
/
Copy pathLeadingWhitespaceRule.swift
58 lines (51 loc) · 2.13 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
//
// LeadingWhitespaceRule.swift
// SwiftLint
//
// Created by JP Simard on 2015-05-16.
// Copyright (c) 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.",
nonTriggeringExamples: [ "//\n" ],
triggeringExamples: [ "\n", " //\n" ],
corrections: ["\n": ""]
)
public func validateFile(file: File) -> [StyleViolation] {
let countOfLeadingWhitespace = file.contents.countOfLeadingCharactersInSet(
NSCharacterSet.whitespaceAndNewlineCharacterSet()
)
if countOfLeadingWhitespace == 0 {
return []
}
return [StyleViolation(ruleDescription: self.dynamicType.description,
severity: configuration.severity,
location: Location(file: file.path, line: 1),
reason: "File shouldn't start with whitespace: " +
"currently starts with \(countOfLeadingWhitespace) whitespace characters")]
}
public func correctFile(file: File) -> [Correction] {
let whitespaceAndNewline = NSCharacterSet.whitespaceAndNewlineCharacterSet()
let spaceCount = file.contents.countOfLeadingCharactersInSet(whitespaceAndNewline)
if spaceCount == 0 {
return []
}
let region = file.regions().filter {
$0.contains(Location(file: file.path, line: max(file.lines.count, 1)))
}.first
if region?.isRuleDisabled(self) == true {
return []
}
let indexEnd = file.contents.startIndex.advancedBy(spaceCount)
file.write(file.contents.substringFromIndex(indexEnd))
let location = Location(file: file.path, line: max(file.lines.count, 1))
return [Correction(ruleDescription: self.dynamicType.description, location: location)]
}
}