好吧,假设有一天我们碰巧做了一堆修改,当我们去提交它们时,我们注意到我们正在错误的分支上工作。
我们如何强制git切换分支不丢弃本地更改.
在等待回复时,我可能会以一种天真的方式解决这个问题,但我想知道是否有正确的程序,因为如果我说这之前没有发生在我身上,我就是在撒谎......
- 备份更改的存储库
git reset --hard
git checkout right-branch
- 恢复更改
git commit -m "changes"
有很多不同的方法,具体取决于您的进度以及您希望它们位于哪个分支。
我们来看看一个经典错误:
$ git checkout master
... pause for coffee, etc ...
... return, edit a bunch of stuff, then: oops, wanted to be on develop
所以现在你想要这些改变,但你还没有承诺master
,要在develop
.
-
If you 没有 a develop
然而,该方法很简单:
$ git checkout -b develop
这创建了一个新的develop
分支从你所在的地方开始
现在。现在你可以提交了,新的东西都已经上线了develop
.
-
You do have a develop
。看看 Git 是否会让你不用切换
做任何事情:
$ git checkout develop
这要么成功,要么抱怨。如果成功了,那就太好了!只是
犯罪。如果不 (error: Your local changes to the following files would be overwritten ...
), you still有很多选择。
The easiest is probably git stash
(as all the other answer-ers
that beat me to clicking post said). Run git stash save
or git stash push
,1 or just plain git stash
which is short for save
/ push
:
$ git stash
这会使用以下命令提交您的代码(是的,它确实进行了一些提交)
一种奇怪的非分支方法。它所做的提交不在任何“上”
分支,但现在已安全地存储在存储库中,因此您现在可以
切换分支,然后“应用”存储:
$ git checkout develop
Switched to branch 'develop'
$ git stash apply
如果一切顺利,并且您喜欢结果,那么您应该git stash drop
藏匿处。这会删除对奇怪的非分支提交的引用。 (它们仍然在存储库中,有时可以在紧急情况下检索,但对于大多数目的,您应该认为它们此时已消失。)
The apply
步骤使用 Git 强大的底层合并机制来合并隐藏的更改,这与进行分支合并时使用的功能相同。这意味着如果您错误地处理的分支与您想要处理的分支有很大不同,您可能会遇到“合并冲突”。所以这是一个好主意仔细检查结果在你假设隐藏物应用干净之前,即使 Git 本身没有检测到任何合并冲突。
很多人都用git stash pop
,这是git stash apply && git stash drop
。就目前而言,这很好,但这意味着,如果应用程序导致混乱,并且您决定不想沿着这条路继续下去,那么您将无法轻松取回隐藏的内容。这就是为什么我建议单独apply
,检查结果,drop
仅当/当满意时。 (当然,这确实引入了另一点,您可以再喝杯咖啡休息一下,忘记自己在做什么,回来做wrong的事情,所以这不是一个完美的治疗方法。)
1The save
in git stash save
is the old verb for creating a new stash. Git version 2.13 introduced the new verb to make things more consistent with pop
and to add more options to the creation command. Git version 2.16 formally deprecated the old verb (though it still works in Git 2.23, which is the latest release at the time I am editing this).
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)