问题描述:
问题出现于我将本地写的项目上传到github时。
本地git仓库已经初始化,并进行了add和commit到本地仓库的操作。
当我直接执行push到origin/master(main)操作时会报错:
Push rejected: Push to xxx/master was rejected
具体错误日志如下:
Pushing to xxx.git
To xxx.git
! [rejected] master -> master (non-fast-forward)
error: failed to push some refs to 'xxx.git'
hint: Updates were rejected because the tip of your current branch is behind
hint: its remote counterpart. Merge the remote changes (e.g. 'git pull')
hint: before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
或者:
你如果不把新代码直接上传到master(main),而是自己新建一个远程分支,这时候你是可以push成功,但是这个分支不能合并到master,报错:
refusing to merge unrelated histories
解决
以上两个报错其实是同一类问题,就是在于本地仓库和远程仓库实际上是独立的两个仓库。假如我之前是直接clone的方式在本地建立起远程github仓库的克隆本地仓库就不会有这问题了。
我们要想办法将这两个仓库强制建立联系,我们可以打开项目位置的Terminal,给它一个pull三连:
git pull
git pull origin master
git pull origin master –allow-unrelated-histories
(其实我觉得就最后一行命令有用,意思是允许合并两个独立历史的分支)
成功之后,你再次执行push,将代码直接提交到master(main),就可以成功了。
如果上一步还有报错说你需要指定你的远程分支,那就:
git branch --set-upstream-to=origin/main master
(这里origin/main以前是origin/master,2020年10月1日之后master被main替换)