簡體   English   中英

如何使用 git 將一個分支重置為另一個分支?

[英]How to reset a branch to another branch with git?

假設我們有一個從master創建的hotfixes分支。 我們向hotfixes添加了提交,但這些提交沒有用,所以現在我們想再次從master的新副本開始。

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

讓我們也說我們推hotfixesorigin遠程因為我們有一個可怕的設立,這就是測試的時候,唯一的方式,所以我們還需要重新設置分支機構的遠程服務器上。

如何將hotfixes重置為master的副本?

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

您的意思是要將本地master推送到遠程hotfixes分支? 像這樣:

git push origin +master:hotfixes

但是,這需要允許您在遠程端重寫歷史記錄。

如果我正確理解了您的問題,那么您正在尋找的是一種將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

這里的答案是可靠的。 將我的暫存分支重置為 master 時,我需要這個確切的更改。 在這種情況下,我既想重置原點以匹配主人,也想重置我的本地以匹配它。 所以這里有一個 git 別名,它允許您傳入分支名稱並一次性執行兩個命令。 (有點危險)

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

然后像這樣使用它:

git reorient hotfixes

以上答案完全正確。 但這只會允許更少的擊鍵和更快的周轉! 希望能幫助到你。

基於此線程中的一些答案,我執行了以下腳本並提供了一些提示,以降低搞砸的風險:

#!/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% 接受任何反饋以改進此腳本。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM