Search code examples
gitgroovyjenkins-pipelinebitbucket-cloud

deploy functions based on the changed files in a commit by Jenkinsfile


I have many functions in my Bitbucket Repository and one single Jenkinsfile to launch one job in order to deploy these python functions. I need to deploy the functions based on the changed files in the repository. The structure of my repo is like this:

-- functions
  -- func1
    -- app.py
  -- func2.py
    -- app.py
  -- fun3.py
    -- app.py

What I want to do is: when I change some function, only deploy this function and not the others. So when I commit a change, I need to look for the changed file and deploy the corresponding function. Inside the jenkinsfile I did something like this:

            sh '''
                last_commit=$(git describe --always)

                access_token=$(cat BITBUCKET_TOKEN)             
                changed_file=$(curl https://api.bitbucket.org/1.0/repositories/account/reponame/changesets/$last_commit?access_token=$access_token | jq -r .files[].file)
                echo $changed_file > CHANGED_FILE
            '''
           CHANGED_FILE = readFile 'CHANGED_FILE'
           if (CHANGED_FILE.contains('functions/func1')) {
              // instructions ... 
           }
           CHANGED_FILE = readFile 'CHANGED_FILE'
           if (CHANGED_FILE.contains('functions/func2')) {
              // instructions ... 
           }

Here I only get the last commit and I get from it only one changed file. I want to know what logic to use to process many commits with many changed files ? I tried to use Webhook plugin but it can't do this.


Solution

  • You can run something like this (sorry for my bad Groovy):

    def changeLogSets = this.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]
               this.deployFunction(file.path)
          }
      }
    }
    

    It's working for me to build docker images. For changes only in one HUGE monorepo.

    For running script uncheck: enter image description here