Skip to content

Commit

Permalink
ci(commitlint): add local hook to enforce commit convention
Browse files Browse the repository at this point in the history
Co-authored-by: Soha Alboghdady <[email protected]>
Co-authored-by: Raghunath Deshpande <[email protected]>
  • Loading branch information
3 people committed Jul 17, 2023
1 parent 45d7cdd commit ed1d37d
Show file tree
Hide file tree
Showing 2 changed files with 70 additions and 0 deletions.
21 changes: 21 additions & 0 deletions .hooks/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
# Git Hooks

Run conventional commit checks locally without any tool installation

## Usage

Adjust the git commit hook configuration as follows, from the root directory of pcap-release:

```shell
git config core.hooksPath .hooks
```

Please note that any hooks you had in other directories may not work.

Alternatively you can also soft-link the commit-msg script:

```shell
ln -s .hooks/commit-msg .git/hooks/commit-msg
```

This invocation will fail if you have a commit-msg hook already, in order to not break existing hooks.
49 changes: 49 additions & 0 deletions .hooks/commit-msg
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
#!/usr/bin/env bash

set -euo pipefail

# use commitlint with its full config if available
if command -v commitlint >/dev/null && commitlint -v >/dev/null; then
# Find base directory (script_location/..)
COMMITLINT_CONFIG="$(realpath "$(dirname "$0")/..")/commitlint.config.js"
# execute commitlint only if the commitlint config exists
[[ -f "$COMMITLINT_CONFIG" ]] && exec commitlint --edit "$1" --verbose --config "$COMMITLINT_CONFIG"
fi

# Configuration

# list of allowed commit types, space separated
TYPES="fix feat dep ci doc refactor test"
# scope length
SCOPE_LENGTH=25
# commit subject length
SUBJECT_LENGTH=70

# Logic
first_line=$(head -n1 "$1")
conv_commit_msg="^(${TYPES// /|})(\(.{1,$SCOPE_LENGTH}\))?(!?): (.{1,$SUBJECT_LENGTH})\$"

_print_convention() {
echo "ERROR: Commit message does not confirm to commit conventions."
echo " ----"
sed 's/^/ > /' "$1"
echo
echo "Rules: type(scope)!: commit subject"
echo " - type: must be one of: ${TYPES// /, }"
echo " - scope: (optional) arbitrary text: "
echo " - !: breaking change indicator. Body MUST contain 'breaking-change:' header (case in-sensitive)"
}

# trap will be fired when the script exits. It will exit if any of the commands, including the grep below, fail.
trap '_print_convention "$1"' EXIT

# check that the first line conforms to the convention pattern
grep -qE "$conv_commit_msg" <<< "$first_line"

# if there is a !, indicating breaking change, ensure that there is a "breaking-change:" header.
if [[ "$(sed -nE "s/$conv_commit_msg/\3/p" <<<"$first_line")" == "!" ]]; then
grep -qiE "^breaking(-| )change: .+" "$1"
fi

# All rules passed. Disable _print_convention printing
trap "" EXIT

0 comments on commit ed1d37d

Please sign in to comment.