利用 Github Actions 自動更新 docfx 文檔

利用 Github Actions 自動更新 docfx 文檔

Intro

docfx 是微軟出品一個 .NET API 文檔框架,有一個理念是程式碼即文檔,會根據項目程式碼自動生成 API 文檔,即使沒有寫任何注釋也會生成 API 文檔,也有一些默認的主題可以配置,也可以自定義主題配置,詳細介紹可以參考官方介紹 //dotnet.github.io/docfx/

目前也有很多項目在使用 docfx 來生成文檔,比如前段時間介紹過的 Reserver-Proxy 項目,也是看到了 reservse-proxy 項目配置了一個 Github Actions 來自動更新文檔所以在我自己的項目里也增加了類似的配置,除了微軟的項目還有很多社區開源項目在用,如果你也在做一些 .NET 類庫類的開源項目,可以嘗試一下

docfx 怎麼使用可以參考官方文檔,本文主要介紹如何使用 Github Actions 實現自動更新文檔

文檔示例

更多可以參考: //weihanli.github.io/WeihanLi.Npoi/index.html

自動更新文檔流程

  1. 檢出要使用的用於生成文檔的分支程式碼
  2. 安裝 docfx 命令行工具,推薦使用 choco 安裝,因為執行 build 的 agent 上已經安裝了 Chocolatey
  3. 使用 docfx 生成文檔
  4. 檢出 gh-pages 分支,用於託管文檔的分支
  5. 刪除 gh-pages 之前的文件(.git目錄包含git資訊,不能刪除)
  6. 把第三步操作生成的文檔複製到 gh-pages 分支下
  7. commit && push,提交程式碼並推送更新在線文檔

Github Actions 示例配置

Actions 示例,源鏈接://github.com/WeihanLi/WeihanLi.Npoi/blob/dev/.github/workflows/docfx.yml

name: docfx build
on:
  push:
    branches:
      - dev
jobs:
  build:
    name: Build
    runs-on: windows-latest
    steps:
      # Check out the branch that triggered this workflow to the 'source' subdirectory
      - name: Checkout Code
        uses: actions/checkout@v2
        with:
          ref: dev
          path: source
      - name: install DocFX
        run: "& choco install docfx -y"
      # Run a build
      - name: Build docs
        run: "& docfx ./docfx.json"
        working-directory: ./source
      # Check out gh-pages branch to the 'docs' subdirectory
      - name: Checkout docs
        uses: actions/checkout@v2
        with:
          ref: gh-pages
          path: docs
      # Sync the site
      - name: Clear docs repo
        run: Get-ChildItem -Force -Exclude .git | ForEach-Object { Remove-Item -Recurse -Verbose -Force $_ }
        working-directory: ./docs
      - name: Sync new content
        run: Copy-Item -Recurse -Verbose -Force "$env:GITHUB_WORKSPACE/source/_site/*" "$env:GITHUB_WORKSPACE/docs"
        working-directory: ./docs
        # update docs
      - name: Commit to gh-pages and push
        run: |
          $ErrorActionPreference = "Continue"
          git add -A
          git diff HEAD --exit-code
          if ($LASTEXITCODE -eq 0) {
            Write-Host "No changes to commit!"
          } else {
            git config --global user.name "github-actions-docfx[bot]"
            git config --global user.email "[email protected]"
            git commit -m "Updated docs from commit $env:GITHUB_SHA on $env:GITHUB_REF"
            git remote set-url origin //x-access-token:${{ secrets.GITHUB_TOKEN }}@github.com/${{ github.repository }}
            git push origin gh-pages
          }
        working-directory: ./docs

我這裡是只要 dev 分支更新了就更新,你也可以根據需要當 master 分支更新時再更新,修改分支名稱即可

More

現在用的還是 2.x 版本,3.x 版本還沒發布,3.x版本發布之後可以直接通過 dotnet tool 來安裝更加方便和可擴展,目前 2.x 使用 choco 來安裝命令行工具,需要依賴 Chocolatey,如果是 dotnet tool 有 dotnet 環境就可以了,就可以方便很多了

不僅僅是 docfx 生成文檔,你也可以擴展其他類似的需求,使用 Github Actions 實現自動同步,更新

Reference