Xcodeproj.swift 6.76 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

Drew's avatar
Drew committed
21 22 23
//test via
//WRAPPER_EXTENSION=xctest PROJECT_FILE_PATH=~/Downloads/NaOH.xcodeproj TARGETNAME=NaOHiOSTestHostAppTests .atllbuild/products/caroline-static-tool

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

///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)
    let tests = findTests(paths)

    var xcTestFile = ""
Drew's avatar
Drew committed
42
    xcTestFile += ApacheLicense
Drew's avatar
Drew committed
43 44 45

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

    if !paths.contains(generatedFilePath) {
Drew's avatar
Drew committed
62
        print("error: You need to add CarolineXCTest.swift to your Xcode Project.  (See \(generatedFilePath))")
Drew's avatar
Drew committed
63 64 65 66 67 68
        exit(1)
    }

    return true
}

69
func parseXcodeProj(_ fileName: String, targetName: String) -> [String] {
Drew's avatar
Drew committed
70 71
    let pathToXcodeProject = fileName.directoryPath
    let file = try! String(file: fileName + "/project.pbxproj")
Drew's avatar
Drew committed
72 73 74 75
    let plistCharacters = "[-[:space:][:alnum:]/}{;_,=<>\"*\\().+]"
    
    //note that inside a character class, we only escape `^ - [ ]`
    // `\` is literal, not escape, so we have to use "clever placement"
Drew's avatar
Drew committed
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
    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.")
    }

Drew's avatar
Drew committed
103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126
    //calculate groups
    //This maps a filename to the path of its group
    //we do this up-front to avoid O(N^2)
    let allGroupsRegex = try! Regex(pattern: "/\\* Begin PBXGroup section \\*/\(plistCharacters)*/\\* End PBXGroup section \\*/")
    guard let allGroups = try! allGroupsRegex.findFirst(inString: file)?.entireMatch.description else {
        fatalError("Can't find group section")
    }
    let groupRegex = try! Regex(pattern: "([[:upper:][:digit:]]{24}) /\\*[^\n]*\\*/ = \\{[^\\}]+};")
    let groupChildSectionRegex = try! Regex(pattern: "children = \\([^\\)]+\\);")
    let groupIndividualChildRegex = try! Regex(pattern: "[[:upper:][:digit:]]{24}")
    let pathRegex = try! Regex(pattern: "path = ([^;]+);")

    var pbxBuildRefToGroupPath: [String:String] = [:]
    for group in groupRegex.findAll(inString: allGroups) {
        let childSection = try! groupChildSectionRegex.findFirst(inString: group.entireMatch.description)!
        ("got child section",childSection)
        guard let path = try! pathRegex.findFirst(inString: group.entireMatch.description) else {
            continue
        }
        for child in groupIndividualChildRegex.findAll(inString: childSection.entireMatch.description) {
            pbxBuildRefToGroupPath[child.entireMatch.description] = path.groups[0]!.description
        }
    }

Drew's avatar
Drew committed
127 128 129 130 131 132 133 134 135 136 137 138 139 140
    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)")
        }
141
        if path.hasSuffix("\"") { path.remove(at: path.characters.index(before: path.characters.endIndex))}
Drew's avatar
Drew committed
142 143 144 145
        guard let groupPath = pbxBuildRefToGroupPath[fileRef] else {
            fatalError("Can't calculate group path for file \(fileRef)")
        }
        paths.append("\(pathToXcodeProject)/\(groupPath)/\(path)")
Drew's avatar
Drew committed
146 147 148
    }
    return paths
}