Customize publish task to upload jar to maven repo per build variant

I am developing an Android project with Android Studio & Gradle build.

I am trying the maven-publish plugin, I managed to upload my jar for each build type by the following script:

apply plugin: 'maven-publish'
  buildTypes {
    release {
     ...
    }
    debug {
     ...
    }
}
  publishing {
    publications {
       android.applicationVariants.all { variant ->
    def buildType = variant.buildType.name
            create("myjar-$buildType", MavenPublication) {
              artefact "$projectDir/myjar.jar"
              artifactId "myjar-$buildType"
              groupId
  "com.my.app"
              version
  "2.1.1"
  }
       }
    }
}

If I run command “gradle clean publish” , artifacts myjar-debug & myjar-release are uploaded to my maven repository successfully.

Everything is good at this point. Now I want to create separate tasks to upload debug & release type jar respectively to maven repo. I modified my publishing closure to the following:

publishing {
    publications {
       android.applicationVariants.all { variant ->
    def buildType = variant.buildType.name
      def publishTask = project.tasks.create("publish${buildType.capitalize()}",{
             create("myjar-$buildType", MavenPublication) {
                artefact "$projectDir/myjar.jar"
                artifactId "myjar-$buildType"
                groupId
  "com.my.app"
                version
  "2.1.1"
     }
          })
       }
    }
}

Now, in my task list, I see there are now tasks

publishDebug

&

publishRelease

in task list. But when I run the task e.g. “gradle clean publishDebug”, the myjar-debug isn’t uploaded to my maven repository at all. So, how to make separate publish task to upload one jar per build type ?

In your first example, you should already have the ability to publish each publication independently. The maven-publish plugin automatically adds tasks for each publication, so you should have seen tasks matching the following pattern: publish{publicationName}PublicationTo{repositoryName}Repository. If you want simpler shortcuts like publishDebug or publishRelease, you can define a task that depends upon the default publication tasks - for instance:

task publishDebug { dependsOn publishMyjarDebugToMavenRepository }
task publishRelease { dependsOn publishMyjarReleaseToMavenRepository }