Git 恢复——没有分段就不能提交

通常,命令 git revert会自动创建一些提交,其中包含提交日志消息,说明恢复了哪些提交。

为了避免自动提交,可以选择 -n(或 --no-commit)。

但是在这个命令之后,恢复的文件就在暂存区域了。我可以使用命令 git reset HEAD卸载它们。

有没有直接的方法可以在不提交和暂存的情况下恢复提交?

换句话说: 是否有一个直接的命令来恢复一个只对工作目录应用更改的提交,而不触及索引?

68275 次浏览

There is no single command for it. As you already noted, you can combine git revert -n with git reset to get the reversion undone in the index.

Besides that method, you can use git apply -R to "reverse apply" a patch, and you can turn a commit into a patch with git show, so:

$ git show <rev> | git apply -R

has the same effect, with one important (but subtle) difference. Let me quote from the git revert documentation and add my own emphasis:

-n, --no-commit
Usually the command automatically creates some commits with commit log messages stating which commits were reverted. This flag applies the changes necessary to revert the named commits to your working tree and the index, but does not make the commits. In addition, when this option is used, your index does not have to match the HEAD commit. The revert is done against the beginning state of your index.

In other words, git revert -n operates in, and on, the index, with a side effect of updating your work tree. The git apply command operates (by default anyway) on the work-tree only, and in fact can be used outside a git repository.