Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jenkins Pipeline: How do I fetch (not pull) a different branch?

I'm trying to use Jenkins Pipelines and I would like to diff the current branch of the job to master. For that I need to have master checked out. Jenkins only checks out the branch I'm building.

I tried: withCredentials([[$class: 'UsernamePasswordMultiBinding', credentialsId: 'GITHUB', usernameVariable: 'GIT_USERNAME', passwordVariable: 'GIT_PASSWORD']]) { sh 'git fetch origin master:master' }

but that only binds the credentials to the ENV variables and git doesn't pick that up.

All the other approaches I've seen use checkout, but that would change my current branch. I only want to fetch the master so I can do a git diff later

like image 877
mirosval Avatar asked Jun 08 '17 10:06

mirosval


People also ask

Is it impossible to checkout a different branch in Jenkinsfile?

@swoop81 answer is working but if you just want to checkout one branch, you could fetch only this one.

How do I run a Jenkins pipeline on a specific branch?

Head over to your Jenkins instance and create a new item. Enter a name for the job, and select the “Multibranch Pipeline” option at the end of the screen. Then, click on the OK button. In the next screen, go to the “Branch sources” tab, click on the “Add source” button, and choose “Git” from the dropdown menu.

How do I pull just the current branch?

Git already only pulls the current branch. If you have branch set up as a tracking branch, you do not need to specify the remote branch. git branch --set-upstream localbranch reponame/remotebranch will set up the tracking relationship. You then issue git pull [--rebase] and only that branch will be updated.


1 Answers

I found a workaround:

git branch: 'master', credentialsId: 'GITHUB', url: env.GIT_URL
git branch: env.BRANCH_NAME, credentialsId: 'GITHUB', url: env.GIT_URL

First I check out the master branch and then check out my branch again. This is not ideal, since its changing the working tree instead of just fetching the master branch, but it works.

like image 134
mirosval Avatar answered Oct 24 '22 20:10

mirosval