git pre-commit hook manager

https://pre-commit.com/

 

pre-commit — Usage in Git

pre-commit is a multi-language Git hooks manager that ensures code quality by automatically running checks before a commit (or other Git hook events). It manages installation, updating, and execution of hooks written in any language.


1. What pre-commit Does

  • Runs automated checks on every commit (e.g., formatting, linting, whitespace cleanup).
  • Installs and manages hook environments (no need for system-level dependencies).
  • Supports many languages (Python, Node, Ruby, Go, Rust, Docker, etc.).

2. How to Use pre-commit in Your Git Repo

Step 1 — Install

 
 
 
Shell
 
 
pip install pre-commit
 
 

Step 2 — Add .pre-commit-config.yaml

A minimal example:

 
 
 
YAML
 
 
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v2.3.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
 
 

Step 3 — Install Git Hook Scripts

 
 
 
Shell
 
 
pre-commit install
 
 

Now hooks run automatically on every git commit.

Step 4 — Run on all files (optional)

 
 
 
Shell
 
 
pre-commit run --all-files
 
 

3. Running Hooks Manually

Run all hooks:

 
 
 
Shell
 
 
pre-commit run --all-files
 
 

Run a specific hook:

 
 
 
Shell
 
 
pre-commit run <hook_id>
 
 

Run only on changed files in a ref range:

 
 
 
Shell
 
 
pre-commit run --from-ref HEAD~3 --to-ref HEAD
 
 

hook versions:

 
 
 
Shell
 
 
pre-commit autoupdate
 
 

5. Creating Custom Hooks

Hooks live in a repository with a .pre-commit-hooks.yaml file describing:

  • id
  • name
  • entry
  • language
  • file filters

Example:

 
 
 
YAML
 
 
- id: trailing-whitespace
name: Trim Trailing Whitespace
entry: trailing-whitespace-fixer
language: python
 
 

6. Useful Features

  • Local repo hooks (no need to publish a repo).
  • Confining hooks to specific Git stages (pre-push, commit-msg, etc.).
  • Skipping hooks via environment variable:
     
     
     
    Shell
     
     
    SKIP=flake8 git commit
     
     
  • meta hooks for validating pre-commit configurations.

7. CI Integration

Common CI usage:

 
 
 
Shell
 
 
pre-commit run --all-files
``
 
 

Cache directories to speed up CI builds (depends on CI platform).


8. Language Support

pre-commit can automatically install environments for:

  • Python
  • Node
  • Go
  • Ruby
  • Rust
  • Docker
  • Julia
  • R
  • Lua
  • Swift …and many others.

If you want, I can also produce: ✅ a shorter “executive summary”
✅ a cheat sheet
✅ a recommended .pre-commit-config.yaml for your R&D engineering projects
Just let me know!

posted @ 2026-01-19 11:06  iTech  阅读(3)  评论(0)    收藏  举报