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

pre-commit钩子失败后COMMIT_EDITMSG未更新致提交重复失败

问题分析

你遇到的核心问题有两个:

  • 钩子脚本硬编码了提交信息文件路径,没有使用Git传递的临时文件参数,导致读取到的是上次失败提交遗留的旧内容
  • pre-commit配置里的钩子阶段设置错误,没有绑定到正确的commit-msg阶段,触发时机不对
修复方案

1. 修改commit-msg.py脚本

将硬编码的文件路径改为读取命令行传入的参数,同时优化正则匹配逻辑(允许提交信息开头有空格):

import sys
import re

# 读取Git传递的提交信息临时文件路径(第一个命令行参数)
if len(sys.argv) < 2:
    print("Error: No commit message file provided")
    sys.exit(1)

msg_temp_file = sys.argv[1]

with open(msg_temp_file, "r", encoding="utf-8") as f_msg:
    lines = f_msg.readlines()

# 过滤注释行,提取有效提交信息
commit_lines = [line.strip() for line in lines if not line.strip().startswith("#")]
# 处理空提交信息的情况
if not commit_lines:
    print('-------------------------------------------------------')
    print('Commit message cannot be empty!')
    print('-------------------------------------------------------')
    sys.exit(1)

commit_message = commit_lines[0]
# 允许提交信息开头有空格,匹配[PRO-XXXX]格式
if not re.match(r"^\s*\[PRO-\d+\]", commit_message):
    print('-------------------------------------------------------')
    print('Commit message does not reference a JIRA id!')
    print('Required format: [PRO-XXXX] your commit message')
    print('-------------------------------------------------------')
    sys.exit(1)

2. 修改.pre-commit-config.yaml配置

将钩子的stages改为commit-msg,这是Git专门用于校验提交信息的阶段,同时添加钩子类型声明:

repos:
- repo: local
  hooks:
  - id: commit-msg
    name: Enforce commit strategy
    description: make sure an epic id is correctly mentioned in the commit message
    entry: python ./commit-msg.py
    language: system
    pass_filenames: false
    always_run: true
    verbose: false
    stages: [commit-msg]
    types: [commit-msg]

3. 更新pre-commit钩子配置

在仓库根目录执行以下命令,让修改后的配置生效:

pre-commit install --hook-type commit-msg
测试验证
  1. 暂存文件后提交无JIRA ID的信息,确认被拒绝
  2. 重新提交,输入[PRO-1234] 修复XX功能这类符合格式的信息,确认提交成功

内容的提问来源于stack exchange,提问作者alaeX

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.30 09:43:20