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

如何在GitHub Actions中获取推送事件源分支并区分PR合并与直接推送?

GitHub Actions分支识别需求与解决方案

场景

  • 仓库存在main分支,通过git checkout -b my-branch创建特性分支
  • 需从my-branch向main发起Pull Request(PR)

初始工作流

最初编写的GitHub Actions工作流如下:

name: test

on:
  push:
  pull_request:
    branches: ["_.//"]

jobs:
  test:
    name: test
    runs-on: [ self-hosted, linux, enterprise ]
    steps:
      - name: echo
        runs: |
          echo "?" # 若为来自`my-branch`的PR,需输出`my-branch`;若为直接推送,输出`direct`

需求

实现分支识别逻辑:

  • 当触发源是来自my-branch的PR时,输出my-branch
  • 当触发源是直接推送代码时,输出direct

尝试方案及问题

尝试使用环境变量组合的方式实现,工作流代码如下:

name: test

on:
  push:
  pull_request:
    branches: ["_.//"]

jobs:
  test:
    name: test
    runs-on: [ self-hosted, linux, enterprise ]
    steps:
      - name: echo
        run: |
          echo "branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}"

测试结果:

  • 在my-branch上直接推送时,输出branch=my-branch
  • 将my-branch的PR合并到main后,main分支触发的工作流输出branch=main,不符合需求(期望输出my-branch)

最终解决方案

调整工作流触发规则,最终采用的配置如下:

name: test

on:
  push:
    branches:
      - "**"
      - "!main"
  pull_request:
    branches: 
      - "main"

jobs:
  test:
    name: test
    runs-on: [ self-hosted, linux, enterprise ]
    steps:
      - name: echo
        run: |
          echo "branch=${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}}"

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.07 03:19:50