4

I am using declarative pipelines and would like to run a stage only when it matches a certain branch and the latest commit does not include certain text.

Matching the branch is the easy part:

when {
  branch 'master'
}

But for checking the latest commit message, I am unsure how to add in this check.

I have come across this answer which is very much the kind of thing I am trying to achieve.

I am wondering if I need to use an expression clause that would contain the logic similar to the answer linked to above, to query the git log and parse\check the latest commit message contains my supplied regex pattern.

Can anyone point me at any snippets that would help me here?

Thanks

mindparse
  • 6,115
  • 27
  • 90
  • 191

1 Answers1

1

I answer a bit late, but it could be useful for others.

The answer you pointed us out is for Scripted Pipeline and works well.

If you want to do this in a Declarative way, you can combine changelog condition and branch condition like this:

stage("Skip release commit") {
    when {
        changelog "^chore\\(release\\):.*"
        branch "master"
    }
    steps {
        script {
            // Abort the build to avoid build loop
            currentBuild.result = "ABORTED"
            error('Last commit is from Jenkins release, cancel execution')
        }
    }
}

My point was to skip the build when Jenkins is commiting on the master branch with a chore(release):... message.

If you have to check a more complex branch name, you can replace branch "master" by something like expression {env.BRANCH_NAME ==~ /^feat\/.+/} (to execute the stage only on branch name starting by "feat/")

Unfortunely, if the contributors on your project do git commit --amend on a previous commit with message that matches the changelog condition then the stage will be not triggered because changelog will be Branch indexing for this amend.

In this case you probably need :

environment {
    CHORE_RELEASE = sh script: "git log -1 | grep 'chore(release):'", returnStatus: true
}
when {
    expression { "${CHORE_RELEASE}" == "0" }
    branch "master"
}

instead of

when {
    changelog "^chore\\(release\\):.*"
    branch "master"
}
Jocker
  • 268
  • 1
  • 2
  • 10