我正在用Github动作构建Docker图像,并想用分支名称标记图像。
我找到了GITHUB_REF变量,但它导致了refs/heads/feature-branch-1,我只需要feature-branch-1。
我正在用Github动作构建Docker图像,并想用分支名称标记图像。
我找到了GITHUB_REF变量,但它导致了refs/heads/feature-branch-1,我只需要feature-branch-1。
当前回答
获取当前分支很简单,下面的代码适用于我和
github.ref_name
是用于获取分支名称的预定义变量吗
jobs:
main-branch-build:
if: github.ref_name == 'main'
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v3
feature-branch-build:
if: github.ref_name != 'main'
runs-on: ubuntu-latest
steps:
- name: Check out code
uses: actions/checkout@v3
其他回答
为了获得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现在支持GITHUB_REF_NAME,它代表触发工作流运行的分支或标记名称。
GitHub文档在这个https://docs.github.com/en/actions/learn-github-actions/environment-variables#default-environment-variables上
在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)"
在这里重复一下,以便更好地看到其他人在之前的回复中作为简单注释写的内容:
https://docs.github.com/en/actions/learn-github-actions/environment-variables
只在这个环境变量中暴露了pull请求的分支名称:
仅为拉请求事件设置。总行的名称。
在GitHub动作中,对应的上下文键是:
github.head_ref
同时处理pull_request和push事件的解决方案。由于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动作中的运行时变量