How to set project.version by passing version prop

2019-02-03 07:59发布

问题:

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'

回答1:

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



回答2:

I found that you need to have the property set in the gradle.properties file and reference it in the build.gradle for the above solution to work. Also make sure the options come before the command (as mentioned above).

gradle.properties contents:

version=1.0.12

build.gradle contents:

version "${version}"

Version can then be overridden on the command line with:

gradle -Pversion=1.0.13 publish


回答3:

If you move version entry to gradle.properties file you can also:

gradle clean build -Dorg.gradle.project.version=1.1


回答4:

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


回答5:

version = (findProperty('version') == 'unspecified') ? '0.1' : version