Skip to content

Instantly share code, notes, and snippets.

@marcojahn
Last active October 31, 2024 16:16
Show Gist options
  • 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

@ppuschmann
Copy link

ppuschmann commented Aug 8, 2024

The only improvement for my use-case in @pplmx 's code (link) is: Add a \. to the (…) to allow ..

-->

^(build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test){1}(\([\w\-\.]+\))?(!)?: .{1,80}(\n|\r\n){2}(.*(\n|\r\n)*)*$

@YellowPluff
Copy link

YellowPluff commented Oct 31, 2024

Here is another take on this, which works better for me because it follows the convention more literally.

^(((Initial commit)|(Merge [^\r\n]+(\s)[^\r\n]+((\s)((\s)[^\r\n]+)+)*(\s)?)|^((build|chore|ci|docs|feat|fix|perf|refactor|revert|style|test)(\([\w\-]+\))?!?: [^\r\n]+((\s)((\s)[^\r\n]+)+)*))(\s)?)$

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