You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求仅在Fork仓库运行的定时同步上游GitHub Action方案

现成可用的GitHub Action推荐

有几个成熟的Action可以直接满足你的需求,比如wei/git-sync:

  • 支持定时同步、上游仓库配置,还能通过参数控制仅在分支落后时执行同步
  • 配置时只需指定上游仓库地址、目标分支,再加上判断当前仓库是否为Fork的条件即可

配置片段参考:

name: Sync Upstream
on:
  schedule:
    - cron: '0 0 * * *' # 每天0点执行
  workflow_dispatch: # 允许手动触发

jobs:
  sync:
    runs-on: ubuntu-latest
    if: github.event.repository.fork == true # 仅在Fork仓库运行
    steps:
      - uses: wei/git-sync@v3
        with:
          source_repo: 'https://github.com/原仓库作者/原仓库名.git'
          source_branch: 'main'
          destination_branch: 'main'
          github_token: ${{ secrets.GITHUB_TOKEN }}
自定义编写Action的建议

如果需要更灵活的控制,可以自己编写Workflow,步骤如下:

  1. 设置触发条件
    用schedule配置24小时执行一次,同时保留手动触发入口,配合Fork判断:
on:
  schedule:
    - cron: '0 0 * * *'
  workflow_dispatch:
  1. 核心步骤编写
  • 全量检出代码:必须设置fetch-depth: 0以拉取完整提交历史
- name: Checkout code
  uses: actions/checkout@v4
  with:
    fetch-depth: 0
    persist-credentials: false # 避免权限冲突
  • 添加上游仓库并拉取更新:
- name: Add upstream repo
  run: |
    git remote add upstream https://github.com/原仓库作者/原仓库名.git
    git fetch upstream
  • 检查当前分支是否落后:
- name: Check if branch is behind upstream
  id: check-behind
  run: |
    BEHIND_COUNT=$(git rev-list --count HEAD..upstream/main)
    echo "behind_count=$BEHIND_COUNT" >> $GITHUB_OUTPUT
  • 执行同步(仅当落后时):
- name: Sync with upstream
  if: steps.check-behind.outputs.behind_count > 0
  run: |
    git config --global user.name "GitHub Actions"
    git config --global user.email "actions@github.com"
    git merge upstream/main --no-edit
    git push https://${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git main
  1. 注意事项
  • 确保GITHUB_TOKEN有推送权限,若默认权限不足,可在Workflow中设置permissions: contents: write
  • 若上游分支有冲突,上述合并会失败,可根据需求添加冲突处理逻辑(比如自动跳过或通知管理员)
  • 替换示例中的分支名(如main)为你实际使用的分支

内容的提问来源于stack exchange,提问作者Echo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 14:15:45