Jenkinsfile Step Check if Files Changed in Directory?

Viewed 2479

I am out of my league here so forgive me if this is hard to understand. What I am trying to accomplish is to check if any files have changed in a certain directory during a pull request in my Jenkinsfile setup. If there are files that have changed compared to the develop branch, I would like to run the particular stage. This is a declarative pipeline. Let me give you example:

stage('Publish Common Module') {
  when {
   // can I check if projects/common/ has any files that are different compared to develop?
   // if so, then I want to run the steps in this stage
  }
}

I am not sure if that gives enough background as to what I am trying to accomplish. The reason for this setup is that there are multiple stages that build a module based on if there are changes in the PR for that module.

Apologies if this is not enough information to get an accurate answer.

1 Answers

I had a look at this and I think the best way would be to do something like this:

stage('Publish Common Module') {
    script{
        if(0 != sh(script: "git diff --exit-code develop", returnStatus: true)){
            // run your stage
        }
    }
}

The exit-code flags causes git to return something other then 0 when there are changes compared to develop. This exit code is returned (because of returnStatus) and compared to 0.

I don't use declarative pipelines, so I don't know if you could also move the condition in a when block instead.

Related