0

As I'm working on a project with uncommitted files, there are times when I have to switch to a new branch.

Sometimes Git switches to a new branch just fine, and takes the changes along with me.

$ git checkout development
Switched to branch 'development'
M       SomeFile1.py
M       SomeFile2.sh
Your branch is up to date with 'origin/development'.

Other times it requires that I either commit or stash my changes when switching to a branch.

$ git checkout development
error: Your local changes to the following files would be overwritten by checkout:
    SomeFile1.py
Please commit your changes or stash them before you switch branches.
Aborting

I can't understand the scenario in when it will switch branches automatically while brining the changes along, versus making me commit/stash my changes before switching.

I either stash/commit my changes if I do get that message, but I am trying to understand the scenario in which that happens versus when it will just switch branches automatically and bring the changes with me.

foxmag86
  • 21
  • 1

2 Answers2

2

It all depends on if the modified files are the same between HEAD and where you want to go. If the files are the same between those 2 commits, git has no problem checking out (and keeps the modified files as they are on the working tree after the checkout).... however, if at least one modified file is not the same between HEAD and where you are going, that would mean that you would need to do a 3-way merge in order to carry out the changes you have on that file (the 3 parts being HEAD, the working tree and where you are going), all of that without the luxury of a commit... which is a no-go, for starters. That's why git refuses to checkout (unless you force it to) and asks you to stash the changes instead.

eftshift0
  • 26,375
  • 3
  • 36
  • 60
1

You might get this error when the same file has been modified both on the current branch and the one you're trying to switch to. See this post's accepted answer:

error: Your local changes to the following files would be overwritten by checkout

Hope this helps!

cmelnu
  • 11
  • 1
  • 8