Filter Git events within a Jenkinsfile
Assuming you're using Git webhooks to trigger your Jenkins builds, let's say you want to trigger a different set of pipeline stages depending on whether the Git event is a push vs. a pull request. I.e for a push you may only wish to run static analysis and unit tests, whereas for a pull request you may want to add Selenium tests.
The following Jenkinsfile snippet will achieve this
// Import JSON Slurper
import groovy.json.JsonSlurperClassic
// Get the Git payload
def payload = new JsonSlurperClassic().parseText(env.payload)
// Now define a method to filter the event type
private String getEventType ( payload ){
if( payload.pull_request && payload.action.toLowerCase().contains("opened") ){
return "pull_req"
}
else if( payload.ref && payload.head_commit){
if( payload.ref.split('/')[1].toLowerCase().contains('head') ){
return "push"
}
else if( payload.ref.split('/')[1].toLowerCase().contains('tag') ){
return "tag"
}
}
}
// Now decide what action to take
def eventType = getEventType( payload )
switch (eventType) {
case "push":
............
do something
............
break;
case "pull_req":
............
do something else
............
break;
default:
println "Git event ignored";
currentBuild.displayName = "Git event ignored"
// Tidy up the Jenkins GUI by deleting the ignored build
def buildNumber = env.BUILD_ID
node {
sh "curl -X POST http://:@:443/job/execute-pipeline/${buildNumber}/doDelete"
}