リポジトリ毎に異なる user.email で commit に署名したい

🔑
note

一つの環境でいくつかのリポジトリを扱う時に、 user.email を分けたいケースがあったのでその状態で commit にそれぞれに対応する署名がされるようにしたい。

まず、必要な分だけ鍵を作成して、GitHub の SSH and GPG keys から Signing keys へ登録する。

ssh-keygen -t ed25519 -C "yaakaito+foo@gmail.com" -f id_ed25519_yaakaito_foo
ssh-keygen -t ed25519 -C "yaakaito+bar@gmail.com" -f id_ed25519_yaakaito_bar

~/.gitconfig に以下のように設定する、ここで user.signingkey は設定しないようにする。

[gpg]
        format = ssh
[gpg "ssh"]
        allowedSignersFile = /Users/yaakaito/.ssh/allowed_signers
[commit]
        gpgsign = true

~/.ssh/allowed_signers に、それぞれのメールアドレスに対応する公開鍵を並べる。

yaakaito+foo@gmail.com ssh-ed25519 <public_key> yaakaito+foo@gmail.com
yaakaito+bar@gmail.com ssh-ed25519 <public_key> yaakaito+bar@gmail.com

この状態で適当なリポジトリで commit しようとすると、次のようなエラーになるはず。

fatal: either user.signingkey or gpg.ssh.defaultKeyCommand needs to be configured

リポジトリに対して使いたい user.emailuser.signingkey を設定する。

git config user.email yaakaito+bar@gmail.com
git config user.signingkey ~/.ssh/id_ed25519_yaakaito_bar.pub

この状態で適当な commit が作れれば OK。リポジトリで設定するまで commit が通らないはずなので、設定漏れも防げるはず。実際に付いているかは git log --show-signature で確認できる。

yaakai.to