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

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


当前回答

${{ github.ref_name }}

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

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

其他回答

如何在Github行动中获得当前的分支?

假设${{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}}。

注:

上述方法仅适用于基于unix的映像(Linux和macOS)。 对于文档,请阅读:GitHub Actions的上下文和表达式语法。

更新

GitHub现在支持GITHUB_REF_NAME,它代表触发工作流运行的分支或标记名称。

GitHub文档在这个https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables上

通常,我总是有一个用nodejs或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;
}

这涉及到以下场景-

我想从PR部署到我的开发环境的变化 我想通过手动触发器将任何分支的更改部署到我的dev env中 我想从master部署更改到我的prod环境

在这里重复一下,以便更好地看到其他人在之前的回复中作为简单注释写的内容:

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

只在这个环境变量中暴露了pull请求的分支名称:

仅为拉请求事件设置。总行的名称。

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

github.head_ref

现在不建议使用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 }}