Prevent Push If Commit Message Does Not Match Pattern

Overview

Prevents pushes to repository if commits present in the push contain commit messages that do not match a predefined regular expression pattern.

Example

You want to enforce that commit messages in your repository follow a specific pattern.

Good to Know

  • This script checks all commits present in the push, if any of them contain a commit message that does not match the expected pattern the entire push will be blocked.

Requirements

Bitbucket Bitbucket (5.5 - 5.16)

import com.atlassian.bitbucket.hook.repository.CommitAddedDetails
import com.atlassian.bitbucket.hook.repository.PreRepositoryHookCommitCallback
import com.atlassian.bitbucket.hook.repository.RepositoryHookCommitFilter
import com.atlassian.bitbucket.hook.repository.RepositoryHookResult

import javax.annotation.Nonnull

def requiredCommitMessagePattern = ~/BUGFIX:.*/
commitCallback = new PreRepositoryHookCommitCallback() {

        @Override
        boolean onCommitAdded(@Nonnull CommitAddedDetails commitDetails) {
            def commit = commitDetails.commit

            if (!(commit.message ==~ requiredCommitMessagePattern)) {
                def msg = "Commit message: (${commit.message}) does not match required pattern: $requiredCommitMessagePattern"
                resultBuilder.veto(msg, msg)

                return false
            }

            true
        }

        @Override
        RepositoryHookResult getResult() {
            resultBuilder.build()
        }
    }

commitFilters << RepositoryHookCommitFilter.ADDED_TO_ANY_REF
RepositoryHookResult.accepted()
Discovered an issue? Report it here

Suggested for you