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

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

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

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


当前回答

根据我的理解,您可以将当前分支分支到现有分支。本质上,这将用当前分支中的所有内容覆盖master:

git branch -f master HEAD

完成后,通常可以推送本地主分支,可能还需要此处的force参数:

git push -f origin master

没有合并,没有长命令。简单地分支和推送——但,是的,这将改写主分支的历史,所以若你们在一个团队中工作,你们必须知道你们在做什么。




或者,我发现您可以将任何分支推送到任何远程分支,因此:

# This will force push the current branch to the remote master
git push -f origin HEAD:master

# Switch current branch to master
git checkout master

# Reset the local master branch to what's on the remote
git reset --hard origin/master

其他回答

为了补充Cascabel的答案,如果你不想在源分支的历史中放置一个无意义的合并,你可以为我们的合并创建一个临时分支,然后扔掉它:

git checkout <source>
git checkout -b temp            # temporary branch for merge
git merge -s ours <target>      # create merge commit with contents of <source>
git checkout <target>           # fast forward <target> to merge commit
git merge temp                  # ...
git branch -d temp              # throw temporary branch away

这样,合并提交将只存在于目标分支的历史记录中。

或者,如果您根本不想创建合并,您可以简单地获取源的内容,并将其用于目标上的新提交:

git checkout <source>                          # fill index with contents of <source>
git symbolic-ref HEAD <target>                 # tell git we're committing on <target>
git commit -m "Setting contents to <source>"   # make an ordinary commit with the contents of <source>

对我来说,我希望我的开发分支在领先之后回到主分支。

在开发过程中:

git checkout master
git pull

git checkout develop
git pull

git reset --hard origin/master
git push -f

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

git checkout main

用“better_branch”覆盖“main”:

git reset --hard better_branch

强制推送到远程存储库:

git push -f origin main

我在博客文章中找到了我想要的答案。用git中的另一个分支替换主分支:

git checkout feature_branch
git merge -s ours --no-commit master
git commit      # Add a message regarding the replacement that you just did
git checkout master
git merge feature_branch

这与卡斯卡贝尔的答案基本相同。除了他们的解决方案下面的“选项”已经嵌入到上面的代码块中。

这样更容易找到。

我将此添加为新答案,因为如果以后需要此解决方案,我希望在一个代码块中包含所有需要使用的代码。

否则,我可能会复制并粘贴,然后阅读下面的详细信息,以查看我应该更改的行-在我已经执行它之后。

我知道这不是OP想要的,但如果你知道你将来会遇到与OP类似的问题,你可以这样做。

这是你的情况,

您需要一个分支,它具有新的优秀的新中断功能,但目前还没有推出。你有计划在未来推动它。您当前的prod分支(master)运行良好,但很无聊。你可以对它做一些小改动。如果以后需要,您希望保持当前主(prod)分支的安全。

如果这让人感到困惑,请参见下图中的糟糕情况。

*bad situation*
initial master   --->           added boring changes       ----merge---> you loose boring
            \                                                /
             ---> (awesome branch) added awesome changes ---

要解决此问题(即停止钻孔损失),请执行以下操作大体上

通过执行git branch boring创建当前主控形状的副本将boring替换为要保留的任何名称现在,您可以向主分支添加新的很棒的功能,并向无聊分支添加无聊的功能。您仍然可以继续更新枯燥的分支,并可能使用它来永远不会将其合并到master。你不会失去乏味的功能。你的主分支将有很棒的功能。

So,

*good situation*
 initial master   --->     added awesome changes     --->    Final master(awesome) branch
                \
                 --->   (boring branch) added boring changes  ---> Dont merge to master  --X-->