Jenkinsfile - get all changes between builds
Regarding this question , is there a way to get equivalent information when using a multi-drop pipeline? In particular, a list of commits since the last successful build.
We are currently using the following
def scmAction = build?.actions.find { action ->
action instanceof jenkins.scm.api.SCMRevisionAction
}
return scmAction?.revision?.hash
but this only returns the last commit that caused the build if multiple commits were pushed. I agree that the very first build of a new branch might be ambiguous, but getting a list of the commits that triggered the build would be very helpful.
source to share
I found a solution that seems to work for us. It revolves around getting a hash function currentBuild
and then a hash code lastSuccessfulBuild
. We first wrote a utility method to get the commit hash of a given Jenkins build object:
def commitHashForBuild(build) {
def scmAction = build?.actions.find { action -> action instanceof jenkins.scm.api.SCMRevisionAction }
return scmAction?.revision?.hash
}
then use this to get the hash lastSuccessfulBuild
:
def getLastSuccessfulCommit() {
def lastSuccessfulHash = null
def lastSuccessfulBuild = currentBuild.rawBuild.getPreviousSuccessfulBuild()
if ( lastSuccessfulBuild ) {
lastSuccessfulHash = commitHashForBuild(lastSuccessfulBuild)
}
return lastSuccessfulHash
}
finally combine these two in a function sh
to get a list of commits
def lastSuccessfulCommit = getLastSuccessfulCommit()
def currentCommit = commitHashForBuild(currentBuild.rawBuild)
if (lastSuccessfulCommit) {
commits = sh(
script: "git rev-list $currentCommit \"^$lastSuccessfulCommit\"",
returnStdout: true
).split('\n')
println "Commits are: $commits"
}
you can use an array commits
to request various things in Git as your build requires. For example. you can use this data to get a list of all changed files since the last successful build.
I've put this in the complete Jenkinsfile Gist example to show how it fits together in context.
A possible improvement would be to use the Java / Groovy Git library instead of stepping through it sh
.
source to share
I think Jenkins Last Changes plugin can provide the information you need, have a look here: https://wiki.jenkins-ci.org/display/JENKINS/Last+Changes+Plugin
source to share