用git恢复提交的一部分

我想在git中恢复一个特定的提交。 不幸的是,我们的组织仍然使用CVS作为标准,所以当我提交回CVS时,多个git提交被合并为一个。 在这种情况下,我很乐意单独提供原始的git commit,但这是不可能的。

有一种类似于git add --patch ,它允许我select性地编辑差异来决定要提交哪个部分进行还原吗?

使用--no-commit-n )选项将git revert ,然后git add --patch更改,然后使用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 add –patch添加的文件是要恢复的文件,而不是要保留的文件。

我已经成功地使用了以下内容。

首先恢复完整的提交(把它放在索引中),但不要提交。

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

然后以交互方式从索引中删除恢复的GOOD更改

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

然后提交不良变更的反向差异

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

最后,恢复的GOOD变化(已经被重置命令取消)仍然在工作树中。 他们需要清理。 如果没有其他未提交的更改留在工作树中,则可以通过

 git reset --hard 

解:

 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. 

就个人而言,我更喜欢这个版本,它重用自动生成的提交信息,并给用户在最终提交之前编辑和粘贴“部分”字样的机会。

 # 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 -- . 

你可以使用git-revert -n,然后使用add –patch来selecthunk。