Skip to content

Commit

Permalink
Merge pull request #7 from S2dentik/fixViolations
Browse files Browse the repository at this point in the history
Fix violations
  • Loading branch information
thelvis4 committed Dec 28, 2015
2 parents 48580b8 + 9ece84e commit 182c560
Show file tree
Hide file tree
Showing 16 changed files with 258 additions and 268 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,18 @@ import Cocoa

private let EmptyResultDictionary = Options()

private let optionReporterType: [String: Option.Type] = [
PathLong: PathOption.self, PathShort: PathOption.self,
TypeLong: TypeOption.self, TypeShort: TypeOption.self,
FileLong: FileOption.self, FileShort: FileOption.self,
ExcludeLong: ExcludeOption.self, ExcludeShort: ExcludeOption.self,
ExcludesFileLong: ExcludesFileOption.self, ExcludesFileShort: ExcludesFileOption.self,
ReporterLong: ReporterOption.self, ReporterShort: ReporterOption.self,
RuleCustomizationLong: RuleCustomizationOption.self,
RuleCustomizationShort: RuleCustomizationOption.self,
VerbosityLong: VerbosityOption.self, VerbosityShort: VerbosityOption.self
]

/*
If you change this class don't forget to fix his mock for actual right tests (if is case)
*/
Expand All @@ -23,11 +35,12 @@ class OptionsProcessor {
var executableOptions = [ExecutableOption]()

func processOptions(arguments: [String]) -> Options {
let options = optionsFromArguments(arguments)
if options.isEmpty {
return EmptyResultDictionary
let options = try! Array(arguments[1..<arguments.count]).reduceTwoElements([Option]()) {
if let optionObject = optionObjectFromOption($1, argument: $2) { return $0 + optionObject }
throw CommandLineError.InvalidArguments("Error committed on option `\($1)`.")
}
analyzePath = currentAnalyzedPath(options)
if options.isEmpty { return EmptyResultDictionary }
analyzePath = options.filter{ $0 is PathOption }.first?.optionArgument.absolutePath() ?? analyzePath
if !OptionsValidator().validateForSingleOptions(options) { return EmptyResultDictionary }
let resultDictionary = buildResultDictionaryFromOptions(executableOptions)
guard processInformationalOptions() else { return EmptyResultDictionary }
Expand All @@ -46,11 +59,6 @@ class OptionsProcessor {
return true
}

func currentAnalyzedPath(options:[Option]) -> String {
return options.filter{ $0 is PathOption }.first?.optionArgument.absolutePath() ?? analyzePath
}


private func buildResultDictionaryFromOptions(options: [ExecutableOption]) -> Options {
var resultDictionary = EmptyResultDictionary
if executeOptionsOnDictionary(&resultDictionary, options: options) {
Expand Down Expand Up @@ -111,52 +119,36 @@ class OptionsProcessor {
}


private func optionsFromArguments(arguments: [String]) -> [Option] {
var options = [Option]()
for var index = 1; index < arguments.count; index+=2 {
let option = arguments[index]
let optionArgument = arguments[index + 1]
let optionObject = optionObjectFromOption(option, argument: optionArgument)
if optionObject == nil {
errorPrinter.printError("Error committed on option `\(option)`.")
return []
}
options.append(optionObject!)
private func optionObjectFromOption(option: String, argument: String) -> Option? {
if option == ExcludesFileLong || option == ExcludesFileShort { isExcludesFileIndicated = true }
if let optionType = optionReporterType[option] {
return configureOption(optionType, argument: argument)
}

return options
return nil
}


private func optionObjectFromOption(option:String, argument:String) -> Option? {
switch option {
case PathLong, PathShort:
return configureOption(PathOption.self, argument: argument)
case TypeLong, TypeShort:
return configureOption(TypeOption.self, argument: argument)
case FileLong, FileShort:
return configureOption(FileOption.self, argument: argument)
case ExcludeLong, ExcludeShort:
return configureOption(ExcludeOption.self, argument: argument)
case ExcludesFileLong, ExcludesFileShort:
isExcludesFileIndicated = true
return configureOption(ExcludesFileOption.self, argument: argument)
case ReporterLong, ReporterShort:
return configureOption(ReporterOption.self, argument: argument)
case RuleCustomizationLong, RuleCustomizationShort:
return configureOption(RuleCustomizationOption.self, argument: argument)
case VerbosityLong, VerbosityShort:
return configureOption(VerbosityOption.self, argument: argument)
default:
return nil
}
}

func configureOption<T: Option>(option: T.Type, argument: String) -> T {
let option = T(argument: argument)
func configureOption(optionType: Option.Type, argument: String) -> Option {
let option = optionType.init(argument: argument)
if let infoOption = option as? InformationalOption { infoOptions.append(infoOption) }
else { executableOptions.append(option as! ExecutableOption) } // Safe to force unwrap

return option
}
}

extension Array {
func reduceTwoElements<T>(initial: T, @noescape combine: (T, Array.Generator.Element, Array.Generator.Element) throws -> T) rethrows -> T {
var result = initial
for (first, second) in Zip2Sequence(self.enumerate().filter { $0.0.isEven }.map { $0.1 },
self.enumerate().filter {$0.0.isOdd }.map {$0.1}) {
do {
result = try combine(result, first, second)
} catch let error as NSError {
errorPrinter.printError(error.localizedDescription)
return initial
}

}
return result
}
}
43 changes: 13 additions & 30 deletions TaylorFramework/Modules/finder/Finder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,18 +28,16 @@ final class Finder {
excludes = Excludes(paths: parameters!.excludes, rootPath: parameters!.rootPath)
let pathsFromDirectory = findPathsInDirectory(parameters!.rootPath)

return removeDuplicatedPaths(pathsFromDirectory + parameters!.files)
return (pathsFromDirectory + parameters!.files).unique
}

private func validateParameters(parameters: Parameters) -> Bool {
return validatePath(parameters.rootPath) && validateFiles(parameters.files)
}

private func findPathsInDirectory(path: String) -> [String] {
guard parameters != nil && excludes != nil else { return [] }
do {
guard parameters != nil && excludes != nil else {
return []
}
let pathsInDirectory = try fileManager.subpathsOfDirectoryAtPath(path)
let paths = exclude(excludes!, fromPaths: pathsInDirectory)
return paths.map { absolutePath(parameters!.rootPath, fileName: $0) }
Expand All @@ -50,18 +48,14 @@ final class Finder {
}

private func exclude(excludes: Excludes, fromPaths files: [FilePath]) -> [FilePath] {
guard parameters != nil else {
return []
}
guard parameters != nil else { return [] }
return files.keepPathsMatchingType(parameters!.type)
.excludePathsContainingSubpathsInArray(excludes.absolutePaths)
.excludePathsContainingDirectories(excludes.relativePaths)
}

private func validateFiles(files:[FilePath]) -> Bool {
guard parameters != nil else {
return true
}
guard parameters != nil else { return true }
for file in files {
if !existsFileOfTypeAtPath(file, type: parameters!.type) {
printer.printWrongFilePath(file)
Expand All @@ -72,11 +66,7 @@ final class Finder {
}

private func existsFileOfTypeAtPath(path: FilePath, type: String) -> Bool {
return fileExistsAtPath(path) && path.isKindOfType(type)
}

private func removeDuplicatedPaths(paths: [FilePath]) -> [FilePath] {
return Array(Set(paths))
return fileManager.fileExistsAtPath(path) && path.isKindOfType(type)
}

private func validatePath(path: FilePath) -> Bool {
Expand All @@ -88,24 +78,17 @@ final class Finder {
}

private func directoryExistsAtPath(path: FilePath) -> Bool {
guard parameters != nil else {
return false
}
return fileExistsAtPath(path) && isDirectoryAtPath(parameters!.rootPath)
}

private func fileExistsAtPath(path: FilePath) -> Bool {
return fileManager.fileExistsAtPath(path)
}

private func isDirectoryAtPath(path: FilePath) -> Bool {
var isDirectory = ObjCBool(false)
fileManager.fileExistsAtPath(path, isDirectory: &isDirectory)

return isDirectory.boolValue
guard let rootPath = parameters?.rootPath else { return false }
return fileManager.fileExistsAtPath(path) && fileManager.isDirectory(rootPath)
}

private func absolutePath(path: FilePath, fileName: String) -> FilePath {
return path + DirectorySuffix.Slash + fileName
}
}

extension Array where Element: Equatable {
var unique: [Element] {
return self.reduce([Element]()) { !$0.contains($1) ? $0 + $1 : $0 }
}
}
25 changes: 12 additions & 13 deletions TaylorFramework/Modules/scissors/ComponentFinder.swift
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ struct ComponentFinder {
do {
let regex = try NSRegularExpression(pattern: pattern, options: [.DotMatchesLineSeparators])
return regex.matchesInString(text, options: [], range: NSMakeRange(0, text.characters.count)).map {
$0.range
$0.range
}.reduce([OffsetRange]()) {
$0 + OffsetRange(start: $1.location, end: $1.location + $1.length)
}
Expand Down Expand Up @@ -52,7 +52,7 @@ struct ComponentFinder {

func findComments() -> [ExtendedComponent] {
return syntaxMap.tokens.filter {
ComponentType(type: $0.type) == ComponentType.Comment
ComponentType(type: $0.type) == ComponentType.Comment
}.reduce([ExtendedComponent]()) {
$0 + ExtendedComponent(dict: $1.dictionaryValue)
}
Expand Down Expand Up @@ -83,9 +83,9 @@ struct ComponentFinder {
let settersRanges = findRanges("(set($|[ \\t\\n{}]))", text: text)
if gettersRanges.isEmpty { return findObserverGetters(text) }

accessors.append(ExtendedComponent(type: .Function, range: gettersRanges.first!, name: "get", parent: nil))
accessors.append(ExtendedComponent(type: .Function, range: gettersRanges.first!, name: "get"))
if !settersRanges.isEmpty {
accessors.append(ExtendedComponent(type: .Function, range: settersRanges.first!, name: "set", parent: nil))
accessors.append(ExtendedComponent(type: .Function, range: settersRanges.first!, name: "set"))
}
accessors.sortInPlace( { $0.offsetRange.start < $1.offsetRange.start } )
if accessors.count == 1 {
Expand All @@ -103,18 +103,17 @@ struct ComponentFinder {
var didSetRanges = findRanges("(didSet($|[ \\t\\n{}]))", text: text)
var observers = [ExtendedComponent]()
if willSetRanges.count > 0 {
observers.append(ExtendedComponent(type: .Function, range: willSetRanges[0], name: "willSet", parent: nil))
observers.append(ExtendedComponent(type: .Function, range: willSetRanges[0], name: "willSet"))
}
if didSetRanges.count > 0 {
observers.append(ExtendedComponent(type: .Function, range: didSetRanges[0], name: "didSet", parent: nil))
observers.append(ExtendedComponent(type: .Function, range: didSetRanges[0], name: "didSet"))
}
observers.sortInPlace( { $0.offsetRange.start < $1.offsetRange.start } )
switch observers.count {
case 0: return []
case 1: observers[0].offsetRange.end = text.characters.count - 1
case 2: observers[0].offsetRange.end = observers[1].offsetRange.start - 1
observers[1].offsetRange.end = text.characters.count - 1
default: break
observers.sortInPlace { $0.offsetRange.start < $1.offsetRange.start }
if observers.count == 1 {
observers[0].offsetRange.end = text.characters.count - 1
} else if observers.count == 2 {
observers[0].offsetRange.end = observers[1].offsetRange.start - 1
observers[1].offsetRange.end = text.characters.count - 1
}

return observers
Expand Down
65 changes: 14 additions & 51 deletions TaylorFramework/Modules/scissors/ExtendedComponent.swift
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,12 @@ final class ExtendedComponent {
var offsetRange: OffsetRange
var type: ComponentType
var name: String?
var parent: ExtendedComponent?
var parent: ExtendedComponent? = nil
var components: [ExtendedComponent]

init(type: ComponentType, range: OffsetRange, name: String? = nil, parent: ExtendedComponent? = nil) {
init(type: ComponentType, range: OffsetRange, name: String? = nil) {
self.type = type
self.offsetRange = range
self.parent = parent
self.components = []
self.name = name
}
Expand All @@ -43,63 +42,27 @@ final class ExtendedComponent {

func appendComponents(var components: [ExtendedComponent], array: XPCArray) -> [ExtendedComponent] {
var braces = 0
for (var childNumber = 0; childNumber < array.count; childNumber++) {
let structure = array[childNumber]
let typeString = structure.asDictionary.type

array.enumerate().forEach { (childNumber, structure) in
var offsetRange = structure.asDictionary.offsetRange
var componentType = ComponentType(type: typeString)
if isElseIf(componentType) { componentType = .ElseIf }
else if isElse(componentType) && childNumber == array.count-1 && braces > 0 { componentType = .Else }
else if componentType.isVariable {
let type = getComponentType(structure.asDictionary.type, bracesCount: braces, isLast: childNumber == array.count - 1)
if type.isVariable {
let bodyOffsetEnd = structure.asDictionary.bodyLength + structure.asDictionary.bodyOffset
if bodyOffsetEnd != 0 {
offsetRange.end = bodyOffsetEnd
}
}
else if componentType.isOther { continue }
if componentType.isBrace { braces++ }

let child = ExtendedComponent(type: componentType, range: offsetRange, name: structure.asDictionary.name)
if bodyOffsetEnd != 0 { offsetRange.end = bodyOffsetEnd }
} else if type.isOther { return }
if type.isBrace { braces++ }
let child = ExtendedComponent(type: type, range: offsetRange, name: structure.asDictionary.name)
components.append(child)
components = child.appendComponents(components, array: structure.asDictionary.substructure)
}

return components
}

func addChild(child: ExtendedComponent) -> ExtendedComponent {
self.components.append(child)
child.parent = self
return child
}

func addChild(type: ComponentType, range: OffsetRange, name: String? = nil) -> ExtendedComponent {
let child = ExtendedComponent(type: type, range: range, name: name, parent: self)
self.components.append(child)
return child
}

func contains(node: ExtendedComponent) -> Bool {
return (node.offsetRange.start >= self.offsetRange.start)
&& (node.offsetRange.end <= self.offsetRange.end)
}

func insert(node: ExtendedComponent) {
for child in self.components {
if child.contains(node) {
child.insert(node)
return
} else if node.contains(child) {
remove(child)
node.addChild(child)
}
}
self.addChild(node)
}

func remove(component: ExtendedComponent) {
components = components.filter() { $0 != component }
func getComponentType(type: String, bracesCount: Int, isLast: Bool) -> ComponentType {
let type = ComponentType(type: type)
if isElseIf(type) { return .ElseIf }
else if isElse(type) && isLast && bracesCount > 0 { return .Else }
else { return type }
}

func insert(components: [ExtendedComponent]) {
Expand Down
Loading

0 comments on commit 182c560

Please sign in to comment.