-
Notifications
You must be signed in to change notification settings - Fork 53
/
Copy pathDeployment.kt
375 lines (313 loc) · 13.5 KB
/
Deployment.kt
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
@file:Suppress("UNCHECKED_CAST")
import groovy.util.Node
import org.gradle.api.NamedDomainObjectCollection
import org.gradle.api.Project
import org.gradle.api.artifacts.Dependency
import org.gradle.api.artifacts.ProjectDependency
import org.gradle.api.plugins.ExtensionAware
import org.gradle.api.plugins.ExtraPropertiesExtension
import org.gradle.api.publish.PublishingExtension
import org.gradle.api.publish.maven.MavenPublication
import org.gradle.api.tasks.SourceSet
import org.gradle.api.tasks.SourceSetContainer
import org.gradle.configurationcache.extensions.capitalized
import org.gradle.jvm.tasks.Jar
import org.gradle.kotlin.dsl.support.uppercaseFirstChar
import org.gradle.kotlin.dsl.withGroovyBuilder
import org.gradle.plugins.signing.Sign
import org.gradle.plugins.signing.SigningExtension
import java.io.File
/**
* Configure deployment tasks and properties for a project using the provided [deployConfig].
*/
fun Project.configureDeployment(deployConfig: Deployed) {
if (this == rootProject) {
throw IllegalStateException("This method can not be called on the root project")
}
val credentials = DeployedCredentials(this)
// Configure root project (this only happens once
// and will raise an error on inconsistent data)
rootProject.configureRootDeployment(deployConfig, credentials)
val isAndroid = plugins.findPlugin("com.android.library") != null
val isGradlePlugin = plugins.hasPlugin("java-gradle-plugin")
apply {
plugin("maven-publish")
plugin("signing")
plugin("org.jetbrains.dokka")
}
// Create artifact tasks
val androidSourcesJar = tasks.create("androidSourcesJar", Jar::class.java) {
archiveClassifier.set("sources")
if (isAndroid) {
// This declaration includes Java source directories
from(android.sourceSets.main.kotlin.srcDirs)
} else {
// This declaration includes Kotlin & Groovy source directories
from(sourceSets.main.allJava.srcDirs)
}
}
val javadocJar = tasks.create("javadocJar", Jar::class.java) {
from(tasks.getByName("dokkaHtml"))
archiveClassifier.set("javadoc")
}
artifacts {
add("archives", androidSourcesJar)
add("archives", javadocJar)
}
// Setup publication details
group = deployConfig.groupId
version = deployConfig.currentVersion
publishing {
publications {
// For Gradle Plugin projects, there already is a 'pluginMaven' publication
// pre-configured by the Java Gradle plugin, which we will extend with more properties and details.
// For other projects, a new publication must be created instead
if (isGradlePlugin) {
all {
if (this !is MavenPublication) return@all
if (name == "pluginMaven") {
applyPublicationDetails(
project = this@configureDeployment,
deployConfig = deployConfig,
isAndroid = isAndroid,
androidSourcesJar = androidSourcesJar,
javadocJar = javadocJar
)
}
// Always extend POM details to satisfy Maven Central's POM validation
// (they require a bunch of metadata for each POM, which isn't filled out by default)
configurePom(deployConfig)
}
} else {
create("release", MavenPublication::class.java)
.applyPublicationDetails(
project = this@configureDeployment,
deployConfig = deployConfig,
isAndroid = isAndroid,
androidSourcesJar = androidSourcesJar,
javadocJar = javadocJar
)
.configurePom(deployConfig)
}
}
}
// Setup code signing
ext["signing.keyId"] = credentials.signingKeyId
ext["signing.password"] = credentials.signingPassword
ext["signing.secretKeyRingFile"] = credentials.signingKeyRingFile
signing {
sign(publishing.publications)
}
// Connect signing task to artifact-producing task
// (build an AAR for Android modules, assemble a JAR for other modules)
tasks.withType(Sign::class.java).configureEach {
dependsOn(if (isAndroid) "bundleReleaseAar" else "assemble")
}
}
/* Private */
private fun Project.configureRootDeployment(deployConfig: Deployed, credentials: DeployedCredentials) {
if (this != rootProject) {
throw IllegalStateException("This method can only be called on the root project")
}
// Validate the integrity of published versions
// (all subprojects must use the same group ID and version number or else an error is raised)
if (version != "unspecified") {
if (version != deployConfig.currentVersion || group != deployConfig.groupId) {
throw IllegalStateException("A subproject tried to set '${deployConfig.groupId}:${deployConfig.currentVersion}' " +
"as the coordinates for the artifacts of the repository, but '$group:$version' was already set " +
"previously by a different subproject. As per the requirements of the Nexus Publishing plugin, " +
"all subprojects must use the same version number! Please check Artifacts.kt for inconsistencies!")
} else {
// Already configured and correct
return
}
}
// One-time initialization beyond this point
group = deployConfig.groupId
version = deployConfig.currentVersion
nexusPublishing(
packageGroup = deployConfig.groupId,
stagingProfileId = credentials.sonatypeStagingProfileId,
sonatypeUsername = credentials.ossrhUsername,
sonatypePassword = credentials.ossrhPassword
)
}
private fun MavenPublication.applyPublicationDetails(
project: Project,
deployConfig: Deployed,
isAndroid: Boolean,
androidSourcesJar: Jar,
javadocJar: Jar
) = also {
groupId = deployConfig.groupId
artifactId = deployConfig.artifactId
version = deployConfig.currentVersion
// Attach artifacts
artifacts.clear()
val buildDir = project.layout.buildDirectory
if (isAndroid) {
artifact(buildDir.file("outputs/aar/${project.name}-release.aar").get().asFile)
} else {
artifact(buildDir.file("libs/${project.name}-$version.jar"))
}
artifact(androidSourcesJar)
artifact(javadocJar)
// Attach dependency information
pom {
withXml {
with(asNode()) {
// Only add dependencies manually if there aren't any already
if (children().filterIsInstance<Node>()
.none { it.name().toString().endsWith("dependencies") }
) {
val dependenciesNode = appendNode("dependencies")
val compileDeps = project.configurations.getByName("api").allDependencies
val runtimeDeps = project.configurations.getByName("implementation").allDependencies +
project.configurations.getByName("runtimeOnly").allDependencies -
compileDeps
val dependencies = mapOf(
"runtime" to runtimeDeps,
"compile" to compileDeps
)
dependencies
.mapValues { entry -> entry.value.filter { it.name != "unspecified" } }
.forEach { (scope, dependencies) ->
dependencies.forEach { dep ->
with(dependenciesNode.appendNode("dependency")) {
if (dep is ProjectDependency) {
appendProjectDependencyCoordinates(dep)
} else {
appendExternalDependencyCoordinates(dep)
}
// Rewrite scope definition for BOM dependencies
val isBom = "-bom" in dep.name
appendNode("scope", if (isBom) "import" else scope)
}
}
}
}
}
}
}
}
private fun Node.appendProjectDependencyCoordinates(dep: ProjectDependency) {
// Find the external coordinates for the given project dependency
val projectName = dep.name
val config = Artifacts.Instrumentation::class.java
.getMethod("get${projectName.uppercaseFirstChar()}")
.invoke(Artifacts.Instrumentation)
as Deployed
appendNode("groupId", config.groupId)
appendNode("artifactId", config.artifactId)
appendNode("version", config.currentVersion)
}
private fun Node.appendExternalDependencyCoordinates(dep: Dependency) {
appendNode("groupId", dep.group)
appendNode("artifactId", dep.name)
dep.version?.let { appendNode("version", it) }
}
private fun MavenPublication.configurePom(deployConfig: Deployed) = also {
pom {
// Name and description cannot be set directly through the property, since they somehow aren't applied
// to Gradle Plugin Marker's POM file (maybe that plugin removes them somehow). Therefore,
// use the XML builder for this node as these properties are still required by Maven Central
withXml {
with(asNode()) {
appendNode("name").setValue(deployConfig.artifactId)
appendNode("description").setValue(deployConfig.description)
}
}
url.set(Artifacts.GITHUB_URL)
licenses {
license {
name.set(Artifacts.LICENSE)
url.set("${Artifacts.GITHUB_URL}/blob/main/LICENSE")
}
}
developers {
developer {
id.set("mannodermaus")
name.set("Marcel Schnelle")
}
}
scm {
connection.set("scm:git:${Artifacts.GITHUB_REPO}.git")
developerConnection.set("scm:git:ssh://github.com/${Artifacts.GITHUB_REPO}.git")
url.set("${Artifacts.GITHUB_URL}/tree/main")
}
}
}
/*
* Type-safe accessor hacks for Kotlin's strictness, accessing properties without having
* access to these external plugins. This is ridiculously ugly, so readers beware.
*/
// Properties
private val Project.ext: ExtraPropertiesExtension
get() = extensions.getByName("ext") as ExtraPropertiesExtension
/**
* Allows us to retain the untyped Groovy API even in the stricter Kotlin context
* ("android.sourceSets.main.java.srcDirs")
*/
private class AndroidDsl(project: Project) {
private val delegate = project.extensions.getByName("android") as ExtensionAware
val sourceSets = SourceSetDsl(delegate)
class SourceSetDsl(android: ExtensionAware) {
private val delegate = android.javaClass.getDeclaredMethod("getSourceSets")
.also { it.isAccessible = true }
.invoke(android) as NamedDomainObjectCollection<Any>
val main = MainDsl(delegate)
class MainDsl(sourceSets: NamedDomainObjectCollection<Any>) {
private val delegate = sourceSets.named("main").get()
val kotlin = KotlinDsl(delegate)
class KotlinDsl(main: Any) {
val srcDirs = main.javaClass
.getDeclaredMethod("getKotlinDirectories")
.invoke(main) as Set<File>
}
}
}
}
private val Project.android
get() = AndroidDsl(this)
private class SourceSetDsl(project: Project) {
private val delegate = project.extensions.getByName("sourceSets") as SourceSetContainer
val main: SourceSet = delegate.named("main").get()
}
private val Project.sourceSets
get() = SourceSetDsl(this)
// Publishing Plugin facade
private fun Project.publishing(action: PublishingExtension.() -> Unit) {
extensions.configure("publishing", action)
}
private val Project.publishing: PublishingExtension
get() = extensions.getByName("publishing") as PublishingExtension
// Signing Plugin facade
private fun Project.signing(action: SigningExtension.() -> Unit) {
extensions.configure("signing", action)
}
// Nexus Staging & Publishing Plugins facade
private fun Project.nexusPublishing(
packageGroup: String,
stagingProfileId: String?,
sonatypeUsername: String?,
sonatypePassword: String?
) {
extensions.getByName("nexusPublishing").withGroovyBuilder {
setProperty("packageGroup", packageGroup)
"repositories" {
"sonatype" {
// 🤮
val cls = delegate.javaClass
cls.getDeclaredMethod("setStagingProfileId", Any::class.java)
.also { it.isAccessible = true }
.invoke(delegate, stagingProfileId)
cls.getDeclaredMethod("setUsername", Any::class.java)
.also { it.isAccessible = true }
.invoke(delegate, sonatypeUsername)
cls.getDeclaredMethod("setPassword", Any::class.java)
.also { it.isAccessible = true }
.invoke(delegate, sonatypePassword)
}
}
}
}