How to set project.version by passing version property on gradle command line?
JavaGroovyGradleJava Problem Overview
I want to build JAR with self-defined version passed via command line, such as:
When I execute gradle build task like this:
gradle build -Pversion=1.0
myproject-1.0.jar should be generated.
I have tried adding the line below to the build.gradle, but it did not work:
version = project.hasProperty('version') ? project['version'] : '10.0.0'
Java Solutions
Solution 1 - Java
Set the property only in the gradle.properties
file (i.e. remove it from build.gradle
). Also make sure the options come before the command (as mentioned above).
gradle.properties contents:
version=1.0.12
Version can then be overridden on the command line with:
gradle -Pversion=1.0.13 publish
Solution 2 - Java
You are not able to override existing project properties from command line, take a look here. So try to rename a version variable to something differing from version and set it with -P
flag before command, like:
gradle -PprojVersion=10.2.10 build
And then in your build.gradle
if (project.hasProperty('projVersion')) {
project.version = project.projVersion
} else {
project.version = '10.0.0'
}
Or as you did with ?: operator
Solution 3 - Java
If you move version
entry to gradle.properties
file you can also:
gradle clean build -Dorg.gradle.project.version=1.1
Solution 4 - Java
If you need a default version other than 'unspecified':
version = "${version != 'unspecified' ? version : 'your-default-version'}"
Pass version via command line:
gradle build -P version=1.0
Solution 5 - Java
You can pass the project version on cli with -Pversion=...
as long as you don't set it in build.gradle. If you need a custom default value for when no version is passed on the cli, use gradle.properties file like so: version=...
TL;DR: Don't set the version in build.gradle file if you want to change it later on via cli.
Solution 6 - Java
version = (findProperty('version') == 'unspecified') ? '0.1' : version
Solution 7 - Java
I've found this to be the easiest and cleanest way, without requiring a gradle.properties
file or changing the version
variable name.
In build.gradle
:
// Note - there is intentionally no equals sign here
version project.hasProperty('version') ? version : '1.0.0'
From the command line:
./gradlew -Pversion=1.5.2 build