before_code
stringlengths
14
465k
reviewer_comment
stringlengths
16
64.5k
after_code
stringlengths
9
467k
diff_context
stringlengths
0
97k
file_path
stringlengths
5
226
comment_line
int32
0
26
language
stringclasses
37 values
quality_score
float32
0.07
1
comment_type
stringclasses
9 values
comment_length
int32
16
64.5k
before_lines
int32
1
17.2k
after_lines
int32
1
12.1k
is_negative
bool
2 classes
pr_title
stringlengths
1
308
pr_number
int32
1
299k
repo_name
stringclasses
533 values
repo_stars
int64
321
419k
repo_language
stringclasses
27 values
reviewer_username
stringlengths
0
39
author_username
stringlengths
2
39
// ResponseSerializationTests.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restricti...
Been thinking about this and I think it would be much better to throw an actual Alamofire error instead of the 3840 which can be misleading. Updated in 83b32faa.
// ResponseSerializationTests.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restricti...
@@ -266,8 +348,8 @@ class ResponseSerializationTestCase: BaseTestCase { XCTAssertNotNil(result.error, "result error should not be nil") if let error = result.error { - XCTAssertEqual(error.domain, Error.Domain, "error domain should match expected value") - XCTAssertEqual(error....
Tests/ResponseSerializationTests.swift
0
Swift
0.571
suggestion
162
592
592
false
Feature - Added 204 Support to Response Serializers
889
Alamofire/Alamofire
41,690
Swift
cnoon
cnoon
// ResponseSerialization.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, i...
I think writing this with parenthesis like this: ``` swift guard (response?.statusCode ?? -1) != 204 else { return .Success(NSData()) } ``` might look better. At a glace I got confused with the precedence of `??` and `!=`.
// ResponseSerialization.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, i...
@@ -145,11 +145,13 @@ extension Request { - returns: A data response serializer. */ public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> { - return ResponseSerializer { _, _, data, error in + return ResponseSerializer { _, response, data, error in ...
Source/ResponseSerialization.swift
0
Swift
0.857
suggestion
225
356
356
false
Feature - Added 204 Support to Response Serializers
889
Alamofire/Alamofire
41,690
Swift
cristeahub
cnoon
// ResponseSerialization.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, i...
If you aren't opposed to using an if, this will do what you want: ``` swift if let statusCode = response?.statusCode where statusCode == 204 { return .Success(NSData()) } ```
// ResponseSerialization.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, i...
@@ -145,11 +145,13 @@ extension Request { - returns: A data response serializer. */ public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> { - return ResponseSerializer { _, _, data, error in + return ResponseSerializer { _, response, data, error in ...
Source/ResponseSerialization.swift
0
Swift
0.714
suggestion
176
356
356
false
Feature - Added 204 Support to Response Serializers
889
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
// ResponseSerialization.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, i...
Yeah that's fair @jshier. Will change.
// ResponseSerialization.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, i...
@@ -145,11 +145,13 @@ extension Request { - returns: A data response serializer. */ public static func dataResponseSerializer() -> ResponseSerializer<NSData, NSError> { - return ResponseSerializer { _, _, data, error in + return ResponseSerializer { _, response, data, error in ...
Source/ResponseSerialization.swift
0
Swift
0.143
suggestion
39
356
356
false
Feature - Added 204 Support to Response Serializers
889
Alamofire/Alamofire
41,690
Swift
cnoon
cnoon
// ValidationTests.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, includi...
Was these left in from debugging?
// ValidationTests.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, includi...
@@ -208,6 +208,33 @@ class ContentTypeValidationTestCase: BaseTestCase { } } + func testThatValidationForRequestWithNoAcceptableContentTypeResponseSucceedsWhenNoDataIsReturned() { + // Given + let URLString = "https://httpbin.org/status/204" + let expectation = expectationWithDes...
Tests/ValidationTests.swift
0
Swift
0.214
bug
34
537
531
false
Feature - Content Type Validation on Empty Data
890
Alamofire/Alamofire
41,690
Swift
kylef
cnoon
// ValidationTests.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, includi...
Grrr...yes, my bad. Will remove.
// ValidationTests.swift // // Copyright (c) 2014–2015 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, includi...
@@ -208,6 +208,33 @@ class ContentTypeValidationTestCase: BaseTestCase { } } + func testThatValidationForRequestWithNoAcceptableContentTypeResponseSucceedsWhenNoDataIsReturned() { + // Given + let URLString = "https://httpbin.org/status/204" + let expectation = expectationWithDes...
Tests/ValidationTests.swift
0
Swift
0.143
suggestion
33
537
531
false
Feature - Content Type Validation on Empty Data
890
Alamofire/Alamofire
41,690
Swift
cnoon
cnoon
/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. public struct Timeline { /// The time the request was initialized. public let requestStartTime: NSDate /// The time the first bytes were received from or sent to the server. public let initialResponseTime: NSDa...
Perhaps we could additionally break serialization duration out into it's own property?
/// Responsible for computing the timing metrics for the complete lifecycle of a `Request`. public struct Timeline { /// The time the request was initialized. public let requestStartTime: CFAbsoluteTime /// The time the first bytes were received from or sent to the server. public let initialResponseTi...
@@ -0,0 +1,104 @@ +// Timeline.swift +// +// Copyright (c) 2014–2016 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Software without re...
Source/Timeline.swift
26
Swift
0.286
question
87
51
51
false
Feature - Request Timelines
1,054
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
Tells the delegate that the session has been invalidated. - parameter session: The session object that was invalidated. - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. */ public func URLSession(session: NSURLSession, ...
shouldn't the `?` be a `!` here as `sessionDidReceiveChallengeWithCompletion` must be `!=nil`? A way to let the compiler know that would be to use ``` objc if let didReceiveChallengeHandler == sessionDidReceiveChallengeWithCompletion { didReceiveChallengeHandler(session, challenge, completionHandler) return }...
// MARK: Delegate Methods /** Tells the delegate that the session has been invalidated. - parameter session: The session object that was invalidated. - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. */ ...
@@ -281,6 +284,11 @@ public class Manager { didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) { + guard sessionDidReceiveChallengeWithCompletion == nil else { + ...
Source/Manager.swift
26
Swift
1
performance
882
51
51
false
Feature - Override Closures with Completion
1,099
Alamofire/Alamofire
41,690
Swift
JoachimK
cnoon
Tells the delegate that the session has been invalidated. - parameter session: The session object that was invalidated. - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. */ public func URLSession(session: NSURLSession, ...
It will still be called due to the check above it. I generally stay away from all `!` usage unless it's absolutely necessary to do so.
// MARK: Delegate Methods /** Tells the delegate that the session has been invalidated. - parameter session: The session object that was invalidated. - parameter error: The error that caused invalidation, or nil if the invalidation was explicit. */ ...
@@ -281,6 +284,11 @@ public class Manager { didReceiveChallenge challenge: NSURLAuthenticationChallenge, completionHandler: ((NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)) { + guard sessionDidReceiveChallengeWithCompletion == nil else { + ...
Source/Manager.swift
26
Swift
0.5
suggestion
135
51
51
false
Feature - Override Closures with Completion
1,099
Alamofire/Alamofire
41,690
Swift
cnoon
cnoon
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders return Manager(configuration: configuration) }() /** Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. */ public static let defaultHTTPHeaders: [String: String] = { ...
@jshier thanks, but we miss the OS build version (like Build 13E230), right?
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders return Manager(configuration: configuration) }() /** Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. */ public static let defaultHTTPHeaders: [String: String] = { ...
@@ -61,14 +61,31 @@ public class Manager { let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" let version = info[kCFBundleVersionKey as String] as? String ?? "Unkno...
Source/Manager.swift
26
Swift
0.214
question
77
51
51
false
[1269] Update generation of the OS version part of the user agent to use non-localized sources.
1,292
Alamofire/Alamofire
41,690
Swift
onmyway133
jshier
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders return Manager(configuration: configuration) }() /** Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. */ public static let defaultHTTPHeaders: [String: String] = { ...
Yes, the build number is no longer going to be present because we cannot extract it in a non-localized manner.
configuration.HTTPAdditionalHeaders = Manager.defaultHTTPHeaders return Manager(configuration: configuration) }() /** Creates default values for the "Accept-Encoding", "Accept-Language" and "User-Agent" headers. */ public static let defaultHTTPHeaders: [String: String] = { ...
@@ -61,14 +61,31 @@ public class Manager { let executable = info[kCFBundleExecutableKey as String] as? String ?? "Unknown" let bundle = info[kCFBundleIdentifierKey as String] as? String ?? "Unknown" let version = info[kCFBundleVersionKey as String] as? String ?? "Unkno...
Source/Manager.swift
26
Swift
0.429
refactor
111
51
51
false
[1269] Update generation of the OS version part of the user agent to use non-localized sources.
1,292
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
// THE SOFTWARE. // import Foundation /// Responsible for sending a request and receiving the response and associated data from the server, as well as /// managing its underlying `URLSessionTask`. public class Request { /// A closure executed once a request has successfully completed in order to determine where ...
This may be overkill to wrap the change here in a lock, but I figure it's better safe than sorry. The only time this can ever change is when a data task is converted to a download task. Previously we were changing the subdelegate and not actually updating the request. That then created a mismatch between what the `Requ...
// THE SOFTWARE. // import Foundation /// Responsible for sending a request and receiving the response and associated data from the server, as well as /// managing its underlying `URLSessionTask`. public class Request { /// A closure executed once a request has successfully completed in order to determine where ...
@@ -35,7 +35,16 @@ public class Request { // MARK: Properties /// The delegate for the underlying task. - public let delegate: TaskDelegate + public internal(set) var delegate: TaskDelegate { + get { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + return ...
Source/Request.swift
26
Swift
0.643
suggestion
373
51
51
false
Feature - Moving SessionDelegate to Store Requests
1,391
Alamofire/Alamofire
41,690
Swift
cnoon
cnoon
// THE SOFTWARE. // import Foundation /// Responsible for sending a request and receiving the response and associated data from the server, as well as /// managing its underlying `URLSessionTask`. public class Request { /// A closure executed once a request has successfully completed in order to determine where ...
If we decide this is unnecessary, then it's really simple. We just need to remove the `taskDelegate` and the `taskDelegateLock` and revert this change while maintaining the `internal(set) var delegate` change.
// THE SOFTWARE. // import Foundation /// Responsible for sending a request and receiving the response and associated data from the server, as well as /// managing its underlying `URLSessionTask`. public class Request { /// A closure executed once a request has successfully completed in order to determine where ...
@@ -35,7 +35,16 @@ public class Request { // MARK: Properties /// The delegate for the underlying task. - public let delegate: TaskDelegate + public internal(set) var delegate: TaskDelegate { + get { + taskDelegateLock.lock() ; defer { taskDelegateLock.unlock() } + return ...
Source/Request.swift
26
Swift
0.643
suggestion
210
51
51
false
Feature - Moving SessionDelegate to Store Requests
1,391
Alamofire/Alamofire
41,690
Swift
cnoon
cnoon
// furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED ...
This is the most important part of this change. By allowing the underlying `task` to be swapped on the `TaskDelegate`, we can essentially defer the suspended queue operations while swapping out the `task` inside the same `Request`. This will allow us to create a new task from the `Request` and swap the task in the `Tas...
// furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED ...
@@ -33,7 +33,7 @@ public class TaskDelegate: NSObject { /// The serial operation queue used to execute all operations after the task completes. public let queue: OperationQueue - let task: URLSessionTask + var task: URLSessionTask
Source/TaskDelegate.swift
26
Swift
0.643
suggestion
332
51
51
false
Feature - Moving SessionDelegate to Store Requests
1,391
Alamofire/Alamofire
41,690
Swift
cnoon
cnoon
/// - parameter temporaryURL: The temporary destination URL of the data returned from the server. /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. /// - parameter resumeData: The resume data generated if the request was cancelled. /// ...
Why is this `AnyObject` and not `URLSessionTaskMetrics`?
// MARK: - /// Used to store all data associated with a serialized response of a download request. public struct DownloadResponse<Value> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? //...
@@ -154,6 +183,8 @@ public struct DownloadResponse<Value> { /// The timeline of the complete lifecycle of the request. public let timeline: Timeline + var _metrics: AnyObject?
Source/Response.swift
26
Swift
0.357
question
57
51
51
false
Feature - Task Metrics
1,492
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
/// - parameter temporaryURL: The temporary destination URL of the data returned from the server. /// - parameter destinationURL: The final destination URL of the data returned from the server if it was moved. /// - parameter resumeData: The resume data generated if the request was cancelled. /// ...
Just so the internal variable didn't need be behind an availability check?
// MARK: - /// Used to store all data associated with a serialized response of a download request. public struct DownloadResponse<Value> { /// The URL request sent to the server. public let request: URLRequest? /// The server's response to the URL request. public let response: HTTPURLResponse? //...
@@ -154,6 +183,8 @@ public struct DownloadResponse<Value> { /// The timeline of the complete lifecycle of the request. public let timeline: Timeline + var _metrics: AnyObject?
Source/Response.swift
26
Swift
0.214
question
75
51
51
false
Feature - Task Metrics
1,492
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
// // SessionManager.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, ...
It seems simpler to just treat `extractedAdaptError` as an optional, rather than having to check type and extract the value separately. Was there a reason for this pattern over just making the `extractedAdaptError` optional? Also, the `extractedAdaptError`, as it is now, seems misleading, because it's either the `extra...
// // SessionManager.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, ...
@@ -261,15 +265,31 @@ open class SessionManager { return request } catch { - return request(failedWith: error) + return request(originalRequest, failedWith: error) } } // MARK: Private - Request Implementation - private func request(failedWith erro...
Source/SessionManager.swift
0
Swift
0.786
refactor
359
827
859
false
Feature - Throwing Adapt Error Calls Retrier
1,682
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
// // TaskDelegate.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, in...
Could we pull the `else` down a line? ``` swift guard let destination = destination, let response = downloadTask.response as? HTTPURLResponse else { return } ```
// // TaskDelegate.swift // // Copyright (c) 2014-2016 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, in...
@@ -330,30 +330,29 @@ class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { didFinishDownloadingTo location: URL) { temporaryURL = location - - if let destination = destination { - let result = destination(location, downloadTask.response as! HTTPURLResponse) - ...
Source/TaskDelegate.swift
0
Swift
0.786
suggestion
172
449
451
false
Fix crash in TaskDelegate
1,723
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
// Given let fileURL = randomCachesFileURL let numberOfLines = 100 let urlString = "https://httpbin.org/stream/\(numberOfLines)" let destination: DownloadRequest.DownloadFileDestination = { _, _ in (fileURL, []) } let expectation = self.expectation(description: "...
Does this reproduce the crash reported in #1708? Assuming yes, but thought I'd ask just to make sure.
// Given let fileURL = randomCachesFileURL let numberOfLines = 100 let urlString = "https://httpbin.org/stream/\(numberOfLines)" let destination: DownloadRequest.DownloadFileDestination = { _, _ in (fileURL, []) } let expectation = self.expectation(description: "Cancelle...
@@ -101,6 +101,34 @@ class DownloadResponseTestCase: BaseTestCase { } } } + + func testCancelledDownloadRequest() { + // Given + let fileURL = randomCachesFileURL + let numberOfLines = 100 + let urlString = "https://httpbin.org/stream/\(numberOfLines)" + ...
Tests/DownloadTests.swift
26
Swift
0.357
bug
103
51
51
false
Fix crash in TaskDelegate
1,723
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
progress = Progress(totalUnitCount: 0) resumeData = nil } // MARK: URLSessionDownloadDelegate var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void...
The `destinationURL` assignment is a bit weird tucked in the middle of the other assignments. How about something like this? ``` swift let result = destination(location, response) let destinationURL = result.destinationURL let options = result.options self.destinationURL = destinationURL do { ```
progress = Progress(totalUnitCount: 0) resumeData = nil } // MARK: URLSessionDownloadDelegate var downloadTaskDidFinishDownloadingToURL: ((URLSession, URLSessionDownloadTask, URL) -> URL)? var downloadTaskDidWriteData: ((URLSession, URLSessionDownloadTask, Int64, Int64, Int64) -> Void...
@@ -330,30 +330,29 @@ class DownloadTaskDelegate: TaskDelegate, URLSessionDownloadDelegate { didFinishDownloadingTo location: URL) { temporaryURL = location - - if let destination = destination { - let result = destination(location, downloadTask.response as! HTTPURLResponse) - ...
Source/TaskDelegate.swift
26
Swift
0.786
suggestion
301
51
51
false
Fix crash in TaskDelegate
1,723
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
request.retryCount += 1 request.startTime = CFAbsoluteTimeGetCurrent() request.endTime = nil task.resume() return true } catch { request.delegate.error = error.underlyingAdaptError ?? error return false } } pr...
I'm unclear as to whether we should be executing this code on a separate queue or the same queue that originally executed the request. Wouldn't this logic create a new queue for every retry attempt? Perhaps at some point one of us should create a runtime diagram that outlines the various queues used...
request.retryCount += 1 request.startTime = CFAbsoluteTimeGetCurrent() request.endTime = nil task.resume() return true } catch { request.delegate.error = error.underlyingAdaptError ?? error return false } } pr...
@@ -874,12 +874,16 @@ open class SessionManager { return } - let retrySucceeded = strongSelf.retry(request) + DispatchQueue.utility.after(timeDelay) {
Source/SessionManager.swift
26
Swift
0.5
suggestion
307
37
41
false
Fix - SessionManager Retry Delay
1,864
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
object: strongSelf, userInfo: [Notification.Key.Task: task] ) strongSelf[task] = nil } guard let request = self[task], let sessionManager = sessionManager else { completeTask(session, task, error) return } ...
This rename doesn't seem necessary, as the previous name wasn't ambiguous (aren't all delays in time?). But it doesn't necessarily need to be changed.
object: strongSelf, userInfo: [Notification.Key.Task: task] ) strongSelf[task] = nil } guard let request = self[task], let sessionManager = sessionManager else { completeTask(session, task, error) return } ...
@@ -471,10 +471,10 @@ extension SessionDelegate: URLSessionTaskDelegate { /// If an error occurred and the retrier is set, asynchronously ask the retrier if the request /// should be retried. Otherwise, complete the task by notifying the task delegate. if let retrier = retrier, let error = er...
Source/SessionDelegate.swift
26
Swift
0.429
suggestion
150
51
51
false
Fix - SessionManager Retry Delay
1,864
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
// Then if let error = mappedResult.error { XCTAssertTrue(error is TransformError) } else { XCTFail("flatMap should catch the transformation error") } } func testThatFlatMapPreservesFailureError() { // Given struct ResultError: Error {} ...
How about: `// MARK: - Error Mapping Tests`?
// Then if let error = mappedResult.error { XCTAssertTrue(error is TransformError) } else { XCTFail("flatMap should catch the transformation error") } } func testThatFlatMapPreservesFailureError() { // Given struct ResultError: Error {} ...
@@ -277,4 +280,194 @@ class ResultTestCase: BaseTestCase { XCTFail("flatMap should preserve the failure error") } } + + // MARK: - map/flatMapError Tests
Tests/ResultTests.swift
26
Swift
0.357
question
44
51
51
false
Add additional functional functionality to Result.
2,135
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
var string = "success" // When result.withError { string = "\(type(of: $0))" } // Then XCTAssertEqual(string, "(ResultError #1)") } func testWithErrorDoesNotExecuteWhenSuccess() { // Given let result: Result<String> = .success("succe...
How about: `// MARK: - If Success or Failure Tests`?
let result: Result<String> = .failure(ResultError()) var string = "success" // When result.withError { string = "\(type(of: $0))" } // Then #if swift(>=3.2) XCTAssertEqual(string, "ResultError #1") #else XCTAssertEqual(string, "(ResultErr...
@@ -277,4 +280,194 @@ class ResultTestCase: BaseTestCase { XCTFail("flatMap should preserve the failure error") } } + + // MARK: - map/flatMapError Tests + + func testMapErrorTransformsErrorValue() { + // Given + struct ResultError: Error {} + struct OtherEr...
Tests/ResultTests.swift
26
Swift
0.357
bug
52
51
51
false
Add additional functional functionality to Result.
2,135
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
} else { XCTFail("mapError should transform error value") } } func testFlatMapErrorCapturesThrownError() { // Given struct ResultError: Error {} struct OtherError: Error { let error: Error init(error: Error) throws { throw ThrownEr...
How about: `// MARK: - With Value or Error Tests`?
} else { XCTFail("mapError should transform error value") } } func testFlatMapErrorCapturesThrownError() { // Given struct ResultError: Error {} struct OtherError: Error { let error: Error init(error: Error) throws { throw ThrownEr...
@@ -277,4 +280,194 @@ class ResultTestCase: BaseTestCase { XCTFail("flatMap should preserve the failure error") } } + + // MARK: - map/flatMapError Tests + + func testMapErrorTransformsErrorValue() { + // Given + struct ResultError: Error {} + struct OtherEr...
Tests/ResultTests.swift
26
Swift
0.5
question
50
51
51
false
Add additional functional functionality to Result.
2,135
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
} func testIfFailureDoesNotExecuteWhenSuccess() { // Given let result: Result<String> = .success("success") var string = "success" // When result.ifFailure { string = "failure" } // Then XCTAssertEqual(string, "success") } ...
How about the following formatting to stay consistent with the rest of the library? ```swift let endResult = result .map { _ in "second" } .flatMap { _ in "third" } .withValue { if $0 == "third" { string = "fourth" } } .ifSuccess { success = true } ```
var string = "success" // When result.ifFailure { string = "failure" } // Then XCTAssertEqual(string, "failure") } func testIfFailureDoesNotExecuteWhenSuccess() { // Given let result: Result<String> = .success("success") var ...
@@ -277,4 +280,194 @@ class ResultTestCase: BaseTestCase { XCTFail("flatMap should preserve the failure error") } } + + // MARK: - map/flatMapError Tests + + func testMapErrorTransformsErrorValue() { + // Given + struct ResultError: Error {} + struct OtherEr...
Tests/ResultTests.swift
26
Swift
0.786
question
277
34
44
false
Add additional functional functionality to Result.
2,135
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
// When result.ifFailure { string = "failure" } // Then XCTAssertEqual(string, "failure") } func testIfFailureDoesNotExecuteWhenSuccess() { // Given let result: Result<String> = .success("success") var string = "success" // W...
`// MARK: - Functional Chaining Tests`?
func testIfFailureExecutesWhenFailure() { // Given struct ResultError: Error {} let result: Result<String> = .failure(ResultError()) var string = "success" // When result.ifFailure { string = "failure" } // Then XCTAssertEqual(st...
@@ -277,4 +280,194 @@ class ResultTestCase: BaseTestCase { XCTFail("flatMap should preserve the failure error") } } + + // MARK: - map/flatMapError Tests + + func testMapErrorTransformsErrorValue() { + // Given + struct ResultError: Error {} + struct OtherEr...
Tests/ResultTests.swift
26
Swift
0.214
question
39
39
49
false
Add additional functional functionality to Result.
2,135
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
struct ResultError: Error {} let result: Result<String> = .failure(ResultError()) var string = "failure" // When result.withValue { string = $0 } // Then XCTAssertEqual(string, "failure") } func testWithErrorExecutesWhenFailure() { ...
Could we dedent the pound defines?
struct ResultError: Error {} let result: Result<String> = .failure(ResultError()) var string = "failure" // When result.withValue { string = $0 } // Then XCTAssertEqual(string, "failure") } func testWithErrorExecutesWhenFailure() { ...
@@ -277,4 +280,204 @@ class ResultTestCase: BaseTestCase { XCTFail("flatMap should preserve the failure error") } } + + // MARK: - Error Mapping Tests + + func testMapErrorTransformsErrorValue() { + // Given + struct ResultError: Error {} + struct OtherError...
Tests/ResultTests.swift
26
Swift
0.143
question
34
51
51
false
Add additional functional functionality to Result.
2,135
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex let range = startIndex..<endIndex let substring = string.substring(with: range) escaped += substring.addingPercentEncoding(withAllowedCharacters: allow...
To keep formatting consistent across Alamofire, how about? ```swift } #if swift(>=4.0) return components.map { "\($0.0)=\($0.1)" }.joined(separator: "&") #else return components.map { "\($0)=\($1)" }.joined(separator: "&") #endif ``` Where the pound defines are demented one tab.
let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex let range = startIndex..<endIndex let substring = string.substring(with: range) escaped += substring.addingPercentEncoding(withAllowedCharacters: allow...
@@ -241,8 +241,11 @@ public struct URLEncoding: ParameterEncoding { let value = parameters[key]! components += queryComponents(fromKey: key, value: value) } - + #if swift(>=4.0) + return components.map { "\($0.0)=\($0.1)" }.joined(separator: "&") + #else ...
Source/ParameterEncoding.swift
26
Swift
0.786
suggestion
306
51
51
false
Add Swift 4 Support
2,163
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
/// directly for any ad hoc requests. open static let `default`: SessionManager = { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders return SessionManager(configuration: configuration) }() /// Creates de...
How about? ```swift // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 #if swift(>=4.0) let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated().map { enumeratedLanguage in let (index, languageCode) = enumeratedLanguage let quality = 1.0 - ...
/// directly for any ad hoc requests. open static let `default`: SessionManager = { let configuration = URLSessionConfiguration.default configuration.httpAdditionalHeaders = SessionManager.defaultHTTPHeaders return SessionManager(configuration: configuration) }() /// Creates de...
@@ -58,10 +58,18 @@ open class SessionManager { let acceptEncoding: String = "gzip;q=1.0, compress;q=0.5" // Accept-Language HTTP Header; see https://tools.ietf.org/html/rfc7231#section-5.3.5 + #if swift(>=4.0) + let acceptLanguage = Locale.preferredLanguages.prefix(6).enumerated()...
Source/SessionManager.swift
26
Swift
0.857
question
672
51
51
false
Add Swift 4 Support
2,163
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
var response: DataResponse<Any>? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).responseJSON { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil...
How about? ```swift if let responseDictionary = response?.result.value as? [String: Any], let args = responseDictionary["args"] as? [String: String] { XCTAssertEqual(args, ["foo": "bar"], "args should match parameters") ``` Also note dictionaries are `[String: String]` and not `[String : Strin...
var response: DataResponse<Any>? // When Alamofire.request(urlString, parameters: ["foo": "bar"]).responseJSON { resp in response = resp expectation.fulfill() } waitForExpectations(timeout: timeout, handler: nil) // Then XCTAssertNotNil...
@@ -272,13 +272,13 @@ class ResponseJSONTestCase: BaseTestCase { XCTAssertNotNil(response?.data) XCTAssertEqual(response?.result.isSuccess, true) - if #available(iOS 10.0, macOS 10.12, tvOS 10.0, *) { + if #available(iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *) { XCTA...
Tests/ResponseTests.swift
26
Swift
0.857
question
324
51
51
false
Add Swift 4 Support
2,163
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
} } } // MARK: - class SessionManagerConfigurationHeadersTestCase: BaseTestCase { enum ConfigurationType { case `default`, ephemeral, background } func testThatDefaultConfigurationHeadersAreSentWithRequest() { // Given, When, Then executeAuthorizationHeaderTest(for: .d...
How about? ```swift #if os(macOS) func testThatBackgroundConfigurationHeadersAreSentWithRequest() { // Given, When, Then executeAuthorizationHeaderTest(for: .background) } #endif ```
} } } // MARK: - class SessionManagerConfigurationHeadersTestCase: BaseTestCase { enum ConfigurationType { case `default`, ephemeral, background } func testThatDefaultConfigurationHeadersAreSentWithRequest() { // Given, When, Then executeAuthorizationHeaderTest(for: .d...
@@ -787,12 +787,12 @@ class SessionManagerConfigurationHeadersTestCase: BaseTestCase { // Given, When, Then executeAuthorizationHeaderTest(for: .ephemeral) } - -// ⚠️ This test has been removed as a result of rdar://26870455 in Xcode 8 Seed 1 -// func testThatBackgroundConfigurationHeadersA...
Tests/SessionManagerTests.swift
26
Swift
0.786
security
216
51
51
false
Add Swift 4 Support
2,163
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
return SessionManager(configuration: configuration) }() let expectation = self.expectation(description: "request should complete successfully") var response: DataResponse<Any>? // When manager.request("https://httpbin.org/headers") .responseJSON { clos...
`[String : Any]` -> `[String: Any]`.
return SessionManager(configuration: configuration) }() let expectation = self.expectation(description: "request should complete successfully") var response: DataResponse<Any>? // When manager.request("https://httpbin.org/headers") .responseJSON { clos...
@@ -840,10 +840,9 @@ class SessionManagerConfigurationHeadersTestCase: BaseTestCase { XCTAssertNotNil(response.data, "data should not be nil") XCTAssertTrue(response.result.isSuccess, "result should be a success") - // The `as NSString` cast is necessary due to a compiler bug. See...
Tests/SessionManagerTests.swift
26
Swift
0.214
suggestion
36
39
39
false
Add Swift 4 Support
2,163
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
response = defaultResponse.response data = defaultResponse.data error = defaultResponse.error expectation.fulfill() } case .failure: expectation.fulfill() } }) waitFo...
Can we dedent the pound defines?
upload.response { defaultResponse in request = defaultResponse.request response = defaultResponse.response data = defaultResponse.data error = defaultResponse.error expectation.fu...
@@ -533,69 +533,66 @@ class UploadMultipartFormDataTestCase: BaseTestCase { } } -// ⚠️ This test has been removed as a result of rdar://26870455 in Xcode 8 Seed 1 -// func testThatUploadingMultipartFormDataOnBackgroundSessionWritesDataToFileToAvoidCrash() { -// // Given -// let manag...
Tests/UploadTests.swift
26
Swift
0.071
question
32
51
51
false
Add Swift 4 Support
2,163
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
var data: Data? var error: Error? var streamingFromDisk: Bool? // When manager.upload(multipartFormData: { multipartFormData in multipartFormData.append(french, withName: "french") multipartFormData.append(japanese, withName: "japanese") }, to: ur...
How about? ```swift // When manager.upload( multipartFormData: { multipartFormData in multipartFormData.append(french, withName: "french") multipartFormData.append(japanese, withName: "japanese") }, to: urlString, encodingCompletion: { result in switch result { ...
var data: Data? var error: Error? var streamingFromDisk: Bool? // When manager.upload( multipartFormData: { multipartFormData in multipartFormData.append(french, withName: "french") multipartFormData.append(japanese, withName: "japanes...
@@ -533,69 +533,66 @@ class UploadMultipartFormDataTestCase: BaseTestCase { } } -// ⚠️ This test has been removed as a result of rdar://26870455 in Xcode 8 Seed 1 -// func testThatUploadingMultipartFormDataOnBackgroundSessionWritesDataToFileToAvoidCrash() { -// // Given -// let manag...
Tests/UploadTests.swift
26
Swift
0.929
bug
824
51
51
false
Add Swift 4 Support
2,163
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
open let queue: OperationQueue /// The data returned by the server. public var data: Data? { return nil } /// The error generated throughout the lifecyle of the task. public var error: Error? private var _task: URLSessionTask? { didSet { reset() } } var task: URLSessionTas...
Could we pull the `private` properties down underneath the `internal` properties? ```swift public var error: Error? var task: URLSessionTask? { set { taskLock.lock(); defer { taskLock.unlock() } _task = newValue } get { taskLock.lock(); defer { taskLock.unlock() } ...
open let queue: OperationQueue /// The data returned by the server. public var data: Data? { return nil } /// The error generated throughout the lifecyle of the task. public var error: Error? var task: URLSessionTask? { set { taskLock.lock(); defer { taskLock.unlock() } ...
@@ -38,19 +38,30 @@ open class TaskDelegate: NSObject { /// The error generated throughout the lifecyle of the task. public var error: Error? - - var task: URLSessionTask? { + + private var _task: URLSessionTask? { didSet { reset() } } - + var task: URLSessionTask? { + set ...
Source/TaskDelegate.swift
26
Swift
1
security
600
51
51
false
Add an NSLock for the task delegate’s task.
2,190
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { for credential in...
I don't believe you need the `before:` call anymore, as `..<` does essentially the same thing.
port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { for credential in...
@@ -308,7 +308,12 @@ extension Request: CustomDebugStringConvertible { let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } - components.append("-b \"\(string.substring(to: strin...
Source/Request.swift
26
Swift
0.357
suggestion
94
51
51
false
Fixed `substring` API warnings for Swift 3.2 and up
2,240
Alamofire/Alamofire
41,690
Swift
jshier
htinlinn
let protectionSpace = URLProtectionSpace( host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialSto...
No need for extra whitespace around the `#if` checks. We prefer to keep the whitespace the same as if there was no check in the first place.
let protectionSpace = URLProtectionSpace( host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialSto...
@@ -308,7 +308,12 @@ extension Request: CustomDebugStringConvertible { let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } - components.append("-b \"\(string.substring(to: strin...
Source/Request.swift
26
Swift
0.571
suggestion
140
51
51
false
Fixed `substring` API warnings for Swift 3.2 and up
2,240
Alamofire/Alamofire
41,690
Swift
jshier
htinlinn
port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { for credential in...
Please unindent the code inside the `#if` check to match out style.
port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { for credential in...
@@ -308,7 +308,12 @@ extension Request: CustomDebugStringConvertible { let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } - components.append("-b \"\(string.substring(to: strin...
Source/Request.swift
26
Swift
0.357
style
67
51
51
false
Fixed `substring` API warnings for Swift 3.2 and up
2,240
Alamofire/Alamofire
41,690
Swift
jshier
htinlinn
host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { ...
`#if` statements and the code should be at the same level.
host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialStorage.credentials(for: protectionSpace)?.values { ...
@@ -308,7 +308,12 @@ extension Request: CustomDebugStringConvertible { let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } + + #if swift(>=3.2)
Source/Request.swift
26
Swift
0.429
suggestion
58
51
51
false
Fixed `substring` API warnings for Swift 3.2 and up
2,240
Alamofire/Alamofire
41,690
Swift
jshier
htinlinn
let protectionSpace = URLProtectionSpace( host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialSto...
Sorry, like I said before, please remove the newlines before and after all version checks. Basically, where there are version checks, the whitespace should match what was there before. Same indentation level, same newlines.
let protectionSpace = URLProtectionSpace( host: host, port: url.port ?? 0, protocol: url.scheme, realm: host, authenticationMethod: NSURLAuthenticationMethodHTTPBasic ) if let credentials = credentialSto...
@@ -308,7 +308,12 @@ extension Request: CustomDebugStringConvertible { let cookies = cookieStorage.cookies(for: url), !cookies.isEmpty { let string = cookies.reduce("") { $0 + "\($1.name)=\($1.value);" } +
Source/Request.swift
26
Swift
0.5
nitpick
223
51
51
false
Fixed `substring` API warnings for Swift 3.2 and up
2,240
Alamofire/Alamofire
41,690
Swift
jshier
htinlinn
fileprivate func lock() { let result = pthread_mutex_lock(&mutex) assert(result == 0, "Failed to lock mutex") } fileprivate func unlock() { let result = pthread_mutex_unlock(&mutex) assert(result == 0, "Failed to unlock mutex") } /// Execute a value producing closur...
I think you might be able to implement both `around` functions in a protocol extension that leverages the `lock` and `unlock` APIs.
return closure() } } // MARK: - /// A `pthread_mutex` wrapper, inspired by ProcedureKit. final class Mutex: Lock { private var mutex = pthread_mutex_t() init() { let result = pthread_mutex_init(&mutex, nil) precondition(result == 0, "Failed to create pthread mutex") } dei...
@@ -0,0 +1,176 @@ +// +// Mutex+Protector.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Sof...
Source/Mutex+Protector.swift
26
Swift
0.5
suggestion
131
51
51
false
Refactor Lock Usage
2,290
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
/// - Returns: The value the closure generated. func around<T>(_ closure: () -> T) -> T { lock(); defer { unlock() } return closure() } /// Execute a closure while aquiring the mutex. /// /// - Parameter closure: The closure to run. func around(_ closure: () -> Voi...
`public` on an `internal` class?
} deinit { let result = pthread_mutex_destroy(&mutex) assert(result == 0, "Failed to destroy mutex") } fileprivate func lock() { let result = pthread_mutex_lock(&mutex) assert(result == 0, "Failed to lock mutex") } fileprivate func unlock() { let result...
@@ -0,0 +1,176 @@ +// +// Mutex+Protector.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Sof...
Source/Mutex+Protector.swift
26
Swift
0.214
question
32
51
51
false
Refactor Lock Usage
2,290
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
/// /// - Parameter closure: The closure to run. /// - Returns: The value the closure generated. func around<T>(_ closure: () -> T) -> T { lock(); defer { unlock() } return closure() } /// Execute a closure while aquiring the mutex. /// /// - Parameter closure:...
I need to read up on `os_unfair_lock` a bit.
let result = pthread_mutex_init(&mutex, nil) precondition(result == 0, "Failed to create pthread mutex") } deinit { let result = pthread_mutex_destroy(&mutex) assert(result == 0, "Failed to destroy mutex") } fileprivate func lock() { let result = pthread_mutex_l...
@@ -0,0 +1,176 @@ +// +// Mutex+Protector.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Sof...
Source/Mutex+Protector.swift
26
Swift
0.214
suggestion
44
51
51
false
Refactor Lock Usage
2,290
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
lock(); defer { unlock() } return closure() } } /// An `os_unfair_lock` wrapper. @available (iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *) final class UnfairLock: Lock { private var unfairLock = os_unfair_lock() public init() { } fileprivate func lock() { os_unfair_lock_lo...
Could we get some `// MARK: -` separators between the types?
} fileprivate func unlock() { let result = pthread_mutex_unlock(&mutex) assert(result == 0, "Failed to unlock mutex") } } // MARK: - /// An `os_unfair_lock` wrapper. @available (iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *) final class UnfairLock: Lock { private var unfairLock = o...
@@ -0,0 +1,176 @@ +// +// Mutex+Protector.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Sof...
Source/Mutex+Protector.swift
26
Swift
0.571
question
60
51
51
false
Refactor Lock Usage
2,290
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
return closure() } /// Execute a closure while aquiring the lock. /// /// - Parameter closure: The closure to run. func around(_ closure: () -> Void) { lock(); defer { unlock() } return closure() } } /// A thread-safe wrapper around a value. final class Protector<T> { ...
Would `value` make more sense than `ward`? Especially since you have an `unsafeValue` API to `ward`?
// MARK: - /// A thread-safe wrapper around a value. final class Protector<T> { private let lock: Lock = { if #available(iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *) { return UnfairLock() } else { return Mutex() } }() private var value: T init(_ va...
@@ -0,0 +1,176 @@ +// +// Mutex+Protector.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Sof...
Source/Mutex+Protector.swift
26
Swift
0.5
question
100
51
51
false
Refactor Lock Usage
2,290
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
} fileprivate func unlock() { os_unfair_lock_unlock(&unfairLock) } /// Execute a value producing closure while aquiring the lock. /// /// - Parameter closure: The closure to run. /// - Returns: The value the closure generated. func around<T>(_ closure: () -> T) -> T {...
I've built similar abstractions before that were named `Locker` instead of `Protector`. Not really sure which one I prefer more. Thoughts?
public init() { } fileprivate func lock() { os_unfair_lock_lock(&unfairLock) } fileprivate func unlock() { os_unfair_lock_unlock(&unfairLock) } } // MARK: - /// A thread-safe wrapper around a value. final class Protector<T> { private let lock: Lock = { if #available(...
@@ -0,0 +1,176 @@ +// +// Mutex+Protector.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Sof...
Source/Mutex+Protector.swift
26
Swift
0.571
refactor
138
51
51
false
Refactor Lock Usage
2,290
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
func around(_ closure: () -> Void) { lock(); defer { unlock() } return closure() } } /// A thread-safe wrapper around a value. final class Protector<T> { private let lock: Lock = { if #available(iOS 10.0, macOS 10.12, tvOS 10.0, watchOS 3.0, *) { return UnfairLock() ...
Should we really name this `unsafe` when it's actually safe for direct reads and writes? Seems a bit scary when used throughout the codebase. Makes me think it's unsafe since it's part of the API.
return UnfairLock() } else { return Mutex() } }() private var value: T init(_ value: T) { self.value = value } /// The contained value. Unsafe for anything more than direct read or write. var directValue: T { get { return lock.around { v...
@@ -0,0 +1,176 @@ +// +// Mutex+Protector.swift +// +// Copyright (c) 2014-2017 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Sof...
Source/Mutex+Protector.swift
26
Swift
0.571
question
196
51
51
false
Refactor Lock Usage
2,290
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
/// executing all operations attached to the serial operation queue upon task completion. open class TaskDelegate: NSObject { // MARK: Properties /// The serial operation queue used to execute all operations after the task completes. open let queue: OperationQueue /// The data returned by the server....
Is the `protected` prefix just meant to make it more clear throughout the code that it's actually wrapped in a `Protector`? Is it overkill?
/// executing all operations attached to the serial operation queue upon task completion. open class TaskDelegate: NSObject { // MARK: Properties /// The serial operation queue used to execute all operations after the task completes. open let queue: OperationQueue /// The data returned by the server....
@@ -41,29 +41,23 @@ open class TaskDelegate: NSObject { var task: URLSessionTask? { set { - taskLock.lock(); defer { taskLock.unlock() } - _task = newValue - } - get { - taskLock.lock(); defer { taskLock.unlock() } - return _task + pro...
Source/TaskDelegate.swift
26
Swift
0.5
question
139
51
51
false
Refactor Lock Usage
2,290
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to /// `application/x-www-form-urlencoded; charset=utf-8`. /// /// There is no published specification for how to encode collection types. By default the convention of appending /// `[]` to the key for array values (`foo[]=1&foo[]=2`),...
I think having `Array` instead of array makes it a bit more clear.
/// The `Content-Type` HTTP header field of an encoded request with HTTP body is set to /// `application/x-www-form-urlencoded; charset=utf-8`. /// /// There is no published specification for how to encode collection types. By default the convention of appending /// `[]` to the key for array values (`foo[]=1&foo[]=2`),...
@@ -82,6 +88,23 @@ public struct URLEncoding: ParameterEncoding { case methodDependent, queryString, httpBody } + /// Configures how array parameters are encoded.
Source/ParameterEncoding.swift
26
Swift
0.429
suggestion
66
51
51
false
Add configurable parameter handling to URLEncoding.
2,431
Alamofire/Alamofire
41,690
Swift
jshier
heiberg
// MARK: Helper Types /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the /// resulting URL request. /// /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` /// ...
I think ticks around `1` and `0` are appropriate here.
// MARK: Helper Types /// Defines whether the url-encoded query string is applied to the existing query string or HTTP body of the /// resulting URL request. /// /// - methodDependent: Applies encoded query string result to existing query string for `GET`, `HEAD` and `DELETE` /// ...
@@ -82,6 +88,23 @@ public struct URLEncoding: ParameterEncoding { case methodDependent, queryString, httpBody } + /// Configures how array parameters are encoded. + /// + /// - brackets: An empty set of square brackets is appended to the key for every value. + /// T...
Source/ParameterEncoding.swift
26
Swift
0.357
suggestion
54
51
51
false
Add configurable parameter handling to URLEncoding.
2,431
Alamofire/Alamofire
41,690
Swift
jshier
heiberg
/// Configures how boolean parameters are encoded. /// /// - numeric: Encode `true` as 1 and `false` as 0. This is the default behavior. /// - literal: Encode `true` and `false` as string literals. public enum BoolEncoding { case numeric, literal } // MARK: Propertie...
It's a bit clearer to just say "The encoding to use for `Array` parameters."
switch self { case .brackets: return "\(key)[]" case .noBrackets: return key } } } /// Configures how `Bool` parameters are encoded. /// /// - numeric: Encode `true` as `1` and `false` as `0`. This is the de...
@@ -99,15 +122,24 @@ public struct URLEncoding: ParameterEncoding { /// The destination defining where the encoded query string is to be applied to the URL request. public let destination: Destination + /// The convention for encoding array parameters.
Source/ParameterEncoding.swift
26
Swift
0.429
suggestion
76
51
51
false
Add configurable parameter handling to URLEncoding.
2,431
Alamofire/Alamofire
41,690
Swift
jshier
heiberg
public enum BoolEncoding { case numeric, literal } // MARK: Properties /// Returns a default `URLEncoding` instance. public static var `default`: URLEncoding { return URLEncoding() } /// Returns a `URLEncoding` instance with a `.methodDependent` destination. public static var meth...
As with `arrayEncoding`, it's a bit clearer to say "The encoding to use for `Bool` parameters."
return key } } } /// Configures how `Bool` parameters are encoded. /// /// - numeric: Encode `true` as `1` and `false` as `0`. This is the default behavior. /// - literal: Encode `true` and `false` as string literals. public enum BoolEncoding ...
@@ -99,15 +122,24 @@ public struct URLEncoding: ParameterEncoding { /// The destination defining where the encoded query string is to be applied to the URL request. public let destination: Destination + /// The convention for encoding array parameters. + public let arrayEncoding: ArrayEncoding + + ...
Source/ParameterEncoding.swift
26
Swift
0.429
suggestion
95
51
51
false
Add configurable parameter handling to URLEncoding.
2,431
Alamofire/Alamofire
41,690
Swift
jshier
heiberg
/// Returns a `URLEncoding` instance with a `.methodDependent` destination. public static var methodDependent: URLEncoding { return URLEncoding() } /// Returns a `URLEncoding` instance with a `.queryString` destination. public static var queryString: URLEncoding { return URLEncoding(destination: .quer...
Need parameter docs for `boolEncoding` as well.
/// - literal: Encode `true` and `false` as string literals. public enum BoolEncoding { case numeric, literal func encode(value: Bool) -> String { switch self { case .numeric: return value ? "1" : "0" case .literal: ret...
@@ -99,15 +122,24 @@ public struct URLEncoding: ParameterEncoding { /// The destination defining where the encoded query string is to be applied to the URL request. public let destination: Destination + /// The convention for encoding array parameters. + public let arrayEncoding: ArrayEncoding + + ...
Source/ParameterEncoding.swift
26
Swift
0.214
suggestion
47
51
51
false
Add configurable parameter handling to URLEncoding.
2,431
Alamofire/Alamofire
41,690
Swift
jshier
heiberg
for key in parameters.keys.sorted(by: <) { let value = parameters[key]! components += queryComponents(fromKey: key, value: value) } return components.map { "\($0)=\($1)" }.joined(separator: "&") } private func encodesParametersInURL(with method: HTTPMethod) -> Bo...
It would be cleaner if this was simply an `encode` function on `ArrayEncoding`. Better encapsulation that way.
while index != string.endIndex { let startIndex = index let endIndex = string.index(index, offsetBy: batchSize, limitedBy: string.endIndex) ?? string.endIndex let range = startIndex..<endIndex let substring = string[range] esc...
@@ -261,6 +293,24 @@ public struct URLEncoding: ParameterEncoding { return false } } + + private func encodeArrayKey(_ key: String) -> String {
Source/ParameterEncoding.swift
26
Swift
0.571
suggestion
110
51
51
false
Add configurable parameter handling to URLEncoding.
2,431
Alamofire/Alamofire
41,690
Swift
jshier
heiberg
case .queryString: return true case .httpBody: return false default: break } switch method { case .get, .head, .delete: return true default: return false } } private func encodeArrayKey(...
Like the array encoding function, this should be an `encode` function on `BoolEncoding`.
index = endIndex } } return escaped } private func query(_ parameters: [String: Any]) -> String { var components: [(String, String)] = [] for key in parameters.keys.sorted(by: <) { let value = parameters[key]! components += q...
@@ -261,6 +293,24 @@ public struct URLEncoding: ParameterEncoding { return false } } + + private func encodeArrayKey(_ key: String) -> String { + switch arrayEncoding { + case .brackets: + return "\(key)[]" + case .noBrackets: + return key + ...
Source/ParameterEncoding.swift
26
Swift
0.429
suggestion
88
51
51
false
Add configurable parameter handling to URLEncoding.
2,431
Alamofire/Alamofire
41,690
Swift
jshier
heiberg
if urlRequest.value(forHTTPHeaderField: "Content-Type") == nil { urlRequest.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type") } urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) ...
Moving the `encode` functionality to `ArrayEncoding` would make this `arrayEncoding.encode(key)`, which I think is much clearer.
/// - throws: An `Error` if the encoding process encounters an error. /// /// - returns: The encoded request. public func encode(_ urlRequest: URLRequestConvertible, with parameters: Parameters?) throws -> URLRequest { var urlRequest = try urlRequest.asURLRequest() guard let parameters ...
@@ -161,16 +193,16 @@ public struct URLEncoding: ParameterEncoding { } } else if let array = value as? [Any] { for value in array { - components += queryComponents(fromKey: "\(key)[]", value: value) + components += queryComponents(fromKey: encodeArrayKey(...
Source/ParameterEncoding.swift
26
Swift
0.5
suggestion
128
51
51
false
Add configurable parameter handling to URLEncoding.
2,431
Alamofire/Alamofire
41,690
Swift
jshier
heiberg
urlRequest.httpBody = query(parameters).data(using: .utf8, allowLossyConversion: false) } return urlRequest } /// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. /// /// - parameter key: The key of the query comp...
With `encode` on `BoolEncoding`, this becomes `boolEncoding.encode(value.boolValue)`.
var urlRequest = try urlRequest.asURLRequest() guard let parameters = parameters else { return urlRequest } if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { guard let url = urlRequest.url else { throw AFErr...
@@ -161,16 +193,16 @@ public struct URLEncoding: ParameterEncoding { } } else if let array = value as? [Any] { for value in array { - components += queryComponents(fromKey: "\(key)[]", value: value) + components += queryComponents(fromKey: encodeArrayKey(...
Source/ParameterEncoding.swift
26
Swift
0.357
suggestion
85
51
51
false
Add configurable parameter handling to URLEncoding.
2,431
Alamofire/Alamofire
41,690
Swift
jshier
heiberg
/// Creates percent-escaped, URL encoded query string components from the given key-value pair using recursion. /// /// - parameter key: The key of the query component. /// - parameter value: The value of the query component. /// /// - returns: The percent-escaped, URL encoded query string co...
With `encode` on `BoolEncoding`, this becomes `boolEncoding.encode(bool)`.
guard let url = urlRequest.url else { throw AFError.parameterEncodingFailed(reason: .missingURL) } if var urlComponents = URLComponents(url: url, resolvingAgainstBaseURL: false), !parameters.isEmpty { let percentEncodedQuery = (urlComponents.percentEn...
@@ -161,16 +193,16 @@ public struct URLEncoding: ParameterEncoding { } } else if let array = value as? [Any] { for value in array { - components += queryComponents(fromKey: "\(key)[]", value: value) + components += queryComponents(fromKey: encodeArrayKey(...
Source/ParameterEncoding.swift
26
Swift
0.357
suggestion
74
51
51
false
Add configurable parameter handling to URLEncoding.
2,431
Alamofire/Alamofire
41,690
Swift
jshier
heiberg
/// No brackets are appended to the key and the key is encoded as is. case noBrackets func encode(_ key: String) -> String { switch self { case .brackets: return "\(key)[]" case .noBrackets: return key } } } /// Configures how...
Is the `plusReplaced` case used to support encoding types for `application/x-www-form-urlencoded ` ?
/// - Returns: The encoded `String`. func encode(_ value: Bool) -> String { switch self { case .numeric: return value ? "1" : "0" case .literal: return value ? "true" : "false" } } } /// Configures how `Array` parameters are encode...
@@ -221,6 +221,25 @@ public final class URLEncodedFormEncoder { } } } + + /// Configures how spaces are encoded. + public enum SpaceEncoding { + /// Encodes spaces according to normal percent escaping rules (%20). + case percentEscaped + /// Encodes spaces as `+...
Source/ParameterEncoder.swift
26
Swift
0.714
question
102
51
51
false
Alamofire 5: Customizable Empty Response Handling
2,639
Alamofire/Alamofire
41,690
Swift
agnosticdev
jshier
} } extension DataRequest { /// Adds a handler to be called once the request has finished. /// /// - Parameters: /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means /// the handler is called on `.main`. //...
Any reason real reason to keep these in the global namespace? Seems like they could move into the `ResponseSerializer` extension directly so they don't sit in global state. Thoughts?
// // ResponseSerialization.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restri...
@@ -570,4 +652,5 @@ extension DataRequest { } /// A set of HTTP response status code that do not contain response data. -private let emptyDataStatusCodes: Set<Int> = [204, 205] +private let emptyResponseCodes: Set<Int> = [204, 205] +private let emptyRequestMethods: Set<HTTPMethod> = [.head]
Source/ResponseSerialization.swift
26
Swift
0.571
question
182
27
594
false
Alamofire 5: Customizable Empty Response Handling
2,639
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
public let emptyResponseCodes: Set<Int> /// HTTP request methods for which empty responses are allowed. public let emptyRequestMethods: Set<HTTPMethod> /// Creates an instance using the provided values. /// /// - Parameters: /// - emptyResponseCodes: The HTTP response codes for which emp...
This is a great change overall! I saw some potential for reuse here given that each of the four response serializers repeated this logic. I took a stab at moving it all into the `ResponseSerializer` protocol and the protocol extension in PR #2646. It makes this logic more reusable for custom response serializers both i...
@discardableResult public func responseData( queue: DispatchQueue? = nil, completionHandler: @escaping (DownloadResponse<Data>) -> Void) -> Self { return response( queue: queue, responseSerializer: DataResponseSerializer(), completionHandle...
@@ -303,19 +308,40 @@ extension DataRequest { /// request returning `nil` or no data is considered an error. However, if the response is has a status code valid for /// empty responses (`204`, `205`), then an empty `Data` value is returned. public final class DataResponseSerializer: ResponseSerializer { + /// HTT...
Source/ResponseSerialization.swift
26
Swift
0.643
refactor
369
51
51
false
Alamofire 5: Customizable Empty Response Handling
2,639
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
let start = CFAbsoluteTimeGetCurrent() let result = Result { try responseSerializer.serializeDownload(request: self.request, response: self.response, ...
Really good idea to allow them to be injected!
return response(queue: queue, responseSerializer: DataResponseSerializer(), completionHandler: completionHandler) } } /// A `ResponseSerializer` that performs minimal reponse checking and returns any response data as-is. By default, a /// request returning `n...
@@ -303,19 +308,40 @@ extension DataRequest { /// request returning `nil` or no data is considered an error. However, if the response is has a status code valid for /// empty responses (`204`, `205`), then an empty `Data` value is returned. public final class DataResponseSerializer: ResponseSerializer { + /// HTT...
Source/ResponseSerialization.swift
26
Swift
0.214
suggestion
46
51
51
false
Alamofire 5: Customizable Empty Response Handling
2,639
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
extension DownloadRequest { /// Adds a handler to be called once the request has finished. /// /// - Parameters: /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means /// the handler is called on `.main`. /// -...
In order to work around the issue you identified in the tests, where types could accidentally return some other `EmptyResponse` type, perhaps this property should have type `Self`? I just don't know if that would break the casting that needed to pull the value out.
extension DownloadRequest { /// Adds a handler to be called once the request has finished. /// /// - Parameters: /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means /// the handler is called on `.main`. /// -...
@@ -515,12 +515,20 @@ extension DownloadRequest { } // MARK: - Empty +/// A protocol for a type representing an empty response. Use `T.emptyValue` to get an instance. +public protocol EmptyResponse { + static var emptyValue: EmptyResponse { get }
Source/ResponseSerialization.swift
26
Swift
0.786
suggestion
265
51
51
false
Implementing protocol EmptyResponse so that an empty response value can be returned when an empty http status code is encountered
2,664
Alamofire/Alamofire
41,690
Swift
jshier
jvannoord
extension DownloadRequest { /// Adds a handler to be called once the request has finished. /// /// - Parameters: /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means /// the handler is called on `.main`. /// -...
I like the transition to a function here, but this seems rather verbose. Perhaps just `emptyValue()`?
extension DownloadRequest { /// Adds a handler to be called once the request has finished. /// /// - Parameters: /// - queue: The queue on which the completion handler is dispatched. Defaults to `nil`, which means /// the handler is called on `.main`. /// -...
@@ -515,12 +515,23 @@ extension DownloadRequest { } // MARK: - Empty +/// A protocol for a type representing an empty response. Use `T.emptyValue` to get an instance. +public protocol EmptyResponse { + static func emptyResponseValue() -> Self
Source/ResponseSerialization.swift
26
Swift
0.5
question
101
51
51
false
Implementing protocol EmptyResponse so that an empty response value can be returned when an empty http status code is encountered
2,664
Alamofire/Alamofire
41,690
Swift
jshier
jvannoord
/// - Parameters: /// - decoder: The `JSONDecoder`. Defaults to a `JSONDecoder()`. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. Defaults to /// `[204, 205]`. /// - emptyRequestMethods: The HTTP request methods for ...
This can again be combined into the guard.
/// - decoder: The `JSONDecoder`. Defaults to a `JSONDecoder()`. /// - emptyResponseCodes: The HTTP response codes for which empty responses are allowed. Defaults to /// `[204, 205]`. /// - emptyRequestMethods: The HTTP request methods for which empty responses ...
@@ -575,11 +586,11 @@ public final class DecodableResponseSerializer<T: Decodable>: ResponseSerializer throw AFError.responseSerializationFailed(reason: .inputDataNilOrZeroLength) } - guard let emptyValue = Empty.value as? T else { + guard let emptyResponseType = T....
Source/ResponseSerialization.swift
26
Swift
0.071
suggestion
42
51
51
false
Implementing protocol EmptyResponse so that an empty response value can be returned when an empty http status code is encountered
2,664
Alamofire/Alamofire
41,690
Swift
jshier
jvannoord
// Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error?.asAFError { XCTAssertTrue(error.isInvalidEmptyResponse) } else { XCTFail("error should not be nil") } } ...
What is this testing? It seems unnecessary with all of the other tests around the feature.
// Then XCTAssertTrue(result.isFailure) XCTAssertNil(result.value) XCTAssertNotNil(result.error) if let error = result.error?.asAFError { XCTAssertTrue(error.isInvalidEmptyResponse) } else { XCTFail("error should not be nil") } } } /...
@@ -567,6 +592,67 @@ final class DecodableResponseSerializerTests: BaseTestCase { XCTAssertNotNil(result.value) XCTAssertNil(result.error) } + + func testThatDecodableResponseSerializerSucceedsWhenDataIsNilWithEmptyResponseConformingTypeAndEmptyResponseStatusCode() { + // Given + ...
Tests/ResponseSerializationTests.swift
26
Swift
0.214
question
90
51
51
false
Implementing protocol EmptyResponse so that an empty response value can be returned when an empty http status code is encountered
2,664
Alamofire/Alamofire
41,690
Swift
jshier
jvannoord
for response: HTTPURLResponse, completion: @escaping (URLRequest?) -> Void) } // MARK: - public struct Redirector { public enum Behavior { case follow case doNotFollow case modify((URLSessionTask, URLRequest, HTTPURLResponse) -> URLRequest?) } public le...
Similar to the caching behavior, we could offer static properties with prebuilt `Behavior` instances.
for response: HTTPURLResponse, completion: @escaping (URLRequest?) -> Void) } // MARK: - /// `Redirector` is a convenience `RedirectHandler` making it easy to follow, not follow, or modify a redirect. public struct Redirector { /// Defines the behavior of the `Redirector` type. ///...
@@ -0,0 +1,79 @@ +// +// RedirectHandler.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Soft...
Source/RedirectHandler.swift
26
Swift
0.571
suggestion
101
37
51
false
Feature - Redirect Handlers
2,699
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OU...
Might it be useful to make this function `throws`? It would allow anyone needing error handling to get it while placing no burden on those who don't. It shouldn't make the implementation much more difficult either.
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OU...
@@ -0,0 +1,79 @@ +// +// RedirectHandler.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in the Soft...
Source/RedirectHandler.swift
26
Swift
0.786
suggestion
214
51
51
false
Feature - Redirect Handlers
2,699
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
open func downloadProgress(queue: DispatchQueue = .main, closure: @escaping ProgressHandler) -> Self { protectedMutableState.write { $0.downloadProgressHandler = (handler: closure, queue: queue) } return self } /// Sets a closure to be called periodically during the lifecycle of the `Reque...
As with some of my other comments, I've been using the type for most parameter docs, so "The `RedirectHandler`." would be my doc here. Also, lining up all of the "The"s to match my previous alignment. Or we can do a documentation pass later.
/// /// Only the last closure provided is used. /// /// - Parameters: /// - queue: The `DispatchQueue` to execute the closure on. Defaults to `.main`. /// - closure: The closure to be executed periodically as data is sent to the server. /// - Returns: The `Request`. @discardableR...
@@ -486,6 +494,18 @@ open class Request { return self } + + // MARK: - Redirects + + /// Sets the redirect handler for the `Request` which will be used if a redirect response is encountered. + /// + /// - Parameter handler: The redirect handler.
Source/Request.swift
26
Swift
0.714
suggestion
245
51
51
false
Feature - Redirect Handlers
2,699
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
import Foundation public protocol CachedResponseHandler { func dataTask(_ task: URLSessionDataTask, willCacheResponse response: CachedURLResponse, completion: @escaping (CachedURLResponse?) -> Void) } // MARK: - public struct ResponseCacher { public enum Behavior { ...
I think some static properties could help users. ```swift static let cache = ResponseCacher(behavior: .cache) ``` etc.
import Foundation /// A type that handles whether the data task should store the HTTP response in the cache. public protocol CachedResponseHandler { /// Determines whether the HTTP response should be stored in the cache. /// /// The `completion` closure should be passed one of three possible options: /...
@@ -0,0 +1,63 @@ +// +// CachedResponseHandler.swift +// +// Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) +// +// Permission is hereby granted, free of charge, to any person obtaining a copy +// of this software and associated documentation files (the "Software"), to deal +// in th...
Source/CachedResponseHandler.swift
26
Swift
0.786
performance
123
40
51
false
Feature - Cached Responses
2,701
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
/// - queue: The `DispatchQueue` to execute the closure on. Defaults to `.main`. /// - closure: The closure to be executed periodically as data is sent to the server. /// - Returns: The `Request`. @discardableResult open func uploadProgress(queue: DispatchQueue = .main, closure: @escaping Pr...
I prefer `using` as the modifier for methods like this. e.g. `.cacheResponse(using: myHandler)`.
return self } // MARK: - Redirects /// Sets the redirect handler for the `Request` which will be used if a redirect response is encountered. /// /// - Parameter handler: The `RedirectHandler`. /// - Returns: The `Request`. @discardableResult open func redirect(using h...
@@ -506,6 +515,14 @@ open class Request { protectedMutableState.write { $0.redirectHandler = handler } return self } + + // MARK: - Cached Responses + + @discardableResult + open func cacheResponse(with handler: CachedResponseHandler) -> Self {
Source/Request.swift
26
Swift
0.571
performance
96
51
51
false
Feature - Cached Responses
2,701
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
} func testThatAdapterCanBeImplementedAsynchronously() { // Given let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/get")!) let session = Session() var adapted = false let adapter = Adapter { request, _, completion in adapted = true ...
Please use our default timeout. It should be available as `timeout`.
} func testThatAdapterCanBeImplementedAsynchronously() { // Given let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/get")!) let session = Session() var adapted = false let adapter = Adapter { request, _, completion in adapted = true ...
@@ -117,6 +117,36 @@ final class AdapterTestCase: BaseTestCase { // Then XCTAssertEqual(result, .doNotRetry) } + + func testThatAdapterCanBeImplementedAsynchronously() { + // Given + let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/get")!) + let session = ...
Tests/RequestInterceptorTests.swift
26
Swift
0.429
suggestion
68
51
51
false
Mark RequestInterceptor closure callback arguments escaping
2,747
Alamofire/Alamofire
41,690
Swift
jshier
cysp
func testThatRetrierCanBeImplementedAsynchronously() { // Given let url = URL(string: "https://httpbin.org/get")! let session = Session(startRequestsImmediately: false) let request = session.request(url) var retried = false let retrier = Retrier { request, session, ...
Please use our default timeout. It should be available as `timeout`.
func testThatRetrierCanBeImplementedAsynchronously() { // Given let url = URL(string: "https://httpbin.org/get")! let session = Session(startRequestsImmediately: false) let request = session.request(url) var retried = false let retrier = Retrier { request, session, ...
@@ -161,6 +191,37 @@ final class RetrierTestCase: BaseTestCase { // Then XCTAssertTrue(result.isSuccess) } + + func testThatRetrierCanBeImplementedAsynchronously() { + // Given + let url = URL(string: "https://httpbin.org/get")! + let session = Session(startRequestsImmedia...
Tests/RequestInterceptorTests.swift
26
Swift
0.429
suggestion
68
51
51
false
Mark RequestInterceptor closure callback arguments escaping
2,747
Alamofire/Alamofire
41,690
Swift
jshier
cysp
XCTAssertTrue(result.error is MockError) } func testThatInterceptorCanAdaptRequestAsynchronously() { // Given let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/get")!) let session = Session() let adapter = Adapter { urlRequest, _, completion in ...
Please use our default timeout. It should be available as `timeout`. Also, there doesn't seem to be a need for the assignment here.
XCTAssertTrue(result.error is MockError) } func testThatInterceptorCanAdaptRequestAsynchronously() { // Given let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/get")!) let session = Session() let adapter = Adapter { urlRequest, _, completion in ...
@@ -258,6 +319,35 @@ final class InterceptorTestCase: BaseTestCase { XCTAssertTrue(result.error is MockError) } + func testThatInterceptorCanAdaptRequestAsynchronously() { + // Given + let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/get")!) + let session = Sessi...
Tests/RequestInterceptorTests.swift
26
Swift
0.571
suggestion
131
51
51
false
Mark RequestInterceptor closure callback arguments escaping
2,747
Alamofire/Alamofire
41,690
Swift
jshier
cysp
} func testThatInterceptorCanRetryRequestAsynchronously() { // Given let url = URL(string: "https://httpbin.org/get")! let session = Session(startRequestsImmediately: false) let request = session.request(url) let retrier = Retrier { _, _, _, completion in Di...
Please use our default timeout. It should be available as `timeout`. Again, there doesn't seem to be a need for the assignment here.
} func testThatInterceptorCanRetryRequestAsynchronously() { // Given let url = URL(string: "https://httpbin.org/get")! let session = Session(startRequestsImmediately: false) let request = session.request(url) let retrier = Retrier { _, _, _, completion in Di...
@@ -312,6 +402,35 @@ final class InterceptorTestCase: BaseTestCase { XCTAssertEqual(result, .retry) } + func testThatInterceptorCanRetryRequestAsynchronously() { + // Given + let url = URL(string: "https://httpbin.org/get")! + let session = Session(startRequestsImmediately: false...
Tests/RequestInterceptorTests.swift
26
Swift
0.571
suggestion
132
51
51
false
Mark RequestInterceptor closure callback arguments escaping
2,747
Alamofire/Alamofire
41,690
Swift
jshier
cysp
/// evaluators consider it valid. public final class CompositeTrustEvaluator: ServerTrustEvaluating { private let evaluators: [ServerTrustEvaluating] /// Creates a `CompositeTrustEvaluator`. /// /// - Parameter evaluators: The `ServerTrustEvaluating` values used to evaluate the server trust. public...
Seems like we should probably hide this internally or inside `AlamofireExtended` as well. Pretty sure it can't be done with `AlamofireExtended` which is probably why you didn't already do it if I had to guess.
/// THIS EVALUATOR SHOULD NEVER BE USED IN PRODUCTION! public final class DisabledEvaluator: ServerTrustEvaluating { public init() { } public func evaluate(_ trust: SecTrust, forHost host: String) throws { } } // MARK: - Extensions public extension Array where Element == ServerTrustEvaluating { #if os(Li...
@@ -352,9 +334,30 @@ public final class DisabledEvaluator: ServerTrustEvaluating { public func evaluate(_ trust: SecTrust, forHost host: String) throws { } } -extension Bundle { +// MARK: - Extensions + +public extension Array where Element == ServerTrustEvaluating { + #if os(Linux) + // Add this same con...
Source/ServerTrustEvaluation.swift
26
Swift
0.643
suggestion
209
51
51
false
[Alamofire 5]: AlamofireExtended extension point.
2,758
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
interceptor: RequestInterceptor? = nil, serverTrustManager: ServerTrustManager? = nil, redirectHandler: RedirectHandler? = nil, cachedResponseHandler: CachedResponseHandler? = nil, eventMonitors: [EventMonitor] = []) { precondition(...
`URLSessionConfiguration.af.default` -> `.af.default`?
interceptor: RequestInterceptor? = nil, serverTrustManager: ServerTrustManager? = nil, redirectHandler: RedirectHandler? = nil, cachedResponseHandler: CachedResponseHandler? = nil, eventMonitors: [EventMonitor] = []) { precondition(...
@@ -74,7 +74,7 @@ open class Session { delegate.stateProvider = self } - public convenience init(configuration: URLSessionConfiguration = .alamofireDefault, + public convenience init(configuration: URLSessionConfiguration = URLSessionConfiguration.af.default,
Source/Session.swift
26
Swift
0.357
question
54
51
51
false
[Alamofire 5]: AlamofireExtended extension point.
2,758
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // f...
Are we sure we don't want to hide this in `AlamofireExtension` as well?
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // f...
@@ -24,9 +24,9 @@ import Foundation -extension URLRequest { +public extension URLRequest { var method: HTTPMethod? { - guard let httpMethod = self.httpMethod else { return nil } + guard let httpMethod = httpMethod else { return nil } return HTTPMethod(rawValue: httpMethod) } }
Source/URLRequest+Alamofire.swift
26
Swift
0.357
question
71
27
27
false
[Alamofire 5]: AlamofireExtended extension point.
2,758
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
/// - parameter arrayEncoding: The encoding to use for `Array` parameters. /// - parameter boolEncoding: The encoding to use for `Bool` parameters. /// /// - returns: The new `URLEncoding` instance. public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, bo...
We now have an extension on `URLRequest` which should return the method, without having to initialize it.
/// - parameter arrayEncoding: The encoding to use for `Array` parameters. /// - parameter boolEncoding: The encoding to use for `Bool` parameters. /// /// - returns: The new `URLEncoding` instance. public init(destination: Destination = .methodDependent, arrayEncoding: ArrayEncoding = .brackets, bo...
@@ -159,7 +164,7 @@ public struct URLEncoding: ParameterEncoding { guard let parameters = parameters else { return urlRequest } - if let method = HTTPMethod(rawValue: urlRequest.httpMethod ?? "GET"), encodesParametersInURL(with: method) { + if let method = HTTPMethod(rawValue: urlRequest.http...
Source/ParameterEncoding.swift
26
Swift
0.571
suggestion
105
51
51
false
Refactor - Switches and Queues
2,765
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // f...
Not that we need to address this in this PR, but we should consider always returning a `.get` and not having this be optional. It defaults to `.get` even when not set.
// of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // f...
@@ -26,7 +26,7 @@ import Foundation public extension URLRequest { var method: HTTPMethod? { - guard let httpMethod = httpMethod else { return nil } - return HTTPMethod(rawValue: httpMethod) + get { return httpMethod.flatMap(HTTPMethod.init) } + set { httpMethod = newValue?.rawValue }...
Source/URLRequest+Alamofire.swift
26
Swift
0.571
suggestion
167
27
28
false
[#2270]: Fix emptyResponseAllowed logic.
2,772
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
XCTAssertTrue(error.isInputDataNilOrZeroLength) } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerFailsWhenDataIsNilWithNonEmptyResponseStatusCode() { // Given let serializer = StringResponseSerializer() let resp...
Looks like some tabs snuck in throughout this file.
XCTAssertTrue(error.isInputDataNilOrZeroLength) } else { XCTFail("error should not be nil") } } func testThatStringResponseSerializerFailsWhenDataIsNilWithNonEmptyResponseStatusCode() { // Given let serializer = StringResponseSerializer() let resp...
@@ -285,20 +324,59 @@ final class DataResponseSerializationTestCase: BaseTestCase { XCTFail("error should not be nil") } } - - func testThatStringResponseSerializerSucceedsWhenDataIsNilWithEmptyResponseStatusCode() { +
Tests/ResponseSerializationTests.swift
26
Swift
0.214
suggestion
51
51
51
false
[#2270]: Fix emptyResponseAllowed logic.
2,772
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
protectedMutableState.write { mutableState in let responseSerializerIndex = mutableState.responseSerializerCompletions.count if responseSerializerIndex < mutableState.responseSerializers.count { responseSerializer = mutableState.responseSerializers[responseSerializerInde...
These should not be called inside the lock. Need to pull the completions out of the lock and then execute.
protectedMutableState.write { mutableState in let responseSerializerIndex = mutableState.responseSerializerCompletions.count if responseSerializerIndex < mutableState.responseSerializers.count { responseSerializer = mutableState.responseSerializers[responseSerializerInde...
@@ -396,8 +396,19 @@ open class Request { /// Processes the next response serializer and calls all completions if response serialization is complete. func processNextResponseSerializer() { guard let responseSerializer = nextResponseSerializer() else { - // Execute all response serializer c...
Source/Request.swift
26
Swift
0.429
suggestion
106
51
51
false
Bugfix - Cancellation Loop
2,778
Alamofire/Alamofire
41,690
Swift
cnoon
cnoon
// Then assertErrorIsAFError(error) { XCTAssertTrue($0.isSessionDeinitializedError) } } } // MARK: - class SessionManagerConfigurationHeadersTestCase: BaseTestCase { enum ConfigurationType { case `default`, ephemeral, background } func testThatDefaultConfigurationHeadersAreSen...
Why is this delay necessary? Is it an attempt to finish the internal race to set the cancellation state? Also, how sensitive is this delay? We've had issues in the past with static delays being too short to reliably pass in the test environment.
// Then assertErrorIsAFError(error) { XCTAssertTrue($0.isSessionDeinitializedError) } } // MARK: Tests - Request Cancellation func testThatSessionOnlyCallsResponseSerializerCompletionWhenCancellingInsideCompletion() { // Given let handler = RequestHandler() let sess...
@@ -1435,6 +1435,43 @@ class SessionTestCase: BaseTestCase { // Then assertErrorIsAFError(error) { XCTAssertTrue($0.isSessionDeinitializedError) } } + + // MARK: Tests - Request Cancellation + + func testThatSessionOnlyCallsResponseSerializerCompletionWhenCancellingInsideCompletion() { + ...
Tests/SessionTests.swift
26
Swift
0.429
security
245
51
51
false
Bugfix - Cancellation Loop
2,778
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
} session = nil waitForExpectations(timeout: timeout, handler: nil) // Then assertErrorIsAFError(error) { XCTAssertTrue($0.isSessionDeinitializedError) } } } // MARK: - class SessionManagerConfigurationHeadersTestCase: BaseTestCase { enum ConfigurationType { c...
It seems like we may want to more generally fix `cancel()` by preventing its actions when the `Request` has already finished. It may be out of scope for this fix, but it makes sense to me that we may want to add an additional stage to state, perhaps `.completed`, to indicate that a `Request` has finished and started ca...
} session = nil waitForExpectations(timeout: timeout, handler: nil) // Then assertErrorIsAFError(error) { XCTAssertTrue($0.isSessionDeinitializedError) } } // MARK: Tests - Request Cancellation func testThatSessionOnlyCallsResponseSerializerCompletionWhenCancellin...
@@ -1435,6 +1435,43 @@ class SessionTestCase: BaseTestCase { // Then assertErrorIsAFError(error) { XCTAssertTrue($0.isSessionDeinitializedError) } } + + // MARK: Tests - Request Cancellation + + func testThatSessionOnlyCallsResponseSerializerCompletionWhenCancellingInsideCompletion() { + ...
Tests/SessionTests.swift
26
Swift
0.714
suggestion
350
51
51
false
Bugfix - Cancellation Loop
2,778
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension Request { /// Posted wh...
Do we want the key to match? `didFinishTask` vs. `didCompleteTask`.
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation public extension Request { /// Posted wh...
@@ -26,13 +26,22 @@ import Foundation public extension Request { /// Posted when a `Request` is resumed. The `Notification` contains the resumed `Request`. - static let didResume = Notification.Name(rawValue: "org.alamofire.notification.name.request.didResume") + static let didResumeNotification = Notific...
Source/Notifications.swift
26
Swift
0.357
question
67
51
51
false
Audit - Notification Names
2,803
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
// // RequestTaskMap.swift // // Copyright (c) 2014-2018 Alamofire Software Foundation (http://alamofire.org/) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, ...
I wonder if reusing the state provider APIs would make sense here: ```swift disassociateIfNecessaryAfterGatheringMetricsForTask -> didGatherMetricsForTask disassociateIfNecessaryAfterCompletingTask -> didCompleteTask ```
precondition(tasksToRequests.count == requestsToTasks.count, "RequestTaskMap.count invalid, requests.count: \(tasksToRequests.count) != tasks.count: \(requestsToTasks.count)") return tasksToRequests.count } var eventCount: Int { precondition(taskEvents.count == cou...
@@ -83,10 +91,46 @@ struct RequestTaskMap { return tasksToRequests.count } + var eventCount: Int { + precondition(taskEvents.count == count, "RequestTaskMap.eventCount invalid, count: \(count) != taskEvents.count: \(taskEvents.count)") + + return taskEvents.count + } + var isEmp...
Source/RequestTaskMap.swift
26
Swift
0.786
suggestion
226
93
50
false
Bugfix: DownloadRequest event duplication and missing events.
2,807
Alamofire/Alamofire
41,690
Swift
cnoon
jshier
public enum ResponseValidationFailureReason { case dataFileNil case dataFileReadFailed(at: URL) case missingContentType(acceptableContentTypes: [String]) case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) case unacceptableStatusCode(co...
Very open to other naming suggestions here!
public enum ResponseValidationFailureReason { case dataFileNil case dataFileReadFailed(at: URL) case missingContentType(acceptableContentTypes: [String]) case unacceptableContentType(acceptableContentTypes: [String], responseContentType: String) case unacceptableStatusCode(co...
@@ -139,6 +139,8 @@ public enum AFError: Error { case decodingFailed(error: Error) /// Generic serialization failed for an empty response that wasn't type `Empty` but instead the associated type. case invalidEmptyResponse(type: String) + /// The response serializer was added to the req...
Source/AFError.swift
26
Swift
0.071
suggestion
43
51
51
false
Feature - Terminal Response Serializers
2,810
Alamofire/Alamofire
41,690
Swift
cnoon
cnoon
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// `Request` is the common superclass of al...
I figured `.finished` was more correct than `.completed` based on the different naming conventions we've come up with in other places with `Request` and `Task`.
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // import Foundation /// `Request` is the common superclass of al...
@@ -38,17 +38,25 @@ public class Request { /// - cancelled: Set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer /// transition to a...
Source/Request.swift
26
Swift
0.5
style
160
51
51
false
Feature - Terminal Response Serializers
2,810
Alamofire/Alamofire
41,690
Swift
cnoon
cnoon
/// - unacceptableStatusCode: The response status code was not acceptable. public enum ResponseValidationFailureReason { case dataFileNil case dataFileReadFailed(at: URL) case missingContentType(acceptableContentTypes: [String]) case unacceptableContentType(acceptableContentType...
I think this should say "A response serializer...", and "completed" should probably be "finished."
/// - unacceptableStatusCode: The response status code was not acceptable. public enum ResponseValidationFailureReason { case dataFileNil case dataFileReadFailed(at: URL) case missingContentType(acceptableContentTypes: [String]) case unacceptableContentType(acceptableContentType...
@@ -139,6 +139,8 @@ public enum AFError: Error { case decodingFailed(error: Error) /// Generic serialization failed for an empty response that wasn't type `Empty` but instead the associated type. case invalidEmptyResponse(type: String) + /// The response serializer was added to the req...
Source/AFError.swift
26
Swift
0.286
suggestion
98
51
51
false
Feature - Terminal Response Serializers
2,810
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
import Foundation /// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback /// handling. public class Request { /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or /// `cancel()` on the ...
I think the state machine need to be updated to ensure (or make explicit) we can only transition to `finished` from non-`cancelled` states.
import Foundation /// `Request` is the common superclass of all Alamofire request types and provides common state, delegate, and callback /// handling. public class Request { /// State of the `Request`, with managed transitions between states set when calling `resume()`, `suspend()`, or /// `cancel()` on the ...
@@ -38,17 +38,26 @@ public class Request { /// - cancelled: Set when `cancel()` is called. Any tasks created for the `Request` will have `cancel()` called on /// them. Unlike `resumed` or `suspended`, once in the `cancelled` state, the `Request` can no longer /// transition to a...
Source/Request.swift
26
Swift
0.5
suggestion
139
51
51
false
Feature - Terminal Response Serializers
2,810
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
delegate.retryResult(for: self, dueTo: error) { retryResult in switch retryResult { case .doNotRetry, .doNotRetryWithError: self.finish(error: retryResult.error) case .retry, .retryWithDelay: delegate.retryRequest(self, withDelay: retryResult.d...
Probably want to check for `.cancelled` separately so we run the serializers either way.
delegate.retryResult(for: self, dueTo: error) { retryResult in switch retryResult { case .doNotRetry, .doNotRetryWithError: self.finish(error: retryResult.error) case .retry, .retryWithDelay: delegate.retryRequest(self, withDelay: retryResult.d...
@@ -387,7 +398,14 @@ public class Request { /// Appends the response serialization closure to the `Request`. func appendResponseSerializer(_ closure: @escaping () -> Void) { - protectedMutableState.write { $0.responseSerializers.append(closure) } + protectedMutableState.write { mutableState in...
Source/Request.swift
26
Swift
0.357
suggestion
88
51
51
false
Feature - Terminal Response Serializers
2,810
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
if responseSerializerIndex < mutableState.responseSerializers.count { responseSerializer = mutableState.responseSerializers[responseSerializerIndex] } } return responseSerializer } /// Processes the next response serializer and calls all completions if ...
We only want to transition to `.finished` if we weren't cancelled, so this should probably use the state transition API.
protectedMutableState.write { mutableState in let responseSerializerIndex = mutableState.responseSerializerCompletions.count if responseSerializerIndex < mutableState.responseSerializers.count { responseSerializer = mutableState.responseSerializers[responseSerializerInd...
@@ -420,6 +438,8 @@ public class Request { // An example of how this can happen is by calling cancel inside a response completion closure. mutableState.responseSerializers.removeAll() mutableState.responseSerializerCompletions.removeAll() + + mutableStat...
Source/Request.swift
26
Swift
0.571
suggestion
120
51
51
false
Feature - Terminal Response Serializers
2,810
Alamofire/Alamofire
41,690
Swift
jshier
cnoon
case deferredToDate /// Encodes the date as a UNIX timestamp. case secondsSince1970 /// Encodes the date as UNIX millisecond timestamp. case millisecondsSince1970 /// Encodes the date as an ISO-8601-formatted string (in RFC 3339 format). case iso8601 /// E...
This is strange; there's no documentation for this `static func string(from:timeZone:formatOptions)`. It would probably be a better idea for `DateEncoding` to define its own `static let` member for this formatter anyway, following what's defined by `JSONEncoder`: ```swift fileprivate var _iso8601Formatter: ISO8601Dat...
case deferredToDate /// Encodes dates as seconds since midnight UTC on January 1, 1970. case secondsSince1970 /// Encodes dates as milliseconds since midnight UTC on January 1, 1970. case millisecondsSince1970 /// Encodes dates according to the ISO 8601 and RFC3339 standa...
@@ -221,6 +224,45 @@ public final class URLEncodedFormEncoder { } } + /// Configures how `Date` parameters are encoded. + public enum DateEncoding { + /// Encodes the date from `Date` structure. + case deferredToDate + /// Encodes the date as a UNIX timestamp. + case se...
Source/ParameterEncoder.swift
26
Swift
0.857
style
625
51
51
false
Date encoding strategies for URLEncodedFormEncoder
2,813
Alamofire/Alamofire
41,690
Swift
jshier
almazrafi
case .numeric: return value ? "1" : "0" case .literal: return value ? "true" : "false" } } } /// Configures how `Date` parameters are encoded. public enum DateEncoding { /// Encodes the date from `Date` structure. case deferredToDate /// E...
`JSONEncoder` allows its `custom` case to produce throwing closures. Alamofire should likely do that same. This method should likely be `throws` so that custom closures can produce errors.
case .numeric: return value ? "1" : "0" case .literal: return value ? "true" : "false" } } } /// Configures how `Date` parameters are encoded. public enum DateEncoding { /// Defers encoding to the `Date` type. case deferredToDate /// Encod...
@@ -221,6 +224,45 @@ public final class URLEncodedFormEncoder { } } + /// Configures how `Date` parameters are encoded. + public enum DateEncoding { + /// Encodes the date from `Date` structure. + case deferredToDate + /// Encodes the date as a UNIX timestamp. + case se...
Source/ParameterEncoder.swift
26
Swift
0.714
suggestion
188
51
51
false
Date encoding strategies for URLEncodedFormEncoder
2,813
Alamofire/Alamofire
41,690
Swift
jshier
almazrafi
/// Encodes the given `Bool` as a `String`. /// /// - Parameter value: The `Bool` to encode. /// - Returns: The encoded `String`. func encode(_ value: Bool) -> String { switch self { case .numeric: return value ? "1" : "0" case .literal...
This closure should likely be a bit closer to what `JSONEncoder` uses: both `@escaping` and `throws`.
/// Encodes the given `Bool` as a `String`. /// /// - Parameter value: The `Bool` to encode. /// - Returns: The encoded `String`. func encode(_ value: Bool) -> String { switch self { case .numeric: return value ? "1" : "0" case .literal...
@@ -221,6 +224,45 @@ public final class URLEncodedFormEncoder { } } + /// Configures how `Date` parameters are encoded. + public enum DateEncoding { + /// Encodes the date from `Date` structure. + case deferredToDate + /// Encodes the date as a UNIX timestamp. + case se...
Source/ParameterEncoder.swift
26
Swift
0.571
suggestion
101
51
51
false
Date encoding strategies for URLEncodedFormEncoder
2,813
Alamofire/Alamofire
41,690
Swift
jshier
almazrafi
/// while older encoding may expect spaces to be replaced with +. /// /// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project. public final class URLEncodedFormEncoder { /// Configures how `Bool` parameters are encoded. public enum BoolEncoding { ...
This comment is a bit confusing. Perhaps "Defers encoding to the `Date` type."
/// while older encoding may expect spaces to be replaced with +. /// /// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project. public final class URLEncodedFormEncoder { /// Configures how `Bool` parameters are encoded. public enum BoolEncoding { ...
@@ -221,6 +224,45 @@ public final class URLEncodedFormEncoder { } } + /// Configures how `Date` parameters are encoded. + public enum DateEncoding { + /// Encodes the date from `Date` structure.
Source/ParameterEncoder.swift
26
Swift
0.5
suggestion
78
51
51
false
Date encoding strategies for URLEncodedFormEncoder
2,813
Alamofire/Alamofire
41,690
Swift
jshier
almazrafi
/// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project. public final class URLEncodedFormEncoder { /// Configures how `Bool` parameters are encoded. public enum BoolEncoding { /// Encodes `true` as `1`, `false` as `0`. case numeric ...
This should be more precise, like `JSONEncoder`'s: "Encodes dates as seconds since midnight UTC on January 1, 1970.".
/// This type is largely based on Vapor's [`url-encoded-form`](https://github.com/vapor/url-encoded-form) project. public final class URLEncodedFormEncoder { /// Configures how `Bool` parameters are encoded. public enum BoolEncoding { /// Encodes `true` as `1`, `false` as `0`. case numeric ...
@@ -221,6 +224,45 @@ public final class URLEncodedFormEncoder { } } + /// Configures how `Date` parameters are encoded. + public enum DateEncoding { + /// Encodes the date from `Date` structure. + case deferredToDate + /// Encodes the date as a UNIX timestamp.
Source/ParameterEncoder.swift
26
Swift
0.571
suggestion
117
51
51
false
Date encoding strategies for URLEncodedFormEncoder
2,813
Alamofire/Alamofire
41,690
Swift
jshier
almazrafi
/// Configures how `Bool` parameters are encoded. public enum BoolEncoding { /// Encodes `true` as `1`, `false` as `0`. case numeric /// Encodes `true` as "true", `false` as "false". case literal /// Encodes the given `Bool` as a `String`. /// /// - Param...
This should also be more precise, like `JSONEncoder`'s: "Encodes dates as milliseconds since midnight UTC on January 1, 1970.".
/// Configures how `Bool` parameters are encoded. public enum BoolEncoding { /// Encodes `true` as `1`, `false` as `0`. case numeric /// Encodes `true` as "true", `false` as "false". case literal /// Encodes the given `Bool` as a `String`. /// /// - Param...
@@ -221,6 +224,45 @@ public final class URLEncodedFormEncoder { } } + /// Configures how `Date` parameters are encoded. + public enum DateEncoding { + /// Encodes the date from `Date` structure. + case deferredToDate + /// Encodes the date as a UNIX timestamp. + case se...
Source/ParameterEncoder.swift
26
Swift
0.571
suggestion
127
51
51
false
Date encoding strategies for URLEncodedFormEncoder
2,813
Alamofire/Alamofire
41,690
Swift
jshier
almazrafi
/// Encodes `true` as "true", `false` as "false". case literal /// Encodes the given `Bool` as a `String`. /// /// - Parameter value: The `Bool` to encode. /// - Returns: The encoded `String`. func encode(_ value: Bool) -> String { switch self...
I don't think it's necessary to mention the `String` conversion in this documentation, as the encoder as a whole only produces a `String`. Perhaps "Encodes dates using the given `DateFormatter`".
/// Encodes `true` as "true", `false` as "false". case literal /// Encodes the given `Bool` as a `String`. /// /// - Parameter value: The `Bool` to encode. /// - Returns: The encoded `String`. func encode(_ value: Bool) -> String { switch self...
@@ -221,6 +224,45 @@ public final class URLEncodedFormEncoder { } } + /// Configures how `Date` parameters are encoded. + public enum DateEncoding { + /// Encodes the date from `Date` structure. + case deferredToDate + /// Encodes the date as a UNIX timestamp. + case se...
Source/ParameterEncoder.swift
26
Swift
0.5
style
195
51
51
false
Date encoding strategies for URLEncodedFormEncoder
2,813
Alamofire/Alamofire
41,690
Swift
jshier
almazrafi