Retrieve Latest Changed Files, Commit ID, Author Name, and Commit Message in Jenkins Pipeline
This guide demonstrates how to use Jenkins' currentBuild.changeSets variable within a pipeline script to obtain the list of files changed between builds, as well as the commit ID, author name, and commit message, enabling conditional flow control based on these details.
Jenkins — Get the latest changed files list, Commit ID, Author Name, and Commit Message
Sometimes requirements arise to run a Jenkins job or stage based solely on changes from the previous build, such as files changed, specific patterns in commit messages, commit ID, or author name.
Using native git commands in a shell step only provides differences between the last two commits, not the changes between Jenkins builds.
To retrieve the desired information, the currentBuild.changeSets environment variable can be used as shown below.
pipeline {
agent any
stages {
stage('Get Last Commit Details') {
steps {
script{
List
changes = getChangedFilesList()
println ("Changed file list: " + changes)
String gitCommitId = getGitcommitID()
println("GIT CommitID: " + gitCommitID)
String gitCommitAuthorName = getAuthorName()
println("GIT CommitAuthorName: " + gitCommitAuthorName)
String gitCommitMessage = getCommitMessage()
println("GIT CommitMessage: " + gitCommitMessage)
}
}
}
}
}
@NonCPS
List
getChangedFilesList(){
def changedFiles = []
for (changeLogSet in currentBuild.changeSets){
for (entry in changeLogSet.getItems()){
changedFiles.addAll(entry.affectedPaths)
}
}
return changedFiles
}
@NonCPS
String getGitcommitID(){
gitCommitID = " "
for (changeLogSet in currentBuild.changeSets){
for (entry in changeLogSet.getItems()){
gitCommitID = entry.commitId
}
}
return gitCommitID
}
@NonCPS
String getAuthorName(){
gitAuthorName = " "
for (changeLogSet in currentBuild.changeSets){
for (entry in changeLogSet.getItems()){
gitAuthorName = entry.authorName
}
}
return gitAuthorName
}
@NonCPS
String getCommitMessage(){
commitMessage = " "
for (changeLogSet in currentBuild.changeSets){
for (entry in changeLogSet.getItems()){
commitMessage = entry.msg
}
}
return commitMessage
}After obtaining the required values, they can be used as data sources to control the flow of the Jenkins pipeline.
Note: changeSets only contain the list of files modified between the current build and the previous successful build; if the previous build failed and was retriggered, changeSets may be empty. You may need to retrieve changes for a specific branch.
DevOps Cloud Academy
Exploring industry DevOps practices and technical expertise.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.