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

如何在GitHub合并PR后准确获取feature1分支的所有Commit Hash

问题分析

你的Workflow存在两个核心问题:

  • 触发事件为push: branches: [stage],但push事件中不存在github.event.pull_request对象,导致pr_number和ref的取值全部失效,既无法正确checkout到feature分支,也无法通过gh pr view获取PR提交。
  • 即使能拿到PR号,合并完成后PR状态变为closed,部分场景下gh pr view的返回结果可能不准确。
修正方案

推荐使用pull_request_closed事件(PR合并时会触发该事件,且merged: true),直接从PR事件中获取分支信息和提交记录,这是最可靠的方式:

name: Stage Deployment Workflow

on:
  pull_request:
    branches: [stage]
    types: [closed]

jobs:
  ci:
    runs-on: ubuntu-latest
    # 仅当PR被合并时执行
    if: github.event.pull_request.merged == true
    steps:
      - name: Checkout 代码
        uses: actions/checkout@v4
        with:
          # 拉取完整提交历史,确保能获取所有分支提交
          fetch-depth: 0
          # 切换到PR的源分支(即feature1)
          ref: ${{ github.event.pull_request.head.ref }}

      - name: 获取feature分支所有提交Hash
        id: list-commits
        run: |
          # 获取当前分支从与stage分支共同祖先到HEAD的所有提交Hash
          # 若要获取分支所有提交,可直接用 git log --format="%H"
          commits=$(git log --format="%H" origin/stage..HEAD)
          echo "Feature分支提交Hash列表:"
          echo "$commits"
          echo "$commits" > commit-hashes.txt

      - name: 保存提交记录到产物
        uses: actions/upload-artifact@v4
        with:
          name: commit-hashes
          path: commit-hashes.txt

如果必须基于push事件实现(比如合并后有其他push场景需要触发),可以通过合并提交的父节点来获取差异提交:

name: Stage Deployment Workflow

on:
  push:
    branches: [stage]

jobs:
  ci:
    runs-on: ubuntu-latest
    # 仅当push是合并提交时执行(合并提交有2个父节点)
    if: github.event.commits[0].parents | length == 2
    steps:
      - name: Checkout 代码
        uses: actions/checkout@v4
        with:
          fetch-depth: 0

      - name: 获取合并提交对应的feature分支提交Hash
        id: list-commits
        run: |
          # 合并提交的第二个父节点是feature分支的HEAD
          feature_head=${{ github.event.commits[0].parents[1].sha }}
          # 获取stage分支合并前的最后一个提交
          stage_merge_base=${{ github.event.commits[0].parents[0].sha }}
          # 列出两个节点之间的所有提交(即feature分支新增的提交)
          commits=$(git log --format="%H" $stage_merge_base..$feature_head)
          echo "Feature分支提交Hash列表:"
          echo "$commits"
          echo "$commits" > commit-hashes.txt

      - name: 保存提交记录到产物
        uses: actions/upload-artifact@v4
        with:
          name: commit-hashes
          path: commit-hashes.txt
关键说明
  • 使用fetch-depth: 0拉取完整仓库历史,避免因为浅克隆导致无法获取分支间的提交差异。
  • 第一种方案更直接,因为PR合并时能直接拿到源分支信息,无需解析合并提交;第二种方案适用于必须基于push事件的场景,但仅能获取合并到stage的那批提交,而非feature分支的全部提交(如果feature分支后续还有其他提交但未合并的话)。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.20 07:32:05