DEV Community

olistik
olistik

Posted on • Updated on

Set commit signing per git repository

When dealing with multiple git identities it's sometimes useful to perform a custom setup for commit signing, for each repository:

λ gpg --list-keys my@email.com
pub   dsa3072 2016-06-23 [SC]
      XXYYZZXXYYZZXXYYZZXXYYZZXXYYZZXXYYZZXXYY
uid           [ unknown] olistik <my@email.com>
sub   elg3072 2016-06-23 [E]
Enter fullscreen mode Exit fullscreen mode

It is also possible to extract the the value with a bit of scripting (Ruby in this case):

λ gpg --list-keys --fingerprint --with-colons my@email.com | ruby -e "puts STDIN.read.lines.grep(/^fpr/)[0].match(/^.*:([0-9A-Z]+):.*/)[1]"
XXYYZZXXYYZZXXYYZZXXYYZZXXYYZZXXYYZZXXYY
Enter fullscreen mode Exit fullscreen mode

And then update the git settings within the repository's directory:

λ git config user.signingkey XXYYZZ
λ git config commit.gpgsign true
λ git config user.email "my@email.com"
λ git config user.name "olistik"
Enter fullscreen mode Exit fullscreen mode

Here's a convenience script that can be invoked to setup commit signing:

#!/bin/bash

set -e

GPG_KEY=$(gpg --list-keys --fingerprint --with-colons my@email.com | ruby -e "puts STDIN.read.lines.grep(/^fpr/)[0].match(/^.*:([0-9A-Z]+):.*/)[1]")
git config user.signingkey $GPG_KEY
git config commit.gpgsign true
git config user.email "my@email.com"
git config user.name "olistik"
Enter fullscreen mode Exit fullscreen mode

Here are the versions of my environment:

λ ruby -v
ruby 2.6.3p62 (2019-04-16 revision 67580) [x86_64-darwin18]
λ gpg --version
gpg (GnuPG) 2.2.17
λ git --version
git version 2.20.1 (Apple Git-117)
Enter fullscreen mode Exit fullscreen mode

Issues when committing

If you encounter the following error after a commit command:

error: gpg failed to sign the data
fatal: failed to write commit object
Enter fullscreen mode Exit fullscreen mode

You could try to update the GPG_TTY environment variable and re-run the commit command:

λ export GPG_TTY=$(tty)
Enter fullscreen mode Exit fullscreen mode

It it succeeds, then you can persist this change by putting this line into your .zshrc (or .bashrc according to the shell you are using).

Top comments (0)