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

如何在GitHub Actions中用Git命令检测最后一次提交是否为还原提交?

检测GitHub Actions中的Git还原提交方案

下面是几种不依赖提交消息、可在GitHub Actions工作流中使用的还原提交检测方案:

方案1:基于反向Diff的精准检测(完全不依赖提交消息)

这个方法通过对比当前提交与父提交的变更,和历史提交的变更是否完全反向,来判断是否为还原提交,适合自定义提交消息的场景:

steps:
  - name: Checkout
    uses: actions/checkout@v3
    with:
      fetch-depth: 0
  - name: Detect revert commit
    id: detect-revert
    run: |
      # 获取当前提交与父提交的diff
      current_diff=$(git diff HEAD^ HEAD)
      is_revert=0
      # 遍历最近100个提交(可根据需求调整范围)
      git log --format="%H" HEAD~1..HEAD~100 | while read commit; do
        # 生成目标提交diff的反向版本
        reversed_target_diff=$(git diff $commit^ $commit | git diff --reverse)
        # 对比两个diff是否完全一致
        if diff -q <(echo "$current_diff") <(echo "$reversed_target_diff") >/dev/null; then
          echo "Found revert commit, targeting: $commit"
          is_revert=1
          break
        fi
      done
      # 设置输出变量供后续步骤调用
      echo "is_revert=$is_revert" >> $GITHUB_OUTPUT
  # 示例:仅当检测到还原提交时执行的步骤
  - name: Execute revert-specific steps
    if: steps.detect-revert.outputs.is_revert == '1'
    run: |
      echo "Running actions for revert commit..."

方案2:基于Git默认还原标记的快速检测(兼容部分自定义消息)

如果自定义提交消息时保留了Git自动添加的This reverts commit <哈希>.行,可以用这个更高效的方法:

steps:
  - name: Checkout
    uses: actions/checkout@v3
    with:
      fetch-depth: 0
  - name: Detect revert via commit message marker
    id: detect-revert
    run: |
      if git log --format="%B" -n 1 HEAD | grep -q "This reverts commit"; then
        echo "is_revert=1" >> $GITHUB_OUTPUT
        # 提取被还原的提交哈希(可选)
        reverted_hash=$(git log --format="%B" -n 1 HEAD | grep "This reverts commit" | awk '{print $4}' | sed 's/\.$//')
        echo "reverted_commit=$reverted_hash" >> $GITHUB_OUTPUT
      else
        echo "is_revert=0" >> $GITHUB_OUTPUT
      fi

方案3:检测还原合并提交(针对合并操作的还原)

还原合并提交(执行git revert -m 1 <合并提交>生成)本身是多父提交,可以通过父提交数量结合消息判断:

steps:
  - name: Checkout
    uses: actions/checkout@v3
    with:
      fetch-depth: 0
  - name: Detect revert merge commit
    id: detect-revert-merge
    run: |
      # 获取当前提交的父提交数量
      parent_count=$(git log --format="%P" -n 1 HEAD | wc -w)
      if [ $parent_count -eq 2 ]; then
        # 进一步验证是否为还原合并
        if git log --format="%B" -n 1 HEAD | grep -q "Revert \"Merge"; then
          echo "is_revert_merge=1" >> $GITHUB_OUTPUT
        else
          echo "is_revert_merge=0" >> $GITHUB_OUTPUT
        fi
      else
        echo "is_revert_merge=0" >> $GITHUB_OUTPUT
      fi

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 20:13:21