git - 重新初始化现有的 git 存储库
问题描述
我有以下情况:有一个 Gitlab 存储库,它已使用默认分支XXX
而不是master
. 该分支XXX
已经有一些提交。
目标是重新初始化master
分支是默认分支和空分支的仓库。现有的更改需要在一个特性分支中,该分支应该从空的master
.
更新:为了更好地解释目标,当前状态:
1-2-3-...-n
^
xxx
期望的状态:
master
▼
1
\
2-3-...-n
^
xxx
补充一点也很有意义,如果需要,这种情况允许将分支中的所有现有提交压缩xxx
到一个“初始”。
解决方案
直观地说,听起来你想从这个开始:
o---o---o
^
master
对此:
o---o----o
^ ^
master feature
但是,您也说过:
现有的更改需要在一个特性分支中,该分支应该从空的 master 分支。
在 Git 中,没有“空”分支的概念;分支是指向一系列提交的最后一个的指针。这意味着您必须指向master
存储库中的第一个提交(即根提交)。
这是你如何做到的:
# Create the 'feature' branch pointing to the commit currently referenced by 'master'
git branch feature master
# Checkout the 'master' branch, if you haven't already
git switch master
# Reset 'master' to the root commit
git reset --hard master~2
master
或者,您可以暂时摆脱分支,稍后当您想“合并”feature
到master
.
这是@tripleee 建议的一种快速方法:
# Rename 'master' to 'feature'
git branch -m master feature
此时,您只需feature
:
o---o---o
^
feature
合并feature
到master
then 只需master
在与以下相同的提交上创建分支即可feature
:
git branch master feature
看起来像这样:
o---o---o
^
feature, master