How to Shift-Left Better with Git Hooks

Cenk Kalpakoğlu22 Aug 2023
DevSecOpsAppSec
#!/bin/sh

# Redirect output to stderr.
exec 1>&2

# Check for 'TODO' comments in staged files.
if git diff --cached --name-only -z | xargs -0 grep -i 'TODO'; then
  echo 'Commit contains TODO comments. Please remove them and try again.'
  exit 1
fi
chmod +x .git/hooks/pre-commit
# Setting up shared hooks
git config --global core.hooksPath /path/to/your/shared/hooks
#!/bin/sh

if git diff --cached | grep -q 'console.log'
then
  echo "Code contains console.log statement. Please remove them before committing."
  exit 1
fi
#!/bin/sh

COMMIT_MSG_FILE=$1

echo "TASK-1234: $(cat ${COMMIT_MSG_FILE})" > ${COMMIT_MSG_FILE}
#!/bin/sh

COMMIT_MSG_FILE=$1
COMMIT_MSG=$(cat $COMMIT_MSG_FILE)

if [[ ! ${COMMIT_MSG} =~ ^TASK-[0-9]+:\ .+ ]]
then
  echo "Commit message does not follow the standard (TASK-XXXX: <message>)."
  exit 1
fi
#!/bin/sh

if [ $(git rev-parse --abbrev-ref HEAD) == "main" ]; then
  echo "You can't rebase the main branch!"
  exit 1
fi
#!/bin/sh

while read oldrev newrev refname
do
  if [[ $refname = "refs/heads/main" ]]; then
    echo "Direct push to the main branch is not allowed."
    exit 1
  fi 
done
#!/bin/sh

refname="$1"

if [[ $refname = "refs/heads/main" ]]; then
  echo "Direct updates to the main branch are not allowed."
  exit 1
fi
#!/bin/sh

echo "Push was successful. Notifying stakeholders..."

# Your notification logic here
#!/bin/sh 

# pre-commit hook enforcing code standards 
ESLINT="node_modules/.bin/eslint" 

git diff --cached --name-only --diff-filter=d | xargs $ESLINT 

if [ $? -ne 0 ]; then 
echo "ESLint checks failed, fix them before committing." 
exit 1 
fi
#!/bin/sh

# pre-push hook running unit tests
jest

if [ $? -ne 0 ]; then
echo "Unit tests failed, fix them before pushing."
exit 1
fi
#!/bin/sh

# Get list of staged files
STAGED_FILES=$(git diff --cached --name-only --diff-filter=ACM)

# Check each file for secrets with TruffleHog
for FILE in $STAGED_FILES
do
  truffleHog --regex --entropy=False $FILE
  if [ $? -ne 0 ]
  then
    echo "TruffleHog found potential secrets in staged file '$FILE':"
    echo "Please remove any sensitive data and commit again."
    exit 1 # prevent commit
  fi
done

# If no secrets were found, allow the commit
exit 0
#!/bin/sh

# Check for python syntax errors in staged files
git diff --cached --name-only | \

grep '\.py$' | \

xargs -I {} python -m py_compile {}

if [ $? -ne 0 ]; then
  echo "Python syntax check failed, fix errors before committing."
  exit 1
fi
#!/bin/sh

# pre-push hook running unit tests via external script

./scripts/run_unit_tests.sh

if [ $? -ne 0 ]; then
  echo "Unit tests failed, fix them before pushing."
  exit 1
fi
#!/bin/sh

# pre-commit hook checking for 'TODO' comments
if git diff --cached -G'TODO'; then
  echo "Commit rejected. Found 'TODO' comments in your changes:"
  git diff --cached -G'TODO'
  exit 1
fi

Get A Demo