Skip to content

Instantly share code, notes, and snippets.

@marcojahn
Last active April 13, 2024 13:27
Show Gist options
  • Star 33 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save marcojahn/482410b728c31b221b70ea6d2c433f0c to your computer and use it in GitHub Desktop.
Save marcojahn/482410b728c31b221b70ea6d2c433f0c to your computer and use it in GitHub Desktop.
Conventional Commit Regex

the following regex will validate all examples provided here: https://www.conventionalcommits.org/en/v1.0.0/

  ^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test){1}(\([\w\-\.]+\))?(!)?: ([\w ])+([\s\S]*)

a grep/posix compatible variant

  ^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test){1}(\([[:alnum:]._-]+\))?(!)?: ([[:alnum:]])+([[:space:][:print:]]*)

checking all commits (https://gist.github.com/opyate/d6b8b728edc16a3e4e185b78d26d4b0b)

#!/bin/sh
# .git/hooks/commit-msg
test "" != "$(egrep '[A-Z]{3,}-\d+' "$1")" || {
    echo >&2 Commit message requires JIRA code.
    exit 1
}

checking a specific branch (https://gist.github.com/pgilad/5d7e4db725a906bd7aa7)

#!/usr/bin/env bash

# set this to your active development branch
develop_branch="develop"
current_branch="$(git rev-parse --abbrev-ref HEAD)"

# only check commit messages on main development branch
[ "$current_branch" != "$develop_branch" ] && exit 0

# regex to validate in commit msg
commit_regex='(wap-[0-9]+|merge)'
error_msg="Aborting commit. Your commit message is missing either a JIRA Issue ('WAP-1111') or 'Merge'"

if ! grep -iqE "$commit_regex" "$1"; then
    echo "$error_msg" >&2
    exit 1
fi

Online resources

Integration

@LordFckHelmchen
Copy link

In the first regex, you need to escape the dash - otherwise it'll try to interpret that as a range. See here for the error

@marcojahn
Copy link
Author

Fixed, thanks!

@mxcd
Copy link

mxcd commented Dec 1, 2022

I think this regex also matches commit messages, where the body is not separated by a blank newline from the header

The body MUST begin one blank line after the description.

According to point #6 of the specification

@boylec
Copy link

boylec commented Jan 13, 2023

To support emojis

^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test){1}(\([\w\.\-\p{Extended_Pictographic}]+\))?(!)?: ([\w \p{Extended_Pictographic}])+([\s\S]*)

@aBraM-aBraM
Copy link

I'd like to suggest two features that I think are very useful:

  • make sure the word cr isn't in the commit message - make developers squash/amend commits instead of pushing garbage)
  • make sure the first word doesn't end with ed - past tense for commits is just wrong..

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment