<commit_before>//
//  Keychain.swift
//  SwiftKeychain
//
//  Created by <NAME> on 11/11/14.
//  Copyright (c) 2014 <NAME>. All rights reserved.
//

import Foundation

public class Keychain: KeychainService {
    
    public let accessMode: NSString
    public let serviceName: String
    public var accessGroup: String?
    private let errorDomain = "swift.keychain.error.domain"
    
    public class var sharedKeychain: Keychain {
        
        struct Singleton {
            
            static let instance = Keychain()
        }
        
        return Singleton.instance
    }
    
    ///////////////////////////////////////////////////////
    // MARK: - Initializers
    ///////////////////////////////////////////////////////
    
    public init(serviceName name: String, accessMode: NSString = kSecAttrAccessibleWhenUnlocked, group: String? = nil) {
        
        self.accessMode = accessMode
        serviceName = name
        accessGroup = group
    }
    
    public convenience init() {
        
        self.init(serviceName: "swift.keychain")
    }
    
    ///////////////////////////////////////////////////////
    // MARK: - Methods
    ///////////////////////////////////////////////////////
    
    private func errorForStatusCode(statusCode: OSStatus) -> NSError {
        
        return NSError(domain: errorDomain, code: Int(statusCode), userInfo: nil)
    }
    
    ///////////////////////////////////////////////////////
    // MARK: - KeychainService
    ///////////////////////////////////////////////////////
    
    public func add(key: KeychainItem) -> NSError? {
        
        let secretFields = key.fieldsToLock()
        
        if secretFields.count == 0 {
            
            return errorForStatusCode(errSecParam)
        }
        
        let query = key.makeQueryForKeychain(self)
            query.addFields(secretFields)
        
        let status = SecItemAdd(query.fields, nil)
        
        if status != errSecSuccess {
            
            return errorForStatusCode(status)
        }
        
        return nil
    }
    
    public func update(key: KeychainItem) -> NSError? {
        
        let changes = key.fieldsToLock()
        
        if changes.count == 0 {
            
            return errorForStatusCode(errSecParam)
        }
        
        let query = key.makeQueryForKeychain(self)
        let status = SecItemUpdate(query.fields, changes)
        
        if status != errSecSuccess {
            
            return errorForStatusCode(status)
        }
        
        return nil
    }
    
    public func remove(key: KeychainItem) -> NSError? {
        
        let query = key.makeQueryForKeychain(self)
        let status = SecItemDelete(query.fields)
        
        if status != errSecSuccess {
            
            return errorForStatusCode(status)
        }
        
        return nil
    }
    
    public func get<T: BaseKey>(key: T) -> (item: T?, error: NSError?) {
        
        var query = key.makeQueryForKeychain(self)
            query.shouldReturnData()
        
        var result: AnyObject?
        
        let status = withUnsafeMutablePointer(&result) {
            cfPointer -> OSStatus in
        
            SecItemCopyMatching(query.fields, UnsafeMutablePointer(cfPointer))
        }<commit_msg>Detect item-not-found in `update` and perform an `add`<commit_after>//
//  Keychain.swift
//  SwiftKeychain
//
//  Created by <NAME> on 11/11/14.
//  Copyright (c) 2014 <NAME>. All rights reserved.
//

import Foundation

public class Keychain: KeychainService {
    
    public let accessMode: NSString
    public let serviceName: String
    public var accessGroup: String?
    private let errorDomain = "swift.keychain.error.domain"
    
    public class var sharedKeychain: Keychain {
        
        struct Singleton {
            
            static let instance = Keychain()
        }
        
        return Singleton.instance
    }
    
    ///////////////////////////////////////////////////////
    // MARK: - Initializers
    ///////////////////////////////////////////////////////
    
    public init(serviceName name: String, accessMode: NSString = kSecAttrAccessibleWhenUnlocked, group: String? = nil) {
        
        self.accessMode = accessMode
        serviceName = name
        accessGroup = group
    }
    
    public convenience init() {
        
        self.init(serviceName: "swift.keychain")
    }
    
    ///////////////////////////////////////////////////////
    // MARK: - Methods
    ///////////////////////////////////////////////////////
    
    private func errorForStatusCode(statusCode: OSStatus) -> NSError {
        
        return NSError(domain: errorDomain, code: Int(statusCode), userInfo: nil)
    }
    
    ///////////////////////////////////////////////////////
    // MARK: - KeychainService
    ///////////////////////////////////////////////////////
    
    public func add(key: KeychainItem) -> NSError? {
        
        let secretFields = key.fieldsToLock()
        
        if secretFields.count == 0 {
            
            return errorForStatusCode(errSecParam)
        }
        
        let query = key.makeQueryForKeychain(self)
            query.addFields(secretFields)
        
        let status = SecItemAdd(query.fields, nil)
        
        if status != errSecSuccess {
            
            return errorForStatusCode(status)
        }
        
        return nil
    }
    
    /**
        Updates or adds the given keychain item.
        
        :param: key The keychain item to update or add
        :returns: An NSError if something goes wrong, nil otherwise
     */
    public func update(key: KeychainItem) -> NSError? {
        let changes = key.fieldsToLock()
        if changes.count == 0 {
            
            return errorForStatusCode(errSecParam)
        }
        
        let query = key.makeQueryForKeychain(self)
        let status = SecItemUpdate(query.fields, changes)
        
        if status != errSecSuccess {
            if status == errSecItemNotFound {
                return add(key)
            }
            return errorForStatusCode(status)
        }
        
        return nil
    }
    
    public func remove(key: KeychainItem) -> NSError? {
        
        let query = key.makeQueryForKeychain(self)
        let status = SecItemDelete(query.fields)
        
        if status != errSecSuccess {
            
            return errorForStatusCode(status)
        }
        
        return nil
    }
    
    public func get<T: BaseKey>(key: T) -> (item: T?, error: NSError?) {
        
        var query = key.makeQueryForKeychain(self)
            query.shouldReturnData()
        
        var result: AnyObject?
        
        let status = withUnsafeMutablePointer(&result) {
            cfPointer -> OSStatus in
        
            SecItemCopyMatching(query.fields, UnsafeMutablePointer(cfPointer))
        }
{'fraction_non_alphanumeric': 0.16606860915745658, 'fraction_numerical': 0.0034448112530500933, 'mean_word_length': 1.257207644962747, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 21, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, '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': '5756213', 'n_tokens_mistral': 1769, 'n_tokens_neox': 1720, 'n_words': 409}