Skip to content
This repository has been archived by the owner on Oct 9, 2020. It is now read-only.

Commit

Permalink
Enable SwiftLint
Browse files Browse the repository at this point in the history
* Turn it on in Xcode
* Make some opinionated choices
* Fix all places where it was wrong
  • Loading branch information
RLovelett committed Aug 27, 2017
1 parent 9911972 commit 8de0110
Show file tree
Hide file tree
Showing 21 changed files with 204 additions and 121 deletions.
18 changes: 14 additions & 4 deletions .swiftlint.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,18 @@ included:
- VHS
- VHSTests
disabled_rules:
- nesting
- todo
- conditional_binding_cascade
- nesting
- todo
- conditional_binding_cascade
opt_in_rules:
- empty_count
- closure_end_indentation
- closure_parameter_position
- closure_spacing
- empty_count
- first_where
- force_unwrapping
- implicitly_unwrapped_optional
- sorted_imports
- switch_case_on_newline
trailing_comma:
mandatory_comma: true
2 changes: 2 additions & 0 deletions .travis.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ osx_image: xcode9
before_install:
- gem install xcpretty
- brew update
- brew outdated swiftlint || brew upgrade swiftlint
- brew outdated carthage || brew upgrade carthage
before_script:
# bootstrap the dependencies for the project
Expand All @@ -14,5 +15,6 @@ env:
- DESTINATION="platform=tvOS Simulator,name=Apple TV 1080p"
- DESTINATION="platform=iOS Simulator,name=iPhone 7,OS=11.0"
script:
- swiftlint --strict
- set -o pipefail # required to let xcpretty use the same exit code like xcodebuild
- xcodebuild test CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY="" -project VHS.xcodeproj -scheme VHS -destination "$DESTINATION" | xcpretty -c
15 changes: 15 additions & 0 deletions VHS.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -360,6 +360,7 @@
941A7BA91D43FF1100B699B7 /* Headers */,
941A7BAA1D43FF1100B699B7 /* Resources */,
941A7BEB1D44087800B699B7 /* CopyFiles */,
943ED71F1F52401D00CE3867 /* SwiftLint */,
);
buildRules = (
);
Expand Down Expand Up @@ -469,6 +470,20 @@
/* End PBXResourcesBuildPhase section */

