Search code examples
gitgithubgit-commitgit-pushgit-pull

Question on merging with local modifications in Git


The following is a very common error message encountered when we try to pull a git repository locally with some existing local changes in the local repository.

Please commit your changes or stash them before you merge. Aborting

I have a question about stdcall's answer in this post.

He has mentioned the following 3 options over there.

Image

Question: If I just commit my local changes using the command git commit -m "Saving my local changes" Is git pull not going to throw the same error that I have mentioned above? I mean I don't need to do a merge (git merge) or anything while pushing to GitLab?

In a normal workflow when I don't see any error, I follow the steps below to commit and push my changes:

  1. git add
  2. git commit -m "My message"
  3. git push

Since I am getting above error, are the following steps correct:

  1. git commit -m "Saving my local changes'
  2. git pull // This will pull whatever is on the branch including my local changes
  3. git push //This will push my local changes to git

I have used git stash in the past and it has resulted in my local changes getting wiped out so I am scared of using it. I didn't do git stash pop though and probably that's the reason it behaved like that.


Solution

  • git pull is throwing that error because the working directory is not clean for it to do a merge. Since, and I am oversimplifying it here, git pull is basically a fetch + merge, git needs a way to merge files. It can't merge if there are changes that are not saved/discarded/stashed.

    This does not save you from conflicts - getting remote changes might cause local conflicts - remote changes touch upon files that you have touched thus causing conflicts. Thus, standard conflict resolution is needed. See this answer for more details.


    I don't merge when I push

    You don't but not every push you do is successful. Sometimes, there are changes in the remote you don't have. Then git will tell you "Hey! There are things in the remote that you don't have and I can't override just like that. Pull them so that you can resolve whatever you need to resolve so that you can then push cleanly". See, now git tells you to pull - hence merge - so that you can push (of course unless you push --force...)