本地Git配置没有覆盖项目全局用户

54

我已经配置了全局的git用户,但是想要在一个单独的git项目中使用不同的用户。

在该项目中,我使用了git config --local user.name "localuser"git config --local user.email "localuser@example.com"来设置本地项目的用户和电子邮件。

但是,当我尝试推送到github上的远程库时,我会遇到以下错误:

remote: Permission to localuser/repo.git denied to globaluser.
fatal: unable to access 'https://github.com/localuser/repo.git/': The requested URL returned error: 403

以下是一些可能有助于诊断的输出:

git remote -v:

github  https://github.com/localuser/repo.git (fetch)
github  https://github.com/localuser/repo.git (push)

git config --list

user.name=globaluser
user.email=globaluser@example.com
...

git config --local --list

user.name=localuser
user.email=localuser@example.com
...

git config user.name

localuser
4个回答

43

我已经提交了我的更改,但是使用全局用户时出现了权限被拒绝的情况。随后设置本地用户没有任何作用,尽管git config user.name报告了正确的本地用户。

解决方法是(参考这个谷歌群组帖子)

git commit --amend --reset-author

我推测提交的更改附带了原始作者信息。


1
是的,这就是解决方案。所以发生的情况是,OP可能已经使用globaluser@example.com作为提交者进行了一些提交,然后更改了电子邮件地址(和可能的用户名)为localuser@example.com。因此,他不被允许使用先前的电子邮件地址推送提交。上述修改命令将更改这些提交的作者。 - John Red
这对我没有解决问题。我必须在Windows凭据管理器下更改git:https://bitbucket.org的用户名和密码。 - aj.toulan
1
这为我解释并最终解决了问题!!!我没有意识到问题不是当前的git用户,而是提交该历史记录的人。 - yuqli
如果有多个更改,您需要修复所有提交而不仅仅是最后一个。在修复了user.name和user.email之后,请尝试以下操作:git rebase -r <last good commit sha> --exec 'git commit --amend --no-edit --reset-author' && git commit && git rebase --continue && git push -f - dbaltor

14

如果你在使用GitHub时在OSX上工作,可能会遇到证书问题。你的GitHub证书将记住你的user.name和user.email,并覆盖本地配置设置。解决方法之一是转到钥匙串并删除GitHub证书。


1
Windows怎么样?我的Github全局设置仍然覆盖本地设置。 - Dijiflex

13
尝试了许多方法,花费了许多时间但都没有有效果。最终我不得不清除所有用户: git config --local --unset credential.helper git config --global --unset credential.helper git config --system --unset credential.helper 现在在推送时我会被要求输入我的GitHub凭据,我可以提供正确的用户ID和密码 :)
如果使用Windows,则还可以通过进入“控制面板\用户帐户\凭据管理器”来删除它。

不幸的是,对我来说在 Mac 上没能工作 :( - Yuseferi

2

在我的情况下,重置提交者并不起作用:

问题在于以下组合:

  • 我的默认ssh密钥id_rsa.pub是由我的全局用户设置在Github上的
  • 我的本地用户没有在Github上设置ssh密钥

因此,您的git将使用链接到全局用户的默认id_rsa

解决方案是:

  • 使用ssh-keygen生成一个新的ssh密钥,比如id_2和id_2.pub,并将此ssh密钥添加到Github中
  • git config --add --local core.sshCommand 'ssh -i <<<PATH_TO_SSH_KEY>>>'将为本地仓库设置带有新ssh密钥的ssh选项

完成。


在为工作和个人分别使用Github账户进行长时间的挣扎后,这种方法对我非常有效。 - Andy
我已经尝试了一切:1)从ssh-add -l中删除所有密钥;2)删除.ssh目录下的所有密钥文件;3)删除两个GitHub账户上的ssh密钥;4)为两个用户生成新的密钥;4)为新的密钥在GitHub上的两个账户创建新的注册;5)更改本地仓库中所有提交的作者。但是,不知何故,即使在所有这些操作之后,git仍然在本地仓库中使用全局用户密钥。"git config --add --local core.sshCommand 'ssh -i <<<PATH_TO_SSH_KEY>>>'"命令对我起到了作用。 - undefined

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