Gitのユーザ情報を細かく管理する

$HOME/.gitconfigをgitで管理して、エイリアスなどの設定を会社と自宅で共有したいが、ユーザ名とメールアドレスは場所によって異なるので、それらを含んだまま管理ができていなかった。

で、cloneしてきた端末ごとにユーザ情報を設定すると、git上での差分となってしまって、何かエイリアスなどを変更した際に、ユーザ情報を含まないようにコミットする必要がある。

ユーザ情報を別の設定ファイルとして切り出し、includeを使用することで上手く使い分けができる。

ユーザ情報を別ファイルに設定する

例えば$HOME/.gitignore.localというファイルにユーザ情報を設定する。

コマンドから追加するときは以下のように実行する。

$ git config --file ~/.gitconfig.local --add user.name 'Kentaro Kawano'
$ git config --file ~/.gitconfig.local --add user.email emailaddress@example.com

--file によって設定を保存するファイル名を指定できる。

内容は以下のようになる。

# $HOME/.gitconfig.local
[user]
    name = Kentaro Kawano
    email = emailaddress@example.com

別のファイルになっているだけで、Gitのための設定ファイルなので、別にユーザ情報だけではなく、端末に依存する設定を含んでもよい。

include を使用する

gitconfigで、別の設定ファイルを読み込むためにはincludeを使用する。

$HOME/.gitconfigの中でincludeを使用して別の設定ファイル($HOME/.gitconfig.local)を読み込むようにする。

# $HOME/.gitconfig
[include]
    path = .gitconfig.local

.gitconfig.local の作成忘れがたまにある

includeの対象となるファイルが存在しなくても、gitの操作を行うにあたって警告が出ることはない。なので、.gitconfig.localを作成せずに(ユーザ情報が設定されないままに)コミットをしてしまうことがある。特に端末のセットアップ直後とか。

その際には、ユーザ情報を勝手に設定したよという注意が出てくる。

Your name and email address were configured automatically based
on your username and hostname. Please check that they are accurate.
You can suppress this message by setting them explicitly:

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

After doing this, you may fix the identity used for this commit with:

    git commit --amend --reset-author

なので、.gitconfig.localを上述の手順で作成した上で、git commit --amend --reset-authorを実行するとよい。