LoginSignup
220
213

More than 5 years have passed since last update.

git hookでサイトを更新、やってみた

Last updated at Posted at 2013-07-27

gitで自鯖のレポジトリにpushがあったら、
同じく自鯖にあるhtmlを更新したい。

(github-hookはちょっと前にやったけど、こっちは初めてだった)

git hook

git hookは、gitが持っている「コミットされたらなんかする」系の仕組み。

開発環境側で「コミットする直前」とか、
サーバーの側で「プッシュされた直後」とか、
いろんなタイミングで、決まったshell scriptを実行できる。

shell scriptは、.git/hooksに置く仕組みになっている模様。

今回は、この サーバーサイドフックの、 post-receiveを使ってみる。

設定する

クライアントサイドでやる作業はなし。

サーバー側でやる作業はだいたいこんな感じ。

# gitレポジトリへ移動
cd git/my-website.git

# post-receiveのスクリプトを設置
vi .git/hooks/post-receive

# 実行権限付ける
chmod +x .git/hooks/post-receive

スクリプトは、今回はこのくらいシンプルに。
--git-dir=.gitは付けないと怒られました。

#!/bin/sh

cd /home/fnobi/sites/my-website
git --git-dir=.git pull

これで完了。
 
git/my-website.gitへpushがあったら、
/home/fnobi/sites/my-websiteに設置してあるhtmlが自動更新されるようになりました。わーい!

成功したかどうかの確認

hookのスクリプトが失敗したときのログとか、どこに出るのかなぁと思っていたら、
pushしたとき手元に出てた。

"remote:"っていう行。

% git push
Counting objects: 11, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (6/6), done.
Writing objects: 100% (6/6), 631 bytes, done.
Total 6 (delta 3), reused 0 (delta 0)
remote: fatal: Not a git repository: '.'
To sasyugo:git/bukko-music-children.git
   f225eab..f7932b2  master -> master

うまく行ったときは、ちゃんとそういうログが出てますよ。

remote: From /home/fnobi/git/my-website
remote:    bbec307..8becb96  master     -> origin/master
remote: Updating bbec307..8becb96
remote: Fast-forward
remote:  index.html             |    4 ++++
remote:  src/ejs/index.html.ejs |    4 ++++
remote:  2 files changed, 8 insertions(+), 0 deletions(-)

べんりだなぁ。

まとめ

クライアントサイドフックで、コミットメッセージに「バルス」が含まれてるかどうかを検知して、
含まれてたらレポジトリを破壊するやつとかあって笑った。

そういえばコミットした瞬間の顔を撮影するやつとかもあったし、
いろんなことできそう。

参考

220
213
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
220
213