Skip to main content

Applying Different Git Configurations by Environment

· 2 min read
Haril Song
Owner, Software Engineer at 42dot

TL;DR

  • The includeIf syntax allows you to apply git configuration files only when specific conditions are met.
  • Useful for separating work and personal environments.

Problems

  • Work and personal development environments are separate.
  • However, the global git config is set based on the personal environment, causing personal settings to overwrite work settings when syncing configuration files with chezmoi.
  • How can work and personal environments be stably separated?

Solution

Git provides a way to apply different configuration files based on conditions for such cases. This is includeIf. include is like modularization, including external files in the git configuration, and by applying a conditional expression, the configuration file is included only when specific conditions are met.

Some companies have rules that check email and name upon commit, and if these are not followed, commits can be rejected.

# ~/projects/company
git config --get user.email
# songkg7@gmail.com <- If a personal account email is set instead of the company email, the commit will be rejected.

Let's configure user.name and user.email to be set to the company account. First, create a file named ~/.gitconfig-work and define the necessary settings as follows.

# ~/.gitconfig-work
[user]
name = kyungkeun.song
email = kyungkeun.song@42dot.ai
# ~/.gitconfig OR ~/.config/git/config
[includeIf "hasconfig:remote.*.url:git@ssh.gitlab.42dot.ai:**/**"]
path = ~/.gitconfig-work

[includeIf "gitdir:~/projects/42dot/"]
path = ~/.gitconfig-work

The top setting includes the ~/.gitconfig-work configuration if the git remote path is set to the defined path. The bottom setting is directory-based, including ~/.gitconfig-work if git is called within the defined directory. Both settings are defined together to prevent any unforeseen rule violations.

note

Personally, I prefer not to have configuration files scattered in the HOME directory, so I prefer to set them under ~/.config/.

After accessing the git directory of the defined path and checking user.name or email,

you can see that the personal settings are applied before the .git folder is created, and the moment the .git folder is created, includeIf is triggered, and the work settings are applied.

Conclusion

For companies that allow remote work, there may be cases where you have to use personal equipment for work. This can be very useful in such situations.