tags:

views:

35

answers:

3

I'm puzzled how to use branches in git to save temporary work.

This is what I tried:

/tmp/gt > git init
Initialized empty Git repository in .git/
/tmp/gt > date > t
/tmp/gt > git add t
/tmp/gt > git commit -m 'initial'
Created initial commit b722fde: initial
 1 files changed, 1 insertions(+), 0 deletions(-)
 create mode 100644 t

Now I'm saving away that work to branch "b".

/tmp/gt > git branch b

and continue to work in the master branch.

/tmp/gt > date >> t
/tmp/gt > cat t
Di 18 Aug 2009 08:52:43 CEST
Di 18 Aug 2009 08:53:13 CEST

What surprises me is this:

/tmp/gt > git checkout b
M       t
Switched to branch "b"
/tmp/gt > cat t
Di 18 Aug 2009 08:52:43 CEST
Di 18 Aug 2009 08:53:13 CEST

I expected that in branch "b" the file "t" was still in the same state when the branch was created (i.e. containg just a single date line).

Can I avoid this auto-merging or is this some conceptual question?

Thanks for guidance, Axel.

+2  A: 

it’s intentional: all your current changes to your working copy will get merged. if do another commit on master and then checkout b, you’ll have the oneliner file.

another solution is to git checkout -f b, but that will overwrite your changes—which you usually don’t want

knittl
A: 
git reset --hard

will restore the state as Git has stored it, so if you call it after your “git checkout b” line t will be restored to its pristine state.

Bombe
But if I go back again to the "master" branch the modification is lost.I guess that I always have to be aware of this and do a commit before checking out a branch.
axelrose
+3  A: 

The rationale is that your unstaged changes are not (yet) on any branch. If your changes don't conflict with the branch switch that you request then you can carry them over onto the new branch.

If you want to go back to exactly branch b, then you need to make sure that you have a clean working tree by committing pending changes, stashing pending changes or resetting pending changes and then changing branches.

The reason that the behaviour is like this is to support the very common workflow: start hacking, realise hacks should be on an alternative (or new) branch, (create and) check out branch, carry on hacking.

Charles Bailey