如何使用git将分支重置为另一个分支?

dan*_*nza 47 git

让我们说我们有一个hotfixes分支是由...创建的master.我们添加了提交hotfixes,但这些提交没有用,所以现在我们想从一个新的副本开始master.

为了更好地澄清,这是参考工作流程:http://nvie.com/posts/a-successful-git-branching-model/

让我们也说我们推hotfixes到了origin遥控器,因为我们设置得很糟糕,这是测试某些东西的唯一方法,所以我们还需要在远程服务器上重置分支.

如何重置hotfixes为副本master

dan*_*nza 68

这就是我用基本的Git命令做到的:

git checkout hotfixes
git reset --hard master
git push --force origin hotfixes
Run Code Online (Sandbox Code Playgroud)

当然,通知每个工作人员都很重要hotfixes.他们很可能不得不删除他们的本地副本并从一个新的副本开始.一个替代的,侵入性较小的想法是创建一个新的分支:

git checkout master
git branch -tb hotfixes-2 # this creates branch `hotfixes-2` from a copy of `master`
git push origin HEAD # this creates `hotfixes-2` on the remote server
Run Code Online (Sandbox Code Playgroud)

  • 我更喜欢这种方式.不容易出错. (3认同)
  • 我应该说这是个人喜好,并不是要陈述事实。对我来说,它需要执行更多操作,这些操作可以更好地描述您在做什么,而不是仅推送到其他远程设备,从而使我更清楚自己在做什么。另外,额外的`-f`标志和`reset --hard`会通过GUI工具(例如sourcetree)发出警告。 (2认同)
  • 抱歉,我的意思是说,如果您使用的是诸如源代码树之类的GUI工具,那么使用上述步骤将使您更加了解,因为在执行过程中会出现警告,这意味着您可以随时中止操作。 (2认同)

Mic*_*ild 39

你的意思是你想把你的本地推master到远程hotfixes分支?像这样:

git push origin +master:hotfixes
Run Code Online (Sandbox Code Playgroud)

但是,这要求您可以在远程端重写历史记录.

  • fyi,加号是推动期间做"--force"的简写:http://stackoverflow.com/questions/1475665/why-git-push-helloworld-mastermaster-instead-of-just-git-push -你好,世界 (15认同)
  • 我认为值得注意的是,这不会更新您的本地(修补程序)分支.之后你仍然可能想要'git reset --hard origin/hotfixes`. (8认同)
  • 这是正确的语法吗?完成此操作后,我得到了一个新的远程分支,名称中带有加号(+)。我不得不移动加号,如`git push origin + master:hotfixes`。这是根据git规范:http://git-scm.com/docs/git-push (2认同)

Tux*_*ude 8

如果我正确地理解了你的问题,你正在寻找的是一种将分支指针移动origin/hotfixes到指向当前版本的方法origin/master.

如果是这种情况,这些命令集应该有效(假设您已经hotfixes在过去的任何时间在本地git仓库中检出过):

# git branch -f does not allow modifying the currently checked out
# branch, so checkout any other branch than hotfixes
git checkout <SOME_OTHER_BRANCH_THAN_HOTFIXES>

# Move the branch pointer of hotfixes to the commit currently
# pointed by origin/master
git branch -f hotfixes origin/master

# Force push the history rewrite in the hotfixes branch
# into origin
git push -f origin hotfixes
Run Code Online (Sandbox Code Playgroud)