git pullでファイルに変更があったら特定のコマンドを実行する。

最近ガッツリnode.jsのプロジェクトを行っているんですが、チームで開発しててよくあるのが、git pullした後にpackage.jsonbower.jsonが変更されている事に気づかず、 そのまま起動してしまい、モジュールが足りてなくて動作しないって事です。

多分コレってnode.jsに限らずrubyとかperlとかphpとかpythonとか何でもあると思うんです。もうすぐ、2014年度です、運用でpullしてエラーが出たらnpm install/cpanm/bundle installしましょうとか言うのは辞めましょう。*1

git pullしたら変更されたファイルの一覧から 対象のファイルが変更されているかどうかを認識して、特定のコマンドを自動で実行するためのコマンド、hookinを作りました。

Getting started

npmが入っているなら超簡単で、

$ npm install hookin -g

で入れて

$ cd <project_root>
$ hookin <チェック対象ファイル> <実行コマンド>

ってやれば/.git/hook/post-mergeにチェック対象のファイルとそのファイルが更新された時に実行されるコマンドが記述されます。

例:

$ hookin package.json "npm install && npm prune"
$ hookin bower.json "bower install && bower prune"

作ったらpackage.jsongithub上で変更を入れてみましょう。package.jsonに変更があったら勝手にnpm install && npm prune が実行されます。(.gitフォルダが有ることが前提なので、git initかgit cloneでgit プロジェクトである必要があります。)

CREDITS

hookin を実行すると、.git/hook/post-merge以下に下記のようなファイルを作ります。

#/usr/bin/env bash
#MIT © Sindre Sorhus - sindresorhus.com
# forked by Yosuke Furukawa

#changed_files checker
changed_files="$(git diff-tree -r --name-only --no-commit-id ORIG_HEAD HEAD)"

check_run() {
  echo "$changed_files" | grep --quiet "$1" && eval "$2"
}
# package.json
check_run package.json "npm install && npm prune"
# bower.json
check_run bower.json "bower install && bower prune"


MITライセンスで明記されているように、これの元ネタはsindresorhusがgistに投稿してた以下のスクリプトから派生したものです。

https://gist.github.com/sindresorhus/7996717

@sindresorhus++

*1:もしかしたら僕の知らない既に発明された対策があるのかもしれないので、そういう場合は遠慮なく教えて下さい。

*2:名前の由来は腹筋から取りました。