簡體   English   中英

使用 AAR 和源代碼 JAR 將 Android 庫發布到 Maven

[英]Publish an Android library to Maven with AAR and sources JAR

有人可以提示我如何使用maven-publish Gradle 插件發布帶有 AAR 和源 jar 的com.android.library項目/模塊嗎? 我可以使用舊的maven插件來做到這一點——但我想使用新的maven-publish插件。

這是使用新的maven-publish插件的示例。

apply plugin: 'maven-publish'

task sourceJar(type: Jar) {
    from android.sourceSets.main.java.srcDirs
    classifier "sources"
}

publishing {
    publications {
        bar(MavenPublication) {
            groupId 'com.foo'
            artifactId 'bar'
            version '0.1'
            artifact(sourceJar)
            artifact("$buildDir/outputs/aar/bar-release.aar")
        }
    }
    repositories {
        maven {
            url "$buildDir/repo"
        }
    }
}

使用./gradlew clean build publish

2020 年 3 月 3 日更新:

自 Android Studio 3.6 發布以來,在 Android Gradle 插件 3.6.0(及更新版本)中實現了對構建 AAR(甚至 APK 和 AAB)的支持。

我們不再需要自己處理 XML 依賴項和東西了。

這是我更新的 Android Studio 3.6.0 要點:https ://gist.github.com/Robyer/a6578e60127418b380ca133a1291f017

來自要點的代碼:

apply plugin: 'maven-publish'

task androidJavadocs(type: Javadoc) {
    source = android.sourceSets.main.java.srcDirs
    classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
    android.libraryVariants.all { variant ->
        if (variant.name == 'release') {
            owner.classpath += variant.javaCompileProvider.get().classpath
        }
    }
    exclude '**/R.html', '**/R.*.html', '**/index.html'
}

task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
    archiveClassifier.set('javadoc')
    from androidJavadocs.destinationDir
}

task androidSourcesJar(type: Jar) {
    archiveClassifier.set('sources')
    from android.sourceSets.main.java.srcDirs
}

// Because the components are created only during the afterEvaluate phase, you must
// configure your publications using the afterEvaluate() lifecycle method.
afterEvaluate {
    publishing {
        publications {
            // Creates a Maven publication called "release".
            release(MavenPublication) {
                // Applies the component for the release build variant.
                from components.release

                // Adds javadocs and sources as separate jars.
                artifact androidJavadocsJar
                artifact androidSourcesJar

                // You can customize attributes of the publication here or in module's build.gradle file (if you save this as script and include it build.gradle file, then you can just replicate this whole block there only with changed fields).
                //groupId = 'com.example'
                //artifactId = 'custom-artifact'
                version = android.defaultConfig.versionName // or just '1.0'
            }
        }
    }
}

舊答案:

這是我根據其他答案改進的解決方案。

要點:https ://gist.github.com/Robyer/a6578e60127418b380ca133a1291f017

其他答案的變化:

  • 更改classifier - 它必須是"sources"而不是"source"
  • 處理依賴關系

    • 還支持@aartransitive: false 在這種情況下,我們在 POM 中設置排除以忽略此依賴項的所有傳遞依賴項。
    • 還支持對依賴項的自定義排除規則,例如:

       compile('com.example:something:1.0', { exclude group: 'com.exclude.this', module: 'some-module' })
  • 不需要手動指定工件路徑。

