Git Multi-Workspace Configuration

git; workspace
252 words

To configure different Git accounts for different workspace paths on one device, you can use the following method to solve it once and for all.

includeIf

This method differs only in path syntax across different platforms.

macOS

Add the following configuration content to the /Users/<username>/.gitconfig file:

# GitHub
[includeIf "gitdir:~/Work-Space/Personal/GitHub/"]
  path = .gitconfig-github

# JihuLab
[includeIf "gitdir:~/Work-Space/Personal/JiHuLab/"]
  path = .gitconfig-jihulab

# Work
## your work path
[includeIf "gitdir:~/Work-Space/Company/xxx/"]
  path = .gitconfig-company-xxx
  1. gitdir:~/Work-Space/Personal/GitHub/ specifies the workspace path. If your workspace path is ~/Work-Space/Personal/GitHub/, then use gitdir:~/Work-Space/Personal/GitHub/.

    • Notes:
      1. Do not add a space between gitdir: and the following path, otherwise the configuration will fail.
      2. The path must end with /, otherwise the configuration will fail.
  2. path = .gitconfig-github specifies the configuration file path for that workspace. If your workspace configuration file is directly under /Users/<username>/, just write path = .gitconfig-github, which is also recommended for easier management.

    • Add the following configuration content to the .gitconfig-github file. The filename is not restricted; just make sure you can find it.

      [user]
        name = <username>
        email = <username>@gmail.com

workspace

This is a method I discovered while using GitHub Copilot to write this document...

git config --global --add workspace.path /Users/<username>/workspace
git config --global --add workspace.name <workspace name>
git config --global --add workspace.gitconfig /Users/<username>/workspace/<workspace name>/.gitconfig

Looking at the command content, it specifies each workspace's path/name/config in the global gitconfig file. This is actually similar to the includeIf method above.

Theoretically it should work, but it needs verification.

Common configs

Here are some commonly used configs:

[pull]
# When pulling, use merge instead of rebase for merging branches
  rebase = false
[init]
# Set default branch name
  defaultBranch = main