Gradle - plugin maven-publish: How to publish only specific publication to a repository
You could disable and hide the "invalid" tasks like so:
apply plugin: 'maven-publish'
publishing {
repositories {
maven {
name 'Dev'
url 'http://dev/'
credentials {
username 'username'
password 'password'
}
}
maven {
name 'Prod'
url 'http://prod/'
credentials {
username 'username'
password 'password'
}
}
}
publications {
// This will only be enabled on Dev
MyDevJar(MavenPublication) {
artifactId "test"
version "1.0"
groupId "org.example"
artifact file('abc')
ext.repo = 'Dev'
}
// This will only be enabled on prod
MyJar(MavenPublication) {
artifactId "test"
version "1.0"
groupId "org.example"
artifact file('abc')
ext.repo = 'Prod'
}
}
}
afterEvaluate {
tasks.withType(PublishToMavenRepository) { task ->
if (task.publication.hasProperty('repo') && task.publication.repo != task.repository.name) {
task.enabled = false
task.group = null
}
}
}
I've just started playing with gradle and it's other plugins and @knut-saua-mathiesen solution was really interresting, however it wasn't working for me.
Inside the 'AfterEvaluate' the task.publication wasn't set to it's correcte value but initialized to 'null'. So i tried a few other things and came up with this solution :
afterEvaluate {
tasks.withType(PublishToMavenRepository).all { publishTask ->
publishTask.onlyIf { task ->
if (task.publication.hasProperty('repo') && task.publication.repo != task.repository.name) {
task.enabled = false
task.group = null
return false
}
return true
}
}
}
Probably this didn't exist when the question was asked, but the Gradle documentation describes just how to achieve the desired conditional publishing.
Using method tasks.withType()
as in the accepted answer, but then using an onlyIf{}
block as well.
"Gradle allows you to skip any task you want based on a condition via the
Task.onlyIf(org.gradle.api.specs.Spec)
method."
So their example uses conditions on the repository name and publication type:
tasks.withType(PublishToMavenRepository) {
onlyIf {
(repository == publishing.repositories.external &&
publication == publishing.publications.binary) ||
(repository == publishing.repositories.internal &&
publication == publishing.publications.binaryAndSources)
}
}
tasks.withType(PublishToMavenLocal) {
onlyIf {
publication == publishing.publications.binaryAndSources
}
}
Where they have defined publications
and repositories
as follows:
publishing {
publications {
binary(MavenPublication) {
from components.java
}
binaryAndSources(MavenPublication) {
from components.java
artifact sourcesJar
}
}
repositories {
// change URLs to point to your repos, e.g. http://my.org/repo
maven {
name = 'external'
url = "$buildDir/repos/external"
}
maven {
name = 'internal'
url = "$buildDir/repos/internal"
}
}
}