<commit_before>// Alamofire.swift
//
// Copyright (c) 2014 Alamofire (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, 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
// 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 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,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

import Foundation

public struct Alamofire {

    // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
    public enum Method: String {
        case OPTIONS = "OPTIONS"
        case GET = "GET"
        case HEAD = "HEAD"
        case POST = "POST"
        case PUT = "PUT"
        case PATCH = "PATCH"
        case DELETE = "DELETE"
        case TRACE = "TRACE"
        case CONNECT = "CONNECT"
    }

    public enum ParameterEncoding {
        case URL
        case JSON(options: NSJSONWritingOptions)
        case PropertyList(format: NSPropertyListFormat, options: NSPropertyListWriteOptions)

        func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
            if parameters == nil {
                return (request, nil)
            }

            var mutableRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest
            var error: NSError? = nil

            switch self {
            case .URL:
                func query(parameters: [String: AnyObject]) -> String! {
                    func queryComponents(key: String, value: AnyObject) -> [(String, String)] {
                        func dictionaryQueryComponents(key: String, dictionary: [String: AnyObject]) -> [(String, String)] {
                            var components: [(String, String)] = []
                            for (nestedKey, value) in dictionary {
                                components += queryComponents("\(key)[\(nestedKey)]", value)
                            }

                            return components
                        }

                        func arrayQueryComponents(key: String, array: [AnyObject]) -> [(String, String)] {
                            var components: [(String, String)] = []
                            for value in array {
                                components += queryComponents("\(key)[]", value)
                            }

                            return components
                        }

                        var components: [(String, String)] = []
                        if let dictionary = value as? [String: AnyObject] {
                            components += dictionaryQueryComponents(key, dictionary)
                        } else if let array = value as? [AnyObject] {
                            components += arrayQueryComponents(key, array)
                        } else {
                            components.append(key, "\(value)")
                        }

                        return components
                    }

                    var components: [(String, String)] = []
                    for key in sorted(Array(parameters.keys), <) {
                        let value: AnyObject! = parameters[key]
                        components += queryComponents(key, value)
                    }

                    return join("&", components.map{"\($0)=\($1)"} as [String])
                }

                func encodesParametersInURL(method: Method) -> Bool {
                    switch method {
                    case .GET, .HEAD, .DELETE:
                        return true
                    default:
                        return false
                    }
                }

                if encodesParametersInURL(Method.fromRaw(request.HTTPMethod)!) {
                    let URLComponents = NSURLComponents(URL: mutableRequest.URL, resolvingAgainstBaseURL: false)
                    URLComponents.query = (URLComponents.query ? URLComponents.query + "&" : "") + query(parameters!)
                    mutableRequest.URL = URLComponents.URL
                } else {
                    if !mutableRequest.valueForHTTPHeaderField("Content-Type") {
                        mutableRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
                    }

                    mutableRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
                }

            case .JSON(let options):
                let data = NSJSONSerialization.dataWithJSONObject(parameters, options: options, error: &error)

                if data {
                    let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
                    mutableRequest.setValue("application/json; charset=\(charset)", forHTTPHeaderField: "Content-Type")
                    mutableRequest.HTTPBody = data
                }
            case .PropertyList(let (format, options)):
                let data = NSPropertyListSerialization.dataWithPropertyList(parameters, format: format, options: options, error: &error)

                if data {
                    let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
                    mutableRequest.setValue("application/x-plist; charset=\(charset)", forHTTPHeaderField: "Content-Type")
                    mutableRequest.HTTPBody = data
                }
            }

