社内やオープンソースのプロジェクトに並行して参加していると、gitconfig の user.name や user.email をリポジトリごとに切り替えたくなることがある。リポジトリを作るたびに git config user.name "My Name" すればいいのだが、 user.name が存在しないか空文字列だと環境変数 NAME の値を暗黙的に使う仕様になっているため、設定をうっかり忘れてしまうとなかなか気づけない。名前やメールアドレスを間違えたまま何度もコミットしてしまうと修正が厄介である。
Git 2.8以上
最近の Git で設定忘れを未然に防ぐには git config --global user.useConfigOnly true を実行する。これを設定するとユーザー情報について環境変数を暗黙に参照することがなくなる。グローバルな gitconfig で user.name と user.email を設定してあるなら削除しておく。こうすることで、各リポジトリ単位で user.name と user.email を設定することを強制できる。
$ git config --global user.useConfigOnly true
$ git config --global --unset user.name
$ git config --global --unset user.email
$ cd /path/to/my_repo
$ git config user.name "My Name"
$ git config user.email "me@example.com"
Git 2.7以下
以前の Git では pre-commit フックで設定の値を検証することになる。 pre-commit フックは git commit の直前に実行され、終了ステータスが非ゼロであれば git commit は中止される。
# !/bin/sh
if [ -z "`git config --local user.name`" ]; then
echo "fatal: user.name is not set locally"
exit 1
fi
if [ -z "`git config --local user.email`" ]; then
echo "fatal: user.email is not set locally"
exit 1
fi
フックスクリプトを実行可能にし、 $my_repo/.git/hooks ディレクトリに配置する。
$ chmod a+x pre-commit
$ mv pre-commit $my_repo/.git/hooks
これで、 $my_repo リポジトリにおいて user.name と user.email が設定されていなければ git commit が失敗するようになった。
$ git commit -m "Add some files"
fatal: user.name is not set locally
$ git config user.name "My Name"
$ git config user.email me@example.com
$ git commit -m "Add some files"
[master deadbeef] Add some files
...
pre-commit フックスクリプトをテンプレートに入れれば、新たに git init か git clone したリポジトリにはフックスクリプトがコピーされるようになる(参考:gitのhooksを管理する(自分用テンプレートを使う))。