67

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).

Max Romanovsky
  • 2,824
  • 5
  • 30
  • 37
  • 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 Dec 12 '13 at 14:33
  • Because this functionality is provided by plugin: https://wiki.jenkins-ci.org/display/JENKINS/Git+Plugin#GitPlugin-Environmentvariables – Max Romanovsky Dec 13 '13 at 12:38
  • 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 Apr 02 '14 at 03:35
  • 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: https://issues.jenkins-ci.org/browse/JENKINS-7554 – markrian Jul 20 '16 at 11:21
  • It exists another variable `GIT_BRANCH` vs `GIT_LOCAL_BRANCH` – Sandburg Feb 07 '23 at 08:55

14 Answers14

83

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.

Jan Včelák
  • 2,459
  • 1
  • 21
  • 19
  • 3
    `${GIT_BRANCH}` is a token macro, not a shell expansion. This will not work when putting it into `Check out to specific local branch` – Daniel Tabuenca Nov 12 '14 at 07:13
  • 4
    The question doesn't specify that this should be put into `Check out to specific local branch`. – Jan Včelák Nov 13 '14 at 07:55
  • 2
    @dtabuenc Any comments on what WILL remove `origin` from a token macro? – alukach Aug 14 '15 at 22:34
  • 1
    Same problem here. No luck yet. The token macro documentation says that ${MACRO_NAME#origin/} should work but it does not in my case, with the Set build name plugin, which uses the Token Macro plugin. – Germán Diago Oct 06 '16 at 08:26
  • 1
    As @GermánDiago pointed out, this does not work with the "Set build name" plugin. – Colin Basnett May 09 '17 at 02:54
  • In some cases, you need to double the braces: `${{GIT_BRANCH#*/}}` (I'm new to Jenkins, not sure why this works as oppose to `${GIT_BRANCH#*/}` - something to do with escaping, ensuring that braces go all the way to shell as oppose to being treated as Jenkins var. – Yuri Astrakhan Jun 20 '18 at 16:25
15

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.

Sean Connolly
  • 5,692
  • 7
  • 37
  • 74
  • Thanks Sean, this works perfectly with M2 Release plugin (0.14.0) and git plugin 3.7.0 – napster Mar 21 '18 at 14:52
  • This actually also solves the problem of having a detached head, if your build uses something like `git symbolic-ref --short HEAD` to retrieve the branch name. Note that when using Jenkins variables, you need to use `GIT_LOCAL_BRANCH` in place of `GIT_BRANCH` to get the name of the local branch. – Jesper Matthiesen Mar 13 '19 at 12:12
14

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/

burcakulug
  • 517
  • 6
  • 17
9

@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)

7

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

Sandburg
  • 757
  • 15
  • 28
Tim Webster
  • 684
  • 8
  • 18
4

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.

roostergx
  • 3,510
  • 1
  • 15
  • 5
4

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).

3

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: 'git@github.com:......git'
}
Josh
  • 4,726
  • 2
  • 20
  • 32
2

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.

fangmobile
  • 839
  • 8
  • 23
2

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']]])
}
webofmars
  • 1,439
  • 1
  • 18
  • 25
2

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.

Chris
  • 739
  • 2
  • 8
  • 23
1

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.

0

No complex shell commands needed to achieve this, just add the below line :

(must have git parameter plugin installed to use:)

branchFilter: 'origin.*/(.*)', in gitParameter as shown below

pipeline {
    agent any
    parameters {
        gitParameter branchFilter: 'origin.*/(.*)', defaultValue: 'master', name: 'BRANCH', type: 'PT_BRANCH'
    }
Ajax
  • 2,465
  • 23
  • 20
Kalyan Raparthi
  • 339
  • 3
  • 11
  • Adding your proposed line, I am getting error below. Please elaborate your solution and its usage. org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed: WorkflowScript: 4: Invalid parameter type "gitParameter". Valid parameter types: [booleanParam, choice, credentials, file, text, password, run, string] @ line 4, column 5. gitParameter branchFilter: 'origin.*/(.*)', defaultValue: 'master', name: 'BRANCH', type: 'PT_BRANCH' ^ 1 error – Seweryn Habdank-Wojewódzki Feb 02 '23 at 17:35
  • Hello @SewerynHabdank-Wojewódzki The error you posted says you did not install git parameter plugin in you jenkins try installing this on server and try again https://plugins.jenkins.io/git-parameter/ – Kalyan Raparthi Feb 06 '23 at 04:41
  • Did you specified this in your proposal? I did not found clear statement like preconditions: install Git Parameter Plugin or so. – Seweryn Habdank-Wojewódzki Feb 06 '23 at 08:21
  • @SewerynHabdank-Wojewódzki If you read question properly , they specified with jenkins git plugin , that mean they installed the plugin already there is no point to specify again to install – Kalyan Raparthi Feb 06 '23 at 10:49
  • 1
    They had install jenkins git plugin. Can you precisely tell me where they mentioned that they installed "git-parameter" plugin? – Seweryn Habdank-Wojewódzki Feb 07 '23 at 10:18
  • Instead of squabbling, I just added the explicit dependency to the answer, and I suggest that, instead of trying to win an argument, next time, just improve the answer once you've discovered, solved and tested a deficiency. – Ajax Feb 18 '23 at 04:41
0

Simply put origin/(.*) as the value for Branch Filter in the Git Plugin, instead of any macro/variable. As per recommendation from documentation https://plugins.jenkins.io/git-parameter/

enter image description here

SRi
  • 1,046
  • 7
  • 10