Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hierarchical Linting #24

Closed
wants to merge 9 commits into from
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,11 +15,15 @@
FunctionBodyLength, Nesting, TypeBodyLength, TypeName, VariableName.
[JP Simard](https://github.com/jpsim)

* Add RuleEnabler, a struct that controls which rules are enabled and which are disabled.
[Aaron Daub](https://github.com/aarondaub)

##### Bug Fixes

None.


## 0.1.0


First Version!
22 changes: 22 additions & 0 deletions Source/SwiftLintFramework/Array+SwiftLint.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
//
// Array+SwiftLint.swift
// SwiftLint
//
// Created by Aaron Daub on 2015-05-20.
// Copyright (c) 2015 Realm. All rights reserved.
//

import Foundation

func flatten<T>(array: [T?]) -> [T] {
return array.reduce([]){
if let e = $1 {
return $0 + [e]
}
return $0
}
}

func flatten<T>(nestedArray: [[T]]) -> [T] {
return reduce(nestedArray, [], +)
}
85 changes: 67 additions & 18 deletions Source/SwiftLintFramework/Linter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,26 +11,62 @@ import SwiftXPC
import SourceKittenFramework

public struct Linter {
private let file: File
private let context: LinterContext
private let file: File

public var styleViolations: [StyleViolation] {
return reduce(
[
LineLengthRule().validateFile(file),
LeadingWhitespaceRule().validateFile(file),
TrailingWhitespaceRule().validateFile(file),
TrailingNewlineRule().validateFile(file),
ForceCastRule().validateFile(file),
FileLengthRule().validateFile(file),
TodoRule().validateFile(file),
ColonRule().validateFile(file),
TypeNameRule().validateFile(file),
VariableNameRule().validateFile(file),
TypeBodyLengthRule().validateFile(file),
FunctionBodyLengthRule().validateFile(file),
NestingRule().validateFile(file)
], [], +)
public var styleViolations: [StyleViolation] {
let linters = self.linters
return linters.flatMap {
$0.styleViolations
} + context.enabledRules().flatMap {
$0.validateFile(self.file)
}
}

private var linters: [Linter] {
let linterContextBegin = "// swift-lint:begin-context"
let linterContextEnd = "// swift-lint:end-context"


var contextDepth = 0
var (contextStartingLineNumber, contextEndingLineNumber) = (0, 0)
var currentLineNumber = 0
var inContext = false

typealias LinterRegion = (start: Int, exclusiveEnd: Int)
let lines = self.context.region.contents.lines()

var regions: [LinterRegion] = flatten(lines.map { (line: Line) -> (LinterRegion)? in
if line.content.trim() == linterContextBegin {
inContext = true
contextDepth += 1
contextStartingLineNumber = currentLineNumber + 1
} else if line.content.trim() == linterContextEnd && inContext {
contextDepth -= 1
inContext = contextDepth != 0

contextEndingLineNumber = currentLineNumber
if !inContext {
return (contextStartingLineNumber, contextEndingLineNumber)
}
}
currentLineNumber += 1
return nil
})

let linters = regions.map { (region: LinterRegion) -> Linter in
let sublines: [String] = map((lines[region.start ..< region.exclusiveEnd])) {
$0.content
}

let substring = "\n".join(sublines + [""]) // postpend the empty string to keep trailing newlines
let region = File(contents: substring)
let context = LinterContext(insideOf: self.context, file: region)
return Linter(file: self.file, context: context)
}

return linters
}

/**
Initialize a Linter by passing in a File.
Expand All @@ -39,5 +75,18 @@ public struct Linter {
*/
public init(file: File) {
self.file = file
self.context = LinterContext(file: file)
}

/**
Initialize a Linter by passing in a LinterContext.
This is for having a child Linter inherit properties
from their parent.

:param: context LinterContext to inherit from
*/
private init(file: File, context: LinterContext) {
self.file = file
self.context = context
}
}
82 changes: 82 additions & 0 deletions Source/SwiftLintFramework/LinterContext.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
//
// LinterContext.swift
// SwiftLint
//
// Created by Aaron Daub on 2015-05-21.
// Copyright (c) 2015 Realm. All rights reserved.
//

import Foundation
import SourceKittenFramework

public struct LinterContext {
var region: File
private var potentiallyEnabledRules: [Rule] = [LineLengthRule(),
LeadingWhitespaceRule(),
TrailingWhitespaceRule(),
TrailingNewlineRule(),
ForceCastRule(),
FileLengthRule(),
TodoRule(),
ColonRule(),
TypeNameRule(),
VariableNameRule(),
TypeBodyLengthRule(),
FunctionBodyLengthRule(),
NestingRule()]
var disabledRules: [Rule] = []
var parentEnabledRules: [Rule] = []

public init(file: File) {
self.region = file
}

public init(insideOf context: LinterContext, file: File) {
(self.region, self.parentEnabledRules) = (file, context.enabledRules())
}

public func enabledRules() -> [Rule] {
// All of our enabled rules that are not enabled in our parent
return potentiallyEnabledRules.filter { (rule: Rule) -> Bool in
return self.parentEnabledRules.filter { $0.identifier == rule.identifier}.count == 0
}
}

func ruleWith(identifier: String, enabled: Bool) -> Rule? {
let arrayToSearch = enabled ? self.potentiallyEnabledRules : self.disabledRules

return filter(arrayToSearch) {
return $0.identifier == identifier
}.first
}

public mutating func enableRule(identifier: String) -> Bool {
return changeRule(identifier, enabled: true)
}

public mutating func disableRule(identifier: String) -> Bool {
return changeRule(identifier, enabled: false)
}

private mutating func changeRule(identifier: String, enabled: Bool) -> Bool {
var (rulesToAddTo, rulesToRemoveFrom) = enabled ? (self.potentiallyEnabledRules, self.disabledRules) : (self.disabledRules, self.potentiallyEnabledRules)

if let rule = ruleWith(identifier, enabled: !enabled) {
moveRule(rule, enabled: enabled)
return true
}
return false
}

private mutating func moveRule(rule: Rule, enabled: Bool) {
let rulesTuple = enabled ? (self.potentiallyEnabledRules, self.disabledRules) : (self.disabledRules, self.potentiallyEnabledRules)
var (rulesToAddTo, rulesToRemoveFrom): ([Rule], [Rule]) = rulesTuple

rulesToAddTo.append(rule)
rulesToRemoveFrom = filter(rulesToRemoveFrom) { (candidateRule: Rule) -> Bool in
return candidateRule.identifier != rule.identifier
}

(self.potentiallyEnabledRules, self.disabledRules) = enabled ? (rulesToAddTo, rulesToRemoveFrom) : (rulesToRemoveFrom, rulesToAddTo)
}
}
2 changes: 1 addition & 1 deletion Source/SwiftLintFramework/Rule.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

import SourceKittenFramework

protocol Rule {
public protocol Rule {
var identifier: String { get }
func validateFile(file: File) -> [StyleViolation]
}
Expand Down
4 changes: 4 additions & 0 deletions Source/SwiftLintFramework/String+SwiftLint.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,10 @@ extension String {
}
return lines
}

func trim(characterSet: NSCharacterSet = NSCharacterSet.whitespaceCharacterSet()) -> String {
return stringByTrimmingCharactersInSet(characterSet)
}

func isUppercase() -> Bool {
return self == uppercaseString
Expand Down
11 changes: 11 additions & 0 deletions Source/SwiftLintFrameworkTests/LinterTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,17 @@ func violations(string: String) -> [StyleViolation] {

class LinterTests: XCTestCase {

// MARK: Nesting

func testNestingEquivalentToNoNesting() {
let lines = ["1", "2", "\n"]
let linesWithNesting = ["1", "// swift-lint:begin-context", "2", "// swift-lint:end-context", "\n"]
let (contents, contentsWithNesting) = ("\n".join(lines), "\n".join(linesWithNesting))
let (file, fileWithNesting) = (File(contents: contents), File(contents: contentsWithNesting))
let (linter, linterWithNesting) = (Linter(file: file), Linter(file: fileWithNesting))
XCTAssertEqual(linter.styleViolations, linterWithNesting.styleViolations, "Nesting shouldn't impact styleViolations")
}

// MARK: AST Violations

func testTypeNames() {
Expand Down
8 changes: 8 additions & 0 deletions SwiftLint.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
objects = {

/* Begin PBXBuildFile section */
345D0CA01B0D3A5A00EF7A41 /* Array+SwiftLint.swift in Sources */ = {isa = PBXBuildFile; fileRef = 345D0C9F1B0D3A5A00EF7A41 /* Array+SwiftLint.swift */; };
345D0CA21B0D3EC100EF7A41 /* LinterContext.swift in Sources */ = {isa = PBXBuildFile; fileRef = 345D0CA11B0D3EC100EF7A41 /* LinterContext.swift */; };
D0AAAB5019FB0960007B24B3 /* SwiftLintFramework.framework in Embed Frameworks */ = {isa = PBXBuildFile; fileRef = D0D1216D19E87B05005E4BAA /* SwiftLintFramework.framework */; settings = {ATTRIBUTES = (CodeSignOnCopy, RemoveHeadersOnCopy, ); }; };
D0D1217819E87B05005E4BAA /* SwiftLintFramework.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D0D1216D19E87B05005E4BAA /* SwiftLintFramework.framework */; };
D0E7B65319E9C6AD00EDBA4D /* SwiftLintFramework.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = D0D1216D19E87B05005E4BAA /* SwiftLintFramework.framework */; };
Expand Down Expand Up @@ -98,6 +100,8 @@
/* End PBXCopyFilesBuildPhase section */

/* Begin PBXFileReference section */
345D0C9F1B0D3A5A00EF7A41 /* Array+SwiftLint.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = "Array+SwiftLint.swift"; sourceTree = "<group>"; };
345D0CA11B0D3EC100EF7A41 /* LinterContext.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LinterContext.swift; sourceTree = "<group>"; };
5499CA961A2394B700783309 /* Components.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Components.plist; sourceTree = "<group>"; };
5499CA971A2394B700783309 /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = "<group>"; };
D0D1211B19E87861005E4BAA /* main.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = main.swift; sourceTree = "<group>"; usesTabs = 0; };
Expand Down Expand Up @@ -310,10 +314,12 @@
E88DEA8B1B0999A000A66CB0 /* ASTRule.swift */,
E88DEA741B09852000A66CB0 /* File+SwiftLint.swift */,
E812249B1B04FADC001783D2 /* Linter.swift */,
345D0CA11B0D3EC100EF7A41 /* LinterContext.swift */,
E88DEA6E1B09843F00A66CB0 /* Location.swift */,
E88DEA761B098D0C00A66CB0 /* Rule.swift */,
E88DEA781B098D4400A66CB0 /* RuleParameter.swift */,
E88DEA721B0984C400A66CB0 /* String+SwiftLint.swift */,
345D0C9F1B0D3A5A00EF7A41 /* Array+SwiftLint.swift */,
E88DEA6A1B0983FE00A66CB0 /* StyleViolation.swift */,
E88DEA6C1B09842200A66CB0 /* StyleViolationType.swift */,
E88DEA701B09847500A66CB0 /* ViolationSeverity.swift */,
Expand Down Expand Up @@ -540,6 +546,7 @@
files = (
E812249C1B04FADC001783D2 /* Linter.swift in Sources */,
E88DEA861B0991BF00A66CB0 /* TrailingWhitespaceRule.swift in Sources */,
345D0CA01B0D3A5A00EF7A41 /* Array+SwiftLint.swift in Sources */,
E88DEA841B0990F500A66CB0 /* ColonRule.swift in Sources */,
E88DEA791B098D4400A66CB0 /* RuleParameter.swift in Sources */,
E88DEA731B0984C400A66CB0 /* String+SwiftLint.swift in Sources */,
Expand All @@ -559,6 +566,7 @@
E88DEA8C1B0999A000A66CB0 /* ASTRule.swift in Sources */,
E88DEA821B0990A700A66CB0 /* TodoRule.swift in Sources */,
E88DEA901B099A3100A66CB0 /* FunctionBodyLengthRule.swift in Sources */,
345D0CA21B0D3EC100EF7A41 /* LinterContext.swift in Sources */,
E88DEA6B1B0983FE00A66CB0 /* StyleViolation.swift in Sources */,
E88DEA7E1B098F2A00A66CB0 /* LeadingWhitespaceRule.swift in Sources */,
);
Expand Down