撤消 git 中未分段更改的一部分

如何在 git 中撤消部分未上演的更改,但保持其余部分未上演?我是这么想的:

git commit --interactive
# Choose the parts I want to delete
# Commit the changes
git stash
git rebase -i master # (I am an ancestor of master)
# Delete the line of the most recent commit
git stash apply

这是可行的,但是如果有类似 git commit --interactive的东西只用于还原更改就更好了。有更好的办法吗?

52722 次浏览

您可以执行 git checkout并为其指定要撤消的部分的名称。

怎么样

  1. 使用索引中的更改退出受影响的文件
  2. 使用 git add -p仅向索引添加所需的更改。

你可以的

git checkout master -- path/to/file

对于要重置的每个文件。

您可以使用 git checkout -p,它允许您从工作副本和索引之间的差异中选择要恢复的单个块。同样,git add -p允许您选择要添加到索引中的块,而 git reset -p允许您从索引和 HEAD 之间的差异中选择单个块以退出索引。

$ git checkout -p file/to/partially/revert
# or ...
$ git checkout -p .

如果您希望在恢复这些更改之前事先对您的 git 存储库进行快照,那么我希望这样做:

$ git stash; git stash apply

如果你经常使用这个词,你可能想给它起个别名:

[alias]
checkpoint = !git stash; git stash apply

如果您使用一个好的编辑器模式或插件,恢复单独的大块或行会更容易,这可能提供直接选择要恢复的行的支持,因为 -p有时使用起来有点笨拙。我使用的是 马吉特,这是一种 Emacs 模式,对于使用 Git 非常有帮助。在 Magit,你可以运行 magit-status,找到你想要恢复的变化的差异,选择你想要恢复的线条(或者只是把光标放在你想要恢复的线条上,如果你想一次恢复一个线条而不是一次恢复一个线条) ,然后按 k恢复那些特定的线条。如果您使用 Emacs,我强烈推荐 Magit。

当我运行“ git status”时,它会显示:

$ git status
# On branch fr/fr.002
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#   (use "git checkout -- <file>..." to discard changes in working directory)
#
#   modified:   makefile
#
no changes added to commit (use "git add" and/or "git commit -a")
$

因此,为了取消非舞台剪辑,它告诉我运行:

git checkout -- makefile
git diff > patchfile

然后编辑补丁文件并删除不想撤销的部分,然后:

patch -R < patchfile