我在Git中有一个存储库。我做了一个分支,然后对主分支和分支都做了一些更改。

然后,几十次提交之后,我意识到分支的状态比主分支好得多,所以我希望分支“成为”主分支,并忽略对主分支的更改。

我无法合并它,因为我不想将更改保留在master上。我该怎么办?

额外:在本例中,“旧”主控已被推送到另一个存储库,如GitHub。这是如何改变事情的?


当前回答

其他两个答案的问题是,新主人没有老主人作为祖先,所以当你推它时,其他人都会被搞砸。这是您想要做的:

git checkout better_branch
git merge --strategy=ours master    # keep the content of this branch, but record a merge
git checkout master
git merge better_branch             # fast-forward master up to the merge

如果你想让你的历史更清楚一点,我建议你在合并提交消息中添加一些信息,让你清楚你做了什么。将第二行更改为:

git merge --strategy=ours --no-commit master
git commit          # add information to the template merge message

其他回答

确保将所有内容推送到远程存储库(GitHub):

git checkout main

用“better_branch”覆盖“main”:

git reset --hard better_branch

强制推送到远程存储库:

git push -f origin main

还可以将其他分支中的所有文件签出到master中:

git checkout master
git checkout better_branch -- .

然后提交所有更改。

我发现这个简单的方法效果最好。它不会重写历史,分支的所有先前签入都将附加到主节点。没有丢失任何内容,您可以在提交日志中清楚地看到发生了什么。

目标:使“分支”的当前状态成为“主”

在分支上工作,提交并推送更改,以确保本地和远程存储库是最新的:

git checkout master      # Set local repository to master
git reset --hard branch  # Force working tree and index to branch
git push origin master    # Update remote repository

在此之后,您的master将是分支的最后一次提交的确切状态,并且您的master提交日志将显示分支的所有签入。

如果您在Eclipse中使用eGit:

在项目节点上单击鼠标右键。选择团队→ 然后是高级→ 然后重命名分支然后展开远程跟踪文件夹。选择名称错误的分支,然后单击重命名按钮,将其重命名为任何新名称。选择新的主控形状,然后将其重命名为主控形状。

其他两个答案的问题是,新主人没有老主人作为祖先,所以当你推它时,其他人都会被搞砸。这是您想要做的:

git checkout better_branch
git merge --strategy=ours master    # keep the content of this branch, but record a merge
git checkout master
git merge better_branch             # fast-forward master up to the merge

如果你想让你的历史更清楚一点,我建议你在合并提交消息中添加一些信息,让你清楚你做了什么。将第二行更改为:

git merge --strategy=ours --no-commit master
git commit          # add information to the template merge message