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

在Pull Request触发的GitHub Actions中获取提交信息遇阻求助

获取Pull Request提交消息并校验的正确姿势

问题原因

默认actions/checkout动作只会拉取合并到base分支的单次合并提交,导致你通过github.event.pull_request.head.sha指定的提交SHA在本地仓库中不存在,自然会报fatal: bad object错误;而直接用git log --pretty=%B -n 1拿到的是PR的合并提交消息,不是你需要的PR头部提交的消息。

两种解决方法

方法1:调整Checkout配置,本地Git获取消息

通过修改actions/checkout的参数,直接拉取PR头部的提交分支,并确保拉取足够的历史:

name: PR Commit Message Validation
on: [pull_request]

jobs:
  validate-commit:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout PR head commit
        uses: actions/checkout@v4
        with:
          ref: ${{ github.event.pull_request.head.sha }}
          fetch-depth: 0  # 拉取全量提交历史,确保目标SHA存在

      - name: Extract commit message
        id: extract-msg
        run: |
          COMMIT_MSG=$(git log --format=%B -n 1 ${{ github.event.pull_request.head.sha }})
          echo "commit_msg=$COMMIT_MSG" >> $GITHUB_OUTPUT

      - name: Validate with regex
        run: |
          # 替换成你的目标正则表达式
          REQUIRED_PATTERN="^(feat|fix|docs|style|refactor|test|chore): .+"
          if ! echo "${{ steps.extract-msg.outputs.commit_msg }}" | grep -qE "$REQUIRED_PATTERN"; then
            echo "❌ 提交消息不符合规范,必须以 feat/fix/docs 等前缀开头"
            exit 1
          else
            echo "✅ 提交消息格式符合要求"
          fi

关键参数说明:

  • ref: ${{ github.event.pull_request.head.sha }}:直接切换到PR头部的具体提交,而非合并后的分支
  • fetch-depth: 0:拉取仓库所有提交历史,避免因拉取深度不足找不到目标SHA

方法2:用GitHub API直接获取(更轻量)

如果不需要操作仓库代码,直接通过GitHub API获取提交消息更高效,无需调整checkout配置:

name: PR Commit Message Validation
on: [pull_request]

jobs:
  validate-commit:
    runs-on: ubuntu-latest
    steps:
      - name: Extract commit message via GitHub API
        id: extract-msg
        run: |
          # 用gh cli调用API,自动处理认证
          COMMIT_MSG=$(gh api repos/${{ github.repository }}/commits/${{ github.event.pull_request.head.sha }} --jq '.commit.message')
          echo "commit_msg=$COMMIT_MSG" >> $GITHUB_OUTPUT
        env:
          GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}  # Actions自动提供的令牌,无需额外配置

      - name: Validate with regex
        run: |
          REQUIRED_PATTERN="^(feat|fix|docs|style|refactor|test|chore): .+"
          if ! echo "${{ steps.extract-msg.outputs.commit_msg }}" | grep -qE "$REQUIRED_PATTERN"; then
            echo "❌ 提交消息不符合规范,必须以 feat/fix/docs 等前缀开头"
            exit 1
          else
            echo "✅ 提交消息格式符合要求"
          fi

这种方法不需要拉取代码仓库,直接通过API获取提交信息,速度更快,适合仅做消息校验的场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 21:32:54