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

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


当前回答

下面是一个代码片段,它是一个基于$GITHUB_REF的环境变量,如果不存在,则默认为dev。

根据您的需求调整sed命令。

export GIT_BRANCH=$(echo ${GITHUB_REF:-dev} | sed s/.*\\///g)

其他回答

为了获得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

${{ github.ref_name }}

至少对推送来说还行。参见ref_name了解更多细节。它说:

触发工作流运行的分支或标记名称。

我只是在GitHub Actions中使用bash脚本做了一个简单的测试:

#!/bin/bash

echo Reserved for REPO_NAME=${GITHUB_REPOSITORY##*/}
echo GITHUB_REF=${GITHUB_REF}
echo EXTRACT_GITHUB_REF=${GITHUB_REF##*/}
echo EXTRACT_GITHUB_REF_HEADS=$(echo ${GITHUB_REF#refs/heads/})

cd $REPO_NAME
git checkout ${GITHUB_REF##*/}
git checkout $(echo ${GITHUB_REF#refs/heads/})

以下是输出的截图:

因此${GITHUB_REF##*/}和$(echo ${GITHUB_REF#refs/heads/})都是正确的

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

- 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'将用_替换分支名称中的/

下面是一个适用于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