How to retrieve the git branch name that was built by Jenkins when using inverse branch selection strategy?

StackOverflow https://stackoverflow.com/questions/14985563

質問

We have one Jenkins job which builds every branch except master when there are new commits. This behavior can be configured via git plugin's 'choosing strategy:inverse' so that it listens to every branch except a specified branch.

This functions very nicely. But the problem is that GIT_BRANCH environment variable always refers to the excluded branch('origin/master' in our case). How to query the actual branch that was built by Jenkins?

Currently I am using a workaround that I grep it from generated changelog.xml. But it happens sometimes that changelog.xml is empty when Jenkins switches between different branches and I cannot find this info. What is the correct way of retrieving/querying from Jenkins the branch that was actually built?

役に立ちましたか?

解決 2

Because git never checks out a branch just a commit directly you have to do the following:

To get the sha of the checked out commit:

git rev-parse HEAD

To get the all branches that commit is under:

git branch -a --contains SHA

The out put of the second command could look like this

master
remotes/origin/HEAD -> origin/master
remotes/origin/develop

他のヒント

I successfully used this syntax:

GIT_BRANCH=`git rev-parse HEAD | git branch -a --contains | grep remotes | sed s/.*remotes.origin.//`

Looks like it's a Jenkins bug? You can grab in your build script the name of the checked out branch with this:

git symbolic-ref -q --short HEAD

Actually Jenkins has the working copy in detached HEAD, which is why git branch returns "no branch". See this quite detailed answer for digging into reconciliation with between a detached HEAD and a branch.

I can't believe how hard this is. I'm doing this for Jenkins as well. I piggypacked off Piotr Kuczynski's solution:

branch=`git rev-parse HEAD | git branch -a --contains | grep remotes | sed s/.*remotes.origin.//`
branch=`echo $branch | awk '{print $NF}'`

Because sometimes, as Matt Kantor pointed out, Piotr's solution gives a lot of junk back. But the last word in that junk appears to always be correct. Note that this solution only works if the ref you're using corresponds exactly with a branch that exists on remote (so local branches will not work).

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top