目标:可以使用相同的机器用于工作和个人的多个账户进行 Git 提交,而无需手动重置你的配置。
Git 的 git config 命令可以为 git 设置用户名、邮箱等全局选项和配置。其有很多选项和配置,其中一个就是 includeIf 选项,它能够帮助我们在拥有多个 git 用户的时候可以灵活的切换到对应的用户上,且使用起来非常方便。
比如说,你既是全职的开发者,或者经过多家公司任职,又或在业余时间适用自己账号自我提升。在这种情况下,大多数人都不想为两个或多个角色使用一个共同的配置,或者,至少他们肯定希望保持配置的某些部分是不同的,尤其是当他们在两个角色中使用同一台计算机时。
# includeIf 的基本概念
includeIf 是 git 2.13 版本引入的一个新特性。
它允许我们在配置文件中根据不同的条件来加载不同的配置文件,这个功能的语法如下:
[includeIf "<condition>"]
path = <path-to-config>
其中 <condition> 可以是 git 的配置,比如 gitdir:<git-directory>,也可以是通过执行命令得到的输出。当 <condition> 满足时,会加载指定的配置文件。
# 适用 includeIf 管理多账户
我的情况就是这样,所以我在 Git 配置中保留了两组不同的邮件 ID。这样一来,在我工作场所的项目仓库中提交的内容就会使用我工作的邮件 ID,而在我个人 GitHub 帐户中提交的内容则使用我个人的邮件 ID。
以下是我的全局配置(维护在 $HOME/.gitconfig)中的一个片段,我将在下文中介绍。
[user]
name = chaos
email = default@email.com
[includeIf "gitdir/i:~/IdeaProjects/A/"]
path = ~/.gitmulticonfig/.gitconfig-A
[includeIf "gitdir/i:~/IdeaProjects/B/"]
path = ~/.gitmulticonfig/.gitconfig-B
[includeIf "gitdir/i:~/IdeaProjects/C/"]
path = ~/.gitmulticonfig/.gitconfig-C
[includeIf "gitdir/i:~/IdeaProjects/D/"]
path = ~/.gitmulticonfig/.gitconfig-D
[alias]
lm = log --no-merges --color --date=format:'%Y-%m-%d %H:%M:%S' --author='chaos' --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Cblue %s %Cgreen(%cd) %C(bold blue)<%an>%Creset' --abbrev-commit
lms = log --no-merges --color --stat --date=format:'%Y-%m-%d %H:%M:%S' --author='chaos' --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Cblue %s %Cgreen(%cd) %C(bold blue)<%an>%Creset' --abbrev-commit
ls = log --no-merges --color --graph --date=format:'%Y-%m-%d %H:%M:%S' --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Cblue %s %Cgreen(%cd) %C(bold blue)<%an>%Creset' --abbrev-commit
lss = log --no-merges --color --stat --graph --date=format:'%Y-%m-%d %H:%M:%S' --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Cblue %s %Cgreen(%cd) %C(bold blue)<%an>%Creset' --abbrev-commit
默认的账户和邮箱配置为 chaos 和 default@email.com,A、B、C、D4 个不同路径对应 4 个不同的配置文件。
举例,在 ~/.gitmulticonfig/.gitconfig-A 文件中,设置的账户设置配置:
[user]
name = nameA
email = your.A.email@example.com
# 结语
这样,当我们在 ~/IdeaProjects/A/ 目录下执行 git 命令时,git 就会自动加载 ~/.gitmulticonfig/.gitconfig-A 文件,并适用工作账户的配置。