publish-module.gradle 17.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
apply plugin: 'maven-publish'
apply plugin: 'signing'

task androidSourcesJar(type: Jar) {
    archiveClassifier.set('sources')
    if (project.plugins.findPlugin("com.android.library")) {
        // For Android libraries
        from android.sourceSets.main.java.srcDirs
        from android.sourceSets.main.kotlin.srcDirs
    } else {
        // For pure Kotlin libraries, in case you have them
        from sourceSets.main.java.srcDirs
        from sourceSets.main.kotlin.srcDirs
    }
}
artifacts {
    archives androidSourcesJar
}

group = PUBLISH_GROUP_ID
version = PUBLISH_VERSION

afterEvaluate {
    publishing {
        publications {
            release(MavenPublication) {
                // The coordinates of the library, being set from variables that
                // we'll set up later
                groupId PUBLISH_GROUP_ID
                artifactId PUBLISH_ARTIFACT_ID
                version PUBLISH_VERSION

                // Two artifacts, the `aar` (or `jar`) and the sources
                if (project.plugins.findPlugin("com.android.library")) {
                    from(project.components.findByName("release"))
                } else {
                    from components.java
                }

                // Sources are now handled by the android block's singleVariant
//                artifact javadocJar

                // POM metadata for Maven Central
                pom {
                    name = PUBLISH_ARTIFACT_ID
                    description = 'Warply Android SDK Maven Plugin'
                    url = 'https://git.warp.ly/open-source/warply_android_sdk_maven_plugin'
                    licenses {
                        license {
                            name = 'Warply Ltd. All rights reserved'
                            url = 'https://git.warp.ly/open-source/warply_android_sdk_maven_plugin'
                        }
                    }
                    developers {
                        developer {
                            id = 'panostr'
                            name = 'Panagiotis Triantafyllou'
                            email = 'panost@warp.ly'
                        }
                        // Add all other devs here...
                    }

                    // Version control info
                    scm {
                        connection = 'scm:git:git.warp.ly/open-source/warply_android_sdk_maven_plugin.git'
                        developerConnection = 'scm:git:ssh://git.warp.ly/open-source/warply_android_sdk_maven_plugin.git'
                        url = 'https://git.warp.ly/open-source/warply_android_sdk_maven_plugin/tree/master'
                    }
                }
            }
        }
    }
}

signing {
    useInMemoryPgpKeys(
            rootProject.ext["signing.keyId"],
            rootProject.ext["signing.key"],
            rootProject.ext["signing.password"],
    )
    sign publishing.publications
}

// Configuration for Central Publishing (similar to Maven plugin configuration)
ext.centralPublishing = [
    autoPublish: false,  // Manual publishing for safety
    // waitUntil: "published", // Commented out - don't wait for publishing
    deploymentName: "Warply Android SDK ${PUBLISH_VERSION}",
    centralBaseUrl: "https://central.sonatype.com"
]

