开发者

Git - switching between branches in the middle of work

开发者 https://www.devze.com 2022-12-22 15:55 出处:网络
For various reasons (code review mostly) I need to switch from current development branch to other branches quite often.

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 an开发者_C百科d 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.


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.


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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号