今天在本地调好代码之后,准备把代码提交到仓库中,在命令行出现了以下报错:
bash
To github.com:iamxurulin/static-resource.git
! [rejected] main -> main (fetch first)
error: failed to push some refs to 'github.com:iamxurulin/static-resource.git'
hint: Updates were rejected because the remote contains work that you do not
hint: have locally. This is usually caused by another repository pushing to
hint: the same ref. If you want to integrate the remote changes, use
hint: 'git pull' before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.
我开始以为是GitHub(远程仓库)上有一些本地仓库里没有的更新,所以执行了强制推送的指令:
bash
git push -f origin main
执行完操作后,我就跑去源代码仓库查看,发现没有提交记录。
后面跑去static-resource仓库一看才发现,刚才把代码全部提交到这个仓库了,并且git 的推送机制把本地历史记录强制同步到了远程,把这个仓库原有的commit记录全部覆盖了,想通过SHA哈希值恢复到以前的版本也恢复不了。
怎么办呢?
GitHub 个人动态在执行强制推送时,会记录这一动作,但是我打开 GitHub 个人主页在页面中间的 Contribution activity(贡献动态)中也没有找到最近几小时的commit记录。
别急,Git 是有"后悔药"的。
既然有两个仓库,本地电脑上是不是应该有两个文件夹?
我进入到存放 static-resource 的文件夹,右键 -> Git Bash Here ,输入 git log -1。
这时,屏幕上显示了 commit xxxxxxxx 。
接下来,我在这个文件夹打开终端,输入:
bash
git push -f https://github.com/username/static-resource.git xxxxxxxx:main
之后,打开static-resource仓库,发现已经恢复了。
所以,后续推送的时候记得执行:
bash
git remote -v
确认一下要推送到的远程仓库。