我在Git中有一个存储库。我做了一个分支,然后对主分支和分支都做了一些更改。
然后,几十次提交之后,我意识到分支的状态比主分支好得多,所以我希望分支“成为”主分支,并忽略对主分支的更改。
我无法合并它,因为我不想将更改保留在master上。我该怎么办?
额外:在本例中,“旧”主控已被推送到另一个存储库,如GitHub。这是如何改变事情的?
我在Git中有一个存储库。我做了一个分支,然后对主分支和分支都做了一些更改。
然后,几十次提交之后,我意识到分支的状态比主分支好得多,所以我希望分支“成为”主分支,并忽略对主分支的更改。
我无法合并它,因为我不想将更改保留在master上。我该怎么办?
额外:在本例中,“旧”主控已被推送到另一个存储库,如GitHub。这是如何改变事情的?
当前回答
我在博客文章中找到了我想要的答案。用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
这与卡斯卡贝尔的答案基本相同。除了他们的解决方案下面的“选项”已经嵌入到上面的代码块中。
这样更容易找到。
我将此添加为新答案,因为如果以后需要此解决方案,我希望在一个代码块中包含所有需要使用的代码。
否则,我可能会复制并粘贴,然后阅读下面的详细信息,以查看我应该更改的行-在我已经执行它之后。
其他回答
编辑:你没说你已经推到了公开回购!这是天壤之别。
有两种方式,“脏”的方式和“干净”的方式。假设您的分支名为new master。这是一种干净的方式:
git checkout new-master
git branch -m master old-master
git branch -m new-master master
# And don't do this part. Just don't. But if you want to...
# git branch -d --force old-master
这将使配置文件更改以匹配重命名的分支。
你也可以用脏的方式来做,这不会更新配置文件。这是在上面的罩下发生的事情。。。
mv -i .git/refs/new-master .git/refs/master
git checkout 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 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
我发现这个简单的方法效果最好。它不会重写历史,分支的所有先前签入都将附加到主节点。没有丢失任何内容,您可以在提交日志中清楚地看到发生了什么。
目标:使“分支”的当前状态成为“主”
在分支上工作,提交并推送更改,以确保本地和远程存储库是最新的:
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提交日志将显示分支的所有签入。
只需访问gitlab或github网站,查找设置即可。
然后在设置下查找存储库。
在那里找到默认分支,展开它,您可以获得重命名它或将其更改为其他分支的选项。
我在gitlab尝试过,结果成功了。