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

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


当前回答

现在不建议使用setenv。建议使用环境文件。基于@youjin的回答,同时仍然允许功能/分支(用-替换所有/的出现),我现在使用这个:

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Get branch name (merge)
        if: github.event_name != 'pull_request'
        shell: bash
        run: echo "BRANCH_NAME=$(echo ${GITHUB_REF#refs/heads/} | tr / -)" >> $GITHUB_ENV

      - name: Get branch name (pull request)
        if: github.event_name == 'pull_request'
        shell: bash
        run: echo "BRANCH_NAME=$(echo ${GITHUB_HEAD_REF} | tr / -)" >> $GITHUB_ENV

      - name: Debug
        run: echo ${{ env.BRANCH_NAME }}

其他回答

我添加了一个单独的步骤,用于从$GITHUB_REF提取分支名称,并将其设置为步骤输出

- name: Extract branch name
  shell: bash
  run: echo "##[set-output name=branch;]$(echo ${GITHUB_REF#refs/heads/})"
  id: extract_branch

在那之后,我可以在接下来的步骤中使用它

- name: Push to ECR
  id: ecr
  uses: jwalton/gh-ecr-push@master
  with:
    access-key-id: ${{ secrets.AWS_ACCESS_KEY_ID }}
    secret-access-key: ${{ secrets.AWS_SECRET_ACCESS_KEY }}
    region: us-west-2
    image: eng:${{ steps.extract_branch.outputs.branch }}

我做了一个获取分支名称的操作,而不管是否触发pull_request。https://github.com/EthanSK/git-branch-name-action

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

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

我只是在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/})都是正确的

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