aboutsummaryrefslogtreecommitdiff
path: root/gradle/interop-as-source-set-klib.gradle
blob: 62f2b7766be8e9512d74b66bfa500f4b57901bb0 (plain)
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
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/*
 * Copyright 2014-2020 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
 */

project.ext.registerInteropAsSourceSetOutput = { interop, sourceSet ->
    afterEvaluate {
        def cinteropTask = tasks.named(interop.interopProcessingTaskName)
        def cinteropKlib = cinteropTask.map { it.outputFile }
        def fakeCinteropCompilation = kotlin.targets["metadata"].compilations[sourceSet.name]
        def destination = fakeCinteropCompilation.compileKotlinTask.destinationDir

        def tempDir = "$buildDir/tmp/${sourceSet.name}UnpackedInteropKlib"

        def prepareKlibTaskProvider = tasks.register("prepare${sourceSet.name.capitalize()}InteropKlib", Sync) {
            from(files(zipTree(cinteropKlib).matching {
                exclude("targets/**", "default/targets/**")
            }).builtBy(cinteropTask))

            into(tempDir)

            doLast {
                def manifest140 = file("$tempDir/default/manifest")
                def manifest1371 = file("$tempDir/manifest")
                def manifest = manifest140.exists() ? manifest140 : manifest1371

                def lines = manifest.readLines()
                def modifiedLines = lines.collect { line ->
                    line.startsWith("depends=") ? "depends=stdlib ${manifest == manifest140 ? 'org.jetbrains.kotlin.native.platform.posix' : 'posix'}" :
                            line.startsWith("native_targets=") ? "native_targets=" :
                                    line
                }
                manifest.text = modifiedLines.join("\n")
            }
        }

        def copyCinteropTaskProvider = tasks.register("copy${sourceSet.name.capitalize()}CinteropKlib",  Zip) {
            from(fileTree(tempDir).builtBy(prepareKlibTaskProvider))
            destinationDirectory.set(destination)
            archiveFileName.set("${project.name}_${fakeCinteropCompilation.name}.klib")
            dependsOn cinteropTask
        }

        fakeCinteropCompilation.output.classesDirs.from(files().builtBy(copyCinteropTaskProvider))

        kotlin.sourceSets.matching {
            def visited = new HashSet()
            def visit
            visit = { s -> if (visited.add(s)) s.dependsOn.each { visit(it) } }
            visit(it)
            sourceSet in visited
        }.all {
            project.dependencies.add(implementationMetadataConfigurationName, files(cinteropKlib))
        }
    }
}