smwikipedia smwikipedia - 1 month ago 6
Git Question

git checkout < branch > failure for local changes

I am new to Git. It seems to be a fantastic non-liner workflow based on the Directed Acyclic Graph.

According to the git checkout doc:


git checkout
<branch>


To prepare for working on , 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>
.



I have 2 branches:


  • master

  • dev



Both branches are clean and up-to-date.

I did this:

git checkout dev
<change a tracked file>
git checkout master


Then I got this error:


error: Your local changes to the following files would be overwritten
by checkout:
readme.txt Please, commit your changes or stash them before you can switch branches. Aborting


So does this conflict with the bold part of the doc?

ADD



Thanks for all the comments and replies. I can understand Git's good intention to avoid data loss. I just want to point out a potential doc ambiguity/error.

Answer

You made a change to readme.txt, which is all well and good.

Then you asked Git to change your current branch from dev to master, which is also OK, except for one problem.

Git compared the tip commit of dev to the tip commit of master and found that readme.txt is different in these two commits. So, in order to switch commits, it "wants" to remove the current readme.txt and replace it with the version out of master.

But you made a change to readme.txt. If Git removes readme.txt and replaces it with the version from master, your changes will be destroyed.

If Git switches to master without getting the different version of readme.txt from master, that might be OK, but it's not programmed to do that. So you must move your changes out of the way first, then you can switch, then you can restore your changes however you like. Using git commit or git stash provide two different ways to do this.

(If you had changed some other file, or if readme.txt were the same in both commits, Git might or definitely would not have run into this problem, and might or definitely would have switched your current branch over.)

Comments