views:

211

answers:

3

For various reasons (code review mostly) I need to switch from current development branch to other branches quite often.

Currently, I use either 'git stash' to shelve the uncommitted changes, checkout other branch, then switch back and do 'git stash apply'

However, sometimes I'd have some newly added files there, which are not tracked. Unfortunately, stashing does not affect them. In this case I'd have to add them to the index and stash.

What I am looking here for is a workflow where I'd have to perform a minimal set of actions to switch the branches, preferably avoiding adding of files into the index.

+3  A: 

You could clone the repository and review/work on the clone. Delete the clone when you are done. If you do happen to make changes on the branch/clone, you can push them back. I think a local clone is cheap. And even if it was not, disk space is still cheaper than your time.

Thilo
+1  A: 

you can clone the repo to another directory and default to the branch you want:

# assume your original repo is in myproj
$ git clone myproj myproj_clone --branch my_branch

If you then go to the myproj_clone folder, it'll be in your branch

$ cd myproj_clone
$ git branch
* my_branch
hasen j
doesn't seem to be proper syntax, this one results in "error: unknown option `branch'"
Art
What version are you using? it works in 1.7
hasen j
A: 

I'm not sure that cloning is the right solution, but since 2 answers are proposing that it's on the brain, so I'm offering a modification on that theme. cloning may not be cheap. In terms of disk-space, it's irrelevant, but the clone itself make take several seconds and that's too much time to waste on an unnecessary operation. As an alternative, you can simply create a new working directory using the old git working dir. ie, if your current working dir is "a" (with changes and un-staged files), try:

$ mkdir ../b
$ cd ../b
$ echo 'gitdir: ../a/.git' > .git
$ git checkout -f foo

Now b is effectively a clone of a, on branch foo, and you've got two working directories to play with. Do what you need to on branch foo in working dir b, then go back to a and checkout the branch you were on when you left.

William Pursell
"the clone itself make take several seconds and that's too much time to waste on an unnecessary operation." Compared to manually stashing and unstashing stuff, and then still having to worry if that worked properly (for example with the untracked files), cloning will be faster. And less error-prone.
Thilo
do I really need to do this .git-fu? What are the advantages over simply cloning the directory?
Art