            return (mutableRequest, error)
        }
    }

    // MARK: -

    class Manager {
        class var sharedInstance: Manager {
            struct Singleton {
                static let instance = Manager()
            }

            return Singleton.instance
        }

        let delegate: SessionDelegate
        let session: NSURLSession!
        let operationQueue: NSOperationQueue = NSOperationQueue()

        var automaticallyStartsRequests: Bool = true

        lazy var defaultHeaders: [String: String] = {
            // Accept-Encoding HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
            let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5"

            // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
            let acceptLanguage: String = {
                var components: [String] = []
                for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as [String]) {
                    let q = 1.0 - (Double(index) * 0.1)
                    components.append("\(languageCode);q=\(q)")
                    if q <= 0.5 {
                        break
                    }
                }

                return components.reduce("", {$0 == "" ? $1 : "\($0),\($1)"})
            }()

            // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
            let userAgent: String = {
                if let info = NSBundle.mainBundle().infoDictionary {
                    let executable: AnyObject? = info[kCFBundleExecutableKey]
                    let bundle: AnyObject? = info[kCFBundleIdentifierKey]
                    let version: AnyObject? = info[kCFBundleVersionKey]
                    let os: AnyObject? = NSProcessInfo.processInfo()?.operatingSystemVersionString

                    var mutableUserAgent = NSMutableString(string: "\(executable!)/\(bundle!) (\(version!); OS \(os!))") as CFMutableString
                    let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
                    if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
                        return mutableUserAgent as NSString
                    }
                }

                return "Alamofire"
            }()

            return ["Accept-Encoding": acceptEncoding,
                    "Accept-Language": acceptLanguage,
                    "User-Agent": userAgent]
        }()

        required init(configuration: NSURLSessionConfiguration! = nil) {
            self.delegate = SessionDelegate()
            self.session = NSURLSession(configuration: configuration, delegate: self.delegate, delegateQueue: self.operationQueue)
        }

        deinit {
            self.session.invalidateAndCancel()
        }

        // MARK: -

        func request(request: NSURLRequest) -> Request {
            var mutableRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest<commit_msg>[Issue #35] nil-Coalescing User-Agent fields to Unknown<commit_after>// Alamofire.swift
//
// Copyright (c) 2014 Alamofire (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, 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
// 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 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,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.

import Foundation

public struct Alamofire {

    // HTTP Method Definitions; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html
    public enum Method: String {
        case OPTIONS = "OPTIONS"
        case GET = "GET"
        case HEAD = "HEAD"
        case POST = "POST"
        case PUT = "PUT"
        case PATCH = "PATCH"
        case DELETE = "DELETE"
        case TRACE = "TRACE"
        case CONNECT = "CONNECT"
    }

    public enum ParameterEncoding {
        case URL
        case JSON(options: NSJSONWritingOptions)
        case PropertyList(format: NSPropertyListFormat, options: NSPropertyListWriteOptions)

        func encode(request: NSURLRequest, parameters: [String: AnyObject]?) -> (NSURLRequest, NSError?) {
            if parameters == nil {
                return (request, nil)
            }

            var mutableRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest
            var error: NSError? = nil

            switch self {
            case .URL:
                func query(parameters: [String: AnyObject]) -> String! {
                    func queryComponents(key: String, value: AnyObject) -> [(String, String)] {
                        func dictionaryQueryComponents(key: String, dictionary: [String: AnyObject]) -> [(String, String)] {
                            var components: [(String, String)] = []
                            for (nestedKey, value) in dictionary {
                                components += queryComponents("\(key)[\(nestedKey)]", value)
                            }

                            return components
                        }

                        func arrayQueryComponents(key: String, array: [AnyObject]) -> [(String, String)] {
                            var components: [(String, String)] = []
                            for value in array {
                                components += queryComponents("\(key)[]", value)
                            }

                            return components
                        }

                        var components: [(String, String)] = []
                        if let dictionary = value as? [String: AnyObject] {
                            components += dictionaryQueryComponents(key, dictionary)
                        } else if let array = value as? [AnyObject] {
                            components += arrayQueryComponents(key, array)
                        } else {
                            components.append(key, "\(value)")
                        }

                        return components
                    }

                    var components: [(String, String)] = []
                    for key in sorted(Array(parameters.keys), <) {
                        let value: AnyObject! = parameters[key]
                        components += queryComponents(key, value)
                    }

                    return join("&", components.map{"\($0)=\($1)"} as [String])
                }

                func encodesParametersInURL(method: Method) -> Bool {
                    switch method {
                    case .GET, .HEAD, .DELETE:
                        return true
                    default:
                        return false
                    }
                }

                if encodesParametersInURL(Method.fromRaw(request.HTTPMethod)!) {
                    let URLComponents = NSURLComponents(URL: mutableRequest.URL, resolvingAgainstBaseURL: false)
                    URLComponents.query = (URLComponents.query ? URLComponents.query + "&" : "") + query(parameters!)
                    mutableRequest.URL = URLComponents.URL
                } else {
                    if !mutableRequest.valueForHTTPHeaderField("Content-Type") {
                        mutableRequest.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
                    }

                    mutableRequest.HTTPBody = query(parameters!).dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
                }

            case .JSON(let options):
                let data = NSJSONSerialization.dataWithJSONObject(parameters, options: options, error: &error)

                if data {
                    let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
                    mutableRequest.setValue("application/json; charset=\(charset)", forHTTPHeaderField: "Content-Type")
                    mutableRequest.HTTPBody = data
                }
            case .PropertyList(let (format, options)):
                let data = NSPropertyListSerialization.dataWithPropertyList(parameters, format: format, options: options, error: &error)

                if data {
                    let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
                    mutableRequest.setValue("application/x-plist; charset=\(charset)", forHTTPHeaderField: "Content-Type")
                    mutableRequest.HTTPBody = data
                }
            }

            return (mutableRequest, error)
        }
    }

    // MARK: -

    class Manager {
        class var sharedInstance: Manager {
            struct Singleton {
                static let instance = Manager()
            }

            return Singleton.instance
        }

        let delegate: SessionDelegate
        let session: NSURLSession!
        let operationQueue: NSOperationQueue = NSOperationQueue()

        var automaticallyStartsRequests: Bool = true

        lazy var defaultHeaders: [String: String] = {
            // Accept-Encoding HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.3
            let acceptEncoding: String = "gzip;q=1.0,compress;q=0.5"

            // Accept-Language HTTP Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4
            let acceptLanguage: String = {
                var components: [String] = []
                for (index, languageCode) in enumerate(NSLocale.preferredLanguages() as [String]) {
                    let q = 1.0 - (Double(index) * 0.1)
                    components.append("\(languageCode);q=\(q)")
                    if q <= 0.5 {
                        break
                    }
                }

                return components.reduce("", {$0 == "" ? $1 : "\($0),\($1)"})
            }()

            // User-Agent Header; see http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.43
            let userAgent: String = {
                if let info = NSBundle.mainBundle().infoDictionary {
                    let executable: AnyObject = info[kCFBundleExecutableKey] ?? "Unknown"
                    let bundle: AnyObject = info[kCFBundleIdentifierKey] ?? "Unknown"
                    let version: AnyObject = info[kCFBundleVersionKey] ?? "Unknown"
                    let os: AnyObject = NSProcessInfo.processInfo()?.operatingSystemVersionString ?? "Unknown"

                    var mutableUserAgent = NSMutableString(string: "\(executable)/\(bundle) (\(version); OS \(os))") as CFMutableString
                    let transform = NSString(string: "Any-Latin; Latin-ASCII; [:^ASCII:] Remove") as CFString
                    if CFStringTransform(mutableUserAgent, nil, transform, 0) == 1 {
                        return mutableUserAgent as NSString
                    }
                }

                return "Alamofire"
            }()

            return ["Accept-Encoding": acceptEncoding,
                    "Accept-Language": acceptLanguage,
                    "User-Agent": userAgent]
        }()

        required init(configuration: NSURLSessionConfiguration! = nil) {
            self.delegate = SessionDelegate()
            self.session = NSURLSession(configuration: configuration, delegate: self.delegate, delegateQueue: self.operationQueue)
        }

        deinit {
            self.session.invalidateAndCancel()
        }

        // MARK: -

        func request(request: NSURLRequest) -> Request {
            var mutableRequest: NSMutableURLRequest! = request.mutableCopy() as NSMutableURLRequest
{'fraction_non_alphanumeric': 0.09362677182137909, 'fraction_numerical': 0.008419482041990835, 'mean_word_length': 1.7273652085452695, 'pattern_counts': {'":': 6, '<': 7, '<?xml version=': 0, '>': 17, 'https://': 0, 'lorem ipsum': 0, 'www.': 10, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4899207', 'n_tokens_mistral': 4735, 'n_tokens_neox': 4333, 'n_words': 1223}