my-notes

git_hooks

1 min read

git hooks

Automate actions at Git events.


πŸ“ Hook Location

Hooks are in .git/hooks/

ls .git/hooks/

Lists available hook samples.


πŸ“Š Hook Types

graph TD
    A[Client Hooks] --> B[pre-commit]
    A --> C[commit-msg]
    A --> D[pre-push]
    E[Server Hooks] --> F[pre-receive]
    E --> G[post-receive]

πŸ”§ Create Hook

Make Hook File

touch .git/hooks/pre-commit

Creates hook file.


Make Executable

chmod +x .git/hooks/pre-commit

Makes hook executable (required).


πŸ“‹ Common Client Hooks

pre-commit

Runs before commit is created.

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

npm test

Exit non-zero to cancel commit.


commit-msg

Validates commit message.

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

message=$(cat "$1")
if ! [[ "$message" =~ ^(feat|fix|docs): ]]; then
    echo "Error: Message must start with feat:, fix:, or docs:"
    exit 1
fi

Enforces commit message format.


pre-push

Runs before push.

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

npm test

Cancel push if tests fail.


post-checkout

Runs after checkout.

#!/bin/bash
# .git/hooks/post-checkout

npm install

Install dependencies after checkout.


πŸ“¦ Sharing Hooks

Create Hooks Directory

mkdir .githooks

Create hooks in version control.


Configure Git to Use

git config core.hooksPath .githooks

Points Git to shared hooks.


πŸ› οΈ Hook Management Tools

Install Husky

npm install husky --save-dev

Popular hook manager for Node.js projects.


Initialize Husky

npx husky install

Sets up Husky.


Add Husky Pre-commit

npx husky add .husky/pre-commit "npm test"

Adds pre-commit hook.


Install pre-commit (Python)

pip install pre-commit

Python-based hook manager.


Run pre-commit Install

pre-commit install

Installs hooks from config.


πŸ“‹ Example .pre-commit-config.yaml

repos:
  - repo: https://github.com/pre-commit/pre-commit-hooks
    rev: v4.4.0
    hooks:
      - id: trailing-whitespace
      - id: end-of-file-fixer

Configuration for pre-commit.


⏭️ Skip Hooks

Skip Pre-commit

git commit --no-verify -m "Message"

Skips pre-commit and commit-msg hooks.


Skip Pre-push

git push --no-verify

Skips pre-push hooks.


πŸ’‘ Tips

Debug Hooks

Add set -x at top of script for debugging.

Keep Hooks Fast

Slow hooks annoy developers. Use caching.



#git #hooks #automation #advanced

Built with mdgarden