LoginSignup
72
71

More than 5 years have passed since last update.

gitのhookを全リポジトリで共有する

Posted at

Customizing Git - Git Hooks

git hookはサーバサイドならばアクセスする全ユーザ共通にできるが、通常使うクライアントサイドのgit hookは特に共有設定などを用意することができない。
そのため、tpopeさんはctagsのタグ生成のために、git initやgit clone時に.gitのテンプレートでhooksを配布する方法をブログに書いている。

しかしこの方法では配布したgit hookを後から共通でいじりたくなってもできない。
そこで、.gitのテンプレートのhooksから~/.githooksにシムリンクを張る方式を提案する。

.gitconfigにinit.templatedirを設定

~/.gitconfig
[init]
  templatedir = ~/.git_template

gitconfigを上記のようにしておくと、~/.git_template内にファイルがあった場合git initやgit clone時に.git内にコピーが配布される。

以下のように~/.git_templateディレクトリを作成しておく。

mkdir ~/.git_template

~/.githooksへのシムリンクを作成

名前はなんでもいいが、~/.githooksを共有のgit hook用のディレクトリとして使う。
git init時に標準で作成される.git/hooksにはgit hookのサンプルが入っているので、これを共有git hookディレクトリのテンプレートに使う。

git init
mv .git/hooks ~/.githooks
ln -s ~/.githooks ~/.git_template/hooks

すでにgit cloneしているリポジトリの.git/hooksを変える

function replace-githooks() {
  if [ -e .git/hooks ]; then
    rm -rf .git/hooks
    ln -s ~/.githooks .git/hooks
  fi
}

という関数を作っておき、必要に応じて実行する。
いちいち実行するのは面倒なので、ghqのユーザーには以下のスクリプトの実行を推奨する。

for repo in `ghq list`; do
  pushd "${GOPATH}/src/${repo}" > /dev/null
  replace-githooks
  popd > /dev/null
done

ローカルフックが必要な場合

hook_name=`basename $0`
local_hook=".git/local_hooks/${hook_name}"
if [ -e $local_hook ]; then
  source $local_hook
fi

というのを~/.githooks/pre-commitに書いておくと、.git/local_hooks/pre-commitにローカルフックを書いておけばこれも使用される。
使う場合は、空の~/.git_template/local_hooksディレクトリを作っておくのがよい。

まとめ

以上の操作により~/.githooks内のgit hookを共有して使うことができる。

72
71
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
72
71