views:

172

answers:

2

Sometimes I'm in a feature branch, but I've made an unrelated change that I want to see in master. Often I can just do:

git checkout master
git commit -m "..." filename

But sometimes when I do the checkout I get a warning that there are local changes and thus I can't switch the branch.

Why does this only happen sometimes? Is there a workaround when I see this message? Maybe stash?

A: 

I've seen this also. I think the issue is when your local changes would change with something in the other branch (as opposed to a new file not in the other branch). You can always check the other branch out in a different directory.

Devin Ceartas
How can you check another branch out in a different directory?
Mike Mazur
Look for help on git-new-workdir, which lets you create a new working directory backed by the same repo.
Phil
I see, it's a script in contrib/workdir in the git git repo. Thanks!
Mike Mazur
+4  A: 

As Devin Ceartas mentioned, this happens when switching branches would change some file that you've already changed locally. (Git won't complain when you have local changes on a file that would not be changed, or add new files that exist on neither the branch nor master.)

Two ways around this:

  1. "git stash" your changes, change to master, and "git stash apply". Then commit the change.

  2. Commit the changes you want on the branch, then "git stash" any other changes (if there are any), change to master, and cherry-pick the change on master.

Phil
Four ways: 3. you can always try to do 3-way merge with "git checkout -m", and 4. you can force checkout (losing your changes) with "git checkout -f".
Jakub Narębski