變更日志:

  • 27.3.2018 - 在新 Gradle 中添加了對api /實現依賴項的支持
  • 2018年11月23日-更名bundleReleasebundleReleaseAar因為它在新的搖籃改變(見這個答案
  • 2018年11月23日-更改getAllDependenciesgetDependencies以修復復制結果條目(如在評論中提到我的GIST)。
  • 23.04.2019 - 包裹在project.afterEvaluate{...}以針對新 Gradle 修復它。

apply plugin: 'maven-publish'

task androidJavadocs(type: Javadoc) {
    source = android.sourceSets.main.java.srcDirs
    classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
    android.libraryVariants.all { variant ->
        if (variant.name == 'release') {
            owner.classpath += variant.javaCompile.classpath
        }
    }
    exclude '**/R.html', '**/R.*.html', '**/index.html'
}

task androidJavadocsJar(type: Jar, dependsOn: androidJavadocs) {
    classifier = 'javadoc'
    from androidJavadocs.destinationDir
}

task androidSourcesJar(type: Jar) {
    classifier = 'sources'
    from android.sourceSets.main.java.srcDirs
}

project.afterEvaluate {
    publishing {
        publications {
            maven(MavenPublication) {
                //groupId 'cz.example'
                //artifactId 'custom-artifact'
                //version = android.defaultConfig.versionName

                artifact bundleReleaseAar
                artifact androidJavadocsJar
                artifact androidSourcesJar

                pom.withXml {
                    final dependenciesNode = asNode().appendNode('dependencies')

                    ext.addDependency = { Dependency dep, String scope ->
                        if (dep.group == null || dep.version == null || dep.name == null || dep.name == "unspecified")
                            return // ignore invalid dependencies

                        final dependencyNode = dependenciesNode.appendNode('dependency')
                        dependencyNode.appendNode('groupId', dep.group)
                        dependencyNode.appendNode('artifactId', dep.name)
                        dependencyNode.appendNode('version', dep.version)
                        dependencyNode.appendNode('scope', scope)

                        if (!dep.transitive) {
                            // If this dependency is transitive, we should force exclude all its dependencies them from the POM
                            final exclusionNode = dependencyNode.appendNode('exclusions').appendNode('exclusion')
                            exclusionNode.appendNode('groupId', '*')
                            exclusionNode.appendNode('artifactId', '*')
                        } else if (!dep.properties.excludeRules.empty) {
                            // Otherwise add specified exclude rules
                            final exclusionNode = dependencyNode.appendNode('exclusions').appendNode('exclusion')
                            dep.properties.excludeRules.each { ExcludeRule rule ->
                                exclusionNode.appendNode('groupId', rule.group ?: '*')
                                exclusionNode.appendNode('artifactId', rule.module ?: '*')
                            }
                        }
                    }

                    // List all "compile" dependencies (for old Gradle)
                    configurations.compile.getDependencies().each { dep -> addDependency(dep, "compile") }
                    // List all "api" dependencies (for new Gradle) as "compile" dependencies
                    configurations.api.getDependencies().each { dep -> addDependency(dep, "compile") }
                    // List all "implementation" dependencies (for new Gradle) as "runtime" dependencies
                    configurations.implementation.getDependencies().each { dep -> addDependency(dep, "runtime") }
                }
            }
        }
    }
}

通過正確的依賴生成對 dskinners 的回答進行一些調整:

apply plugin: 'maven-publish'

task sourceJar(type: Jar) {
    from android.sourceSets.main.java.srcDirs
    classifier "source"
}

publishing {
    publications {
        bar(MavenPublication) {
            groupId 'com.foo'
            artifactId 'bar'
            version '0.1'
            artifact(sourceJar)
            artifact("$buildDir/outputs/aar/bar-release.aar")
            pom.withXml {
                def dependenciesNode = asNode().appendNode('dependencies')
                //Iterate over the compile dependencies (we don't want the test ones), adding a <dependency> node for each
                configurations.compile.allDependencies.each {
                    if(it.group != null && (it.name != null || "unspecified".equals(it.name)) && it.version != null)
                    {
                        def dependencyNode = dependenciesNode.appendNode('dependency')
                        dependencyNode.appendNode('groupId', it.group)
                        dependencyNode.appendNode('artifactId', it.name)
                        dependencyNode.appendNode('version', it.version)
                    }
                }
            }
        }
    }
    repositories {
        maven {
            url "$buildDir/repo"
        }
    }
}

您可以通過定義來更改versiongroupId

version = '1.0.0'
group = 'foo.bar'

如果你想避免樣板代碼,因為maven-publish插件不會將依賴寫入 pom.xml

試試這個插件: android-maven-publish

publishing {
    publications {
        mavenAar(MavenPublication) {
            groupId 'com.example'
            artifactId 'mylibrary'
            version '1.0.0'
            from components.android
        }
    }

    repositories {
        maven {
            url "$buildDir/releases"
        }
    }
}

這就是我使用Kotlin DSL (build.gradle.kts) 為我的 Android Kotlin 庫包含Dokka在線查看)和源 JAR 的方式:

