Skip to content

Instantly share code, notes, and snippets.

@gbpereira
Last active May 3, 2023 15:18
Show Gist options
  • Save gbpereira/692046248598760da482b57de1981cae to your computer and use it in GitHub Desktop.
Save gbpereira/692046248598760da482b57de1981cae to your computer and use it in GitHub Desktop.
Git hooks
#!/usr/bin/env bash
#
# usage:
#   # just place it to the git repository hooks dir, named as "commit-msg"
#   # with execution permission (+x)
#   $ cp commit-msg <repo_path>/.git/hooks/
#   $ chmod +x <repo_path>/.git.hooks/commit-msg
#
pattern="^((\[SB)-[0-9]{4}\]|(\[(HOTFIX|Hotfix|hotfix)\]))\s\w+"

if ! [[ `head -n1 $1` =~ $pattern ]]; then
  echo "Bad commit message, please use the pattern:"
  echo "'[SB-0000|hotfix] my commit message'"
  exit 1
fi
#!/bin/sh
#
# usage:
#   # just place it to the git repository hooks dir, named as "pre-commit"
#   # with execution permission (+x)
#   $ cp pre-commit <repo_path>/.git/hooks/
#   $ chmod +x <repo_path>/.git.hooks/pre-commit
#
if git-rev-parse --verify HEAD >/dev/null 2>&1; then
  against=HEAD
else
  against=4b825dc642cb6eb9a060e54bf8d69288fbee4904
fi

for FILE in `git diff-index --name-only $against` ; do
  if [[ $FILE =~ .rb$ ]]; then
    if [[ $FILE =~ _spec.rb$ ]]; then
      if grep -q "focus: true" $FILE; then
        echo "[ERROR] $FILE contains focus: true!"
        exit 1
      fi
      if grep -q "puts" $FILE; then
        echo "[ERROR] $FILE contains puts!"
        exit 1
      fi
    fi
    # Check if the file contains 'byebug'
    if grep -q byebug $FILE; then
        echo "[ERROR] $FILE contains byebug!"
        exit 1
    fi
    # Check if the file contains 'binding.pry'
    if grep -q binding.pry $FILE; then
        echo "[ERROR] $FILE contains binding.pry!"
        exit 1
    fi
  fi
  if [[ $FILE =~ .js.*$ ]]; then
    # Check if the file contains 'console.log'
    if grep -q console.log $FILE; then
        echo "[ERROR] $FILE contains console.log()!"
        exit 1
    fi
    if grep -q "alert(" $FILE; then
        echo "[ERROR] $FILE contains alert()!"
        exit 1
    fi
  fi
  if [[ $FILE =~ structure.sql ]]; then
    # Check for trailing whitespaces in structure.sql
    if grep -q "[[:blank:]]$" $FILE; then
        echo "[ERROR] $FILE contains trailing whitespaces!"
        exit 1
    fi
  fi
  if [[ $FILE =~ rps_communicator.log ]]; then
    # We cannot commit this file with modifications
    echo "[ERROR] $FILE cannot be updated!"
    exit 1
  fi
done
exit

Reference: https://git-scm.com/book/en/v2/Customizing-Git-Git-Hooks

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