Xcodeproj.swift 4.98 KB
Newer Older
Drew's avatar
Drew committed
1 2 3 4 5 6 7 8 9 10 11 12 13
// Copyright (c) 2016 Drew Crawford.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
Drew's avatar
Drew committed
14 15 16 17 18 19 20

#if os(Linux)
import Glibc
#else
import Darwin
#endif

21
func env_(_ variable: String) -> String? {
Drew's avatar
Drew committed
22 23
    let env = getenv(variable)
    if env == nil { return nil }
24
    return String(validatingUTF8: env!)
Drew's avatar
Drew committed
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
}

///Performs XCTest integration
///- returns: True if XCTest integration was performed.
///This means we can avoid doing atbuild-like activity.
func performXcodeIntegration() -> Bool {
    if env_("WRAPPER_EXTENSION") != "xctest" { return false }
    print("performing XCTest integration")
    let xcodeProject = env_("PROJECT_FILE_PATH")!
    let target = env_("TARGETNAME")!
    let paths = parseXcodeProj(xcodeProject, targetName: target)
    print(paths)
    let tests = findTests(paths)

    var xcTestFile = ""
Drew's avatar
Drew committed
40
    xcTestFile += ApacheLicense
Drew's avatar
Drew committed
41 42 43 44 45 46 47

    xcTestFile += "import XCTest\n"
    xcTestFile += "import CarolineCore\n"
    xcTestFile += "@testable import MyMacFramework\n"
    xcTestFile += "\n"
    xcTestFile += "class CarolineEngineTests: XCTestCase {\n"
    xcTestFile += "    func testAllCarolineTests() {\n"
48
    xcTestFile += allTestsDeclaration(tests: tests, indentation: 8) + "\n"
Drew's avatar
Drew committed
49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64
    xcTestFile += "        let engine = CarolineCoreEngine()\n"
    xcTestFile += "        engine.testAll(allTests)\n"
    xcTestFile += "    }\n"
    xcTestFile += "}\n"
    
    let generatedFilePath = "\(xcodeProject.directoryPath)/\(target)/CarolineXCTest.swift"
    try! xcTestFile.write(file: generatedFilePath)

    if !paths.contains(generatedFilePath) {
        print("You need to add \(generatedFilePath) to your Xcode Project.")
        exit(1)
    }

    return true
}

65
func parseXcodeProj(_ fileName: String, targetName: String) -> [String] {
Drew's avatar
Drew committed
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109
    let pathToXcodeProject = fileName.directoryPath
    let file = try! String(file: fileName + "/project.pbxproj")
    let plistCharacters = "[[:space:][:alnum:]/\\*={};_\"\\(\\),\\.\\-]"
    let allTargetsRegex = try! Regex(pattern: "/\\* Begin PBXNativeTarget section \\*/\(plistCharacters)*/\\* End PBXNativeTarget section \\*/")
    
    guard let allTargets = try! allTargetsRegex.findFirst(inString: file)?.entireMatch.description else {
        fatalError("Can't find any targets for file \(fileName)")
    }
    
    let searchTargetRegex = try! Regex(pattern: "/\\* \(targetName) \\*/ = {\(plistCharacters)*};")
    guard let searchTarget = try! searchTargetRegex.findFirst(inString: allTargets)?.entireMatch.description else {
        fatalError("Can't find so-called target \(targetName)")
    }

    let sourcePhaseRegex = try! Regex(pattern: "([[:upper:][:digit:]]{24}) /\\* Sources \\*/")
    guard let sourcePhase = try! sourcePhaseRegex.findFirst(inString: searchTarget)?.groups[0]?.description else {
        fatalError("Can't find a source phase for \(searchTarget)")
    }


    let sourcePhaseDefinitionRegex = try! Regex(pattern: "\(sourcePhase) /\\* Sources \\*/ = {[^\\}]+};")
    guard let sourcePhaseDefinition = try! sourcePhaseDefinitionRegex.findFirst(inString: file)?.entireMatch.description else {
        fatalError("Can't find source phase definition for source phase \(sourcePhase)")
    }
    
    let filesListingRegex = try! Regex(pattern: "files = \\([^\\)]+);")
    guard let filesListing = try! filesListingRegex.findFirst(inString: sourcePhaseDefinition)?.entireMatch.description else {
        fatalError("Can't find filesListing for source phase.")
    }

    var paths: [String] = []
    let fileIDRegex = try! Regex(pattern: "([[:upper:][:digit:]]{24}) /\\*")
    for fileID_ in fileIDRegex.findAll(inString: filesListing) {
        guard let fileID = fileID_.groups[0] else {
            fatalError("No group for fileID \(fileID_)")
        }
        let fileRefRegex = try! Regex(pattern: "\(fileID) [^\n]* \\{[^\n]*fileRef = ([[:upper:][:digit:]]{24})")
        guard let fileRef = try! fileRefRegex.findFirst(inString: file)?.groups[0]?.description else {
            fatalError("Can't find fileRef for file \(fileID)")
        }
        let pathRegex = try! Regex(pattern: "\(fileRef) [^\n]*isa = PBXFileReference;[^\n]* path = [\"]?([^;]+);")
        guard var path = try! pathRegex.findFirst(inString: file)?.groups[0]?.description else {
            fatalError("Can't find path for file \(fileRef)")
        }
110
        if path.hasSuffix("\"") { path.remove(at: path.characters.index(before: path.characters.endIndex))}
Drew's avatar
Drew committed
111 112 113 114 115
        //this is cheating; the targetName may not be the same as the group, but fuck it
        paths.append("\(pathToXcodeProject)/\(targetName)/\(path)")
    }
    return paths
}