Skip to content

Instantly share code, notes, and snippets.

@mrhockeymonkey
Last active March 16, 2024 02:11
Show Gist options
  • Save mrhockeymonkey/6b7b815b7bf3732f32ad1c5c913afff5 to your computer and use it in GitHub Desktop.
Save mrhockeymonkey/6b7b815b7bf3732f32ad1c5c913afff5 to your computer and use it in GitHub Desktop.
Jenkins: git diff in pipeline to discover modified files
#!groovy
// https://medium.com/rocket-travel-engineering/running-advanced-git-commands-in-a-declarative-multibranch-jenkinsfile-e82b075dbc53
// Jenkins only checks out the branch for performance reasons so to be able to do more advanced git commands we need to
// also fetch master (or anything else you need)
pipeline {
agent any
stages {
stage ("info") {
when {
changeRequest()
}
steps {
powershell 'gci env:\\ | ft name,value -autosize'
// add a ref to git config to make it aware of master
powershell '& git config --add remote.origin.fetch +refs/heads/master:refs/remotes/origin/master'
// now fetch master so you can do a diff against it
powershell '& git fetch --no-tags'
// do the diff and set some variable based on the result
powershell '''
$DiffToMaster = & git diff --name-only origin/master..origin/$env:BRANCH_NAME
Switch ($DiffToMaster) {
'server-1607/base.json' {$env:PACK_BASE = $true}
'server-1607/basic.json' {$env:PACK_BASIC = $true}
'server-1607/algo.json' {$env:PACK_ALGO = $true}
'server-1607/build.json' {$env:PACK_BUILD = $true}
'server-1607/calc.json' {$env:PACK_CALC = $true}
}
gci env:/PACK_*
'''
}
}
}
}
@sphimmer
Copy link

OMG! this is what i was looking for. So good! thank you for putting this out there!

@mrhockeymonkey
Copy link
Author

@sphimmer I'm glad this was helpful! Just a word of warning about something I've learnt since and haven't updated here:

There is a subtle difference between origin/master..origin/$env:BRANCH_NAME and origin/master...origin/$env:BRANCH_NAME. Notice the dots. If you want to see the changes exactly as they would appear on a GitHub PR you will want to use ....

See this blog post for a better explanation

@romatr
Copy link

romatr commented Dec 21, 2021

Thanks, this helped a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment