Gradle获取git的commit信息

声明获取commit短hash的函数:

def getGitCommit() {
    def gitDir = new File("${new File("${rootDir}").getParent()}/.git")
    if (!gitDir.isDirectory()) {
        return 'non-git-build'
    }

    def cmd = 'git log --pretty=format:%h -1'
    def gitCommit = cmd.execute().text.trim()
    assert !gitCommit.isEmpty()
    gitCommit
}

Gradle中调用

task doSth {
    doLast {
        println("commit: ${getGitCommit()}")
    }
}

执行:

$ ./gradlew doSth
// 输出:commit: 69546da

你可能感兴趣的:(Gradle获取git的commit信息)