Gitで新しいレポジトリにコミットするときにうっかりuser.nameやuser.emailの設定を忘れて、意図しない名前やメールアドレスでコミットされてpushしてしまう、ということを結構やってしまう。
そこで、pre-commit hookを使ってuser.name、user.emailが未設定だったらコミットを弾くようにした。
環境
- Mac OSX
- Git 2.11.1
特定のレポジトリではなく、PC上で扱う全てのレポジトリのコミットをhookするため、グローバルの.gitテンプレートディレクトリを準備する。
ディレクトリを作成
mkdir -p ~/.git_template/hooks
.gitのテンプレートに.git_templateを指定する。
git config --global init.templatedir ~/.git_template/
これで新たにgitレポジトリを作ったりcloneすると.git_templateディレクトリの設定が有効になる。
hookファイル作成
vi ~/.git_template/hooks/pre-commit
内容は以下のようにする。
#!/bin/sh
if [ -z `git config user.name` ] || [ -z `git config user.email` ]
then
cat <<\EOF
Error: Your name or email address is empty.
commit fails.
EOF
exit 1
fi
hookファイルのパーミッション変更
パーミッションを変えて実行可能にする。
これをしないとhookされない。
chmod +x ~/.git_template/hooks/pre-commit
結果
以上の設定をすると、以降作ったりcloneしてきたレポジトリでuser.nameやuser.emailが設定されていない場合に
Error: Your name or email address is empty. commit fails.
とメッセージが出てコミットが失敗するようになる(既存のレポジトリには反映されないので注意)。
参考
- 「git-commit前にsyntaxチェックする」 http://qiita.com/ymko/items/9209aa8ed811db795024
- 「git hook のテンプレート」 http://please-sleep.cou929.nu/git-init-templatedir.html