我正在用Github动作构建Docker图像,并想用分支名称标记图像。

我找到了GITHUB_REF变量,但它导致了refs/heads/feature-branch-1,我只需要feature-branch-1。


当前回答

对于那些刚刚找到这个线程,你现在可以使用GITHUB_REF_NAME例如${{github。ref_name}}。https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables

因此,如果你触发的操作工作流分支是main,这个变量将被设置为main。例如,如果你有多个带有发行版和主要分支的回购,这就很有用。

其他回答

为了获得delete事件上的ref名称,我最终使用了sed。

on:
  delete:
...
steps:
  - name: Do something
    shell: bash
    run: |
      refname=$(sed -e s:refs/heads/::g -e s:/:-:g <<< ${{ github.event.ref }})

剪掉指针/头/并将斜杠转换为破折号,例如。引用/heads/feature/somefeature到feature-somefeature

要将其设置为环境变量,我使用以下语法:

- name: Extract branch name
  shell: bash
  run: echo "::set-env name=BRANCH_NAME::$(echo ${GITHUB_REF#refs/heads/} | sed 's/\//_/g')"
- name: Test
  run: echo "${BRANCH_NAME}"

我发现这个语法在这里:Github动作-启动worflows#如何定义环境变量?# 68

Rmq: sed 's/\//_/g'将用_替换分支名称中的/

同时处理pull_request和push事件的解决方案。由于set-env已弃用,因此实现了保存获得的分支名称以供后续步骤使用的变通方法。 不需要第三方操作。

name: CI
on: [ pull_request, push ]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: "Get branch name and save to env"
        env:
          IS_PR: ${{ github.EVENT_NAME == 'pull_request' }}
        run: |
          if ${IS_PR}; then
            BRANCH_NAME="${GITHUB_HEAD_REF}"
          else
            BRANCH_NAME="${GITHUB_REF##*/}"
          fi
          echo "BRANCH_NAME=${BRANCH_NAME}" >> $GITHUB_ENV

      - name: "Another step uses branch name"
        run: echo "Branch name is ${{ env.BRANCH_NAME }}"

GitHub动作中的运行时变量

下面是一个适用于push和pull_request事件的完整工作流

name: whichBranch
on: [pull_request, push]

jobs:
  which_branch:
    runs-on: ubuntu-latest
    steps:
      - name: Extract branch name on push
        if: github.event_name != 'pull_request'
        shell: bash
        run: echo "::set-env name=BRANCH_NAME::$(echo ${GITHUB_REF#refs/heads/})"
        id: extract_branch

      - name: Extract branch name on pull request
        if: github.event_name == 'pull_request'
        run: echo "::set-env name=BRANCH_NAME::$(echo ${GITHUB_HEAD_REF})"

      - name: Print branch name
        run: echo 'The branch name is' $BRANCH_NAME

博士TL;

这适用于你可以在on下指定的每个触发器(例如push或pull_request):

env:
 BRANCH_NAME: ${{ github.head_ref || github.ref_name }} 

解释

诀窍在于github。head_ref仅在工作流由pull_request触发时设置,并且它包含PR. github的源分支的值。Ref_name只在工作流不是由pull_request触发的情况下使用,而且它也只包含分支名称。

GitHub的文档

来自GitHub官方文档的详细解释:

github。ref_name string触发工作流运行的分支或标记的短引用名称。该值与GitHub上显示的分支或标记名称匹配。例如,feature-branch-1。

github。工作流运行中pull请求的head_ref或源分支。此属性仅在触发工作流运行的事件为pull_request或pull_request_target时可用。