简体   繁体   English

Git-在工作中间切换分支

[英]Git - switching between branches in the middle of work

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' 目前,我使用'git stash'搁置未提交的更改,签出其他分支,然后切换回去并执行'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. 我在这里寻找的是一个工作流,在该工作流中,我必须执行最少的一组操作来切换分支,最好避免将文件添加到索引中。

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 如果然后转到myproj_clone文件夹,它将位于您的分支中

$ 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. 我不确定克隆是否是正确的解决方案,但是由于有2个答案表明克隆在大脑中,因此我在此主题上进行了修改。 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. 作为替代,您可以简单地使用旧的git working dir创建一个新的工作目录。 ie, if your current working dir is "a" (with changes and un-staged files), try: 即,如果您当前的工作目录为“ a”(包含更改和未暂存的文件),请尝试:

$ 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. 现在b实际上是foo分支上a的一个克隆,并且您可以使用两个工作目录。 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. 在工作目录b中的分支foo上执行所需的操作,然后返回到a并签出离开时所在的分支。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM