How to prevent gradle from publishing artifacts to remote repository?

(Note: I’m using gradle 1.10 and the new Maven Publishing as described in chapter 65. )

I would like to prevent the publishMavenJavaPublicationToMavenRepository task to run if some condition is met. Checking the condition and preventing the build task to run is working fine:

build.onlyIf{
  myCustomUpToDateCheck.isBuildRequired()
 }

But it does not work with the publish task. So I also tried with a rule:

tasks.addRule("Pattern: publishMavenJavaPublicationToMavenRepository: do not publish if repo artifact is up-to-date."){ String taskName ->
  if( taskName == "publishMavenJavaPublicationToMavenRepository"){
   task(taskName).doFirst {
    if(!myCustomUpToDateCheck.isBuildRequired()){
     logger.quiet "Stopping execution of ${taskName} for ${project.name} since build is not required"
     throw new StopExecutionException()
    }
   }
  }
 }

What did I do wrong ? Is it possible at all to prevent the publish task from running ?

Background information:

The reason for the custom up-to-date check is: - sources are generated as part of a central code-generation infrastructure - build is run automatically - but components which did not change (comparing local and remote revision, stored as metadata in maven pom) must not be uploaded

I found a solution.

I had to find out that the task publishMavenJavaPublicationToMavenRepository is added dynamically during configuration phase. So we have to use the following to apply the onlyIf closure:

def runOnlyIfNecessary = { t->
  t.onlyIf { myCustomUpToDateCheck.isBuildRequired() }
}
  tasks.whenTaskAdded{t->
 if( t.name == "publishMavenJavaPublicationToMavenRepository"){
  logger.debug "Customizing ${t.name} to run only if necessary"
  t.with runOnlyIfNecessary
 }
}

A shorter way to achieve the same is:

tasks.matching { it.name == "publishMavenJavaPublicationToMavenRepository" }.all {
    onlyIf { myCustomUpToDateCheck.isBuildRequired() }
}

Maybe even ‘tasks.findByName’ will work, but I’m not sure.