From 41e7f310132e66ccd1bc239389d6c3b0fd2c35f1 Mon Sep 17 00:00:00 2001 From: Peter Zignego Date: Fri, 9 Jun 2017 16:54:09 -0400 Subject: [PATCH] SwiftLint + Gardening --- .swiftlint.yml | 8 ++++ SKServer.xcodeproj/project.pbxproj | 48 +++++++++++++++++++ .../SKServer/Conformers/SwifterServer.swift | 21 ++++---- .../Middleware/MessageActionMiddleware.swift | 5 +- .../SKServer/Middleware/OAuthMiddleware.swift | 14 ++++-- .../Middleware/RedirectMiddleware.swift | 5 +- .../Middleware/ResponseMiddleware.swift | 16 +++---- .../SKServer/Model/AuthorizeResponse.swift | 3 +- Sources/SKServer/Model/IncomingWebhook.swift | 3 +- .../SKServer/Model/MessageActionRequest.swift | 3 +- .../SKServer/Model/MessageActionRoute.swift | 3 +- Sources/SKServer/Model/OAuthResponse.swift | 5 +- Sources/SKServer/Model/RequestRoute.swift | 3 +- Sources/SKServer/Model/SKResponse.swift | 9 ++-- Sources/SKServer/Model/WebhookRequest.swift | 3 +- Sources/SKServer/SKServer.swift | 7 ++- Sources/SKServer/SlackKitResponder.swift | 9 ++-- 17 files changed, 108 insertions(+), 57 deletions(-) create mode 100644 .swiftlint.yml diff --git a/.swiftlint.yml b/.swiftlint.yml new file mode 100644 index 0000000..afa3ce1 --- /dev/null +++ b/.swiftlint.yml @@ -0,0 +1,8 @@ +disabled_rules: + - identifier_name + - function_parameter_count +line_length: 140 +excluded: # paths to ignore during linting. Takes precedence over `included`. + - Carthage + - Pods + - Sources/SKServer/Titan \ No newline at end of file diff --git a/SKServer.xcodeproj/project.pbxproj b/SKServer.xcodeproj/project.pbxproj index 51988b6..d07cbff 100644 --- a/SKServer.xcodeproj/project.pbxproj +++ b/SKServer.xcodeproj/project.pbxproj @@ -346,6 +346,7 @@ 2684F1791E95AA6900536DCC /* Frameworks */, 2684F17A1E95AA6900536DCC /* Headers */, 2684F17B1E95AA6900536DCC /* Resources */, + 2668B5181EEB40E00082DE33 /* SwiftLint */, ); buildRules = ( ); @@ -364,6 +365,7 @@ 2684F1DE1E95ABD400536DCC /* Frameworks */, 2684F1DF1E95ABD400536DCC /* Headers */, 2684F1E01E95ABD400536DCC /* Resources */, + 2668B5191EEB40EA0082DE33 /* SwiftLint */, ); buildRules = ( ); @@ -382,6 +384,7 @@ 2684F2021E95ABD600536DCC /* Frameworks */, 2684F2031E95ABD600536DCC /* Headers */, 2684F2041E95ABD600536DCC /* Resources */, + 2668B51A1EEB40F30082DE33 /* SwiftLint */, ); buildRules = ( ); @@ -456,6 +459,51 @@ }; /* End PBXResourcesBuildPhase section */ +/* Begin PBXShellScriptBuildPhase section */ + 2668B5181EEB40E00082DE33 /* SwiftLint */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = SwiftLint; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi"; + }; + 2668B5191EEB40EA0082DE33 /* SwiftLint */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = SwiftLint; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi"; + }; + 2668B51A1EEB40F30082DE33 /* SwiftLint */ = { + isa = PBXShellScriptBuildPhase; + buildActionMask = 2147483647; + files = ( + ); + inputPaths = ( + ); + name = SwiftLint; + outputPaths = ( + ); + runOnlyForDeploymentPostprocessing = 0; + shellPath = /bin/sh; + shellScript = "if which swiftlint >/dev/null; then\n swiftlint\nelse\n echo \"warning: SwiftLint not installed, download from https://github.com/realm/SwiftLint\"\nfi"; + }; +/* End PBXShellScriptBuildPhase section */ + /* Begin PBXSourcesBuildPhase section */ 2684F1781E95AA6900536DCC /* Sources */ = { isa = PBXSourcesBuildPhase; diff --git a/Sources/SKServer/Conformers/SwifterServer.swift b/Sources/SKServer/Conformers/SwifterServer.swift index d111e37..4a83b4e 100644 --- a/Sources/SKServer/Conformers/SwifterServer.swift +++ b/Sources/SKServer/Conformers/SwifterServer.swift @@ -25,22 +25,21 @@ import Foundation import Swifter class SwifterServer: SlackKitServer { - let server = HttpServer() let port: in_port_t let forceIPV4: Bool - + init(port: in_port_t = 8080, forceIPV4: Bool = false, responder: SlackKitResponder) { self.port = port self.forceIPV4 = forceIPV4 - + for route in responder.routes { server[route.path] = { request in return route.middleware.respond(to: (request.request, Response())).1.httpResponse } } } - + public func start() { do { try server.start(port, forceIPv4: forceIPV4) @@ -48,15 +47,15 @@ class SwifterServer: SlackKitServer { print("Server failed to start with error: \(error)") } } - + deinit { server.stop() } } - + extension HttpRequest { public var request: RequestType { - return Request(self.method, self.path, String(bytes: self.body, encoding: .utf8) ?? "", self.headers.map{($0.key, $0.value)}) + return Request(self.method, self.path, String(bytes: self.body, encoding: .utf8) ?? "", self.headers.map {($0.key, $0.value) }) } } @@ -64,7 +63,7 @@ extension ResponseType { public var contentType: String? { return self.headers.first(where: {$0.name.lowercased() == "content-type"})?.value } - + public var httpResponse: HttpResponse { switch self.code { case 200 where contentType == nil: @@ -76,9 +75,11 @@ extension ResponseType { do { let json = try JSONSerialization.jsonObject(with: data, options: []) #if os(Linux) - return .ok(.json(json as! AnyObject)) + //swiftlint:disable force_cast + return .ok(.json(json as! AnyObject)) + //swiftlint:enable force_cast #else - return .ok(.json(json as AnyObject)) + return .ok(.json(json as AnyObject)) #endif } catch let error { return .badRequest(.text(error.localizedDescription)) diff --git a/Sources/SKServer/Middleware/MessageActionMiddleware.swift b/Sources/SKServer/Middleware/MessageActionMiddleware.swift index 9c8d901..6072369 100644 --- a/Sources/SKServer/Middleware/MessageActionMiddleware.swift +++ b/Sources/SKServer/Middleware/MessageActionMiddleware.swift @@ -22,15 +22,14 @@ // THE SOFTWARE. public struct MessageActionMiddleware: Middleware { - let token: String let routes: [MessageActionRoute] - + public init(token: String, routes: [MessageActionRoute]) { self.token = token self.routes = routes } - + public func respond(to request: (RequestType, ResponseType)) -> (RequestType, ResponseType) { if let form = request.0.formURLEncodedBody.first(where: {$0.name == "ssl_check"}), form.value == "1" { return (request.0, Response(200)) diff --git a/Sources/SKServer/Middleware/OAuthMiddleware.swift b/Sources/SKServer/Middleware/OAuthMiddleware.swift index b4fd47a..5497a1f 100644 --- a/Sources/SKServer/Middleware/OAuthMiddleware.swift +++ b/Sources/SKServer/Middleware/OAuthMiddleware.swift @@ -25,20 +25,24 @@ import SKCore import SKWebAPI public struct OAuthMiddleware: Middleware { - private let config: OAuthConfig - internal(set) public var authed: ((OAuthResponse) -> Void)? = nil - + internal(set) public var authed: ((OAuthResponse) -> Void)? + public init(config: OAuthConfig, authed: ((OAuthResponse) -> Void)? = nil) { self.config = config self.authed = authed } - + public func respond(to request: (RequestType, ResponseType)) -> (RequestType, ResponseType) { guard let response = AuthorizeResponse(queryItems: request.0.query), let code = response.code, response.state == config.state else { return (request.0, Response(400)) } - let authResponse = WebAPI.oauthAccess(clientID: config.clientID, clientSecret: config.clientSecret, code: code, redirectURI: config.redirectURI) + let authResponse = WebAPI.oauthAccess( + clientID: config.clientID, + clientSecret: config.clientSecret, + code: code, + redirectURI: config.redirectURI + ) self.authed?(OAuthResponse(response: authResponse)) guard let redirect = config.redirectURI else { return (request.0, Response(200)) diff --git a/Sources/SKServer/Middleware/RedirectMiddleware.swift b/Sources/SKServer/Middleware/RedirectMiddleware.swift index 7260afb..b9ec9f5 100644 --- a/Sources/SKServer/Middleware/RedirectMiddleware.swift +++ b/Sources/SKServer/Middleware/RedirectMiddleware.swift @@ -22,15 +22,14 @@ // SOFTWARE. public struct RedirectMiddleware: Middleware { - let location: String let shouldRedirect: (RequestType) -> Bool - + public init(redirectTo location: String, if shouldRedirect: @escaping (RequestType) -> Bool) { self.location = location self.shouldRedirect = shouldRedirect } - + public func respond(to request: (RequestType, ResponseType)) -> (RequestType, ResponseType) { if shouldRedirect(request.0) { return (request.0, Response(code: 302, body: "", headers: [("location", location)])) diff --git a/Sources/SKServer/Middleware/ResponseMiddleware.swift b/Sources/SKServer/Middleware/ResponseMiddleware.swift index 08f6447..88263da 100644 --- a/Sources/SKServer/Middleware/ResponseMiddleware.swift +++ b/Sources/SKServer/Middleware/ResponseMiddleware.swift @@ -24,26 +24,24 @@ import Foundation public struct ResponseMiddleware: Middleware { - let token: String let response: SKResponse - + public init(token: String, response: SKResponse) { self.token = token self.response = response } - + public func respond(to request: (RequestType, ResponseType)) -> (RequestType, ResponseType) { if let respondable = Respondable(request: request.0), respondable.token == token { return (request.0, Response(response: response)) } return (request.0, Response(400)) } - + private struct Respondable { - let token: String - + init?(request: RequestType) { if let webhook = WebhookRequest(request: request), let token = webhook.token { self.token = token @@ -89,8 +87,10 @@ extension Response { public init(response: SKResponse) { if response.attachments == nil { self.init(200, response.text) - } else if let data = try? JSONSerialization.data(withJSONObject: response.json, options: []), let body = String(data: data, encoding: .utf8) { - self.init(code: 200, body: body, headers: [("content-type","application/json")]) + } else if + let data = try? JSONSerialization.data(withJSONObject: response.json, options: []), + let body = String(data: data, encoding: .utf8) { + self.init(code: 200, body: body, headers: [("content-type", "application/json")]) } else { self.init(400) } diff --git a/Sources/SKServer/Model/AuthorizeResponse.swift b/Sources/SKServer/Model/AuthorizeResponse.swift index 67048d8..2dbbf6f 100644 --- a/Sources/SKServer/Model/AuthorizeResponse.swift +++ b/Sources/SKServer/Model/AuthorizeResponse.swift @@ -22,10 +22,9 @@ // THE SOFTWARE. public struct AuthorizeResponse { - var code: String? var state: String? - + init?(queryItems: [String: String]) { for item in queryItems { switch item.key { diff --git a/Sources/SKServer/Model/IncomingWebhook.swift b/Sources/SKServer/Model/IncomingWebhook.swift index 625391b..356926b 100644 --- a/Sources/SKServer/Model/IncomingWebhook.swift +++ b/Sources/SKServer/Model/IncomingWebhook.swift @@ -22,14 +22,13 @@ // THE SOFTWARE. public struct IncomingWebhook { - public let url: String? public let channel: String? public let configurationURL: String? public let username: String? public let iconEmoji: String? public let iconURL: String? - + internal init(webhook: [String: Any]?) { url = webhook?["url"] as? String channel = webhook?["channel"] as? String diff --git a/Sources/SKServer/Model/MessageActionRequest.swift b/Sources/SKServer/Model/MessageActionRequest.swift index 288bfe8..321e19f 100644 --- a/Sources/SKServer/Model/MessageActionRequest.swift +++ b/Sources/SKServer/Model/MessageActionRequest.swift @@ -24,7 +24,6 @@ import SKCore public struct MessageActionRequest { - public let action: Action? public let callbackID: String? public let team: Team? @@ -36,7 +35,7 @@ public struct MessageActionRequest { public let token: String? public let originalMessage: Message? public let responseURL: String? - + internal init(response: [String: Any]?) { action = (response?["actions"] as? [Any])?.map({$0 as? [String: Any]}).first.map({Action(action: $0)}) callbackID = response?["callback_id"] as? String diff --git a/Sources/SKServer/Model/MessageActionRoute.swift b/Sources/SKServer/Model/MessageActionRoute.swift index 112f2cd..979518d 100644 --- a/Sources/SKServer/Model/MessageActionRoute.swift +++ b/Sources/SKServer/Model/MessageActionRoute.swift @@ -24,10 +24,9 @@ import SKCore public struct MessageActionRoute { - let action: Action let middleware: Middleware - + public init(action: Action, middleware: Middleware) { self.action = action self.middleware = middleware diff --git a/Sources/SKServer/Model/OAuthResponse.swift b/Sources/SKServer/Model/OAuthResponse.swift index 88bc3f8..445d85d 100644 --- a/Sources/SKServer/Model/OAuthResponse.swift +++ b/Sources/SKServer/Model/OAuthResponse.swift @@ -24,7 +24,6 @@ import SKCore public struct OAuthResponse { - public let accessToken: String? public let scope: [Scope]? public let userID: String? @@ -32,10 +31,10 @@ public struct OAuthResponse { public let teamID: String? public let incomingWebhook: IncomingWebhook? public let bot: Bot? - + internal init(response: [String: Any]?) { accessToken = response?["access_token"] as? String - scope = (response?["scope"] as? String)?.components(separatedBy: ",").flatMap{Scope(rawValue: $0)} + scope = (response?["scope"] as? String)?.components(separatedBy: ",").flatMap { Scope(rawValue: $0) } userID = response?["user_id"] as? String teamName = response?["team_name"] as? String teamID = response?["team_id"] as? String diff --git a/Sources/SKServer/Model/RequestRoute.swift b/Sources/SKServer/Model/RequestRoute.swift index 4f71815..bc7ecf6 100644 --- a/Sources/SKServer/Model/RequestRoute.swift +++ b/Sources/SKServer/Model/RequestRoute.swift @@ -22,10 +22,9 @@ // THE SOFTWARE. public struct RequestRoute { - let path: String let middleware: Middleware - + public init(path: String, middleware: Middleware) { self.path = path self.middleware = middleware diff --git a/Sources/SKServer/Model/SKResponse.swift b/Sources/SKServer/Model/SKResponse.swift index 80691f9..f3341a9 100644 --- a/Sources/SKServer/Model/SKResponse.swift +++ b/Sources/SKServer/Model/SKResponse.swift @@ -25,25 +25,24 @@ import Foundation import SKCore public struct SKResponse { - let text: String let responseType: MessageResponseType let attachments: [Attachment]? - + public init(text: String, responseType: MessageResponseType = .inChannel, attachments: [Attachment]? = nil) { self.responseType = responseType self.text = text self.attachments = attachments } - + internal var json: [String: Any] { - var json = [String : Any]() + var json = [String: Any]() json["text"] = text json["response_type"] = responseType.rawValue json["attachments"] = attachments?.map({$0.dictionary}) return json } - + internal var data: Data? { return try? JSONSerialization.data(withJSONObject: self.json, options: []) } diff --git a/Sources/SKServer/Model/WebhookRequest.swift b/Sources/SKServer/Model/WebhookRequest.swift index 419ca9b..54f20ac 100644 --- a/Sources/SKServer/Model/WebhookRequest.swift +++ b/Sources/SKServer/Model/WebhookRequest.swift @@ -22,7 +22,6 @@ // THE SOFTWARE. public struct WebhookRequest { - public let token: String? public let teamID: String? public let teamDomain: String? @@ -35,7 +34,7 @@ public struct WebhookRequest { public let text: String? public let triggerWord: String? public let responseURL: String? - + internal init(request: [String: Any]?) { token = request?["token"] as? String teamID = request?["team_id"] as? String diff --git a/Sources/SKServer/SKServer.swift b/Sources/SKServer/SKServer.swift index b49ae9d..325a7a8 100644 --- a/Sources/SKServer/SKServer.swift +++ b/Sources/SKServer/SKServer.swift @@ -32,7 +32,6 @@ public protocol Middleware { } public final class SKServer { - internal let server: SlackKitServer public init?(server: SlackKitServer? = nil, responder: SlackKitResponder) { @@ -42,18 +41,18 @@ public final class SKServer { self.server = SwifterServer(responder: responder) } } - + public convenience init?(server: SlackKitServer? = nil, responder: SlackKitResponder, oauth: OAuthConfig) { var res = responder res.routes.append(SKServer.oauthRequestRoute(config: oauth)) self.init(server: server, responder: res) } - + private static func oauthRequestRoute(config: OAuthConfig) -> RequestRoute { let oauth = OAuthMiddleware(config: config) return RequestRoute(path: "/oauth", middleware: oauth) } - + public func start() { server.start() } diff --git a/Sources/SKServer/SlackKitResponder.swift b/Sources/SKServer/SlackKitResponder.swift index 3ac5393..4b353c0 100644 --- a/Sources/SKServer/SlackKitResponder.swift +++ b/Sources/SKServer/SlackKitResponder.swift @@ -25,18 +25,19 @@ import Dispatch #endif +//swiftlint:disable line_length public struct SlackKitResponder: Middleware { - + public var routes: [RequestRoute] - + public init(routes: [RequestRoute]) { self.routes = routes } - + public func respond(to request: (RequestType, ResponseType)) -> (RequestType, ResponseType) { if let form = request.0.formURLEncodedBody.first(where: {$0.name == "ssl_check"}), form.value == "1" { return (request.0, Response(200)) } - return routes.filter{$0.path == request.0.path}.first?.middleware.respond(to: (request.0, request.1)) ?? (request.0, Response(404)) + return routes.filter { $0.path == request.0.path }.first?.middleware.respond(to: (request.0, request.1)) ?? (request.0, Response(404)) } }