You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在RepoA提交时自动执行分支校验脚本并拦截不合规提交

Let's break down how to fix both of your issues so your branch validation script works reliably on every commit:

1. Ensuring the Script Runs Automatically 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:

  1. Install husky as a development dependency:
    npm install husky --save-dev
    
  2. Enable Git hook support in your project:
    npx husky install
    
  3. Add a prepare script to your package.json so anyone cloning your repo will automatically enable hooks when they install dependencies:
    {
      "scripts": {
        "prepare": "husky install",
        "test:script": "./branchname.sh",
        // ... your other existing scripts
      }
    }
    
  4. Create a pre-commit hook that runs your validation script:
    npx husky add .husky/pre-commit "npm run test:script"
    
    This generates a .husky/pre-commit file that guarantees your script runs every time you execute git 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.

2. Aborting the Commit When the Branch Name Is Invalid

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.28 04:16:14