改为由Github Actions部署

Travis CI 去年开始收费后就就一直想着迁移到 GitHub Actions来部署,然而几乎一年未更新内容,就一直搁置着(归根结底就是懒了),最近想起这茬事就顺道给迁移了

一开始想直接套个 marketplace 里现成的hexo-action,但因为不支持 Pandoc(使用了hexo-rendering-pandoc),只能手动创建一个 workflow

Github Actions 由 yml 文件控制,存在.github/workflow目录下,其运行的逻辑如官方文档所说

You can configure a GitHub Actions workflow to be triggered when an event occurs in your repository, such as a pull request being opened or an issue being created. Your workflow contains one or more jobs which can run in sequential order or in parallel. Each job will run inside its own virtual machine runner, or inside a container, and has one or more steps that either run a script that you define or run an action, which is a reusable extension that can simplify your workflow.

新建一个名为 Deployment 的 workflow,由于博客的源文件单独放在了一个仓库中,而平时的修改都在 draft 分支上进行,因此设置当 master 分支接收到 pull request 时触发此 workflow,workflow_dispatch用于手动在 Github 中执行 workflow 以便调试

1
2
3
4
5
6
7
8
9
name: Deployment

# Controls when the workflow will run
on:
pull_request:
branches:
- master
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:

接着创建一个在 ubuntu-latest 上运行,名称为 build 的 job,详细的步骤在steps下设定

1
2
3
4
5
6
7
8
# A workflow run is made up of one or more jobs that can run sequentially or in parallel
jobs:
# This workflow contains a single job called "build"
build:
# The type of runner that the job will run on
runs-on: ubuntu-latest
# Steps represent a sequence of tasks that will be executed as part of the job
steps:

首先确认在 $GITHUB_WORKSPACE 下并安装node.js,node-version 指定版本或者使用 nvm lts 写法,cache 根据需求选择 npm 或者 yarn

1
2
3
4
5
6
7
8
9
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- name: Checkout
uses: actions/checkout@v3
- name: Install node.js and modules
uses: actions/setup-node@v3
with:
node-version: 'lts/*'
cache: 'npm'
- run: npm install

接着安装 pandoc,pandoc 官方文档中给出的 Github Actions 安装方式是依赖于 docker 的,无法直接在 node.js 中调用,因此选择手动安装,版本号由下载目录决定,$RUNNER_TOOL_CACHE为 Github 默认环境变量,包含 GitHub 托管运行器预安装工具的目录路径

1
2
- name: Install pandoc
run: curl -s -L https://github.com/jgm/pandoc/releases/download/2.18/pandoc-2.18-linux-amd64.tar.gz | tar xvzf - -C $RUNNER_TOOL_CACHE/

将 pandoc 加入 PATH 中,执行 build,生成静态文件

1
2
3
4
5
- name: Build
run: |
# add pandoc to PATH
export PATH="$PATH:$RUNNER_TOOL_CACHE/pandoc-2.18/bin"
npm run build

使用 actions-gh-pages 将生成的静态文件推送到指定仓库和分支上,如果在同一仓库中可以直接使用 github_token (已在环境变量中),跨仓库可使用 deploy_key (SSH)或者 personal_token(HTTPS),需在GitHub设置中配置,具体参考 Options

1
2
3
4
5
6
7
8
# Deploy hexo blog website.
- name: Deploy
uses: peaceiris/actions-gh-pages@v3
with:
deploy_key: ${{ secrets.DEPLOY_KEY }}
publish_dir: ./public
external_repository: leaf-hsiao/leaf-hsiao.github.io
publish_branch: master

最后按惯例在 readme 中加入徽章(

参考资料

从 Travis CI 迁移到 GitHub Actions

https://hexo.io/docs/github-pages.html

Github Actions 测试 - 自动部署 Hexo