Each git commit has a field called Author which consists ‘user.name’ and ‘user.email’.
We usually set these variables once, after installing git, with git config --global
so that each repo gets the variables from the global definition.
We can also set them locally for a specific repo without using the --global
keyword.
Global configs can be found at ~\.gitconfig
and local config path-to-repo\.git\config
.
Partial Configurations
Sometimes you may need to set up different email/user.name for different repos. Usually when working on both personal and work projects in the same computer. In that case, you may choose configure email and username manually for each repo but this is boring and open to errors. Luckily, there is a better way.
- Add as many gitconfig as you need:
~\.gitconfig-work
,~\.gitconfig-github
etc. - Define configurations in these partial config files.
[user]
email = 43188411+mertbakir@users.noreply.github.com
- Then in the main config at
~\.gitconfig
, define which partial configuration will be applied to which directory.
[includeIf "gitdir:Desktop/projects/work"]
path = .gitconfig-work
[includeIf "gitdir:Desktop/projects/github/"]
path = .gitconfig-github
Private Commit Email
Git services like GitLab and GitHub is using the email you’ve configured in your account settings and the email on the commits to link a commit with your account. So the email address we use for commits is important. What happens if we don’t want to use that email anymore or what if we don’t the email adress to be public. In this case we can use a non-reply commit e-mail. Both GitLab and GitHub provides such feature.
Edit Email for Previous Commits
If you want to edit email address for the previous commits this means you’ll overwrite the git history. In other words, the commit hashs will be different after the process. So, you’ll need to use git push --force
.
I suggest creating a test repo and test it safely.
Add the line below to ~\.gitconfig
[alias]
change-commits = "!f() { VAR=$1; OLD=$2; NEW=$3; shift 3; git filter-branch --env-filter \"if [[ \\\"$`echo $VAR`\\\" = '$OLD' ]]; then export $VAR='$NEW'; fi\" $@; }; f"
Then use:
git change-commits GIT_AUTHOR_EMAIL "old_email_address" "new_email_address_here"
You can also use it change other properties like GIT_AUTHOR_NAME
. One good thing is, this process won’t change the commit date only the property you’ve passed.
If you get an error like ‘backup already exists’, you may use: git update-ref -d refs/original/refs/heads/master
.
The solution is from stackoverflow. I recently used this method and wanted to take note.