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

持续集成

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

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

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

Travis CI

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

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

选择仓库

选择仓库

设置

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

设置

设置

personal access token

personal access token

生命周期

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 的运行流程很简单,任何项目都会经过两个阶段。

  • install 阶段:安装依赖
  • script 阶段:运行脚本

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

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

  • passed:运行成功,所有步骤的退出码都是0
  • canceled:用户取消执行
  • errored:before_install、install、before_script有非零退出码,运行会立即停止
  • failed :script有非零状态码 ,会继续运行

一个 Hugo 的例子

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

 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
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 "i@imtqy.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

参考