165

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

有没有一种类似的方法git add --patch可以让我有选择地编辑差异来决定要恢复提交的哪些部分?

4

6 回答 6

259

使用--no-commit( -n) 选项git revert,然后取消暂存更改,然后使用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 添加的文件是您要恢复的文件,而不是您要保留的文件。

于 2011-01-25T16:30:38.763 回答
45

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

首先恢复完整提交(将其放入索引中)但不提交。

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 更改(已通过 reset 命令取消暂存)仍在工作树中。他们需要清理干净。如果工作树中没有其他未提交的更改,则可以通过

git reset --hard
于 2012-12-19T13:32:57.337 回答
5

解决方案:

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.
于 2014-08-11T12:57:20.130 回答
5

就个人而言,我更喜欢这个版本,它重用了自动生成的提交消息,并让用户有机会在最终提交之前编辑并粘贴“部分”一词。

# 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 -- .
于 2014-10-08T16:39:33.197 回答
3

另一种选择(如果您当前的文件版本与您尝试恢复的版本不太远)是在您希望部分恢复的版本之前立即获取提交git log的哈希(从)。然后你的命令变成:

$ git checkout -p <hash_preceding_commit_to_revert> -- file/you/want/to/fix.ext

这确实会更改工作树中的文件,但不会创建任何提交,所以如果你真的塞满了,你可以重新开始git reset --hard -- file/you/want/to/fix.ext

于 2018-03-13T00:44:22.017 回答
1

你可以使用 git-revert -n,然后使用 add --patch 来选择 hunks。

于 2011-01-25T16:28:50.653 回答