diff --git a/.githooks/commit-msg b/.githooks/commit-msg index 115005abe..fd39f7ea1 100755 --- a/.githooks/commit-msg +++ b/.githooks/commit-msg @@ -1,27 +1,28 @@ #!/usr/bin/env bash -# The script below adds the branch name automatically to -# every one of your commit messages. The regular expression -# below searches for linear issue key's. The issue key will -# be extracted out of your branch name +# +# Extract ISSUE_ID from branch (e.g. JS-1234, GO-4222, FOO-99999) and +# prepend it to your commit message if not already present. -REGEX_ISSUE_ID="[a-zA-Z0-9]+-[0-9]+" - -# Find current branch name +REGEX_ISSUE_ID='[A-Za-z]+-[0-9]+' # letters-dash-numbers BRANCH_NAME=$(git rev-parse --abbrev-ref HEAD) COMMIT_MSG_FILE=$1 -COMMIT_TEXT=$(cat "$COMMIT_MSG_FILE") +COMMIT_TEXT=$(< "$COMMIT_MSG_FILE") -if [[ -z "$BRANCH_NAME" ]]; then - echo "Commit message validation failed: no branch name!"; exit 1 +# Find and uppercase the first matching issue key +ISSUE_ID=$(echo "$BRANCH_NAME" \ + | grep -oE "$REGEX_ISSUE_ID" \ + | head -1 \ + | tr '[:lower:]' '[:upper:]') + +# If no issue key, reject the commit +if [[ -z "$ISSUE_ID" ]]; then + echo "ERROR: Branch name must contain an issue key (e.g. GO-1234)." >&2 + exit 1 fi -# Extract issue id from branch name -ISSUE_ID=$(echo "$BRANCH_NAME" | grep -o -E "$REGEX_ISSUE_ID" | head -1 | awk '{print toupper($0)}') - -if [[ "$ISSUE_ID" != "GO-"* ]]; then - echo "Commit message validation failed: branch name should contain issue name!"; exit 1 +# If the commit message doesn’t already start with ISSUE_ID, prepend it +if [[ ! "$COMMIT_TEXT" =~ ^$ISSUE_ID ]]; then + printf "%s %s\n" "$ISSUE_ID" "$COMMIT_TEXT" > "$COMMIT_MSG_FILE" fi -if [[ "$COMMIT_TEXT" != "GO-"* ]]; then - echo "$ISSUE_ID" "$COMMIT_TEXT" > "$COMMIT_MSG_FILE" -fi +exit 0 \ No newline at end of file