git放弃所有更改并从上游拉出


144

我该如何获取上游回购并使其替代母版?我的仓库中只有一个分支,即主分支,我完全搞砸了,所以基本上我需要从上游重新开始。我认为init可以完成工作,但是有没有更简单的方法?

Answers:


250

您至少可以做两件事–可以克隆远程仓库,或者reset --hard到共同的祖先,然后进行拉取,这将快进到远程主数据库上的最新提交。

具体来说,这是Nevik Rehnel原始答案的简单扩展:

git reset --hard origin/master
git pull origin master

注意:using git reset --hard会丢弃所有未提交的更改,如果您是git的新手,可能会很容易将自己与该命令混淆,因此在继续之前,请确保您已经知道要做什么。


1
为新秀提供更多帮助:git gc清理并运行一些家政服务。另一方面,我从没跑过git gc。运行很好,但不需要。
约书亚舞

@JoshuaDance-好点 我不确定为什么最初包含它。
埃里克·沃克

23

在分支主管上时: git reset --hard origin/master

然后进行清理git gc(有关手册页的更多信息)

更新:您可能还需要做一个git fetch origin(或者git fetch origin master如果您想要那个分支);重置之前还是之后都不要紧。(感谢@ eric-walker)


1
您可能需要在结束之后进行拉动reset --hard
埃里克·沃克

一旦在重置之前运行git fetch origin,就无需从master提取。
sciritai 2012年

@sciritai:我的评论是在提及从来源获取之前添加的。
埃里克·沃克

19

您可以在一个命令中完成:

git fetch --all && git reset --hard origin/master

或使用一对命令:

git fetch --all
git reset --hard origin/master

请注意,您将丢失所有本地更改


5
git reset <hash>  # you need to know the last good hash, so you can remove all your local commits

git fetch upstream
git checkout master
git merge upstream/master
git push origin master -f

瞧,现在您的叉子回到了上游。


0

我现在终于意识到git fetch --all && git reset --hard origin/master,应该git fetch --all && git reset --hard origin/<branch_name>改为,而不是,(如果一个在另一个分支上工作)

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.