// Custom task that implements the same functionality as org.sonatype.central:central-publishing-maven-plugin:0.8.0
// This uses the Central Portal API directly to achieve the same result
task publishToCentralPortal {
    dependsOn 'publishReleasePublicationToMavenLocal'
    
    description = 'Publishes to Maven Central Portal using the same API as central-publishing-maven-plugin:0.8.0'
    group = 'publishing'
    
    doLast {
        def username = rootProject.ext["centralPortalUsername"]
        def password = rootProject.ext["centralPortalPassword"]
        def config = project.ext.centralPublishing
        
        if (!username || !password) {
            throw new GradleException("Central Portal credentials not configured. Please set centralPortalUsername and centralPortalPassword in local.properties or environment variables.")
        }
        
        println "=== Central Portal Publishing ==="
        println "Deployment: ${config.deploymentName}"
        println "Auto-publish: ${config.autoPublish}"
        println "Portal URL: ${config.centralBaseUrl}"
        println ""
        
        // Step 1: Create deployment bundle
        println "Step 1: Creating deployment bundle..."
        def bundleFile = createDeploymentBundle()
        println "✓ Bundle created: ${bundleFile.name} (${bundleFile.length()} bytes)"
        
        // Step 2: Upload bundle to Central Portal
        println "\nStep 2: Uploading to Central Portal..."
        def deploymentId = uploadBundle(bundleFile, username, password, config)
        println "✓ Upload successful. Deployment ID: ${deploymentId}"
        
        // Step 3: Wait for validation
        println "\nStep 3: Waiting for validation..."
        def validationResult = waitForValidation(deploymentId, username, password, config)
        
        if (validationResult.success) {
            def state = validationResult.state
            println "✓ Validation successful! State: ${state}"
            
            if (config.autoPublish && state == "VALIDATED") {
                println "\nStep 4: Auto-publishing..."
                def publishResult = publishDeployment(deploymentId, username, password, config)
                if (publishResult.success) {
                    println "✓ Published successfully to Maven Central!"
                } else {
                    throw new GradleException("Auto-publishing failed: ${publishResult.error}")
                }
            } else if (state == "PUBLISHED") {
                println "✓ Already published to Maven Central!"
                def response = validationResult.response
                def purls = response.purls ?: []
                if (purls) {
                    println "   Published artifacts:"
                    purls.each { purl -> println "     - ${purl}" }
                }
            } else {
                println "\n✓ Deployment uploaded and validated successfully!"
                println "📋 Manual action required:"
                println "   Visit: ${config.centralBaseUrl}/publishing/deployments"
                println "   Find deployment: ${config.deploymentName}"
                println "   Click 'Publish' to complete the process"
            }
        } else {
            throw new GradleException("Validation failed: ${validationResult.error}")
        }
        
        println "\n=== Publishing Complete ==="
    }
}

def createDeploymentBundle() {
    def bundleDir = file("${buildDir}/central-publishing")
    def stagingDir = file("${bundleDir}/staging")
    
    // Clean and create directories
    bundleDir.deleteDir()
    stagingDir.mkdirs()
    
    // Create Maven repository structure
    def groupPath = PUBLISH_GROUP_ID.replace('.', '/')
    def artifactDir = file("${stagingDir}/${groupPath}/${PUBLISH_ARTIFACT_ID}/${PUBLISH_VERSION}")
    artifactDir.mkdirs()
    
    // Copy artifacts to staging area
    def artifacts = [:]
    
    // AAR file
    def aarFile = file("${buildDir}/outputs/aar/warply_android_sdk-release.aar")
    if (aarFile.exists()) {
        def targetAar = file("${artifactDir}/${PUBLISH_ARTIFACT_ID}-${PUBLISH_VERSION}.aar")
        copy {
            from aarFile
            into artifactDir
            rename { targetAar.name }
        }
        artifacts['aar'] = targetAar
        
        // Copy AAR signature if exists
        def aarSigFile = file("${aarFile.path}.asc")
        if (aarSigFile.exists()) {
            def targetAarSig = file("${targetAar.path}.asc")
            copy {
                from aarSigFile
                into artifactDir
                rename { targetAarSig.name }
            }
            artifacts['aar-sig'] = targetAarSig
        }
    }
    
    // Sources JAR
    def sourcesFile = file("${buildDir}/libs/warply_android_sdk-${PUBLISH_VERSION}-sources.jar")
    if (sourcesFile.exists()) {
        def targetSources = file("${artifactDir}/${PUBLISH_ARTIFACT_ID}-${PUBLISH_VERSION}-sources.jar")
        copy {
            from sourcesFile
            into artifactDir
            rename { targetSources.name }
        }
        artifacts['sources'] = targetSources
        
        // Copy sources signature if exists
        def sourcesSigFile = file("${sourcesFile.path}.asc")
        if (sourcesSigFile.exists()) {
            def targetSourcesSig = file("${targetSources.path}.asc")
            copy {
                from sourcesSigFile
                into artifactDir
                rename { targetSourcesSig.name }
            }
            artifacts['sources-sig'] = targetSourcesSig
        }
    }
    
    // POM file
    def pomFile = file("${buildDir}/publications/release/pom-default.xml")
    if (pomFile.exists()) {
        def targetPom = file("${artifactDir}/${PUBLISH_ARTIFACT_ID}-${PUBLISH_VERSION}.pom")
        copy {
            from pomFile
            into artifactDir
            rename { targetPom.name }
        }
        artifacts['pom'] = targetPom
        
        // Copy POM signature if exists
        def pomSigFile = file("${pomFile.path}.asc")
        if (pomSigFile.exists()) {
            def targetPomSig = file("${targetPom.path}.asc")
            copy {
                from pomSigFile
                into artifactDir
                rename { targetPomSig.name }
            }
            artifacts['pom-sig'] = targetPomSig
        }
    }
    
    // Generate checksums for all files
    artifacts.each { type, artifactFile ->
        if (artifactFile.exists()) {
            generateChecksums(artifactFile)
        }
    }
    
    // Create bundle ZIP
    def bundleFile = file("${bundleDir}/central-bundle.zip")
    ant.zip(destfile: bundleFile) {
        fileset(dir: stagingDir)
    }
    
    return bundleFile
}

