PR获批后自动推送当前分支至第三方仓库的Workflow需求
GitHub Actions Workflow:PR获批后同步分支到第三方仓库
需求实现
针对你提出的内部审核流程后同步第三方仓库的需求,以下Workflow会在当前仓库的PR获得批准时,自动将PR对应的分支推送到指定的第三方仓库。
完整Workflow配置
创建.github/workflows/sync-to-third-party.yml文件,内容如下:
name: Sync Branch to Third Party Repo on PR Approval # 触发条件:当PR的审核状态变为"Approved"时触发 on: pull_request_review: types: [submitted] jobs: sync-branch: # 仅当PR已批准且状态为Open时执行(避免重复触发) if: github.event.review.state == 'approved' && github.event.pull_request.state == 'open' runs-on: ubuntu-latest permissions: contents: write # 授予读写仓库内容的权限 steps: - name: Checkout current repo branch uses: actions/checkout@v4 with: ref: ${{ github.event.pull_request.head.ref }} # 检出PR对应的分支 fetch-depth: 0 # 拉取完整提交历史,避免推送时的历史问题 - name: Configure Git user run: | git config --global user.name "GitHub Actions Bot" git config --global user.email "actions@github.com" - name: Add third party repo remote run: | git remote add third-party https://${{ secrets.THIRD_PARTY_REPO_TOKEN }}@${{ secrets.THIRD_PARTY_REPO_URL }} # 示例:如果第三方仓库地址是https://github.com/owner/repo.git,THIRD_PARTY_REPO_URL填github.com/owner/repo.git - name: Push branch to third party repo run: | git push third-party ${{ github.event.pull_request.head.ref }}:${{ github.event.pull_request.head.ref }} # 格式:git push <远程名称> <本地分支>:<远程分支>,这里保持分支名一致
关键配置说明
- 触发条件:监听
pull_request_review事件,仅当审核状态为approved且PR处于open状态时执行任务,避免重复触发。 - 权限设置:授予
contents: write权限,确保Workflow有推送代码的权限。 - Secret配置:需要在当前仓库的「Settings > Secrets and variables > Actions」中添加两个Secret:
THIRD_PARTY_REPO_TOKEN:第三方仓库的访问令牌(需有推送权限)THIRD_PARTY_REPO_URL:第三方仓库的地址(格式如github.com/owner/repo.git,去掉开头的https://)
- 分支推送:直接将PR对应的分支推送到第三方仓库,保持分支名称一致,确保同步准确性。
可选调整
如果你的需求是PR合并后再同步,可以将触发条件改为:
on: pull_request: types: [closed] jobs: sync-branch: if: github.event.pull_request.merged == true # 后续步骤同上
内容的提问来源于stack exchange,提问作者Austin Poulson
相关产品推荐
相关产品推荐

