-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathvalidate-conventional-commit.sh
More file actions
executable file
·54 lines (45 loc) · 1.73 KB
/
Copy pathvalidate-conventional-commit.sh
File metadata and controls
executable file
·54 lines (45 loc) · 1.73 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env bash
# Validate that commit messages follow the Conventional Commits specification.
#
# Format: type(scope): description
# type: feat, fix, docs, style, refactor, perf, test, build, ci, chore, revert
# scope: optional
# description: concise summary of the change
#
# Usage:
# $0 <commit-message-file>
#
# This hook reads the commit message from the specified file and validates it.
set -euo pipefail
ALLOWED_TYPES=(feat fix docs style refactor perf test build ci chore revert)
COMMIT_MSG_FILE="${1:-.git/COMMIT_EDITMSG}"
if [[ ! -f "$COMMIT_MSG_FILE" ]]; then
echo "ERROR: Commit message file not found: $COMMIT_MSG_FILE" >&2
exit 1
fi
# Read commit message, strip comments and trailing whitespace
COMMIT_MSG=$(sed '/^#/d' "$COMMIT_MSG_FILE" | sed -e 's/[[:space:]]*$//' | head -1)
if [[ -z "$COMMIT_MSG" ]]; then
echo "ERROR: Empty commit message." >&2
exit 1
fi
# Validate format: type(scope)!: description OR type!: description
# Allow optional scope in parentheses, but keep it a single token with common
# path-like punctuation and no spaces.
if ! printf '%s\n' "$COMMIT_MSG" | grep -Eq '^([a-z]+)(\([A-Za-z0-9._/-]+\))?(!)?: .+'; then
echo "ERROR: Commit message does not follow Conventional Commits format." >&2
echo "Expected format: type(scope)!: description" >&2
echo "Got: $COMMIT_MSG" >&2
exit 1
fi
# Extract type from commit message without external tools
COMMIT_TYPE="${COMMIT_MSG%%:*}"
COMMIT_TYPE="${COMMIT_TYPE%%(*}"
COMMIT_TYPE="${COMMIT_TYPE%!}"
# Validate that type is in the allowed list
if ! printf '%s\n' "${ALLOWED_TYPES[@]}" | grep -q "^$COMMIT_TYPE$"; then
echo "ERROR: Invalid commit type: '$COMMIT_TYPE'" >&2
echo "Allowed types: ${ALLOWED_TYPES[*]}" >&2
exit 1
fi
exit 0