2009-04-21 120 views
30

我最近搞砸了我的git repo,並想知道是否有任何補救措施。創建git分支,並將原始狀態還原爲上游狀態

我的設置是這樣的:

Central repo on github. 
Personal repo on github (which is a fork of Central) 
    +Central is setup as remote (upstream/master) 
    +Master branch (origin/master) 
    +Feature branch (origin/feature) 

我的工作流程是這樣的:

Need to fix something in Central: 
    1. checkout Master 
    2. Make changes 
    3. Pull from upstream/master and merge 
    3. Commit, push to upstream/master 

Need to work on a New Feature: 
    1. Checkout/Create Feature branch 
    2. Work work work 
    3. Pull from upstream/master and merge 
    4. Commit, push to upstream/master 

這樣,我總是在我的主分支中心的原始狀態。

現在我所做的就是開始在Master分支上工作。因此,我對主人進行了更改,不能再從中分出來獲取中央副本。無論何時我需要製作並向Central推送一些修復程序,我必須將中心克隆到另一個目錄並從那裏開始工作。

我的問題:有沒有辦法將我的主人「還原」爲中央的相同副本,同時將我在主人所做的所有更改移動到另一個分支(比如說Feature)?

我知道這很讓人困惑,我很感激任何幫助。我會澄清,如果有什麼不清楚。

回答

47

嘛解決方案是非常簡單的,由Pat諾茨和氣罐暗示。

#Make sure we're on the master branch 
$ git checkout master 

# Make a new branch to hold the work I've done 
$ git branch old_master 
# Save this branch on my remote repo (for backup) 
$ git checkout old_master 
$ git push origin old_master 

# Reset my local master back to match the commit just before I started 
# working on my new feature 
$ git checkout master 
$ git reset --hard 2aa93842342342 
# Get it to be the same as my Central 
$ git pull upstream master 

# Now DELETE my master on my remote repo 
$ git push origin :master 
# And recreate it 
$ git push origin master 

# Branch created! 
#* [new branch]  master -> master 

# 

現在我有兩個很好的分支:master和old_master。主人是我的中央副本,修復生產問題,而old_master則擁有我之前完成的所有工作!

謝謝!

3

究竟你的意思由

我搞砸[置頂]我的主人,不能再分支從它。

無論您的存儲庫中有多少「搞砸」,您都可以從存儲庫中的任何提交中創建一個新的分支,順便說一句,Git沒有任何理念。

基本上你可以將你的倉庫恢復到它以前的任何狀態,因爲Git不會明確地刪除任何對象,它只會偶爾垃圾收集未引用的(懸空)對象。所以你只需要找出你的倉庫看起來像什麼。 gitkgit log可以幫助你。

將本地存儲庫恢復到您喜歡的狀態後,您可以簡單地將其推回到中央公共存儲庫。如果這導致非快進推送,則可能需要在推送時指定--force標誌。

+0

嗨,我的意思是說我不能再從它那裏分支來獲得中央倉庫的副本,所以我可以開始創建一個新功能。 關於你的建議,我想到了這一點 - 但那會讓我放棄我對主人所做的所有工作。它不會?謝謝。 – drozzy 2009-04-21 15:04:19

16
# Make sure we're on the master branch 
$ git checkout master 

# Make a new branch to hold the work I've done 
$ git branch old_master 

# Reset my local master back to match origin/master 
$ git reset --hard origin/master 

現在,您可以檢出old_master並使用它,就像你做你的feature分支

+0

Origin/master指向我的主服務器的遠程存儲庫。但我已經將我的更改壓入了我的github回購。 我需要將其重置到我的中央回購站的上游/主站。有沒有辦法做到這一點? – drozzy 2009-04-21 17:12:58

+0

不出所料,`git reset --hard upstream/master`似乎工作正常(如果你已經設置上游指向正確的repo)。 – starwed 2013-06-10 16:33:09