Max Koretskyi
Max Koretskyi

Reputation: 105499

git change branches with some files being modified

I'm working on the branch 'br3'. I have 3 modified files. I want to commit them to different branch, for example 'br1'. I know that I can safely change branches only if I don't have modified files in the tree, so I need to either:

I've never tried second option and I'm not sure it will work out. Will it? Or there is better alternative to the ones I outlined above?

Upvotes: 0

Views: 78

Answers (3)

UpAndAdam
UpAndAdam

Reputation: 5467

Stashing and applying is one solution

git stash
git checkout TARGET_BRANCH
git apply
#review and if i like it
git stash drop

Read more about it here: http://git-scm.com/book/en/Git-Tools-Stashing

Another is diff based, perhaps the other branch you already have open in another repo (stashes don't go from repo to repo). Or perhaps even on a different box!

git diff HEAD > ~/mypatch
cd SOME_OTHER_REPO 
#(or mail it to the other box or what have you and extract to ~/mypatch)
git checkout other_branch
git apply ~/mypatch

Upvotes: 1

cdhowie
cdhowie

Reputation: 169008

You can do a so-called "merge checkout" which will attempt to merge any changes you have made in the working tree into the target branch.

git checkout --merge br1

If there are any conflicts then you will have to resolve them just as when merging branches.

I would strongly suggest running git stash && git stash apply first, as this will make sure that you can return the working directory to its current state in case the merge fails so badly that you have to reset. If this happens and you did stash your changes, you can restore the working directory like this, and then try again:

git reset --hard
git checkout br3
git stash apply

Upvotes: 2

Carl Norum
Carl Norum

Reputation: 224944

I know that I can safely change branches only if I don't have modified files in the tree,

That's not really true; if the changes will apply cleanly, it will work fine. If not, you'll be told so and given the chance to fix them.

Your second option is probably the safest:

$ git stash
$ git checkout br1
$ git stash apply
$ git add ...
$ git commit ...

But it's quite likely that just:

$ git checkout br1
$ git add ... 
$ git commit ...

will work just fine.

Upvotes: 3

Related Questions