-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathbuild.gradle
More file actions
536 lines (442 loc) · 22.6 KB
/
build.gradle
File metadata and controls
536 lines (442 loc) · 22.6 KB
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
mavenCentral()
gradlePluginPortal()
}
}
import org.jmailen.gradle.kotlinter.tasks.LintTask
import org.jmailen.gradle.kotlinter.tasks.FormatTask
buildscript {
ext.modules = [
"sdkVersionName" : "1.1.14",
"androidMinSdkVersion": 23,
"androidTargetVersion": 34
]
dependencies {
classpath 'org.apache.httpcomponents:httpclient:4.5.13'
classpath 'com.fasterxml.jackson.core:jackson-databind:2.13.0'
}
}
plugins {
id 'com.android.application' version '8.0.2' apply false
id 'com.android.library' version '8.0.2' apply false
id 'org.jetbrains.kotlin.android' version '1.8.22' apply false
id 'org.jmailen.kotlinter' version '3.16.0'
id 'signing'
id 'maven-publish'
id 'io.codearte.nexus-staging' version '0.30.0'
}
tasks.register('ktLint', LintTask) {
group 'formatting'
source files('demo/src', 'library/src')
reports = [
'checkstyle': file('build/reports/ktlint/main-lint.xml')
]
}
tasks.register('ktFormat', FormatTask) {
group 'formatting'
source files('demo/src', 'library/src')
report = file('build/reports/ktlint/format-report.txt')
}
version modules.sdkVersionName
// Central Portal API integration
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.ContentType
import org.apache.http.entity.mime.MultipartEntityBuilder
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
import com.fasterxml.jackson.databind.ObjectMapper
import java.net.URLEncoder
import org.apache.tools.ant.taskdefs.condition.Os
tasks.register('publishToCentralPortal') {
group = 'publishing'
description = 'Publishes artifacts to Sonatype Central Portal using the Maven plugin'
// Check if signing is configured
def isSigningConfigured = System.getenv('SIGNING_KEY_ID') &&
System.getenv('SIGNING_KEY_PASSWORD') &&
System.getenv('SIGNING_KEY_FILE') &&
!System.getenv('SIGNING_KEY_ID').isEmpty() &&
!System.getenv('SIGNING_KEY_PASSWORD').isEmpty() &&
!System.getenv('SIGNING_KEY_FILE').isEmpty()
dependsOn ':library:assembleRelease', ':library:generatePomFileForReleasePublication'
doLast {
logger.lifecycle("====================================================================")
logger.lifecycle("Publishing to Maven Central via Central Portal REST API")
logger.lifecycle("====================================================================")
// Make sure we have credentials
def username = System.getenv('SONATYPE_NEXUS_USERNAME') ?:
findProperty('sonatypeUsername') ?:
project.hasProperty('sonatypeUsername') ? project.getProperty('sonatypeUsername') : null
def token = System.getenv('SONATYPE_NEXUS_PASSWORD') ?:
findProperty('sonatypePassword') ?:
project.hasProperty('sonatypePassword') ? project.getProperty('sonatypePassword') : null
if (!username || !token) {
throw new GradleException("SONATYPE_NEXUS_USERNAME and SONATYPE_NEXUS_PASSWORD environment variables or properties are required")
}
// Resolve library project details
def libraryProject = project.findProject(':library')
def version = libraryProject.version
def artifactId = libraryProject.ext.name
def groupId = libraryProject.group
logger.lifecycle("Preparing bundle for ${groupId}:${artifactId}:${version}")
// Locate artifacts
def aarFile = file("${libraryProject.buildDir}/outputs/aar/library-release.aar")
def pomFile = file("${libraryProject.buildDir}/publications/release/pom-default.xml")
def sourcesJar = file("${libraryProject.buildDir}/libs/library-${version}-sources.jar")
if (!aarFile.exists()) {
throw new GradleException("AAR file not found: ${aarFile.absolutePath}")
}
if (!pomFile.exists()) {
throw new GradleException("POM file not found: ${pomFile.absolutePath}")
}
if (!sourcesJar.exists()) {
throw new GradleException("Sources JAR not found: ${sourcesJar.absolutePath}")
}
// Prepare bundle directory
def bundleDir = file("${libraryProject.buildDir}/central-bundle")
bundleDir.deleteDir()
bundleDir.mkdirs()
// Copy artifacts with correct names
copy {
from aarFile
into bundleDir
rename { "${artifactId}-${version}.aar" }
}
copy {
from pomFile
into bundleDir
rename { "${artifactId}-${version}.pom" }
}
copy {
from sourcesJar
into bundleDir
rename { "${artifactId}-${version}-sources.jar" }
}
// Optionally sign artifacts
def keyId = System.getenv('SIGNING_KEY_ID') ?: project.findProperty('signing.keyId')
def password = System.getenv('SIGNING_KEY_PASSWORD') ?: project.findProperty('signing.password')
def secretKeyRingFile = System.getenv('SIGNING_KEY_FILE') ?: project.findProperty('signing.secretKeyRingFile')
if (keyId && password && secretKeyRingFile) {
logger.lifecycle("Signing artifacts...")
bundleDir.listFiles().each { f ->
if (f.name.endsWith('.aar') || f.name.endsWith('.pom') || f.name.endsWith('.jar')) {
exec {
commandLine 'gpg', '--batch', '--yes', '--armor', '--detach-sign',
'--default-key', keyId,
'--passphrase', password,
'--pinentry-mode', 'loopback',
f.absolutePath
}
}
}
} else {
logger.lifecycle("Signing not configured; proceeding without signatures")
}
// Create bundle ZIP
def bundleZip = file("${libraryProject.buildDir}/${artifactId}-${version}-bundle.zip")
ant.zip(destfile: bundleZip) {
fileset(dir: bundleDir)
}
logger.lifecycle("Bundle created at: ${bundleZip.absolutePath}")
logger.lifecycle("Bundle contents:")
bundleDir.listFiles().each { logger.lifecycle(" - ${it.name}") }
// Upload to Central Portal
def client = HttpClients.createDefault()
def auto = project.hasProperty('autoPublish')
def publishingType = auto ? 'AUTOMATIC' : 'USER_MANAGED'
def uploadUrl = "https://central.sonatype.com/api/v1/publisher/upload?publishingType=${publishingType}"
def post = new HttpPost(uploadUrl)
post.setHeader("Authorization", "Bearer ${token}")
def entity = MultipartEntityBuilder.create()
.addBinaryBody("bundle", bundleZip, ContentType.APPLICATION_OCTET_STREAM, bundleZip.name)
.build()
post.setEntity(entity)
logger.lifecycle("Uploading bundle to Central Portal (${publishingType})...")
def response = client.execute(post)
def statusCode = response.getStatusLine().getStatusCode()
def responseBody = EntityUtils.toString(response.getEntity())
if (statusCode == 200 || statusCode == 201 || statusCode == 202) {
logger.lifecycle("Successfully uploaded to Central Portal")
logger.lifecycle("Response: ${responseBody}")
} else {
throw new GradleException("Failed to upload to Central Portal. Status: ${statusCode}, Response: ${responseBody}")
}
client.close()
logger.lifecycle("====================================================================")
logger.lifecycle("Publishing to Maven Central completed (upload).")
logger.lifecycle("NOTE: After successful publishing, it may take several hours for")
logger.lifecycle("the artifacts to appear on Maven Central and search indexes.")
logger.lifecycle("====================================================================")
}
}
tasks.register('checkCentralPortalDeployment') {
group = 'publishing'
description = 'Checks the status of deployments in Sonatype Central Portal using Maven plugin'
doLast {
logger.lifecycle("====================================================================")
logger.lifecycle("Checking deployment status in Central Portal")
logger.lifecycle("====================================================================")
// Make sure we have credentials
def username = System.getenv('SONATYPE_NEXUS_USERNAME') ?:
findProperty('sonatypeUsername') ?:
project.hasProperty('sonatypeUsername') ? project.getProperty('sonatypeUsername') : null
def token = System.getenv('SONATYPE_NEXUS_PASSWORD') ?:
findProperty('sonatypePassword') ?:
project.hasProperty('sonatypePassword') ? project.getProperty('sonatypePassword') : null
if (!username || !token) {
throw new GradleException("SONATYPE_NEXUS_USERNAME and SONATYPE_NEXUS_PASSWORD environment variables or properties are required")
}
// Get library project information
def libraryProject = project.findProject(':library')
def groupId = libraryProject.group
def artifactId = libraryProject.name
def version = libraryProject.version
// Ensure we have Maven available
def mvnExecutable = Os.isFamily(Os.FAMILY_WINDOWS) ? "mvn.cmd" : "mvn"
// Create the command to check status
def cmd = [
mvnExecutable,
"org.sonatype.central:central-publishing-maven-plugin:status",
"-f", "${project.rootDir}/library/pom.xml",
"-s", "${project.rootDir}/.mvn/maven-settings.xml",
"-Dcentral.groupId=${groupId}",
"-Dcentral.artifactId=${artifactId}",
"-Dcentral.version=${version}",
"--batch-mode"
].collect { it.toString() }
// Execute the Maven command
def processBuilder = new ProcessBuilder(cmd)
// Pass the environment variables to the process
def env = processBuilder.environment()
env.put("SONATYPE_NEXUS_USERNAME", username)
env.put("SONATYPE_NEXUS_PASSWORD", token)
// Redirect output to the Gradle logger
processBuilder.redirectErrorStream(true)
def process = processBuilder.start()
// Read the output
def reader = new BufferedReader(new InputStreamReader(process.getInputStream()))
String line
while ((line = reader.readLine()) != null) {
logger.lifecycle(line)
}
// Wait for the process to complete
def exitCode = process.waitFor()
if (exitCode != 0) {
logger.warn("Maven status check failed with exit code: ${exitCode}")
}
logger.lifecycle("====================================================================")
logger.lifecycle("NOTE: After successful publishing, it may take several hours for")
logger.lifecycle("the artifacts to appear on Maven Central (https://repo.maven.apache.org/maven2)")
logger.lifecycle("and search indexes like mvnrepository.com or search.maven.org.")
logger.lifecycle("====================================================================")
}
}
subprojects {
group = "com.paypal.messages"
}
// Configure Nexus Staging to close and release automatically (OSSRH s01)
nexusStaging {
serverUrl = "https://s01.oss.sonatype.org/service/local/"
packageGroup = "com.paypal.messages"
// Check if we're using token authentication
def tokenAuth = System.getenv('SONATYPE_TOKEN_AUTH') == 'true' || findProperty('sonatypeTokenAuth') == 'true'
if (tokenAuth) {
// For token auth, we need special configuration
numberOfRetries = 60
delayBetweenRetriesInMillis = 5000
// For the Nexus Staging plugin, we need to use customized REST client
// that includes the token in the header. The plugin doesn't directly support
// token authentication, so we use a modified HTTP client configuration in closeAndPromoteRepository task
} else {
// Traditional username/password auth
username = (findProperty('sonatypeUsername') ?: System.getenv('OSSRH_USERNAME') ?: System.getenv('SONATYPE_NEXUS_USERNAME') ?: '') as String
password = (findProperty('sonatypePassword') ?: System.getenv('OSSRH_PASSWORD') ?: System.getenv('SONATYPE_NEXUS_PASSWORD') ?: '') as String
}
}
// Configure duplicate handling for ZIP tasks
tasks.withType(Zip) {
duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
// Add custom token-based authentication for closeAndPromoteRepository task
import groovy.json.JsonSlurper
import org.apache.http.client.methods.HttpGet
import org.apache.http.client.methods.HttpPost
import org.apache.http.entity.StringEntity
import org.apache.http.impl.client.HttpClients
import org.apache.http.util.EntityUtils
tasks.register('closeAndPromoteRepositoryWithToken') {
group = 'publishing'
description = 'Close and promote repository using token authentication'
doLast {
def tokenAuth = System.getenv('SONATYPE_TOKEN_AUTH') == 'true' || findProperty('sonatypeTokenAuth') == 'true'
if (!tokenAuth) {
logger.lifecycle("Token auth not enabled, skipping custom close and promote task.")
return
}
def token = System.getenv('SONATYPE_NEXUS_PASSWORD') ?: findProperty('sonatypePassword')
if (!token) {
logger.error("============================================================")
logger.error("ERROR: SONATYPE_NEXUS_PASSWORD token is required for token authentication")
logger.error("You can create a token at: https://central.sonatype.com/profile")
logger.error("")
logger.error("Add it to your environment with: export SONATYPE_NEXUS_PASSWORD=your-token-here")
logger.error("============================================================")
throw new GradleException("Missing SONATYPE_NEXUS_PASSWORD token for Maven Central authentication")
}
// Create HTTP client
def client = HttpClients.createDefault()
def baseUrl = "https://s01.oss.sonatype.org/service/local/"
try {
// 1. Get staging repositories
def listReposUrl = baseUrl + "staging/profile_repositories"
def getRepos = new HttpGet(listReposUrl)
getRepos.setHeader("Authorization", "Bearer " + token)
getRepos.setHeader("Accept", "application/json")
def response = client.execute(getRepos)
def responseCode = response.getStatusLine().getStatusCode()
def responseBody = EntityUtils.toString(response.getEntity())
if (responseCode != 200) {
throw new GradleException("Failed to get staging repositories: ${responseCode}, ${responseBody}")
}
// Parse response to find our repository
def json = new JsonSlurper().parseText(responseBody)
def repoId = null
json.data.each { repo ->
if (repo.type == "open" && repo.profileId.contains("com.paypal.messages")) {
repoId = repo.repositoryId
}
}
if (!repoId) {
throw new GradleException("No open staging repository found for com.paypal.messages")
}
logger.lifecycle("Found staging repository: ${repoId}")
// 2. Close the repository
def closeUrl = baseUrl + "staging/bulk/close"
def closePost = new HttpPost(closeUrl)
closePost.setHeader("Authorization", "Bearer " + token)
closePost.setHeader("Content-Type", "application/json")
closePost.setHeader("Accept", "application/json")
def closePayload = """
{
"data": {
"stagedRepositoryIds": ["${repoId}"],
"description": "Closed by Gradle closeAndPromoteRepositoryWithToken task"
}
}
"""
closePost.setEntity(new StringEntity(closePayload))
response = client.execute(closePost)
responseCode = response.getStatusLine().getStatusCode()
responseBody = EntityUtils.toString(response.getEntity())
if (responseCode < 200 || responseCode > 299) {
throw new GradleException("Failed to close repository: ${responseCode}, ${responseBody}")
}
logger.lifecycle("Successfully closed repository: ${repoId}")
// Wait for repository to be closed
boolean isClosed = false
for (int i = 0; i < 30; i++) {
Thread.sleep(5000)
getRepos = new HttpGet(listReposUrl)
getRepos.setHeader("Authorization", "Bearer " + token)
getRepos.setHeader("Accept", "application/json")
response = client.execute(getRepos)
responseBody = EntityUtils.toString(response.getEntity())
json = new JsonSlurper().parseText(responseBody)
def repo = json.data.find { it.repositoryId == repoId }
if (repo && repo.type == "closed") {
isClosed = true
logger.lifecycle("Repository successfully closed: ${repoId}")
break
} else if (repo && repo.type == "open") {
logger.lifecycle("Repository is still open, waiting for close operation to complete...")
} else if (repo) {
logger.lifecycle("Repository status: ${repo.type}, waiting for close operation to complete...")
}
logger.lifecycle("Waiting for repository to be closed... (${i+1}/30)")
}
if (!isClosed) {
// Check if there are errors in the repository status
getRepos = new HttpGet(listReposUrl)
getRepos.setHeader("Authorization", "Bearer " + token)
getRepos.setHeader("Accept", "application/json")
response = client.execute(getRepos)
responseBody = EntityUtils.toString(response.getEntity())
json = new JsonSlurper().parseText(responseBody)
def repo = json.data.find { it.repositoryId == repoId }
if (repo && repo.transitioning) {
logger.error("Repository is still transitioning after timeout period")
throw new GradleException("Repository closing timed out after 150 seconds, but is still transitioning")
} else if (repo && repo.type != "closed") {
// Check for errors in the repository
def errorsUrl = baseUrl + "staging/repository/${repoId}/activity"
def getErrors = new HttpGet(errorsUrl)
getErrors.setHeader("Authorization", "Bearer " + token)
getErrors.setHeader("Accept", "application/json")
response = client.execute(getErrors)
responseBody = EntityUtils.toString(response.getEntity())
logger.error("Repository failed to close, current status: ${repo.type}")
logger.error("Activity log: ${responseBody}")
throw new GradleException("Repository failed to close. Current status: ${repo.type}")
} else {
throw new GradleException("Repository closing timed out after 150 seconds")
}
}
// 3. Release the repository
def releaseUrl = baseUrl + "staging/bulk/promote"
def releasePost = new HttpPost(releaseUrl)
releasePost.setHeader("Authorization", "Bearer " + token)
releasePost.setHeader("Content-Type", "application/json")
releasePost.setHeader("Accept", "application/json")
def releasePayload = """
{
"data": {
"stagedRepositoryIds": ["${repoId}"],
"description": "Released by Gradle closeAndPromoteRepositoryWithToken task"
}
}
"""
releasePost.setEntity(new StringEntity(releasePayload))
response = client.execute(releasePost)
responseCode = response.getStatusLine().getStatusCode()
responseBody = EntityUtils.toString(response.getEntity())
if (responseCode < 200 || responseCode > 299) {
throw new GradleException("Failed to release repository: ${responseCode}, ${responseBody}")
}
logger.lifecycle("Successfully released repository: ${repoId}")
logger.lifecycle("Artifact publishing complete! Please allow 30 minutes for synchronization to Maven Central.")
} finally {
client.close()
}
}
}
//./gradlew -PversionParam=0.0.1 changeReleaseVersion
tasks.register('changeReleaseVersion') {
doLast {
def newVersion = versionParam
// Update build.gradle
def topLevelGradleFile = file('./build.gradle')
def topLevelGradleFileText = topLevelGradleFile.getText('UTF-8')
def updatedGradleScript = topLevelGradleFileText.replaceFirst(
/("sdkVersionName"\s*: )".*",/,
'$1"' + newVersion + '",'
)
topLevelGradleFile.write(updatedGradleScript, 'UTF-8')
// Update library/pom.xml
def pomFile = file('./library/pom.xml')
if (pomFile.exists()) {
def pomText = pomFile.getText('UTF-8')
def updatedPomText = pomText.replaceFirst(
/<version>.*?<\/version>/,
"<version>" + newVersion + "</version>"
)
pomFile.write(updatedPomText, 'UTF-8')
println("Updated version in library/pom.xml to " + newVersion)
} else {
println("Warning: library/pom.xml not found")
}
println("Version updated to " + newVersion)
}
}