forked from realm/SwiftLint
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FunctionBodyLengthRule.swift
48 lines (43 loc) · 2 KB
/
FunctionBodyLengthRule.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
//
// FunctionBodyLengthRule.swift
// SwiftLint
//
// Created by JP Simard on 5/16/15.
// Copyright © 2015 Realm. All rights reserved.
//
import SourceKittenFramework
public struct FunctionBodyLengthRule: ASTRule, ConfigurationProviderRule {
public var configuration = SeverityLevelsConfiguration(warning: 40, error: 100)
public init() {}
public static let description = RuleDescription(
identifier: "function_body_length",
name: "Function Body Length",
description: "Functions bodies should not span too many lines."
)
public func validate(file: File, kind: SwiftDeclarationKind,
dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] {
guard SwiftDeclarationKind.functionKinds().contains(kind),
let offset = dictionary.offset,
let bodyOffset = dictionary.bodyOffset,
let bodyLength = dictionary.bodyLength,
case let contentsNSString = file.contents.bridge(),
let startLine = contentsNSString.lineAndCharacter(forByteOffset: bodyOffset)?.line,
let endLine = contentsNSString.lineAndCharacter(forByteOffset: bodyOffset + bodyLength)?.line
else {
return []
}
for parameter in configuration.params {
let (exceeds, lineCount) = file.exceedsLineCountExcludingCommentsAndWhitespace(
startLine, endLine, parameter.value
)
guard exceeds else { continue }
return [StyleViolation(ruleDescription: type(of: self).description,
severity: parameter.severity,
location: Location(file: file, byteOffset: offset),
reason: "Function body should span \(parameter.value) lines or less " +
"excluding comments and whitespace: currently spans \(lineCount) " +
"lines")]
}
return []
}
}