简体   繁体   English

从意外切换到另一个分支中恢复未提交的Git更改

[英]Recover uncommited changes in Git from accidentally switching to another branch

I have a project that I have made a lot of changes to in Branch A. I never commited these changes because I was following the suggested practice of only commiting code in a working state. 我有一个项目,在分支A中进行了很多更改。我从未提交过这些更改,因为我遵循了仅在工作状态下提交代码的建议做法。

Today, I made the stupid mistake of switching to another branch, forgetting to stash or commit my changes. 今天,我犯了一个愚蠢的错误,那就是切换到另一个分支,忘记存储或提交更改。

The code is opened up in PyCharm, and I haven't clicked on the PyCharm window to bring it into focus because I know it will listen for the changes and wipe everything out on the screen. 该代码是在PyCharm中打开的,而我没有单击PyCharm窗口以使其成为焦点,因为我知道它会侦听更改并清除屏幕上的所有内容。 I also have not switched back to Branch A in fear of doing any more damage. 我还没有切换回A分支,以免造成更多损失。

Did I just wipe out a whole bunch of work? 我只是消灭了一大堆工作吗? Am I able to recover any of it through Git or PyCharm's current state? 我可以通过Git或PyCharm的当前状态恢复其中的任何一个吗?

When you switch to another branch, your changes will carry over. 当您切换到另一个分支时,您的更改将继续。 You just have to switch back to your branch and commit or stash. 您只需要切换回分支并提交或隐藏即可。

Further more if your current change will get a conflict with the another branch, git will refuse to switch branch. 而且,如果您当前的更改将与另一个分支发生冲突,则git将拒绝切换该分支。

You can see your current changes with git status . 您可以使用git status查看当前更改。

Somme commands can delete your works like git clean , git reset , git checkout --force mybranch , git checkout . Somme命令可以删除git cleangit resetgit checkout --force mybranchgit checkout . do note the dot, this command will discard all changes in the working tree ( files that are tracked by git, files are tracked by adding them with git add for example.). 请注意点,此命令将放弃工作树中的所有更改(例如, git add跟踪的文件,通过使用git add添加它们来跟踪文件)。

To summarize : 总结一下:

Doing a git checkout MyBranch does not overwrite or delete your changes 进行git checkout MyBranch不会覆盖或删除您的更改

To elaborate on @Nitixx's answer according to the OP's request, let's cite the manual: 为了根据OP的要求详细说明@Nitixx的答案,让我们引用该手册:

git checkout <branch>

To prepare for working on <branch> , switch to it by updating the index and the files in the working tree, and by pointing HEAD at the branch. 要准备在<branch>上工作,请通过更新工作树中的索引和文件,并将HEAD指向分支来切换到该分支。 Local modifications to the files in the working tree are kept, so that they can be committed to the <branch> . 保留对工作树中文件的本地修改,以便可以将它们提交到<branch>

(emphasis mine). (强调我的)。

So, yes, unless you also somehow explicitly messed with overwriring the contents of the affected files, a mere checkout of the original branch will carry your local modification over. 因此,是的, 除非您还以某种方式明确地弄乱了受影响文件的内容, 否则仅检查原始分支将使您的本地修改结束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM