如何在来自Fork仓库的Pull Request中运行GitHub Action工作流
解决Fork仓库PR触发GitHub Action构建失败的问题
问题原因
当PR来自Fork仓库时,你当前的checkout步骤指定了ref: ${{github.head_ref}},但默认checkout操作只会拉取基准仓库(比如myurud/jasminegraph)的代码,而github.head_ref对应的分支只存在于发起PR的Fork仓库中,基准仓库没有这个分支,因此会报错找不到分支。
解决方案
修改checkout步骤,动态指定要拉取的仓库和分支:
- 当触发事件是PR时,拉取发起者Fork仓库的对应分支
- 当触发事件是push时,保持拉取基准仓库的分支
修改后的checkout步骤配置如下:
- uses: actions/checkout@v2 with: # PR事件用Fork仓库,push事件用基准仓库 repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }} # PR事件用head_ref,push事件用当前分支 ref: ${{ github.head_ref || github.ref }} fetch-depth: 0
完整修改后的Workflow文件
name: Build on: push: branches: [master] pull_request: branches: [master] env: BUILD_TYPE: Release jobs: build: runs-on: ubuntu-latest steps: - uses: actions/checkout@v2 with: repository: ${{ github.event.pull_request.head.repo.full_name || github.repository }} ref: ${{ github.head_ref || github.ref }} fetch-depth: 0 - name: Build run: docker build -t <tag-name> .
补充说明
- 这个配置同时兼容同一仓库的PR、push操作,以及Fork仓库的PR操作
- GitHub Actions处理Fork仓库的PR时,默认只有读权限,这里仅拉取代码,不会涉及权限问题
内容的提问来源于stack exchange,提问作者Mohamed Ishad
相关产品推荐
相关产品推荐

