1.创建Token

访问Github->头像(右上角)->Settings->Developer Settings->Personal access tokens->Tokens(classic)->generate new token(classic),创建的Token名称随意,但必须勾选repo项和workflows项。

Expiration选择No expiration

token只会显示这一次,之后将无法查看,务必保存下来。

2.创建存放源码的私有仓库

创建一个用来存放Hexo博客源码的私有仓库[XXX],选择Privata

3.配置Github Action

在[D:\XXXX]新建.github文件夹,注意开头是有个.的。然后在.github内新建workflows文件夹,再在workflows文件夹内新建autodeploy.yml,在[D:\XXXX].github\workflows\autodeploy.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
# 当有改动推送到main分支时,启动Action
name: 自动部署

on:
push:
branches:
- main

release:
types:
- published

jobs:
deploy:
runs-on: ubuntu-latest
steps:
- name: 检查分支
uses: actions/checkout@v2
with:
ref: main

- name: 安装 Node
uses: actions/setup-node@v1
with:
node-version: "12.x" #action使用的node版本,建议大版本和本地保持一致。可以在本地用node -v查询版本号。

- name: 安装 Hexo
run: |
export TZ='Asia/Shanghai'
npm install hexo-cli -g

- name: 缓存 Hexo
uses: actions/cache@v1
id: cache
with:
path: node_modules
key: ${{runner.OS}}-${{hashFiles('**/package-lock.json')}}

- name: 安装依赖
if: steps.cache.outputs.cache-hit != 'true'
run: |
npm install --save

- name: 生成静态文件
run: |
hexo clean
hexo generate

- name: 部署 #此处master:main 指从本地的master分支提交到远程仓库的main分支,若远程仓库没有对应分支则新建一个。如有其他需要,可以根据自己的需求更改。
run: |
cd ./public
git init
git config --global user.name '${{ secrets.GITHUBUSERNAME }}'
git config --global user.email '${{ secrets.GITHUBEMAIL }}'
git add .
git commit -m "${{ github.event.head_commit.message }} $(date +"%Z %Y-%m-%d %A %H:%M:%S") Updated By Github Actions"
git push --force --quiet "https://${{ secrets.GITHUBUSERNAME }}:${{ secrets.GITHUBTOKEN }}@github.com/${{ secrets.GITHUBUSERNAME }}/${{ secrets.GITHUBUSERNAME }}.github.io.git" master:main

到仓库[XXX]的Settings->Secrets->actions 下添加环境变量

GITHUBUSERNAME、GITHUBEMAIL、GITHUBTOKEN

4.重新设置远程仓库和分支

删除[D:\XXXX]\themes\butterfly.git

在[D:\XXXX]打开Open Git Bash Here,输入以下命令

1
2
3
git init #初始化
git remote add origin git@github.com:[GithubUsername]/[SourceRepo].git #[SourceRepo]为存放源码的github私有仓库
git checkout -b main

打开[D:\XXXX].gitignore,输入以下内容:

.DS_Store
Thumbs.db
db.json
.log
node_modules/
public/
.deploy
/
.deploy_git*/
.idea
themes/butterfly/.git

输入以下命令

1
2
3
git add .
git commit -m "github action update" #引号内的内容可以自行更改作为提交记录。
git push origin main