OSX(Mac) 系统下 git credential.helper 的位置

git / osx

最近把本地 git push 到云端的时候遇到了一个问题,git push 时显示账户和实际要使用的账户不符,这个问题是因为 OSX 系统下,credential.helper 的位置跟其他系统有别

1 问题

执行 git push 时遇到以下提示

git push -u origin master
remote: You (@username) must accept the Terms of Service in order to
perform this action. Please access GitLab from a web browser to accept these terms.
fatal: unable to access 'https://gitlab.com/username/projectname.git/':
The requested URL returned error: 403

@username 是之前另一个项目使用的用户名,不知为何,现在变成了默认用户

2 解决

2.1 确定问题

检查一下 git config

git config --list
credential.helper=osxkeychain
user.name=xxxxx
[email protected]
core.repositoryformatversion=0
core.filemode=true
core.bare=false
core.logallrefupdates=true

用户名和邮箱其实和 push 时并不一样,但是为什么不使用配置的用户名呢,很好推测,应该是第一行的 credential.helper 在作祟

2.2 定位 credential.helper

一般 credential.helper 会配置在三个地方 local, global, system,分别用以下命令查看

git config --local credential.helper
git config --global credential.helper
git config --system credential.helper

不过我们并没有找到哪里配置了 credential.helper,不过我们还有办法查看

git config --show-origin --get credential.helper
file:/Applications/Xcode.app/Contents/Developer/usr/share/git-core/gitconfig	osxkeychain

原来 xcode 下有配置了 credential.helper,我们查看一下这个配置文件

cat /Applications/Xcode.app/Contents/Developer/usr/share/git-core/gitconfig
[credential]
	helper = osxkeychain

接下来问题就简单了,删除 helper 这行(需要 sudo),再执行 push

git push -u origin master
Username for 'https://gitlab.com':

我们终于摆脱了 credential.helper

3 总结

其实 osxkeychain 已经暗示这个问题可能是跟平台相关的问题,不过一般思路我们还是先考虑了通用的情况,再去考虑平台相关的情况,但是我觉得问题不大,这个思路比较符合多数场景,而且针对这个问题,其实也没浪费多少时间