Quanyin 说

借助 Travis CI 实现自动部署

Travis CI 提供的是持续集成服务(Continuous Integration,简称 CI)。它绑定 Github 上面的项目,只要有新的代码,就会自动抓取。然后,提供一个运行环境,执行测试,完成构建,还能部署到服务器。

持续集成

持续集成(Continuous Integration)指的是,频繁地(一天多次)将代码集成到主干。

持续集成的目的,就是让产品可以快速迭代,同时还能保持高质量。

它的核心措施是,代码集成到主干之前,必须通过自动化测试。只要有一个测试用例失败,就不能集成。

Travis CI

Travis CI 对 Github 上的开源项目提供免费服务,这要求必须有 Github 账号。官网 https://travis-ci.org 只支持开源项目,如果想要对私人项目使用,则需要使用 https://travis-ci.com.

首先,访问官方网站,点击右上角的个人头像,使用 Github 账户登入 Travis CI。Travis 会列出 Github 上面你的所有仓库,以及你所属于的组织。此时,选择你需要 Travis 帮你构建的仓库,打开仓库旁边的开关。一旦激活了一个仓库,Travis 会监听这个仓库的所有变化。

设置

选择好要进行持续集成的仓库之后,然后指定分支,在 setting 里选择 Build only if .travis.yml is present,因为要进行提交部署,所以要在 Github 里生成 personal access token 并作为环境变量填在 Travis 里。


生命周期

Travis 具有一个完整的生命周期,从开始到结束是下面的流程。

  1. before_install:install 阶段之前执行
  2. install: 用来指定安装脚本
  3. before_script:script 阶段之前执行
  4. script: 用来指定构建或测试脚本
  5. after_failure 或 after_success:script 阶段失败(成功)时执行
  6. [OPTIONAL] before_deploy:deploy 步骤之前执行
  7. [OPTIONAL] deploy:
  8. [OPTIONAL] after_deploy:deploy 步骤之后执行
  9. after_script:script 阶段之后执行

运行流程

Travis 的运行流程很简单,任何项目都会经过两个阶段。

其中,如果不需要安装,即跳过安装阶段,就直接设为 true

Travis 每次运行,可能会返回四种状态。

一个 Hugo 的例子

下面的这个.travis.yml脚本实现的是每当想 Hugo-theme 继续 commit 时,travis 就会自动的把 exampleSite 生成为网页文件并提交到 Github 的 gh-pages 分支

sudo: required
dist: trusty
git:
  depth: false

matrix:
  fast_finish: true
branches:
  only:
  - hugo-theme              # 只有特定分支的推送才触发构建
env:                        # 设置环境变量
  - HUGO_VERSION : 0.41

install:                    # 安装hugo
  - cd $TRAVIS_BUILD_DIR    #回到初始目录
  - wget -O hugo.tar.gz https://github.com/gohugoio/hugo/releases/download/v${HUGO_VERSION}/hugo_${HUGO_VERSION}_Linux-64bit.tar.gz
  - tar -xzvf hugo.tar.gz
  - chmod a+x hugo
#after_install:

before_script:
  - cd $TRAVIS_BUILD_DIR            

script:
    - cd exampleSite
    - ../hugo version
    - ../hugo --baseUrl="https://theme.quanyin.ml" -t Blog-theme

after_success:
  - cd public
  - git config --global user.name "Quanyin Tang"
  - git config --global user.email "qytang326@gmail.com"
  - git init
  - git add .
  - git commit -m "Travis CI build"
  - git branch gh-pages
  - git checkout gh-pages
  - git remote add origin https://${GH_TOKEN}@github.com/qytang326/Blog-theme.git
  - git push -f -u origin gh-pages

参考

当前页面是本站的「Google AMP」版。查看和发表评论请点击:完整版 »