forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathCommaRule.swift
69 lines (58 loc) · 2.4 KB
/
CommaRule.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
61
62
63
64
65
66
67
68
69
//
// Comma.swift
// SwiftLint
//
// Created by Alex Culeva on 10/22/15.
// Copyright © 2015 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct CommaRule: CorrectableRule {
public init() {}
public static let description = RuleDescription(
identifier: "comma",
name: "Comma Spacing",
description: "There should be no space before and one after any comma.",
nonTriggeringExamples: [
"func abc(a: String, b: String) { }",
"abc(a: \"string\", b: \"string\"",
"enum a { case a, b, c }"
],
triggeringExamples: [
"func abc(a: String↓ ,b: String) { }",
"abc(a: \"string\"↓,b: \"string\"",
"enum a { case a↓ ,b }"
],
corrections: [
"func abc(a: String,b: String) {}\n": "func abc(a: String, b: String) {}\n",
"abc(a: \"string\",b: \"string\"\n": "abc(a: \"string\", b: \"string\"\n",
"abc(a: \"string\" , b: \"string\"\n": "abc(a: \"string\", b: \"string\"\n",
"enum a { case a ,b }\n": "enum a { case a, b }\n"
]
)
public func validateFile(file: File) -> [StyleViolation] {
let pattern = "(\\,[^\\s])|(\\s\\,)"
let excludingKinds = SyntaxKind.commentAndStringKinds()
return file.matchPattern(pattern, excludingSyntaxKinds: excludingKinds).map {
StyleViolation(ruleDescription: self.dynamicType.description,
location: Location(file: file, characterOffset: $0.location))
}
}
public func correctFile(file: File) -> [Correction] {
if validateFile(file).isEmpty { return [] }
let pattern = "\\s*\\,\\s*([^\\s])"
let description = self.dynamicType.description
var corrections = [Correction]()
var contents = file.contents
let matches = file.matchPattern(pattern, withSyntaxKinds: [.Identifier])
let regularExpression = regex(pattern)
for range in matches.reverse() {
contents = regularExpression.stringByReplacingMatchesInString(contents,
options: [], range: range, withTemplate: ", $1")
let location = Location(file: file, characterOffset: range.location)
corrections.append(Correction(ruleDescription: description, location: location))
}
file.write(contents)
return corrections
}
}