def generateChecksums(File file) {
    ['md5', 'sha1', 'sha256', 'sha512'].each { algorithm ->
        def checksum = file.withInputStream { stream ->
            java.security.MessageDigest.getInstance(algorithm.toUpperCase()).digest(stream.bytes).encodeHex().toString()
        }
        new File("${file.path}.${algorithm}").text = checksum
    }
}

def uploadBundle(File bundleFile, String username, String password, Map config) {
    def url = "${config.centralBaseUrl}/api/v1/publisher/upload"
    def credentials = "${username}:${password}".bytes.encodeBase64().toString()
    
    // Add query parameters
    def publishingType = config.autoPublish ? "AUTOMATIC" : "USER_MANAGED"
    def urlWithParams = "${url}?publishingType=${publishingType}&name=${URLEncoder.encode(config.deploymentName, 'UTF-8')}"
    
    println "   Uploading to: ${urlWithParams}"
    println "   Publishing type: ${publishingType}"
    
    def connection = new URL(urlWithParams).openConnection() as HttpURLConnection
    connection.setRequestMethod("POST")
    connection.setRequestProperty("Authorization", "Bearer ${credentials}")
    connection.setDoOutput(true)
    connection.setDoInput(true)
    
    // Create multipart/form-data boundary
    def boundary = "----WebKitFormBoundary" + System.currentTimeMillis()
    connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=${boundary}")
    
    // Write multipart data
    connection.outputStream.withWriter("UTF-8") { writer ->
        writer.write("--${boundary}\r\n")
        writer.write("Content-Disposition: form-data; name=\"bundle\"; filename=\"${bundleFile.name}\"\r\n")
        writer.write("Content-Type: application/octet-stream\r\n")
        writer.write("\r\n")
        writer.flush()
        
        // Write file content
        bundleFile.withInputStream { input ->
            connection.outputStream << input
        }
        
        writer.write("\r\n--${boundary}--\r\n")
        writer.flush()
    }
    
    // Get response
    def responseCode = connection.responseCode
    if (responseCode == 201) {
        def deploymentId = connection.inputStream.text.trim()
        println "   ✓ Upload successful (HTTP ${responseCode})"
        return deploymentId
    } else {
        def errorMessage = connection.errorStream?.text ?: "Unknown error"
        throw new GradleException("Upload failed (HTTP ${responseCode}): ${errorMessage}")
    }
}

