Publish Groups Of Artifacts To Multiple Repos Based On Artifact Type


(Rick Bryant) #1

This is from our Advanced Gradle Fundamentals for Java/JVM training this week (April 25-28, 2017). When executing gradle publish, the following script will publish all .exe artifacts to the dists repo and will publish all .jar/.war artifacts to the libs repo (the afterEvaluate script determines which publish tasks are available at runtime):


publishing {
  repositories {
    maven {
      name 'dists'
      if('SNAPSHOT'.equals(buildType)) {
        url artifactoryDistsSnapshotUrl
      } else {
        url artifactoryDistsReleaseUrl
      }
      credentials {
        username (project.hasProperty('artifactoryPublishUsername') ? artifactoryPublishUsername : '')  //in gradle.properties
        password (project.hasProperty('artifactoryPublishPassword') ? artifactoryPublishPassword : '')  //in gradle.properties
      }
    }
    maven {
      name 'libs'
      if('SNAPSHOT'.equals(buildType)) {
        url artifactoryLibsSnapshotUrl
      } else {
        url artifactoryLibsReleaseUrl
      }
      credentials {
        username (project.hasProperty('artifactoryPublishUsername') ? artifactoryPublishUsername : '')  //in gradle.properties
        password (project.hasProperty('artifactoryPublishPassword') ? artifactoryPublishPassword : '')  //in gradle.properties
      }
    }
  }
  publications {
    appA(MavenPublication) {
      groupId "com.company"
      artifactId "app-a"
      version “1.0"
      artifact "$distsDir/app-a-1.0.exe"
      ext.repo = 'dists'
    }
    appB(MavenPublication) {
      groupId "com.company"
      artifactId "app-b"
      version "1.0"
      artifact "$distsDir/app-b-1.0.exe"
      ext.repo = 'dists'
    }
    appC(MavenPublication) {
      groupId "com.company"
      artifactId "app-c"
      version "1.0"
      artifact "$distsDir/app-c-1.0.exe"
      ext.repo = 'dists'
    }
    debugJar(MavenPublication) {
      groupId "com.company"
      artifactId "app"
      version "1.0"
      artifact "$libsDir/app-1.0.jar"
      ext.repo = 'libs'
    }
    prodWar(MavenPublication) {
      groupId "com.company"
      artifactId "app"
      version "1.0"
      artifact "$libsDir/app-1.0.war"
      ext.repo = 'libs'
    }
  }
}

afterEvaluate {
  tasks.withType(PublishToMavenRepository) { task ->
    if (task.publication.hasProperty('repo') && task.publication.repo != task.repository.name) {
      task.enabled = false
      task.group = null
    }
  }
}

(Rick Bryant) #2

This solution leverages the maven-publish plugin. The key aspects are:

  • assign unique name to each maven repository using the name attribute
  • reference unique repo name in each publication by assigning value to ext.repo variable
  • implement afterEvaluate to filter which publish tasks should be enabled at runtime