如何通过GitHub Action编辑GitHub Pages内容而不覆盖原有内容?
如何通过GitHub Action编辑GitHub Pages内容而不覆盖原有内容?
嘿,我完全懂你的困扰!现在你的Action能自动把主分支的文档发布到GitHub Pages,但你想给每个PR也生成一份文档放到/pulls/[PR编号]/这样的子目录里,又怕新部署会把主分支已经存在的内容给冲掉——毕竟默认的Pages部署是直接替换整个站点内容的对吧?
别担心,咱们可以通过先拉取现有Pages内容,再合并新内容后重新部署的方式解决这个问题,核心思路是操作GitHub Pages背后的gh-pages分支(或者你自定义的Pages源分支),把新内容加到对应的位置,再整体上传部署。
一、调整主分支的文档部署Workflow
首先,原来的主分支部署会直接覆盖整个站点,咱们得改一改,让它保留/pulls/目录的内容,只更新根目录的主分支文档:
name: Publish Main Branch Docs on: push: branches: [main] permissions: pages: write id-token: write contents: read jobs: build: runs-on: ubuntu-latest steps: - name: Checkout main branch code uses: actions/checkout@v4 - name: Build docs run: cargo doc --no-deps # 生成主分支文档,根据你的项目调整命令 - name: Checkout existing gh-pages content uses: actions/checkout@v4 with: ref: gh-pages path: gh-pages-content fetch-depth: 0 - name: Clear old main docs (keep /pulls/ directory) run: | # 删除根目录下除了pulls文件夹之外的所有内容 cd gh-pages-content ls -1 | grep -v 'pulls' | xargs rm -rf - name: Copy new main docs to root run: cp -r target/doc/* gh-pages-content/ - name: Upload updated Pages artifact uses: actions/upload-pages-artifact@v3 with: path: gh-pages-content deploy: needs: build runs-on: ubuntu-latest environment: name: github-pages url: ${{ steps.deployment.outputs.page_url }} steps: - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v4
二、新增PR文档的部署Workflow
接下来创建一个专门处理PR的Workflow,每个PR触发时,把它的文档放到/pulls/[PR编号]/目录下,同时保留现有所有内容:
name: Publish PR Docs on: pull_request: types: [opened, synchronize, reopened] permissions: pages: write id-token: write contents: read jobs: build-and-deploy-pr-docs: runs-on: ubuntu-latest steps: - name: Checkout PR code uses: actions/checkout@v4 with: ref: ${{ github.head_ref }} - name: Build PR docs run: cargo doc --no-deps # 同样,根据你的项目调整构建命令 - name: Checkout existing gh-pages content uses: actions/checkout@v4 with: ref: gh-pages path: gh-pages-content fetch-depth: 0 - name: Create PR docs directory run: mkdir -p gh-pages-content/pulls/${{ github.event.pull_request.number }} - name: Copy PR docs to target directory run: cp -r target/doc/* gh-pages-content/pulls/${{ github.event.pull_request.number }}/ - name: Upload updated Pages artifact uses: actions/upload-pages-artifact@v3 with: path: gh-pages-content - name: Deploy to GitHub Pages id: deployment uses: actions/deploy-pages@v4
额外小贴士
- 如果想在PR关闭后自动删除对应的
/pulls/[PR编号]/目录,可以再加一个Workflow,触发条件设为pull_request: types: [closed],步骤类似:拉取gh-pages内容,删除对应目录,再部署。 - 注意权限设置:两个Workflow都需要
pages: write和id-token: write权限才能部署,contents: read用来拉取代码和gh-pages分支。 - 测试的时候可以先开个小PR,看看部署后的Pages站点是不是同时保留了主分支的根目录文档和PR的子目录文档~
备注:内容来源于stack exchange,提问作者joshlf
相关产品推荐
相关产品推荐

