I have a work computer where
git commit --author=...
I've had the same issue for a while: I want different email addresses to be used for work projects, open source projects, personal projects, and so on, and I want it to be set automatically based on folder structure rather than remembering to do it per repo.
This solution will automate the process of setting the email on a per-repo basis. One assumption I'll make is that you have divided your projects into folders based on owner (or rather, based on the email address you want to use). E.g.:
code/ work/ (All subfolders use work email.) open-source/ (All subfolders use open source email.) personal/ (All subfolders use personal email.)
According to the Git Docs, post-checkout hooks are run after a
git clone command, so we can use a global post-checkout hook to set the email per-repo.
git config --global init.templatedir '~/.git_template'
Then create that folder and a subfolder called
hooks. Add the following bash script as
#!/bin/bash # Automatically set Git config values from parent folders. dir=$(pwd) while [ "$dir" != "/" ] do # First directory would be the new Git repo, so skip it. dir=$(dirname $dir) if [ -f $dir/.gitconfig ] then for config in $(git config --file $dir/.gitconfig --list) do var=$(echo $config | cut -d = -f 1) value=$(echo $config | cut -d = -f 2) actual=$(git config $var) if [ "$actual" != "$value" ] then git config $var $value fi done fi done
(You can also find this script at my GitHub repo
Now, for each of the folders I mentioned, add a
.gitconfig file with the appropriate email. Do e.g.:
git config --file /mnt/data/code/open-source/.gitconfig user.email "firstname.lastname@example.org"
Now, as long as you
git clone into the right folder, your repos will automatically have the correct email address set in the local config.
For those repos you have already cloned, you can just
cd to the relevant Git directory and call
~/.git_template/hooks/post-checkout directly to update the email.
You can add whatever config you want to the
.gitconfig files, and those settings will also be added to the repo.
Currently it searches the directories from
/, when it should reverse the order. This shouldn't be hard to fix, so I'll add that to my solution at some point.
The script will be executed after every
checkout, not just after initial clone, so there may be a small performance penalty. However, the conditionals ensure that it won't set the value if it has already been set, or if no
.gitconfig file is found.
Due to #2, there isn't a way to override the settings with repo-specific values.