我正在用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动作上使用分支名称
使用当前分支名称的方便操作。 使用
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}
其他回答
你可以使用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
if: github.ref == 'refs/heads/integration' && github.event_name == 'push'
您可以使用上面的命令替换您想要运行的任何分支或事件。
有一个非常简单的git命令来获取当前分支:
git rev-parse --abbrev-ref HEAD
要在env文件变量中获得输出,只需输入:
- name: Set CURRENT_BRANCH run: echo "CURRENT_BRANCH=$(git rev-parse --abbrev-ref HEAD)" >> $GITHUB_ENV
获取env变量的输出:
- name: Get CURRENT_BRANCH run: echo ${{ env.CURRENT_BRANCH}}
来源:https://www.techiedelight.com/determine-current-branch-name-git/
如何在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_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 }}