<commit_before>//
//  Project.swift
//  Buildasaur
//
//  Created by <NAME> on 14/02/2015.
//  Copyright (c) 2015 <NAME>. All rights reserved.
//

import Foundation
import BuildaUtils
import XcodeServerSDK
import ReactiveCocoa

public class Project {
    
    public var url: NSURL {
        return NSURL(fileURLWithPath: self._config.url, isDirectory: true)
    }
    
    public let config: MutableProperty<ProjectConfig>
    
    private var _config: ProjectConfig {
        return self.config.value
    }
    
    public var urlString: String { return self.url.absoluteString }
    public var privateSSHKey: String? { return self.getContentsOfKeyAtPath(self._config.privateSSHKeyPath) }
    public var publicSSHKey: String? { return self.getContentsOfKeyAtPath(self._config.publicSSHKeyPath) }
    
    public var availabilityState: AvailabilityCheckState = .Unchecked
    
    private(set) public var workspaceMetadata: WorkspaceMetadata?
    
    public init(config: ProjectConfig) throws {
        
        self.config = MutableProperty<ProjectConfig>(config)
        self.setupBindings()
        try self.refreshMetadata()
    }
    
    private init(original: Project, forkOriginURL: String) throws {
        
        self.config = MutableProperty<ProjectConfig>(original.config.value)
        self.workspaceMetadata = try original.workspaceMetadata?.duplicateWithForkURL(forkOriginURL)
    }
    
    private func setupBindings() {
        
        self.config.producer.startWithNext { [weak self] _ in
            _ = try? self?.refreshMetadata()
        }
    }
    
    public func duplicateForForkAtOriginURL(forkURL: String) throws -> Project {
        return try Project(original: self, forkOriginURL: forkURL)
    }
    
    public class func attemptToParseFromUrl(url: NSURL) throws -> WorkspaceMetadata {
        return try Project.loadWorkspaceMetadata(url)
    }

    private func refreshMetadata() throws {
        let meta = try Project.attemptToParseFromUrl(self.url)
        self.workspaceMetadata = meta
    }
    
    public func schemes() -> [XcodeScheme] {
        
        let schemes = XcodeProjectParser.sharedSchemesFromProjectOrWorkspaceUrl(self.url)
        return schemes
    }
    
    private class func loadWorkspaceMetadata(url: NSURL) throws -> WorkspaceMetadata {
        
        return try XcodeProjectParser.parseRepoMetadataFromProjectOrWorkspaceURL(url)
    }
    
    public func serviceRepoName() -> String? {
        
        guard let meta = self.workspaceMetadata else { return nil }
        
        let projectUrl = meta.projectURL
        let service = meta.service
        
        let originalStringUrl = projectUrl.absoluteString
        let stringUrl = originalStringUrl.lowercaseString
        
        /*
        both https and ssh repos on github have a form of:
        {https://|git@}SERVICE_URL{:|/}organization/repo.git
        here I need the organization/repo bit, which I'll do by finding "SERVICE_URL" and shifting right by one
        and scan up until ".git"
        */
        
        let serviceUrl = service.hostname().lowercaseString
        if let githubRange = stringUrl.rangeOfString(serviceUrl, options: NSStringCompareOptions(), range: nil, locale: nil),
            let dotGitRange = stringUrl.rangeOfString(".git", options: NSStringCompareOptions.BackwardsSearch, range: nil, locale: nil) {
                
                let start = githubRange.endIndex.advancedBy(1)
                let end = dotGitRange.startIndex
            
                let repoName = originalStringUrl[start ..< end]
                return repoName
        }
        return nil
    }

