我开始在我的 master 分支上工作,认为我的任务会很容易。过了一会儿,我意识到这需要更多的工作,我想在一个新的分支机构中完成所有这些工作。
如何在不弄脏 master 的情况下创建一个新分支并进行所有这些更改?
最佳答案
如果您还没有进行任何提交,那么只有 (1: branch) 和 (3: checkout) 就足够了。
或者,在一个命令中: git checkout -b newBranch
与 Git 2.23+ (2019 年第三季度),new command git switch
将在一行中创建分支(使用相同类型的 reset --hard
,所以注意它的影响):
# First, save your work in progress!
git stash
# Then, one command to create *and* switch to a new branch
git switch -f -c topic/wip HEAD~3
或者,按照 Alia 中的建议的 answer , 使用 git switch -m
, 没有 git stash
:
git switch -c topic/wip -m
--merge
If you have local modifications to one or more files that are different between the current branch and the branch to which you are switching, the command refuses to switch branches in order to preserve your modifications in context.
However, with this option, a three-way merge between the current branch, your working tree contents, and the new branch is done, and you will be on the new branch.
When a merge conflict happens, the index entries for conflicting paths are left unmerged, and you need to resolve the conflicts and mark the resolved paths with
git add
(orgit rm
if the merge should result in deletion of the path).
如 git reset
man page 中所述:
$ git stash # (0) Save your work in progress
$ git branch topic/wip # (1)
$ git reset --hard HEAD~3 # (2) NOTE: use $git reset --soft HEAD~3 (explanation below)
$ git checkout topic/wip # (3)
- 你已经做了一些提交,但意识到它们在“
master
”分支中还为时过早。您希望在主题分支中继续完善它们,因此创建当前topic/wip
的“HEAD
”分支. - 倒回
master
分支以摆脱这三个提交。 - 切换到“
topic/wip
”分支并继续工作。
同样:新方法(自 2019 年和 Git2.23 以来)在一个命令中完成所有这些:
git switch -f -c topic/wip HEAD~3
注意:由于 git reset --hard
的“破坏性”影响命令(它确实会重置索引和工作树。自 <commit>
以来对工作树中跟踪文件的任何更改都将被丢弃),我宁愿使用:
$ git reset --soft HEAD~3 # (2)
这将确保我不会丢失任何私有(private)文件(未添加到索引中)。
--soft
选项根本不会触及索引文件或工作树(但会将头部重置为 <commit>
,就像所有模式一样)。
关于git - 使用当前更改创建 Git 分支,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3899627/