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

Drew's avatar
Drew committed
15 16
import StandBack

Drew's avatar
Drew committed
17 18 19 20 21 22
#if os(Linux)
import Glibc
#else
import Darwin
#endif

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

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

///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
44
    xcTestFile += ApacheLicense
Drew's avatar
Drew committed
45 46 47

    xcTestFile += "import XCTest\n"
    xcTestFile += "import CarolineCore\n"
Drew's avatar
Drew committed
48
    xcTestFile += "@testable import \(target)\n"
Drew's avatar
Drew committed
49 50 51
    xcTestFile += "\n"
    xcTestFile += "class CarolineEngineTests: XCTestCase {\n"
    xcTestFile += "    func testAllCarolineTests() {\n"
52
    xcTestFile += allTestsDeclaration(tests: tests, indentation: 8) + "\n"
Drew's avatar
Drew committed
53
    xcTestFile += "        let engine = CarolineCoreEngine()\n"
Drew's avatar
Drew committed
54 55 56
    xcTestFile += "        if !engine.testAll(allTests) {\n"
    xcTestFile += "            XCTFail(\"Caroline tests failed\")\n"
    xcTestFile += "        }\n"
Drew's avatar
Drew committed
57 58 59 60 61 62 63
    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
64
        print("error: You need to add CarolineXCTest.swift to your Xcode Project.  (See \(generatedFilePath))")
Drew's avatar
Drew committed
65 66 67 68 69 70
        exit(1)
    }

    return true
}

71
func parseXcodeProj(_ fileName: String, targetName: String) -> [String] {
Drew's avatar
Drew committed
72 73
    let pathToXcodeProject = fileName.directoryPath
    let file = try! String(file: fileName + "/project.pbxproj")
Drew's avatar
Drew committed
74 75 76 77
    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
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
    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
105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
    //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
129 130 131 132 133 134 135 136 137 138 139 140 141 142
    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)")
        }
143
        if path.hasSuffix("\"") { path.remove(at: path.characters.index(before: path.characters.endIndex))}
Drew's avatar
Drew committed
144 145 146 147
        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
148 149 150
    }
    return paths
}