LoginSignup
254
229

More than 5 years have passed since last update.

リポジトリごとに user.name や user.email の設定を強制する

Last updated at Posted at 2013-08-28

社内やオープンソースのプロジェクトに並行して参加していると、gitconfig の user.nameuser.email をリポジトリごとに切り替えたくなることがある。リポジトリを作るたびに git config user.name "My Name" すればいいのだが、 user.name が存在しないか空文字列だと環境変数 NAME の値を暗黙的に使う仕様になっているため、設定をうっかり忘れてしまうとなかなか気づけない。名前やメールアドレスを間違えたまま何度もコミットしてしまうと修正が厄介である。

Git 2.8以上

最近の Git で設定忘れを未然に防ぐには git config --global user.useConfigOnly true を実行する。これを設定するとユーザー情報について環境変数を暗黙に参照することがなくなる。グローバルな gitconfig で user.nameuser.email を設定してあるなら削除しておく。こうすることで、各リポジトリ単位で user.nameuser.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 は中止される。

pre-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.nameuser.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 initgit clone したリポジトリにはフックスクリプトがコピーされるようになる(参考:gitのhooksを管理する(自分用テンプレートを使う))。

254
229
1

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
254
229