创建源码仓库

在github上新创建一个仓库blog来存放源码以及主题文件

注意一共需要两个仓库, 一个是源文件仓库, 一个是你的github.io仓库

将该仓库克隆到本地

把原来的文件夹内所有内容复制过来(除了.git文件夹)

(注意把themes文件夹以及其子文件夹中的.git删掉, 否则git add时会报错)

==注意: 如果使用自己的域名则需要在source目录下添加一个名CNAME的文件, 内容填写你的域名即可, (否则每次部署后github pages的域名设置都会失效)如果没有域名, 则忽略此步骤==

配置 Github Actions

接下来在根目录创建.github/workflows/deploy.yml 文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
name: HEXO CI

on:
push:
branches:
- master

jobs:
build:
runs-on: ubuntu-latest
strategy:
matrix:
node-version: [14.x]

steps:
- uses: actions/checkout@v1

- name: Use Node.js ${{ matrix.node-version }}
uses: actions/setup-node@v1
with:
node-version: ${{ matrix.node-version }}

- name: Configuration environment
env:
HEXO_DEPLOY_PRI: ${{secrets.HEXO_DEPLOY_PRI}}
run: |
mkdir -p ~/.ssh/
echo "$HEXO_DEPLOY_PRI" > ~/.ssh/id_rsa
chmod 600 ~/.ssh/id_rsa
ssh-keyscan github.com >> ~/.ssh/known_hosts
git config --global user.name "yourgithubname"
git config --global user.email "xxx@xx.com"
- name: Install dependencies
run: |
npm i -g hexo-cli
npm i
- name: Deploy hexo
run: |
hexo clean && hexo generate && hexo deploy

配置秘钥

1
ssh-keygen -t rsa -f github-deploy-key

生成了两个文件,github-deploy-keygithub-deploy-key.pub

在 Github 打开 blog 仓库,打开 Settings->Secrets->New Secrets,Name 填 HEXO_DEPLOY_PRI,Value填 github-deploy-key的内容。

再打开 你的github.io仓库,打开 Settings->Deploy Key->Add deploy key,Title 不用填写,Key填写 github-deploy-key.pub的内容

配置秘钥完成

Push代码

将你的代码push到远程仓库中

1
2
3
4
5
6
# 将文件添加到缓冲区
git add .
# 提交修改
git commit -m "提交信息"
# 推送到github
git push

推送成功后即可看到blog仓库的actions已经开始执行

执行完之后github.io仓库的actions也开始自动执行

等到两个仓库的action执行完毕, 自动部署就已经完成, 访问你的域名或者github.io即可看到博客

下次写博客时就可以写完后直接推送到github, github的action会自动帮你完成部署

完结

随时随地写blog~

补充

由于action中git操作会改变文件的更新时间, 在deploy.yml中添加如下代码来保证文件的时间不会改变

1
2
3
- name: Restore file modification time
run: |
find source/_posts -name '*.md' | while read file; do touch -d "$(git log -1 --format="@%ct" "$file")" "$file"; done