plugins {
    // ...
    id("org.jetbrains.dokka") version "1.4.32"
    id("maven-publish")
}

lateinit var sourcesArtifact: PublishArtifact
lateinit var javadocArtifact: PublishArtifact

tasks {
    val sourcesJar by creating(Jar::class) {
        archiveClassifier.set("sources")
        from(android.sourceSets["main"].java.srcDirs)
    }
    val dokkaHtml by getting(org.jetbrains.dokka.gradle.DokkaTask::class)
    val javadocJar by creating(Jar::class) {
        dependsOn(dokkaHtml)
        archiveClassifier.set("javadoc")
        from(dokkaHtml.outputDirectory)
    }
    artifacts {
        sourcesArtifact = archives(sourcesJar)
        javadocArtifact = archives(javadocJar)
    }
}

publishing {
    // ...
    publications {
        create<MavenPublication>("MyPublication") {
            from(components["release"])
            artifact(sourcesArtifact)
            artifact(javadocArtifact)
            // ...
        }
    }
}

您還可以使用android maven 插件 它創建 .aar、javadoc.jar、sources.jar 和 .pom,並在將文件上傳到 maven 存儲庫后更新 maven-metadata.xml。 我也把腳本放在GitHub 上

apply plugin: 'com.android.library'
apply plugin: 'maven'

//Your android configuration
android {
    //...
}

//maven repository info
group = 'com.example'
version = '1.0.0'

ext {
    //Specify your maven repository url here
    repositoryUrl = 'ftp://your.maven.repository.com/maven2'
    //Or you can use 'file:\\\\C:\\Temp' or 'maven-temp' for a local maven repository
}

//Upload android library to maven with javadoc and android sources
configurations {
    deployerJars
}

//If you want to deploy to an ftp server
dependencies {
    deployerJars "org.apache.maven.wagon:wagon-ftp:2.2"
}

// custom tasks for creating source/javadoc jars
task javadoc(type: Javadoc) {
    source = android.sourceSets.main.java.srcDirs
    classpath += project.files(android.getBootClasspath().join(File.pathSeparator))
    destinationDir = file("../javadoc/")
    failOnError false
}

task javadocJar(type: Jar, dependsOn: javadoc) {
    classifier = 'javadoc'
    from javadoc.destinationDir
}

//Creating sources with comments
task androidSourcesJar(type: Jar) {
    classifier = 'sources'
    from android.sourceSets.main.java.srcDirs
}

//Put the androidSources and javadoc to the artifacts
artifacts {
    archives androidSourcesJar
    archives javadocJar
}

uploadArchives {
    repositories {
        mavenDeployer {
            configuration = configurations.deployerJars
            repository(url: repositoryUrl) {
                //if your repository needs authentication
                authentication(userName: "username", password: "password")
            }
        }
    }
}

調用它

./gradlew uploadArchives

使用 Kotlin build.gradle.kts

publishing.publications {
    register<MavenPublication>("aar") {
        groupId = "com.foo"
        artifactId = "bar"
        version = "0.1"

        artifact("$buildDir/outputs/aar/bar-release.aar")

        pom.withXml {
            val dependencies = asNode().appendNode("dependencies")

            val addNode = { groupId: String, artifactId: String, version: String ->
                val dependency = dependencies.appendNode("dependency")
                dependency.appendNode("groupId", groupId)
                dependency.appendNode("artifactId", artifactId)
                dependency.appendNode("version", version)
            }

            addNode("com.example", "dependency-name", "1.0")
        }
    }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM