1/*
2 * Copyright 2014-2020 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license.
3 */
4
5
6/**
7 * Publish the platform JAR and POM so that consumers who depend on this module and can't read Gradle module
8 * metadata can still get the platform artifact and transitive dependencies from the POM
9 * (see details in https://youtrack.jetbrains.com/issue/KT-39184#focus=streamItem-27-4115233.0-0)
10 */
11project.ext.publishPlatformArtifactsInRootModule = { MavenPublication platformPublication ->
12    afterEvaluate {
13        XmlProvider platformXml = null
14
15        platformPublication.pom.withXml { platformXml = it }
16
17        publishing.publications.kotlinMultiplatform {
18            pom.withXml {
19                Node root = asNode()
20                // Remove the original content and add the content from the platform POM:
21                root.children().toList().each { root.remove(it as Node) }
22                platformXml.asNode().children().each { root.append(it as Node) }
23
24                // Adjust the self artifact ID, as it should match the root module's coordinates:
25                ((root.get("artifactId") as NodeList).get(0) as Node).setValue(artifactId)
26
27                // Set packaging to POM to indicate that there's no artifact:
28                root.appendNode("packaging", "pom")
29
30                // Remove the original platform dependencies and add a single dependency on the platform module:
31                Node dependencies = (root.get("dependencies") as NodeList).get(0) as Node
32                dependencies.children().toList().each { dependencies.remove(it as Node) }
33                Node singleDependency = dependencies.appendNode("dependency")
34                singleDependency.appendNode("groupId", platformPublication.groupId)
35                singleDependency.appendNode("artifactId", platformPublication.artifactId)
36                singleDependency.appendNode("version", platformPublication.version)
37                singleDependency.appendNode("scope", "compile")
38            }
39        }
40
41        tasks.matching { it.name == "generatePomFileForKotlinMultiplatformPublication"}.configureEach {
42            dependsOn(tasks["generatePomFileFor${platformPublication.name.capitalize()}Publication"])
43        }
44    }
45}