Get the Git Working Branch in Gradle on Jenkins

2019-04-17 12:09发布

问题:

I want to have the current Git branch in the Version name of my Android app. I built in this snippet from here into my build.gradle:

def getWorkingBranch() {
    // Triple double-quotes for the breaklines
    def workingBranch = """git --git-dir=${rootDir}/git
                               --work-tree=${rootDir}/..
                               rev-parse --abbrev-ref HEAD""".execute().text.trim()
    print "Working branch: " + workingBranch
    return workingBranch
}

The snippet is slightly altered as suggested in the first comment on the article.

It works fine when I build my app locally, but doesn't when the app is built with Jenkins. I also tried the original variant of the snippet, in both cases the workingBranch String is empty.

Jenkins seems to be 'aware' of the branch it builds, it lists the branches under

Git Build Data / Built Branches

, so it should be possible

回答1:

If this is only for testers/downstream, what about using Jenkins' Git environment variables instead, e.g. $GIT_BRANCH?

Locally, it will show no version/empty when you build, but when you build on Jenkins it will show the correct branch name in your 'version' string.

To get around the local builds producing an empty string, you could use your above snippet to set the branch into GIT_BRANCH. Not perfect, but it should work.