Gitのリポジトリごとにコミット時の名前とメールアドレスの設定を促す方法

2018.01.31

この記事は公開されてから1年以上経過しています。情報が古い可能性がありますので、ご注意ください。

事業開発部の野村です。本日はGitのちょいネタで。

個人的なことですが、同じ端末で複数のプロジェクトのGitリポジトリを使用していると、コミットに表示されるAuthor情報は各プロジェクトごとに適した名称user.name・メールアドレスuser.emailを設定したくなります。

グローバルの.gitconfigや環境変数でuser.nameuser.emailを設定していて、うっかり関係ないプロジェクトでその名称やアドレスを利用しないための設定をご紹介いたします。

実行環境

  • macOS High Sierra 10.13.2
  • Git 2.15.1

設定方法

グローバル設定のuser.useConfigOnlyをtrueにすることで、グローバル設定も含め明示的にuser.nameuser.email指定していないとコミットができなくなります。

※Gitバージョン2.8からこの設定が可能となります。詳細はGit 2.8 has been releasedをご参照ください。

$ git config --global user.useConfigOnly true

リポジトリごとに明示的にuser.nameuser.emailを指定したい場合は、グローバル設定を削除します。

$ git config --global --unset user.email
$ git config --global --unset user.name

これで、user.nameuser.emailを指定しない状態でとあるリポジトリにコミットを入れようとすると、以下のように*** Please tell me who you are.から先の内容が表示され、コミットは中断されます。

$ git commit -m "first commit"

*** Please tell me who you are.

Run

  git config --global user.email "you@example.com"
  git config --global user.name "Your Name"

to set your account's default identity.
Omit --global to set the identity only in this repository.

fatal: no email was given and auto-detection is disabled

上記で表示された通り、git configコマンドでuser.nameuser.emailを設定します。 ※リポジトリごとに設定する場合は、--globalオプションは付けません。

$ git config user.email "you@example.com"
$ git config user.name "Your Name"

再度コミットを実行します。

$ git commit -m "first commit"
[master xxxxx] first commit

今度はコミット成功しました。git logコマンドでコミット履歴を確認すると、Authorにuser.nameuser.emailもちゃんと上記で指定したものが表示されていることが確認できます。

$ git log
commit xxxxx (HEAD -> master)
Author: Your Name <you@example.com>
Date:   Wed Jan 31 14:20:59 2018 +0900

    first commit

おわりに

複数のアカウントを持つ方には特に効果的な方法かと思います。ぜひお試しください!

それでは。