How to merge different authors in Git

Fixing the past without screwing the Git history

Ali Kamalizade
CodeX

--

Photo by Jørgen Håland on Unsplash

Have you ever worked on the same codebase on different devices? For example using your company laptop as well as your private desktop machine? I have for sure! I’ve always had a dedicated GitHub account for work and my personal one.

Obviously, it makes a lot of sense using dedicated accounts instead of a shared account. Yet we don’t always do that in some contexts (e.g. when you’re the only developer in a startup). At latest when more developers are contributing code as well you should think about having a dedicated account to separate private and work usage.

Creating a dedicated account is easy but what do you with the existing Git history? It would be great if your great stats were not lost after switching to a new account, right? Take a look at the following fictional example. You’ll see two contributors yet this is the same person.

Git history could be changed but this is usually avoided. The goal is to merge different authors without changing the actual history (as that could cause side effects). In this blog post I want to share a simple solution for this situation.

gitmailmap to the rescue

Git supports the usage of a special file called .mailmap which should be ideally placed at the root of the repository. Its purpose is to map author/committer names and/or email addresses.

The command git shortlog -se can be used to view all contributors of the current Git repository. If we run this command we will get the following output:

Two contributors

Now we will merge these contributors by creating a .mailmap file in our Git repository.

# All emails used by John Doe
John Doe <john.doe@acme.org> <john.doe@gmail.com>
John Doe <john.doe@acme.org> <john.doe.123456@acme.org>

If we rerun our command after adding this file our output looks different:

One contributor

There is only one contributor called John Doe and all commits are assigned to him. We did this without altering the Git history.

Conclusion

Thanks for reading this short post about merging different authors in Git without changing the history. Have you been in this situation and needed something like this? Let me know in the comments.

--

--

Ali Kamalizade
CodeX
Writer for

Co-founder of Sunhat. Posts about software engineering, startups and anything else. 有難うございます。🚀