我们有一个在
test
分支上运行的测试环境,我想运行一个 Github 操作,在推送到 test
时使 main
保持最新状态,但我似乎无法获取它。当我通过 CLI 运行代码时,它可以工作,但是当我运行操作时,它不起作用......
name: Update Test Branch
on:
push:
branches: [main]
jobs:
sync:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
- name: Setup Git User
run: |
git config user.name "GitHub Action"
git config user.email "<EMAIL>"
- name: Update Test Branch
run: |
git fetch origin
git checkout test
git pull
git merge --allow-unrelated-histories origin/main
git push origin test
一开始,我得到了
fatal: refusing to merge unrelated histories
,所以我添加了 --allow-unrelated-histories 标签。现在,我收到一条错误,表明存在一些合并冲突。但是,当我手动运行命令时,不会抛出错误。
从未有过任何手动提交到
test
。它仅且始终应该依赖于main
,这意味着它应该始终具有相关的历史。未来可能会有例外,但我们尚未实现这一目标。
请帮助我理解我做错了什么!
由于 GitHub Actions Runner 出于性能原因执行浅克隆,因此当您尝试进行合并时,完整的历史记录在运行器上不可用。这就是导致“无关历史”错误的原因。
要解决此问题,您需要将
fetch-depth: 0
添加到结帐步骤:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
这应该消除你的提交块中对
--allow-unrelated-histories
的需要:
- name: Update Test Branch
run: |
git checkout main
git fetch origin
git checkout test
git pull
git merge origin/main
git push origin test
最后,您需要添加推送回存储库的权限,新的默认设置是您的运行程序将配置为只读权限。在这里授予
contents: write
就足够了。 从安全角度来看,最好提供所需的最小集:
permissions:
contents: write
最终的工作流程如下:
name: Update Test Branch
on:
push:
branches: [main]
permissions:
contents: write
jobs:
sync:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup Git User
run: |
git config user.name "GitHub Action"
git config user.email "<EMAIL>"
- name: Update Test Branch
run: |
git checkout main
git fetch origin
git checkout test
git pull
git merge origin/main
git push origin test
扩展@jessehouwing 的有用的评论,结帐步骤需要是完整的结帐。此外,我必须将我的操作配置为具有对存储库的写访问权限。动作完整执行如下:
name: Update Test Branch
on:
push:
branches: [main]
permissions: write-all
jobs:
sync:
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v3
with:
fetch-depth: 0
- name: Setup Git User
run: |
git config user.name "GitHub Action"
git config user.email "<EMAIL>"
- name: Update Test Branch
run: |
git checkout main
git fetch origin
git checkout test
git pull
git merge origin/main
git push origin test
谢谢杰西,如果你想给出完整的答案,我可以接受你的。