Hugo - Hosting on GitHub Pages

はじめに

blogをghostで運用していたんですが、GitHub Pagesでホスティングできることを小耳にはさみやってみることにしました。

GitHub Pages<username>.github.ioというリポジトリを作成してmasterブランチにhtmlファイルを配置すればよいだけというお手軽さです。ソース管理もできるしこれを使わない手はなさそうです。

htmlファイルの生成はgolangだという理由でHugoを使うことにしました。生成速度が速いとかエントリ数が増えても動作が軽いとか色々利点はあるようです。

GitHubブランチの作成

2つのリポジトリを作成します。 1. GitHub Pages用リポジトリ(<username>.github.io) 1. blog更新用リポジトリ(<username_hugo)

blog更新用リポジトリでHugoを実行し、生成されたpublicディレクトリと<username>.github.ioリポジトリをgit submoduleを使って連携させます。

道具の準備

Bash on Windows環境下にgolangとHugoをインストールします。

Install golang

Bash on Windows環境でapt-getすると古いgolangがインストールされてしまいますので、公式から最新版をダウンロードしインストールします。

curl -L -O https://storage.googleapis.com/golang/go1.7.3.linux-amd64.tar.gz
sudo tar -C /usr/local -xzf go1.7.3.linux-amd64.tar.gz
export PATH=$PATH:/usr/local/go/bin
export GOPATH=/usr/local/go

Install Hugo

公式からパッケージをダウンロードしてインストールします。

curl -L -O https://github.com/spf13/hugo/releases/download/v0.17/hugo_0.17-64bit.deb
sudo dpkg -i hugo_0.17-64bit.deb

blogサイトの作成

hugoコマンドを使って作成します。テーマはHugo Themes Siteから選びます。ここではHugo Zen をインストールします。

hugo new site <username>_hugo
cd <username>_hugo

# install theme(hugo-zen)
git clone https://github.com/rakuishi/hugo-zen.git themes/hugo-zen

リポジトリの更新

ひとまずリポジトリを更新し、GitHub Pages用リポジトリ(<username>.github.io)とsubmoduleで連携させます。

# add remote
git init
git add .
git commit -m ‘First commit.’
git remote add origin https://github.com/<username>/<username>_hugo.git

git submodule add -b master https://github.com/<username>/<username>_hugo.git public

git push origin master

blogエントリの作成

hugoコマンドで作成し、mdファイルを編集します。

hugo new hello.md

ローカルサーバーでの確認

hugo server --theme=hugo-zen --buildDrafts --watch

GitHub Pagesへデプロイ

デプロイ用のシェルスクリプトを作成し、実行します。

cat <<'_EOT_' > deploy.sh

#!/bin/bash

echo -e "\033[0;32mDeploying updates to GitHub...\033[0m"

# Build the project.
hugo -t hugo-zen # if using a theme, replace by `hugo -t <yourtheme>`

# Go To Public folder
cd public
# Add changes to git.
git add -A

# Commit changes.
msg="rebuilding site `date`"
if [ $# -eq 1 ]
  then msg="$1"
fi
git commit -m "$msg"

# Push source and build repos.
git push origin master

# Come Back
cd ..
_EOT_

chmod +x deploy.sh

これで https://.gihub.io/ に反映されました。