Create a Custom Commitlint Pattern


How to create a custom rule for for a git commit log format

You can read about how to setup commitlint to enforce your log format. And you can choose a pre-existing format, such as "Conventional Commit".

But in this case, we want to create our own custom format. We want each of our git commit log titles to match our ticketing system ticket numbers, which are in the format of COOL-1234 or COOL-4422, etc.

Let's do it by setting up commitlint.config.mjs to read:

export default {
  parserPreset: {
    parserOpts: {
      headerPattern: /^(COOL-\d{1,4}) - (.+)/,
      headerCorrespondence: ['issue', 'title'],
    },
  },
  plugins: [
    {
      rules: {
        'title-pattern': ({ issue, title }) =>
          issue === null || title === null
            ? [false, "title must begin with the ticket number 'COOL-1234 - title'"]
            : [true, ''],
      },
    },
  ],
  rules: {
    'title-pattern': [2, 'always'],
  },
}

Now to try it out. Assuming we've installed the tool and configed as linked and shown above, we could try a bad commit message:

git add .
git commit -m "asdf"

And we'd get some error feedback, clarifying our enforcement:

input: asdf
title must begin with the ticket number 'COOL-1234 - title' [title-pattern]

found 1 problem, 0 warnings

And if we used a good commit message, like:

git commit -m "COOL-1234 - Add a new feature"

We're committed, and good to go. So get committed!