DEV Community

loading...

Per-directory git config

davidjones418 profile image David Jones ・2 min read

Lets say I use my work email (david@example.org) to commit code to a GitHub Enterprise deployment, and a private email (david2864212@example.com) for personal and open source projects on GitHub.com.

I clone down work repos into one directory, named after the GitHub Enterprise host (/home/david/github.example.org/) and open source stuff into another (/home/david/github.com/).

I sign my commits with GPG so I want to make sure that I’m using the right email address or my commits will be rejected when I try to push them upstream. To do this I split my git config into three parts: a shared config in home, and per-directory configs corresponding to the two git hosts.

In the shared config I set my name (fortunately this doesn’t change) and anything else I want to share between hosts:

# ~/.gitconfig

[commit]
gpgsign = true

# ... etc ...

[user]
name = David Jones

[includeIf "gitdir:~/github.com/"]
path = ~/github.com/.gitconfig

[includeIf "gitdir:~/github.example.org/"]
path = ~/github.example.org/.gitconfig
Enter fullscreen mode Exit fullscreen mode

And then I configure my email address per host:

# ~/github.com/.gitconfig

[user]
email = david2864212@example.com
Enter fullscreen mode Exit fullscreen mode
# ~/github.example.org/.gitconfig

[user]
email = david@example.org
Enter fullscreen mode Exit fullscreen mode

Now I can switch happily between projects, and as long as I’m below one of those two directories I can be sure that I’m using the correct email address and corresponding GPG key to sign my work.

Note that this isn’t at all specific to a particular git host and there’s nothing special about the filenames or directories, I could also use a scheme like ~/.gitconfig.github or ~/work/.config/gitconfig.

Check out the manual entry on conditional includes for more details, including matching by branch which sounds like it could be useful.

Discussion (0)

Forem Open with the Forem app