How to set/reference optional global properties?


(Ryan Nelson) #1

I’d like to set a property in the global space that would only exist on certain environments (ex.: prod vs. dev). For example, I have some Nexus connection credentials for publishing artifacts that will exist on a CI box, but that I don’t want individual developers storing on their local machines. I currently do this as follows:

$HOME/.gradle/gradle.properties (CI box only)

nexusUrl=https://my-nexus.example.com
nexusUsername=username
nexusPassword=password

build.gradle:

uploadArchives {
   onlyIf { project.hasProperty('nexusUrl') && project.hasProperty('nexusUsername') && project.hasProperty('nexusPassword') }
      repositories {
        mavenDeployer {
            repository(url: nexusUrl) {
                authentication(userName: nexusUsername, password: nexusPassword )
                  pom.version = "1.0-SNAPSHOT"
                pom.artifactId = "paat"
                pom.groupId = "com.pearson"
            }
        }
    }
}

When a developer runs this on a local machine (sans the global gradle.properties file), they get an error:

No such property: nexusUrl for class: org.gradle.api.publication.maven.internal.ant.DefaultGroovyMavenDeployer

This fails because the onlyIf directive is only honored in execution mode, but during configuration mode Gradle still expects those variables to exist. Work arounds are to create a properties file with empty values for those keys, or to provide dummy versions command-line.

But I’d like to know if there is a better, more Gradle-idiomatic way of doing this. How do I specify optional properties/functionality like this in a way that makes sense?


(Gary Hale) #2

In the general case, probably the simplest way to handle this is to move your onlyIf conditional to an if statement around the uploadArchives configuration. That effectively moves the condition from execution time to configuration time.

In this specific case, you might also look at using the nexus plugin (https://github.com/bmuschko/gradle-nexus-plugin). It might simplify your script.


(Ryan Nelson) #3

Thanks, Gary, that’s helpful.