def waitForValidation(String deploymentId, String username, String password, Map config) {
    def credentials = "${username}:${password}".bytes.encodeBase64().toString()
    def maxAttempts = 60 // 5 minutes with 5-second intervals
    def attempt = 0
    
    while (attempt < maxAttempts) {
        attempt++
        
        def url = "${config.centralBaseUrl}/api/v1/publisher/status?id=${deploymentId}"
        def connection = new URL(url).openConnection() as HttpURLConnection
        connection.setRequestMethod("POST")
        connection.setRequestProperty("Authorization", "Bearer ${credentials}")
        connection.setRequestProperty("Content-Type", "application/json")
        
        def responseCode = connection.responseCode
        if (responseCode == 200) {
            def response = new groovy.json.JsonSlurper().parseText(connection.inputStream.text)
            def state = response.deploymentState
            
            println "   Status check ${attempt}: ${state}"
            
            switch (state) {
                case "PENDING":
                case "VALIDATING":
                    // Continue waiting
                    Thread.sleep(5000)
                    break
                case "VALIDATED":
                    return [success: true, state: state, response: response]
                case "PUBLISHED":
                    return [success: true, state: state, response: response]
                case "FAILED":
                    def errors = response.errors ?: ["Unknown validation error"]
                    return [success: false, error: "Validation failed: ${errors.join(', ')}", response: response]
                default:
                    return [success: false, error: "Unknown deployment state: ${state}", response: response]
            }
        } else {
            def errorMessage = connection.errorStream?.text ?: "Unknown error"
            throw new GradleException("Status check failed (HTTP ${responseCode}): ${errorMessage}")
        }
    }
    
    return [success: false, error: "Timeout waiting for validation (${maxAttempts * 5} seconds)"]
}

def publishDeployment(String deploymentId, String username, String password, Map config) {
    def credentials = "${username}:${password}".bytes.encodeBase64().toString()
    def url = "${config.centralBaseUrl}/api/v1/publisher/deployment/${deploymentId}"
    
    println "   Calling publish API..."
    
    def connection = new URL(url).openConnection() as HttpURLConnection
    connection.setRequestMethod("POST")
    connection.setRequestProperty("Authorization", "Bearer ${credentials}")
    
    def responseCode = connection.responseCode
    if (responseCode == 204) {
        println "   ✓ Publish request successful (HTTP ${responseCode})"
        
        // Wait for publishing to complete
        println "   Waiting for publishing to complete..."
        def result = waitForPublishing(deploymentId, username, password, config)
        return result
    } else {
        def errorMessage = connection.errorStream?.text ?: "Unknown error"
        throw new GradleException("Publish failed (HTTP ${responseCode}): ${errorMessage}")
    }
}

def waitForPublishing(String deploymentId, String username, String password, Map config) {
    def credentials = "${username}:${password}".bytes.encodeBase64().toString()
    def maxAttempts = 120 // 10 minutes with 5-second intervals
    def attempt = 0
    
    while (attempt < maxAttempts) {
        attempt++
        
        def url = "${config.centralBaseUrl}/api/v1/publisher/status?id=${deploymentId}"
        def connection = new URL(url).openConnection() as HttpURLConnection
        connection.setRequestMethod("POST")
        connection.setRequestProperty("Authorization", "Bearer ${credentials}")
        connection.setRequestProperty("Content-Type", "application/json")
        
        def responseCode = connection.responseCode
        if (responseCode == 200) {
            def response = new groovy.json.JsonSlurper().parseText(connection.inputStream.text)
            def state = response.deploymentState
            
            println "   Publishing status ${attempt}: ${state}"
            
            switch (state) {
                case "PUBLISHING":
                    // Continue waiting
                    Thread.sleep(5000)
                    break
                case "PUBLISHED":
                    def purls = response.purls ?: []
                    println "   ✓ Successfully published to Maven Central!"
                    if (purls) {
                        println "   Published artifacts:"
                        purls.each { purl -> println "     - ${purl}" }
                    }
                    return [success: true, state: state, response: response]
                case "FAILED":
                    def errors = response.errors ?: ["Unknown publishing error"]
                    return [success: false, error: "Publishing failed: ${errors.join(', ')}", response: response]
                default:
                    return [success: false, error: "Unexpected state during publishing: ${state}", response: response]
            }
        } else {
            def errorMessage = connection.errorStream?.text ?: "Unknown error"
            throw new GradleException("Publishing status check failed (HTTP ${responseCode}): ${errorMessage}")
        }
    }
    
    return [success: false, error: "Timeout waiting for publishing (${maxAttempts * 5} seconds)"]
}