Xcodeproj.swift 5.87 KB
Newer Older
Drew's avatar
Drew committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/*
Copyright (C) 2016 Drew Crawford
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions
are met:
1. Redistributions of source code must retain the above copyright
   notice, this list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright
   notice, this list of conditions and the following disclaimer in the
   documentation  and/or other materials provided with the distribution.
3. Neither the names of the copyright holders nor the names of any
   contributors may be used to endorse or promote products derived from this
   software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
POSSIBILITY OF SUCH DAMAGE.
*/
#if os(Linux)
import Glibc
#else
import Darwin
#endif

35
func env_(_ variable: String) -> String? {
Drew's avatar
Drew committed
36 37
    let env = getenv(variable)
    if env == nil { return nil }
38
    return String(validatingUTF8: env!)
Drew's avatar
Drew committed
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
}

///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 = ""
    xcTestFile += MITLicense

    xcTestFile += "import XCTest\n"
    xcTestFile += "import CarolineCore\n"
    xcTestFile += "@testable import MyMacFramework\n"
    xcTestFile += "\n"
    xcTestFile += "class CarolineEngineTests: XCTestCase {\n"
    xcTestFile += "    func testAllCarolineTests() {\n"
62
    xcTestFile += allTestsDeclaration(tests: tests, indentation: 8) + "\n"
Drew's avatar
Drew committed
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78
    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
}

79
func parseXcodeProj(_ fileName: String, targetName: String) -> [String] {
Drew's avatar
Drew committed
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 110 111 112 113 114 115 116 117 118 119 120 121 122 123
    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)")
        }
124
        if path.hasSuffix("\"") { path.remove(at: path.characters.index(before: path.characters.endIndex))}
Drew's avatar
Drew committed
125 126 127 128 129
        //this is cheating; the targetName may not be the same as the group, but fuck it
        paths.append("\(pathToXcodeProject)/\(targetName)/\(path)")
    }
    return paths
}