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

时间:2013-04-11 07:54:10

标签: git

假设我们有一个hotfixes分支,它是从master创建的。我们将提交添加到hotfixes,但这些提交没有用,所以现在我们想要从master的新副本开始。

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

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

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

5 个答案:

答案 0 :(得分:57)

这就是我用基本的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

答案 1 :(得分:36)

您的意思是您想将本地master推送到远程hotfixes分支机构?像这样:

git push origin +master:hotfixes

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

答案 2 :(得分:7)

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

如果是这种情况,这些命令集应该有效(假设您在过去的任何时间已经在本地git仓库中检出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

答案 3 :(得分:2)

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

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

然后使用它:

git reorient hotfixes

上述答案完全正确。但这只会减少击键次数并缩短周转时间!希望能帮助到你。

答案 4 :(得分:1)

基于该线程中的一些答案,我做了以下脚本,并提供了一些提示,以减少弄乱东西的风险:

#!/bin/bash
# Questions for loop:
for value in {1..3}
do
  # Asking if user wants to reset hotfix:
  if [ "$value" == "1" ] ;then
    echo -n "Are you sure you want to hard reset the hotfix branch (y/n)? "
    read answer
    if [ "$answer" == "${answer#[Yy]}" ] ;then
        echo 'Okay, maybe next time.'
        exit
    fi
  fi
  # Asking if user is in void:
  if [ "$value" == "2" ] ;then
    echo -n "Are you in the void branch (y/n)? "
    read answer
    if [ "$answer" == "${answer#[Yy]}" ] ;then
        echo 'You should checkout to the void branch.'
        exit
    fi
  fi
  # Asking if user has any uncommited changes:
  if [ "$value" == "3" ] ;then
    echo -n "Do you have any uncommited changes (y/n)? "
    read answer
    if [ "$answer" == "${answer#[Nn]}" ] ;then
        echo 'You should commit your changes to avoid losing them.'
        exit
    fi
  fi
done

echo 'Resetting...'
git checkout void
git branch -f hotfix origin/master
git push -f origin hotfix

100%愿意接受任何反馈以改进此脚本。