Retrieving git branch name in prompt or Android gradle: on Jenkins it returns HEAD

蓝咒 提交于 2020-02-03 08:39:29

问题


In gradle I'd like to add both the current branch-name and commit-number as suffix to my versionName. (Why? Because when I build my app in Jenkins to release it in HockeyApp, it's useful to show what branch & commit that app was built from!)

So when I enter this in command prompt, my current branch name is returned:

git rev-parse --abbrev-ref HEAD

Same happens when I use this line in Android gradle, using the code in either this answer, or as shown in this piece of gradle code:

def getVersionNameSuffix = { ->

    def branch = new ByteArrayOutputStream()
    exec {
        // The command line to request the current branch:
        commandLine 'git', 'rev-parse', '--abbrev-ref', 'HEAD'
        standardOutput = branch
    }
    println "My current branch: " + branch
    def versionNameSuffix = "-" + branch

    // ... some other suffix additions ...

    return versionNameSuffix
}

buildTypes {
    debug {
        applicationIdSuffix ".test"
        versionNameSuffix getVersionNameSuffix()
    }
}

Resulting log (this is exactly what I want):

"My current branch: feature/MyFeature"

However, when I build my app in a Jenkins job, it will output a different result:

"My current branch: HEAD"

Why does this happen, and how to correctly retrieve my current branch name in Jenkins?

EDIT:

I've used a different approach, which returns the branchName correctly in most cases, also on Jenkins:

git name-rev --name-only HEAD

Example output in prompt:

"My current branch: feature/MyFeature"

Example output in Jenkins:

"My current branch: remotes/origin/feature/MyFeature"

I can remove "remotes/origin/" if i like, so that's okay!

But this approach causes different trouble (both in prompt, gradle and on Jenkins). When I have tagged the last commit, it won't output the branch-name, but this:

"My current branch: tags/MyTag^0"

EDIT 2:

A third approach can be found here.

Including the comments below the answer, I could use grep * to retrieve the branch in prompt. However, I cannot use the backslash in the gradle code. This fails:

commandLine 'git', 'branch', '|', 'grep', '\\*'

Any advice?


回答1:


Try the env: BRANCH_NAME

BRANCH_NAME 
    For a multibranch project, this will be set to the name of the branch being built, for example in case you wish to deploy to production from master but not from feature branches.

Access it with env.BRANCH_NAME



来源:https://stackoverflow.com/questions/41044807/retrieving-git-branch-name-in-prompt-or-android-gradle-on-jenkins-it-returns-he

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!