阿里云主机折上折
  • 微信号
Current Site:Index > Git Hooks: Automatically intercept low-level errors before committing

Git Hooks: Automatically intercept low-level errors before committing

Author:Chuan Chen 阅读数:33810人阅读 分类: 前端综合

What Are Git Hooks

Git Hooks are a mechanism in the Git version control system that allows developers to automatically trigger custom scripts when specific Git events occur. These scripts can intercept or modify Git's workflow, such as running checks before committing code or executing tests before pushing code. Git Hooks are stored in the .git/hooks directory of a project and include some sample scripts by default (e.g., pre-commit.sample). Removing the .sample suffix enables them.

Why Intercept Low-Level Errors Before Committing

Low-level errors, such as typos, unused variables, incorrect indentation, or missing semicolons, may not directly cause program crashes but can harm code readability and maintainability. If these errors make their way into the codebase, they may lead to more serious issues during later development. By using Git Hooks to automatically intercept these errors before committing, you can ensure the codebase remains high-quality.

Common Types of Low-Level Errors

1. Syntax Errors

For example, missing parentheses or mismatched quotes in JavaScript. These errors prevent the code from running.

// Error example: Missing closing parenthesis
function sayHello() {
  console.log("Hello, world!";
}

2. Unused Variables

Variables that are defined but not used, which may be leftover code or logical errors.

// Error example: Unused variable
const unusedVar = "This is not used";
function doSomething() {
  console.log("Doing something");
}

3. Code Style Issues

For example, inconsistent indentation or missing semicolons. While these don't affect execution, they can hinder team collaboration.

// Error example: Inconsistent indentation
function badIndent() {
console.log("This is badly indented");
}

4. Debugging Code Leftovers

For example, committing console.log statements or debug breakpoints.

// Error example: Debugging code leftover
function calculateSum(a, b) {
  console.log("Calculating sum..."); // Debugging code that shouldn't be committed
  return a + b;
}

How to Use Git Hooks to Intercept Errors

1. Using the pre-commit Hook

The pre-commit hook triggers before a commit and can run code-checking tools at this stage.

Example: Using ESLint to Check Code

First, install ESLint:

npm install eslint --save-dev

Then, write the following script in .git/hooks/pre-commit:

#!/bin/sh

# Run ESLint check
echo "Running ESLint..."
eslint .

if [ $? -ne 0 ]; then
  echo "ESLint found errors. Please fix them before committing."
  exit 1
fi

2. Using the commit-msg Hook

The commit-msg hook can check whether commit messages follow a specified format, such as including a JIRA task number.

Example: Checking Commit Message Format

#!/bin/sh

# Check if the commit message includes a JIRA task number
if ! grep -qE '^[A-Z]+-[0-9]+' "$1"; then
  echo "Commit message must include a JIRA task number (e.g., PROJ-123)."
  exit 1
fi

3. Using Husky to Simplify Hook Management

Managing Git Hooks manually can be cumbersome. Tools like Husky can simplify the process.

Installing Husky

npm install husky --save-dev
npx husky install

Adding a pre-commit Hook

npx husky add .husky/pre-commit "npm run lint"

Practical Examples: Intercepting Common Errors

Example 1: Intercepting Unused Variables

Configure the ESLint rule no-unused-vars and run the check in pre-commit.

.eslintrc.json:

{
  "rules": {
    "no-unused-vars": "error"
  }
}

Example 2: Intercepting Debugging Code

Use ESLint's no-console rule to block console.log commits.

.eslintrc.json:

{
  "rules": {
    "no-console": "error"
  }
}

Example 3: Intercepting Typos

Use the cspell tool to check for spelling errors.

Installation:

npm install cspell --save-dev

pre-commit script:

#!/bin/sh

echo "Running spell check..."
npx cspell "**/*.{js,jsx,ts,tsx}"

if [ $? -ne 0 ]; then
  echo "Spell check failed. Fix errors before committing."
  exit 1
fi

Advanced Usage: Combining Multiple Tools

You can combine tools like ESLint, Prettier, and TypeScript for comprehensive checks.

Example: Comprehensive Check Script

#!/bin/sh

echo "Running checks..."

# 1. Run ESLint
eslint .
if [ $? -ne 0 ]; then
  exit 1
fi

# 2. Run TypeScript type checking
tsc --noEmit
if [ $? -ne 0 ]; then
  exit 1
fi

# 3. Run unit tests
npm test
if [ $? -ne 0 ]; then
  exit 1
fi

Notes

  1. Performance Issues: If the project is large, running checks can be slow. Optimize by checking only staged files:

    git diff --cached --name-only | grep -E '\.(js|jsx|ts|tsx)$' | xargs eslint
    
  2. Flexibility: Sometimes you may need to skip checks temporarily. Use the --no-verify option to bypass:

    git commit --no-verify -m "Emergency fix"
    
  3. Team Collaboration: Git Hooks are not synced to remote repositories by default. Use tools like Husky to ensure consistent configuration across team members.

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.