在prompt或Android gradle中检索git分支名称:在Jenkins上返回HEAD

在prompt或Android gradle中检索git分支名称:在Jenkins上返回HEAD,jenkins,android-gradle-plugin,command-prompt,git-branch,Jenkins,Android Gradle Plugin,Command Prompt,Git Branch,在gradle中,我想将当前分支名称和提交编号作为后缀添加到我的versionName中。(为什么?因为当我在Jenkins中构建我的应用程序并在HockeyApp中发布时,显示该应用程序是从哪个分支和提交构建的非常有用!) 因此,当我在命令提示符下输入此命令时,将返回我当前的分支名称: git rev-parse --abbrev-ref HEAD 当我在Android gradle中使用这一行时,也会发生同样的情况,使用任一答案中的代码,或者如这段gradle代码所示: def getVe

在gradle中,我想将当前分支名称和提交编号作为后缀添加到我的versionName中。(为什么?因为当我在Jenkins中构建我的应用程序并在HockeyApp中发布时,显示该应用程序是从哪个分支和提交构建的非常有用!)

因此,当我在命令提示符下输入此命令时,将返回我当前的分支名称:

git rev-parse --abbrev-ref HEAD
当我在Android gradle中使用这一行时,也会发生同样的情况,使用任一答案中的代码,或者如这段gradle代码所示:

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()
    }
}
结果日志(这正是我想要的):

“我的当前分支:功能/MyFeature”

但是,当我在Jenkins作业中构建应用程序时,它将输出不同的结果:

“我现在的分支机构:负责人”

为什么会发生这种情况,以及如何在Jenkins中正确检索我当前的分支名称

编辑:

我使用了一种不同的方法,在大多数情况下正确返回branchName,在Jenkins上也是如此:

git name-rev --name-only HEAD
提示符中的输出示例:

“我的当前分支:功能/MyFeature”

Jenkins中的输出示例:

git name-rev --name-only HEAD
“我的当前分支:remotes/origin/feature/MyFeature”

如果愿意,我可以删除“remotes/origin/”,所以没关系

但这种方法会带来不同的麻烦(在prompt、gradle和on Jenkins中)。当我标记最后一次提交时,它不会输出分支名称,但是:

“我的当前分支:标记/MyTag^0”

编辑2:

可以找到第三种方法

包括答案下面的注释,我可以使用grep*在提示符中检索分支。但是,我不能在gradle代码中使用反斜杠。这失败了:

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

有什么建议吗?

试试env:BRANCH\u名称

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.

使用env.BRANCH_NAME访问它

我可以在build.gradle中使用“env.”,但不能使用env.BRANCH_NAME。我可以访问Jenkins文件中的env.BRANCH_名称,因此我可以将其用作管道或Jenkins作业的参数,但我猜这不会有帮助。我需要在build.gradle.try“$System.env.BRANCH_NAME”中使用它,但它也不起作用,您是否能够在应用(或移动)模块的build.gradle中使用该命令?如果是这样的话:你在哪里定义它?
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.