我正在用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
其他回答
我做了一个获取分支名称的操作,而不管是否触发pull_request。https://github.com/EthanSK/git-branch-name-action
注意,如果你在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
要将其设置为环境变量,我使用以下语法:
- 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动作-启动worflows#如何定义环境变量?# 68
Rmq: sed 's/\//_/g'将用_替换分支名称中的/
获取当前分支很简单,下面的代码适用于我和
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
对于使用Windows映像来运行操作的人,有几个要点需要了解:
假设GitHub动作使用CMD shell是不正确的。他们默认使用PowerShell。 您可以指定shell使用以下方式:
- run: |
...
shell: cmd
您可以使用值'bash'在bash shell上下文中执行命令。
所以,总而言之,你不需要浪费潜在的时间试图弄清楚如何以破旧的cmd方式做事(就像我做的那样)。
为了简单地获取当前分支的名称,你可以在将shell设置为'bash'时使用流行的解决方案,或者使用例如下面的简单方法在默认PowerShell中设置变量:
$branchName = $Env:GITHUB_REF -replace "refs/heads/", ""