我在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

其他回答

以下步骤在Atlassian(Bitbucket服务器)支持的Git浏览器中执行

将{当前分支}设置为主分支

从master中创建一个分支,并将其命名为“master duplicate”。从{current branch}中创建一个分支,并将其命名为“{currentbranch}-copy”。在存储库设置(Bitbucket)中,将“默认分支”更改为指向“主副本”(如果没有此步骤,您将无法删除主副本-“在下一步”)。删除“master”分支-我从源代码树中执行了这一步骤(您可以在CLI或Git浏览器中执行)将“{current branch}”重命名为“master”并推送到存储库(这将创建一个新的“master”分支,但“{当前分支}”仍然存在)。在存储库设置中,将“Default Branch”更改为指向“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>

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

git checkout master
git checkout better_branch -- .

然后提交所有更改。

只需访问gitlab或github网站,查找设置即可。

然后在设置下查找存储库。

在那里找到默认分支,展开它,您可以获得重命名它或将其更改为其他分支的选项。

我在gitlab尝试过,结果成功了。

如果您在Eclipse中使用eGit:

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