/* Begin PBXShellScriptBuildPhase section */
943ED71F1F52401D00CE3867 /* 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";
};
948B28101D94DA0500B412C4 /* Copy Carthage Frameworks */ = {
isa = PBXShellScriptBuildPhase;
buildActionMask = 2147483647;
Expand Down
2 changes: 1 addition & 1 deletion VHS/Extensions/Dictionary.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ extension Dictionary {
init<S: Sequence>(_ sequence: S) where S.Iterator.Element == Element {
self = Dictionary(minimumCapacity: sequence.underestimatedCount)
for (key, value) in sequence {
let _ = self.updateValue(value, forKey: key)
_ = self.updateValue(value, forKey: key)
}
}
}
2 changes: 1 addition & 1 deletion VHS/Extensions/JSON.swift
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ extension JSON {
func encode() -> Any {
switch self {
case .object(let dictionary):
var accum = Dictionary<String, Any>(minimumCapacity: dictionary.count)
var accum: [String : Any] = Dictionary(minimumCapacity: dictionary.count)
for (key, value) in dictionary {
accum[key] = value.encode()
}
Expand Down
6 changes: 4 additions & 2 deletions VHS/Functions/ArgoDecoders.swift
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,8 @@ func decode(json: JSON) -> Decoded<URL> {
case .string(let urlString):
let decodedURL: Decoded<URL>? = URL(string: urlString).map(pure)
return decodedURL ?? .typeMismatch(expected: "URL", actual: json)
default: return .typeMismatch(expected: "URL", actual: json)
default:
return .typeMismatch(expected: "URL", actual: json)
}
}

Expand All @@ -60,6 +61,7 @@ func decodeHeader(from json: JSON?) -> Decoded<HTTPHeaders?> {
return .typeMismatch(expected: "[String : String]", actual: json)
}
return pure(headers)
default: return .typeMismatch(expected: "[String : String]", actual: json)
default:
return .typeMismatch(expected: "[String : String]", actual: json)
}
}
4 changes: 2 additions & 2 deletions VHS/Types/Cassette.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ public struct Cassette {
/// file-extension.
/// - throws: If the requested fixture cannot be found it throws `VCR.Error.missing`
public init(fixtureWithName name: String) throws {
let bundle = Bundle.allBundles.filter() { $0.bundlePath.hasSuffix(".xctest") }.first
let bundle = Bundle.allBundles.first(where: { $0.bundlePath.hasSuffix(".xctest") })
guard let resource = bundle?.url(forResource: name, withExtension: "json")
else { throw VCR.Error.missing(resource: name + ".json") }
try self.init(contentsOf: resource)
Expand All @@ -46,7 +46,7 @@ public struct Cassette {
switch decodedTracks {
case .success(let tracks):
self.tracks = tracks
case .failure(_):
case .failure:
throw VCR.Error.invalidFormat(resource: fixture.description)
}
}
Expand Down
32 changes: 21 additions & 11 deletions VHS/Types/Track.swift
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ extension Track.ContentType {
return str.data(using: .utf8)
case (.string(let str), .base64):
return Data(base64Encoded: str)
case (.object(_), .json):
case (.object, .json):
let obj = body.encode()
return try? JSONSerialization.data(withJSONObject: obj, options: [])
default:
Expand All @@ -133,16 +133,26 @@ extension Track.Request.Method {
init(ignoringCase rawValue: String?) {
let verb = rawValue?.lowercased() ?? "get"
switch verb {
case "options": self = .options
case "get": self = .get
case "head": self = .head
case "post": self = .post
case "put": self = .put
case "patch": self = .patch
case "delete": self = .delete
case "trace": self = .trace
case "connect": self = .connect
default: self = .get
case "options":
self = .options
case "get":
self = .get
case "head":
self = .head
case "post":
self = .post
case "put":
self = .put
case "patch":
self = .patch
case "delete":
self = .delete
case "trace":
self = .trace
case "connect":
self = .connect
default:
self = .get
}
}
}
Expand Down
12 changes: 7 additions & 5 deletions VHS/Types/VCR.swift
Original file line number Diff line number Diff line change
Expand Up @@ -113,7 +113,7 @@ public final class VCR: URLSession {

fileprivate let queue: OperationQueue

fileprivate let _delegate: URLSessionDelegate?
fileprivate weak var _delegate: URLSessionDelegate?

/// Create a `VCR` instance to playback recorded HTTP interactions from a `Cassette`.
///
Expand Down Expand Up @@ -264,13 +264,15 @@ extension VCR.PlaybackSequence.MatchType {
switch (thing(from: track.request.url), request.url.flatMap(thing(from:))) {
case let (.some(trackQueryItems), .some(rquestQueryItems)):
return trackQueryItems == rquestQueryItems
default: return false
default:
return false
}
case .headers:
switch (track.request.headers, request.allHTTPHeaderFields) {
case let (.some(trackHeaders), .some(requestHeaders)):
return trackHeaders == requestHeaders
default: return false
default:
return false
}
case .body:
switch (track.request.body, request.httpBody) {
Expand All @@ -290,7 +292,7 @@ extension VCR.Error : CustomErrorConvertible {

func userInfo() -> [String : String]? {
return [
NSLocalizedDescriptionKey: "Unable to find match for request."
NSLocalizedDescriptionKey: "Unable to find match for request.",
]
}

Expand All @@ -300,7 +302,7 @@ extension VCR.Error : CustomErrorConvertible {

func code() -> Int {
switch self {
case .recordNotFound(_):
case .recordNotFound:
return 404
default:
return 500
Expand Down
14 changes: 7 additions & 7 deletions VHS/Types/VCRTask.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ private func generate() -> AnyIterator<Int> {
var current = 0

return AnyIterator<Int> {
current = current + 1
current += 1
return current
}
}
Expand All @@ -29,7 +29,7 @@ final class VCRTask: URLSessionDataTask {

private let callback: VCRTaskCallback?

internal var delegate: URLSessionDataDelegate?
internal weak var delegate: URLSessionDataDelegate?

internal lazy var queue: OperationQueue = {
let q = OperationQueue()
Expand Down Expand Up @@ -76,22 +76,22 @@ final class VCRTask: URLSessionDataTask {

// Delegate Message #1
if let response = _response {
self.queue.addOperation() {
self.queue.addOperation {
let session = URLSession()
self.delegate?.urlSession?(session, dataTask: self, didReceive: response) { (_) in }
}
}

// Delegate Message #2
if let data = self.recordedResponse?.body {
self.queue.addOperation() {
self.queue.addOperation {
let session = URLSession()
self.delegate?.urlSession?(session, dataTask: self, didReceive: data)
}
}

// Delegate Message #3
self.queue.addOperation() {
self.queue.addOperation {
let session = URLSession()
self.delegate?.urlSession?(session, task: self, didCompleteWithError: self.error)
self.callback?(self.recordedResponse?.body, self.response, self.error)
Expand All @@ -118,12 +118,12 @@ final class VCRTask: URLSessionDataTask {
return request
}

private var _response: URLResponse? = nil
private var _response: URLResponse?
override var response: URLResponse? {
return _response
}

private let _taskIdentifier: Int = sharedSequence.next()!
private let _taskIdentifier: Int = sharedSequence.next() ?? 0
override var taskIdentifier: Int {
return _taskIdentifier
}
Expand Down
2 changes: 1 addition & 1 deletion VHSTests/Helpers/Argo+JSON+Test+Helpers.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import Foundation

// Idea taken from Venmo/DVR/Vinyl (thanks!)
private func testingBundle() -> Bundle? {
let bundleArray = Bundle.allBundles.filter() { $0.bundlePath.hasSuffix(".xctest") }
let bundleArray = Bundle.allBundles.filter { $0.bundlePath.hasSuffix(".xctest") }
guard bundleArray.count == 1 else { return nil }
return bundleArray.first
}
Expand Down
6 changes: 3 additions & 3 deletions VHSTests/Helpers/ExpectResponseFromDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ import XCTest
final class ExpectResponseFromDelegate: NSObject, URLSessionDataDelegate {

enum QueueType {
case DefaultQueue, MainQueue
case `default`, main
}

private let type: QueueType
Expand All @@ -31,9 +31,9 @@ final class ExpectResponseFromDelegate: NSObject, URLSessionDataDelegate {
didCompleteWithError error: Error?
) {
switch self.type {
case .DefaultQueue:
case .default:
XCTAssertFalse(Thread.isMainThread)
case .MainQueue:
case .main:
XCTAssertTrue(Thread.isMainThread)
}

Expand Down
7 changes: 4 additions & 3 deletions VHSTests/Helpers/URL+Arbitrary.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
// Created by Ryan Lovelett on 6/24/16.
// Copyright © 2016 Ryan Lovelett. All rights reserved.
//
// swiftlint:disable force_unwrapping

import Foundation
import SwiftCheck
Expand All @@ -27,7 +28,7 @@ private let schemeGen = Gen<Character>.one(of: [
digit,
Gen.pure("+"),
Gen.pure("-"),
Gen.pure(".")
Gen.pure("."),
]).proliferateNonEmpty
.map({ String.init($0) })
.suchThat({
Expand All @@ -46,12 +47,12 @@ private let hostGen = glue(parts: [hostname, Gen.pure("."), tld])

private let portGen = Gen<Int?>.frequency([
(1, Gen<Int?>.pure(nil)),
(3, Int.arbitrary.map({ abs($0) }).map(Optional.some))
(3, Int.arbitrary.map({ abs($0) }).map(Optional.some)),
])

private let pathPartGen: Gen<String> = Gen<Character>.one(of: [
alpha,
Gen.pure("/")
Gen.pure("/"),
]).proliferateNonEmpty
.map({ "/" + String.init($0) })

Expand Down
6 changes: 3 additions & 3 deletions VHSTests/Types/CassetteTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,14 @@
// Copyright © 2016 Ryan Lovelett. All rights reserved.
//

import XCTest
@testable import VHS
import XCTest

final class CassetteTests: XCTestCase {

func testMissingFixture() {
do {
let _ = try Cassette(fixtureWithName: "🏅👻🍻")
_ = try Cassette(fixtureWithName: "🏅👻🍻")
} catch VCR.Error.missing(let name) {
XCTAssertEqual(name, "🏅👻🍻.json")
} catch let error as NSError {
Expand All @@ -23,7 +23,7 @@ final class CassetteTests: XCTestCase {

func testMalformedFixture() {
do {
let _ = try Cassette(fixtureWithName: "dvr_multiple")
_ = try Cassette(fixtureWithName: "dvr_multiple")
} catch VCR.Error.invalidFormat(let name) {
XCTAssertTrue(name.contains("dvr_multiple.json"))
} catch let error as NSError {
Expand Down
10 changes: 6 additions & 4 deletions VHSTests/Types/PlaybackSequenceMatchTypeTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,19 +5,21 @@
// Created by Ryan Lovelett on 7/17/16.
// Copyright © 2016 Ryan Lovelett. All rights reserved.
//
// swiftlint:disable force_unwrapping
// swiftlint:disable implicitly_unwrapped_optional

import Argo
import XCTest
@testable import VHS
import XCTest

private let url = URL(string: "http://api.test2.com/this/is/a/path?one=two&three=4")!
private let baseComponents = URLComponents(url: url, resolvingAgainstBaseURL: true)!

// "8J+RiyBteSBuYW1lIGlzIFJ5YW4=" -> "👋 my name is Ryan"
private let json = JSON.string("8J+RiyBteSBuYW1lIGlzIFJ5YW4=")
private let reqHeader = ["username" : "cool"]
private let reqHeader = ["username": "cool"]
private let trackRequest = Track.Request(from: url, using: .head, with: reqHeader, sending: json)
private let resHeader = ["ETag" : "686897696a7c876b7e"]
private let resHeader = ["ETag": "686897696a7c876b7e"]
private let trackResponse = Track.Response(from: url, providing: 200, with: resHeader, sending: nil)
private let track = Track(request: trackRequest, response: trackResponse)

Expand Down Expand Up @@ -179,7 +181,7 @@ final class PlaybackSequenceMatchTypeHeaderTests: XCTestCase {
}

func testDifferentHeaders() {
self.request.allHTTPHeaderFields = [ "username" : "Cool" ]
self.request.allHTTPHeaderFields = [ "username": "Cool" ]
XCTAssertFalse(self.matcher.match(track, with: self.request))
}

Expand Down
Loading

0 comments on commit 8de0110

Please sign in to comment.