    private func getContentsOfKeyAtPath(path: String) -> String? {<commit_msg>Github issue #244: Sometimes github strings do not have ".git" attached to the end. I have a fix that will address both kinds of strings to extract the repo name<commit_after>//
//  Project.swift
//  Buildasaur
//
//  Created by <NAME> on 14/02/2015.
//  Copyright (c) 2015 <NAME>. All rights reserved.
//

import Foundation
import BuildaUtils
import XcodeServerSDK
import ReactiveCocoa

public class Project {
    
    public var url: NSURL {
        return NSURL(fileURLWithPath: self._config.url, isDirectory: true)
    }
    
    public let config: MutableProperty<ProjectConfig>
    
    private var _config: ProjectConfig {
        return self.config.value
    }
    
    public var urlString: String { return self.url.absoluteString }
    public var privateSSHKey: String? { return self.getContentsOfKeyAtPath(self._config.privateSSHKeyPath) }
    public var publicSSHKey: String? { return self.getContentsOfKeyAtPath(self._config.publicSSHKeyPath) }
    
    public var availabilityState: AvailabilityCheckState = .Unchecked
    
    private(set) public var workspaceMetadata: WorkspaceMetadata?
    
    public init(config: ProjectConfig) throws {
        
        self.config = MutableProperty<ProjectConfig>(config)
        self.setupBindings()
        try self.refreshMetadata()
    }
    
    private init(original: Project, forkOriginURL: String) throws {
        
        self.config = MutableProperty<ProjectConfig>(original.config.value)
        self.workspaceMetadata = try original.workspaceMetadata?.duplicateWithForkURL(forkOriginURL)
    }
    
    private func setupBindings() {
        
        self.config.producer.startWithNext { [weak self] _ in
            _ = try? self?.refreshMetadata()
        }
    }
    
    public func duplicateForForkAtOriginURL(forkURL: String) throws -> Project {
        return try Project(original: self, forkOriginURL: forkURL)
    }
    
    public class func attemptToParseFromUrl(url: NSURL) throws -> WorkspaceMetadata {
        return try Project.loadWorkspaceMetadata(url)
    }

    private func refreshMetadata() throws {
        let meta = try Project.attemptToParseFromUrl(self.url)
        self.workspaceMetadata = meta
    }
    
    public func schemes() -> [XcodeScheme] {
        
        let schemes = XcodeProjectParser.sharedSchemesFromProjectOrWorkspaceUrl(self.url)
        return schemes
    }
    
    private class func loadWorkspaceMetadata(url: NSURL) throws -> WorkspaceMetadata {
        
        return try XcodeProjectParser.parseRepoMetadataFromProjectOrWorkspaceURL(url)
    }
    
    public func serviceRepoName() -> String? {
        
        guard let meta = self.workspaceMetadata else { return nil }
        
        let projectUrl = meta.projectURL
        let service = meta.service
        
        let originalStringUrl = projectUrl.absoluteString
        let stringUrl = originalStringUrl.lowercaseString
        
        /*
        both https and ssh repos on github have a form of:
        {https://|git@}SERVICE_URL{:|/}organization/repo.git
        here I need the organization/repo bit, which I'll do by finding "SERVICE_URL" and shifting right by one
        and scan up until ".git"
        */
        
        let serviceUrl = service.hostname().lowercaseString
        let dotGitRange = stringUrl.rangeOfString(".git", options: NSStringCompareOptions.BackwardsSearch, range: nil, locale: nil) ?? Range(start: stringUrl.endIndex, end: stringUrl.endIndex)
        if let githubRange = stringUrl.rangeOfString(serviceUrl, options: NSStringCompareOptions(), range: nil, locale: nil){
                
                let start = githubRange.endIndex.advancedBy(1)
                let end = dotGitRange.startIndex
            
                let repoName = originalStringUrl[start ..< end]
                return repoName
        }
        return nil
    }

    private func getContentsOfKeyAtPath(path: String) -> String? {
{'fraction_non_alphanumeric': 0.07757607418048844, 'fraction_numerical': 0.0037873840929868096, 'mean_word_length': 2.5684995340167753, 'pattern_counts': {'":': 0, '<': 15, '<?xml version=': 0, '>': 25, 'https://': 2, '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': '1966426', 'n_tokens_mistral': 2081, 'n_tokens_neox': 2029, 'n_words': 535}