在 Gradle 构建中需要定义构件的三元组(groupId, artifactID, version),其中第三项 version 随着程序的演进需要不停地增加,如果你习惯于使用 git tag 定义程序的版本,那么你不再需要通过修改代码来管理版本了。gradle-git-version 就是这剂灵丹妙药。

plugins {
    id 'com.palantir.git-version' version '0.5.2'
}

def details = versionDetails()
version = details.commitDistance ? details.lastTag + '-SNAPSHOT' : details.lastTag

// 或使用如下方式将 git describe 信息作为 version
version = gitVersion()

版本管理参照:语义化版本

The Maven way

1.0-SNAPSHOT   =>   1.0
      |              |
 during dev      when released

插件: Maven Release plugin

The Continuous Delivery way

   1.0.134   =>   1.0.134
      |              |
 during dev      when released

Every commit can be a release

implemented with Gradle

gradle/versioning.gradle

ext.buildTimestamp = new Date().format('yyyy-MM-dd HH:mm:ss')

def ciBuildNumber = System.env.SOURCE_BUILD_NUMBER      // Jenkins Build Number
version = (ciBuildNumber) ? new ProjectVersion(1, 0, Integer.parseInt(ciBuildNumber)) :
        new ProjectVersion(1, 0, 0)

class ProjectVersion {

    Integer major
    Integer minor
    Integer build

    ProjectVersion(Integer major, Integer minor, Integer build) {
        this.major = major
        this.minor = minor
        this.build = build
    }

    @Override
    String toString() {     // Builds version String representation
        "$major.$minor.$build"
    }
}

在根项目的build.gradle中包含以下内容:

allprojects {
    apply from: "$rootDir/gradle/versioning.gradle"
}