Monday 25 October 2021

Get last commit changed files in Jenkins Pipeline




To get all the modified files when starting a Jenkins Pipeline, you've just have to do 2 steps.


1. Add to the end of your scripted pipeline the following function:

 @NonCPS
def getChangedFilesList() {
    changedFiles = []

for (changeLogSet in currentBuild.changeSets) {

for (entry in changeLogSet.getItems()) { //for each commit in detected changes

for (file in entry.getAffectedFiles()) {

if (!changedFiles.contains(file.getPath())) {
// do not add duplicates

changedFiles.add(file.getPath())

}
}
}
}

return changedFiles
}


2. Call the function in a stage, after cloning the repo of your source code, to get the list of changed files (with their relative paths):

stage('Check environment') {
    steps {
        script {
            modified_files = getChangedFilesList()
            if ("myfile.txt" in modified_files) {
                echo "The file has been changed"
            } else {
                echo "The file has not been changed"
}
}
}
}

That's all!

1 comment: