From f66bca9f72054ad07810678fb57b483118c5e210 Mon Sep 17 00:00:00 2001 From: "eric.marchand" Date: Wed, 10 Feb 2021 23:06:48 +0100 Subject: [PATCH] swiftlint autocorrect --- Clients/Ulysses.swift | 4 +- .../CallbackURLKitDemo/AppDelegate.swift | 10 ++-- .../CallbackURLKitDemo.swift | 16 +++--- .../CallbackURLKitDemo/ViewController.swift | 20 ++++--- Sources/CallbackURLKit.swift | 9 ++-- Sources/Client.swift | 14 ++--- Sources/Extensions.swift | 32 ++++++----- Sources/Manager.swift | 53 +++++++++---------- Sources/Request.swift | 3 +- 9 files changed, 74 insertions(+), 87 deletions(-) diff --git a/Clients/Ulysses.swift b/Clients/Ulysses.swift index 814c1eb..a2d74a1 100644 --- a/Clients/Ulysses.swift +++ b/Clients/Ulysses.swift @@ -85,7 +85,7 @@ public class Ulysses: Client { @param index Optional. The position of the new sheet in its parent group. Use 0 to make it the first sheet. Available since Ulysses 2.8 (API version 2). */ public func newSheet(text: String, group: String? = nil, format: String? = nil, index: String? = nil, onSuccess: SuccessCallback? = nil, onFailure: FailureCallback? = nil, onCancel: CancelCallback? = nil) throws { - + var parameters = ["text": text] if let group = group { parameters["group"] = group @@ -96,7 +96,7 @@ public class Ulysses: Client { if let index = index { parameters["index"] = index } - + try self.perform(action: "new-sheet", parameters: parameters, onSuccess: onSuccess, onFailure: onFailure, onCancel: onCancel) } diff --git a/SampleApp/CallbackURLKitDemo/AppDelegate.swift b/SampleApp/CallbackURLKitDemo/AppDelegate.swift index 6534f80..595a40c 100644 --- a/SampleApp/CallbackURLKitDemo/AppDelegate.swift +++ b/SampleApp/CallbackURLKitDemo/AppDelegate.swift @@ -18,7 +18,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { let manager = Manager.shared manager.callbackURLScheme = Manager.urlSchemes?.first manager[CallbackURLKitDemo.PrintActionString] = CallbackURLKitDemo.PrintAction - + return true } @@ -27,7 +27,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate { } } - + #elseif os(OSX) import Cocoa @@ -39,15 +39,15 @@ class AppDelegate: NSObject, NSApplicationDelegate { manager.registerToURLEvent() manager.callbackURLScheme = Manager.urlSchemes?.first manager[CallbackURLKitDemo.PrintActionString] = CallbackURLKitDemo.PrintAction - - manager["success"] = { (parameters, success, failure, cancel) in + + manager["success"] = { (_, success, _, _) in DispatchQueue.main.async { success(nil) } } } - + } #endif diff --git a/SampleApp/CallbackURLKitDemo/CallbackURLKitDemo.swift b/SampleApp/CallbackURLKitDemo/CallbackURLKitDemo.swift index 9cd98b8..804491b 100644 --- a/SampleApp/CallbackURLKitDemo/CallbackURLKitDemo.swift +++ b/SampleApp/CallbackURLKitDemo/CallbackURLKitDemo.swift @@ -11,7 +11,7 @@ import CallbackURLKit enum DemoError: FailureCallbackError { case noText - + var code: Int { switch self { case .noText: return 0 @@ -25,32 +25,32 @@ enum DemoError: FailureCallbackError { } open class CallbackURLKitDemo: Client { - + public static let instance = CallbackURLKitDemo() - + public init() { super.init(urlScheme: "callbackurlkit") } - + open func printMessage(_ message: String, onSuccess: SuccessCallback? = nil, onFailure: FailureCallback? = nil, onCancel: CancelCallback? = nil) throws { let parameters = ["text": message] try self.perform(action: CallbackURLKitDemo.PrintActionString, parameters: parameters, onSuccess: onSuccess, onFailure: onFailure, onCancel: onCancel) } - + public static let PrintActionString = "print" - public static let PrintAction: ActionHandler = { parameters, success, failed, cancel in + public static let PrintAction: ActionHandler = { parameters, success, failed, _ in if let text = parameters["text"] { print(text) let formatter = DateFormatter() formatter.dateStyle = .long formatter.timeStyle = .medium - + let dateString = formatter.string(from: Date()) success(["text": text, "date": dateString]) } else { failed(DemoError.noText) } } - + } diff --git a/SampleApp/CallbackURLKitDemo/ViewController.swift b/SampleApp/CallbackURLKitDemo/ViewController.swift index c860dc2..3e9caf2 100644 --- a/SampleApp/CallbackURLKitDemo/ViewController.swift +++ b/SampleApp/CallbackURLKitDemo/ViewController.swift @@ -17,7 +17,7 @@ import CallbackURLKit #endif extension ViewController { - + override func viewDidLoad() { super.viewDidLoad() } @@ -28,19 +28,19 @@ extension ViewController { try chrome.open(url: "http://www.google.com") } catch CallbackURLKitError.appWithSchemeNotInstalled(let scheme) { print("chrome(\(scheme)) not installed or not implement x-callback-url in current os") - + } catch CallbackURLKitError.callbackURLSchemeNotDefined { print("current app scheme not defined") } catch let e { print("exception \(e)") } } - + @IBAction func printAction(_ sender: AnyObject!) { do { try CallbackURLKitDemo.instance.printMessage( "a message %20 % = &toto=a", - onSuccess: { parameters in + onSuccess: { parameters in print("parameters \(String(describing: parameters))") }, onFailure: { error in @@ -49,20 +49,20 @@ extension ViewController { ) } catch CallbackURLKitError.appWithSchemeNotInstalled(let scheme) { print("\(scheme) not installed or not implement x-callback-url in current os") - + } catch CallbackURLKitError.callbackURLSchemeNotDefined { print("current app scheme not defined") } catch let e { print("exception \(e)") } } - + @IBAction func ulysseAuthorize(_ sender: AnyObject!) { let ulysses = Ulysses() do { try ulysses.authorize( appName: Manager.shared.callbackURLScheme ?? "callbackUrlKit", - onSuccess: { token in + onSuccess: { token in print("token \(token)") // try? ulysses.newSheet(text: "test") @@ -71,17 +71,15 @@ extension ViewController { print("\(error)") } ) - + } catch CallbackURLKitError.appWithSchemeNotInstalled(let scheme) { print("chrome(\(scheme)) not installed or not implement x-callback-url in current os") - + } catch CallbackURLKitError.callbackURLSchemeNotDefined { print("current app scheme not defined") } catch let e { print("exception \(e)") } } - } - diff --git a/Sources/CallbackURLKit.swift b/Sources/CallbackURLKit.swift index 5e9426b..39e78b6 100644 --- a/Sources/CallbackURLKit.swift +++ b/Sources/CallbackURLKit.swift @@ -35,10 +35,8 @@ public typealias SuccessCallback = (Parameters?) -> Void public typealias FailureCallback = (FailureCallbackError) -> Void public typealias CancelCallback = () -> Void - // MARK: global functions - // Perform an action on client application // - Parameter action: The action to perform. // - Parameter urlScheme: The urlScheme for application to apply action. @@ -70,7 +68,7 @@ public protocol FailureCallbackError: Error { var message: String {get} } extension FailureCallbackError { - public var XCUErrorParameters: Parameters { + public var XCUErrorParameters: Parameters { return [kXCUErrorCode: "\(self.code)", kXCUErrorMessage: self.message] } public var XCUErrorQuery: String { @@ -95,7 +93,7 @@ extension FailureCallbackError { } // Framework errors -public enum CallbackURLKitError : Error { +public enum CallbackURLKitError: Error { // It's seems that application with specified scheme has not installed case appWithSchemeNotInstalled(scheme: String) // Failed to create NSURL for request @@ -121,10 +119,9 @@ let kXCUErrorMessage = "errorMessage" // URL to open if the requested action is cancelled by the user. In the case where the target app offer the user the option to “cancel” the requested action, without a success or error result, this the the URL that should be opened to return the user to the source app. let kXCUCancel = "x-cancel" - // MARK: - framework strings let kResponse = "response" -let kResponseType = "responseType"; +let kResponseType = "responseType" let kRequestID = "requestID" let protocolKeys = [kResponse, kResponseType, kRequestID] diff --git a/Sources/Client.swift b/Sources/Client.swift index b114d5d..ea9089f 100644 --- a/Sources/Client.swift +++ b/Sources/Client.swift @@ -32,18 +32,18 @@ open class Client { open var urlScheme: String open var manager: Manager? - + public init(urlScheme: String) { self.urlScheme = urlScheme } - + open var appInstalled: Bool { - guard let url = URL(string:"\(self.urlScheme)://dummy") else { + guard let url = URL(string: "\(self.urlScheme)://dummy") else { return false } #if os(iOS) || os(tvOS) return UIApplication.shared.canOpenURL(url) - + #elseif os(OSX) return NSWorkspace.shared.urlForApplication(toOpen: url) != nil #endif @@ -60,11 +60,11 @@ open class Client { open func perform(action: Action, parameters: Parameters = [:], onSuccess: SuccessCallback? = nil, onFailure: FailureCallback? = nil, onCancel: CancelCallback? = nil) throws { - + let request = Request( ID: UUID().uuidString, client: self, action: action, parameters: parameters, - successCallback: onSuccess, failureCallback: onFailure, cancelCallback: onCancel + successCallback: onSuccess, failureCallback: onFailure, cancelCallback: onCancel ) let manager = self.manager ?? Manager.shared @@ -74,7 +74,7 @@ open class Client { // Return an error according to url, could be changed to fulfiled your need open func error(code: String?, message: String?) -> FailureCallbackError { let codeInt: Int - if let c = code, let ci = Int(c) { + if let c = code, let ci = Int(c) { codeInt = ci } else { codeInt = ErrorCode.missingErrorCode.rawValue diff --git a/Sources/Extensions.swift b/Sources/Extensions.swift index 165646a..fe8be35 100644 --- a/Sources/Extensions.swift +++ b/Sources/Extensions.swift @@ -26,8 +26,8 @@ import Foundation // MARK: String extension String { - var toQueryDictionary: [String : String] { - var result: [String : String] = [String : String]() + var toQueryDictionary: [String: String] { + var result: [String: String] = [String: String]() let pairs: [String] = self.components(separatedBy: "&") for pair in pairs { let comps: [String] = pair.components(separatedBy: "=") @@ -43,17 +43,17 @@ extension String { var queryEncodeRFC3986: String { let generalDelimitersToEncode = ":#[]@" // does not include "?" or "/" due to RFC 3986 - Section 3.4 let subDelimitersToEncode = "!$&'()*+,;=" - + var allowedCharacterSet = CharacterSet.urlQueryAllowed - allowedCharacterSet.remove(charactersIn : generalDelimitersToEncode + subDelimitersToEncode) - + allowedCharacterSet.remove(charactersIn: generalDelimitersToEncode + subDelimitersToEncode) + return self.addingPercentEncoding(withAllowedCharacters: allowedCharacterSet) ?? self } - + var queryEncode: String { return self.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) ?? self } - + var queryDecode: String { return self.removingPercentEncoding ?? self } @@ -73,31 +73,30 @@ extension Dictionary { } return parts.joined(separator: "&") as String } - + fileprivate func join(_ other: Dictionary) -> Dictionary { var joinedDictionary = Dictionary() - + for (key, value) in self { joinedDictionary.updateValue(value, forKey: key) } - + for (key, value) in other { joinedDictionary.updateValue(value, forKey: key) } - + return joinedDictionary } - + init(_ pairs: [Element]) { self.init() for (k, v) in pairs { self[k] = v } } - -} -func + (left: [K : V], right: [K : V]) -> [K : V] { return left.join(right) } +} +func + (left: [K: V], right: [K: V]) -> [K: V] { return left.join(right) } // MARK: NSURLComponents extension URLComponents { @@ -125,8 +124,7 @@ extension URLComponents { self.percentEncodedQuery = add } } - + } func &= (left: inout URLComponents, right: String) { left.addToQuery(right) } - diff --git a/Sources/Manager.swift b/Sources/Manager.swift index af34fb4..f932d7a 100644 --- a/Sources/Manager.swift +++ b/Sources/Manager.swift @@ -42,13 +42,13 @@ open class Manager { open var callbackURLScheme: String? open var callbackQueue: DispatchQueue = .main - + #if APP_EXTENSIONS /// In case of application extension, put your extensionContext here open var extensionContext: NSExtensionContext? - open var extensionContextCompletionHandler: ((Bool) -> Swift.Void)? = nil + open var extensionContextCompletionHandler: ((Bool) -> Swift.Void)? #endif - + /// Init public init(callbackURLScheme: String? = nil) { self.callbackURLScheme = callbackURLScheme @@ -79,11 +79,11 @@ open class Manager { let parameters = url.query?.toQueryDictionary ?? [:] let actionParameters = Manager.action(parameters: parameters) - + // is a reponse? if action == kResponse { if let requestID = parameters[kRequestID] /*as? RequestID*/, let request = requests[requestID] { - + if let rawType = parameters[kResponseType], let responseType = ResponseType(rawValue: rawType) { switch responseType { case .success: @@ -93,15 +93,14 @@ open class Manager { case .cancel: request.cancelCallback?() } - + requests.removeValue(forKey: requestID) } return true } return false - } - else if let actionHandler = actions[action] { // handle the action - let successCallback: SuccessCallback = { [weak self] returnParams in + } else if let actionHandler = actions[action] { // handle the action + let successCallback: SuccessCallback = { [weak self] returnParams in self?.openCallback(parameters, type: .success) { comp in if let query = returnParams?.queryString { comp &= query @@ -116,15 +115,14 @@ open class Manager { let cancelCallback: CancelCallback = { [weak self] in self?.openCallback(parameters, type: .cancel) } - + actionHandler(actionParameters, successCallback, failureCallback, cancelCallback) return true - } - else { + } else { // unknown action, notifiy it if let errorURLString = parameters[kXCUError], let url = URL(string: errorURLString) { let error = NSError.error(code: .notSupportedAction, failureReason: "\(action) not supported by \(Manager.appName)") - + var comp = URLComponents(url: url, resolvingAgainstBaseURL: false)! comp &= error.XCUErrorQuery if let newURL = comp.url { @@ -137,8 +135,8 @@ open class Manager { } return false } - - fileprivate func openCallback(_ parameters: [String : String], type: ResponseType, handler: ((inout URLComponents) -> Void)? = nil ) { + + fileprivate func openCallback(_ parameters: [String: String], type: ResponseType, handler: ((inout URLComponents) -> Void)? = nil ) { if let urlString = parameters[type.key], let url = URL(string: urlString), var comp = URLComponents(url: url, resolvingAgainstBaseURL: false) { handler?(&comp) @@ -154,7 +152,7 @@ open class Manager { public static func handleOpen(url: URL) -> Bool { return self.shared.handleOpen(url: url) } - + // MARK: - perform action with temporary client /// Perform an action on client application @@ -177,7 +175,7 @@ open class Manager { onSuccess: SuccessCallback? = nil, onFailure: FailureCallback? = nil, onCancel: CancelCallback? = nil) throws { try Manager.shared.perform(action: action, urlScheme: urlScheme, parameters: parameters, onSuccess: onSuccess, onFailure: onFailure, onCancel: onCancel) } - + /// Utility function to get URL schemes from Info.plist public static var urlSchemes: [String]? { guard let urlTypes = Bundle.main.infoDictionary?["CFBundleURLTypes"] as? [[String: AnyObject]] else { @@ -194,22 +192,21 @@ open class Manager { // MARK: internal - func send(request: Request) throws { if !request.client.appInstalled { throw CallbackURLKitError.appWithSchemeNotInstalled(scheme: request.client.urlScheme) } - + var query: Parameters = [:] query[kXCUSource] = Manager.appName - + if let scheme = self.callbackURLScheme { - + var xcuComponents = URLComponents() xcuComponents.scheme = scheme xcuComponents.host = kXCUHost xcuComponents.path = "/" + kResponse - + let xcuParams: Parameters = [kRequestID: request.ID] for reponseType in request.responseTypes { @@ -218,13 +215,12 @@ open class Manager { query[reponseType.key] = urlString } } - + if request.hasCallback { requests[request.ID] = request } - } - else if request.hasCallback { + } else if request.hasCallback { throw CallbackURLKitError.callbackURLSchemeNotDefined } let components = request.URLComponents(query) @@ -235,7 +231,7 @@ open class Manager { self.open(url: URL) } - static func action(parameters: [String : String]) -> [String : String] { + static func action(parameters: [String: String]) -> [String: String] { let resultArray: [(String, String)] = parameters.filter { tuple in return !(tuple.0.hasPrefix(kXCUPrefix) || protocolKeys.contains(tuple.0)) } @@ -254,8 +250,7 @@ open class Manager { #if APP_EXTENSIONS if let extensionContext = extensionContext { extensionContext.open(url, completionHandler: extensionContextCompletionHandler) - } - else { + } else { #if os(iOS) || os(tvOS) UIApplication.shared.open(url) #elseif os(OSX) @@ -289,7 +284,7 @@ extension Manager { @objc public func handleURLEvent(_ event: NSAppleEventDescriptor, withReply replyEvent: NSAppleEventDescriptor) { if let urlString = event.paramDescriptor(forKeyword: AEKeyword(keyDirectObject))?.stringValue, let url = URL(string: urlString) { - let _ = handleOpen(url: url) + _ = handleOpen(url: url) } } diff --git a/Sources/Request.swift b/Sources/Request.swift index a2ccb7c..2bc5aed 100644 --- a/Sources/Request.swift +++ b/Sources/Request.swift @@ -69,7 +69,7 @@ enum ResponseType: String { case success case error case cancel - + var key: String { switch self { case .success: @@ -81,4 +81,3 @@ enum ResponseType: String { } } } -