191

我正在使用 Github Actions 构建 Docker 映像,并希望使用分支名称标记映像。

我找到了GITHUB_REF变量,但结果是refs/heads/feature-branch-1我只需要feature-branch-1.

4

26 回答 26

203

我添加了一个单独的步骤,用于从中提取分支名称$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 }}
于 2019-09-20T21:15:37.570 回答
141

我相信GITHUB_REF是唯一包含分支名称的环境变量。

您可以从该字符串的其余部分中仅提取分支名称,如下所示:

${GITHUB_REF##*/}

例子:

$ GITHUB_REF=refs/heads/feature-branch-1
$ echo ${GITHUB_REF##*/}
feature-branch-1

更新:添加了一个完整的工作流示例。

工作流程

name: CI
on: push
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - name: Git checkout
        uses: actions/checkout@v1
      - name: Branch name
        run: echo running on branch ${GITHUB_REF##*/}
      - name: Build
        run: docker build -t tedmiston/tag-example:${GITHUB_REF##*/} .

来源:https ://github.com/tedmiston/x/blob/master/.github/workflows/workflow.yml

示例输出 - 主分支

Run docker build -t tedmiston/tag-example:${GITHUB_REF##*/} .
  docker build -t tedmiston/tag-example:${GITHUB_REF##*/} .
  shell: /bin/bash -e {0}
Sending build context to Docker daemon  146.9kB

Step 1/1 : FROM alpine
latest: Pulling from library/alpine
9d48c3bd43c5: Pulling fs layer
9d48c3bd43c5: Verifying Checksum
9d48c3bd43c5: Download complete
9d48c3bd43c5: Pull complete
Digest: sha256:72c42ed48c3a2db31b7dafe17d275b634664a708d901ec9fd57b1529280f01fb
Status: Downloaded newer image for alpine:latest
 ---> 961769676411
Successfully built 961769676411
Successfully tagged tedmiston/tag-example:master

日志:https ://github.com/tedmiston/x/commit/cdcc58a908e41d3d90c39ab3bf6fef1ad2c4238a/checks#step:4:16

示例输出 - 非主分支

Run docker build -t tedmiston/tag-example:${GITHUB_REF##*/} .
  docker build -t tedmiston/tag-example:${GITHUB_REF##*/} .
  shell: /bin/bash -e {0}
Sending build context to Docker daemon  144.9kB

Step 1/1 : FROM alpine
latest: Pulling from library/alpine
9d48c3bd43c5: Pulling fs layer
9d48c3bd43c5: Verifying Checksum
9d48c3bd43c5: Download complete
9d48c3bd43c5: Pull complete
Digest: sha256:72c42ed48c3a2db31b7dafe17d275b634664a708d901ec9fd57b1529280f01fb
Status: Downloaded newer image for alpine:latest
 ---> 961769676411
Successfully built 961769676411
Successfully tagged tedmiston/tag-example:branch-name-test

日志:https ://github.com/tedmiston/x/commit/4e8d31259f861aaa2c30375756fc081c3659bddf/checks#step:4:16


有关参数扩展语法的更多信息,请参阅此答案

作为参考,GitHub Actions 的虚拟环境页面列出了执行环境中可用的所有环境变量。

于 2019-09-20T20:28:49.590 回答
109

请注意,如果您在拉取请求触发器上执行 GitHub 操作,那么GITHUB_REF变量将包含类似refs/pull/421/merge这样的内容,如果您尝试使用git push该名称,它很可能会失败。

不过,您可以使用 YAML 中 GitHub 上下文的引用。就像是:${{ github.head_ref }}

https://help.github.com/en/actions/automating-your-workflow-with-github-actions/contexts-and-expression-syntax-for-github-actions#github-context

Github 动作上下文参考

于 2020-01-17T02:54:58.313 回答
37

你可以使用https://github.com/rlespinasse/github-slug-action

# Just add this  => 
- name: Inject slug/short variables
  uses: rlespinasse/github-slug-action@v3.x



# And you get this  => 
- name: Print slug/short variables
  run: |
    echo "Slug variables"
    echo " - ${{ env.GITHUB_REF_SLUG }}"    
    echo " - ${{ env.GITHUB_HEAD_REF_SLUG }}"
    echo " - ${{ env.GITHUB_BASE_REF_SLUG }}"
    echo " - ${{ env.GITHUB_REPOSITORY_SLUG }}"
    # output e.g. : master feat-new-feature v1.0.0 product-1.0.0-rc.2 new-awesome-product
    echo "Slug URL variables"
    echo " - ${{ env.GITHUB_REF_SLUG_URL }}"
    echo " - ${{ env.GITHUB_HEAD_REF_SLUG_URL }}"
    echo " - ${{ env.GITHUB_BASE_REF_SLUG_URL }}"
    echo " - ${{ env.GITHUB_REPOSITORY_SLUG_URL }}"
    # output e.g. : master feat-new-feature v1-0-0 product-1-0-0-rc-2 new-awesome-product
    echo "Short SHA variables"
    echo " - ${{ env.GITHUB_SHA_SHORT }}"
    # output e.g. : ffac537e
于 2019-11-06T13:01:02.693 回答
37

使用setenv现在已弃用。建议使用环境文件。在@youjin 的回答的基础上,在仍然允许feature/ 分支(替换所有出现的/with -)的同时,我现在正在使用这个:

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 }}
于 2020-10-05T14:27:08.393 回答
17

如何在 Github Actions 中获取当前分支?

假设${{ github.ref }}类似于refs/heads/mybranch,您可以使用以下方法提取分支名称:

steps:
  - name: Prints the current branch name
    run: echo "${GITHUB_BRANCH##*/}"
    env:
      GITHUB_BRANCH: ${{ github.ref }}

如果您的分支包含斜杠(例如feature/foo),请使用以下语法:

steps:
  - name: Prints the current branch name
    run: echo "${GITHUB_REF#refs/heads/}"

致谢:@rmunn 评论

或者使用接受的答案中的方法,这里是更短的版本(lint 友好):

steps:
  - name: Get the current branch name
    shell: bash
    run: echo "::set-output name=branch::${GITHUB_REF#refs/heads/}"
    id: myref

然后在其他步骤中参考${{ steps.myref.outputs.branch }}

笔记:

于 2020-06-08T20:37:43.710 回答
16

GitHub Action FranzDiebold/github-env-vars-action公开了几个有用的环境变量,例如当前分支名称及其 slug 值。我完全针对这个用例做了这个动作。

用法

steps:
  - uses: FranzDiebold/github-env-vars-action@v1.2.0
  - name: Print environment variables
    run: |
      echo "GITHUB_REPOSITORY_SLUG=$GITHUB_REPOSITORY_SLUG"
      echo "GITHUB_REPOSITORY_OWNER=$GITHUB_REPOSITORY_OWNER"
      echo "GITHUB_REPOSITORY_OWNER_SLUG=$GITHUB_REPOSITORY_OWNER_SLUG"
      echo "GITHUB_REPOSITORY_NAME=$GITHUB_REPOSITORY_NAME"
      echo "GITHUB_REPOSITORY_NAME_SLUG=$GITHUB_REPOSITORY_NAME_SLUG"
      echo "GITHUB_REF_SLUG=$GITHUB_REF_SLUG"
      echo "GITHUB_REF_NAME=$GITHUB_REF_NAME"
      echo "GITHUB_REF_NAME_SLUG=$GITHUB_REF_NAME_SLUG"
      echo "GITHUB_SHA_SHORT=$GITHUB_SHA_SHORT"

在此处输入图像描述

存储库的演示工作流程文件中还提供了适用于所有操作系统(Linux、macOS 和 Windows)的演示!

于 2020-09-02T05:23:43.373 回答
14

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

- 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 actions - starter worflows#How to define env variable? #68

rmq:是在分支名称sed 's/\//_/g'中替换/_

于 2019-12-22T22:46:20.667 回答
10

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

#!/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/})都是正确的

于 2019-12-11T10:48:32.850 回答
10

这是一个适用于pushpull_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
于 2020-08-13T02:04:13.527 回答
7

更新

GitHub 现在支持GITHUB_REF_NAME,它代表:The branch or tag name that triggered the workflow run.

GitHub 上的文档https://docs.github.com/en/actions/learn-github-actions/environment-variables

于 2021-12-07T18:58:29.547 回答
5
${{ github.ref_name }}

似乎至少适用于推送。

于 2021-11-10T12:55:03.357 回答
4

如果您使用的是 V2,actions/checkout那么您始终可以运行git branch --show-current以获取当前签出的分支的名称。

于 2021-06-01T17:10:51.367 回答
3

现在${{github.ref}}是获取分支名称的正确方法。请记住${{github.ref}}refs/heads/..前缀

于 2021-12-11T15:50:22.863 回答
2

要同时处理pull_request事件(在这种情况下,$GITHUB_REF包含一些无用的东西,例如refs/pull/519/merge),您可以使用这个衬里:

   - name: Set branch name
     run: echo "::set-output name=branch_name::$(echo ${GITHUB_HEAD_REF:-${GITHUB_REF#refs/heads/}})"
于 2021-09-17T08:33:35.163 回答
1

在 GitHub 操作上使用分支名称

使用当前分支名称的便利操作。用法

name: build
on: push

jobs:
  build:
    runs-on: ubuntu-latest
    steps:
    - uses: actions/checkout@v1
    - run: npm ci
    - uses: nelonoel/branch-name@v1
    # Use branch name for whatever purpose
    - run: echo ${BRANCH_NAME}
于 2020-08-10T11:37:51.473 回答
1

对于使用 Windows 映像运行操作的人,需要了解的几个关键点:

  1. 假设 GitHub 操作使用 CMD shell 是不正确的。他们默认使用 PowerShell
  2. 您可以指定使用以下方式的shell:
- run: |
    ...
  shell: cmd
  1. 您可以使用值 'bash' 在 bash shell 的上下文中执行命令。

所以,总而言之,你不需要浪费潜在的时间来试图弄清楚如何以破旧的 cmd 方式做事(就像我做的那样)。

为了获取当前分支的名称,您可以在将 shell 设置为“bash”时使用流行的解决方案,或者使用例如以下简单方法在默认 PowerShell shell 中设置变量:

$branchName = $Env:GITHUB_REF -replace "refs/heads/", ""
于 2021-02-22T15:01:42.567 回答
1

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

于 2021-04-17T18:48:49.303 回答
1

处理pull_requestpush事件的解决方案。实施解决方法以保存获得的分支名称以进行进一步的步骤,因为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 Actions 中的运行时变量

于 2022-01-31T20:11:43.960 回答
1

只需使用:

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

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

于 2022-02-17T13:17:56.463 回答
0
if: github.ref == 'refs/heads/integration' && github.event_name == 'push' 

您可以使用上述命令并替换您想要运行的任何分支或事件。

于 2020-04-02T15:06:15.220 回答
0

在 Windows 上运行?Windows 默认命令是 PowerShell 终端。

  - name: SET CURRENT_BRANCH
    run: |
      $branchName = "${{github.ref}}".Split("/")["${{github.ref}}".Split("/").Length -1]
      echo "::set-env name=CURRENT_BRANCH::$(echo $branchName)"
于 2020-07-15T21:37:42.797 回答
0

这是一个基于 设置的环境变量的片段,如果不存在则$GITHUB_REF默认为。dev

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

export GIT_BRANCH=$(echo ${GITHUB_REF:-dev} | sed s/.*\\///g)
于 2021-06-09T04:18:37.413 回答
0

通常,我总是有一个用nodejsor编写的脚本python,它从workflow.yaml. 该脚本通常负责获取正确的分支引用等工作。

我有一个像下面这样的函数,在一个prepare-deployment.js脚本中-

const VALID_REF_PREFIX = 'refs/heads/';
...

function getBranchRef(isProd = false) {
  let branchRef = 'origin/master';

  if (isProd) {
    return branchRef;
  }
  /**
   * When the workflow is invoked from manual flow, the branch name
   * is in GITHUB_REF, otherwise, we have to look into GITHUB_BASE_REF
   */
  if (GITHUB_REF.startsWith(VALID_REF_PREFIX)) {
    // coming from a manual workflow trigger
    branchName = `origin/${GITHUB_REF.replace(VALID_REF_PREFIX, '')}`;
  } else {
    // coming from a PR
    branchRef = `origin/${GITHUB_HEAD_REF}`;
  }

  return branchRef;
}

这需要处理以下情况 -

  1. 我想将 PR 中的更改部署到我的开发环境
  2. 我想通过手动触发器将我想要的任何分支的更改部署到我的开发环境中
  3. 我想将更改从 master 部署到我的 prod env
于 2021-10-11T05:40:40.933 回答
0

有一个非常简单的 git 命令来获取当前分支:

git rev-parse --abbrev-ref 头

要在 env 文件变量中获取输出,只需输入:

      - 名称:设置 CURRENT_BRANCH
        运行: echo "CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)" >> $GITHUB_ENV

要从 env 变量中获取输出:

      - 名称:获取 CURRENT_BRANCH
        运行:回声 ${{ env.CURRENT_BRANCH}}

来源:https ://www.techiedelight.com/determine-current-branch-name-git/

于 2022-01-18T09:14:43.913 回答
0

在这里重复一下,以便更好地了解其他人在以前的回复中作为简单评论所写的内容:

https://docs.github.com/en/actions/learn-github-actions/environment-variables

仅拉取请求的分支名称在此环境变量中公开:

GITHUB_HEAD_REF Only set for pull request events. The name of the head branch.

在 GitHub 操作中,对应的上下文键是:

github.head_ref
于 2022-01-18T14:48:15.113 回答