Skip to content
subuilds.dev

← logbuild #11 passedde498da

Git Hooks for Automation: Catch Mistakes Before You Push

Learn how to use Git hooks (pre-commit, commit-msg, pre-push). They check code quality automatically, keep commit messages in one format, and stop broken code before it reaches your repository.

· 10 min read

In Simple Words#

The problem
Small mistakes reach the shared repository: lint errors, failing tests, a commit message like “fix stuff”. CI fails minutes later, and the whole team sees it.
The root cause
Nothing checks your work on your own computer. The first check happens only after you push, and each person follows the rules in a different way.
The solution
Add Git hooks: small scripts that Git runs before a commit and before a push. They stop a bad commit in seconds. Share them with Husky, and keep CI/CD as the second check.
Think of it like this
You read a letter one more time before you put it in the mailbox. A wrong word takes seconds to fix at your desk. After you send the letter, everyone who reads it sees the mistake.

Why Use Git Hooks?#

You commit a console.log by mistake. CI fails. You forgot the tests. Your commit message says “fix stuff.” Your team lead is not happy.

Git hooks stop that. A hook is a script that Git runs at a fixed point in your workflow: before a commit, before a push, after a merge. Hooks catch mistakes before anyone sees them.

What hooks prevent:

  1. Bad code that reaches the repo

    • Linting errors (a linter is a tool that finds common code mistakes), unused imports, formatting problems
    • Failing tests
    • Hardcoded secrets (passwords or API keys written in the code), vulnerable dependencies
    • Syntax errors, type errors
  2. Messy commit history

    • Wrong message formats (fix stuff → fix: resolve login timeout)
    • Missing issue numbers (a hook can require feat: add dashboard (#123))
    • Direct commits to protected branches
  3. Wasted CI/CD minutes

    • Problems are caught on your computer, so CI never runs on broken code
    • Feedback in seconds, not minutes
  4. Different rules for each person

    • The same checks run for everyone, automatically
    • Nobody can say “it works on my machine”
    • The rules are applied, and nobody has to remind people

The hooks we really use:

Hook When It Runs What It Checks Skip It?
pre-commit Before commit is saved Linting, formatting, tests git commit --no-verify
commit-msg After commit message written Message format, length git commit --no-verify
pre-push Before pushing to remote Full test suite, build git push --no-verify

Tip: You can skip hooks with --no-verify. Do it only when you know what you are doing. One example: you fix a typo in the docs and do not want to run the full test suite.

Pre-commit Hook#

This hook checks code quality before each commit:

bash
#!/bin/bash
# .git/hooks/pre-commit

echo "Running pre-commit checks..."

# 1. Lint code
npm run lint
if [ $? -ne 0 ]; then
    echo "❌ Linting failed. Please fix errors before committing."
    exit 1
fi

# 2. Run tests
npm test
if [ $? -ne 0 ]; then
    echo "❌ Tests failed. Please fix failing tests before committing."
    exit 1
fi

# 3. Check commit message format (if using commitlint)
npm run commitlint --edit $1
if [ $? -ne 0 ]; then
    echo "❌ Commit message doesn't follow convention."
    exit 1
fi

echo "✅ Pre-commit checks passed!"
exit 0

Commit Message Hook#

This hook checks the format of the commit message:

bash
#!/bin/bash
# .git/hooks/commit-msg

commit_msg=$(cat "$1")

# Check format: <type>(<scope>): <subject>
if ! echo "$commit_msg" | grep -qE "^(feat|fix|docs|style|refactor|perf|test|chore|ci|build)(\(.+\))?: .{1,50}"; then
    echo "❌ Invalid commit message format!"
    echo ""
    echo "Format: <type>(<scope>): <subject>"
    echo ""
    echo "Types: feat, fix, docs, style, refactor, perf, test, chore, ci, build"
    echo ""
    echo "Example: feat(auth): add JWT authentication"
    exit 1
fi

echo "✅ Commit message format is valid!"
exit 0

Using Husky for Git Hooks#

Hooks that you write by hand in .git/hooks/ work, but you cannot share them with the team. Husky fixes that. It is a tool that keeps the hooks in a folder that Git tracks.

bash
# Install husky
npm install --save-dev husky

# Initialize husky
npx husky install

# Add pre-commit hook
npx husky add .husky/pre-commit "npm test"

# Add commit-msg hook
npx husky add .husky/commit-msg "npx commitlint --edit $1"

Why Husky?

  • Shared - Git does not track .git/hooks/, but it tracks .husky/
  • Automatic - New team members get the hooks through npm install
  • Cross-platform - Works on Windows, Mac, and Linux
  • Simple - You only add scripts. You do not need to be good at bash

Integrating Hooks with CI/CD#

Hooks catch problems locally, on your computer. This is fast. CI/CD is the automatic pipeline on the server. It catches what the hooks missed, as a second check. Use both.

The plan:

  1. Pre-commit hook → Quick checks (linting, fast unit tests)
  2. Pre-push hook → Slower checks (full test suite)
  3. CI/CD pipeline → Everything + deployment

Example GitLab CI/CD pipeline:

yaml
# .gitlab-ci.yml

stages:
  - lint
  - test
  - build
  - deploy

# Run on all branches
lint:
  stage: lint
  script:
    - npm run lint
  only:
    - branches

# Run on all branches
test:
  stage: test
  script:
    - npm test
  only:
    - branches

# Build on all branches
build:
  stage: build
  script:
    - npm run build
  artifacts:
    paths:
      - dist/
  only:
    - branches

# Deploy develop → dev environment
deploy_dev:
  stage: deploy
  script:
    - npm run deploy:dev
  environment:
    name: development
    url: https://dev.example.com
  only:
    - develop

# Deploy staging → staging environment
deploy_staging:
  stage: deploy
  script:
    - npm run deploy:staging
  environment:
    name: staging
    url: https://staging.example.com
  only:
    - staging

# Deploy main → production (manual)
deploy_production:
  stage: deploy
  script:
    - npm run deploy:prod
  environment:
    name: production
    url: https://example.com
  only:
    - main
  when: manual

The workflow:

  1. You run git commit. Before Git saves the commit, the hooks run on your computer.
  2. pre-commit runs lint and tests. It finds a lint error in 5 seconds and stops the commit.
  3. You fix the error and commit again. pre-commit passes, and commit-msg accepts the message format.
  4. You run git push. pre-push runs the full test suite before the code leaves your computer.
  5. The remote gets clean code. The CI/CD pipeline runs every check again and then deploys.
5 / 5
  1. Developer makes changes
  2. Pre-commit hook catches lint errors in 5 seconds
  3. Fix, commit again
  4. Pre-push hook catches failing tests in 30 seconds
  5. Push to remote
  6. CI/CD pipeline runs all checks + deployment

Common Hook Patterns#

1. Prevent Commits to Protected Branches#

Block direct commits to main:

bash
#!/bin/bash
# .git/hooks/pre-commit

branch=$(git symbolic-ref HEAD | sed -e 's,.*/\(.*\),\1,')

if [ "$branch" = "main" ] || [ "$branch" = "master" ]; then
    echo "❌ Direct commits to $branch are not allowed!"
    echo "Create a feature branch instead:"
    echo "  git checkout -b feature/my-feature"
    exit 1
fi

2. Check for Hardcoded Secrets#

Catch API keys and passwords before the commit:

bash
#!/bin/bash
# .git/hooks/pre-commit

# Check for common secret patterns
if git diff --cached | grep -qE '(api_key|API_KEY|password|PASSWORD|secret|SECRET)\s*='; then
    echo "❌ Possible hardcoded secret detected!"
    echo "Use environment variables instead."
    exit 1
fi

3. Auto-Format Code Before Commit#

Run Prettier on staged files (the files you added with git add):

bash
#!/bin/bash
# .git/hooks/pre-commit

# Format staged files
npx prettier --write $(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(js|jsx|ts|tsx|css|md)$')

# Re-stage formatted files
git add $(git diff --cached --name-only --diff-filter=ACM | grep -E '\.(js|jsx|ts|tsx|css|md)$')

4. Require Issue Number in Commit Message#

Make every commit message name an issue:

bash
#!/bin/bash
# .git/hooks/commit-msg

commit_msg=$(cat "$1")

# Check for issue number (#123)
if ! echo "$commit_msg" | grep -qE '\(#[0-9]+\)'; then
    echo "❌ Commit message must reference an issue number!"
    echo "Example: feat: add user login (#123)"
    exit 1
fi

Troubleshooting Hooks#

Hook Not Running#

Problem: The hook exists but does not run.

Solutions:

  1. Make it executable: chmod +x .git/hooks/pre-commit
  2. Check the shebang line: #!/bin/bash must be the first line
  3. Check the name: pre-commit not pre-commit.sh

Hook Runs But Always Fails#

Problem: The script has errors.

How to debug:

bash
# Run hook manually to see errors
bash .git/hooks/pre-commit

# Add debug output
echo "Debug: Current directory is $(pwd)"
echo "Debug: Git status:"
git status

Need to Skip Hook Temporarily#

Solution:

bash
# Skip pre-commit and commit-msg hooks
git commit --no-verify -m "fix: emergency hotfix"

# Skip pre-push hook
git push --no-verify

Use --no-verify only when you really must. It skips your safety checks.

Hooks Work Locally But Not for Team#

Problem: Git does not track .git/hooks/.

Solution: Use Husky (see Using Husky above). It stores hooks in .husky/, and Git DOES track that folder.

Conclusion#

Git hooks are your first check. Set them up once, and stop debugging CI failures.

Quick setup checklist:

  • Install Husky: npm install --save-dev husky
  • Initialize hooks: npx husky install
  • Add pre-commit linting: npx husky add .husky/pre-commit "npm run lint"
  • Add the commit-msg check: npx husky add .husky/commit-msg "npx commitlint --edit $1"
  • Add auto-install: "prepare": "husky install" in package.json
  • Test: make a commit and check that the hooks run
  • Commit .husky/ to share with the team

Catch mistakes on your computer before they reach review or break CI.

Hands-On Implementation Guide#

Do you want to see this in a real project? The practical guide sets up Husky, lint-staged, and commitlint in a real Astro blog, step by step:

Implementing Git Hooks with Husky: A Real-World Example →

It covers:

  • Step-by-step Husky installation with terminal output
  • Commitlint config for conventional commits
  • Lint-staged for faster pre-commit checks (6-10x faster)
  • GitLab CI/CD integration
  • Real troubleshooting from problems we had
  • Time saved, before and after

This is what we run on blog.stack101. It is well tested and ready for production.

Related reading: