How to list GIT branches from Jenkins

Published on:

The problem

I need to select in a Jenkins job a branch of a GIT repository to work on.

Possible solutions

The git-parameter plugin of Jenkins

This standard Jenkins plugin called git-parameter does the job, but it has these limitations (at least in May 2015):

- If we clean the workspace, it is unable to find the branches.
- Branches aren't sorted

Let's see if we can see other solutions.

Solution based on Groovy scripting

This solution needs a slight modification to the server, supposing you are using gitolite for authorizing the access to your repository.

Modifying your gitolite installation

Following this guide, I have added a new command called branch.

For it to work, I log in to the computer that hosts the gitolite server and edit the .gitolite.rc file:

su - git
vim ~/.gitolite.rc

and add this line:

LOCAL_CODE => "$ENV{HOME}/local",

then I create the 'branch' command:

mkdir -p local/commands
cd local/commands
vim branch

and place this content:


cd ~/repositories/$1.git &&
git branch

Let's make it executable:

chmod +x branch

Now let's test it:

gitolite branch myrepo

and remotely:

ssh branch myrepo

It is left as an improvement, to control if the user has access to the repository.

Create the parameter

Now let's configure our Jenkins job to include a parameter.

I use the Extensible choice plugin in order to have a dynamically filled combo box.

I configure to have a source of System Groovy Choice parameter, and enter this small Groovy script:

[ "ssh", "", "branch myrepo"].execute().text.tokenize("\n").collect() {
  it.trim().replace("*", "")

git highlights the current repo with a star, and places some space at the left for aesthetical purposes.

If the parameter has a name of branch, then in the Branches to build field you can simply type origin/$branch.

This solution is simple, and doesn't have all the limitations of the previous solution.


comments powered by Disqus