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

GitHub Actions 创建/更新Git Tag 重复引用报错解决方案问询

你遇到的报错是因为github.git.createRef接口仅支持创建不存在的Git引用,当对应PR号的标签已经生成过,再次调用就会触发引用已存在的报错。

GitHub 提供了git.updateRef接口用于更新已有引用,你可以调整脚本逻辑,先尝试创建标签,若判定为标签已存在的错误,就调用更新接口强制移动标签指向当前最新提交SHA,修改后的配置如下:

env:
  PR_NUMBER: ${{ github.event.number }}

steps:
- name: Create or update Git tag for PR
  uses: actions/github-script@v4
  with:
    script: |
      const tagName = `0.0.0-pr${process.env.PR_NUMBER}`
      const fullRef = `refs/tags/${tagName}`
      try {
        // 首次提交时直接创建标签
        await github.git.createRef({
          owner: context.repo.owner,
          repo: context.repo.repo,
          ref: fullRef,
          sha: context.sha
        })
      } catch (err) {
        // 捕获标签已存在的错误,更新标签指向最新提交
        if (err.status === 422 && err.message.includes("Reference already exists")) {
          await github.git.updateRef({
            owner: context.repo.owner,
            repo: context.repo.repo,
            // updateRef 接口的ref参数不需要前缀refs/
            ref: `tags/${tagName}`,
            sha: context.sha,
            // 强制移动标签到新的提交哈希
            force: true
          })
          return
        }
        // 其他类型错误正常抛出
        throw err
      }

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 23:12:03