强制Git用户在工作副本中设置电子邮件地址

4

显然,可以通过以下gitconfig设置强制Git用户为每个新存储库添加电子邮件地址:

git config --global user.email "(none)"
git config --global user.useConfigOnly true

我已经完成了。我的gitconfig -l输出(截断):
core.symlinks=true
core.autocrlf=true
core.fscache=true
color.diff=auto
color.status=auto
color.branch=auto
color.interactive=true
help.format=html
diff.astextplain.textconv=astextplain
rebase.autosquash=true
http.sslcainfo=C:/Program Files/Git/mingw64/ssl/certs/ca-bundle.crt
diff.astextplain.textconv=astextplain
filter.lfs.clean=git-lfs clean -- %f
filter.lfs.smudge=git-lfs smudge -- %f
filter.lfs.required=true
filter.lfs.process=git-lfs filter-process
credential.helper=manager
core.autocrlf=true
core.eol=native
user.name=David Wright
user.email=(none)
user.useconfigonly=true

但是好像没有起作用。我可以在不设置电子邮件地址的情况下提交。提交时列出的电子邮件地址是“(none)”。
我正在使用git版本2.13.0.windows.1。
我想这样做是因为我在同一台计算机上使用两个不同的帐户。我能够在我的ssh-config文件中实现类似的设置,以应用不同的ssh密钥:
# github account
Host github.com
Port 22
HostName github.com
User git
IdentityFile <file>

但是显然Git本身没有这样的可能性。

无论如何,我希望能够强制要求为每个存储库设置用户电子邮件地址,并且我希望这是我的全局gitconfig的一部分。 我知道可以使用pre-commit钩子来实现这一点,但据我所知,此钩子需要在克隆后复制到每个存储库中,这不是我想要的。

1个回答

5
Git配置文档中解释了以下内容:

user.useConfigOnly

指示Git避免尝试猜测user.emailuser.name的默认值,而是仅从配置中检索这些值。例如,如果您有多个电子邮件地址,并希望为每个存储库使用不同的电子邮件地址,则在全局配置中设置此配置选项为true并提供名称后,Git将提示您在新克隆的存储库中进行新提交之前设置电子邮件。默认值为false

在类Unix系统(Linux,macOS等)上,当未设置user.email时,Git尝试通过连接操作系统用户名、@和主机名来生成电子邮件地址。

通过将user.useConfigOnly设置为true,可以抑制此行为,Git仅使用在配置文件中找到的user.email的值,如果有的话。

由于您已将(none)设置为user.email,因此Git将其用作提交者电子邮件地址。

使用git config --global --unset user.email将其删除,Git将开始要求您为每个未设置user.email的存储库(新建或现有)输入电子邮件地址(或至少会抱怨user.email未设置)。


1
真是太神奇了,解决问题的方法竟然如此简单,尽管我花了数小时来弄清楚自己错在哪里。我查看的其他资料都说要将 user.email 设置为 "(none)",但感谢您明确地取消了电子邮件地址,这种方法居然奏效了,尽管我使用的是 Windows 操作系统。 - David Wright
然而,git 不知道选项“-g”和命令“unset”,我不得不使用“git config --global --unset user.email”。 - David Wright
1
“--global --unset” 是正确的方式。在我的回答中犯了错误,现在已经修正了。感谢您指出这一点。 - axiac

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接