LoginSignup
2

More than 5 years have passed since last update.

gitのpre-commit hookを使ってuser.nameやuser.emailが未設定だったらコミットを弾く

Last updated at Posted at 2017-03-12

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.

とメッセージが出てコミットが失敗するようになる(既存のレポジトリには反映されないので注意)。

参考

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
2