Appearance
使用GitAction实现自动化部署
整体流程
目前blog采用vitepress工程(以下称MD仓库)和生成的博客文件(以下称Blog仓库)独立仓库的方式,即将vitepress build生成的文件单独仓库作为博客的发布源来实施。整个自动化所希望达到的目的是当MD有提交的时候自动化触发编译,并将编译生成文件提交到Blog仓库。
null
准备工作
vitepress默认生成的文件在docs/.vitepress/dist中,我们将生成的目录在config.js中修改成../blogdist,这样文件将生成在blogdist中,方便我们操作。我们将Blog仓库check到和MD仓库同一父目录的blogdist。当我们完成编译后,将blogdist中的文件复制到../blogdist
bash
.
├─ viteblog
│ ├─ docs
│ │ └─ .vitepress
│ └─ blogdist
└─ blogdist
GitAction实现
创建GitAction
在github页面中,选择Actions tab,创建一个简单Action,我们命名为AutoBuild.yaml, 然后编辑内容。
首先,我们的目的是当有提交,或手动都可以触发编译,国为我们的主干是master,故监听master的变更:
yaml
name: CI
# Controls when the workflow will run
on:
# Triggers the workflow on push or pull request events but only for the master branch
push:
branches: [ master ]
pull_request:
branches: [ master ]
# Allows you to run this workflow manually from the Actions tab
workflow_dispatch:
编译步骤
然后我们来配置具体的编译步骤,首先是将我们的MD仓库和Blog仓库分别check下来.对MD仓库,可以直接使用内置的action进行,对blog仓库则需要我们自己使用shell来check,注意此时工作目录要设置为父目录
yaml
# 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:
# Checks-out your repository under $GITHUB_WORKSPACE, so your job can access it
- uses: actions/checkout@v3
- name: clone old blog
working-directory: ./..
run: |
df -hT $PWD
git clone https://github.com/sofent/sofent.github.io blogdist
然后,我们需要设置node和yarn的环境,正好都有对应的action,注意要添加对vitepress的依赖。应该也有其他的方式来重新下载node_modules,但重新添加依赖好像是一个比较简单的方案。这里在配置过程中曾遇到一个错误,之前把node_modules直接提交到仓库中了,但不同平台的node_modules并不通用。故从仓库中去除,并通过添加依赖重新下载。
yaml
- uses: actions/setup-node@v3.2.0
- uses: borales/actions-yarn@v2.3.0
with:
cmd: add --dev vitepress
然后我们可以直接编译,并将文件copy到blog仓库所在的目录(这里应该需要先把原来文件删除,不然可能存在垃圾文件),注意这里的git remote rm origin ,这里因为后面的目录提交是通过添加upstream的方式实现的,如果不删除,则后面会报错
yaml
- uses: borales/actions-yarn@v2.3.0
with:
cmd: docs:build
- name: copy build file
working-directory: .
run: |
cp -rf docs/blogdist/* ../blogdist
cd ../blogdist
git remote rm origin
现在我们的blog仓库所在的目录是新的,我们需要提交并push到我们的blog仓库即可
yaml
- name: Push dir to Git
uses: liziwl/git-push-action@v1.0.4
with:
# Username of token holder
git_token_holder: <github username>
# Token for the destination repo. Can be passed in using $\{{ secrets.GIT_TOKEN }}
git_token: ${{ secrets.SUPER_TOKEN }}
# Repository URL after "https://", like "github.com/USER_NAME/REPO_NAME.git"
repository_url: <blog repo>
# Directory to push
push_dir: ../blogdist
# User to commit
commit_user: <git user>
# Email of the user to commit
commit_email: <git user mail>
# Destination branch to push changes
branch: main
# Commit messgae
commit_message: auto build
注意事项
在最后一步提交到blog仓库的时候,可能会遇到secrets.GITHUBTOKEN没有权限的问题,所以我们需要在你的个人profile中生成一个有权限的token,然后在工程的安全设置作为安全key配置,然后引用这个安全key就可以。我们配置key名字叫SUPER_TOKEN,在这里secrets.SUPER_TOKEN引用