2011-01-25 103 views
96

我想恢復git中的特定提交。不幸的是,我們的組織仍然使用CVS作爲標準,所以當我重新回到CVS時,多個git提交被合併爲一個。在這種情況下,我很想單獨提供原始的git commit,但這是不可能的。使用git恢復提交的一部分

是否有類似於git add --patch的方法,它允許我選擇性地編輯差異來決定要恢復的提交的哪些部分?

+0

更多解決方案[here](http://stackoverflow.com/q/5669358/470844),但重點是限制部分恢復到特定文件。 – ntc2 2014-08-26 23:02:04

回答

160

使用--no-commit-n)選項git revert,然後unstage的變化,然後使用git add --patch

$ git revert -n $bad_commit # Revert the commit, but don't commit the changes 
$ git reset HEAD .    # Unstage the changes 
$ git add --patch .   # Add whatever changes you want 
$ git commit     # Commit those changes 

注意:您添加使用Git的文件添加--patch是要恢復這些文件,而不是你想保留的文件。

+12

可能值得添加最後所需的命令,對於那些不熟悉git的人來說:在提交之後,`git reset --hard`放棄您不想恢復的其他更改。 – tremby 2012-09-26 21:03:37

+10

`git reset --hard`對新手來說很危險,因爲它可能會丟失想要的編輯。相反,習慣`git status`,這提示`git checkout - FILE..`可以更安全地恢復事物。 – Tino 2013-07-16 10:30:34

+0

`git`有什麼大的遺漏; `git revert`應該只需要一個`--patch`參數。 – Kaz 2017-03-31 14:33:28

1

您可以使用git-revert -n,然後使用add --patch選擇hunk。

32

我已經成功地使用了以下內容。

首先恢復完全提交(將其放入索引)但不提交。

git revert -n <sha1> # -n is short for --no-commit 

然後交互地從索引中移除

git reset -p   # -p is short for --patch 

的還原GOOD變化然後提交的不良變化反向的diff

git commit -m "Partially revert <sha1>..." 

最後恢復GOOD變化(已不分階段由重置命令)仍然在工作樹中。他們需要清理。如果沒有其他未提交的更改都留在了工作樹,這可以通過完成

git reset --hard 
4

解決方案:

git revert --no-commit <commit hash> 
git reset -p  # every time choose 'y' if you want keep the change, otherwise choose 'n' 
git commit -m "Revert ..." 
git checkout -- . # Don't forget to use it. 
3

就個人而言,我更喜歡這個版本,其中重用自動生成的提交信息,並給出用戶有機會在最終提交之前編輯並粘貼「部分」一詞。

# generate a revert commit 
# note the hash printed to console on success 
git revert --no-edit <hash to revert> 

# undo that commit, but not its changes to the working tree 
# (reset index to commit-before-last; that is, one graph entry up from HEAD) 
git reset HEAD~1 

# interactively add reversions 
git add -p 

# commit with pre-filled message 
git commit -c <hash from revert commit, printed to console after first command> 

# reset the rest of the current directory's working tree to match git 
# this will reapply the excluded parts of the reversion to the working tree 
# you may need to change the paths to be checked out 
# be careful not to accidentally overwrite unsaved work 
git checkout -- .