Black Pine

Global git hooks setup

Create global git hooks and configure Git to use them.

Set up a global pre-commit hook

  1. Create a global Git hooks folder:

    mkdir ~/.git-hooks
  2. Create the pre-commit script:

    cd ~/.git-hooks
    touch pre-commit
  3. Add your script to pre-commit file. For a quick sanity check, add a line like:

    echo "Triggered pre-commit hook"
  4. Make the script executable:

    chmod +x ~/.git-hooks/pre-commit
  5. Configure Git to use the global hooks path:

    git config --global core.hooksPath ~/.git-hooks

Set up a global commit-msg hook

  1. Create a global Git hooks folder (if not created above):

    mkdir ~/.git-hooks
  2. Create the commit-msg script:

    cd ~/.git-hooks
    touch commit-msg
  3. Add your script to commit-msg file. For a quick sanity check, add a line like:

    echo "Triggered commit-msg hook"
  4. Make the script executable:

    chmod +x ~/.git-hooks/commit-msg

Disable global hooks for a specific repository

If you need to disable the global hooks for a specific repository, run this inside that repository:

git config core.hooksPath .git/hooks

Examples of pre-commit and commit-msg hooks

pre-commit that blocks commit of files containing TODO/FIXME comments in staged diff

#!/usr/bin/env bash
set -euo pipefail

echo "pre-commit: running checks..."

files=$(git diff --cached --name-only --diff-filter=AM | tr '\n' ' ')
[ -z "${files// }" ] && exit 0

if git diff --cached -U0 | grep -E '^\+.*\b(TODO|FIXME)\b' >/dev/null 2>&1; then
  echo "pre-commit: TODO/FIXME found in staged changes. Resolve or remove before committing."
  exit 1
fi

echo "pre-commit: OK"

commit-msg that enforces commit message format

#!/usr/bin/env bash
set -euo pipefail

msg_file="$1"
subject="$(head -n 1 "$msg_file" | tr -d '\r')"

if [[ "$subject" =~ ^Merge\  ]] || [[ "$subject" =~ ^Revert\ \" ]]; then
  exit 0
fi

if [ "${#subject}" -lt 10 ]; then
  echo "commit-msg: message is too short (min 10 chars)."
  echo "Example: feature: added new css file for dark mode"
  exit 1
fi

pattern='^(feat|fix|docs|refactor|test|chore|build|style|revert)(\([a-z0-9._-]+\))?: .+'
if [[ ! "$subject" =~ $pattern ]]; then
  echo "commit-msg: invalid format."
  echo "Use: type(scope): message"
  echo "Example: docs(blog): add tiny web server post"
  exit 1
fi