简体   繁体   中英

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.

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. I also have not switched back to Branch A in fear of doing any more damage.

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?

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.

You can see your current changes with git status .

Somme commands can delete your works like git clean , git reset , git checkout --force mybranch , git 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.).

To summarize :

Doing a git checkout MyBranch does not overwrite or delete your changes

To elaborate on @Nitixx's answer according to the OP's request, let's cite the manual:

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. Local modifications to the files in the working tree are kept, so that they can be committed to the <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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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