Git: automatically set and use multiple commit identities

Git: automatically set and use multiple commit identities

Sure, git is great. Sure it is possible to use multiple commit identities in git - just set local per-repo variables. If it weren't for the fact that chances of forgetting about it is about 99.9%.

Problem context

When installing git, it is required to configure a username and an email that end up in commit logs:

commit b8e77cefcceccddbc74cb13348ccc51d9128872f
Author: Alan Franzoni <username@franzoni.eu>
Date:   Thu Aug 3 16:35:53 2017 +0200

    Drop fc24, add fc26 support

I've got a work computer, and a personal one, but I often do some work from my own machine, and sometimes (i.e. during lunch breaks or commuting) I do some personal-related work from my work machine. So, when I clone a personal project on my work machine or vice-versa, then commit anything, I end up with mixed up work-related email & usernames.

Sure, nothing tragic, but annoying - especially if CI systems pickup commit logs for sending error mails, and I don't realize I've broken a build until it's too late.

The stupid but effective solution

On my personal workstation, I set my personal info for the global config, then override my git executable this way:

#!/bin/bash
GIT_BIN="/usr/local/bin/git"
# include the trailing slash, not a leading one for ssh/https compatibility
GITHUB_ORGNAME="MyMightyOrganization/"
OVERRIDE_USERNAME="Alan Franzoni"
OVERRIDE_EMAIL="alan@mymightyorganization.com"
if [ "$1" != "clone" ] || grep -v "${GITHUB_ORGNAME}" <<< "$@" ; then
	${GIT_BIN} "$@"
	EXIT_CODE="$?"
	exit ${EXIT_CODE}
fi

shift

${GIT_BIN} clone --config user.name="${OVERRIDE_USERNAME}" --config user.email="${OVERRIDE_EMAIL}" "$@"
EXIT_CODE="$?"
exit ${EXIT_CODE}

I leverage the fact that it's possible to set per-repository config values that override global ones, and I hook into the clone command and set those values at clone time, so I don't risk forgetting about it. Since it's a repository property that gets set, it will work in other clients, GUIs or IDEs as well.

Photo by Andre Hunter