PackageAtbin.swift 7.84 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
// Copyright (c) 2016 Anarchy Tools Contributors.
//
// 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.
import atpkg
import atfoundation

class PackageAtbin:Tool {
    private enum Options: String {
        case Name = "name"
        case Platforms = "platforms"
        case AtllbuildTask = "atllbuild-task"
Drew's avatar
Drew committed
22
        case Compress = "compress"
Drew's avatar
Drew committed
23 24
    }

Drew's avatar
Drew committed
25
    func run(task: Task) {
Drew's avatar
Drew committed
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69

        guard let n_ = task[Options.Name.rawValue] else {
            fatalError("No \(Options.Name.rawValue) for \(task)")
        }
        guard case .StringLiteral(let name) = n_ else {
            fatalError("Non-string \(Options.Name.rawValue) for \(task)")
        }

        guard let t_ = task[Options.AtllbuildTask.rawValue] else {
            fatalError("No \(Options.AtllbuildTask.rawValue) for \(task)")
        }
        guard case .StringLiteral(let atllbuildTaskName) = t_ else {
            fatalError("Non-string \(Options.AtllbuildTask.rawValue) for \(task)")
        }
        guard let atllbuildTask = task.package.tasks[atllbuildTaskName]  else {
            fatalError("Unknown atllbuild task \(atllbuildTaskName) for \(task)")
        }

        //rm atbin if exists
        let atbinPath = Path("bin/\(name).atbin")
        let _ = try? FS.removeItem(path: atbinPath, recursive: true)
        try! FS.createDirectory(path: atbinPath, intermediate: true)

        //create working directory for lipo
        let workDir = Path(".atllbuild/lipo/")
        try! FS.createDirectory(path: workDir, intermediate: true)

        //restore old platform before leaving
        let oldPlatform = Platform.targetPlatform
        defer { Platform.targetPlatform = oldPlatform }

        guard case .some(.StringLiteral(let outputTypeString)) = atllbuildTask[ATllbuild.Options.OutputType.rawValue] else {
            fatalError("No \(ATllbuild.Options.OutputType.rawValue) for \(atllbuildTask) ")
        }

        guard let outputType = ATllbuild.OutputType(rawValue: outputTypeString) else {
            fatalError("Unknown \(ATllbuild.Options.OutputType.rawValue) \(outputTypeString)")
        }


        guard case .some(.StringLiteral(let outputName)) = atllbuildTask[ATllbuild.Options.Name.rawValue] else {
            fatalError("No \(ATllbuild.Options.Name.rawValue) for \(atllbuildTask)")
        }

70 71 72 73 74
        //for clarity, in the code below, we use moduleName when we refer to modules
        //and outputName when we refer to the atbin output.
        //by definition, the atbin output is the module name, but we might change this definition.  Who knows.
        let moduleName = outputName

Drew's avatar
Drew committed
75 76 77
        let payloadFileName: String
        switch(outputType) {
            case .DynamicLibrary:
78
            payloadFileName = "\(moduleName)\(Platform.targetPlatform.dynamicLibraryExtension)"
Drew's avatar
Drew committed
79
            case .StaticLibrary:
80
            payloadFileName = "\(moduleName).a"
Drew's avatar
Drew committed
81
            case .Executable:
82 83 84 85
            if case.some(.StringLiteral(let e)) = atllbuildTask[ATllbuild.Options.ExecutableName.rawValue] {
                payloadFileName = e
            }
            else  { payloadFileName = moduleName }
Drew's avatar
Drew committed
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
        }

        guard case .some(.Vector(let platformArray)) = task[Options.Platforms.rawValue] else {
            fatalError("No \(Options.Platforms.rawValue) for \(task)")
        }

        var requestedBuildPlatforms : [String] = []
        for requestedPlatform in platformArray {
            guard case .StringLiteral(let p) = requestedPlatform else {
                fatalError("Non-string platform \(requestedPlatform)")
            }
            requestedBuildPlatforms.append(p)
        }

        let targetPlatforms: [Platform]
        if requestedBuildPlatforms == ["all"] {
            targetPlatforms = Platform.targetPlatform.allPlatforms
        }else {
            targetPlatforms = Platform.targetPlatform.allPlatforms.filter({requestedBuildPlatforms.contains($0.description)})
        } 

        if targetPlatforms.count == 0 {
            print("Warning: The intersection of \(requestedBuildPlatforms) and \(Platform.targetPlatform.allPlatforms) is the empty set; won't build atbin")
            return
        }
        //iterate through supported platforms
        for platform in targetPlatforms {
            Platform.targetPlatform = platform
            //run the underlying atbuild task
Drew's avatar
Drew committed
115
            TaskRunner.runTask(task: atllbuildTask, package: task.package, force: true)
Drew's avatar
Drew committed
116 117 118 119

            //copy payload to lipo location
            try! FS.copyItem(from: Path(".atllbuild/products/\(payloadFileName)"), to: workDir.join(Path("\(payloadFileName).\(Platform.targetPlatform)")))

120
            let modulePath = Path(".atllbuild/products/\(moduleName).swiftmodule")
Drew's avatar
Drew committed
121 122 123 124
            if FS.fileExists(path: modulePath) {
                try! FS.copyItem(from: modulePath, to: atbinPath.join(Path("\(platform).swiftmodule")))
            }

125
            let docPath = Path(".atllbuild/products/\(moduleName).swiftdoc")
Drew's avatar
Drew committed
126 127 128 129
            if FS.fileExists(path: docPath) {
                try! FS.copyItem(from: docPath, to: atbinPath.join(Path("\(platform).swiftdoc")))
            }

130
            let moduleMapPath = Path(".atllbuild/products/\(moduleName).modulemap")
Drew's avatar
Drew committed
131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146
            if FS.fileExists(path: moduleMapPath) {
                try! FS.copyItem(from: moduleMapPath, to: atbinPath.join(Path("module.modulemap")))
            }
        }

        //lipo outputs
        switch(oldPlatform) {
            case .Linux:
            //no lipo, only one arch anyway
            try! FS.copyItem(from: workDir.join(Path("\(payloadFileName).\(Platform.targetPlatform)")), to: atbinPath.join(Path(payloadFileName)))

            case .OSX, .iOS, .iOSGeneric:
            var lipoCmd = "lipo -output bin/\(name).atbin/\(payloadFileName) -create "
            for platform in targetPlatforms {
                lipoCmd += "-arch \(platform.architecture) .atllbuild/lipo/\(payloadFileName).\(platform) "
            }
Drew's avatar
Drew committed
147
            anarchySystem(lipoCmd)
Drew's avatar
Drew committed
148 149
        }

Drew's avatar
Drew committed
150
        //generate compiled.atpkg
Drew's avatar
Drew committed
151 152 153 154 155 156 157 158 159 160 161
        var s = ""
        s += "(package\n"
        s += ":name \"\(name)\"\n"
        s += ":payload \"\(payloadFileName)\"\n"
        s += ":platforms ["
        for platform in targetPlatforms {
            s += "\"\(platform)\" "
        }
        s += "]\n"
        s += ":type \"\(outputType.rawValue)\"\n"
        s += ")\n"
Drew's avatar
Drew committed
162
        try! s.write(to: atbinPath.join(Path("compiled.atpkg")))
Drew's avatar
Drew committed
163 164

        if task[Options.Compress.rawValue]?.bool == true {
165 166 167 168 169 170 171 172 173

            let tarxz: String
            if let v = task.package.version {
                tarxz = "bin/\(name)-\(v)-\(Platform.targetPlatform).atbin.tar.xz"
            }
            else {
                tarxz = "bin/\(name)-\(Platform.targetPlatform).atbin.tar.xz"
            }
             
Drew's avatar
Drew committed
174 175 176
            let cmd: String
            switch Platform.hostPlatform {
                case .OSX:
177 178 179
                let fc = currentConfiguration.fastCompile == true
                let compressionLevel = fc ? "0" :"9"
                cmd = "tar c --options \"xz:compression-level=\(compressionLevel)\" -Jf \(tarxz) bin/\(name).atbin -C bin"
Drew's avatar
Drew committed
180
                case .Linux:
181 182 183
                let fc = currentConfiguration.fastCompile == true
                let compressionLevel = fc ? "0" :"8"
                cmd = "XZ_OPT=-\(compressionLevel) tar cJf \(tarxz) bin/\(name).atbin -C bin"
Drew's avatar
Drew committed
184 185 186
                default:
                fatalError("Unsupported host platform \(Platform.hostPlatform)")
            }
Drew's avatar
Drew committed
187
            anarchySystem(cmd)
Drew's avatar
Drew committed
188
        }
Drew's avatar
Drew committed
189
    }
Drew's avatar
Drew committed
190
}