Publishing gh-pages with Travis-CI

The solution at nodemeatspace.com


All my latest articles can be found at the RisingStack blog.

At node-meatspace we faced one recurring task every time a pull request was merged: we had to run our build script (which builds html from markdown), and push the changes back to GitHub.

Now we only have to push the merge button, and the gh-pages branch updates auto-magically. But how?

Using Travis. The entry point of the Travis execution is the .travis.yml file. As our build script is written in Node, we have to enable it. Also we have to specify what script to run:

language: node_js
node_js:
- '0.10'
script: npm run-script deploy
env:
global:
- GH_REF: github.com/knode/node-meatspace.git
- secure: RIbIq8hI153J5trRa........

In the env section we have to set our repo url and a secure token. This is how you can create yours:

  1. Go to GitHub.com -> Settings -> Applications -> Personal Access Tokens — > Create new token, and copy it to your clipboard
  2. Let’s generate our secure token, and copy it to the .travis.yml file
npm install travis-encrypt -g
travis-encrypt -r [repository slug] -k GH_TOKEN -v [the token you created before]

Congrats, your .travis.yml is done! ☺

As in the script section of the travis file we wrote npm run-script, it will look it up in our package.json file. Make sure you have a script section in it:

.... 
"scripts": {
"deploy": "./deploy-ghpages.sh"
},
....

The only thing we have left is to write our deploy-ghpages.sh file!

#!/bin/bash
rm -rf out || exit 0;
mkdir out;
node build.js
( cd out
git init
git config user.name "Travis-CI"
git config user.email "travis@nodemeatspace.com"
cp ../CNAME ./CNAME
cp ../countryiso.js ./countryiso.js
git add .
git commit -m "Deployed to Github Pages"
git push --force --quiet "https://${GH_TOKEN}@${GH_REF}" master:gh-pages > /dev/null 2>&1
)

This snippet just creates a directory (called out), then runs the build.js, which puts its output into that directory. After that, we initizalize a new git repository in that directory, copy some necessary files from the parent directory, then push all the things to the gh-pages branch. Notice the > /dev/null 2>&1 on the end! It prevents any unwanted sensitive information to be recorded in the travis logs (if push fails for any reason).

I hope it all makes sense, and helps your open-source project to build the documentation/readme easier.

Inspired by @madbence and @oroce, thank you guys!