'Build stages in Jenkins only when specific files are changed but use a function

I want to update my Jenkins pipeline in way that certain stages are only build when some specific files are changed (git is already integrated in the pipeline). I found a promising solution on this site, which would go like this for my use case (this code run successful):

stage("TEST STAGE 1") {
  when {
    anyOf { changeset "*dir1/*"; changeset "*dir2/*"; changeset "*somefile" }
  }
  steps {
    // Do stuff
  }
}

But I have more stages (TEST STAGE 2 and TEST STAGE 3) which should also be triggered only when these files are changed. To avoid writing the same code over and over (which would be bad practice), I implemented a function (I got the code from here):

def runStage(changeset) {
  return {
    changeset ==~ ("*dir1/*"||"*dir2/*"||"*somefile")
  }
}

I call this function in the TEST stages (also TEST 2 and 3):

stage("TEST STAGE 1") {
  when {
    expression{ runStage(changeset) }
  }
  steps {
    // Do stuff
  }
}

But now my pipeline fails when entering the first TEST stage. I get this error:

hudson.remoting.ProxyException: groovy.lang.MissingPropertyException: No such property: changeset for class: WorkflowScript

Do you have an idea what I am doing wrong?



Solution 1:[1]

I found a solution. This is my function:

def runStage() {
   CHANGE_SET = sh (
      script: 'git log -2 --name-only --oneline --pretty="format:"',
      returnStdout: true
   ).trim()
   echo "Current changeset: ${CHANGE_SET}"
   return (CHANGE_SET ==~ "(.*)dir1(.*)|(.*)dir2(.*)|(.*)somefile")
}

I call it in my pipeline stage like this:

stage("TEST STAGE 1") {
   when { 
      expression { runStage() }
   }
   steps {
      //stuff
   }
}

I would have prefered using changeset in the when block instead of git log, but it looks like it can't be done for my case.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ano