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

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


当前回答

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

其他回答

注意,如果你在pull request触发器上执行你的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

在Windows上运行? Windows default命令是一个PowerShell终端。

  - name: SET CURRENT_BRANCH
    run: |
      $branchName = "${{github.ref}}".Split("/")["${{github.ref}}".Split("/").Length -1]
      echo "::set-env name=CURRENT_BRANCH::$(echo $branchName)"

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

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

通常,我总是有一个用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环境