Search code examples
jenkinsjenkins-pipelinejenkins-pluginsjenkins-groovyjenkins-cli

How to get list of changed files in Jenkinsfile for a pull request?


Is it possible to get a list of changed files in the Jenkinsfile during a pull request build? I am currently doing this...

def changeLogSets = currentBuild.rawBuild.changeSets
    for (int i = 0; i < changeLogSets.size(); i++) {
        def entries = changeLogSets[i].items
        for (int j = 0; j < entries.length; j++) {
            def entry = entries[j]
            def files = new ArrayList(entry.affectedFiles)
            for (int k = 0; k < files.size(); k++) {
                def file = files[k]
                print file.path 
            }
        }
    }

but if I am building a new branch for the very first time this method does not return any changes because there is no previous build to compare to. Has anyone found a solution to this?

Thanks


Solution

  • As far as I know there's no built-in functionality to do this.

    Fortunately, you can find that out programmatically:

        def local_branch = sh (
            script: "git rev-parse --abbrev-ref HEAD",
            label: "Getting current branch name",
            returnStdout: true
        ).trim()
        println "Local branch is ${local_branch}"
    
        def base_branch = 'master' 
        // This is very naive.
        // In reality, you need a better way to find out what your base branch is.
        // One way is to have a file with a name of a base branch.
        // Another one is to invoke API, e.g. GitHub API, to find out base branch.
        // Use whatever works for you.
        println "Base branch is ${base_branch}"
    
        sh script: "git fetch origin --no-tags ${base_branch}", label: "Getting base branch"
    
        def git_diff = sh (
            script: "git diff --name-only origin/${base_branch}..${local_branch}",
            returnStdout: true
        ).trim()
    

    Now you have a list of changed files in the git_diff variable.

    Using Jenkins changesets is mostly not working, and is reserved for other purposes anyhow.