Configuring multiple upload repositories in Gradle

2019-02-07 11:12发布

问题:

I want to upload my artifacts to a remote Nexus repo. Therefore I have configured a snaphot and a release repo in Nexus. Deployment to both works.

Now I want to configure my build so I can decide in which repo I want to deploy:

  • gradle uploadArchives should deploy to my snapshots repo
  • gradle release uploadArchives should deploy to my release repo

This was my try:

apply plugin: 'war'
apply plugin: 'maven'

group = 'testgroup'
version = '2.0.0'
def release = false

repositories {
    mavenCentral()
    mavenLocal()
}

dependencies{ providedCompile 'javax:javaee-api:6.0' }

task release <<{
    release = true;
    println 'releasing!'
}

uploadArchives {
    repositories {

        mavenDeployer {
            repository(url: "http://.../nexus/content/repositories/releases"){
                authentication(userName: "admin", password: "admin123")
            }
            addFilter('lala'){ x, y -> release }
        }
        mavenDeployer {
            repository(url: "http://.../nexus/content/repositories/snapshots"){
                authentication(userName: "admin", password: "admin123")
            }
            addFilter('lala'){ x, y ->!release}
            pom.version = version + '-SNAPSHOT'
        }
    }
}

The build works if I comment out one of the two mavenDeployer configs, but not as a whole.
Any ideas how to configure two target archives in one build file?

回答1:

One solution is to add an if-else statement that adds exactly one of the two deployers depending on the circumstances. For example:

// should defer decision until end of configuration phase
gradle.projectsEvaluated {
    uploadArchives {
        repositories {
            mavenDeployer {
                if (version.endsWith("-SNAPSHOT")) { ... } else { ... }
            }               
        }
    }
}

If you do need to vary the configuration based on whether some task is "present", you can either make an eager decision based on gradle.startParameter.taskNames (but then you'll only catch tasks that are specified as part of the Gradle invocation), or use the gradle.taskGraph.whenReady callback (instead of gradle.projectsEvaluated) and check whether the task is scheduled for execution.



回答2:

Correct me if I'm wrong, but shouldn't you use the separate snapshotRepository in this case (as opposed to an if statement)? For example,

mavenDeployer {

  repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
    authentication(userName: sonatypeUsername, password: sonatypePassword)
  }

  snapshotRepository(url: "https://oss.sonatype.org/content/repositories/snapshots/") {
    authentication(userName: sonatypeUsername, password: sonatypePassword)
  }
}