使用Travis-CI自动部署博客
因为在github上面存储的是编译好的html代码,不是hexo博客中的博客源文件,所以如果没有备份源文件的话,丢失了源文件(包括md,一堆配置文件)后就不能继续更新博客了,而且也不能多端部署Hexo。网上看到可以使用Travis-CI来自动部署,同时解决了博客源文件的备份问题。
新建hexo分支来保存源文件
新建分支
直接在对应的github.io项目上的branch 按钮处点击新建分支 hexo。
官方文档https://help.github.com/en/articles/setting-the-default-branch
# 克隆项目到本地
> git clone https://github.com/BraveY/BraveY.github.io.git
设置默认分支
参照官方文档设置https://help.github.com/en/articles/setting-the-default-branch
修改推送hexo分支
现将原来的文件BraveY.github.io 修改为BraveY.github.io.bak 避免拷贝的时候出现文件夹重名,同时将原来的hexo 目录blog文件也修改为blog.bak
直接克隆到 本地
# 克隆项目到本地
> git clone https://github.com/BraveY/BraveY.github.io.git
这时拷贝的项目已经是hexo分支下面的,因为之前是设置了hexo分支作为默认分支的。
将克隆的BraveY.github.io文件夹重命名为blog
在克隆的文件夹里面删除除了.git的所有文件
注意 :因为主题的next也是个git仓库,所以需要先把next目录下的.git删除
然后先把theme/next 目录下的.git 给删除掉,不然的话next这个主题本来就是个git仓库,里面的个性化配置是无法上传到自己的项目中的,而且以后也无法克隆。
从blog.bak文件中把所有hexo的源码文件拷过来。
在博客目录下初始化git仓库并将所有文件提交。
添加到远程仓库
git add .
git commit -m"description"
git push origin
现在hexo分支已经是存放了hexo的源文件了。
设置Travis CI
主要参考下面的三个博客,
Travis CI 官网登陆
使用github账号登陆Travis CI官网 ,选择博客项目启动。然后进行设置。
没有文章中说的Build only if .travis.yml is present
选项,但好像没有影响,采用默认的选项。
github生成Access Token
参考博客,不赘述。
Travis CI
配置travis.yml
在blog根目录下设置travis配置文件。
.travis.yml 文件的配置为:
language: node_js # 设置语言
node_js: stable # 设置相应版本
cache:
apt: true
directories:
- node_modules # 缓存不经常更改的内容
before_install:
- export TZ='Asia/Shanghai' # 更改时区
install:
- npm install
script:
- hexo clean
- hexo g
after_script:
- git clone https://${GH_REF} .deploy_git
- cd .deploy_git
- git checkout master
- cd ../
- mv .deploy_git/.git/ ./public/
- cd ./public
- git config user.name "BraveY"
- git config user.email "lsz_yky@163.com"
- git add .
- git commit -m "Travis CI Auto Builder at `date +"%Y-%m-%d %H:%M"`"
- git push --force --quiet "https://${github_blog@${GH_REF}" master:master
branches:
only:
- hexo
env:
global:
- GH_REF: github.com/BraveY/BraveY.github.io.git
notifications:
email:
- lsz_yky@163.com
on_success: change
on_failure: always
新增文章到_posts
增减文章后,使用git push 命令即可,自动部署。
可以看到 Travis CI 上面构建的一系列输出,但是博客并没有更新,而且github上的master分支也没有更改过。查看Travis CI 上的输出信息,发现在执行
git push --force --quiet "https://${github_blog@${GH_REF}" master:master
这句后报错:
/home/travis/.travis/functions: eval: line 104: unexpected EOF while looking for matching `"'
/home/travis/.travis/functions: eval: line 105: syntax error: unexpected end of file
然后发现${github_blog@${GH_REF}
这句花括号没有对齐匹配,无语。加上漏掉的右边花括号} 重新执行操作。一切正常。
博客更新操作
后面就不用自己hexo g -d
了
在_posts目录下增加文章后
git add .
git commit -m""
git push origin
感觉可以写个脚本
命名为git_script.ps1 以后直接用powershell运行这个脚本就可以了。
git add .
$date = get-date -uformat "%Y-%m-%d %H:%M:%S"
git commit -m"new post $date"
git push origin
参考
https://www.itfanr.cc/2017/08/09/using-travis-ci-automatic-deploy-hexo-blogs/
http://www.dxjia.cn/2016/01/27/hexo-write-everywhere/
http://www.yanglangjing.com/2018/08/28/travis_ci_auto_deploy_hexo_to_vps/