如何在RepoA提交时自动执行分支校验脚本并拦截不合规提交
Let's break down how to fix both of your issues so your branch validation script works reliably on every commit:
The reason your pre-commit field in package.json isn't triggering consistently is that most modern Node.js projects rely on a hook manager like husky to wire up Git hooks—just adding the field alone won't work unless you have a dedicated tool to bridge the gap between npm scripts and Git's native hook system. Here's the step-by-step fix:
- Install husky as a development dependency:
npm install husky --save-dev - Enable Git hook support in your project:
npx husky install - Add a
preparescript to yourpackage.jsonso anyone cloning your repo will automatically enable hooks when they install dependencies:{ "scripts": { "prepare": "husky install", "test:script": "./branchname.sh", // ... your other existing scripts } } - Create a pre-commit hook that runs your validation script:
This generates anpx husky add .husky/pre-commit "npm run test:script".husky/pre-commitfile that guarantees your script runs every time you executegit commit.
If you previously tried using the standalone pre-commit npm package, uninstall it to avoid conflicts—husky is the more widely supported and maintained tool for this use case now.
Git hooks automatically abort the commit process if the hooked script returns a non-zero exit code. All you need to do is add exit 1 to the else branch of your script. Here's the updated, fixed version of your branchname.sh:
#!/bin/bash currentBranch=$(git rev-parse --abbrev-ref HEAD) if [[ $currentBranch = *"my-"* ]]; then echo "Branch name is valid (contains 'my-')" else echo "Hold on there! You need to rename your branch before you commit!" exit 1 # This non-zero exit code tells Git to stop the commit fi
Also, double-check that your script has executable permissions (run this if it doesn't):
chmod +x branchname.sh
Now, whenever someone tries to commit from a branch that doesn't include "my-", the script will print the warning and immediately halt the commit process.
内容的提问来源于stack exchange,提问作者The Walrus

