The Ultimate Guide to Precommit Hook for Efficient Development Workflows

Introduction to Precommit Hook

Precommit hooks are scripts that run automatically before you make a commit. They are crucial for automated code quality checks, testing, and much more. In this guide, we’ll delve into the various APIs of precommit-hook and provide examples for better understanding.

Setting Up Precommit Hook

To set up a precommit hook, you need to add a script in the .git/hooks directory. Here’s a basic setup:

#!/bin/sh echo "Running pre-commit hook" 

Example APIs

Linting Code

Use precommit hooks to run a linter before committing. This ensures code quality:

#!/bin/sh eslint . --fix if [ $? -ne 0 ]; then
  echo "Linting failed"
  exit 1
fi 

Running Tests

Ensure all tests pass before committing:

#!/bin/sh npm test if [ $? -ne 0 ]; then
  echo "Tests failed"
  exit 1
fi 

Checking for Large Files

Prevent large files from being committed:

#!/bin/sh FILES=$(git diff --cached --name-only) for FILE in $FILES; do
  if [ $(stat -c%s "$FILE") -gt 1048576 ]; then
    echo "File $FILE is too large"
    exit 1
  fi
done 

Validating Commit Messages

Ensure commit messages follow a convention:

#!/bin/sh COMMIT_MSG=$(cat "$1") if ! [[ $COMMIT_MSG =~ ^(feat|fix|docs|style|refactor|test|chore)\(.*\): ]]; then
  echo "Commit message does not follow the convention"
  exit 1
fi 

Application Example

Imagine you are developing an application and want to enforce code style, run tests, and check for sensitive data before each commit. Here’s how you can set it up:

#!/bin/sh # Run ESLint eslint . --fix if [ $? -ne 0 ]; then
  echo "Linting failed"
  exit 1
fi
# Run Tests npm test if [ $? -ne 0 ]; then
  echo "Tests failed"
  exit 1
fi
# Check for sensitive data grep -r "API_KEY" . && {
  echo "Sensitive data found"
  exit 1
} 

With this example, we ensure that our code adheres to the standards, all tests pass, and no sensitive data is committed. This strengthens our development workflow and minimizes errors.

Hash: 64c52689555f8291d86e0683efb7f38ce34345e4c7aa98613db483e51c5413cc

Leave a Reply

Your email address will not be published. Required fields are marked *