Home > Software engineering >  How to prevent unintended git merge
How to prevent unintended git merge

Time:11-11

Today I was working on 2 branches, main and working-branch. I commit my changes to working-branch then when everything is good, I'll then merge it to the main branch then push to the remote main branch.

I had a bug in my working-branch that I was trying to fix, while I quickly want to switch to the main branch to check something out, I forgot to commit my current changes to the working-branch, as I switched to the main branch the changes in the working-branch was automatically copied to the main branch without warning. I had to discard the changes in the main branch. By the time I switched back to the working-branch, I also lost the changes there too.

For me I think git should have warned me to commit my changes first before switching from working-branch to the main branch but then it didn't. So how do I prevent this occurrence next time or what would I have done to get around this?. Thank you.

CodePudding user response:

I forgot to commit my current changes to the working-branch

The simplest solution here is to go back to your working-branch and commit your changes into the local version of your working branch. You can always edit commits on your local branch before you merge to your main branch anyway if you are worried about having lots of small commits 'placeholder' commits.

The other thing you can do if you are doing something really quickly on the main branch would be to do

git stash

This will cache all your uncommitted changes so you can do whatever you need to do on your main branch quickly without interfering with your uncommitted changes.

To get the changes back after you have finished whatever you needed to do on you main branch you can just run

git stash apply

There is more functionality in the git stash command if you want to get more complicated, but I would recommend just locally committing things you want to make sure you save so there is no chance you end up losing those changes.

  •  Tags:  
  • git
  • Related