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

GitHub Actions Checkout步骤如何自动检出staging.开头的分支?

解决GitHub Actions检出staging.开头分支的方案

GitHub Actions的actions/checkout本身不支持用通配符指定分支,所以得先动态查询符合条件的分支,再传入checkout步骤。下面是两种可行的实现方式:

方案一:用Git命令获取最新的staging分支

通过Git命令筛选出所有staging.开头的远程分支,再按版本号排序取最新的那个,存入环境变量后用于checkout。

完整的Workflow示例:

jobs:
  deploy-staging:
    runs-on: ubuntu-latest
    steps:
      # 先拉取所有远程分支,确保能查到所有staging分支
      - name: Fetch all remote branches
        run: git fetch --all --prune

      # 查询并输出最新的staging分支
      - name: Get latest staging branch
        id: get-staging
        run: |
          # 过滤出staging.开头的远程分支,去掉origin/前缀
          STAGING_BRANCHES=$(git branch -r | grep "origin/staging\." | sed 's/origin\///')
          # 如果没有找到对应分支,直接终止流程
          if [ -z "$STAGING_BRANCHES" ]; then
            echo "Error: No staging.* branch found"
            exit 1
          fi
          # 按版本号自然排序,取最后一个(最新版本)
          LATEST_STAGING=$(echo "$STAGING_BRANCHES" | sort -V | tail -n 1)
          echo "branch=$LATEST_STAGING" >> $GITHUB_OUTPUT

      # 检出目标分支
      - name: Checkout latest staging branch
        uses: actions/checkout@v4
        with:
          ref: ${{ steps.get-staging.outputs.branch }}

关键命令说明:

  • git branch -r:列出所有远程分支
  • grep "origin/staging\.":筛选出origin/staging.开头的分支(转义点号避免匹配任意字符)
  • sed 's/origin\///':去掉分支名前的origin/前缀
  • sort -V:按版本号自然排序(比如staging.2.22.23会排在staging.2.22.2后面)
  • tail -n 1:取排序后的最后一个分支(即最新版本)

方案二:触发工作流时自动匹配staging分支

如果你的Workflow是在staging.*分支推送时触发,可以直接用GitHub提供的上下文变量获取当前分支,不需要额外查询:

on:
  push:
    branches:
      - 'staging.*'

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Checkout current staging branch
        uses: actions/checkout@v4
        # 直接用github.event.ref获取触发分支,不需要硬编码
        with:
          ref: ${{ github.event.ref }}

这个方案适合分支推送时自动触发的场景,不需要手动查询分支名。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 16:01:01