Skip to content

Instantly share code, notes, and snippets.

@jmrozanec
Last active December 5, 2018 09:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jmrozanec/06e505dd5d5d81e4a9b2265c559f7ff8 to your computer and use it in GitHub Desktop.
Save jmrozanec/06e505dd5d5d81e4a9b2265c559f7ff8 to your computer and use it in GitHub Desktop.
Provides formatted messages to notify build status through Slack
def shallWeNotify(String policy, String lastStatus, String currentStatus) {
switch(policy){
case 'all-builds':
return true;
case 'status-change':
return !lastStatus.equals(currentStatus)
case 'unstable-builds':
return currentStatus.equals('UNSTABLE') || currentStatus.equals('FAILURE')
case 'broken-builds':
return currentStatus.equals('FAILURE')
}
return false
}
def getColor(String status){
switch(status){
case 'SUCCESS':
return '#BDFFC3'
case 'UNSTABLE':
return '#FFFE89'
case 'FAILURE':
return '#FF9FA1'
case 'ABORTED':
return '#C0C0C0'
}
}
def getRandomEmoji(String status){
emojis = [:]
emojis['SUCCESS']= ['hugging_face', 'nerd_face', 'sunglasses', 'muscle', 'raised_hands', 'rocket', 'tada']
emojis['FAILURE']= ['slightly_frowning_face', 'disappointed', 'disappointed_relieved', 'thinking_face', 'tired_face', 'face_palm']
emojis['UNSTABLE']= ['face_with_raised_eyebrow','neutral_face']
emojis['ABORTED']= ['hushed', 'frowning', 'astonished']
selected_list = emojis[status]
return selected_list[new Random().nextInt(selected_list.size())]
}
def createSlackMessage(String status){
String failureData = "Check <${env.BUILD_URL}/changes|build changes> and <${env.BUILD_URL}/console|console output> for more info"
String unstableData = "Check <${env.BUILD_URL}/changes|build changes>, <${env.BUILD_URL}/cobertura|coverage reports> and <${env.BUILD_URL}/console|console output> for more info"
String abortedData = "Perhaps interested on <${env.BUILD_URL}/changes|build changes>?"
String emoji = getRandomEmoji(status)
switch(status){
case 'SUCCESS':
return "Yay! `${env.JOB_NAME}` is good again! :${emoji}:"
case 'UNSTABLE':
return "Hmmm ... `${env.JOB_NAME}` is unstable again :${emoji}: \n" + unstableData;
case 'FAILURE':
return "Ooops! `${env.JOB_NAME}` failed ... :${emoji}: \n" + failureData;
case 'CANCELLED':
return "Hey! `${env.JOB_NAME}` was cancelled! :${emoji}: \n" + abortedData;
}
}
def notifySlack(String buildStatus = 'STARTED') {
def policy = 'all-builds' //ideally defined in another place :)
previousBuildStatus = currentBuild.rawBuild.getPreviousBuild()?.getResult()
if(shallWeNotify(policy, previousBuildStatus.toString(), buildStatus)){
slackSend(color: getColor(buildStatus), message: createSlackMessage(buildStatus))
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment