如何在不执行提交操作的情况下手动运行Git pre-commit钩子?
Got it, you want to validate your code against the pre-commit hook without actually going through a commit? No problem—here's how to do it easily, depending on how your hooks are set up:
Native Git Pre-Commit Hook
If you're using a custom or default pre-commit hook script directly in your repo:
- First, make sure the hook has executable permissions (Git doesn't set this automatically for template hooks). Run this in your project root:
chmod +x .git/hooks/pre-commit - Then, execute the hook script directly to trigger the checks:
.git/hooks/pre-commit
This will run exactly the same checks that would fire when you try to commit, but it won't create any commit or modify your repo state. If the checks fail, the script will exit with a non-zero code (just like during a real commit); if they pass, it'll exit cleanly.
Using the pre-commit Framework
If you're using the popular pre-commit tool to manage your hooks (super common for Python projects and beyond):
- To check all files in your working tree (not just staged ones), run:
pre-commit run --all-files - If you only want to check files that are currently staged (mimicking the behavior of a real commit), just run:
pre-commit run
This tool will handle executing all configured hooks and report any failures clearly, no commit required.
Pro Tip
Keep in mind: Native hooks might only check staged files by default (depending on how the script is written). If you want to validate all modified files without staging them, using the pre-commit tool with --all-files is usually the easiest way.
内容的提问来源于stack exchange,提问作者callum

