Git Multi-Workspace Configuration
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-
gitdir:~/Work-Space/Personal/GitHub/specifies the workspace path. If your workspace path is~/Work-Space/Personal/GitHub/, then usegitdir:~/Work-Space/Personal/GitHub/.- Notes:
- Do not add a space between
gitdir:and the following path, otherwise the configuration will fail. - The path must end with
/, otherwise the configuration will fail.
- Do not add a space between
- Notes:
-
path = .gitconfig-githubspecifies the configuration file path for that workspace. If your workspace configuration file is directly under/Users/<username>/, just writepath = .gitconfig-github, which is also recommended for easier management.-
Add the following configuration content to the
.gitconfig-githubfile. 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>/.gitconfigLooking 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