自动同步github仓库 Fork 工作流

自动同步远程fork仓库的工作流

完整可直接使用的 sync-fork.yml 模板

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# 工作流名称,可自定义
name: Auto Sync Fork with Upstream

# 触发条件:定时执行 + 手动触发
on:
  # 定时执行:每天 UTC 0 点(北京时间 8 点)执行一次
  # 如需调整频率,可改 cron 表达式(比如 0 */12 * * * 是每12小时)
  schedule:
    - cron: '0 0 * * *'
  # 手动触发:在仓库 Actions 页面可手动点击运行
  workflow_dispatch:

# 执行的任务
jobs:
  sync:
    # 运行环境:使用最新的 Ubuntu
    runs-on: ubuntu-latest
    steps:
      # 第一步:检出当前 Fork 仓库的代码
      - name: Checkout Fork Repository
        uses: actions/checkout@v4
        with:
          fetch-depth: 0          # 拉取所有历史,避免合并冲突
          persist-credentials: false

      # 第二步:配置 Git 用户名和邮箱(Actions 提交代码用)
      - name: Configure Git User
        run: |
          git config --global user.name "GitHub Actions"
          git config --global user.email "actions@github.com"

      # 第三步:添加上游仓库(原仓库)地址
      - name: Add Upstream Remote
        run: |
          # 👇 【必改】替换成你 Fork 的原仓库地址(格式:https://github.com/原作者/原仓库名.git)
          git remote add upstream https://github.com/ORIGINAL_OWNER/ORIGINAL_REPOSITORY.git
          # 验证远程仓库是否添加成功
          git remote -v

      # 第四步:拉取上游仓库的最新代码
      - name: Fetch Upstream Code
        run: git fetch upstream

      # 第五步:合并上游代码到当前分支
      - name: Merge Upstream to Fork
        run: |
          # 👇 【必改】替换成你要同步的分支名(通常是 main 或 master)
          git checkout main
          # 快进合并,避免不必要的提交记录;如果无更新则提示,不中断流程
          git merge --ff-only upstream/main || echo "No new changes to sync from upstream"

      # 第六步:推送合并后的代码到你的 Fork 仓库
      - name: Push to Fork Repository
        run: |
          git push https://x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}.git main

如何使用这个文件?

  1. 打开你的 Fork 仓库 → 点击顶部的 Add fileCreate new file
  2. 文件名填写 .github/workflows/sync-fork.yml(注意路径和后缀不能错);文件路径必须是 .github/workflows/sync-fork.yml,否则 GitHub Actions 无法识别;
  3. 把上面修改好的模板内容粘贴进去;
  4. 拉到页面底部,填写提交信息(比如 Add auto sync fork workflow),点击 Commit new file
  5. 提交后,你可以在仓库的 Actions 页面看到这个工作流,点击 Run workflow 可手动测试一次同步是否成功;
  6. 如果同步时遇到冲突(比如你修改了 Fork 仓库的默认分支),工作流会失败,此时需要你本地手动解决冲突后再同步;
  7. cron 表达式可自定义频率,比如:
  • 每6小时:0 */6 * * *
  • 每天凌晨2点(北京时间):0 18 * * *(UTC 时间比北京时间晚8小时,18+8=26→次日2点)
  • 支持定时自动同步 + 手动触发,无需额外配置权限(GITHUB_TOKEN 是内置的)。
原文链接: https://www.17you.com/programming/%E8%87%AA%E5%8A%A8%E5%90%8C%E6%AD%A5fork%E4%BB%93%E5%BA%93/ 已复制!
编程和技术

寻找技术支持帮助和技术合伙人一起搞事。

请点击联系我


相关内容