如何使用git将分支重置为其他分支?

问题描述:

假设我们有一个从master创建的hotfixes分支。我们添加了提交到hotfixes,但这些提交没有用处,所以现在我们想要再次从master的新副本开始。如何使用git将分支重置为其他分支?

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

,让我们也说我们推hotfixesorigin远程因为我们有一个可怕的设立,这就是测试的时候,唯一的方式,所以我们需要也在远程服务器上重置分支。

如何将hotfixes重置为master的副本?

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

git push origin +master:hotfixes 

但是,这要求您允许您重写远程端的历史记录。

+0

这是正确的语法吗?当我这样做时,我得到了一个新的远程分支,名称中带有加号(+)。我必须移动像git push origin + master:hotfixes这样的加号。这是根据git规范:http://git-scm.com/docs/git-push – jwynveen 2014-07-01 21:17:54

+0

@jwynveen你是对的,修复。 – 2014-07-03 09:15:05

+6

fyi,加号是在推送过程中执行'--force'的简写:http://*.com/questions/1475665/why-git-push-helloworld-mastermaster-instead-of-just-git- push-helloworld – 2016-03-01 15:23:28

如果我正确地理解了您的问题,您正在寻找的是将origin/hotfixes的分支指针移至指向origin/master的当前修订版的方法。

如果是这样的话,这些set命令应该工作(假设你已经在你的本地混帐回购协议的任何时间过去检查了hotfixes):

# 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 
+0

'分支hotifxes设置为从原点追踪远程分支主。“ - 不知道这是所有想要的 – 2016-10-11 12:44:12

这是我如何与做的基本的Git命令:

git checkout hotfixes 
git reset --hard master 
git push --force origin hotfixes 

当然它来通知大家工作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 
+0

我更喜欢这种方式。不太容易出错。 – 2016-11-15 07:37:15

+0

感谢您的偏好,但我很想知道为什么你发现它更不容易出错 – danza 2016-11-22 16:14:50

+1

我应该说这是个人偏好,并没有试图说明一个事实。 对我而言,它需要更多的动作,它们更好地描述你正在做的事情,而不是仅仅推到不同的遥控器,这反过来又使我更加意识到自己在做什么。 此外,额外的'-f'标志和'复位--hard'具有警告与GUI工具,如sourcetree例如.. – 2016-11-23 09:13:32

这里的答案是可靠的。将我的暂存分支重置为主时,我需要进行确切的更改。在这种情况下,我希望将原点重置为匹配主,并重置我的本地以匹配它。所以这里有一个git别名,它允许你传入分支名称并一次执行两个命令。 (这是一个有点危险)

reorient = "!f() { git push origin +master:$1 && git reset --hard origin/$1 ; }; f" 

然后使用它像:以上

git reorient hotfixes 

的答案是完全正确的。但这只会减少按键和更快的周转!希望能帮助到你。

+0

我不会在一个别名中很容易地包装'git reset --hard' ...我会害怕忘记和丢失重要变化 – danza 2018-01-25 11:39:55

+1

是的。就像我在解释“这有点危险”中所说的那样。然而,在某些情况下,你可以发现自己在常规上做这件事,在这种情况下,你可能需要更快一些。 – 2018-01-30 00:47:14