拿到新电脑或者初次使用 Git 时会要求配置提交信息,比如用户 name 和 email,官方文档告诉我们通常的做法是:
git config --global user.name "public_user" git config --global user.email "public_user@example.com"
这是全局的配置,所有的仓库都会默认使用这个用户名和邮箱。要是想让某个特殊仓库设置不同的用户名和邮箱该怎么办?我们通常可以找到的做法是:从命令行进入该仓库的根目录,然后配置参数改为 --local
:
cd ~/PrivateProjects/SecretRepository git config --local user.name "private_user" git config --local user.email "private_user@example.com"
这个时候该仓库的 Git 提交用户将变为 private_user,这个方法会在仓库下的 .git/config
文件中写死刚刚设置的用户名和邮箱。
这样看上去并没有什么不妥,但是当我们每新加一个特殊仓库就要手动敲两次 git config xxx 还是显得太繁琐,那么可不可以针对不同文件夹下的仓库进行批量统一配置 Git 用户名和邮箱呢?
其实是可以的!Git 的配置也是可以像 Nginx 那样使用 include 的方式包含不同的配置文件。
还是上面的需求,全局的默认的 Git 用户希望设置为 public_user,~/PrivateProjects/
文件夹下的所有仓库用户名希望设置为 private_user。
.gitconfig
文件通常是在根目录下,不同系统位置可能有差异。
cat ~/.gitconfig
原始配置信息大概是这样的:
[core] excludesfile = /Users/computerUserName/.gitignore_global [user] name = public_user email = public_user@example.com [commit] template = /Users/computerUserName/.stCommitMsg
配置文件中的 [user]
字段就是我们全局配置的用户名和邮箱,我们需要把 ~/PrivateProjects/
文件夹下的所有仓库的用户都设置为 private_user 可以 vim .gitconfig
并在其末尾添加一个 includeIf
条件:
[core] excludesfile = /Users/computerUserName/.gitignore_global [user] name = public_user email = public_user@example.com [commit] template = /Users/computerUserName/.stCommitMsg [includeIf "gitdir:~/PrivateProjects/"] path = .gitconfig-private
然后我们在 .gitconfig
文件同级的目录下新增文件 touch .gitconfig-private
并添加以下配置内容:
[user] name = private_user email = private_user@example.com
保存退出,重启终端,就可以实现对不同文件夹仓库使用不同 Git 用户名和邮箱了。
这里很常见的一个是问题是:很多人习惯将自己公司内的 ID 和公司邮箱设置为全局,当我们偶尔要向外网贡献开源时,容易忘记设置成其他的用户名,提交后已经带上全局的用户信息,如果已经 push 到远端,很容易暴露自己的 ID 和邮箱到外网。
这种情况可以将私密仓库(工作)和开源仓库(公开)分开文件夹设置,当往开源仓库文件夹添加任何仓库和提交都不用担心会在外网暴露自己的 ID 和公司邮箱信息了。
除了广告和敏感话题言论之外,可以畅所欲言。 | |
为自己起个简短易记的名字。 | |
方便我可以联系到你,绝对不会被公开。 | |
你的个人主页,链接会加在昵称上方便大家访问。 |