65
votes

I am using Branch Specifier option of Jenkins Git plugin (v2.0) to run build on specific branch, e.g. 1.4.

${GIT_BRANCH} in this case contains origin/1.4 value.

How can I receive a name of the local Git branch used for cloning (i.e. just 1.4 without origin/ prefix?

I've tried Check out to specific local branch Additional Behaviour with branch name 1.4, but nothing had changed.

I've seen related PR on GitHub, but it was declined (as it fixes only one case with just origin remote).

12
Why do you care about the name of the local branch (if any)? Does git name-rev give you what you want?Magnus Bäck
Because this functionality is provided by plugin: wiki.jenkins-ci.org/display/JENKINS/…Max Romanovsky
I'm having trouble with this as well. It was a recent version of the plugin that started adding 'origin/' in front. I need to grab the branch name because I'm checking out code in another location.ifightcrime
I've been trying to figure out why Jenkins wasn't setting the GIT_* environment variables for my builds. It turns out it's because I have Jenkins configured to watch more than one branch. There's a feature request to support this: issues.jenkins-ci.org/browse/JENKINS-7554markrian

12 Answers

77
votes

You can strip the prefix from the variable pretty easily: ${GIT_BRANCH##origin/}

Although this is not a very general solution, it's quite simple and I haven't seen a repository cloned by Jenkins, which would use something else than origin for the remote name.

Update: Actually, ${GIT_BRANCH#*/} will work for any origin and even for branches containing slashes. The # does non-greedy glob matching, ## enables greedy matching. See Bash Reference Manual for details.

13
votes

As of March 2016 (Git Plugin v2.4.3) this is now supported natively. Simply put ** as the value for Check out to specific local branch in the Git Plugin, instead of any macro/variable.

The description for the field details the new behavior:

If selected, and its value is an empty string or "**", then the branch name is computed from the remote branch without the origin. In that case, a remote branch origin/master will be checked out to a local branch named master, and a remote branch origin/develop/new-feature will be checked out to a local branch named develop/newfeature.

This was introduced by @roostergx & @NickVolynkin mentioned when it was released. I'm just documenting here to hopefully help folks in the future.

12
votes

I managed to do that with a couple steps:

  1. Add Execute shell pre step with these:

    git_branch_local=$(echo $GIT_BRANCH | sed -e "s|origin/||g") echo GIT_BRANCH_LOCAL=$git_branch_local > build.properties

  2. Add an Inject environment variables pre step for build.properties file

then you should have a GIT_BRANCH_LOCAL environment variable that doesn't have origin/

8
votes

@Chris answer helped me. Thank you!

Don't forget to add the "Additional Behavior -> Check out to specific local branch" under "Source Code Management".

enter image description here

Until I did not add that the ${GIT_LOCAL_BRANCH} variable was not availabe when I tried use it. (E.g.: execute shell command 'printenv' then check Console output)

6
votes

If you check it out as a local branch and then use ${GIT_LOCAL_BRANCH} it gives the local branch name (i.e. 'develop' instead of 'origin/develop'. (Git Plugin version 3.0.0)

4
votes

I posted a message to the jenkins-ci group (https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!msg/jenkinsci-dev/xuweZbwn9zE/BAWfs-ZeFAAJ) suggesting an enhancement to the Git plugin "Check Out to Local Branch" option. By default, the git plugin checks out a detached head. The Local Branch allows you to specify a specific branch name. When configured, using this method, the local branch name is exactly as specified.

If you are using Jenkins to do a maven release, it is mandatory that the local branch name is the same as the remote branch name. See the post to google groups for more on this.

To address this requirement, I've created a pull request (https://github.com/jenkinsci/git-plugin/pull/381) with code and test cases.

Also created a JIRA issue (https://issues.jenkins-ci.org/browse/JENKINS-33202) to document the problem.

If anyone is in need of this feature, I encourage you post to the group discussion, and to vote for the JENKINS-33202.

4
votes

While it's true, as dtabuenc says in a comment to Jan Včelák's answer, that shell syntax isn't going to work on token macros directly, if you are trying to get at the branch name in an Execute Shell build step (or similar), you can still use the same idea.

TEMP_GIT_BRANCH=${GIT_BRANCH}
MY_GIT_BRANCH="${TEMP_GIT_BRANCH#*/}"

works fine (and that's valid POSIX, no bash required).

2
votes

In a pipeline you can do it like this :

// get arround a git scm anoying feature
stage ('Bootstrap') {
    sh "echo GIT_BRANCH_LOCAL=\\\"$GIT_BRANCH\\\" | sed -e 's|origin/||g' | tee version.properties"
}

stage('Checkout') {
    load('version.properties')
    checkout([$class: 'GitSCM', branches: [[name: '**']], doGenerateSubmoduleConfigurations: false, extensions: [[$class: 'LocalBranch', localBranch: "${GIT_BRANCH_LOCAL}"]], submoduleCfg: [], userRemoteConfigs: [[url: 'https://github.com/webofmars/grails-website.git']]])
}
2
votes

Based on this SO answer: How to do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

I used this, and finally was able to get it to work (the below example assumes a branch variable of $Branch):

stage('Checkout') {
    GIT_BRANCH_LOCAL = sh (
        script: "echo $Branch | sed -e 's|origin/||g'",
        returnStdout: true
    ).trim()
    echo "Git branch: ${GIT_BRANCH_LOCAL}"
    git branch: "${GIT_BRANCH_LOCAL}", credentialsId: '...', url: '[email protected]:......git'
}
2
votes

I ran into the problem today. The reason is Jenkins git plug-in will add "origin/" to any branch name you supplied to GIT_BRANCH build parameter. See https://wiki.jenkins-ci.org/display/JENKINS/Git+Plugin

The git plugin sets several environment variables you can use in your scripts: GIT_BRANCH - Name of the branch currently being used, e.g. "master" or "origin/foo"

As a result, when you build with parameter GIT_BRANCH = foo, Jenkins will just add "origin/" in front of it. Then, when you do

git check out ${GIT_BRANCH}

you are actually doing

git check out origin/foo

What you can do to avoid this, is using something else in your build parameter, such as GIT_BRANCH_NAME or what ever else, just do not use GIT_BRANCH. In configuration, delete the GIT_BRANCH parameter, and add another one with name GIT_BRANCH_NAME. Then in "Build with parameter", under GIT_BRANCH_NAME, specify your branch.

2
votes

After long time I finally got the solution for my case to get local git name (for SonarQube) without "origin/" in my Jenkins freestyle project (not Jenkinsfile). I am using Windows environment.

In Jenkins:

  • At "Source Code Management" section: add "Check out to specific local branch" and at "Branch name" enter: **
  • At "Build" section: I used and added "SonarScanner for MSBuild - Begin Analysis", where at "Additional arguments" I added: /d:sonar.branch.name=${GIT_LOCAL_BRANCH}

So only with this combination of ** and ${GIT_LOCAL_BRANCH} it worked for me.

1
votes

I ran into this problem as well to day. It seems to be that when I change the value of Check out to specific local branch, I need to delete the local repo on the build server before triggering a new build.